text
stringlengths
54
60.6k
<commit_before>/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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 "Filter.hxx" #include "CompletionHandler.hxx" #include "lib/openssl/Name.hxx" #include "lib/openssl/UniqueX509.hxx" #include "FifoBufferBio.hxx" #include "fs/ThreadSocketFilter.hxx" #include "memory/fb_pool.hxx" #include "memory/SliceFifoBuffer.hxx" #include "util/AllocatedArray.hxx" #include "util/AllocatedString.hxx" #include <openssl/ssl.h> #include <openssl/err.h> #include <assert.h> #include <string.h> class SslFilter final : public ThreadSocketFilterHandler, SslCompletionHandler { /** * Buffers which can be accessed from within the thread without * holding locks. These will be copied to/from the according * #thread_socket_filter buffers. */ SliceFifoBuffer encrypted_input, decrypted_input, plain_output, encrypted_output; const UniqueSSL ssl; bool handshaking = true; AllocatedArray<unsigned char> alpn_selected; public: AllocatedString peer_subject, peer_issuer_subject; SslFilter(UniqueSSL &&_ssl) :ssl(std::move(_ssl)) { SSL_set_bio(ssl.get(), NewFifoBufferBio(encrypted_input), NewFifoBufferBio(encrypted_output)); SetSslCompletionHandler(*ssl, *this); } std::span<const unsigned char> GetAlpnSelected() const noexcept { return {alpn_selected.data(), alpn_selected.size()}; } private: /** * Called from inside Run() right after the handshake has * completed. This is used to collect some data for our * public getters. */ void PostHandshake() noexcept; void Encrypt(); /* virtual methods from class ThreadSocketFilterHandler */ void PreRun(ThreadSocketFilterInternal &f) noexcept override; void Run(ThreadSocketFilterInternal &f) override; void PostRun(ThreadSocketFilterInternal &f) noexcept override; /* virtual methods from class SslCompletionHandler */ void OnSslCompletion() noexcept override { ScheduleRun(); } }; static std::runtime_error MakeSslError() { unsigned long error = ERR_get_error(); char buffer[120]; return std::runtime_error(ERR_error_string(error, buffer)); } static AllocatedString format_subject_name(X509 *cert) { return ToString(X509_get_subject_name(cert)); } static AllocatedString format_issuer_subject_name(X509 *cert) { return ToString(X509_get_issuer_name(cert)); } [[gnu::pure]] static bool is_ssl_error(SSL *ssl, int ret) { if (ret == 0) /* this is always an error according to the documentation of SSL_read(), SSL_write() and SSL_do_handshake() */ return true; switch (SSL_get_error(ssl, ret)) { case SSL_ERROR_NONE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: return false; default: return true; } } static void CheckThrowSslError(SSL *ssl, int result) { if (is_ssl_error(ssl, result)) throw MakeSslError(); } inline void SslFilter::PostHandshake() noexcept { const unsigned char *alpn_data; unsigned int alpn_length; SSL_get0_alpn_selected(ssl.get(), &alpn_data, &alpn_length); if (alpn_length > 0) alpn_selected = ConstBuffer<unsigned char>(alpn_data, alpn_length); UniqueX509 cert(SSL_get_peer_certificate(ssl.get())); if (cert != nullptr) { peer_subject = format_subject_name(cert.get()); peer_issuer_subject = format_issuer_subject_name(cert.get()); } } enum class SslDecryptResult { SUCCESS, /** * More encrypted_input data is required. */ MORE, CLOSE_NOTIFY_ALERT, }; static SslDecryptResult ssl_decrypt(SSL *ssl, ForeignFifoBuffer<uint8_t> &buffer) { /* SSL_read() must be called repeatedly until there is no more data (or until the buffer is full) */ while (true) { auto w = buffer.Write(); if (w.empty()) return SslDecryptResult::SUCCESS; int result = SSL_read(ssl, w.data, w.size); if (result < 0 && SSL_get_error(ssl, result) == SSL_ERROR_WANT_READ) return SslDecryptResult::MORE; if (result <= 0) { if (SSL_get_error(ssl, result) == SSL_ERROR_ZERO_RETURN) /* got a "close notify" alert from the peer */ return SslDecryptResult::CLOSE_NOTIFY_ALERT; CheckThrowSslError(ssl, result); return SslDecryptResult::SUCCESS; } buffer.Append(result); } } static void ssl_encrypt(SSL *ssl, ForeignFifoBuffer<uint8_t> &buffer) { /* SSL_write() must be called repeatedly until there is no more data; with SSL_MODE_ENABLE_PARTIAL_WRITE, SSL_write() finishes only the current incomplete record, and additional data which has been submitted more recently will only be considered in the next SSL_write() call */ while (true) { auto r = buffer.Read(); if (r.empty()) return; int result = SSL_write(ssl, r.data, r.size); if (result <= 0) { CheckThrowSslError(ssl, result); return; } buffer.Consume(result); } } inline void SslFilter::Encrypt() { ssl_encrypt(ssl.get(), plain_output); } /* * thread_socket_filter_handler * */ void SslFilter::PreRun(ThreadSocketFilterInternal &f) noexcept { if (f.IsIdle()) { decrypted_input.AllocateIfNull(fb_pool_get()); encrypted_output.AllocateIfNull(fb_pool_get()); } } void SslFilter::Run(ThreadSocketFilterInternal &f) { /* copy input (and output to make room for more output) */ { std::unique_lock<std::mutex> lock(f.mutex); if (f.decrypted_input.IsNull() || f.encrypted_output.IsNull()) { /* retry, let PreRun() allocate the missing buffer */ f.again = true; return; } f.decrypted_input.MoveFromAllowNull(decrypted_input); plain_output.MoveFromAllowNull(f.plain_output); encrypted_input.MoveFromAllowSrcNull(f.encrypted_input); f.encrypted_output.MoveFromAllowNull(encrypted_output); if (decrypted_input.IsNull() || encrypted_output.IsNull()) { /* retry, let PreRun() allocate the missing buffer */ f.again = true; return; } } /* let OpenSSL work */ ERR_clear_error(); if (handshaking) [[unlikely]] { int result = SSL_do_handshake(ssl.get()); if (result == 1) { handshaking = false; PostHandshake(); } else { try { CheckThrowSslError(ssl.get(), result); /* flush the encrypted_output buffer, because it may contain a "TLS alert" */ } catch (...) { const std::lock_guard<std::mutex> lock(f.mutex); f.encrypted_output.MoveFromAllowNull(encrypted_output); throw; } } } if (!handshaking) [[likely]] { Encrypt(); switch (ssl_decrypt(ssl.get(), decrypted_input)) { case SslDecryptResult::SUCCESS: break; case SslDecryptResult::MORE: if (encrypted_input.IsDefinedAndFull()) throw std::runtime_error("SSL encrypted_input buffer is full"); break; case SslDecryptResult::CLOSE_NOTIFY_ALERT: { std::unique_lock<std::mutex> lock(f.mutex); f.input_eof = true; } break; } } /* copy output */ { std::unique_lock<std::mutex> lock(f.mutex); f.decrypted_input.MoveFromAllowNull(decrypted_input); f.encrypted_output.MoveFromAllowNull(encrypted_output); f.drained = plain_output.empty() && encrypted_output.empty(); if (!decrypted_input.IsDefinedAndFull() && !f.encrypted_input.empty()) /* there's more data to be decrypted and we still have room in the destination buffer, so let's run again */ f.again = true; if (!f.plain_output.empty() && !plain_output.IsDefinedAndFull() && !encrypted_output.IsDefinedAndFull()) /* there's more data, and we're ready to handle it: try again */ f.again = true; f.handshaking = handshaking; } } void SslFilter::PostRun(ThreadSocketFilterInternal &f) noexcept { if (f.IsIdle()) { plain_output.FreeIfEmpty(); encrypted_input.FreeIfEmpty(); decrypted_input.FreeIfEmpty(); encrypted_output.FreeIfEmpty(); } } /* * constructor * */ std::unique_ptr<ThreadSocketFilterHandler> ssl_filter_new(UniqueSSL &&ssl) noexcept { return std::make_unique<SslFilter>(std::move(ssl)); } SslFilter & ssl_filter_cast_from(ThreadSocketFilterHandler &tsfh) noexcept { return static_cast<SslFilter &>(tsfh); } const SslFilter * ssl_filter_cast_from(const SocketFilter *socket_filter) noexcept { const auto *tsf = dynamic_cast<const ThreadSocketFilter *>(socket_filter); if (tsf == nullptr) return nullptr; return dynamic_cast<const SslFilter *>(&tsf->GetHandler()); } std::span<const unsigned char> ssl_filter_get_alpn_selected(const SslFilter &ssl) noexcept { return ssl.GetAlpnSelected(); } const char * ssl_filter_get_peer_subject(const SslFilter &ssl) noexcept { return ssl.peer_subject.c_str(); } const char * ssl_filter_get_peer_issuer_subject(const SslFilter &ssl) noexcept { return ssl.peer_issuer_subject.c_str(); } <commit_msg>ssl/Filter: support SSL_ERROR_WANT_X509_LOOKUP<commit_after>/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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 "Filter.hxx" #include "CompletionHandler.hxx" #include "lib/openssl/Name.hxx" #include "lib/openssl/UniqueX509.hxx" #include "FifoBufferBio.hxx" #include "fs/ThreadSocketFilter.hxx" #include "memory/fb_pool.hxx" #include "memory/SliceFifoBuffer.hxx" #include "util/AllocatedArray.hxx" #include "util/AllocatedString.hxx" #include <openssl/ssl.h> #include <openssl/err.h> #include <assert.h> #include <string.h> class SslFilter final : public ThreadSocketFilterHandler, SslCompletionHandler { /** * Buffers which can be accessed from within the thread without * holding locks. These will be copied to/from the according * #thread_socket_filter buffers. */ SliceFifoBuffer encrypted_input, decrypted_input, plain_output, encrypted_output; const UniqueSSL ssl; bool handshaking = true; AllocatedArray<unsigned char> alpn_selected; public: AllocatedString peer_subject, peer_issuer_subject; SslFilter(UniqueSSL &&_ssl) :ssl(std::move(_ssl)) { SSL_set_bio(ssl.get(), NewFifoBufferBio(encrypted_input), NewFifoBufferBio(encrypted_output)); SetSslCompletionHandler(*ssl, *this); } std::span<const unsigned char> GetAlpnSelected() const noexcept { return {alpn_selected.data(), alpn_selected.size()}; } private: /** * Called from inside Run() right after the handshake has * completed. This is used to collect some data for our * public getters. */ void PostHandshake() noexcept; void Encrypt(); /* virtual methods from class ThreadSocketFilterHandler */ void PreRun(ThreadSocketFilterInternal &f) noexcept override; void Run(ThreadSocketFilterInternal &f) override; void PostRun(ThreadSocketFilterInternal &f) noexcept override; /* virtual methods from class SslCompletionHandler */ void OnSslCompletion() noexcept override { ScheduleRun(); } }; static std::runtime_error MakeSslError() { unsigned long error = ERR_get_error(); char buffer[120]; return std::runtime_error(ERR_error_string(error, buffer)); } static AllocatedString format_subject_name(X509 *cert) { return ToString(X509_get_subject_name(cert)); } static AllocatedString format_issuer_subject_name(X509 *cert) { return ToString(X509_get_issuer_name(cert)); } [[gnu::pure]] static bool is_ssl_error(SSL *ssl, int ret) { if (ret == 0) /* this is always an error according to the documentation of SSL_read(), SSL_write() and SSL_do_handshake() */ return true; switch (SSL_get_error(ssl, ret)) { case SSL_ERROR_NONE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: case SSL_ERROR_WANT_X509_LOOKUP: return false; default: return true; } } static void CheckThrowSslError(SSL *ssl, int result) { if (is_ssl_error(ssl, result)) throw MakeSslError(); } inline void SslFilter::PostHandshake() noexcept { const unsigned char *alpn_data; unsigned int alpn_length; SSL_get0_alpn_selected(ssl.get(), &alpn_data, &alpn_length); if (alpn_length > 0) alpn_selected = ConstBuffer<unsigned char>(alpn_data, alpn_length); UniqueX509 cert(SSL_get_peer_certificate(ssl.get())); if (cert != nullptr) { peer_subject = format_subject_name(cert.get()); peer_issuer_subject = format_issuer_subject_name(cert.get()); } } enum class SslDecryptResult { SUCCESS, /** * More encrypted_input data is required. */ MORE, CLOSE_NOTIFY_ALERT, }; static SslDecryptResult ssl_decrypt(SSL *ssl, ForeignFifoBuffer<uint8_t> &buffer) { /* SSL_read() must be called repeatedly until there is no more data (or until the buffer is full) */ while (true) { auto w = buffer.Write(); if (w.empty()) return SslDecryptResult::SUCCESS; int result = SSL_read(ssl, w.data, w.size); if (result < 0 && SSL_get_error(ssl, result) == SSL_ERROR_WANT_READ) return SslDecryptResult::MORE; if (result <= 0) { if (SSL_get_error(ssl, result) == SSL_ERROR_ZERO_RETURN) /* got a "close notify" alert from the peer */ return SslDecryptResult::CLOSE_NOTIFY_ALERT; CheckThrowSslError(ssl, result); return SslDecryptResult::SUCCESS; } buffer.Append(result); } } static void ssl_encrypt(SSL *ssl, ForeignFifoBuffer<uint8_t> &buffer) { /* SSL_write() must be called repeatedly until there is no more data; with SSL_MODE_ENABLE_PARTIAL_WRITE, SSL_write() finishes only the current incomplete record, and additional data which has been submitted more recently will only be considered in the next SSL_write() call */ while (true) { auto r = buffer.Read(); if (r.empty()) return; int result = SSL_write(ssl, r.data, r.size); if (result <= 0) { CheckThrowSslError(ssl, result); return; } buffer.Consume(result); } } inline void SslFilter::Encrypt() { ssl_encrypt(ssl.get(), plain_output); } /* * thread_socket_filter_handler * */ void SslFilter::PreRun(ThreadSocketFilterInternal &f) noexcept { if (f.IsIdle()) { decrypted_input.AllocateIfNull(fb_pool_get()); encrypted_output.AllocateIfNull(fb_pool_get()); } } void SslFilter::Run(ThreadSocketFilterInternal &f) { /* copy input (and output to make room for more output) */ { std::unique_lock<std::mutex> lock(f.mutex); if (f.decrypted_input.IsNull() || f.encrypted_output.IsNull()) { /* retry, let PreRun() allocate the missing buffer */ f.again = true; return; } f.decrypted_input.MoveFromAllowNull(decrypted_input); plain_output.MoveFromAllowNull(f.plain_output); encrypted_input.MoveFromAllowSrcNull(f.encrypted_input); f.encrypted_output.MoveFromAllowNull(encrypted_output); if (decrypted_input.IsNull() || encrypted_output.IsNull()) { /* retry, let PreRun() allocate the missing buffer */ f.again = true; return; } } /* let OpenSSL work */ ERR_clear_error(); if (handshaking) [[unlikely]] { int result = SSL_do_handshake(ssl.get()); if (result == 1) { handshaking = false; PostHandshake(); } else { try { CheckThrowSslError(ssl.get(), result); /* flush the encrypted_output buffer, because it may contain a "TLS alert" */ } catch (...) { const std::lock_guard<std::mutex> lock(f.mutex); f.encrypted_output.MoveFromAllowNull(encrypted_output); throw; } } } if (!handshaking) [[likely]] { Encrypt(); switch (ssl_decrypt(ssl.get(), decrypted_input)) { case SslDecryptResult::SUCCESS: break; case SslDecryptResult::MORE: if (encrypted_input.IsDefinedAndFull()) throw std::runtime_error("SSL encrypted_input buffer is full"); break; case SslDecryptResult::CLOSE_NOTIFY_ALERT: { std::unique_lock<std::mutex> lock(f.mutex); f.input_eof = true; } break; } } /* copy output */ { std::unique_lock<std::mutex> lock(f.mutex); f.decrypted_input.MoveFromAllowNull(decrypted_input); f.encrypted_output.MoveFromAllowNull(encrypted_output); f.drained = plain_output.empty() && encrypted_output.empty(); if (!decrypted_input.IsDefinedAndFull() && !f.encrypted_input.empty()) /* there's more data to be decrypted and we still have room in the destination buffer, so let's run again */ f.again = true; if (!f.plain_output.empty() && !plain_output.IsDefinedAndFull() && !encrypted_output.IsDefinedAndFull()) /* there's more data, and we're ready to handle it: try again */ f.again = true; f.handshaking = handshaking; } } void SslFilter::PostRun(ThreadSocketFilterInternal &f) noexcept { if (f.IsIdle()) { plain_output.FreeIfEmpty(); encrypted_input.FreeIfEmpty(); decrypted_input.FreeIfEmpty(); encrypted_output.FreeIfEmpty(); } } /* * constructor * */ std::unique_ptr<ThreadSocketFilterHandler> ssl_filter_new(UniqueSSL &&ssl) noexcept { return std::make_unique<SslFilter>(std::move(ssl)); } SslFilter & ssl_filter_cast_from(ThreadSocketFilterHandler &tsfh) noexcept { return static_cast<SslFilter &>(tsfh); } const SslFilter * ssl_filter_cast_from(const SocketFilter *socket_filter) noexcept { const auto *tsf = dynamic_cast<const ThreadSocketFilter *>(socket_filter); if (tsf == nullptr) return nullptr; return dynamic_cast<const SslFilter *>(&tsf->GetHandler()); } std::span<const unsigned char> ssl_filter_get_alpn_selected(const SslFilter &ssl) noexcept { return ssl.GetAlpnSelected(); } const char * ssl_filter_get_peer_subject(const SslFilter &ssl) noexcept { return ssl.peer_subject.c_str(); } const char * ssl_filter_get_peer_issuer_subject(const SslFilter &ssl) noexcept { return ssl.peer_issuer_subject.c_str(); } <|endoftext|>
<commit_before>/******************************************************************************* * Copyright (c) 2013 Wojciech Migda * All rights reserved * Distributed under the terms of the GNU LGPL v3 ******************************************************************************* * * Filename: test_foo.hpp * * Description: * description * * Authors: * Wojciech Migda (wm) * ******************************************************************************* * History: * -------- * Date Who Ticket Description * ---------- --- --------- ------------------------------------------------ * 2013-06-27 wm Initial version * ******************************************************************************/ #include <cxxtest/TestSuite.h> #include <gmock/gmock.h> #include <memory> class TestFoo : public CxxTest::TestSuite { private: public: TestFoo() { } ~TestFoo() { } void test_111(void) { } }; <commit_msg>license<commit_after>/******************************************************************************* * Copyright (c) 2013 Wojciech Migda * All rights reserved * Distributed under the terms of the Apache 2.0 license ******************************************************************************* * * Filename: test_foo.hpp * * Description: * description * * Authors: * Wojciech Migda (wm) * ******************************************************************************* * History: * -------- * Date Who Ticket Description * ---------- --- --------- ------------------------------------------------ * 2013-06-27 wm Initial version * ******************************************************************************/ #include <cxxtest/TestSuite.h> #include <gmock/gmock.h> #include <memory> class TestFoo : public CxxTest::TestSuite { private: public: TestFoo() { } ~TestFoo() { } void test_111(void) { } }; <|endoftext|>
<commit_before>#ifndef STRUCTURES_H #define STRUCTURES_H 1 #include <QString> #include "manager.hpp" #include "singleton.hpp" //! Structure représentant un semestre temporel struct SemestreT { //! Constructeur, prend en argument une QString ex: "A12" SemestreT(const QString& s) { representation = s; isPrintemps = s.startsWith('P'); annee = 2000 + s.left(1).toInt(); } //! Représentation du semestre ex: "A12" QString representation; //! Année du semestre ex: 2012 unsigned int annee; //! Indique le semestre de l’année ex: false bool isPrintemps; //! Opérateur d’égalité pour ordonner les semestres inline bool operator==(const SemestreT &s) const { return (annee == s.annee) && (isPrintemps == s.isPrintemps); } //! Opérateur de comparaison pour ordonner les semestres inline bool operator<(const SemestreT &s) const { if (*this == s) { return false; } else { if (annee < s.annee) { return true; } if (!isPrintemps) { return true; } return false; } } }; //! Structure définissant les catégories d'UV struct CategorieUV { //! Nom de la catégorie QString nom; //! Abbréviation de la catégorie QString abbreviation; }; //! Structure définissant les notes obtenues aux UVs struct NoteUV { //! Note obtenue (A, B, C, ...) QString nom; //! Booléen indiquant la réussite de l'UV bool reussite; }; typedef Singleton<Manager<CategorieUV>> CategorieUVManager; #endif // STRUCTURES_H <commit_msg>Ajout d’un NoteUVManager<commit_after>#ifndef STRUCTURES_H #define STRUCTURES_H 1 #include <QString> #include "manager.hpp" #include "singleton.hpp" //! Structure représentant un semestre temporel struct SemestreT { //! Constructeur, prend en argument une QString ex: "A12" SemestreT(const QString& s) { representation = s; isPrintemps = s.startsWith('P'); annee = 2000 + s.left(1).toInt(); } //! Représentation du semestre ex: "A12" QString representation; //! Année du semestre ex: 2012 unsigned int annee; //! Indique le semestre de l’année ex: false bool isPrintemps; //! Opérateur d’égalité pour ordonner les semestres inline bool operator==(const SemestreT &s) const { return (annee == s.annee) && (isPrintemps == s.isPrintemps); } //! Opérateur de comparaison pour ordonner les semestres inline bool operator<(const SemestreT &s) const { if (*this == s) { return false; } else { if (annee < s.annee) { return true; } if (!isPrintemps) { return true; } return false; } } }; //! Structure définissant les catégories d'UV struct CategorieUV { //! Nom de la catégorie QString nom; //! Abbréviation de la catégorie QString abbreviation; }; //! Structure définissant les notes obtenues aux UVs struct NoteUV { //! Note obtenue (A, B, C, ...) QString nom; //! Booléen indiquant la réussite de l'UV bool reussite; }; typedef Singleton<Manager<CategorieUV>> CategorieUVManager; typedef Singleton<Manager<NoteUV>> NoteUVManager; #endif // STRUCTURES_H <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014 * * * * 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 "gtest/gtest.h" #include <ghoul/cmdparser/cmdparser> #include <ghoul/filesystem/filesystem> #include <ghoul/logging/logging> #include <ghoul/misc/dictionary.h> #include <ghoul/lua/ghoul_lua.h> #include <openspace/tests/test_common.inl> #include <openspace/tests/test_spicemanager.inl> //#include <openspace/tests/test_scenegraph.inl> #include <openspace/tests/test_powerscalecoordinates.inl> #include <openspace/engine/openspaceengine.h> #include <openspace/util/constants.h> #include <openspace/util/factorymanager.h> #include <openspace/util/spice.h> #include <openspace/util/time.h> #include <iostream> using namespace ghoul::cmdparser; using namespace ghoul::filesystem; using namespace ghoul::logging; namespace { std::string _loggerCat = "OpenSpaceTest"; } int main(int argc, char** argv) { LogManager::initialize(LogManager::LogLevel::Debug); LogMgr.addLog(new ConsoleLog); FileSystem::initialize(); std::string configurationFilePath = ""; LDEBUG("Finding configuration"); if( ! openspace::OpenSpaceEngine::findConfiguration(configurationFilePath)) { LFATAL("Could not find OpenSpace configuration file!"); assert(false); } LINFO("Configuration file found: " << FileSys.absolutePath(configurationFilePath)); LDEBUG("registering base path"); if( ! openspace::OpenSpaceEngine::registerBasePathFromConfigurationFile(configurationFilePath)) { LFATAL("Could not register base path"); assert(false); } ghoul::Dictionary configuration; ghoul::lua::loadDictionaryFromFile(configurationFilePath, configuration); if (configuration.hasKey(openspace::constants::openspaceengine::keyPaths)) { ghoul::Dictionary pathsDictionary; if (configuration.getValue(openspace::constants::openspaceengine::keyPaths, pathsDictionary)) { openspace::OpenSpaceEngine::registerPathsFromDictionary(pathsDictionary); } } /*openspace::Time::init(); openspace::Spice::init(); openspace::Spice::ref().loadDefaultKernels();*/ openspace::FactoryManager::initialize(); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Added LuaConversions test suite<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014 * * * * 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 "gtest/gtest.h" #include <ghoul/cmdparser/cmdparser> #include <ghoul/filesystem/filesystem> #include <ghoul/logging/logging> #include <ghoul/misc/dictionary.h> #include <ghoul/lua/ghoul_lua.h> #include <openspace/tests/test_common.inl> #include <openspace/tests/test_spicemanager.inl> //#include <openspace/tests/test_scenegraph.inl> #include <openspace/tests/test_luaconversions.inl> #include <openspace/tests/test_powerscalecoordinates.inl> #include <openspace/engine/openspaceengine.h> #include <openspace/util/constants.h> #include <openspace/util/factorymanager.h> #include <openspace/util/spice.h> #include <openspace/util/time.h> #include <iostream> using namespace ghoul::cmdparser; using namespace ghoul::filesystem; using namespace ghoul::logging; namespace { std::string _loggerCat = "OpenSpaceTest"; } int main(int argc, char** argv) { LogManager::initialize(LogManager::LogLevel::Debug); LogMgr.addLog(new ConsoleLog); FileSystem::initialize(); std::string configurationFilePath = ""; LDEBUG("Finding configuration"); if( ! openspace::OpenSpaceEngine::findConfiguration(configurationFilePath)) { LFATAL("Could not find OpenSpace configuration file!"); assert(false); } LINFO("Configuration file found: " << FileSys.absolutePath(configurationFilePath)); LDEBUG("Registering base path"); if( ! openspace::OpenSpaceEngine::registerBasePathFromConfigurationFile(configurationFilePath)) { LFATAL("Could not register base path"); assert(false); } ghoul::Dictionary configuration; ghoul::lua::loadDictionaryFromFile(configurationFilePath, configuration); if (configuration.hasKey(openspace::constants::openspaceengine::keyPaths)) { ghoul::Dictionary pathsDictionary; if (configuration.getValue(openspace::constants::openspaceengine::keyPaths, pathsDictionary)) { openspace::OpenSpaceEngine::registerPathsFromDictionary(pathsDictionary); } } openspace::FactoryManager::initialize(); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/*! \file * \brief Main include. * * This is the only file you have to include in order to use the * complete threadpool library. * * Copyright (c) 2005-2007 Philipp Henkel * * Use, modification, and distribution are subject to the * Boost Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * * http://threadpool.sourceforge.net * */ #ifndef THREADPOOL_HPP_INCLUDED #define THREADPOOL_HPP_INCLUDED #include "./threadpool/future.hpp" #include "./threadpool/pool.hpp" #include "./threadpool/pool_adaptors.hpp" #include "./threadpool/task_adaptors.hpp" #endif // THREADPOOL_HPP_INCLUDED <commit_msg>Removed unused header file from old threadpool code.<commit_after><|endoftext|>
<commit_before>#include <gflags/gflags.h> #include <stddef.h> #include <chrono> #include <cmath> #include <cstdint> #include <memory> #include <random> #include <string> #include <utility> #include <vector> #include "ncode_common/src/common.h" #include "ncode_common/src/file.h" #include "ncode_common/src/logging.h" #include "ncode_common/src/lp/demand_matrix.h" #include "ncode_common/src/net/algorithm.h" #include "ncode_common/src/net/net_common.h" #include "ncode_common/src/perfect_hash.h" #include "ncode_common/src/strutil.h" #include "ncode_common/src/substitute.h" #include "ncode_common/src/thread_runner.h" #include "opt/opt.h" #include "topology_input.h" DEFINE_string(output_pattern, "demand_matrices/scale_factor_$2/locality_$1/$0_$3.demands", "Traffic matrices will be saved to files named after this " "pattern, with $0 replaced by the topology name, $1 replaced by " "locality, $2 replaced by scale factor and $3 replaced by a " "unique integer identifier."); DEFINE_double(min_scale_factor, 1.3, "The generated matrix should be scaleable by at least this much " "without becoming unfeasible."); DEFINE_double(locality, 0.0, "How much of does locality factor into the traffic matrix."); DEFINE_uint64(seed, 1ul, "Seed for the generated TM."); DEFINE_uint64(tm_count, 1, "Number of TMs to generate."); DEFINE_uint64(threads, 2, "Number of threads to use."); // Generates a DemandMatrix using a scheme based on Roughan's '93 CCR paper. The // method there is extended to support geographic locality. class DemandGenerator { public: DemandGenerator(const nc::net::GraphStorage* graph) : sp_({}, graph->AdjacencyList(), nullptr, nullptr), graph_(graph), sum_inverse_delays_squared_(0) { for (nc::net::GraphNodeIndex src : graph_->AllNodes()) { for (nc::net::GraphNodeIndex dst : graph_->AllNodes()) { if (src == dst) { continue; } double distance = sp_.GetDistance(src, dst).count(); sum_inverse_delays_squared_ += std::pow(1.0 / distance, 2); } } } // Produces a demand matrix. The matrix is not guaranteed to the satisfiable. std::unique_ptr<nc::lp::DemandMatrix> SinglePass(double locality, nc::net::Bandwidth mean, std::mt19937* rnd) const { // Will start by getting the total incoming/outgoing traffic at each node. // These will come from an exponential distribution with the given mean. std::exponential_distribution<double> dist(1.0 / mean.Mbps()); nc::net::GraphNodeMap<double> incoming_traffic_Mbps; nc::net::GraphNodeMap<double> outgoing_traffic_Mbps; double total_Mbps = 0; double sum_in = 0; double sum_out = 0; for (nc::net::GraphNodeIndex node : graph_->AllNodes()) { double in = dist(*rnd); double out = dist(*rnd); incoming_traffic_Mbps[node] = in; outgoing_traffic_Mbps[node] = out; total_Mbps += in + out; sum_in += in; sum_out += out; } double sum_product = sum_in * sum_out; // Time to compute the demand for each aggregate. double total_p = 0; std::vector<nc::lp::DemandMatrixElement> elements; for (nc::net::GraphNodeIndex src : graph_->AllNodes()) { for (nc::net::GraphNodeIndex dst : graph_->AllNodes()) { double gravity_p = (1 - locality) * incoming_traffic_Mbps.GetValueOrDie(src) * outgoing_traffic_Mbps.GetValueOrDie(dst) / sum_product; if (src == dst) { total_p += gravity_p; continue; } double distance = sp_.GetDistance(src, dst).count(); double locality_p = locality / (distance * distance * sum_inverse_delays_squared_); double value_Mbps = (locality_p + gravity_p) * total_Mbps; total_p += locality_p + gravity_p; auto bw = nc::net::Bandwidth::FromMBitsPerSecond(value_Mbps); if (bw > nc::net::Bandwidth::Zero()) { elements.push_back({src, dst, bw}); } } } CHECK(std::abs(total_p - 1.0) < 0.0001) << "Not a distribution " << total_p; return nc::make_unique<nc::lp::DemandMatrix>(elements, graph_); } // Returns a random matrix with the given commodity scale factor. Will // repeatedly call SinglePass to generate a series of matrices with the // highest mean rate that the commodity scale factor allows. std::unique_ptr<nc::lp::DemandMatrix> Generate(double commodity_scale_factor, double locality, std::mt19937* rnd) const { CHECK(commodity_scale_factor >= 1.0); CHECK(locality >= 0); CHECK(locality <= 1); auto demand_matrix = SinglePass(locality, nc::net::Bandwidth::FromMBitsPerSecond(1), rnd); double csf = demand_matrix->MaxCommodityScaleFactor({}, 1.0); CHECK(csf != 0); demand_matrix = demand_matrix->Scale(csf); demand_matrix = demand_matrix->Scale(1.0 / commodity_scale_factor); LOG(INFO) << "M " << csf; return demand_matrix; } private: // For the locality constraints will also need the delays of the N*(N-1) // shortest paths in the graph. nc::net::AllPairShortestPath sp_; // The graph. const nc::net::GraphStorage* graph_; // Sum of 1 / D_i where D_i is the delay of the shortest path of the i-th // IE-pair double sum_inverse_delays_squared_; DISALLOW_COPY_AND_ASSIGN(DemandGenerator); }; using DemandMatrixVector = std::vector<std::unique_ptr<nc::lp::DemandMatrix>>; using Input = std::pair<const ctr::TopologyAndFilename*, uint32_t>; // Generates a single traffic matrix for a given graph. void ProcessMatrix(const Input& input) { std::string topology_filename = input.first->file; topology_filename = nc::File::ExtractFileName(topology_filename); topology_filename = nc::Split(topology_filename, ".").front(); const std::vector<std::string>& node_order = input.first->node_order; uint32_t id = input.second; DemandGenerator generator(input.first->graph.get()); std::mt19937 gen(FLAGS_seed + id); auto demand_matrix = generator.Generate(FLAGS_min_scale_factor, FLAGS_locality, &gen); // Will ignore all aggregates less than 1Mbps. // demand_matrix = // demand_matrix->Filter([](const nc::lp::DemandMatrixElement& element) { // return element.demand < nc::net::Bandwidth::FromMBitsPerSecond(1); // }); std::string output_location = nc::Substitute(FLAGS_output_pattern.c_str(), topology_filename, FLAGS_locality, FLAGS_min_scale_factor, id); std::string directory = nc::File::ExtractDirectoryName(output_location); if (directory != "") { nc::File::RecursivelyCreateDir(directory, 0777); } LOG(INFO) << "Will write " << demand_matrix->ToString() << " to " << output_location; nc::File::WriteStringToFileOrDie(demand_matrix->ToRepetita(node_order), output_location); } int main(int argc, char** argv) { gflags::ParseCommandLineFlags(&argc, &argv, true); std::vector<ctr::TopologyAndFilename> topologies = ctr::GetTopologyInputs(); std::vector<Input> inputs; uint32_t id = 0; for (const auto& topology : topologies) { for (size_t i = 0; i < FLAGS_tm_count; ++i) { inputs.emplace_back(&topology, id++); } } nc::RunInParallel<Input>( inputs, [](const Input& input) { ProcessMatrix(input); }, FLAGS_threads); } <commit_msg>updated TM generation<commit_after>#include <gflags/gflags.h> #include <stddef.h> #include <chrono> #include <cmath> #include <cstdint> #include <memory> #include <random> #include <string> #include <utility> #include <vector> #include "ncode_common/src/common.h" #include "ncode_common/src/file.h" #include "ncode_common/src/logging.h" #include "ncode_common/src/lp/demand_matrix.h" #include "ncode_common/src/net/algorithm.h" #include "ncode_common/src/net/net_common.h" #include "ncode_common/src/perfect_hash.h" #include "ncode_common/src/strutil.h" #include "ncode_common/src/substitute.h" #include "ncode_common/src/thread_runner.h" #include "opt/opt.h" #include "topology_input.h" DEFINE_string(output_pattern, "demand_matrices/scale_factor_$2/locality_$1/$0_$3.demands", "Traffic matrices will be saved to files named after this " "pattern, with $0 replaced by the topology name, $1 replaced by " "locality, $2 replaced by scale factor and $3 replaced by a " "unique integer identifier."); DEFINE_double(min_scale_factor, 1.3, "The generated matrix should be scaleable by at least this much " "without becoming unfeasible."); DEFINE_double(locality, 0.0, "How much of does locality factor into the traffic matrix."); DEFINE_uint64(seed, 1ul, "Seed for the generated TM."); DEFINE_uint64(tm_count, 1, "Number of TMs to generate."); DEFINE_uint64(threads, 2, "Number of threads to use."); // Generates a DemandMatrix using a scheme based on Roughan's '93 CCR paper. The // method there is extended to support geographic locality. class DemandGenerator { public: DemandGenerator(const nc::net::GraphStorage* graph) : sp_({}, graph->AdjacencyList(), nullptr, nullptr), graph_(graph), sum_inverse_delays_squared_(0) { for (nc::net::GraphNodeIndex src : graph_->AllNodes()) { for (nc::net::GraphNodeIndex dst : graph_->AllNodes()) { if (src == dst) { continue; } double distance = sp_.GetDistance(src, dst).count(); sum_inverse_delays_squared_ += std::pow(1.0 / distance, 2); } } } // Produces a demand matrix. The matrix is not guaranteed to the satisfiable. std::unique_ptr<nc::lp::DemandMatrix> SinglePass(nc::net::Bandwidth mean, std::mt19937* rnd) const { // Will start by getting the total incoming/outgoing traffic at each node. // These will come from an exponential distribution with the given mean. std::exponential_distribution<double> dist(1.0 / mean.Mbps()); nc::net::GraphNodeMap<double> incoming_traffic_Mbps; nc::net::GraphNodeMap<double> outgoing_traffic_Mbps; double total_Mbps = 0; double sum_in = 0; double sum_out = 0; for (nc::net::GraphNodeIndex node : graph_->AllNodes()) { double in = dist(*rnd); double out = dist(*rnd); incoming_traffic_Mbps[node] = in; outgoing_traffic_Mbps[node] = out; total_Mbps += in + out; sum_in += in; sum_out += out; } double sum_product = sum_in * sum_out; // Time to compute the demand for each aggregate. double total_p = 0; std::vector<nc::lp::DemandMatrixElement> elements; for (nc::net::GraphNodeIndex src : graph_->AllNodes()) { for (nc::net::GraphNodeIndex dst : graph_->AllNodes()) { double gravity_p = incoming_traffic_Mbps.GetValueOrDie(src) * outgoing_traffic_Mbps.GetValueOrDie(dst) / sum_product; if (src == dst) { total_p += gravity_p; continue; } double value_Mbps = gravity_p * total_Mbps; total_p += gravity_p; auto bw = nc::net::Bandwidth::FromMBitsPerSecond(value_Mbps); if (bw > nc::net::Bandwidth::Zero()) { elements.push_back({src, dst, bw}); } } } CHECK(std::abs(total_p - 1.0) < 0.0001) << "Not a distribution " << total_p; return nc::make_unique<nc::lp::DemandMatrix>(elements, graph_); } // Like above, but for a single source. static std::unique_ptr<nc::lp::DemandMatrix> LocalizeSource( nc::net::GraphNodeIndex src_node, const nc::lp::DemandMatrix& matrix, double locality) { // Need to first get the current distribution. nc::net::Bandwidth total_demand = nc::net::Bandwidth::Zero(); nc::net::GraphNodeMap<nc::net::Bandwidth> demands; for (const auto& element : matrix.elements()) { if (element.src != src_node) { continue; } demands[element.dst] += element.demand; total_demand += element.demand; } // Now figure out what the distribution entirely based on locality would be. const nc::net::GraphStorage* graph = matrix.graph(); nc::net::GraphNodeSet to = graph->AllNodes(); to.Remove(src_node); nc::net::ShortestPath sp_tree(src_node, to, {}, graph->AdjacencyList(), nullptr, nullptr); double sum_delays_inverse = 0; for (nc::net::GraphNodeIndex dst : to) { nc::net::Delay delay = sp_tree.GetPathDistance(dst); sum_delays_inverse += 1.0 / delay.count(); } nc::net::GraphNodeMap<double> local_probabilities; for (nc::net::GraphNodeIndex dst : to) { nc::net::Delay delay = sp_tree.GetPathDistance(dst); local_probabilities[dst] = 1.0 / (delay.count() * sum_delays_inverse); } // Now to get the mixture distribution. std::vector<nc::lp::DemandMatrixElement> new_demands; double total_p = 0; for (nc::net::GraphNodeIndex dst : to) { double current_p = demands[dst] / total_demand; double local_p = local_probabilities.GetValueOrDie(dst); double new_p = current_p * (1 - locality) + locality * local_p; total_p += new_p; new_demands.emplace_back(src_node, dst, total_demand * new_p); } CHECK(std::abs(total_p - 1.0) < 0.0001) << "Not a distribution " << total_p; return nc::make_unique<nc::lp::DemandMatrix>(new_demands, graph); } // Makes a demand matrix more local. If locality is 0 demands are not changed // if locality is 1. All traffic coming out of a node will be distributed // inversely proportional to SP delay from node to other nodes. static std::unique_ptr<nc::lp::DemandMatrix> Localize( const nc::lp::DemandMatrix& matrix, double locality) { std::unique_ptr<nc::lp::DemandMatrix> out; for (const auto& element : matrix.elements()) { if (out) { out = LocalizeSource(element.src, *out, locality); } else { out = LocalizeSource(element.src, matrix, locality); } } return out; } // Returns a random matrix with the given commodity scale factor. Will // repeatedly call SinglePass to generate a series of matrices with the // highest mean rate that the commodity scale factor allows. std::unique_ptr<nc::lp::DemandMatrix> Generate(double commodity_scale_factor, double locality, std::mt19937* rnd) const { CHECK(commodity_scale_factor >= 1.0); CHECK(locality >= 0); CHECK(locality <= 1); auto demand_matrix = SinglePass(nc::net::Bandwidth::FromMBitsPerSecond(1), rnd); demand_matrix = Localize(*demand_matrix, locality); double csf = demand_matrix->MaxCommodityScaleFactor({}, 1.0); CHECK(csf != 0); demand_matrix = demand_matrix->Scale(csf); demand_matrix = demand_matrix->Scale(1.0 / commodity_scale_factor); LOG(INFO) << "M " << csf; return demand_matrix; } private: // For the locality constraints will also need the delays of the N*(N-1) // shortest paths in the graph. nc::net::AllPairShortestPath sp_; // The graph. const nc::net::GraphStorage* graph_; // Sum of 1 / D_i where D_i is the delay of the shortest path of the i-th // IE-pair double sum_inverse_delays_squared_; DISALLOW_COPY_AND_ASSIGN(DemandGenerator); }; using DemandMatrixVector = std::vector<std::unique_ptr<nc::lp::DemandMatrix>>; using Input = std::pair<const ctr::TopologyAndFilename*, uint32_t>; // Generates a single traffic matrix for a given graph. void ProcessMatrix(const Input& input) { std::string topology_filename = input.first->file; topology_filename = nc::File::ExtractFileName(topology_filename); topology_filename = nc::Split(topology_filename, ".").front(); const std::vector<std::string>& node_order = input.first->node_order; uint32_t id = input.second; DemandGenerator generator(input.first->graph.get()); std::mt19937 gen(FLAGS_seed + id); auto demand_matrix = generator.Generate(FLAGS_min_scale_factor, FLAGS_locality, &gen); // Will ignore all aggregates less than 1Mbps. // demand_matrix = // demand_matrix->Filter([](const nc::lp::DemandMatrixElement& element) { // return element.demand < nc::net::Bandwidth::FromMBitsPerSecond(1); // }); std::string output_location = nc::Substitute(FLAGS_output_pattern.c_str(), topology_filename, FLAGS_locality, FLAGS_min_scale_factor, id); std::string directory = nc::File::ExtractDirectoryName(output_location); if (directory != "") { nc::File::RecursivelyCreateDir(directory, 0777); } LOG(INFO) << "Will write " << demand_matrix->ToString() << " to " << output_location; nc::File::WriteStringToFileOrDie(demand_matrix->ToRepetita(node_order), output_location); } int main(int argc, char** argv) { gflags::ParseCommandLineFlags(&argc, &argv, true); std::vector<ctr::TopologyAndFilename> topologies = ctr::GetTopologyInputs(); std::vector<Input> inputs; uint32_t id = 0; for (const auto& topology : topologies) { for (size_t i = 0; i < FLAGS_tm_count; ++i) { inputs.emplace_back(&topology, id++); } } nc::RunInParallel<Input>( inputs, [](const Input& input) { ProcessMatrix(input); }, FLAGS_threads); } <|endoftext|>
<commit_before>/* Copyright 2017 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // portability wrapper over NUMA system interfaces // NOTE: this is nowhere near a full libnuma-style interface - it's just the // calls that Realm's NUMA module needs #include "numasysif.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <vector> #ifdef __linux__ #include <unistd.h> #include <sys/syscall.h> #include <linux/mempolicy.h> #include <dirent.h> #include <sched.h> #include <ctype.h> #include <sys/mman.h> namespace { long get_mempolicy(int *policy, const unsigned long *nmask, unsigned long maxnode, void *addr, int flags) { return syscall(__NR_get_mempolicy, policy, nmask, maxnode, addr, flags); } long mbind(void *start, unsigned long len, int mode, const unsigned long *nmask, unsigned long maxnode, unsigned flags) { return syscall(__NR_mbind, (long)start, len, mode, (long)nmask, maxnode, flags); } #if 0 long set_mempolicy(int mode, const unsigned long *nmask, unsigned long maxnode) { return syscall(__NR_set_mempolicy, mode, nmask, maxnode); } #endif }; #endif namespace Realm { // as soon as we get more than one real version of these, split them out into // separate files // is NUMA support available in the system? bool numasysif_numa_available(void) { #ifdef __linux__ int policy; unsigned long nmask = 0; errno = 0; int ret = get_mempolicy(&policy, &nmask, 8*sizeof(nmask), 0, MPOL_F_MEMS_ALLOWED); if((ret != 0) || (nmask == 0)) { fprintf(stderr, "get_mempolicy() returned: ret=%d nmask=%08lx errno=%d\n", ret, nmask, errno); return false; } //printf("policy=%d nmask=%08lx\n", policy, nmask); //ret = get_mempolicy(&policy, &nmask, 8*sizeof(nmask), 0, 0); //printf("ret=%d policy=%d nmask=%08lx\n", ret, policy, nmask); return true; #else return false; #endif } // return info on the memory and cpu in each NUMA node // default is to restrict to only those nodes enabled in the current affinity mask bool numasysif_get_mem_info(std::map<int, NumaNodeMemInfo>& info, bool only_available /*= true*/) { #ifdef __linux__ int policy = -1; unsigned long nmask = 0; int ret = -1; if(only_available) { // first, ask for the default policy for the thread to detect binding via // numactl, mpirun, etc. ret = get_mempolicy(&policy, &nmask, 8*sizeof(nmask), 0, 0); } if((ret != 0) || (policy != MPOL_BIND) || (nmask == 0)) { // not a reasonable-looking bound state, so ask for all nodes ret = get_mempolicy(&policy, &nmask, 8*sizeof(nmask), 0, MPOL_F_MEMS_ALLOWED); if((ret != 0) || (nmask == 0)) { // still no good return false; } } // for each bit set in the mask, try to query the free memory for(int i = 0; i < 8*(int)sizeof(nmask); i++) if(((nmask >> i) & 1) != 0) { // free information comes from /sys... char fname[80]; sprintf(fname, "/sys/devices/system/node/node%d/meminfo", i); FILE *f = fopen(fname, "r"); if(!f) { fprintf(stderr, "can't read '%s': %s\n", fname, strerror(errno)); continue; } char line[256]; while(fgets(line, 256, f)) { const char *s = strstr(line, "MemFree"); if(!s) continue; const char *endptr; errno = 0; long long sz = strtoll(s+9, (char **)&endptr, 10); if((errno != 0) || strcmp(endptr, " kB\n")) { fprintf(stderr, "ill-formed line: '%s' '%s'\n", s, endptr); continue; } // success - add this to the list and stop reading NumaNodeMemInfo& mi = info[i]; mi.node_id = i; mi.bytes_available = (sz << 10); break; } // if we get all the way through the file without finding the size, // we just don't add anything to the info fclose(f); } // as long as we got at least one valid node, assume we're successful return !info.empty(); #else return false; #endif } bool numasysif_get_cpu_info(std::map<int, NumaNodeCpuInfo>& info, bool only_available /*= true*/) { #ifdef __linux__ // if we're restricting to what's been made available, find what's been // made available cpu_set_t avail_cpus; if(only_available) { int ret = sched_getaffinity(0, sizeof(avail_cpus), &avail_cpus); if(ret != 0) { fprintf(stderr, "sched_getaffinity failed: %s\n", strerror(errno)); return false; } } else CPU_ZERO(&avail_cpus); // now enumerate cpus via /sys and determine which nodes they belong to std::map<int, int> cpu_counts; DIR *cpudir = opendir("/sys/devices/system/cpu"); if(!cpudir) { fprintf(stderr, "couldn't read /sys/devices/system/cpu: %s\n", strerror(errno)); return false; } struct dirent *de; while((de = readdir(cpudir)) != 0) if(!strncmp(de->d_name, "cpu", 3)) { int cpu_index = atoi(de->d_name + 3); if(only_available && !CPU_ISSET(cpu_index, &avail_cpus)) continue; // find the node symlink to determine the node char path2[256]; sprintf(path2, "/sys/devices/system/cpu/%s", de->d_name); DIR *d2 = opendir(path2); if(!d2) { fprintf(stderr, "couldn't read '%s': %s\n", path2, strerror(errno)); continue; } struct dirent *de2; while((de2 = readdir(d2)) != 0) if(!strncmp(de2->d_name, "node", 4)) { int node_index = atoi(de2->d_name + 4); cpu_counts[node_index]++; break; } closedir(d2); } // any matches is "success" if(!cpu_counts.empty()) { for(std::map<int,int>::const_iterator it = cpu_counts.begin(); it != cpu_counts.end(); ++it) { NumaNodeCpuInfo& ci = info[it->first]; ci.node_id = it->first; ci.cores_available = it->second; } return true; } else return false; #else return false; #endif } // return the "distance" between two nodes - try to normalize to Linux's model of // 10 being the same node and the cost for other nodes increasing by roughly 10 // per hop int numasysif_get_distance(int node1, int node2) { #ifdef __linux__ static std::map<int, std::vector<int> > saved_distances; std::map<int, std::vector<int> >::iterator it = saved_distances.find(node1); if(it == saved_distances.end()) { // not one we've already looked up, so do it now // if we break out early, we'll end up with an empty vector, which means // we'll return -1 for all future queries std::vector<int>& v = saved_distances[node1]; char fname[256]; sprintf(fname, "/sys/devices/system/node/node%d/distance", node1); FILE *f = fopen(fname, "r"); if(!f) { fprintf(stderr, "can't read '%s': %s\n", fname, strerror(errno)); saved_distances[node1].clear(); return -1; } char line[256]; if(fgets(line, 256, f)) { char *p = line; while(isdigit(*p)) { errno = 0; int d = strtol(p, &p, 10); if(errno != 0) break; v.push_back(d); while(isspace(*p)) p++; } } fclose(f); if((node2 >= 0) && (node2 < (int)v.size())) return v[node2]; else return -1; } else { const std::vector<int>& v = it->second; if((node2 >= 0) && (node2 < (int)v.size())) return v[node2]; else return -1; } #else return -1; #endif } // allocate memory on a given NUMA node - pin if requested void *numasysif_alloc_mem(int node, size_t bytes, bool pin) { #ifdef __linux__ // get memory from mmap // TODO: hugetlbfs, if possible void *base = mmap(0, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if(!base) return 0; // use the bind call for the rest if(numasysif_bind_mem(node, base, bytes, pin)) return base; // if not, clean up and return failure numasysif_free_mem(node, base, bytes); return 0; #else return 0; #endif } // free memory allocated on a given NUMA node bool numasysif_free_mem(int node, void *base, size_t bytes) { #ifdef __linux__ int ret = munmap(base, bytes); return(ret == 0); #else return false; #endif } // bind already-allocated memory to a given node - pin if requested // may fail if the memory has already been touched bool numasysif_bind_mem(int node, void *base, size_t bytes, bool pin) { #ifdef __linux__ int policy = MPOL_BIND; unsigned long nmask = (1UL << node); int ret = mbind(base, bytes, policy, &nmask, 8*sizeof(nmask), MPOL_MF_STRICT | MPOL_MF_MOVE); if(ret != 0) { fprintf(stderr, "failed to bind memory for node %d: %s\n", node, strerror(errno)); return false; } // attempt to pin the memory if requested if(pin) { int ret = mlock(base, bytes); if(ret != 0) { fprintf(stderr, "mlock failed for memory on node %d: %s\n", node, strerror(errno)); return false; } } return true; #else return false; #endif } }; <commit_msg>numa: support for more than 64 NUMA nodes<commit_after>/* Copyright 2017 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // portability wrapper over NUMA system interfaces // NOTE: this is nowhere near a full libnuma-style interface - it's just the // calls that Realm's NUMA module needs #include "numasysif.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <vector> #ifdef __linux__ #include <alloca.h> #include <unistd.h> #include <sys/syscall.h> #include <linux/mempolicy.h> #include <dirent.h> #include <sched.h> #include <ctype.h> #include <sys/mman.h> namespace { long get_mempolicy(int *policy, unsigned long *nmask, unsigned long maxnode, void *addr, int flags) { return syscall(__NR_get_mempolicy, policy, nmask, maxnode, addr, flags); } long mbind(void *start, unsigned long len, int mode, const unsigned long *nmask, unsigned long maxnode, unsigned flags) { return syscall(__NR_mbind, (long)start, len, mode, (long)nmask, maxnode, flags); } #if 0 long set_mempolicy(int mode, const unsigned long *nmask, unsigned long maxnode) { return syscall(__NR_set_mempolicy, mode, nmask, maxnode); } #endif }; #endif namespace Realm { // as soon as we get more than one real version of these, split them out into // separate files #ifdef __linux__ namespace { // Linux wants you to guess how many nodes there are, and if you're wrong, // it just tells you to try again - save the answer here so we only have // to do it once int detected_node_count = 8 * sizeof(unsigned long); const int max_supported_node_count = 1024 * sizeof(unsigned long); }; #endif static bool mask_nonempty(const unsigned char *nmask, int max_count) { for(int i = 0; i < (max_count >> 3); i++) if(nmask[i] != 0) return true; return false; } // is NUMA support available in the system? bool numasysif_numa_available(void) { #ifdef __linux__ int policy; unsigned char *nmask = (unsigned char *)alloca(max_supported_node_count >> 3); while(1) { errno = 0; int ret = get_mempolicy(&policy, (unsigned long *)nmask, detected_node_count, 0, MPOL_F_MEMS_ALLOWED); if(ret == 0) break; // EINVAL maybe means our mask isn't big enough if((errno == EINVAL) && (detected_node_count < max_supported_node_count)) { detected_node_count <<= 1; } else { // otherwise we're out of luck //fprintf(stderr, "get_mempolicy() returned: ret=%d errno=%d\n", ret, errno); return false; } } // also check that we have at least one node set in the mask - if not, // assume numa support is disabled if(!mask_nonempty(nmask, detected_node_count)) { //fprintf(stderr, "get_mempolicy() returned empty node mask!\n"); return false; } return true; #else return false; #endif } // return info on the memory and cpu in each NUMA node // default is to restrict to only those nodes enabled in the current affinity mask bool numasysif_get_mem_info(std::map<int, NumaNodeMemInfo>& info, bool only_available /*= true*/) { #ifdef __linux__ int policy = -1; unsigned char *nmask = (unsigned char *)alloca(detected_node_count >> 3); for(int i = 0; i < detected_node_count >> 3; i++) nmask[i] = 0; int ret = -1; if(only_available) { // first, ask for the default policy for the thread to detect binding via // numactl, mpirun, etc. errno = 0; ret = get_mempolicy(&policy, (unsigned long *)nmask, detected_node_count, 0, 0); } if((ret != 0) || (policy != MPOL_BIND) || !mask_nonempty(nmask, detected_node_count)) { // not a reasonable-looking bound state, so ask for all nodes errno = 0; ret = get_mempolicy(&policy, (unsigned long *)nmask, detected_node_count, 0, MPOL_F_MEMS_ALLOWED); if((ret != 0) || !mask_nonempty(nmask, detected_node_count)) { // this really shouldn't fail, since we made the same call above in // numasysif_numa_available() fprintf(stderr, "mems_allowed: ret=%d errno=%d mask=%08lx count=%d\n", ret, errno, *(unsigned long *)nmask, detected_node_count); return false; } } // for each bit set in the mask, try to query the free memory for(int i = 0; i < detected_node_count; i++) if(((nmask[i >> 3] >> (i & 7)) & 1) != 0) { // free information comes from /sys... char fname[80]; sprintf(fname, "/sys/devices/system/node/node%d/meminfo", i); FILE *f = fopen(fname, "r"); if(!f) { fprintf(stderr, "can't read '%s': %s\n", fname, strerror(errno)); continue; } char line[256]; while(fgets(line, 256, f)) { const char *s = strstr(line, "MemFree"); if(!s) continue; const char *endptr; errno = 0; long long sz = strtoll(s+9, (char **)&endptr, 10); if((errno != 0) || strcmp(endptr, " kB\n")) { fprintf(stderr, "ill-formed line: '%s' '%s'\n", s, endptr); continue; } // success - add this to the list and stop reading NumaNodeMemInfo& mi = info[i]; mi.node_id = i; mi.bytes_available = (sz << 10); break; } // if we get all the way through the file without finding the size, // we just don't add anything to the info fclose(f); } // as long as we got at least one valid node, assume we're successful return !info.empty(); #else return false; #endif } bool numasysif_get_cpu_info(std::map<int, NumaNodeCpuInfo>& info, bool only_available /*= true*/) { #ifdef __linux__ // if we're restricting to what's been made available, find what's been // made available cpu_set_t avail_cpus; if(only_available) { int ret = sched_getaffinity(0, sizeof(avail_cpus), &avail_cpus); if(ret != 0) { fprintf(stderr, "sched_getaffinity failed: %s\n", strerror(errno)); return false; } } else CPU_ZERO(&avail_cpus); // now enumerate cpus via /sys and determine which nodes they belong to std::map<int, int> cpu_counts; DIR *cpudir = opendir("/sys/devices/system/cpu"); if(!cpudir) { fprintf(stderr, "couldn't read /sys/devices/system/cpu: %s\n", strerror(errno)); return false; } struct dirent *de; while((de = readdir(cpudir)) != 0) if(!strncmp(de->d_name, "cpu", 3)) { int cpu_index = atoi(de->d_name + 3); if(only_available && !CPU_ISSET(cpu_index, &avail_cpus)) continue; // find the node symlink to determine the node char path2[256]; sprintf(path2, "/sys/devices/system/cpu/%s", de->d_name); DIR *d2 = opendir(path2); if(!d2) { fprintf(stderr, "couldn't read '%s': %s\n", path2, strerror(errno)); continue; } struct dirent *de2; while((de2 = readdir(d2)) != 0) if(!strncmp(de2->d_name, "node", 4)) { int node_index = atoi(de2->d_name + 4); cpu_counts[node_index]++; break; } closedir(d2); } // any matches is "success" if(!cpu_counts.empty()) { for(std::map<int,int>::const_iterator it = cpu_counts.begin(); it != cpu_counts.end(); ++it) { NumaNodeCpuInfo& ci = info[it->first]; ci.node_id = it->first; ci.cores_available = it->second; } return true; } else return false; #else return false; #endif } // return the "distance" between two nodes - try to normalize to Linux's model of // 10 being the same node and the cost for other nodes increasing by roughly 10 // per hop int numasysif_get_distance(int node1, int node2) { #ifdef __linux__ static std::map<int, std::vector<int> > saved_distances; std::map<int, std::vector<int> >::iterator it = saved_distances.find(node1); if(it == saved_distances.end()) { // not one we've already looked up, so do it now // if we break out early, we'll end up with an empty vector, which means // we'll return -1 for all future queries std::vector<int>& v = saved_distances[node1]; char fname[256]; sprintf(fname, "/sys/devices/system/node/node%d/distance", node1); FILE *f = fopen(fname, "r"); if(!f) { fprintf(stderr, "can't read '%s': %s\n", fname, strerror(errno)); saved_distances[node1].clear(); return -1; } char line[256]; if(fgets(line, 256, f)) { char *p = line; while(isdigit(*p)) { errno = 0; int d = strtol(p, &p, 10); if(errno != 0) break; v.push_back(d); while(isspace(*p)) p++; } } fclose(f); if((node2 >= 0) && (node2 < (int)v.size())) return v[node2]; else return -1; } else { const std::vector<int>& v = it->second; if((node2 >= 0) && (node2 < (int)v.size())) return v[node2]; else return -1; } #else return -1; #endif } // allocate memory on a given NUMA node - pin if requested void *numasysif_alloc_mem(int node, size_t bytes, bool pin) { #ifdef __linux__ // get memory from mmap // TODO: hugetlbfs, if possible void *base = mmap(0, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if(!base) return 0; // use the bind call for the rest if(numasysif_bind_mem(node, base, bytes, pin)) return base; // if not, clean up and return failure numasysif_free_mem(node, base, bytes); return 0; #else return 0; #endif } // free memory allocated on a given NUMA node bool numasysif_free_mem(int node, void *base, size_t bytes) { #ifdef __linux__ int ret = munmap(base, bytes); return(ret == 0); #else return false; #endif } // bind already-allocated memory to a given node - pin if requested // may fail if the memory has already been touched bool numasysif_bind_mem(int node, void *base, size_t bytes, bool pin) { #ifdef __linux__ int policy = MPOL_BIND; if((node < 0) || (node >= detected_node_count)) { fprintf(stderr, "bind request for node out of range: %d\n", node); return false; } unsigned char *nmask = (unsigned char *)alloca(detected_node_count >> 3); for(int i = 0; i < detected_node_count >> 3; i++) nmask[i] = 0; nmask[(node >> 3)] = (1 << (node & 7)); int ret = mbind(base, bytes, policy, (const unsigned long *)nmask, detected_node_count, MPOL_MF_STRICT | MPOL_MF_MOVE); if(ret != 0) { fprintf(stderr, "failed to bind memory for node %d: %s\n", node, strerror(errno)); return false; } // attempt to pin the memory if requested if(pin) { int ret = mlock(base, bytes); if(ret != 0) { fprintf(stderr, "mlock failed for memory on node %d: %s\n", node, strerror(errno)); return false; } } return true; #else return false; #endif } }; <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkSpline.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 "vtkSpline.h" // Construct a spline wth the folloing defaults: // ClampValueOff vtkSpline::vtkSpline () { this->ComputeTime = 0; this->ClampValue = 0; this->PiecewiseFunction = new vtkPiecewiseFunction; this->Intervals = NULL; this->Coefficients = NULL; this->LeftConstraint = 1; this->LeftValue = 0.0; this->RightConstraint = 1; this->RightValue = 0.0; this->Closed = 0; } vtkSpline::~vtkSpline () { if (this->PiecewiseFunction) this->PiecewiseFunction->Delete(); if (this->Coefficients) delete [] this->Coefficients; if (this->Intervals) delete [] this->Intervals; } // Add a point to the Piecewise Functions containing the data void vtkSpline::AddPoint (float t, float x) { this->PiecewiseFunction->AddPoint (t, x); } // Remove a point from the Piecewise Functions. void vtkSpline::RemovePoint (float t) { this->PiecewiseFunction->RemovePoint (t); } // Remove all points from the Piecewise Functions. void vtkSpline::RemoveAllPoints () { this->PiecewiseFunction->RemoveAllPoints (); } // Overload standard modified time function. If data is modified, // then this object is modified as well. unsigned long vtkSpline::GetMTime() { unsigned long mTime=this->vtkObject::GetMTime(); unsigned long DataMTime; if ( this->PiecewiseFunction != NULL ) { DataMTime = this->PiecewiseFunction->GetMTime(); mTime = ( DataMTime > mTime ? DataMTime : mTime ); } return mTime; } void vtkSpline::PrintSelf(ostream& os, vtkIndent indent) { vtkObject::PrintSelf(os,indent); os << indent << "Clamp Value: " << (this->ClampValue ? "On\n" : "Off\n"); os << indent << "Left Constraint: " << this->LeftConstraint << "\n"; os << indent << "Right Constraint: " << this->RightConstraint << "\n"; os << indent << "Left Value: " << this->LeftValue << "\n"; os << indent << "Right Value: " << this->RightValue << "\n"; os << indent << "Closed: " << (this->Closed ? "On\n" : "Off\n"); os << indent << "Piecewise Function:\n"; this->PiecewiseFunction->PrintSelf(os,indent.GetNextIndent()); } <commit_msg>ERR:Added extra print info<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkSpline.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 "vtkSpline.h" // Construct a spline wth the folloing defaults: // ClampValueOff vtkSpline::vtkSpline () { this->ComputeTime = 0; this->ClampValue = 0; this->PiecewiseFunction = new vtkPiecewiseFunction; this->Intervals = NULL; this->Coefficients = NULL; this->LeftConstraint = 1; this->LeftValue = 0.0; this->RightConstraint = 1; this->RightValue = 0.0; this->Closed = 0; } vtkSpline::~vtkSpline () { if (this->PiecewiseFunction) this->PiecewiseFunction->Delete(); if (this->Coefficients) delete [] this->Coefficients; if (this->Intervals) delete [] this->Intervals; } // Add a point to the Piecewise Functions containing the data void vtkSpline::AddPoint (float t, float x) { this->PiecewiseFunction->AddPoint (t, x); } // Remove a point from the Piecewise Functions. void vtkSpline::RemovePoint (float t) { this->PiecewiseFunction->RemovePoint (t); } // Remove all points from the Piecewise Functions. void vtkSpline::RemoveAllPoints () { this->PiecewiseFunction->RemoveAllPoints (); } // Overload standard modified time function. If data is modified, // then this object is modified as well. unsigned long vtkSpline::GetMTime() { unsigned long mTime=this->vtkObject::GetMTime(); unsigned long DataMTime; if ( this->PiecewiseFunction != NULL ) { DataMTime = this->PiecewiseFunction->GetMTime(); mTime = ( DataMTime > mTime ? DataMTime : mTime ); } return mTime; } void vtkSpline::PrintSelf(ostream& os, vtkIndent indent) { vtkObject::PrintSelf(os,indent); os << indent << "Clamp Value: " << (this->ClampValue ? "On\n" : "Off\n"); os << indent << "Left Constraint: " << this->LeftConstraint << "\n"; os << indent << "Right Constraint: " << this->RightConstraint << "\n"; os << indent << "Left Value: " << this->LeftValue << "\n"; os << indent << "Right Value: " << this->RightValue << "\n"; os << indent << "Closed: " << (this->Closed ? "On\n" : "Off\n"); os << indent << "Piecewise Function:\n"; this->PiecewiseFunction->PrintSelf(os,indent.GetNextIndent()); os << indent << "Closed: " << (this->Closed ? "On\n" : "Off\n"); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "global.hxx" #include "scresid.hxx" #include "impex.hxx" #include "asciiopt.hxx" #include "asciiopt.hrc" #include <comphelper/string.hxx> #include <rtl/tencinfo.h> #include <unotools/transliterationwrapper.hxx> // ause #include "editutil.hxx" // ============================================================================ static const sal_Char pStrFix[] = "FIX"; static const sal_Char pStrMrg[] = "MRG"; // ============================================================================ ScAsciiOptions::ScAsciiOptions() : bFixedLen ( false ), aFieldSeps ( OUString(';') ), bMergeFieldSeps ( false ), bQuotedFieldAsText(false), bDetectSpecialNumber(false), cTextSep ( cDefaultTextSep ), eCharSet ( osl_getThreadTextEncoding() ), eLang ( LANGUAGE_SYSTEM ), bCharSetSystem ( false ), nStartRow ( 1 ), nInfoCount ( 0 ), pColStart ( NULL ), pColFormat ( NULL ) { } ScAsciiOptions::ScAsciiOptions(const ScAsciiOptions& rOpt) : bFixedLen ( rOpt.bFixedLen ), aFieldSeps ( rOpt.aFieldSeps ), bMergeFieldSeps ( rOpt.bMergeFieldSeps ), bQuotedFieldAsText(rOpt.bQuotedFieldAsText), bDetectSpecialNumber(rOpt.bDetectSpecialNumber), cTextSep ( rOpt.cTextSep ), eCharSet ( rOpt.eCharSet ), eLang ( rOpt.eLang ), bCharSetSystem ( rOpt.bCharSetSystem ), nStartRow ( rOpt.nStartRow ), nInfoCount ( rOpt.nInfoCount ) { if (nInfoCount) { pColStart = new sal_Int32[nInfoCount]; pColFormat = new sal_uInt8[nInfoCount]; for (sal_uInt16 i=0; i<nInfoCount; i++) { pColStart[i] = rOpt.pColStart[i]; pColFormat[i] = rOpt.pColFormat[i]; } } else { pColStart = NULL; pColFormat = NULL; } } ScAsciiOptions::~ScAsciiOptions() { delete[] pColStart; delete[] pColFormat; } void ScAsciiOptions::SetColInfo( sal_uInt16 nCount, const sal_Int32* pStart, const sal_uInt8* pFormat ) { delete[] pColStart; delete[] pColFormat; nInfoCount = nCount; if (nInfoCount) { pColStart = new sal_Int32[nInfoCount]; pColFormat = new sal_uInt8[nInfoCount]; for (sal_uInt16 i=0; i<nInfoCount; i++) { pColStart[i] = pStart[i]; pColFormat[i] = pFormat[i]; } } else { pColStart = NULL; pColFormat = NULL; } } void ScAsciiOptions::SetColumnInfo( const ScCsvExpDataVec& rDataVec ) { delete[] pColStart; pColStart = NULL; delete[] pColFormat; pColFormat = NULL; nInfoCount = static_cast< sal_uInt16 >( rDataVec.size() ); if( nInfoCount ) { pColStart = new sal_Int32[ nInfoCount ]; pColFormat = new sal_uInt8[ nInfoCount ]; for( sal_uInt16 nIx = 0; nIx < nInfoCount; ++nIx ) { pColStart[ nIx ] = rDataVec[ nIx ].mnIndex; pColFormat[ nIx ] = rDataVec[ nIx ].mnType; } } } ScAsciiOptions& ScAsciiOptions::operator=( const ScAsciiOptions& rCpy ) { SetColInfo( rCpy.nInfoCount, rCpy.pColStart, rCpy.pColFormat ); bFixedLen = rCpy.bFixedLen; aFieldSeps = rCpy.aFieldSeps; bMergeFieldSeps = rCpy.bMergeFieldSeps; bQuotedFieldAsText = rCpy.bQuotedFieldAsText; cTextSep = rCpy.cTextSep; eCharSet = rCpy.eCharSet; bCharSetSystem = rCpy.bCharSetSystem; nStartRow = rCpy.nStartRow; return *this; } bool ScAsciiOptions::operator==( const ScAsciiOptions& rCmp ) const { if ( bFixedLen == rCmp.bFixedLen && aFieldSeps == rCmp.aFieldSeps && bMergeFieldSeps == rCmp.bMergeFieldSeps && bQuotedFieldAsText == rCmp.bQuotedFieldAsText && cTextSep == rCmp.cTextSep && eCharSet == rCmp.eCharSet && bCharSetSystem == rCmp.bCharSetSystem && nStartRow == rCmp.nStartRow && nInfoCount == rCmp.nInfoCount ) { OSL_ENSURE( !nInfoCount || (pColStart && pColFormat && rCmp.pColStart && rCmp.pColFormat), "0-Zeiger in ScAsciiOptions" ); for (sal_uInt16 i=0; i<nInfoCount; i++) if ( pColStart[i] != rCmp.pColStart[i] || pColFormat[i] != rCmp.pColFormat[i] ) return false; return true; } return false; } // // Der Options-String darf kein Semikolon mehr enthalten (wegen Pickliste) // darum ab Version 336 Komma stattdessen // void ScAsciiOptions::ReadFromString( const String& rString ) { xub_StrLen nCount = comphelper::string::getTokenCount(rString, ','); String aToken; xub_StrLen nSub; xub_StrLen i; // // Feld-Trenner // if ( nCount >= 1 ) { bFixedLen = bMergeFieldSeps = false; aFieldSeps.Erase(); aToken = rString.GetToken(0,','); if ( aToken.EqualsAscii(pStrFix) ) bFixedLen = true; nSub = comphelper::string::getTokenCount(aToken, '/'); for ( i=0; i<nSub; i++ ) { String aCode = aToken.GetToken( i, '/' ); if ( aCode.EqualsAscii(pStrMrg) ) bMergeFieldSeps = true; else { sal_Int32 nVal = aCode.ToInt32(); if ( nVal ) aFieldSeps += (sal_Unicode) nVal; } } } // // Text-Trenner // if ( nCount >= 2 ) { aToken = rString.GetToken(1,','); sal_Int32 nVal = aToken.ToInt32(); cTextSep = (sal_Unicode) nVal; } // // Zeichensatz // if ( nCount >= 3 ) { aToken = rString.GetToken(2,','); eCharSet = ScGlobal::GetCharsetValue( aToken ); } // // Startzeile // if ( nCount >= 4 ) { aToken = rString.GetToken(3,','); nStartRow = aToken.ToInt32(); } // // Spalten-Infos // if ( nCount >= 5 ) { delete[] pColStart; delete[] pColFormat; aToken = rString.GetToken(4,','); nSub = comphelper::string::getTokenCount(aToken, '/'); nInfoCount = nSub / 2; if (nInfoCount) { pColStart = new sal_Int32[nInfoCount]; pColFormat = new sal_uInt8[nInfoCount]; for (sal_uInt16 nInfo=0; nInfo<nInfoCount; nInfo++) { pColStart[nInfo] = (sal_Int32) aToken.GetToken( 2*nInfo, '/' ).ToInt32(); pColFormat[nInfo] = (sal_uInt8) aToken.GetToken( 2*nInfo+1, '/' ).ToInt32(); } } else { pColStart = NULL; pColFormat = NULL; } } // Language if (nCount >= 6) { aToken = rString.GetToken(5, ','); eLang = static_cast<LanguageType>(aToken.ToInt32()); } // Import quoted field as text. if (nCount >= 7) { aToken = rString.GetToken(6, ','); bQuotedFieldAsText = aToken.EqualsAscii("true") ? true : false; } // Detect special numbers. if (nCount >= 8) { aToken = rString.GetToken(7, ','); bDetectSpecialNumber = aToken.EqualsAscii("true") ? true : false; } else bDetectSpecialNumber = true; // default of versions that didn't add the parameter // 9th token is used for "Save as shown" in export options // 10th token is used for "Save cell formulas" in export options } String ScAsciiOptions::WriteToString() const { OUString aOutStr; // // Feld-Trenner // if ( bFixedLen ) aOutStr += pStrFix; else if ( !aFieldSeps.Len() ) aOutStr += "0"; else { xub_StrLen nLen = aFieldSeps.Len(); for (xub_StrLen i=0; i<nLen; i++) { if (i) aOutStr += "/"; aOutStr += OUString::number(aFieldSeps.GetChar(i)); } if ( bMergeFieldSeps ) { aOutStr += "/"; aOutStr += pStrMrg; } } aOutStr += "," + // Text-Trenner OUString::number(cTextSep) + ","; // // Zeichensatz // if ( bCharSetSystem ) // force "SYSTEM" aOutStr += ScGlobal::GetCharsetString( RTL_TEXTENCODING_DONTKNOW ); else aOutStr += ScGlobal::GetCharsetString( eCharSet ); aOutStr += "," + // Startzeile OUString::number(nStartRow) + ","; // // Spalten-Infos // OSL_ENSURE( !nInfoCount || (pColStart && pColFormat), "0-Zeiger in ScAsciiOptions" ); for (sal_uInt16 nInfo=0; nInfo<nInfoCount; nInfo++) { if (nInfo) aOutStr += "/"; aOutStr += OUString::number(pColStart[nInfo]) + "/" + OUString::number(pColFormat[nInfo]); } // #i112025# the options string is used in macros and linked sheets, // so new options must be added at the end, to remain compatible aOutStr += "," + // Language OUString::number(eLang) + "," + // Import quoted field as text. OUString::boolean( bQuotedFieldAsText ) + "," + // Detect special numbers. OUString::boolean( bDetectSpecialNumber ); // 9th token is used for "Save as shown" in export options // 10th token is used for "Save cell formulas" in export options return aOutStr; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>translated comments<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "global.hxx" #include "scresid.hxx" #include "impex.hxx" #include "asciiopt.hxx" #include "asciiopt.hrc" #include <comphelper/string.hxx> #include <rtl/tencinfo.h> #include <unotools/transliterationwrapper.hxx> // ause #include "editutil.hxx" // ============================================================================ static const sal_Char pStrFix[] = "FIX"; static const sal_Char pStrMrg[] = "MRG"; // ============================================================================ ScAsciiOptions::ScAsciiOptions() : bFixedLen ( false ), aFieldSeps ( OUString(';') ), bMergeFieldSeps ( false ), bQuotedFieldAsText(false), bDetectSpecialNumber(false), cTextSep ( cDefaultTextSep ), eCharSet ( osl_getThreadTextEncoding() ), eLang ( LANGUAGE_SYSTEM ), bCharSetSystem ( false ), nStartRow ( 1 ), nInfoCount ( 0 ), pColStart ( NULL ), pColFormat ( NULL ) { } ScAsciiOptions::ScAsciiOptions(const ScAsciiOptions& rOpt) : bFixedLen ( rOpt.bFixedLen ), aFieldSeps ( rOpt.aFieldSeps ), bMergeFieldSeps ( rOpt.bMergeFieldSeps ), bQuotedFieldAsText(rOpt.bQuotedFieldAsText), bDetectSpecialNumber(rOpt.bDetectSpecialNumber), cTextSep ( rOpt.cTextSep ), eCharSet ( rOpt.eCharSet ), eLang ( rOpt.eLang ), bCharSetSystem ( rOpt.bCharSetSystem ), nStartRow ( rOpt.nStartRow ), nInfoCount ( rOpt.nInfoCount ) { if (nInfoCount) { pColStart = new sal_Int32[nInfoCount]; pColFormat = new sal_uInt8[nInfoCount]; for (sal_uInt16 i=0; i<nInfoCount; i++) { pColStart[i] = rOpt.pColStart[i]; pColFormat[i] = rOpt.pColFormat[i]; } } else { pColStart = NULL; pColFormat = NULL; } } ScAsciiOptions::~ScAsciiOptions() { delete[] pColStart; delete[] pColFormat; } void ScAsciiOptions::SetColInfo( sal_uInt16 nCount, const sal_Int32* pStart, const sal_uInt8* pFormat ) { delete[] pColStart; delete[] pColFormat; nInfoCount = nCount; if (nInfoCount) { pColStart = new sal_Int32[nInfoCount]; pColFormat = new sal_uInt8[nInfoCount]; for (sal_uInt16 i=0; i<nInfoCount; i++) { pColStart[i] = pStart[i]; pColFormat[i] = pFormat[i]; } } else { pColStart = NULL; pColFormat = NULL; } } void ScAsciiOptions::SetColumnInfo( const ScCsvExpDataVec& rDataVec ) { delete[] pColStart; pColStart = NULL; delete[] pColFormat; pColFormat = NULL; nInfoCount = static_cast< sal_uInt16 >( rDataVec.size() ); if( nInfoCount ) { pColStart = new sal_Int32[ nInfoCount ]; pColFormat = new sal_uInt8[ nInfoCount ]; for( sal_uInt16 nIx = 0; nIx < nInfoCount; ++nIx ) { pColStart[ nIx ] = rDataVec[ nIx ].mnIndex; pColFormat[ nIx ] = rDataVec[ nIx ].mnType; } } } ScAsciiOptions& ScAsciiOptions::operator=( const ScAsciiOptions& rCpy ) { SetColInfo( rCpy.nInfoCount, rCpy.pColStart, rCpy.pColFormat ); bFixedLen = rCpy.bFixedLen; aFieldSeps = rCpy.aFieldSeps; bMergeFieldSeps = rCpy.bMergeFieldSeps; bQuotedFieldAsText = rCpy.bQuotedFieldAsText; cTextSep = rCpy.cTextSep; eCharSet = rCpy.eCharSet; bCharSetSystem = rCpy.bCharSetSystem; nStartRow = rCpy.nStartRow; return *this; } bool ScAsciiOptions::operator==( const ScAsciiOptions& rCmp ) const { if ( bFixedLen == rCmp.bFixedLen && aFieldSeps == rCmp.aFieldSeps && bMergeFieldSeps == rCmp.bMergeFieldSeps && bQuotedFieldAsText == rCmp.bQuotedFieldAsText && cTextSep == rCmp.cTextSep && eCharSet == rCmp.eCharSet && bCharSetSystem == rCmp.bCharSetSystem && nStartRow == rCmp.nStartRow && nInfoCount == rCmp.nInfoCount ) { OSL_ENSURE( !nInfoCount || (pColStart && pColFormat && rCmp.pColStart && rCmp.pColFormat), "NULL pointer in ScAsciiOptions::operator==() column info" ); for (sal_uInt16 i=0; i<nInfoCount; i++) if ( pColStart[i] != rCmp.pColStart[i] || pColFormat[i] != rCmp.pColFormat[i] ) return false; return true; } return false; } // The options string must not contain semicolons (because of the pick list), // use comma as separator. void ScAsciiOptions::ReadFromString( const String& rString ) { xub_StrLen nCount = comphelper::string::getTokenCount(rString, ','); String aToken; xub_StrLen nSub; xub_StrLen i; // Field separator. if ( nCount >= 1 ) { bFixedLen = bMergeFieldSeps = false; aFieldSeps.Erase(); aToken = rString.GetToken(0,','); if ( aToken.EqualsAscii(pStrFix) ) bFixedLen = true; nSub = comphelper::string::getTokenCount(aToken, '/'); for ( i=0; i<nSub; i++ ) { String aCode = aToken.GetToken( i, '/' ); if ( aCode.EqualsAscii(pStrMrg) ) bMergeFieldSeps = true; else { sal_Int32 nVal = aCode.ToInt32(); if ( nVal ) aFieldSeps += (sal_Unicode) nVal; } } } // Text separator. if ( nCount >= 2 ) { aToken = rString.GetToken(1,','); sal_Int32 nVal = aToken.ToInt32(); cTextSep = (sal_Unicode) nVal; } // Text encoding. if ( nCount >= 3 ) { aToken = rString.GetToken(2,','); eCharSet = ScGlobal::GetCharsetValue( aToken ); } // Number of start row. if ( nCount >= 4 ) { aToken = rString.GetToken(3,','); nStartRow = aToken.ToInt32(); } // Column info. if ( nCount >= 5 ) { delete[] pColStart; delete[] pColFormat; aToken = rString.GetToken(4,','); nSub = comphelper::string::getTokenCount(aToken, '/'); nInfoCount = nSub / 2; if (nInfoCount) { pColStart = new sal_Int32[nInfoCount]; pColFormat = new sal_uInt8[nInfoCount]; for (sal_uInt16 nInfo=0; nInfo<nInfoCount; nInfo++) { pColStart[nInfo] = (sal_Int32) aToken.GetToken( 2*nInfo, '/' ).ToInt32(); pColFormat[nInfo] = (sal_uInt8) aToken.GetToken( 2*nInfo+1, '/' ).ToInt32(); } } else { pColStart = NULL; pColFormat = NULL; } } // Language if (nCount >= 6) { aToken = rString.GetToken(5, ','); eLang = static_cast<LanguageType>(aToken.ToInt32()); } // Import quoted field as text. if (nCount >= 7) { aToken = rString.GetToken(6, ','); bQuotedFieldAsText = aToken.EqualsAscii("true") ? true : false; } // Detect special numbers. if (nCount >= 8) { aToken = rString.GetToken(7, ','); bDetectSpecialNumber = aToken.EqualsAscii("true") ? true : false; } else bDetectSpecialNumber = true; // default of versions that didn't add the parameter // 9th token is used for "Save as shown" in export options // 10th token is used for "Save cell formulas" in export options } String ScAsciiOptions::WriteToString() const { OUString aOutStr; // Field separator. if ( bFixedLen ) aOutStr += pStrFix; else if ( !aFieldSeps.Len() ) aOutStr += "0"; else { xub_StrLen nLen = aFieldSeps.Len(); for (xub_StrLen i=0; i<nLen; i++) { if (i) aOutStr += "/"; aOutStr += OUString::number(aFieldSeps.GetChar(i)); } if ( bMergeFieldSeps ) { aOutStr += "/"; aOutStr += pStrMrg; } } // Text delimiter. aOutStr += "," + OUString::number(cTextSep) + ","; // Text encoding. if ( bCharSetSystem ) // force "SYSTEM" aOutStr += ScGlobal::GetCharsetString( RTL_TEXTENCODING_DONTKNOW ); else aOutStr += ScGlobal::GetCharsetString( eCharSet ); // Number of start row. aOutStr += "," + OUString::number(nStartRow) + ","; // Column info. OSL_ENSURE( !nInfoCount || (pColStart && pColFormat), "NULL pointer in ScAsciiOptions column info" ); for (sal_uInt16 nInfo=0; nInfo<nInfoCount; nInfo++) { if (nInfo) aOutStr += "/"; aOutStr += OUString::number(pColStart[nInfo]) + "/" + OUString::number(pColFormat[nInfo]); } // #i112025# the options string is used in macros and linked sheets, // so new options must be added at the end, to remain compatible aOutStr += "," + // Language OUString::number(eLang) + "," + // Import quoted field as text. OUString::boolean( bQuotedFieldAsText ) + "," + // Detect special numbers. OUString::boolean( bDetectSpecialNumber ); // 9th token is used for "Save as shown" in export options // 10th token is used for "Save cell formulas" in export options return aOutStr; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Time: O(n) // Space: O(h) /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: The root of binary tree. * @return: An integer */ int minDepth(TreeNode *root) { if (root == nullptr) { return 0; } // Both children exist. if (root->left != nullptr && root->right != nullptr) { return 1 + min(minDepth(root->left), minDepth(root->right)); } else { return 1 + max(minDepth(root->left), minDepth(root->right)); } } }; <commit_msg>Update minimum-depth-of-binary-tree.cpp<commit_after>// Time: O(n) // Space: O(n) /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: The root of binary tree. * @return: An integer */ int minDepth(TreeNode *root) { if (root == nullptr) { return 0; } // Both children exist. if (root->left != nullptr && root->right != nullptr) { return 1 + min(minDepth(root->left), minDepth(root->right)); } else { return 1 + max(minDepth(root->left), minDepth(root->right)); } } }; <|endoftext|>
<commit_before>/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ #include "ColladaRecursiveImporter.hpp" #include "../../internal/Exception.hpp" #include "../AiImporter/AiSceneImporter.hpp" namespace AssimpWorker { using ATLAS::Model::DataDeletingBlob; using ATLAS::Model::Folder; ColladaRecursiveImporter::ColladaRecursiveImporter(const Poco::URI& colladaFileURI, Log& log, Poco::URI pathToWorkingDirectory) : Importer(colladaFileURI.toString(), log), pathToWorkingDirectory(pathToWorkingDirectory), massager(colladaFileURI), colladaFileURI(colladaFileURI) { return; } ColladaRecursiveImporter::~ColladaRecursiveImporter(){ delete importer; } void ColladaRecursiveImporter::addElementsTo(ATLAS::Model::Folder& root){ massager.purgeNames(); importer = new AssimpWorker::AssimpImporter(); const aiScene* scene = importer->importSceneFromFile(colladaFileURI.getPath(), log); if (!scene) { return; } aiNode* startingPoint = scene->mRootNode; if (colladaFileURI.getFragment() != "") { aiNode* startingPoint = findaiNodeWithName(scene->mRootNode, colladaFileURI.getFragment()); if (startingPoint == NULL){ throw AMLException("Could not find a Node with id '" + colladaFileURI.getFragment() + "'"); } } restoreOriginalNames(startingPoint); AiSceneImporter sceneImporter(scene, pathToWorkingDirectory.getPath(), log); sceneImporter.importSubtreeOfScene(root, startingPoint); } void ColladaRecursiveImporter::restoreOriginalNames(aiNode* node) { node->mName = massager.getNameForId(node->mName.C_Str()); for (int i = 0; i < node->mNumChildren; i++){ restoreOriginalNames(node->mChildren[i]); } } aiNode* ColladaRecursiveImporter::findaiNodeWithName(aiNode* node, const std::string& name){ if (name == node->mName.C_Str()){ return node; } aiNode* childNode = NULL; for (int i = 0; i < node->mNumChildren; i++){ childNode = findaiNodeWithName(node->mChildren[i], name); if (childNode != NULL) { break; } } return childNode; } }<commit_msg>Do not purge the names if the reference does not have a fragment<commit_after>/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ #include <iostream> #include "ColladaRecursiveImporter.hpp" #include "../../internal/Exception.hpp" #include "../AiImporter/AiSceneImporter.hpp" namespace AssimpWorker { using ATLAS::Model::DataDeletingBlob; using ATLAS::Model::Folder; ColladaRecursiveImporter::ColladaRecursiveImporter(const Poco::URI& colladaFileURI, Log& log, Poco::URI pathToWorkingDirectory) : Importer(colladaFileURI.toString(), log), pathToWorkingDirectory(pathToWorkingDirectory), massager(colladaFileURI), colladaFileURI(colladaFileURI), importer(NULL) { return; } ColladaRecursiveImporter::~ColladaRecursiveImporter(){ delete importer; } void ColladaRecursiveImporter::addElementsTo(ATLAS::Model::Folder& root){ std::cout << "Importing: " << colladaFileURI.toString() << std::endl; bool needToPurge = colladaFileURI.getFragment() != ""; if (needToPurge) { massager.purgeNames(); } this->importer = new AssimpWorker::AssimpImporter(); const aiScene* scene = importer->importSceneFromFile(colladaFileURI.getPath(), log); if (!scene) { return; } if (needToPurge) { aiNode* startingPoint = findaiNodeWithName(scene->mRootNode, colladaFileURI.getFragment()); if (startingPoint == NULL){ throw AMLException("Could not find a Node with id '" + colladaFileURI.getFragment() + "'"); } restoreOriginalNames(startingPoint); AiSceneImporter sceneImporter(scene, pathToWorkingDirectory.getPath(), log); sceneImporter.importSubtreeOfScene(root, startingPoint); } else { AiSceneImporter sceneImporter(scene, pathToWorkingDirectory.getPath(), log); sceneImporter.addElementsTo(root); } } void ColladaRecursiveImporter::restoreOriginalNames(aiNode* node) { node->mName = massager.getNameForId(node->mName.C_Str()); for (int i = 0; i < node->mNumChildren; i++){ restoreOriginalNames(node->mChildren[i]); } } aiNode* ColladaRecursiveImporter::findaiNodeWithName(aiNode* node, const std::string& name){ if (name == node->mName.C_Str()){ return node; } aiNode* childNode = NULL; for (int i = 0; i < node->mNumChildren; i++){ childNode = findaiNodeWithName(node->mChildren[i], name); if (childNode != NULL) { break; } } return childNode; } }<|endoftext|>
<commit_before>/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group 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 (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, see <http://www.gnu.org/licenses/>. The full license is available in the file GPLv3. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ //$Id$ #include "FindWidget.h" #include "GUIObjects/GUIModelObject.h" #include "GUIObjects/GUIContainerObject.h" #include "ModelWidget.h" #include "GraphicsView.h" #include "Utilities/GUIUtilities.h" #include "Widgets/TextEditorWidget.h" #include "ModelHandler.h" #include "global.h" #include <QLineEdit> #include <QLabel> #include <QToolButton> #include <QPushButton> #include <QComboBox> #include <QHBoxLayout> #include <QVBoxLayout> FindWidget::FindWidget(QWidget *parent) : QWidget(parent) { mpFindLineEdit = new QLineEdit(this); mpReplaceLabel = new QLabel("Replace: ", this); mpReplaceLineEdit = new QLineEdit(this); mpFindWhatComboBox = new QComboBox(this); mpFindWhatComboBox->addItem("Component"); mpFindWhatComboBox->addItem("System Parameter"); mpFindWhatComboBox->addItem("Alias"); mpFindButton = new QPushButton("Find", this); mpFindButton->setShortcut(QKeySequence(Qt::Key_Enter)); mpPreviousButton = new QPushButton("Find Previous", this); mpPreviousButton->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Enter)); mpNextButton = new QPushButton("Find Next", this); mpNextButton->setShortcut(QKeySequence(Qt::Key_Enter)); mpReplaceButton = new QPushButton("Replace", this); mpReplaceAndFindButton = new QPushButton("Replace & Find", this); mpReplaceAllButton = new QPushButton("Replace All", this); QToolButton *pCloseButton = new QToolButton(this); mpCaseSensitivityCheckBox = new QCheckBox("Case Sensitive", this); mpWildcardCheckBox = new QCheckBox("Match Wildcards (*)", this); pCloseButton->setIcon(QIcon(":graphics/uiicons/svg/Hopsan-Discard.svg")); QGridLayout *pLayout = new QGridLayout(this); pLayout->addWidget(new QLabel("Find: ", this), 0, 0); pLayout->addWidget(mpFindLineEdit, 0, 1, 1, 2); pLayout->addWidget(mpFindWhatComboBox, 0, 3); pLayout->addWidget(mpFindButton, 0, 4); pLayout->addWidget(mpPreviousButton, 0, 3); pLayout->addWidget(mpNextButton, 0, 4); pLayout->addWidget(pCloseButton, 0, 5); pLayout->setColumnStretch(1,1); pLayout->addWidget(mpReplaceLabel, 1, 0); pLayout->addWidget(mpReplaceLineEdit, 1, 1); pLayout->addWidget(mpReplaceButton, 1, 2); pLayout->addWidget(mpReplaceAndFindButton, 1, 3); pLayout->addWidget(mpReplaceAllButton, 1, 4); pLayout->addWidget(mpCaseSensitivityCheckBox, 2, 0); pLayout->addWidget(mpWildcardCheckBox, 2, 1); connect(mpFindButton, SIGNAL(clicked()), this, SLOT(findInContainer())); connect(mpPreviousButton, SIGNAL(clicked()), this, SLOT(findPrevious())); connect(mpNextButton, SIGNAL(clicked()), this, SLOT(findNext())); connect(pCloseButton, SIGNAL(clicked()), this, SLOT(close())); connect(mpReplaceButton, SIGNAL(clicked()), this, SLOT(replace())); connect(mpReplaceAndFindButton, SIGNAL(clicked()), this, SLOT(replaceAndFind())); connect(mpReplaceAllButton, SIGNAL(clicked()), this, SLOT(replaceAll())); connect(mpFindLineEdit, SIGNAL(returnPressed()), this, SLOT(findNext())); resize(600, height()); setWindowTitle("Find Widget"); } void FindWidget::setContainer(SystemObject *pContainer) { mpContainer = pContainer; mpTextEditor = nullptr; mpFindWhatComboBox->setVisible(true); mpWildcardCheckBox->setVisible(true); mpPreviousButton->setVisible(false); mpNextButton->setVisible(false); mpFindButton->setVisible(true); mpReplaceLabel->setVisible(false); mpReplaceLineEdit->setVisible(false); mpReplaceButton->setVisible(false); mpReplaceAndFindButton->setVisible(false); mpReplaceAllButton->setVisible(false); } void FindWidget::setTextEditor(TextEditorWidget *pEditor) { mpTextEditor = pEditor; mpContainer = nullptr; mpFindWhatComboBox->setVisible(false); mpWildcardCheckBox->setVisible(false); mpPreviousButton->setVisible(true); mpNextButton->setVisible(true); mpFindButton->setVisible(false); mpReplaceLabel->setVisible(true); mpReplaceLineEdit->setVisible(true); mpReplaceButton->setVisible(true); mpReplaceAndFindButton->setVisible(true); mpReplaceAllButton->setVisible(true); } void FindWidget::findPrevious() { QTextDocument::FindFlags flags; flags |= QTextDocument::FindBackward; if(mpCaseSensitivityCheckBox->isChecked()) { flags |= QTextDocument::FindCaseSensitively; } mpTextEditor->find(mpFindLineEdit->text(), flags); } void FindWidget::findNext() { QTextDocument::FindFlags flags; if(mpCaseSensitivityCheckBox->isChecked()) { flags |= QTextDocument::FindCaseSensitively; } mpTextEditor->find(mpFindLineEdit->text(), flags); } void FindWidget::findInContainer() { Qt::CaseSensitivity caseSensitivity = Qt::CaseInsensitive; if(mpCaseSensitivityCheckBox->isChecked()) caseSensitivity = Qt::CaseSensitive; bool wildcard = mpWildcardCheckBox->isChecked(); switch(mpFindWhatComboBox->currentIndex()) { case 0: //Component findComponent(mpFindLineEdit->text(), true, caseSensitivity, wildcard); break; case 1: //System Parameter findSystemParameter(mpFindLineEdit->text(), true, caseSensitivity, wildcard); break; case 2: //Alias findAlias(mpFindLineEdit->text(), true, caseSensitivity, wildcard); break; } } void FindWidget::findComponent(const QString &rName, const bool centerView, Qt::CaseSensitivity caseSensitivity, bool wildcard) { if (mpContainer) { clearHighlights(); QPointF mean; int nFound=0; QStringList compNames = mpContainer->getModelObjectNames(); //! @todo what about searching in subsystems for(QString comp : compNames) { bool match; if(wildcard) { QRegExp re(rName, caseSensitivity, QRegExp::Wildcard); match = re.exactMatch(comp); } else { match = comp.contains(rName, caseSensitivity); } if (match) { ModelObject *pMO = mpContainer->getModelObject(comp); if (pMO) { ++nFound; pMO->highlight(); mean += pMO->pos(); } } } // Now center view over found model objects if (nFound > 0 && centerView) { mean /= double(nFound); mpContainer->mpModelWidget->getGraphicsView()->centerOn(mean); } } } void FindWidget::findAlias(const QString &rName, const bool centerView, Qt::CaseSensitivity caseSensitivity, bool wildcard) { if (mpContainer) { clearHighlights(); QPointF mean; int nFound=0; QStringList aliasNames = mpContainer->getAliasNames(); //! @todo what about searching in subsystems for(QString alias : aliasNames) { bool match; if(wildcard) { QRegExp re(rName, caseSensitivity, QRegExp::Wildcard); match = re.exactMatch(alias); } else { match = alias.contains(rName, caseSensitivity); } if (match) { QString fullName = mpContainer->getFullNameFromAlias(alias); QString comp, port, var; QStringList sysHierarchy; splitFullVariableName(fullName, sysHierarchy, comp, port, var); ModelObject *pMO = mpContainer->getModelObject(comp); //! @todo we should actually highlight the port also (and center on the port) if (pMO) { ++nFound; pMO->highlight(); mean += pMO->pos(); } } } // Now center view over found model objects if (nFound > 0 && centerView) { mean /= double(nFound); mpContainer->mpModelWidget->getGraphicsView()->centerOn(mean); } } } void FindWidget::findSystemParameter(const QString &rName, const bool centerView, Qt::CaseSensitivity caseSensitivity, bool wildcard) { QStringList sl {rName}; findSystemParameter(sl, centerView, caseSensitivity, wildcard); } void FindWidget::findSystemParameter(const QStringList &rNames, const bool centerView, Qt::CaseSensitivity caseSensitivity, bool wildcard) { if (mpContainer) { clearHighlights(); QList<QRegExp> res; for (auto &name : rNames) { res.append(QRegExp(name, caseSensitivity, QRegExp::Wildcard)); } QPointF mean; int nFound=0; const QList<ModelObject*> mops = mpContainer->getModelObjects(); for(ModelObject* pMO : mops) { bool hasPar = false; QVector<CoreParameterData> pars; pMO->getParameters(pars); for(CoreParameterData par : pars) { QString expression = removeAllSpaces(par.mValue); // OK, I cant figure out how to write the regexp to solve this, so I am splitting the string instead QStringList parts; splitOnAny(expression,{"+","-","*","/","(",")","^"}, parts); for (QString &part : parts) { if(wildcard) { for (auto &re : res) { if (re.exactMatch(part)) { hasPar = true; break; } } } else { for (auto &name : rNames) { if(part.contains(name, caseSensitivity)) { hasPar = true; break; } } } if (hasPar) { break; } } } if(hasPar) { pMO->highlight(); ++nFound; mean += pMO->pos(); } } if (nFound > 0 && centerView) { mean /= double(nFound); mpContainer->mpModelWidget->getGraphicsView()->centerOn(mean); } } } void FindWidget::findAny(const QString &rName) { //Not yet implemented } void FindWidget::replace() { if(mpTextEditor->getSelectedText() == mpFindLineEdit->text()) { mpTextEditor->replaceSelectedText(mpReplaceLineEdit->text()); } } void FindWidget::replaceAndFind() { if(mpTextEditor->getSelectedText() == mpFindLineEdit->text()) { mpTextEditor->replaceSelectedText(mpReplaceLineEdit->text()); } QTextDocument::FindFlags flags; if(mpCaseSensitivityCheckBox->isChecked()) { flags |= QTextDocument::FindCaseSensitively; } mpTextEditor->find(mpFindLineEdit->text(), flags); } void FindWidget::replaceAll() { //Search backward findPrevious(); while(mpTextEditor->getSelectedText() == mpFindLineEdit->text()) { mpTextEditor->replaceSelectedText(mpReplaceLineEdit->text()); findPrevious(); } //Search forward findNext(); while(mpTextEditor->getSelectedText() == mpFindLineEdit->text()) { mpTextEditor->replaceSelectedText(mpReplaceLineEdit->text()); findNext(); } } void FindWidget::setVisible(bool visible) { //If text is selected in current editor, update it in find widget if(mpTextEditor) { QString selection = mpTextEditor->getSelectedText(); if(!selection.contains("\u2029") && mpFindLineEdit->text() != selection && !selection.isEmpty()) { mpFindLineEdit->setText(selection); visible = true; } } QWidget::setVisible(visible); if(visible) { this->mpFindLineEdit->setFocus(); this->mpFindLineEdit->selectAll(); } } void FindWidget::keyPressEvent(QKeyEvent* event) { if(event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { this->findInContainer(); } QWidget::keyPressEvent(event); } void FindWidget::clearHighlights() { mpContainer->mpModelWidget->getGraphicsView()->clearHighlights(); } <commit_msg>Only close find widget when it has focus, otherwise give it focus<commit_after>/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group 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 (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, see <http://www.gnu.org/licenses/>. The full license is available in the file GPLv3. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ //$Id$ #include "FindWidget.h" #include "GUIObjects/GUIModelObject.h" #include "GUIObjects/GUIContainerObject.h" #include "ModelWidget.h" #include "GraphicsView.h" #include "Utilities/GUIUtilities.h" #include "Widgets/TextEditorWidget.h" #include "ModelHandler.h" #include "global.h" #include <QLineEdit> #include <QLabel> #include <QToolButton> #include <QPushButton> #include <QComboBox> #include <QHBoxLayout> #include <QVBoxLayout> FindWidget::FindWidget(QWidget *parent) : QWidget(parent) { mpFindLineEdit = new QLineEdit(this); mpReplaceLabel = new QLabel("Replace: ", this); mpReplaceLineEdit = new QLineEdit(this); mpFindWhatComboBox = new QComboBox(this); mpFindWhatComboBox->addItem("Component"); mpFindWhatComboBox->addItem("System Parameter"); mpFindWhatComboBox->addItem("Alias"); mpFindButton = new QPushButton("Find", this); mpFindButton->setShortcut(QKeySequence(Qt::Key_Enter)); mpPreviousButton = new QPushButton("Find Previous", this); mpPreviousButton->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Enter)); mpNextButton = new QPushButton("Find Next", this); mpNextButton->setShortcut(QKeySequence(Qt::Key_Enter)); mpReplaceButton = new QPushButton("Replace", this); mpReplaceAndFindButton = new QPushButton("Replace & Find", this); mpReplaceAllButton = new QPushButton("Replace All", this); QToolButton *pCloseButton = new QToolButton(this); mpCaseSensitivityCheckBox = new QCheckBox("Case Sensitive", this); mpWildcardCheckBox = new QCheckBox("Match Wildcards (*)", this); pCloseButton->setIcon(QIcon(":graphics/uiicons/svg/Hopsan-Discard.svg")); QGridLayout *pLayout = new QGridLayout(this); pLayout->addWidget(new QLabel("Find: ", this), 0, 0); pLayout->addWidget(mpFindLineEdit, 0, 1, 1, 2); pLayout->addWidget(mpFindWhatComboBox, 0, 3); pLayout->addWidget(mpFindButton, 0, 4); pLayout->addWidget(mpPreviousButton, 0, 3); pLayout->addWidget(mpNextButton, 0, 4); pLayout->addWidget(pCloseButton, 0, 5); pLayout->setColumnStretch(1,1); pLayout->addWidget(mpReplaceLabel, 1, 0); pLayout->addWidget(mpReplaceLineEdit, 1, 1); pLayout->addWidget(mpReplaceButton, 1, 2); pLayout->addWidget(mpReplaceAndFindButton, 1, 3); pLayout->addWidget(mpReplaceAllButton, 1, 4); pLayout->addWidget(mpCaseSensitivityCheckBox, 2, 0); pLayout->addWidget(mpWildcardCheckBox, 2, 1); connect(mpFindButton, SIGNAL(clicked()), this, SLOT(findInContainer())); connect(mpPreviousButton, SIGNAL(clicked()), this, SLOT(findPrevious())); connect(mpNextButton, SIGNAL(clicked()), this, SLOT(findNext())); connect(pCloseButton, SIGNAL(clicked()), this, SLOT(close())); connect(mpReplaceButton, SIGNAL(clicked()), this, SLOT(replace())); connect(mpReplaceAndFindButton, SIGNAL(clicked()), this, SLOT(replaceAndFind())); connect(mpReplaceAllButton, SIGNAL(clicked()), this, SLOT(replaceAll())); connect(mpFindLineEdit, SIGNAL(returnPressed()), this, SLOT(findNext())); resize(600, height()); setWindowTitle("Find Widget"); } void FindWidget::setContainer(SystemObject *pContainer) { mpContainer = pContainer; mpTextEditor = nullptr; mpFindWhatComboBox->setVisible(true); mpWildcardCheckBox->setVisible(true); mpPreviousButton->setVisible(false); mpNextButton->setVisible(false); mpFindButton->setVisible(true); mpReplaceLabel->setVisible(false); mpReplaceLineEdit->setVisible(false); mpReplaceButton->setVisible(false); mpReplaceAndFindButton->setVisible(false); mpReplaceAllButton->setVisible(false); } void FindWidget::setTextEditor(TextEditorWidget *pEditor) { mpTextEditor = pEditor; mpContainer = nullptr; mpFindWhatComboBox->setVisible(false); mpWildcardCheckBox->setVisible(false); mpPreviousButton->setVisible(true); mpNextButton->setVisible(true); mpFindButton->setVisible(false); mpReplaceLabel->setVisible(true); mpReplaceLineEdit->setVisible(true); mpReplaceButton->setVisible(true); mpReplaceAndFindButton->setVisible(true); mpReplaceAllButton->setVisible(true); } void FindWidget::findPrevious() { QTextDocument::FindFlags flags; flags |= QTextDocument::FindBackward; if(mpCaseSensitivityCheckBox->isChecked()) { flags |= QTextDocument::FindCaseSensitively; } mpTextEditor->find(mpFindLineEdit->text(), flags); } void FindWidget::findNext() { QTextDocument::FindFlags flags; if(mpCaseSensitivityCheckBox->isChecked()) { flags |= QTextDocument::FindCaseSensitively; } mpTextEditor->find(mpFindLineEdit->text(), flags); } void FindWidget::findInContainer() { Qt::CaseSensitivity caseSensitivity = Qt::CaseInsensitive; if(mpCaseSensitivityCheckBox->isChecked()) caseSensitivity = Qt::CaseSensitive; bool wildcard = mpWildcardCheckBox->isChecked(); switch(mpFindWhatComboBox->currentIndex()) { case 0: //Component findComponent(mpFindLineEdit->text(), true, caseSensitivity, wildcard); break; case 1: //System Parameter findSystemParameter(mpFindLineEdit->text(), true, caseSensitivity, wildcard); break; case 2: //Alias findAlias(mpFindLineEdit->text(), true, caseSensitivity, wildcard); break; } } void FindWidget::findComponent(const QString &rName, const bool centerView, Qt::CaseSensitivity caseSensitivity, bool wildcard) { if (mpContainer) { clearHighlights(); QPointF mean; int nFound=0; QStringList compNames = mpContainer->getModelObjectNames(); //! @todo what about searching in subsystems for(QString comp : compNames) { bool match; if(wildcard) { QRegExp re(rName, caseSensitivity, QRegExp::Wildcard); match = re.exactMatch(comp); } else { match = comp.contains(rName, caseSensitivity); } if (match) { ModelObject *pMO = mpContainer->getModelObject(comp); if (pMO) { ++nFound; pMO->highlight(); mean += pMO->pos(); } } } // Now center view over found model objects if (nFound > 0 && centerView) { mean /= double(nFound); mpContainer->mpModelWidget->getGraphicsView()->centerOn(mean); } } } void FindWidget::findAlias(const QString &rName, const bool centerView, Qt::CaseSensitivity caseSensitivity, bool wildcard) { if (mpContainer) { clearHighlights(); QPointF mean; int nFound=0; QStringList aliasNames = mpContainer->getAliasNames(); //! @todo what about searching in subsystems for(QString alias : aliasNames) { bool match; if(wildcard) { QRegExp re(rName, caseSensitivity, QRegExp::Wildcard); match = re.exactMatch(alias); } else { match = alias.contains(rName, caseSensitivity); } if (match) { QString fullName = mpContainer->getFullNameFromAlias(alias); QString comp, port, var; QStringList sysHierarchy; splitFullVariableName(fullName, sysHierarchy, comp, port, var); ModelObject *pMO = mpContainer->getModelObject(comp); //! @todo we should actually highlight the port also (and center on the port) if (pMO) { ++nFound; pMO->highlight(); mean += pMO->pos(); } } } // Now center view over found model objects if (nFound > 0 && centerView) { mean /= double(nFound); mpContainer->mpModelWidget->getGraphicsView()->centerOn(mean); } } } void FindWidget::findSystemParameter(const QString &rName, const bool centerView, Qt::CaseSensitivity caseSensitivity, bool wildcard) { QStringList sl {rName}; findSystemParameter(sl, centerView, caseSensitivity, wildcard); } void FindWidget::findSystemParameter(const QStringList &rNames, const bool centerView, Qt::CaseSensitivity caseSensitivity, bool wildcard) { if (mpContainer) { clearHighlights(); QList<QRegExp> res; for (auto &name : rNames) { res.append(QRegExp(name, caseSensitivity, QRegExp::Wildcard)); } QPointF mean; int nFound=0; const QList<ModelObject*> mops = mpContainer->getModelObjects(); for(ModelObject* pMO : mops) { bool hasPar = false; QVector<CoreParameterData> pars; pMO->getParameters(pars); for(CoreParameterData par : pars) { QString expression = removeAllSpaces(par.mValue); // OK, I cant figure out how to write the regexp to solve this, so I am splitting the string instead QStringList parts; splitOnAny(expression,{"+","-","*","/","(",")","^"}, parts); for (QString &part : parts) { if(wildcard) { for (auto &re : res) { if (re.exactMatch(part)) { hasPar = true; break; } } } else { for (auto &name : rNames) { if(part.contains(name, caseSensitivity)) { hasPar = true; break; } } } if (hasPar) { break; } } } if(hasPar) { pMO->highlight(); ++nFound; mean += pMO->pos(); } } if (nFound > 0 && centerView) { mean /= double(nFound); mpContainer->mpModelWidget->getGraphicsView()->centerOn(mean); } } } void FindWidget::findAny(const QString &rName) { //Not yet implemented } void FindWidget::replace() { if(mpTextEditor->getSelectedText() == mpFindLineEdit->text()) { mpTextEditor->replaceSelectedText(mpReplaceLineEdit->text()); } } void FindWidget::replaceAndFind() { if(mpTextEditor->getSelectedText() == mpFindLineEdit->text()) { mpTextEditor->replaceSelectedText(mpReplaceLineEdit->text()); } QTextDocument::FindFlags flags; if(mpCaseSensitivityCheckBox->isChecked()) { flags |= QTextDocument::FindCaseSensitively; } mpTextEditor->find(mpFindLineEdit->text(), flags); } void FindWidget::replaceAll() { //Search backward findPrevious(); while(mpTextEditor->getSelectedText() == mpFindLineEdit->text()) { mpTextEditor->replaceSelectedText(mpReplaceLineEdit->text()); findPrevious(); } //Search forward findNext(); while(mpTextEditor->getSelectedText() == mpFindLineEdit->text()) { mpTextEditor->replaceSelectedText(mpReplaceLineEdit->text()); findNext(); } } void FindWidget::setVisible(bool visible) { if(mpTextEditor) { //If text is selected in current editor, update it in find widget QString selection = mpTextEditor->getSelectedText(); if(!selection.contains("\u2029") && mpFindLineEdit->text() != selection && !selection.isEmpty()) { mpFindLineEdit->setText(selection); visible = true; } //If find widget does not have focus, give it focus instead of hiding it if(gpMainWindowWidget->focusWidget() != mpFindLineEdit) { visible = true; } } QWidget::setVisible(visible); if(visible) { this->mpFindLineEdit->setFocus(); this->mpFindLineEdit->selectAll(); } } void FindWidget::keyPressEvent(QKeyEvent* event) { if(event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { this->findInContainer(); } QWidget::keyPressEvent(event); } void FindWidget::clearHighlights() { mpContainer->mpModelWidget->getGraphicsView()->clearHighlights(); } <|endoftext|>
<commit_before>// tests.hpp // Copyright (C) 2007 by Nathan Reed. All rights and priveleges reserved. // A set of tests of different types' communication with Lua #include <cstdio> #include <iostream> #include <iomanip> #include <lua.hpp> #include <string> #include <vector> #include "../include/luabridge.hpp" using namespace std; int traceback (lua_State *L); void register_lua_funcs (lua_State *L); int main (int argc, char **argv) { // Create the Lua state lua_State *L = luaL_newstate(); // Provide the base libraries luaopen_base(L); luaopen_table(L); luaopen_string(L); luaopen_math(L); luaopen_debug(L); // Provide user libraries register_lua_funcs(L); // Put the traceback function on the stack lua_pushcfunction(L, &traceback); int errfunc_index = lua_gettop(L); // Execute lua files in order if (luaL_loadfile(L, "src/test.lua") != 0) { // compile-time error cerr << lua_tostring(L, -1) << endl; lua_close(L); return 1; } else if (lua_pcall(L, 0, 0, errfunc_index) != 0) { // runtime error cerr << lua_tostring(L, -1) << endl; lua_close(L); return 1; } lua_close(L); return 0; } // traceback function, adapted from lua.c // when a runtime error occurs, this will append the call stack to the error message int traceback (lua_State *L) { // look up Lua's 'debug.traceback' function lua_getglobal(L, "debug"); if (!lua_istable(L, -1)) { lua_pop(L, 1); return 1; } lua_getfield(L, -1, "traceback"); if (!lua_isfunction(L, -1)) { lua_pop(L, 2); return 1; } lua_pushvalue(L, 1); /* pass error message */ lua_pushinteger(L, 2); /* skip this function and traceback */ lua_call(L, 2, 1); /* call debug.traceback */ return 1; } /* * Test classes */ bool g_success = true; bool testSucceeded () { bool b = g_success; g_success = false; return b; } typedef int fn_type; enum { FN_CTOR, FN_DTOR, FN_STATIC, FN_VIRTUAL, FN_PROPGET, FN_PROPSET, FN_STATIC_PROPGET, FN_STATIC_PROPSET, NUM_FN_TYPES }; struct fn_called { bool called[NUM_FN_TYPES]; fn_called () { memset(called, 0, NUM_FN_TYPES * sizeof(bool)); } }; fn_called A_functions, B_functions; bool testAFnCalled (fn_type f) { bool b = A_functions.called[f]; A_functions.called[f] = false; return b; } bool testBFnCalled (fn_type f) { bool b = B_functions.called[f]; B_functions.called[f] = false; return b; } class A { protected: string name; mutable bool success; public: A (const string &name_): name(name_), success(false), testProp(47) { A_functions.called[FN_CTOR] = true; } virtual ~A () { A_functions.called[FN_DTOR] = true; } virtual void testVirtual () { A_functions.called[FN_VIRTUAL] = true; } const char * getName () const { return name.c_str(); } void setSuccess () const { success = true; } bool testSucceeded () const { bool b = success; success = false; return b; } static void testStatic () { A_functions.called[FN_STATIC] = true; } int testProp; int testPropGet () const { A_functions.called[FN_PROPGET] = true; return testProp; } void testPropSet (int x) { A_functions.called[FN_PROPSET] = true; testProp = x; } static int testStaticProp; static int testStaticPropGet () { A_functions.called[FN_STATIC_PROPGET] = true; return testStaticProp; } static void testStaticPropSet (int x) { A_functions.called[FN_STATIC_PROPSET] = true; testStaticProp = x; } }; int A::testStaticProp = 47; class B: public A { public: B (const string &name_): A(name_) { B_functions.called[FN_CTOR] = true; } virtual ~B () { B_functions.called[FN_DTOR] = true; } virtual void testVirtual () { B_functions.called[FN_VIRTUAL] = true; } static void testStatic2 () { B_functions.called[FN_STATIC] = true; } }; /* * Test functions */ int testRetInt () { return 47; } float testRetFloat () { return 47.0f; } const char * testRetConstCharPtr () { return "Hello, world"; } string testRetStdString () { static string ret("Hello, world"); return ret; } void testParamInt (int a) { g_success = (a == 47); } void testParamBool (bool b) { g_success = b; } void testParamFloat (float f) { g_success = (f == 47.0f); } void testParamConstCharPtr (const char *str) { g_success = !strcmp(str, "Hello, world"); } void testParamStdString (string str) { g_success = !strcmp(str.c_str(), "Hello, world"); } void testParamStdStringRef (const string &str) { g_success = !strcmp(str.c_str(), "Hello, world"); } void testParamAPtr (A * a) { a->setSuccess(); } void testParamAPtrConst (A * const a) { a->setSuccess(); } void testParamConstAPtr (const A * a) { a->setSuccess(); } void testParamSharedPtrA (luabridge::shared_ptr<A> a) { a->setSuccess(); } luabridge::shared_ptr<A> testRetSharedPtrA () { static luabridge::shared_ptr<A> sp_A(new A("from C")); return sp_A; } luabridge::shared_ptr<const A> testRetSharedPtrConstA () { static luabridge::shared_ptr<A> sp_A(new A("const A")); return sp_A; } // add our own functions and classes to a Lua environment void register_lua_funcs (lua_State *L) { luabridge::module m(L); m .function("testSucceeded", &testSucceeded) .function("testAFnCalled", &testAFnCalled) .function("testBFnCalled", &testBFnCalled) .function("testRetInt", &testRetInt) .function("testRetFloat", &testRetFloat) .function("testRetConstCharPtr", &testRetConstCharPtr) .function("testRetStdString", &testRetStdString) .function("testParamInt", &testParamInt) .function("testParamBool", &testParamBool) .function("testParamFloat", &testParamFloat) .function("testParamConstCharPtr", &testParamConstCharPtr) .function("testParamStdString", &testParamStdString) .function("testParamStdStringRef", &testParamStdStringRef); m.class_<A>("A") .constructor<void (*) (const string &)>() .method("testVirtual", &A::testVirtual) .method("getName", &A::getName) .method("testSucceeded", &A::testSucceeded) .property_rw("testProp", &A::testProp) .property_rw("testProp2", &A::testPropGet, &A::testPropSet) .static_method("testStatic", &A::testStatic) .static_property_rw("testStaticProp", &A::testStaticProp) .static_property_rw("testStaticProp2", &A::testStaticPropGet, &A::testStaticPropSet); m.subclass<B, A>("B") .constructor<void (*) (const string &)>() .static_method("testStatic2", &B::testStatic2); m .function("testParamAPtr", &testParamAPtr) .function("testParamAPtrConst", &testParamAPtrConst) .function("testParamConstAPtr", &testParamConstAPtr) .function("testParamSharedPtrA", &testParamSharedPtrA) .function("testRetSharedPtrA", &testRetSharedPtrA) .function("testRetSharedPtrConstA", &testRetSharedPtrConstA); } <commit_msg>Further changes to make g++ happy<commit_after>// tests.hpp // Copyright (C) 2007 by Nathan Reed. All rights and priveleges reserved. // A set of tests of different types' communication with Lua #include <cstdio> #include <iostream> #include <iomanip> #include <lua.hpp> #include <string> #include <vector> #include "../include/luabridge.hpp" using namespace std; int traceback (lua_State *L); void register_lua_funcs (lua_State *L); int main (int argc, char **argv) { (void)argc; (void)argv; // Create the Lua state lua_State *L = luaL_newstate(); // Provide the base libraries luaopen_base(L); luaopen_table(L); luaopen_string(L); luaopen_math(L); luaopen_debug(L); // Provide user libraries register_lua_funcs(L); // Put the traceback function on the stack lua_pushcfunction(L, &traceback); int errfunc_index = lua_gettop(L); // Execute lua files in order if (luaL_loadfile(L, "src/test.lua") != 0) { // compile-time error cerr << lua_tostring(L, -1) << endl; lua_close(L); return 1; } else if (lua_pcall(L, 0, 0, errfunc_index) != 0) { // runtime error cerr << lua_tostring(L, -1) << endl; lua_close(L); return 1; } lua_close(L); return 0; } // traceback function, adapted from lua.c // when a runtime error occurs, this will append the call stack to the error message int traceback (lua_State *L) { // look up Lua's 'debug.traceback' function lua_getglobal(L, "debug"); if (!lua_istable(L, -1)) { lua_pop(L, 1); return 1; } lua_getfield(L, -1, "traceback"); if (!lua_isfunction(L, -1)) { lua_pop(L, 2); return 1; } lua_pushvalue(L, 1); /* pass error message */ lua_pushinteger(L, 2); /* skip this function and traceback */ lua_call(L, 2, 1); /* call debug.traceback */ return 1; } /* * Test classes */ bool g_success = true; bool testSucceeded () { bool b = g_success; g_success = false; return b; } typedef int fn_type; enum { FN_CTOR, FN_DTOR, FN_STATIC, FN_VIRTUAL, FN_PROPGET, FN_PROPSET, FN_STATIC_PROPGET, FN_STATIC_PROPSET, NUM_FN_TYPES }; struct fn_called { bool called[NUM_FN_TYPES]; fn_called () { memset(called, 0, NUM_FN_TYPES * sizeof(bool)); } }; fn_called A_functions, B_functions; bool testAFnCalled (fn_type f) { bool b = A_functions.called[f]; A_functions.called[f] = false; return b; } bool testBFnCalled (fn_type f) { bool b = B_functions.called[f]; B_functions.called[f] = false; return b; } class A { protected: string name; mutable bool success; public: A (const string &name_): name(name_), success(false), testProp(47) { A_functions.called[FN_CTOR] = true; } virtual ~A () { A_functions.called[FN_DTOR] = true; } virtual void testVirtual () { A_functions.called[FN_VIRTUAL] = true; } const char * getName () const { return name.c_str(); } void setSuccess () const { success = true; } bool testSucceeded () const { bool b = success; success = false; return b; } static void testStatic () { A_functions.called[FN_STATIC] = true; } int testProp; int testPropGet () const { A_functions.called[FN_PROPGET] = true; return testProp; } void testPropSet (int x) { A_functions.called[FN_PROPSET] = true; testProp = x; } static int testStaticProp; static int testStaticPropGet () { A_functions.called[FN_STATIC_PROPGET] = true; return testStaticProp; } static void testStaticPropSet (int x) { A_functions.called[FN_STATIC_PROPSET] = true; testStaticProp = x; } }; int A::testStaticProp = 47; class B: public A { public: B (const string &name_): A(name_) { B_functions.called[FN_CTOR] = true; } virtual ~B () { B_functions.called[FN_DTOR] = true; } virtual void testVirtual () { B_functions.called[FN_VIRTUAL] = true; } static void testStatic2 () { B_functions.called[FN_STATIC] = true; } }; /* * Test functions */ int testRetInt () { return 47; } float testRetFloat () { return 47.0f; } const char * testRetConstCharPtr () { return "Hello, world"; } string testRetStdString () { static string ret("Hello, world"); return ret; } void testParamInt (int a) { g_success = (a == 47); } void testParamBool (bool b) { g_success = b; } void testParamFloat (float f) { g_success = (f == 47.0f); } void testParamConstCharPtr (const char *str) { g_success = !strcmp(str, "Hello, world"); } void testParamStdString (string str) { g_success = !strcmp(str.c_str(), "Hello, world"); } void testParamStdStringRef (const string &str) { g_success = !strcmp(str.c_str(), "Hello, world"); } void testParamAPtr (A * a) { a->setSuccess(); } void testParamAPtrConst (A * const a) { a->setSuccess(); } void testParamConstAPtr (const A * a) { a->setSuccess(); } void testParamSharedPtrA (luabridge::shared_ptr<A> a) { a->setSuccess(); } luabridge::shared_ptr<A> testRetSharedPtrA () { static luabridge::shared_ptr<A> sp_A(new A("from C")); return sp_A; } luabridge::shared_ptr<const A> testRetSharedPtrConstA () { static luabridge::shared_ptr<A> sp_A(new A("const A")); return sp_A; } // add our own functions and classes to a Lua environment void register_lua_funcs (lua_State *L) { luabridge::module m(L); m .function("testSucceeded", &testSucceeded) .function("testAFnCalled", &testAFnCalled) .function("testBFnCalled", &testBFnCalled) .function("testRetInt", &testRetInt) .function("testRetFloat", &testRetFloat) .function("testRetConstCharPtr", &testRetConstCharPtr) .function("testRetStdString", &testRetStdString) .function("testParamInt", &testParamInt) .function("testParamBool", &testParamBool) .function("testParamFloat", &testParamFloat) .function("testParamConstCharPtr", &testParamConstCharPtr) .function("testParamStdString", &testParamStdString) .function("testParamStdStringRef", &testParamStdStringRef); m.class_<A>("A") .constructor<void (*) (const string &)>() .method("testVirtual", &A::testVirtual) .method("getName", &A::getName) .method("testSucceeded", &A::testSucceeded) .property_rw("testProp", &A::testProp) .property_rw("testProp2", &A::testPropGet, &A::testPropSet) .static_method("testStatic", &A::testStatic) .static_property_rw("testStaticProp", &A::testStaticProp) .static_property_rw("testStaticProp2", &A::testStaticPropGet, &A::testStaticPropSet); m.subclass<B, A>("B") .constructor<void (*) (const string &)>() .static_method("testStatic2", &B::testStatic2); m .function("testParamAPtr", &testParamAPtr) .function("testParamAPtrConst", &testParamAPtrConst) .function("testParamConstAPtr", &testParamConstAPtr) .function("testParamSharedPtrA", &testParamSharedPtrA) .function("testRetSharedPtrA", &testRetSharedPtrA) .function("testRetSharedPtrConstA", &testRetSharedPtrConstA); } <|endoftext|>
<commit_before><commit_msg>Fix build: remove DCHECK on TestTaskRunner<commit_after><|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2014, Balazs Racz * 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. * * \file SimpleLog.hxx * * A very simple logging mechanism of driver events that is capable of logging * a few entries of an 8-byte enum value, in a gdb-friendly way. * * @author Balazs Racz * @date 14 September 2014 */ #ifndef _FREERTOS_DRIVERS_COMMON_SIMPLELOG_HXX_ #define _FREERTOS_DRIVERS_COMMON_SIMPLELOG_HXX_ /// A very simple logging mechanism of driver events that is capable of logging /// a few entries of an 8-bit enum value, in a gdb-friendly way. /// /// C is typically uint64_t. template <typename C> class SimpleLog { public: SimpleLog() : log_(0) { } /// Append a byte worth of data to the end of the log buffer. Rotates out /// some old data. void log(uint8_t value) { log_ <<= 8; log_ |= value; } private: /// The raw log buffer. C log_; }; /// Actual class that keeps 8 log entries of one byte each. typedef SimpleLog<uint64_t> LogBuffer; #endif // _FREERTOS_DRIVERS_COMMON_SIMPLELOG_HXX_ <commit_msg>Adds a debug logging facility to hold a bunch of samples of data in RAM for testing history with gdb.<commit_after>/** \copyright * Copyright (c) 2014, Balazs Racz * 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. * * \file SimpleLog.hxx * * A very simple logging mechanism of driver events that is capable of logging * a few entries of an 8-byte enum value, in a gdb-friendly way. * * @author Balazs Racz * @date 14 September 2014 */ #ifndef _FREERTOS_DRIVERS_COMMON_SIMPLELOG_HXX_ #define _FREERTOS_DRIVERS_COMMON_SIMPLELOG_HXX_ /// A very simple logging mechanism of driver events that is capable of logging /// a few entries of an 8-bit enum value, in a gdb-friendly way. /// /// C is typically uint64_t. template <typename C> class SimpleLog { public: SimpleLog() : log_(0) { } /// Append a byte worth of data to the end of the log buffer. Rotates out /// some old data. void log(uint8_t value) { log_ <<= 8; log_ |= value; } private: /// The raw log buffer. C log_; }; /// Actual class that keeps 8 log entries of one byte each. typedef SimpleLog<uint64_t> LogBuffer; /// Alternative for hundreds of entries. template<class T, int N> class LogRing { public: void add(T data) { data_[next_] = data; last_ = data_ + next_; if (next_) { --next_; } else { next_ = N-1; } } private: T data_[N]; unsigned next_{N}; T* last_{data_}; }; #endif // _FREERTOS_DRIVERS_COMMON_SIMPLELOG_HXX_ <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CopasiTime.cpp,v $ $Revision: 1.4 $ $Name: $ $Author: shoops $ $Date: 2005/01/24 18:39:26 $ End CVS Header */ #include <sstream> #include "CopasiTime.h" #include "utility.h" CopasiTimePoint::CopasiTimePoint(): mTime(getCurrentTime_msec()) {} C_INT32 CopasiTimePoint::init() {return mTime = getCurrentTime_msec();} C_INT32 CopasiTimePoint::get() const {return mTime;} C_INT32 CopasiTimePoint::getTimeDiff() const { C_INT32 diff = getCurrentTime_msec() - mTime; return diff & 0x7fffffff; } //the following is linux (posix? unix?) specific and might not work under windows //from the web I guess that windows needs something with // #include <time.h> // ... // return timeGetTime() // ... // but I cannot test that #ifndef WIN32 #include <sys/time.h> //static C_INT64 CopasiTimePoint::getCurrentTime_msec() { timeval ttt; gettimeofday(&ttt, 0); long long int time; time = ttt.tv_sec * 1000 + ttt.tv_usec / 1000; return time & 0x7fffffffffffffff; } #else #include <windows.h> #include <winbase.h> //static C_INT64 CopasiTimePoint::getCurrentTime_msec() { LARGE_INTEGER SystemTime; GetSystemTimeAsFileTime((FILETIME *) &SystemTime); return (SystemTime.QuadPart / 10000) & MAXLONGLONG; } #endif CCopasiTimeVariable::CCopasiTimeVariable(): mTime(0) {} CCopasiTimeVariable::CCopasiTimeVariable(const CCopasiTimeVariable & src): mTime(src.mTime) {} CCopasiTimeVariable::CCopasiTimeVariable(const C_INT64 & value): mTime(value) {} CCopasiTimeVariable::~CCopasiTimeVariable() {} CCopasiTimeVariable CCopasiTimeVariable::operator + (const CCopasiTimeVariable & value) {return mTime + value.mTime;} CCopasiTimeVariable CCopasiTimeVariable::operator - (const CCopasiTimeVariable & value) {return mTime - value.mTime;} CCopasiTimeVariable & CCopasiTimeVariable::operator = (const CCopasiTimeVariable & rhs) { mTime = rhs.mTime; return *this; } CCopasiTimeVariable & CCopasiTimeVariable::operator = (const C_INT64 & value) { mTime = value; return *this; } std::string CCopasiTimeVariable::isoFormat() const { std::stringstream Iso; bool first = true; if (mTime < 0) { CCopasiTimeVariable Tmp(-mTime); Iso << "-"; Iso << Tmp.isoFormat(); return Iso.str(); } if (mTime >= 86400000000) { Iso << LL2String(getDays()) << ":"; first = false; } if (mTime >= 3600000000) Iso << LL2String(getHours(true), first ? 0 : 2) << ":"; if (mTime >= 60000000) Iso << LL2String(getMinutes(true), first ? 0 : 2) << ":"; if (mTime >= 1000000) Iso << LL2String(getSeconds(true), first ? 0 : 2) << "."; else Iso << "0."; Iso << LL2String(getMilliSeconds(true), 3) << LL2String(getMicroSeconds(true), 3); return Iso.str(); } C_INT64 CCopasiTimeVariable::getMicroSeconds(const bool & bounded) const { if (bounded) return mTime % 1000; else return mTime; } C_INT64 CCopasiTimeVariable::getMilliSeconds(const bool & bounded) const { C_INT64 MilliSeconds = (mTime - (mTime % 1000)) / 1000; if (bounded) return MilliSeconds % 1000; else return MilliSeconds; } C_INT64 CCopasiTimeVariable::getSeconds(const bool & bounded) const { C_INT64 Seconds = (mTime - (mTime % 1000000)) / 1000000; if (bounded) return Seconds % 60; else return Seconds; } C_INT64 CCopasiTimeVariable::getMinutes(const bool & bounded) const { C_INT64 Minutes = (mTime - (mTime % 60000000)) / 60000000; if (bounded) return Minutes % 60; else return Minutes; } C_INT64 CCopasiTimeVariable::getHours(const bool & bounded) const { C_INT64 Hours = (mTime - (mTime % 3600000000)) / 3600000000; if (bounded) return Hours % 24; else return Hours; } C_INT64 CCopasiTimeVariable::getDays() const { C_INT64 Days = (mTime - (mTime % 86400000000)) / 86400000000; return Days; } #ifndef WIN32 #include <sys/time.h> //static CCopasiTimeVariable CCopasiTimeVariable::getCurrentWallTime() { timeval ttt; gettimeofday(&ttt, 0); C_INT64 time; time = ((C_INT64) ttt.tv_sec) * 1000000 + (C_INT64) ttt.tv_usec; return time; } #else #include <windows.h> #include <winbase.h> //static CCopasiTimeVariable CCopasiTimeVariable::getCurrentWallTime() { LARGE_INTEGER SystemTime; GetSystemTimeAsFileTime((FILETIME *) &SystemTime); return SystemTime.QuadPart / 10; } #endif std::string CCopasiTimeVariable::LL2String(const C_INT64 & value, const C_INT32 & digits) { std::string format; if (digits > 0) format = "%0" + StringPrint("d", digits); else format = "%"; #ifdef WIN32 format += "I64d"; #else format += "lld"; #endif return StringPrint(format.c_str(), value); } <commit_msg>Fixed to compile under gcc.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CopasiTime.cpp,v $ $Revision: 1.5 $ $Name: $ $Author: shoops $ $Date: 2005/01/24 18:52:30 $ End CVS Header */ #include <sstream> #include "copasi.h" #include "CopasiTime.h" #include "utility.h" CopasiTimePoint::CopasiTimePoint(): mTime(getCurrentTime_msec()) {} C_INT32 CopasiTimePoint::init() {return mTime = getCurrentTime_msec();} C_INT32 CopasiTimePoint::get() const {return mTime;} C_INT32 CopasiTimePoint::getTimeDiff() const { C_INT32 diff = getCurrentTime_msec() - mTime; return diff & 0x7fffffff; } //the following is linux (posix? unix?) specific and might not work under windows //from the web I guess that windows needs something with // #include <time.h> // ... // return timeGetTime() // ... // but I cannot test that #ifndef WIN32 #include <sys/time.h> //static C_INT64 CopasiTimePoint::getCurrentTime_msec() { timeval ttt; gettimeofday(&ttt, 0); long long int time; time = ttt.tv_sec * 1000 + ttt.tv_usec / 1000; return time & LLONG_MAX; } #else #include <windows.h> #include <winbase.h> //static C_INT64 CopasiTimePoint::getCurrentTime_msec() { LARGE_INTEGER SystemTime; GetSystemTimeAsFileTime((FILETIME *) &SystemTime); return (SystemTime.QuadPart / 10000) & LLONG_MAX; } #endif CCopasiTimeVariable::CCopasiTimeVariable(): mTime(0) {} CCopasiTimeVariable::CCopasiTimeVariable(const CCopasiTimeVariable & src): mTime(src.mTime) {} CCopasiTimeVariable::CCopasiTimeVariable(const C_INT64 & value): mTime(value) {} CCopasiTimeVariable::~CCopasiTimeVariable() {} CCopasiTimeVariable CCopasiTimeVariable::operator + (const CCopasiTimeVariable & value) {return mTime + value.mTime;} CCopasiTimeVariable CCopasiTimeVariable::operator - (const CCopasiTimeVariable & value) {return mTime - value.mTime;} CCopasiTimeVariable & CCopasiTimeVariable::operator = (const CCopasiTimeVariable & rhs) { mTime = rhs.mTime; return *this; } CCopasiTimeVariable & CCopasiTimeVariable::operator = (const C_INT64 & value) { mTime = value; return *this; } std::string CCopasiTimeVariable::isoFormat() const { std::stringstream Iso; bool first = true; if (mTime < 0LL) { CCopasiTimeVariable Tmp(-mTime); Iso << "-"; Iso << Tmp.isoFormat(); return Iso.str(); } if (mTime >= 86400000000LL) { Iso << LL2String(getDays()) << ":"; first = false; } if (mTime >= 3600000000LL) Iso << LL2String(getHours(true), first ? 0 : 2) << ":"; if (mTime >= 60000000LL) Iso << LL2String(getMinutes(true), first ? 0 : 2) << ":"; if (mTime >= 1000000LL) Iso << LL2String(getSeconds(true), first ? 0 : 2) << "."; else Iso << "0."; Iso << LL2String(getMilliSeconds(true), 3) << LL2String(getMicroSeconds(true), 3); return Iso.str(); } C_INT64 CCopasiTimeVariable::getMicroSeconds(const bool & bounded) const { if (bounded) return mTime % 1000; else return mTime; } C_INT64 CCopasiTimeVariable::getMilliSeconds(const bool & bounded) const { C_INT64 MilliSeconds = (mTime - (mTime % 1000)) / 1000; if (bounded) return MilliSeconds % 1000; else return MilliSeconds; } C_INT64 CCopasiTimeVariable::getSeconds(const bool & bounded) const { C_INT64 Seconds = (mTime - (mTime % 1000000)) / 1000000; if (bounded) return Seconds % 60; else return Seconds; } C_INT64 CCopasiTimeVariable::getMinutes(const bool & bounded) const { C_INT64 Minutes = (mTime - (mTime % 60000000)) / 60000000; if (bounded) return Minutes % 60; else return Minutes; } C_INT64 CCopasiTimeVariable::getHours(const bool & bounded) const { C_INT64 Hours = (mTime - (mTime % 3600000000LL)) / 3600000000LL; if (bounded) return Hours % 24; else return Hours; } C_INT64 CCopasiTimeVariable::getDays() const { C_INT64 Days = (mTime - (mTime % 86400000000LL)) / 86400000000LL; return Days; } #ifndef WIN32 #include <sys/time.h> //static CCopasiTimeVariable CCopasiTimeVariable::getCurrentWallTime() { timeval ttt; gettimeofday(&ttt, 0); C_INT64 time; time = ((C_INT64) ttt.tv_sec) * 1000000 + (C_INT64) ttt.tv_usec; return time; } #else #include <windows.h> #include <winbase.h> //static CCopasiTimeVariable CCopasiTimeVariable::getCurrentWallTime() { LARGE_INTEGER SystemTime; GetSystemTimeAsFileTime((FILETIME *) &SystemTime); return SystemTime.QuadPart / 10; } #endif std::string CCopasiTimeVariable::LL2String(const C_INT64 & value, const C_INT32 & digits) { std::string format; if (digits > 0) format = "%0" + StringPrint("d", digits); else format = "%"; #ifdef WIN32 format += "I64d"; #else format += "lld"; #endif return StringPrint(format.c_str(), value); } <|endoftext|>
<commit_before>/* * Copyright (C) 2013 * Alessio Sclocco <a.sclocco@vu.nl> * * 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 * (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, see <http://www.gnu.org/licenses/>. * */ #include <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <cmath> using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using std::exception; using std::ofstream; using std::fixed; using std::setprecision; using std::numeric_limits; #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <CLData.hpp> #include <utils.hpp> #include <Folding.hpp> #include <Timer.hpp> using isa::utils::ArgumentList; using isa::utils::toStringValue; using isa::utils::Timer; using AstroData::Observation; using isa::OpenCL::initializeOpenCL; using isa::OpenCL::CLData; using PulsarSearch::Folding; typedef float dataType; const string typeName("float"); const unsigned int maxThreadsPerBlock = 1024; const unsigned int maxItemsPerThread = 256; const unsigned int padding = 32; // Common parameters const unsigned int nrBeams = 1; const unsigned int nrStations = 64; // LOFAR /*const float minFreq = 138.965f; const float channelBandwidth = 0.195f; const unsigned int nrSamplesPerSecond = 200000; const unsigned int nrChannels = 32;*/ // Apertif const float minFreq = 1425.0f; const float channelBandwidth = 0.2929f; const unsigned int nrSamplesPerSecond = 20000; const unsigned int nrChannels = 1024; // Periods const unsigned int nrBins = 32; int main(int argc, char * argv[]) { unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; Observation< dataType > observation("FoldingTuning", typeName); CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true); CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true); CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true); try { ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); } catch ( exception & err ) { cerr << err.what() << endl; return 1; } // Setup of the observation observation.setPadding(padding); observation.setNrSamplesPerSecond(nrSamplesPerSecond); observation.setFirstPeriod(nrBins); observation.setPeriodStep(nrBins); observation.setNrBins(nrBins); cl::Context * clContext = new cl::Context(); vector< cl::Platform > * clPlatforms = new vector< cl::Platform >(); vector< cl::Device > * clDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >(); initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); cout << fixed << endl; cout << "# nrDMs nrPeriods nrPeriodsPerBlock GFLOP/s err time err GB/s err " << endl << endl; for ( unsigned int nrDMs = 2; nrDMs <= 4096; nrDMs *= 2 ) { observation.setNrDMs(nrDMs); for ( unsigned int nrPeriods = 32; nrPeriods <= 1024; nrPeriods *= 2 ) { observation.setNrPeriods(nrPeriods); // Allocate memory dedispersedData->allocateHostData(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); foldedData->allocateHostData(observation.getNrDMs() * observation.getNrBins() * observation.getNrPaddedPeriods()); counterData->allocateHostData(observation.getNrDMs() * observation.getNrBins() * observation.getNrPaddedPeriods()); dedispersedData->setCLContext(clContext); dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); foldedData->setCLContext(clContext); foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); counterData->setCLContext(clContext); counterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); try { dedispersedData->allocateDeviceData(); foldedData->allocateDeviceData(); foldedData->copyHostToDevice(); counterData->allocateDeviceData(); counterData->copyHostToDevice(); } catch ( OpenCLError err ) { cerr << err.what() << endl; } // Find the parameters vector< unsigned int > periodsPerBlock; for ( unsigned int periods = 32; periods <= maxThreadsPerBlock; periods += 32 ) { if ( (observation.getNrPeriods() % periods) == 0 ) { periodsPerBlock.push_back(periods); } } for ( vector< unsigned int >::iterator periods = periodsPerBlock.begin(); periods != periodsPerBlock.end(); periods++ ) { double Acur[2] = {0.0, 0.0}; double Aold[2] = {0.0, 0.0}; double Vcur[2] = {0.0, 0.0}; double Vold[2] = {0.0, 0.0}; try { // Generate kernel Folding< dataType > clFold("clFoldv21p" + toStringValue< unsigned int >(*periods), typeName); clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0))); clFold.setObservation(&observation); clFold.setNrPeriodsPerBlock(*periods); clFold.generateCode(); for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { clFold(0, dedispersedData, foldedData, counterData); if ( iteration == 0 ) { Acur[0] = clFold.getGFLOP() / clFold.getTimer().getLastRunTime(); Acur[1] = clFold.getGB() / clFold.getTimer().getLastRunTime(); } else { Aold[0] = Acur[0]; Vold[0] = Vcur[0]; Acur[0] = Aold[0] + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold[0]) / (iteration + 1)); Vcur[0] = Vold[0] + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold[0]) * ((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Acur[0])); Aold[1] = Acur[1]; Vold[1] = Vcur[1]; Acur[1] = Aold[1] + (((clFold.getGB() / clFold.getTimer().getLastRunTime()) - Aold[1]) / (iteration + 1)); Vcur[1] = Vold[1] + (((clFold.getGB() / clFold.getTimer().getLastRunTime()) - Aold[1]) * ((clFold.getGB() / clFold.getTimer().getLastRunTime()) - Acur[1])); } } Vcur[0] = sqrt(Vcur[0] / nrIterations); Vcur[1] = sqrt(Vcur[1] / nrIterations); cout << nrDMs << " " << nrPeriods << " " << *periods << " " << setprecision(3) << Acur[0] << " " << Vcur[0] << " " << setprecision(6) << clFold.getTimer().getAverageTime() << " " << clFold.getTimer().getStdDev() << " " << setprecision(3) << Acur[1] << " " << Vcur[1] << endl; } catch ( OpenCLError err ) { cerr << err.what() << endl; continue; } } cout << endl << endl; } } cout << endl; return 0; } <commit_msg>Updated the tuning experiment.<commit_after>/* * Copyright (C) 2013 * Alessio Sclocco <a.sclocco@vu.nl> * * 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 * (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, see <http://www.gnu.org/licenses/>. * */ #include <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <cmath> using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using std::exception; using std::ofstream; using std::fixed; using std::setprecision; using std::numeric_limits; #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <CLData.hpp> #include <utils.hpp> #include <Folding.hpp> #include <Timer.hpp> using isa::utils::ArgumentList; using isa::utils::toStringValue; using isa::utils::Timer; using AstroData::Observation; using isa::OpenCL::initializeOpenCL; using isa::OpenCL::CLData; using PulsarSearch::Folding; typedef float dataType; const string typeName("float"); const unsigned int maxThreadsPerBlock = 1024; const unsigned int maxItemsPerThread = 256; const unsigned int padding = 32; // Common parameters const unsigned int nrBeams = 1; const unsigned int nrStations = 64; // LOFAR /*const float minFreq = 138.965f; const float channelBandwidth = 0.195f; const unsigned int nrSamplesPerSecond = 200000; const unsigned int nrChannels = 32;*/ // Apertif const float minFreq = 1425.0f; const float channelBandwidth = 0.2929f; const unsigned int nrSamplesPerSecond = 20000; const unsigned int nrChannels = 1024; // Periods const unsigned int nrBins = 256; int main(int argc, char * argv[]) { unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; Observation< dataType > observation("FoldingTuning", typeName); CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true); CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true); CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true); try { ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); } catch ( exception & err ) { cerr << err.what() << endl; return 1; } // Setup of the observation observation.setPadding(padding); observation.setNrSamplesPerSecond(nrSamplesPerSecond); observation.setFirstPeriod(nrBins); observation.setPeriodStep(nrBins); observation.setNrBins(nrBins); cl::Context * clContext = new cl::Context(); vector< cl::Platform > * clPlatforms = new vector< cl::Platform >(); vector< cl::Device > * clDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >(); initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); cout << fixed << endl; cout << "# nrDMs nrPeriods nrDMsPerBlock GFLOP/s err time err" << endl << endl; for ( unsigned int nrDMs = 2; nrDMs <= 4096; nrDMs *= 2 ) { observation.setNrDMs(nrDMs); for ( unsigned int nrPeriods = 2; nrPeriods <= 1024; nrPeriods *= 2 ) { observation.setNrPeriods(nrPeriods); // Allocate memory dedispersedData->allocateHostData(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); foldedData->allocateHostData(observation.getNrDMs() * observation.getNrBins() * observation.getNrPaddedPeriods()); counterData->allocateHostData(observation.getNrDMs() * observation.getNrBins() * observation.getNrPaddedPeriods()); dedispersedData->setCLContext(clContext); dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); foldedData->setCLContext(clContext); foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); counterData->setCLContext(clContext); counterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); try { dedispersedData->allocateDeviceData(); foldedData->allocateDeviceData(); foldedData->copyHostToDevice(); counterData->allocateDeviceData(); counterData->copyHostToDevice(); } catch ( OpenCLError err ) { cerr << err.what() << endl; } // Find the parameters vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = 2; DMs <= maxThreadsPerBlock; DMs += 2 ) { if ( (observation.getNrDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } for ( vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); DMs++ ) { double Acur[2] = {0.0, 0.0}; double Aold[2] = {0.0, 0.0}; double Vcur[2] = {0.0, 0.0}; double Vold[2] = {0.0, 0.0}; try { // Generate kernel Folding< dataType > clFold("clFold", typeName); clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0))); clFold.setObservation(&observation); clFold.setNrDMsPerBlock(*DMs); clFold.generateCode(); for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { clFold(0, dedispersedData, foldedData, counterData); if ( iteration == 0 ) { Acur[0] = clFold.getGFLOP() / clFold.getTimer().getLastRunTime(); // Acur[1] = clFold.getGB() / clFold.getTimer().getLastRunTime(); } else { Aold[0] = Acur[0]; Vold[0] = Vcur[0]; Acur[0] = Aold[0] + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold[0]) / (iteration + 1)); Vcur[0] = Vold[0] + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold[0]) * ((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Acur[0])); // Aold[1] = Acur[1]; // Vold[1] = Vcur[1]; // Acur[1] = Aold[1] + (((clFold.getGB() / clFold.getTimer().getLastRunTime()) - Aold[1]) / (iteration + 1)); // Vcur[1] = Vold[1] + (((clFold.getGB() / clFold.getTimer().getLastRunTime()) - Aold[1]) * ((clFold.getGB() / clFold.getTimer().getLastRunTime()) - Acur[1])); } } Vcur[0] = sqrt(Vcur[0] / nrIterations); // Vcur[1] = sqrt(Vcur[1] / nrIterations); cout << nrDMs << " " << nrPeriods << " " << *DMs << " " << setprecision(3) << Acur[0] << " " << Vcur[0] << " " << setprecision(6) << clFold.getTimer().getAverageTime() << " " << clFold.getTimer().getStdDev() << endl; } catch ( OpenCLError err ) { cerr << err.what() << endl; continue; } } cout << endl << endl; } } cout << endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: d_token.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-07-12 15:13:30 $ * * 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 CSI_DSAPI_D_TOKEN_HXX #define CSI_DSAPI_D_TOKEN_HXX // USED SERVICES // BASE CLASSES #include <ary_i/ci_text2.hxx> #include <ary_i/ci_atag2.hxx> // COMPONENTS // PARAMETERS #include <display/uidldisp.hxx> namespace csi { namespace dsapi { using ary::info::DocumentationDisplay; class DT_Dsapi : public ary::info::DocuToken { public: virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const = 0; }; class DT_TextToken : public DT_Dsapi { public: DT_TextToken( const char * i_sText ) : sText(i_sText) {} DT_TextToken( const String & i_sText ) : sText(i_sText) {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; const char * GetText() const { return sText; } const String & GetTextStr() const { return sText; } String & Access_Text() { return sText; } private: String sText; }; class DT_MLTag : public DT_Dsapi { public: enum E_Kind { k_unknown = 0, k_begin, k_end, k_single }; }; class DT_MupType : public DT_MLTag { public: DT_MupType( /// Constructor for End-Tag bool i_bEnd ) /// Must be there, but is not evaluated. : bIsBegin(false) {} DT_MupType( /// Constructor for Begin-Tag const udmstri & i_sScope ) : sScope(i_sScope), bIsBegin(true) {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; const udmstri & Scope() const { return sScope; } bool IsBegin() const { return bIsBegin; } private: udmstri sScope; bool bIsBegin; }; class DT_MupMember : public DT_MLTag { public: DT_MupMember( /// Constructor for End-Tag bool i_bEnd ) /// Must be there, but is not evaluated. : bIsBegin(false) {} DT_MupMember( /// Constructor for Begin-Tag const udmstri & i_sScope ) : sScope(i_sScope), bIsBegin(true) {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; const udmstri & Scope() const { return sScope; } bool IsBegin() const { return bIsBegin; } private: udmstri sScope; bool bIsBegin; }; class DT_MupConst : public DT_Dsapi { public: DT_MupConst( const char * i_sConstText ) : sConstText(i_sConstText) {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; const char * GetText() const { return sConstText; } private: udmstri sConstText; /// Without HTML. }; class DT_Style : public DT_MLTag { public: DT_Style( const char * i_sPlainHtmlTag, bool i_bNewLine ) : sText(i_sPlainHtmlTag), bNewLine(i_bNewLine) {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; const char * GetText() const { return sText; } bool IsStartOfNewLine() const { return bNewLine; } private: udmstri sText; /// With HTML. E_Kind eKind; bool bNewLine; }; class DT_EOL : public DT_Dsapi { public: virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; private: udmstri sText; }; class DT_AtTag : public ary::info::AtTag2 { public: void AddToken( DYN ary::info::DocuToken & let_drToken ) { aText.AddToken(let_drToken); } void SetName( const char * i_sName ) { sTitle = i_sName; } protected: DT_AtTag( const char * i_sTitle ) : ary::info::AtTag2(i_sTitle) {} }; class DT_StdAtTag : public DT_AtTag { public: DT_StdAtTag( const char * i_sTitle ) : DT_AtTag(i_sTitle) {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; }; class DT_SeeAlsoAtTag : public DT_AtTag { public: DT_SeeAlsoAtTag() : DT_AtTag("") {} // void SetLinkText( // const char * i_sLinkText ) // { sLinkText = i_sLinkText; } virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; const udmstri & LinkText() const { return sTitle; } // Missbrauch von sTitle private: // udmstri sLinkText; }; class DT_ParameterAtTag : public DT_AtTag { public: DT_ParameterAtTag() : DT_AtTag("") {} void SetTitle( const char * i_sTitle ); virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; }; class DT_SinceAtTag : public DT_AtTag { public: DT_SinceAtTag() : DT_AtTag("Since version") {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; }; } // namespace dsapi } // namespace csi #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.4.24); FILE MERGED 2005/09/05 13:09:39 rt 1.4.24.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: d_token.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-07 16:25:10 $ * * 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 CSI_DSAPI_D_TOKEN_HXX #define CSI_DSAPI_D_TOKEN_HXX // USED SERVICES // BASE CLASSES #include <ary_i/ci_text2.hxx> #include <ary_i/ci_atag2.hxx> // COMPONENTS // PARAMETERS #include <display/uidldisp.hxx> namespace csi { namespace dsapi { using ary::info::DocumentationDisplay; class DT_Dsapi : public ary::info::DocuToken { public: virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const = 0; }; class DT_TextToken : public DT_Dsapi { public: DT_TextToken( const char * i_sText ) : sText(i_sText) {} DT_TextToken( const String & i_sText ) : sText(i_sText) {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; const char * GetText() const { return sText; } const String & GetTextStr() const { return sText; } String & Access_Text() { return sText; } private: String sText; }; class DT_MLTag : public DT_Dsapi { public: enum E_Kind { k_unknown = 0, k_begin, k_end, k_single }; }; class DT_MupType : public DT_MLTag { public: DT_MupType( /// Constructor for End-Tag bool i_bEnd ) /// Must be there, but is not evaluated. : bIsBegin(false) {} DT_MupType( /// Constructor for Begin-Tag const udmstri & i_sScope ) : sScope(i_sScope), bIsBegin(true) {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; const udmstri & Scope() const { return sScope; } bool IsBegin() const { return bIsBegin; } private: udmstri sScope; bool bIsBegin; }; class DT_MupMember : public DT_MLTag { public: DT_MupMember( /// Constructor for End-Tag bool i_bEnd ) /// Must be there, but is not evaluated. : bIsBegin(false) {} DT_MupMember( /// Constructor for Begin-Tag const udmstri & i_sScope ) : sScope(i_sScope), bIsBegin(true) {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; const udmstri & Scope() const { return sScope; } bool IsBegin() const { return bIsBegin; } private: udmstri sScope; bool bIsBegin; }; class DT_MupConst : public DT_Dsapi { public: DT_MupConst( const char * i_sConstText ) : sConstText(i_sConstText) {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; const char * GetText() const { return sConstText; } private: udmstri sConstText; /// Without HTML. }; class DT_Style : public DT_MLTag { public: DT_Style( const char * i_sPlainHtmlTag, bool i_bNewLine ) : sText(i_sPlainHtmlTag), bNewLine(i_bNewLine) {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; const char * GetText() const { return sText; } bool IsStartOfNewLine() const { return bNewLine; } private: udmstri sText; /// With HTML. E_Kind eKind; bool bNewLine; }; class DT_EOL : public DT_Dsapi { public: virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; private: udmstri sText; }; class DT_AtTag : public ary::info::AtTag2 { public: void AddToken( DYN ary::info::DocuToken & let_drToken ) { aText.AddToken(let_drToken); } void SetName( const char * i_sName ) { sTitle = i_sName; } protected: DT_AtTag( const char * i_sTitle ) : ary::info::AtTag2(i_sTitle) {} }; class DT_StdAtTag : public DT_AtTag { public: DT_StdAtTag( const char * i_sTitle ) : DT_AtTag(i_sTitle) {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; }; class DT_SeeAlsoAtTag : public DT_AtTag { public: DT_SeeAlsoAtTag() : DT_AtTag("") {} // void SetLinkText( // const char * i_sLinkText ) // { sLinkText = i_sLinkText; } virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; const udmstri & LinkText() const { return sTitle; } // Missbrauch von sTitle private: // udmstri sLinkText; }; class DT_ParameterAtTag : public DT_AtTag { public: DT_ParameterAtTag() : DT_AtTag("") {} void SetTitle( const char * i_sTitle ); virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; }; class DT_SinceAtTag : public DT_AtTag { public: DT_SinceAtTag() : DT_AtTag("Since version") {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; }; } // namespace dsapi } // namespace csi #endif <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/prediction/common/prediction_util.h" #include <cmath> #include <limits> #include <string> #include <vector> #include "cyber/common/log.h" #include "modules/common/math/linear_interpolation.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" namespace apollo { namespace prediction { namespace math_util { double Normalize(const double value, const double mean, const double std) { const double eps = 1e-10; return (value - mean) / (std + eps); } double Sigmoid(const double value) { return 1.0 / (1.0 + std::exp(-1.0 * value)); } double Relu(const double value) { return (value > 0.0) ? value : 0.0; } std::vector<double> Softmax(const std::vector<double>& value) { std::vector<double> result; double sum = 0.0; for (std::size_t i = 0; i < value.size(); ++i) { sum += std::exp(value[i]); } for (std::size_t i = 0; i < value.size(); ++i) { result.push_back(std::exp(value[i]) / sum); } return result; } int SolveQuadraticEquation(const std::vector<double>& coefficients, std::pair<double, double>* roots) { if (coefficients.size() != 3) { return -1; } const double& a = coefficients[0]; const double& b = coefficients[1]; const double& c = coefficients[2]; if (std::fabs(a) <= std::numeric_limits<double>::epsilon()) { return -1; } double delta = b * b - 4.0 * a * c; if (delta < 0.0) { return -1; } double sqrt_delta = std::sqrt(delta); roots->first = (-b + sqrt_delta) * 0.5 / a; roots->second = (-b - sqrt_delta) * 0.5 / a; return 0; } double EvaluateQuinticPolynomial( const std::array<double, 6>& coeffs, const double t, const uint32_t order, const double end_t, const double end_v) { if (t >= end_t) { switch (order) { case 0: { double end_value = ((((coeffs[5] * end_t + coeffs[4]) * end_t + coeffs[3]) * end_t + coeffs[2]) * end_t + coeffs[1]) * end_t + coeffs[0]; return end_value + end_v * (t - end_t); } case 1: { return end_v; } default: { return 0.0; } } } switch (order) { case 0: { return ((((coeffs[5] * t + coeffs[4]) * t + coeffs[3]) * t + coeffs[2]) * t + coeffs[1]) * t + coeffs[0]; } case 1: { return (((5.0 * coeffs[5] * t + 4.0 * coeffs[4]) * t + 3.0 * coeffs[3]) * t + 2.0 * coeffs[2]) * t + coeffs[1]; } case 2: { return (((20.0 * coeffs[5] * t + 12.0 * coeffs[4]) * t) + 6.0 * coeffs[3]) * t + 2.0 * coeffs[2]; } case 3: { return (60.0 * coeffs[5] * t + 24.0 * coeffs[4]) * t + 6.0 * coeffs[3]; } case 4: { return 120.0 * coeffs[5] * t + 24.0 * coeffs[4]; } case 5: { return 120.0 * coeffs[5]; } default: return 0.0; } } double EvaluateQuarticPolynomial( const std::array<double, 5>& coeffs, const double t, const uint32_t order, const double end_t, const double end_v) { if (t >= end_t) { switch (order) { case 0: { double end_value = (((coeffs[4] * end_t + coeffs[3]) * end_t + coeffs[2]) * end_t + coeffs[1]) * end_t + coeffs[0]; return end_value + (t - end_t) * end_v; } case 1: { return end_v; } default: { return 0.0; } } } switch (order) { case 0: { return (((coeffs[4] * t + coeffs[3]) * t + coeffs[2]) * t + coeffs[1]) * t + coeffs[0]; } case 1: { return ((4.0 * coeffs[4] * t + 3.0 * coeffs[3]) * t + 2.0 * coeffs[2]) * t + coeffs[1]; } case 2: { return (12.0 * coeffs[4] * t + 6.0 * coeffs[3]) * t + 2.0 * coeffs[2]; } case 3: { return 24.0 * coeffs[4] * t + 6.0 * coeffs[3]; } case 4: { return 24.0 * coeffs[4]; } default: return 0.0; } } double EvaluateCubicPolynomial( const std::array<double, 4>& coefs, const double t, const uint32_t order, const double end_t, const double end_v) { if (t > end_t) { switch (order) { case 0: { double end_value = ((coefs[3] * end_t + coefs[2]) * end_t + coefs[1]) * end_t + coefs[0]; return end_value + (t - end_t) * end_v; } case 1: { return end_v; } default: { return 0.0; } } } switch (order) { case 0: { return ((coefs[3] * t + coefs[2]) * t + coefs[1]) * t + coefs[0]; } case 1: { return (3.0 * coefs[3] * t + 2.0 * coefs[2]) * t + coefs[1]; } case 2: { return 6.0 * coefs[3] * t + 2.0 * coefs[2]; } case 3: { return 6.0 * coefs[3]; } default: return 0.0; } } } // namespace math_util namespace predictor_util { using apollo::common::PathPoint; using apollo::common::TrajectoryPoint; void TranslatePoint(const double translate_x, const double translate_y, TrajectoryPoint* point) { if (point == nullptr || !point->has_path_point()) { AERROR << "Point is nullptr or has NO path_point."; return; } const double original_x = point->path_point().x(); const double original_y = point->path_point().y(); point->mutable_path_point()->set_x(original_x + translate_x); point->mutable_path_point()->set_y(original_y + translate_y); } void GenerateFreeMoveTrajectoryPoints( Eigen::Matrix<double, 6, 1>* state, const Eigen::Matrix<double, 6, 6>& transition, double theta, const std::size_t num, const double period, std::vector<TrajectoryPoint>* points) { double x = (*state)(0, 0); double y = (*state)(1, 0); double v_x = (*state)(2, 0); double v_y = (*state)(3, 0); double acc_x = (*state)(4, 0); double acc_y = (*state)(5, 0); for (std::size_t i = 0; i < num; ++i) { double speed = std::hypot(v_x, v_y); double acc = 0.0; if (speed <= std::numeric_limits<double>::epsilon()) { speed = 0.0; v_x = 0.0; v_y = 0.0; acc_x = 0.0; acc_y = 0.0; acc = 0.0; } else if (speed > FLAGS_max_speed) { speed = FLAGS_max_speed; } // update theta and acc if (speed > std::numeric_limits<double>::epsilon()) { if (points->size() > 0) { TrajectoryPoint& prev_trajectory_point = points->back(); PathPoint* prev_path_point = prev_trajectory_point.mutable_path_point(); theta = std::atan2(y - prev_path_point->y(), x - prev_path_point->x()); prev_path_point->set_theta(theta); acc = (speed - prev_trajectory_point.v()) / period; prev_trajectory_point.set_a(acc); } } else { if (points->size() > 0) { theta = points->back().path_point().theta(); } } // update state (*state)(2, 0) = v_x; (*state)(3, 0) = v_y; (*state)(4, 0) = acc_x; (*state)(5, 0) = acc_y; // obtain position x = (*state)(0, 0); y = (*state)(1, 0); // Generate trajectory point TrajectoryPoint trajectory_point; PathPoint path_point; path_point.set_x(x); path_point.set_y(y); path_point.set_z(0.0); path_point.set_theta(theta); trajectory_point.mutable_path_point()->CopyFrom(path_point); trajectory_point.set_v(speed); trajectory_point.set_a(acc); trajectory_point.set_relative_time(i * period); points->emplace_back(std::move(trajectory_point)); // Update position, velocity and acceleration (*state) = transition * (*state); x = (*state)(0, 0); y = (*state)(1, 0); v_x = (*state)(2, 0); v_y = (*state)(3, 0); acc_x = (*state)(4, 0); acc_y = (*state)(5, 0); } } double AdjustSpeedByCurvature(const double speed, const double curvature) { if (std::abs(curvature) < FLAGS_turning_curvature_lower_bound) { return speed; } if (std::abs(curvature) > FLAGS_turning_curvature_upper_bound) { return FLAGS_speed_at_upper_curvature; } return apollo::common::math::lerp(FLAGS_speed_at_lower_curvature, FLAGS_turning_curvature_lower_bound, FLAGS_speed_at_upper_curvature, FLAGS_turning_curvature_upper_bound, curvature); } } // namespace predictor_util } // namespace prediction } // namespace apollo <commit_msg>Prediction: minor fix softmax<commit_after>/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/prediction/common/prediction_util.h" #include <cmath> #include <limits> #include <string> #include <vector> #include "cyber/common/log.h" #include "modules/common/math/linear_interpolation.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" namespace apollo { namespace prediction { namespace math_util { double Normalize(const double value, const double mean, const double std) { const double eps = 1e-10; return (value - mean) / (std + eps); } double Sigmoid(const double value) { return 1.0 / (1.0 + std::exp(-1.0 * value)); } double Relu(const double value) { return (value > 0.0) ? value : 0.0; } std::vector<double> Softmax(const std::vector<double>& value) { std::vector<double> result; double sum = 0.0; for (std::size_t i = 0; i < value.size(); ++i) { double exp_value = std::exp(value[i]); sum += exp_value; result.push_back(exp_value); } for (std::size_t i = 0; i < value.size(); ++i) { result[i] = result[i] / sum; } return result; } int SolveQuadraticEquation(const std::vector<double>& coefficients, std::pair<double, double>* roots) { if (coefficients.size() != 3) { return -1; } const double& a = coefficients[0]; const double& b = coefficients[1]; const double& c = coefficients[2]; if (std::fabs(a) <= std::numeric_limits<double>::epsilon()) { return -1; } double delta = b * b - 4.0 * a * c; if (delta < 0.0) { return -1; } double sqrt_delta = std::sqrt(delta); roots->first = (-b + sqrt_delta) * 0.5 / a; roots->second = (-b - sqrt_delta) * 0.5 / a; return 0; } double EvaluateQuinticPolynomial( const std::array<double, 6>& coeffs, const double t, const uint32_t order, const double end_t, const double end_v) { if (t >= end_t) { switch (order) { case 0: { double end_value = ((((coeffs[5] * end_t + coeffs[4]) * end_t + coeffs[3]) * end_t + coeffs[2]) * end_t + coeffs[1]) * end_t + coeffs[0]; return end_value + end_v * (t - end_t); } case 1: { return end_v; } default: { return 0.0; } } } switch (order) { case 0: { return ((((coeffs[5] * t + coeffs[4]) * t + coeffs[3]) * t + coeffs[2]) * t + coeffs[1]) * t + coeffs[0]; } case 1: { return (((5.0 * coeffs[5] * t + 4.0 * coeffs[4]) * t + 3.0 * coeffs[3]) * t + 2.0 * coeffs[2]) * t + coeffs[1]; } case 2: { return (((20.0 * coeffs[5] * t + 12.0 * coeffs[4]) * t) + 6.0 * coeffs[3]) * t + 2.0 * coeffs[2]; } case 3: { return (60.0 * coeffs[5] * t + 24.0 * coeffs[4]) * t + 6.0 * coeffs[3]; } case 4: { return 120.0 * coeffs[5] * t + 24.0 * coeffs[4]; } case 5: { return 120.0 * coeffs[5]; } default: return 0.0; } } double EvaluateQuarticPolynomial( const std::array<double, 5>& coeffs, const double t, const uint32_t order, const double end_t, const double end_v) { if (t >= end_t) { switch (order) { case 0: { double end_value = (((coeffs[4] * end_t + coeffs[3]) * end_t + coeffs[2]) * end_t + coeffs[1]) * end_t + coeffs[0]; return end_value + (t - end_t) * end_v; } case 1: { return end_v; } default: { return 0.0; } } } switch (order) { case 0: { return (((coeffs[4] * t + coeffs[3]) * t + coeffs[2]) * t + coeffs[1]) * t + coeffs[0]; } case 1: { return ((4.0 * coeffs[4] * t + 3.0 * coeffs[3]) * t + 2.0 * coeffs[2]) * t + coeffs[1]; } case 2: { return (12.0 * coeffs[4] * t + 6.0 * coeffs[3]) * t + 2.0 * coeffs[2]; } case 3: { return 24.0 * coeffs[4] * t + 6.0 * coeffs[3]; } case 4: { return 24.0 * coeffs[4]; } default: return 0.0; } } double EvaluateCubicPolynomial( const std::array<double, 4>& coefs, const double t, const uint32_t order, const double end_t, const double end_v) { if (t > end_t) { switch (order) { case 0: { double end_value = ((coefs[3] * end_t + coefs[2]) * end_t + coefs[1]) * end_t + coefs[0]; return end_value + (t - end_t) * end_v; } case 1: { return end_v; } default: { return 0.0; } } } switch (order) { case 0: { return ((coefs[3] * t + coefs[2]) * t + coefs[1]) * t + coefs[0]; } case 1: { return (3.0 * coefs[3] * t + 2.0 * coefs[2]) * t + coefs[1]; } case 2: { return 6.0 * coefs[3] * t + 2.0 * coefs[2]; } case 3: { return 6.0 * coefs[3]; } default: return 0.0; } } } // namespace math_util namespace predictor_util { using apollo::common::PathPoint; using apollo::common::TrajectoryPoint; void TranslatePoint(const double translate_x, const double translate_y, TrajectoryPoint* point) { if (point == nullptr || !point->has_path_point()) { AERROR << "Point is nullptr or has NO path_point."; return; } const double original_x = point->path_point().x(); const double original_y = point->path_point().y(); point->mutable_path_point()->set_x(original_x + translate_x); point->mutable_path_point()->set_y(original_y + translate_y); } void GenerateFreeMoveTrajectoryPoints( Eigen::Matrix<double, 6, 1>* state, const Eigen::Matrix<double, 6, 6>& transition, double theta, const std::size_t num, const double period, std::vector<TrajectoryPoint>* points) { double x = (*state)(0, 0); double y = (*state)(1, 0); double v_x = (*state)(2, 0); double v_y = (*state)(3, 0); double acc_x = (*state)(4, 0); double acc_y = (*state)(5, 0); for (std::size_t i = 0; i < num; ++i) { double speed = std::hypot(v_x, v_y); double acc = 0.0; if (speed <= std::numeric_limits<double>::epsilon()) { speed = 0.0; v_x = 0.0; v_y = 0.0; acc_x = 0.0; acc_y = 0.0; acc = 0.0; } else if (speed > FLAGS_max_speed) { speed = FLAGS_max_speed; } // update theta and acc if (speed > std::numeric_limits<double>::epsilon()) { if (points->size() > 0) { TrajectoryPoint& prev_trajectory_point = points->back(); PathPoint* prev_path_point = prev_trajectory_point.mutable_path_point(); theta = std::atan2(y - prev_path_point->y(), x - prev_path_point->x()); prev_path_point->set_theta(theta); acc = (speed - prev_trajectory_point.v()) / period; prev_trajectory_point.set_a(acc); } } else { if (points->size() > 0) { theta = points->back().path_point().theta(); } } // update state (*state)(2, 0) = v_x; (*state)(3, 0) = v_y; (*state)(4, 0) = acc_x; (*state)(5, 0) = acc_y; // obtain position x = (*state)(0, 0); y = (*state)(1, 0); // Generate trajectory point TrajectoryPoint trajectory_point; PathPoint path_point; path_point.set_x(x); path_point.set_y(y); path_point.set_z(0.0); path_point.set_theta(theta); trajectory_point.mutable_path_point()->CopyFrom(path_point); trajectory_point.set_v(speed); trajectory_point.set_a(acc); trajectory_point.set_relative_time(i * period); points->emplace_back(std::move(trajectory_point)); // Update position, velocity and acceleration (*state) = transition * (*state); x = (*state)(0, 0); y = (*state)(1, 0); v_x = (*state)(2, 0); v_y = (*state)(3, 0); acc_x = (*state)(4, 0); acc_y = (*state)(5, 0); } } double AdjustSpeedByCurvature(const double speed, const double curvature) { if (std::abs(curvature) < FLAGS_turning_curvature_lower_bound) { return speed; } if (std::abs(curvature) > FLAGS_turning_curvature_upper_bound) { return FLAGS_speed_at_upper_curvature; } return apollo::common::math::lerp(FLAGS_speed_at_lower_curvature, FLAGS_turning_curvature_lower_bound, FLAGS_speed_at_upper_curvature, FLAGS_turning_curvature_upper_bound, curvature); } } // namespace predictor_util } // namespace prediction } // namespace apollo <|endoftext|>
<commit_before><commit_msg>`Node::~Node`: call `Graph::unbind_node` for unbinding.<commit_after><|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 <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include "base/command_line.h" #include "base/eintr_wrapper.h" #include "base/file_util.h" #include "base/logging.h" #include "base/memory/singleton.h" #include "base/time.h" #include "content/common/sandbox_linux.h" #include "content/common/seccomp_sandbox.h" #include "content/common/sandbox_seccomp_bpf_linux.h" #include "content/public/common/content_switches.h" #include "content/public/common/sandbox_linux.h" #include "sandbox/linux/suid/client/setuid_sandbox_client.h" namespace { void LogSandboxStarted(const std::string& sandbox_name) { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); const std::string process_type = command_line.GetSwitchValueASCII(switches::kProcessType); const std::string activated_sandbox = "Activated " + sandbox_name + " sandbox for process type: " + process_type + "."; #if defined(OS_CHROMEOS) LOG(WARNING) << activated_sandbox; #else VLOG(1) << activated_sandbox; #endif } // Implement the command line enabling logic for seccomp-legacy. bool IsSeccompLegacyDesired() { #if defined(SECCOMP_SANDBOX) #if defined(NDEBUG) // Off by default. Allow turning on with a switch. return CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableSeccompSandbox); #else // On by default. Allow turning off with a switch. return !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableSeccompSandbox); #endif // NDEBUG #endif // SECCOMP_SANDBOX return false; } // Our "policy" on whether or not to enable seccomp-legacy. Only renderers are // supported. bool ShouldEnableSeccompLegacy(const std::string& process_type) { if (IsSeccompLegacyDesired() && process_type == switches::kRendererProcess) { return true; } else { return false; } } } // namespace namespace content { LinuxSandbox::LinuxSandbox() : proc_fd_(-1), pre_initialized_(false), seccomp_legacy_supported_(false), seccomp_bpf_supported_(false), setuid_sandbox_client_(sandbox::SetuidSandboxClient::Create()) { if (setuid_sandbox_client_ == NULL) { LOG(FATAL) << "Failed to instantiate the setuid sandbox client."; } } LinuxSandbox::~LinuxSandbox() { } LinuxSandbox* LinuxSandbox::GetInstance() { LinuxSandbox* instance = Singleton<LinuxSandbox>::get(); CHECK(instance); return instance; } void LinuxSandbox::PreinitializeSandboxBegin() { CHECK(!pre_initialized_); seccomp_legacy_supported_ = false; seccomp_bpf_supported_ = false; #if defined(SECCOMP_SANDBOX) if (IsSeccompLegacyDesired()) { proc_fd_ = open("/proc", O_DIRECTORY | O_RDONLY); if (proc_fd_ < 0) { LOG(ERROR) << "Cannot access \"/proc\". Disabling seccomp-legacy " "sandboxing."; // Now is a good time to figure out if we can support seccomp sandboxing // at all. We will call SupportsSeccompSandbox again later, when actually // enabling it, but we allow the implementation to cache some information. // This is the only place where we will log full lack of seccomp-legacy // support. } else if (!SupportsSeccompSandbox(proc_fd_)) { VLOG(1) << "Lacking support for seccomp-legacy sandbox."; CHECK_EQ(HANDLE_EINTR(close(proc_fd_)), 0); proc_fd_ = -1; } else { seccomp_legacy_supported_ = true; } } #endif // SECCOMP_SANDBOX // Similarly, we "pre-warm" the code that detects supports for seccomp BPF. // TODO(jln): Use proc_fd_ here too once we're comfortable it does not create // an additional security risk. if (SandboxSeccompBpf::IsSeccompBpfDesired()) { if (!SandboxSeccompBpf::SupportsSandbox()) { VLOG(1) << "Lacking support for seccomp-bpf sandbox."; } else { seccomp_bpf_supported_ = true; } } pre_initialized_ = true; } // Once we finally know our process type, we can cleanup proc_fd_ // or pass it to seccomp-legacy. void LinuxSandbox::PreinitializeSandboxFinish( const std::string& process_type) { CHECK(pre_initialized_); if (proc_fd_ >= 0) { if (ShouldEnableSeccompLegacy(process_type)) { #if defined(SECCOMP_SANDBOX) SeccompSandboxSetProcFd(proc_fd_); #endif } else { DCHECK_GE(proc_fd_, 0); CHECK_EQ(HANDLE_EINTR(close(proc_fd_)), 0); } proc_fd_ = -1; } } void LinuxSandbox::PreinitializeSandbox(const std::string& process_type) { PreinitializeSandboxBegin(); PreinitializeSandboxFinish(process_type); } int LinuxSandbox::GetStatus() const { CHECK(pre_initialized_); int sandbox_flags = 0; if (setuid_sandbox_client_->IsSandboxed()) { sandbox_flags |= kSandboxLinuxSUID; if (setuid_sandbox_client_->IsInNewPIDNamespace()) sandbox_flags |= kSandboxLinuxPIDNS; if (setuid_sandbox_client_->IsInNewNETNamespace()) sandbox_flags |= kSandboxLinuxNetNS; } if (seccomp_legacy_supported() && ShouldEnableSeccompLegacy(switches::kRendererProcess)) { // We report whether the sandbox will be activated when renderers go // through sandbox initialization. sandbox_flags |= kSandboxLinuxSeccompLegacy; } if (seccomp_bpf_supported() && SandboxSeccompBpf::ShouldEnableSeccompBpf(switches::kRendererProcess)) { // Same here, what we report is what we will do for the renderer. sandbox_flags |= kSandboxLinuxSeccompBpf; } return sandbox_flags; } bool LinuxSandbox::IsSingleThreaded() const { // TODO(jln): re-implement this properly and use our proc_fd_ if available. // Possibly racy, but it's ok because this is more of a debug check to catch // new threaded situations arising during development. int num_threads = file_util::CountFilesCreatedAfter( FilePath("/proc/self/task"), base::Time::UnixEpoch()); // We pass the test if we don't know ( == 0), because the setuid sandbox // will prevent /proc access in some contexts. return num_threads == 1 || num_threads == 0; } sandbox::SetuidSandboxClient* LinuxSandbox::setuid_sandbox_client() const { return setuid_sandbox_client_.get(); } // For seccomp-legacy, we implement the policy inline, here. bool LinuxSandbox::StartSeccompLegacy(const std::string& process_type) { if (!pre_initialized_) PreinitializeSandbox(process_type); if (seccomp_legacy_supported() && ShouldEnableSeccompLegacy(process_type)) { // SupportsSeccompSandbox() returns a cached result, as we already // called it earlier in the PreinitializeSandbox(). Thus, it is OK for us // to not pass in a file descriptor for "/proc". #if defined(SECCOMP_SANDBOX) if (SupportsSeccompSandbox(-1)) { StartSeccompSandbox(); LogSandboxStarted("seccomp-legacy"); return true; } #endif } return false; } // For seccomp-bpf, we use the SandboxSeccompBpf class. bool LinuxSandbox::StartSeccompBpf(const std::string& process_type) { if (!pre_initialized_) PreinitializeSandbox(process_type); bool started_bpf_sandbox = false; if (seccomp_bpf_supported()) started_bpf_sandbox = SandboxSeccompBpf::StartSandbox(process_type); if (started_bpf_sandbox) LogSandboxStarted("seccomp-bpf"); return started_bpf_sandbox; } bool LinuxSandbox::seccomp_legacy_supported() const { CHECK(pre_initialized_); return seccomp_legacy_supported_; } bool LinuxSandbox::seccomp_bpf_supported() const { CHECK(pre_initialized_); return seccomp_bpf_supported_; } } // namespace content <commit_msg>Disable seccomp-legacy if --no-sandbox is passed.<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 <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include "base/command_line.h" #include "base/eintr_wrapper.h" #include "base/file_util.h" #include "base/logging.h" #include "base/memory/singleton.h" #include "base/time.h" #include "content/common/sandbox_linux.h" #include "content/common/seccomp_sandbox.h" #include "content/common/sandbox_seccomp_bpf_linux.h" #include "content/public/common/content_switches.h" #include "content/public/common/sandbox_linux.h" #include "sandbox/linux/suid/client/setuid_sandbox_client.h" namespace { void LogSandboxStarted(const std::string& sandbox_name) { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); const std::string process_type = command_line.GetSwitchValueASCII(switches::kProcessType); const std::string activated_sandbox = "Activated " + sandbox_name + " sandbox for process type: " + process_type + "."; #if defined(OS_CHROMEOS) LOG(WARNING) << activated_sandbox; #else VLOG(1) << activated_sandbox; #endif } // Implement the command line enabling logic for seccomp-legacy. bool IsSeccompLegacyDesired() { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kNoSandbox)) { return false; } #if defined(SECCOMP_SANDBOX) #if defined(NDEBUG) // Off by default. Allow turning on with a switch. return command_line->HasSwitch(switches::kEnableSeccompSandbox); #else // On by default. Allow turning off with a switch. return !command_line->HasSwitch(switches::kDisableSeccompSandbox); #endif // NDEBUG #endif // SECCOMP_SANDBOX return false; } // Our "policy" on whether or not to enable seccomp-legacy. Only renderers are // supported. bool ShouldEnableSeccompLegacy(const std::string& process_type) { if (IsSeccompLegacyDesired() && process_type == switches::kRendererProcess) { return true; } else { return false; } } } // namespace namespace content { LinuxSandbox::LinuxSandbox() : proc_fd_(-1), pre_initialized_(false), seccomp_legacy_supported_(false), seccomp_bpf_supported_(false), setuid_sandbox_client_(sandbox::SetuidSandboxClient::Create()) { if (setuid_sandbox_client_ == NULL) { LOG(FATAL) << "Failed to instantiate the setuid sandbox client."; } } LinuxSandbox::~LinuxSandbox() { } LinuxSandbox* LinuxSandbox::GetInstance() { LinuxSandbox* instance = Singleton<LinuxSandbox>::get(); CHECK(instance); return instance; } void LinuxSandbox::PreinitializeSandboxBegin() { CHECK(!pre_initialized_); seccomp_legacy_supported_ = false; seccomp_bpf_supported_ = false; #if defined(SECCOMP_SANDBOX) if (IsSeccompLegacyDesired()) { proc_fd_ = open("/proc", O_DIRECTORY | O_RDONLY); if (proc_fd_ < 0) { LOG(ERROR) << "Cannot access \"/proc\". Disabling seccomp-legacy " "sandboxing."; // Now is a good time to figure out if we can support seccomp sandboxing // at all. We will call SupportsSeccompSandbox again later, when actually // enabling it, but we allow the implementation to cache some information. // This is the only place where we will log full lack of seccomp-legacy // support. } else if (!SupportsSeccompSandbox(proc_fd_)) { VLOG(1) << "Lacking support for seccomp-legacy sandbox."; CHECK_EQ(HANDLE_EINTR(close(proc_fd_)), 0); proc_fd_ = -1; } else { seccomp_legacy_supported_ = true; } } #endif // SECCOMP_SANDBOX // Similarly, we "pre-warm" the code that detects supports for seccomp BPF. // TODO(jln): Use proc_fd_ here too once we're comfortable it does not create // an additional security risk. if (SandboxSeccompBpf::IsSeccompBpfDesired()) { if (!SandboxSeccompBpf::SupportsSandbox()) { VLOG(1) << "Lacking support for seccomp-bpf sandbox."; } else { seccomp_bpf_supported_ = true; } } pre_initialized_ = true; } // Once we finally know our process type, we can cleanup proc_fd_ // or pass it to seccomp-legacy. void LinuxSandbox::PreinitializeSandboxFinish( const std::string& process_type) { CHECK(pre_initialized_); if (proc_fd_ >= 0) { if (ShouldEnableSeccompLegacy(process_type)) { #if defined(SECCOMP_SANDBOX) SeccompSandboxSetProcFd(proc_fd_); #endif } else { DCHECK_GE(proc_fd_, 0); CHECK_EQ(HANDLE_EINTR(close(proc_fd_)), 0); } proc_fd_ = -1; } } void LinuxSandbox::PreinitializeSandbox(const std::string& process_type) { PreinitializeSandboxBegin(); PreinitializeSandboxFinish(process_type); } int LinuxSandbox::GetStatus() const { CHECK(pre_initialized_); int sandbox_flags = 0; if (setuid_sandbox_client_->IsSandboxed()) { sandbox_flags |= kSandboxLinuxSUID; if (setuid_sandbox_client_->IsInNewPIDNamespace()) sandbox_flags |= kSandboxLinuxPIDNS; if (setuid_sandbox_client_->IsInNewNETNamespace()) sandbox_flags |= kSandboxLinuxNetNS; } if (seccomp_legacy_supported() && ShouldEnableSeccompLegacy(switches::kRendererProcess)) { // We report whether the sandbox will be activated when renderers go // through sandbox initialization. sandbox_flags |= kSandboxLinuxSeccompLegacy; } if (seccomp_bpf_supported() && SandboxSeccompBpf::ShouldEnableSeccompBpf(switches::kRendererProcess)) { // Same here, what we report is what we will do for the renderer. sandbox_flags |= kSandboxLinuxSeccompBpf; } return sandbox_flags; } bool LinuxSandbox::IsSingleThreaded() const { // TODO(jln): re-implement this properly and use our proc_fd_ if available. // Possibly racy, but it's ok because this is more of a debug check to catch // new threaded situations arising during development. int num_threads = file_util::CountFilesCreatedAfter( FilePath("/proc/self/task"), base::Time::UnixEpoch()); // We pass the test if we don't know ( == 0), because the setuid sandbox // will prevent /proc access in some contexts. return num_threads == 1 || num_threads == 0; } sandbox::SetuidSandboxClient* LinuxSandbox::setuid_sandbox_client() const { return setuid_sandbox_client_.get(); } // For seccomp-legacy, we implement the policy inline, here. bool LinuxSandbox::StartSeccompLegacy(const std::string& process_type) { if (!pre_initialized_) PreinitializeSandbox(process_type); if (seccomp_legacy_supported() && ShouldEnableSeccompLegacy(process_type)) { // SupportsSeccompSandbox() returns a cached result, as we already // called it earlier in the PreinitializeSandbox(). Thus, it is OK for us // to not pass in a file descriptor for "/proc". #if defined(SECCOMP_SANDBOX) if (SupportsSeccompSandbox(-1)) { StartSeccompSandbox(); LogSandboxStarted("seccomp-legacy"); return true; } #endif } return false; } // For seccomp-bpf, we use the SandboxSeccompBpf class. bool LinuxSandbox::StartSeccompBpf(const std::string& process_type) { if (!pre_initialized_) PreinitializeSandbox(process_type); bool started_bpf_sandbox = false; if (seccomp_bpf_supported()) started_bpf_sandbox = SandboxSeccompBpf::StartSandbox(process_type); if (started_bpf_sandbox) LogSandboxStarted("seccomp-bpf"); return started_bpf_sandbox; } bool LinuxSandbox::seccomp_legacy_supported() const { CHECK(pre_initialized_); return seccomp_legacy_supported_; } bool LinuxSandbox::seccomp_bpf_supported() const { CHECK(pre_initialized_); return seccomp_bpf_supported_; } } // namespace content <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "modulemerger.h" #include "value.h" #include <logging/translator.h> #include <tools/qbsassert.h> namespace qbs { namespace Internal { ModuleMerger::ModuleMerger(const Logger &logger, Item *root, Item *moduleToMerge, const QualifiedId &moduleName) : m_logger(logger) , m_rootItem(root) , m_mergedModuleItem(moduleToMerge) , m_moduleName(moduleName) { } void ModuleMerger::start() { if (!m_mergedModuleItem->isPresentModule()) return; Item::Module m; m.item = m_rootItem; const Item::PropertyMap props = dfs(m, Item::PropertyMap()); Item::PropertyMap mergedProps = m_mergedModuleItem->properties(); Item *moduleProto = m_mergedModuleItem->prototype(); while (moduleProto->prototype()) moduleProto = moduleProto->prototype(); for (auto it = props.constBegin(); it != props.constEnd(); ++it) { appendPrototypeValueToNextChain(moduleProto, it.key(), it.value()); mergedProps[it.key()] = it.value(); } m_mergedModuleItem->setProperties(mergedProps); } Item::PropertyMap ModuleMerger::dfs(const Item::Module &m, Item::PropertyMap props) { Item *moduleInstance = 0; int numberOfOutprops = m.item->modules().count(); foreach (const Item::Module &dep, m.item->modules()) { if (dep.name == m_moduleName) { --numberOfOutprops; moduleInstance = dep.item; pushScalarProperties(&props, moduleInstance); break; } } QVector<Item::PropertyMap> outprops; outprops.reserve(numberOfOutprops); foreach (const Item::Module &dep, m.item->modules()) { if (dep.item != moduleInstance) outprops << dfs(dep, props); } if (!outprops.isEmpty()) { props = outprops.first(); for (int i = 1; i < outprops.count(); ++i) mergeOutProps(&props, outprops.at(i)); } if (moduleInstance) pullListProperties(&props, moduleInstance); return props; } void ModuleMerger::pushScalarProperties(Item::PropertyMap *dst, Item *srcItem) { Item *origSrcItem = srcItem; do { if (!m_seenInstancesTopDown.contains(srcItem)) { m_seenInstancesTopDown.insert(srcItem); for (auto it = srcItem->properties().constBegin(); it != srcItem->properties().constEnd(); ++it) { const ValuePtr &srcVal = it.value(); if (srcVal->type() != Value::JSSourceValueType) continue; const PropertyDeclaration srcDecl = srcItem->propertyDeclaration(it.key()); if (!srcDecl.isValid() || !srcDecl.isScalar()) continue; ValuePtr &v = (*dst)[it.key()]; if (v) continue; ValuePtr clonedVal = srcVal->clone(); m_decls[clonedVal] = srcDecl; clonedVal->setDefiningItem(origSrcItem); v = clonedVal; } } srcItem = srcItem->prototype(); } while (srcItem && srcItem->type() == ItemType::ModuleInstance); } void ModuleMerger::mergeOutProps(Item::PropertyMap *dst, const Item::PropertyMap &src) { for (auto it = src.constBegin(); it != src.constEnd(); ++it) { ValuePtr &v = (*dst)[it.key()]; if (!v) { v = it.value(); QBS_ASSERT(it.value(), continue); continue; } // possible conflict JSSourceValuePtr dstVal = v.dynamicCast<JSSourceValue>(); if (!dstVal) continue; JSSourceValuePtr srcVal = it.value().dynamicCast<JSSourceValue>(); if (!srcVal) continue; const PropertyDeclaration pd = m_decls.value(srcVal); if (!pd.isValid()) continue; if (pd.isScalar()) { if (dstVal->sourceCode() != srcVal->sourceCode() && dstVal->isInExportItem() == srcVal->isInExportItem()) { m_logger.qbsWarning() << Tr::tr("Conflicting scalar values at %1 and %2.").arg( dstVal->location().toString(), srcVal->location().toString()); // TODO: yield error with a hint how to solve the conflict. } if (!dstVal->isInExportItem()) v = it.value(); } else { lastInNextChain(dstVal)->setNext(srcVal); } } } void ModuleMerger::pullListProperties(Item::PropertyMap *dst, Item *instance) { Item *origInstance = instance; do { if (!m_seenInstancesBottomUp.contains(instance)) { m_seenInstancesBottomUp.insert(instance); for (Item::PropertyMap::const_iterator it = instance->properties().constBegin(); it != instance->properties().constEnd(); ++it) { const ValuePtr &srcVal = it.value(); if (srcVal->type() != Value::JSSourceValueType) continue; const PropertyDeclaration srcDecl = instance->propertyDeclaration(it.key()); if (!srcDecl.isValid() || srcDecl.isScalar()) continue; ValuePtr clonedVal = srcVal->clone(); m_decls[clonedVal] = srcDecl; clonedVal->setDefiningItem(origInstance); ValuePtr &v = (*dst)[it.key()]; if (v) { QBS_CHECK(!clonedVal->next()); clonedVal->setNext(v); } v = clonedVal; } } instance = instance->prototype(); } while (instance && instance->type() == ItemType::ModuleInstance); } void ModuleMerger::appendPrototypeValueToNextChain(Item *moduleProto, const QString &propertyName, const ValuePtr &sv) { const PropertyDeclaration pd = m_mergedModuleItem->propertyDeclaration(propertyName); if (pd.isScalar()) return; ValuePtr protoValue = moduleProto->property(propertyName); if (!protoValue) return; if (!m_clonedModulePrototype) { m_clonedModulePrototype = moduleProto->clone(); Item * const scope = Item::create(m_clonedModulePrototype->pool()); scope->setFile(m_clonedModulePrototype->file()); m_mergedModuleItem->scope()->copyProperty(QLatin1String("project"), scope); m_mergedModuleItem->scope()->copyProperty(QLatin1String("product"), scope); m_clonedModulePrototype->setScope(scope); } const ValuePtr clonedValue = protoValue->clone(); clonedValue->setDefiningItem(m_clonedModulePrototype); lastInNextChain(sv)->setNext(clonedValue); } ValuePtr ModuleMerger::lastInNextChain(const ValuePtr &v) { ValuePtr n = v; while (n->next()) n = n->next(); return n; } } // namespace Internal } // namespace qbs <commit_msg>ModuleMerger: Replace a check with an assertion.<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "modulemerger.h" #include "value.h" #include <logging/translator.h> #include <tools/qbsassert.h> namespace qbs { namespace Internal { ModuleMerger::ModuleMerger(const Logger &logger, Item *root, Item *moduleToMerge, const QualifiedId &moduleName) : m_logger(logger) , m_rootItem(root) , m_mergedModuleItem(moduleToMerge) , m_moduleName(moduleName) { } void ModuleMerger::start() { if (!m_mergedModuleItem->isPresentModule()) return; Item::Module m; m.item = m_rootItem; const Item::PropertyMap props = dfs(m, Item::PropertyMap()); Item::PropertyMap mergedProps = m_mergedModuleItem->properties(); Item *moduleProto = m_mergedModuleItem->prototype(); while (moduleProto->prototype()) moduleProto = moduleProto->prototype(); for (auto it = props.constBegin(); it != props.constEnd(); ++it) { appendPrototypeValueToNextChain(moduleProto, it.key(), it.value()); mergedProps[it.key()] = it.value(); } m_mergedModuleItem->setProperties(mergedProps); } Item::PropertyMap ModuleMerger::dfs(const Item::Module &m, Item::PropertyMap props) { Item *moduleInstance = 0; int numberOfOutprops = m.item->modules().count(); foreach (const Item::Module &dep, m.item->modules()) { if (dep.name == m_moduleName) { --numberOfOutprops; moduleInstance = dep.item; pushScalarProperties(&props, moduleInstance); break; } } QVector<Item::PropertyMap> outprops; outprops.reserve(numberOfOutprops); foreach (const Item::Module &dep, m.item->modules()) { if (dep.item != moduleInstance) outprops << dfs(dep, props); } if (!outprops.isEmpty()) { props = outprops.first(); for (int i = 1; i < outprops.count(); ++i) mergeOutProps(&props, outprops.at(i)); } if (moduleInstance) pullListProperties(&props, moduleInstance); return props; } void ModuleMerger::pushScalarProperties(Item::PropertyMap *dst, Item *srcItem) { Item *origSrcItem = srcItem; do { if (!m_seenInstancesTopDown.contains(srcItem)) { m_seenInstancesTopDown.insert(srcItem); for (auto it = srcItem->properties().constBegin(); it != srcItem->properties().constEnd(); ++it) { const ValuePtr &srcVal = it.value(); if (srcVal->type() != Value::JSSourceValueType) continue; const PropertyDeclaration srcDecl = srcItem->propertyDeclaration(it.key()); if (!srcDecl.isValid() || !srcDecl.isScalar()) continue; ValuePtr &v = (*dst)[it.key()]; if (v) continue; ValuePtr clonedVal = srcVal->clone(); m_decls[clonedVal] = srcDecl; clonedVal->setDefiningItem(origSrcItem); v = clonedVal; } } srcItem = srcItem->prototype(); } while (srcItem && srcItem->type() == ItemType::ModuleInstance); } void ModuleMerger::mergeOutProps(Item::PropertyMap *dst, const Item::PropertyMap &src) { for (auto it = src.constBegin(); it != src.constEnd(); ++it) { ValuePtr &v = (*dst)[it.key()]; if (!v) { v = it.value(); QBS_ASSERT(it.value(), continue); continue; } // possible conflict JSSourceValuePtr dstVal = v.dynamicCast<JSSourceValue>(); if (!dstVal) continue; JSSourceValuePtr srcVal = it.value().dynamicCast<JSSourceValue>(); if (!srcVal) continue; const PropertyDeclaration pd = m_decls.value(srcVal); QBS_CHECK(pd.isValid()); if (pd.isScalar()) { if (dstVal->sourceCode() != srcVal->sourceCode() && dstVal->isInExportItem() == srcVal->isInExportItem()) { m_logger.qbsWarning() << Tr::tr("Conflicting scalar values at %1 and %2.").arg( dstVal->location().toString(), srcVal->location().toString()); // TODO: yield error with a hint how to solve the conflict. } if (!dstVal->isInExportItem()) v = it.value(); } else { lastInNextChain(dstVal)->setNext(srcVal); } } } void ModuleMerger::pullListProperties(Item::PropertyMap *dst, Item *instance) { Item *origInstance = instance; do { if (!m_seenInstancesBottomUp.contains(instance)) { m_seenInstancesBottomUp.insert(instance); for (Item::PropertyMap::const_iterator it = instance->properties().constBegin(); it != instance->properties().constEnd(); ++it) { const ValuePtr &srcVal = it.value(); if (srcVal->type() != Value::JSSourceValueType) continue; const PropertyDeclaration srcDecl = instance->propertyDeclaration(it.key()); if (!srcDecl.isValid() || srcDecl.isScalar()) continue; ValuePtr clonedVal = srcVal->clone(); m_decls[clonedVal] = srcDecl; clonedVal->setDefiningItem(origInstance); ValuePtr &v = (*dst)[it.key()]; if (v) { QBS_CHECK(!clonedVal->next()); clonedVal->setNext(v); } v = clonedVal; } } instance = instance->prototype(); } while (instance && instance->type() == ItemType::ModuleInstance); } void ModuleMerger::appendPrototypeValueToNextChain(Item *moduleProto, const QString &propertyName, const ValuePtr &sv) { const PropertyDeclaration pd = m_mergedModuleItem->propertyDeclaration(propertyName); if (pd.isScalar()) return; ValuePtr protoValue = moduleProto->property(propertyName); if (!protoValue) return; if (!m_clonedModulePrototype) { m_clonedModulePrototype = moduleProto->clone(); Item * const scope = Item::create(m_clonedModulePrototype->pool()); scope->setFile(m_clonedModulePrototype->file()); m_mergedModuleItem->scope()->copyProperty(QLatin1String("project"), scope); m_mergedModuleItem->scope()->copyProperty(QLatin1String("product"), scope); m_clonedModulePrototype->setScope(scope); } const ValuePtr clonedValue = protoValue->clone(); clonedValue->setDefiningItem(m_clonedModulePrototype); lastInNextChain(sv)->setNext(clonedValue); } ValuePtr ModuleMerger::lastInNextChain(const ValuePtr &v) { ValuePtr n = v; while (n->next()) n = n->next(); return n; } } // namespace Internal } // namespace qbs <|endoftext|>
<commit_before>// vim:set ts=4 sw=4 ai: /* * Copyright (c) 2010-2013 BitTorrent, Inc. * * 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 <string.h> #include <assert.h> #include <stdio.h> #include "utp_types.h" #include "utp_hash.h" #include "utp_packedsockaddr.h" #ifdef WIN32 #include "win32_inet_ntop.h" #endif byte PackedSockAddr::get_family() const { #if defined(__sh__) return ((_sin6d[0] == 0) && (_sin6d[1] == 0) && (_sin6d[2] == htonl(0xffff)) != 0) ? AF_INET : AF_INET6; #else return (IN6_IS_ADDR_V4MAPPED(&_in._in6addr) != 0) ? AF_INET : AF_INET6; #endif // defined(__sh__) } bool PackedSockAddr::operator==(const PackedSockAddr& rhs) const { if (&rhs == this) return true; if (_port != rhs._port) return false; return memcmp(_sin6, rhs._sin6, sizeof(_sin6)) == 0; } bool PackedSockAddr::operator!=(const PackedSockAddr& rhs) const { return !(*this == rhs); } uint32 PackedSockAddr::compute_hash() const { return utp_hash_mem(&_in, sizeof(_in)) ^ _port; } void PackedSockAddr::set(const SOCKADDR_STORAGE* sa, socklen_t len) { if (sa->ss_family == AF_INET) { assert(len >= sizeof(sockaddr_in)); const sockaddr_in *sin = (sockaddr_in*)sa; _sin6w[0] = 0; _sin6w[1] = 0; _sin6w[2] = 0; _sin6w[3] = 0; _sin6w[4] = 0; _sin6w[5] = 0xffff; _sin4 = sin->sin_addr.s_addr; _port = ntohs(sin->sin_port); } else { assert(len >= sizeof(sockaddr_in6)); const sockaddr_in6 *sin6 = (sockaddr_in6*)sa; _in._in6addr = sin6->sin6_addr; _port = ntohs(sin6->sin6_port); } } PackedSockAddr::PackedSockAddr(const SOCKADDR_STORAGE* sa, socklen_t len) { set(sa, len); } PackedSockAddr::PackedSockAddr(void) { SOCKADDR_STORAGE sa; socklen_t len = sizeof(SOCKADDR_STORAGE); memset(&sa, 0, len); sa.ss_family = AF_INET; set(&sa, len); } SOCKADDR_STORAGE PackedSockAddr::get_sockaddr_storage(socklen_t *len = NULL) const { SOCKADDR_STORAGE sa; const byte family = get_family(); if (family == AF_INET) { sockaddr_in *sin = (sockaddr_in*)&sa; if (len) *len = sizeof(sockaddr_in); memset(sin, 0, sizeof(sockaddr_in)); sin->sin_family = family; sin->sin_port = htons(_port); sin->sin_addr.s_addr = _sin4; } else { sockaddr_in6 *sin6 = (sockaddr_in6*)&sa; memset(sin6, 0, sizeof(sockaddr_in6)); if (len) *len = sizeof(sockaddr_in6); sin6->sin6_family = family; sin6->sin6_addr = _in._in6addr; sin6->sin6_port = htons(_port); } return sa; } // #define addrfmt(x, s) x.fmt(s, sizeof(s)) cstr PackedSockAddr::fmt(str s, size_t len) const { memset(s, 0, len); const byte family = get_family(); str i; if (family == AF_INET) { libutp::inet_ntop(family, (uint32*)&_sin4, s, len); i = s; while (*++i) {} } else { i = s; *i++ = '['; libutp::inet_ntop(family, (in6_addr*)&_in._in6addr, i, len-1); while (*++i) {} *i++ = ']'; } snprintf(i, len - (i-s), ":%u", _port); return s; } <commit_msg>Fix compile error on Linux.<commit_after>// vim:set ts=4 sw=4 ai: /* * Copyright (c) 2010-2013 BitTorrent, Inc. * * 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 <string.h> #include <assert.h> #include <stdio.h> #include "utp_types.h" #include "utp_hash.h" #include "utp_packedsockaddr.h" #ifdef WIN32 #include "win32_inet_ntop.h" #endif byte PackedSockAddr::get_family() const { #if defined(__sh__) return ((_sin6d[0] == 0) && (_sin6d[1] == 0) && (_sin6d[2] == htonl(0xffff)) != 0) ? AF_INET : AF_INET6; #else return (IN6_IS_ADDR_V4MAPPED(&_in._in6addr) != 0) ? AF_INET : AF_INET6; #endif // defined(__sh__) } bool PackedSockAddr::operator==(const PackedSockAddr& rhs) const { if (&rhs == this) return true; if (_port != rhs._port) return false; return memcmp(_sin6, rhs._sin6, sizeof(_sin6)) == 0; } bool PackedSockAddr::operator!=(const PackedSockAddr& rhs) const { return !(*this == rhs); } uint32 PackedSockAddr::compute_hash() const { return utp_hash_mem(&_in, sizeof(_in)) ^ _port; } void PackedSockAddr::set(const SOCKADDR_STORAGE* sa, socklen_t len) { if (sa->ss_family == AF_INET) { assert(len >= sizeof(sockaddr_in)); const sockaddr_in *sin = (sockaddr_in*)sa; _sin6w[0] = 0; _sin6w[1] = 0; _sin6w[2] = 0; _sin6w[3] = 0; _sin6w[4] = 0; _sin6w[5] = 0xffff; _sin4 = sin->sin_addr.s_addr; _port = ntohs(sin->sin_port); } else { assert(len >= sizeof(sockaddr_in6)); const sockaddr_in6 *sin6 = (sockaddr_in6*)sa; _in._in6addr = sin6->sin6_addr; _port = ntohs(sin6->sin6_port); } } PackedSockAddr::PackedSockAddr(const SOCKADDR_STORAGE* sa, socklen_t len) { set(sa, len); } PackedSockAddr::PackedSockAddr(void) { SOCKADDR_STORAGE sa; socklen_t len = sizeof(SOCKADDR_STORAGE); memset(&sa, 0, len); sa.ss_family = AF_INET; set(&sa, len); } SOCKADDR_STORAGE PackedSockAddr::get_sockaddr_storage(socklen_t *len = NULL) const { SOCKADDR_STORAGE sa; const byte family = get_family(); if (family == AF_INET) { sockaddr_in *sin = (sockaddr_in*)&sa; if (len) *len = sizeof(sockaddr_in); memset(sin, 0, sizeof(sockaddr_in)); sin->sin_family = family; sin->sin_port = htons(_port); sin->sin_addr.s_addr = _sin4; } else { sockaddr_in6 *sin6 = (sockaddr_in6*)&sa; memset(sin6, 0, sizeof(sockaddr_in6)); if (len) *len = sizeof(sockaddr_in6); sin6->sin6_family = family; sin6->sin6_addr = _in._in6addr; sin6->sin6_port = htons(_port); } return sa; } // #define addrfmt(x, s) x.fmt(s, sizeof(s)) cstr PackedSockAddr::fmt(str s, size_t len) const { memset(s, 0, len); const byte family = get_family(); str i; if (family == AF_INET) { inet_ntop(family, (uint32*)&_sin4, s, len); i = s; while (*++i) {} } else { i = s; *i++ = '['; inet_ntop(family, (in6_addr*)&_in._in6addr, i, len-1); while (*++i) {} *i++ = ']'; } snprintf(i, len - (i-s), ":%u", _port); return s; } <|endoftext|>
<commit_before>/* * Copyright 2004-2014 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ParamForLoop.h" #include "AstVisitor.h" #include "build.h" #include "resolution.h" /************************************ | ************************************* * * * Factory methods for the Parser * * * ************************************* | ************************************/ BlockStmt* ParamForLoop::buildParamForLoop(VarSymbol* indexVar, Expr* range, BlockStmt* stmts) { VarSymbol* lowVar = newParamVar(); VarSymbol* highVar = newParamVar(); VarSymbol* strideVar = newParamVar(); LabelSymbol* breakLabel = new LabelSymbol("_breakLabel"); CallExpr* call = toCallExpr(range); Expr* low = NULL; Expr* high = NULL; Expr* stride = NULL; BlockStmt* outer = new BlockStmt(); if (call && call->isNamed("by")) { stride = call->get(2)->remove(); call = toCallExpr(call->get(1)); } else { stride = new SymExpr(new_IntSymbol(1)); } if (call && call->isNamed("_build_range")) { low = call->get(1)->remove(); high = call->get(1)->remove(); } else { USR_FATAL(range, "iterators for param-for-loops must be literal ranges"); } outer->insertAtTail(new DefExpr(indexVar, new_IntSymbol((int64_t) 0))); outer->insertAtTail(new DefExpr(lowVar)); outer->insertAtTail(new CallExpr(PRIM_MOVE, lowVar, low)); outer->insertAtTail(new DefExpr(highVar)); outer->insertAtTail(new CallExpr(PRIM_MOVE, highVar, high)); outer->insertAtTail(new DefExpr(strideVar)); outer->insertAtTail(new CallExpr(PRIM_MOVE, strideVar, stride)); outer->insertAtTail(new ParamForLoop(indexVar, lowVar, highVar, strideVar, breakLabel, stmts)); outer->insertAtTail(new DefExpr(breakLabel)); return buildChapelStmt(outer); } VarSymbol* ParamForLoop::newParamVar() { VarSymbol* retval = newTemp(); retval->addFlag(FLAG_MAYBE_PARAM); return retval; } /************************************ | ************************************* * * * Instance methods * * * ************************************* | ************************************/ ParamForLoop::ParamForLoop() : LoopStmt(0) { } ParamForLoop::ParamForLoop(VarSymbol* indexVar, VarSymbol* lowVar, VarSymbol* highVar, VarSymbol* strideVar, LabelSymbol* breakLabel, BlockStmt* initBody) : LoopStmt(initBody) { mIndexVariable = indexVar; mLowVariable = lowVar; mHighVariable = highVar; mStrideVariable = strideVar; breakLabelSet(breakLabel); BlockStmt::blockInfoSet(new CallExpr(PRIM_BLOCK_PARAM_LOOP, indexVar, lowVar, highVar, strideVar)); } ParamForLoop::~ParamForLoop() { } ParamForLoop* ParamForLoop::copy(SymbolMap* mapRef, bool internal) { SymbolMap localMap; SymbolMap* map = (mapRef != 0) ? mapRef : &localMap; CallExpr* blockInfo = paramInfoGet(); ParamForLoop* retval = new ParamForLoop(); retval->astloc = astloc; retval->blockTag = blockTag; retval->breakLabel = breakLabel; retval->continueLabel = continueLabel; if (blockInfo != 0) retval->BlockStmt::blockInfoSet(blockInfo->copy(map, true)); for_alist(expr, body) retval->insertAtTail(expr->copy(map, true)); if (internal == false) update_symbols(retval, map); return retval; } bool ParamForLoop::isParamForLoop() const { return true; } CallExpr* ParamForLoop::paramInfoGet() const { return BlockStmt::blockInfoGet(); } CallExpr* ParamForLoop::blockInfoGet() const { printf("Migration: ParamForLoop %12d Unexpected call to blockInfoGet()\n", id); return BlockStmt::blockInfoGet(); } CallExpr* ParamForLoop::blockInfoSet(CallExpr* expr) { printf("Migration: ParamForLoop %12d Unexpected call to blockInfoSet()\n", id); return BlockStmt::blockInfoSet(expr); } BlockStmt* ParamForLoop::copyBody(SymbolMap* map) { BlockStmt* retval = new BlockStmt(); retval->astloc = astloc; retval->blockTag = blockTag; retval->breakLabelSet (breakLabel); retval->continueLabelSet(continueLabel); if (modUses != 0) retval->modUses = modUses->copy(map, true); if (byrefVars != 0) retval->byrefVars = byrefVars->copy(map, true); for_alist(expr, body) retval->insertAtTail(expr->copy(map, true)); update_symbols(retval, map); return retval; } void ParamForLoop::accept(AstVisitor* visitor) { if (visitor->enterParamForLoop(this) == true) { for_alist(next_ast, body) next_ast->accept(visitor); if (paramInfoGet() != 0) paramInfoGet()->accept(visitor); if (modUses) modUses->accept(visitor); if (byrefVars) byrefVars->accept(visitor); visitor->exitParamForLoop(this); } } void ParamForLoop::verify() { BlockStmt::verify(); if (BlockStmt::blockInfoGet() == 0) INT_FATAL(this, "ParamForLoop::verify. blockInfo is NULL"); if (modUses != 0) INT_FATAL(this, "ParamForLoop::verify. modUses is not NULL"); if (byrefVars != 0) INT_FATAL(this, "ParamForLoop::verify. byrefVars is not NULL"); } GenRet ParamForLoop::codegen() { GenRet ret; INT_FATAL(this, "ParamForLoop::codegen This should be unreachable"); return ret; } // // The following functions support function resolution. // The first two functions support a post-order iteration over the AST. // It is important that the "loop header" is traversed before the body // could be visited. // // The second two functions are used to unroll the body of the loop // and then replace the loop with a NOP. // Expr* ParamForLoop::getFirstExpr() { Expr* retval = 0; if (paramInfoGet() != 0) retval = paramInfoGet()->getFirstExpr(); else if (body.head != 0) retval = body.head->getFirstExpr(); else retval = this; return retval; } Expr* ParamForLoop::getNextExpr(Expr* expr) { Expr* retval = this; if (expr == paramInfoGet() && body.head != 0) retval = body.head->getFirstExpr(); return retval; } CallExpr* ParamForLoop::foldForResolve() { CallExpr* loopInfo = paramInfoGet(); SymExpr* idxExpr = toSymExpr(loopInfo->get(1)); SymExpr* lse = toSymExpr(loopInfo->get(2)); SymExpr* hse = toSymExpr(loopInfo->get(3)); SymExpr* sse = toSymExpr(loopInfo->get(4)); if (!lse || !hse || !sse) USR_FATAL(loopInfo, "param for loop must be defined over a param range"); VarSymbol* lvar = toVarSymbol(lse->var); VarSymbol* hvar = toVarSymbol(hse->var); VarSymbol* svar = toVarSymbol(sse->var); CallExpr* noop = new CallExpr(PRIM_NOOP); if (!lvar || !hvar || !svar) USR_FATAL(loopInfo, "param for loop must be defined over a param range"); if (!lvar->immediate || !hvar->immediate || !svar->immediate) USR_FATAL(loopInfo, "param for loop must be defined over a param range"); Symbol* idxSym = idxExpr->var; Type* idxType = indexType(); IF1_int_type idxSize = (get_width(idxType) == 32) ? INT_SIZE_32 : INT_SIZE_64; // Insert an "insertion marker" for loop unrolling insertAfter(noop); if (is_int_type(idxType)) { int64_t low = lvar->immediate->int_value(); int64_t high = hvar->immediate->int_value(); int64_t stride = svar->immediate->int_value(); if (stride <= 0) { for (int64_t i = high; i >= low; i += stride) { SymbolMap map; map.put(idxSym, new_IntSymbol(i, idxSize)); noop->insertBefore(copyBody(&map)); } } else { for (int64_t i = low; i <= high; i += stride) { SymbolMap map; map.put(idxSym, new_IntSymbol(i, idxSize)); noop->insertBefore(copyBody(&map)); } } } else { INT_ASSERT(is_uint_type(idxType) || is_bool_type(idxType)); uint64_t low = lvar->immediate->uint_value(); uint64_t high = hvar->immediate->uint_value(); int64_t stride = svar->immediate->int_value(); if (stride <= 0) { for (uint64_t i = high; i >= low; i += stride) { SymbolMap map; map.put(idxSym, new_UIntSymbol(i, idxSize)); noop->insertBefore(copyBody(&map)); } } else { for (uint64_t i = low; i <= high; i += stride) { SymbolMap map; map.put(idxSym, new_UIntSymbol(i, idxSize)); noop->insertBefore(copyBody(&map)); } } } // Remove the "insertion marker" noop->remove(); // Replace the paramLoop with the NO-OP replace(noop); return noop; } // // Determine the index type for a ParamForLoop. // // This implementation creates a range with low/high values and then // asks for its type. // Type* ParamForLoop::indexType() { CallExpr* loopInfo = paramInfoGet(); SymExpr* lse = toSymExpr(loopInfo->get(2)); SymExpr* hse = toSymExpr(loopInfo->get(3)); CallExpr* range = new CallExpr("_build_range", lse->copy(), hse->copy()); Type* idxType = 0; insertBefore(range); resolveCall(range); if (FnSymbol* sym = range->isResolved()) { resolveFormals(sym); DefExpr* formal = toDefExpr(sym->formals.get(1)); if (toArgSymbol(formal->sym)->typeExpr) { idxType = toArgSymbol(formal->sym)->typeExpr->body.tail->typeInfo(); } else { idxType = formal->sym->type; } range->remove(); } else { INT_FATAL("unresolved range"); } return idxType; } <commit_msg>Whitespace 3<commit_after>/* * Copyright 2004-2014 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ParamForLoop.h" #include "AstVisitor.h" #include "build.h" #include "resolution.h" /************************************ | ************************************* * * * Factory methods for the Parser * * * ************************************* | ************************************/ BlockStmt* ParamForLoop::buildParamForLoop(VarSymbol* indexVar, Expr* range, BlockStmt* stmts) { VarSymbol* lowVar = newParamVar(); VarSymbol* highVar = newParamVar(); VarSymbol* strideVar = newParamVar(); LabelSymbol* breakLabel = new LabelSymbol("_breakLabel"); CallExpr* call = toCallExpr(range); Expr* low = NULL; Expr* high = NULL; Expr* stride = NULL; BlockStmt* outer = new BlockStmt(); if (call && call->isNamed("by")) { stride = call->get(2)->remove(); call = toCallExpr(call->get(1)); } else { stride = new SymExpr(new_IntSymbol(1)); } if (call && call->isNamed("_build_range")) { low = call->get(1)->remove(); high = call->get(1)->remove(); } else { USR_FATAL(range, "iterators for param-for-loops must be literal ranges"); } outer->insertAtTail(new DefExpr(indexVar, new_IntSymbol((int64_t) 0))); outer->insertAtTail(new DefExpr(lowVar)); outer->insertAtTail(new CallExpr(PRIM_MOVE, lowVar, low)); outer->insertAtTail(new DefExpr(highVar)); outer->insertAtTail(new CallExpr(PRIM_MOVE, highVar, high)); outer->insertAtTail(new DefExpr(strideVar)); outer->insertAtTail(new CallExpr(PRIM_MOVE, strideVar, stride)); outer->insertAtTail(new ParamForLoop(indexVar, lowVar, highVar, strideVar, breakLabel, stmts)); outer->insertAtTail(new DefExpr(breakLabel)); return buildChapelStmt(outer); } VarSymbol* ParamForLoop::newParamVar() { VarSymbol* retval = newTemp(); retval->addFlag(FLAG_MAYBE_PARAM); return retval; } /************************************ | ************************************* * * * Instance methods * * * ************************************* | ************************************/ ParamForLoop::ParamForLoop() : LoopStmt(0) { } ParamForLoop::ParamForLoop(VarSymbol* indexVar, VarSymbol* lowVar, VarSymbol* highVar, VarSymbol* strideVar, LabelSymbol* breakLabel, BlockStmt* initBody) : LoopStmt(initBody) { mIndexVariable = indexVar; mLowVariable = lowVar; mHighVariable = highVar; mStrideVariable = strideVar; breakLabelSet(breakLabel); BlockStmt::blockInfoSet(new CallExpr(PRIM_BLOCK_PARAM_LOOP, indexVar, lowVar, highVar, strideVar)); } ParamForLoop::~ParamForLoop() { } ParamForLoop* ParamForLoop::copy(SymbolMap* mapRef, bool internal) { SymbolMap localMap; SymbolMap* map = (mapRef != 0) ? mapRef : &localMap; CallExpr* blockInfo = paramInfoGet(); ParamForLoop* retval = new ParamForLoop(); retval->astloc = astloc; retval->blockTag = blockTag; retval->breakLabel = breakLabel; retval->continueLabel = continueLabel; if (blockInfo != 0) retval->BlockStmt::blockInfoSet(blockInfo->copy(map, true)); for_alist(expr, body) retval->insertAtTail(expr->copy(map, true)); if (internal == false) update_symbols(retval, map); return retval; } bool ParamForLoop::isParamForLoop() const { return true; } CallExpr* ParamForLoop::paramInfoGet() const { return BlockStmt::blockInfoGet(); } CallExpr* ParamForLoop::blockInfoGet() const { printf("Migration: ParamForLoop %12d Unexpected call to blockInfoGet()\n", id); return BlockStmt::blockInfoGet(); } CallExpr* ParamForLoop::blockInfoSet(CallExpr* expr) { printf("Migration: ParamForLoop %12d Unexpected call to blockInfoSet()\n", id); return BlockStmt::blockInfoSet(expr); } BlockStmt* ParamForLoop::copyBody(SymbolMap* map) { BlockStmt* retval = new BlockStmt(); retval->astloc = astloc; retval->blockTag = blockTag; retval->breakLabelSet (breakLabel); retval->continueLabelSet(continueLabel); if (modUses != 0) retval->modUses = modUses->copy(map, true); if (byrefVars != 0) retval->byrefVars = byrefVars->copy(map, true); for_alist(expr, body) retval->insertAtTail(expr->copy(map, true)); update_symbols(retval, map); return retval; } void ParamForLoop::accept(AstVisitor* visitor) { if (visitor->enterParamForLoop(this) == true) { for_alist(next_ast, body) next_ast->accept(visitor); if (paramInfoGet() != 0) paramInfoGet()->accept(visitor); if (modUses) modUses->accept(visitor); if (byrefVars) byrefVars->accept(visitor); visitor->exitParamForLoop(this); } } void ParamForLoop::verify() { BlockStmt::verify(); if (BlockStmt::blockInfoGet() == 0) INT_FATAL(this, "ParamForLoop::verify. blockInfo is NULL"); if (modUses != 0) INT_FATAL(this, "ParamForLoop::verify. modUses is not NULL"); if (byrefVars != 0) INT_FATAL(this, "ParamForLoop::verify. byrefVars is not NULL"); } GenRet ParamForLoop::codegen() { GenRet ret; INT_FATAL(this, "ParamForLoop::codegen This should be unreachable"); return ret; } // // The following functions support function resolution. // The first two functions support a post-order iteration over the AST. // It is important that the "loop header" is traversed before the body // could be visited. // // The second two functions are used to unroll the body of the loop // and then replace the loop with a NOP. // Expr* ParamForLoop::getFirstExpr() { Expr* retval = 0; if (paramInfoGet() != 0) retval = paramInfoGet()->getFirstExpr(); else if (body.head != 0) retval = body.head->getFirstExpr(); else retval = this; return retval; } Expr* ParamForLoop::getNextExpr(Expr* expr) { Expr* retval = this; if (expr == paramInfoGet() && body.head != 0) retval = body.head->getFirstExpr(); return retval; } CallExpr* ParamForLoop::foldForResolve() { CallExpr* loopInfo = paramInfoGet(); SymExpr* idxExpr = toSymExpr(loopInfo->get(1)); SymExpr* lse = toSymExpr(loopInfo->get(2)); SymExpr* hse = toSymExpr(loopInfo->get(3)); SymExpr* sse = toSymExpr(loopInfo->get(4)); if (!lse || !hse || !sse) USR_FATAL(loopInfo, "param for loop must be defined over a param range"); VarSymbol* lvar = toVarSymbol(lse->var); VarSymbol* hvar = toVarSymbol(hse->var); VarSymbol* svar = toVarSymbol(sse->var); CallExpr* noop = new CallExpr(PRIM_NOOP); if (!lvar || !hvar || !svar) USR_FATAL(loopInfo, "param for loop must be defined over a param range"); if (!lvar->immediate || !hvar->immediate || !svar->immediate) USR_FATAL(loopInfo, "param for loop must be defined over a param range"); Symbol* idxSym = idxExpr->var; Type* idxType = indexType(); IF1_int_type idxSize = (get_width(idxType) == 32) ? INT_SIZE_32 : INT_SIZE_64; // Insert an "insertion marker" for loop unrolling insertAfter(noop); if (is_int_type(idxType)) { int64_t low = lvar->immediate->int_value(); int64_t high = hvar->immediate->int_value(); int64_t stride = svar->immediate->int_value(); if (stride <= 0) { for (int64_t i = high; i >= low; i += stride) { SymbolMap map; map.put(idxSym, new_IntSymbol(i, idxSize)); noop->insertBefore(copyBody(&map)); } } else { for (int64_t i = low; i <= high; i += stride) { SymbolMap map; map.put(idxSym, new_IntSymbol(i, idxSize)); noop->insertBefore(copyBody(&map)); } } } else { INT_ASSERT(is_uint_type(idxType) || is_bool_type(idxType)); uint64_t low = lvar->immediate->uint_value(); uint64_t high = hvar->immediate->uint_value(); int64_t stride = svar->immediate->int_value(); if (stride <= 0) { for (uint64_t i = high; i >= low; i += stride) { SymbolMap map; map.put(idxSym, new_UIntSymbol(i, idxSize)); noop->insertBefore(copyBody(&map)); } } else { for (uint64_t i = low; i <= high; i += stride) { SymbolMap map; map.put(idxSym, new_UIntSymbol(i, idxSize)); noop->insertBefore(copyBody(&map)); } } } // Remove the "insertion marker" noop->remove(); // Replace the paramLoop with the NO-OP replace(noop); return noop; } // // Determine the index type for a ParamForLoop. // // This implementation creates a range with low/high values and then // asks for its type. // Type* ParamForLoop::indexType() { CallExpr* loopInfo = paramInfoGet(); SymExpr* lse = toSymExpr(loopInfo->get(2)); SymExpr* hse = toSymExpr(loopInfo->get(3)); CallExpr* range = new CallExpr("_build_range", lse->copy(), hse->copy()); Type* idxType = 0; insertBefore(range); resolveCall(range); if (FnSymbol* sym = range->isResolved()) { resolveFormals(sym); DefExpr* formal = toDefExpr(sym->formals.get(1)); if (toArgSymbol(formal->sym)->typeExpr) idxType = toArgSymbol(formal->sym)->typeExpr->body.tail->typeInfo(); else idxType = formal->sym->type; range->remove(); } else { INT_FATAL("unresolved range"); } return idxType; } <|endoftext|>
<commit_before>/* * * Copyright (c) 2020 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "RecordData.h" #include <inet/arpa-inet-compatibility.h> namespace mdns { namespace Minimal { bool ParseTxtRecord(const BytesRange & data, TxtRecordDelegate * callback) { // FORMAT: // length-prefixed strings of the form "foo=bar" where = may be missing const uint8_t * pos = data.Start(); while (data.Contains(pos)) { uint8_t length = *pos; if (!data.Contains(pos + length)) { return false; } pos++; // name=value string of size length const uint8_t * equalPos = pos; while ((*equalPos != '=') && ((equalPos - pos) < length)) { equalPos++; } if (pos + length == equalPos) { callback->OnRecord(BytesRange(pos, equalPos), BytesRange()); } else { callback->OnRecord(BytesRange(pos, equalPos), BytesRange(equalPos + 1, pos + length)); } pos += length; } return pos == data.End(); } bool SrvRecord::Parse(const BytesRange & data, const BytesRange & packet) { // FORMAT: // - priority // - weight // - port // - target if (data.Size() < 7) { return false; } const uint8_t * p = data.Start(); mPriority = chip::Encoding::BigEndian::Read16(p); mWeight = chip::Encoding::BigEndian::Read16(p); mPort = chip::Encoding::BigEndian::Read16(p); mName = SerializedQNameIterator(packet, p); return true; } bool ParseARecord(const BytesRange & data, chip::Inet::IPAddress * addr) { if (data.Size() != 4) { return false; } addr->Addr[0] = 0; addr->Addr[1] = 0; addr->Addr[2] = htonl(0xFFFF); addr->Addr[3] = htonl(chip::Encoding::BigEndian::Get32(data.Start())); return true; } bool ParseAAAARecord(const BytesRange & data, chip::Inet::IPAddress * addr) { if (data.Size() != 16) { return false; } const uint8_t * p = data.Start(); chip::Inet::IPAddress::ReadAddress(p, *addr); return true; } bool ParsePtrRecord(const BytesRange & data, const BytesRange & packet, SerializedQNameIterator * name) { if (data.Size() < 1) { return false; } *name = SerializedQNameIterator(packet, data.Start()); return true; } } // namespace Minimal } // namespace mdns <commit_msg>[asan] heap-buffer-overflow if the txt record does not contains an = and is the len field has the right size (#15917)<commit_after>/* * * Copyright (c) 2020 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "RecordData.h" #include <inet/arpa-inet-compatibility.h> #include <stdio.h> namespace mdns { namespace Minimal { bool ParseTxtRecord(const BytesRange & data, TxtRecordDelegate * callback) { // FORMAT: // length-prefixed strings of the form "foo=bar" where = may be missing const uint8_t * pos = data.Start(); while (data.Contains(pos)) { uint8_t length = *pos; if (!data.Contains(pos + length)) { return false; } // name=value string of size length const uint8_t * equalPos = pos + 1; while (((equalPos - pos) < length) && (*equalPos != '=')) { equalPos++; } if (pos + length == equalPos && *equalPos == '=') { // If there is an '=' sign with an empty value, just ignore it and position the end cursor directly onto // the position of the '=' callback->OnRecord(BytesRange(pos + 1, equalPos), BytesRange()); } else if (pos + length == equalPos && *equalPos != '=') { callback->OnRecord(BytesRange(pos + 1, equalPos + 1), BytesRange()); } else { callback->OnRecord(BytesRange(pos + 1, equalPos), BytesRange(equalPos + 1, pos + 1 + length)); } pos += 1 + length; } return pos == data.End(); } bool SrvRecord::Parse(const BytesRange & data, const BytesRange & packet) { // FORMAT: // - priority // - weight // - port // - target if (data.Size() < 7) { return false; } const uint8_t * p = data.Start(); mPriority = chip::Encoding::BigEndian::Read16(p); mWeight = chip::Encoding::BigEndian::Read16(p); mPort = chip::Encoding::BigEndian::Read16(p); mName = SerializedQNameIterator(packet, p); return true; } bool ParseARecord(const BytesRange & data, chip::Inet::IPAddress * addr) { if (data.Size() != 4) { return false; } addr->Addr[0] = 0; addr->Addr[1] = 0; addr->Addr[2] = htonl(0xFFFF); addr->Addr[3] = htonl(chip::Encoding::BigEndian::Get32(data.Start())); return true; } bool ParseAAAARecord(const BytesRange & data, chip::Inet::IPAddress * addr) { if (data.Size() != 16) { return false; } const uint8_t * p = data.Start(); chip::Inet::IPAddress::ReadAddress(p, *addr); return true; } bool ParsePtrRecord(const BytesRange & data, const BytesRange & packet, SerializedQNameIterator * name) { if (data.Size() < 1) { return false; } *name = SerializedQNameIterator(packet, data.Start()); return true; } } // namespace Minimal } // namespace mdns <|endoftext|>
<commit_before><commit_msg>Babi: read the question before answering, you silly<commit_after><|endoftext|>
<commit_before>#ifndef INCLUDED_SROOK_CXX17_MPL_RUN_LENGTH_HPP #define INCLUDED_SROOK_CXX17_MPL_RUN_LENGTH_HPP #include<srook/cxx17/mpl/any_pack.hpp> namespace srook{ inline namespace mpl{ inline namespace v1{ namespace detail{ template<std::size_t,auto,class> struct search_length; template<std::size_t counter,auto search,auto... tail> struct search_length<counter,search,any_pack<search,tail...>>{ static constexpr std::size_t value=search_length<counter+1,search,any_pack<tail...>>::value; using type=typename search_length<counter+1,search,any_pack<tail...>>::type; }; template<std::size_t counter,auto search,auto head,auto... tail> struct search_length<counter,search,any_pack<head,tail...>>{ static constexpr std::size_t value=counter; using type=any_pack<search,counter>; }; template<std::size_t counter,auto search> struct search_length<counter,search,any_pack<>>{ static constexpr std::size_t value=counter; using type=any_pack<search,counter>; }; template<auto search,class Anypack> using search_length_t=typename search_length<0,search,Anypack>::type; template<auto search,class Anypack> constexpr std::size_t search_length_v=search_length<0,search,Anypack>::value; template<class> struct run_length_impl; template<auto head,auto... tail> struct run_length_impl<any_pack<head,tail...>>{ private: using length_type=search_length_t<head,any_pack<head,tail...>>; static constexpr std::size_t length_value=search_length_v<head,any_pack<head,tail...>>; public: using type= detail::concat_t< std::conditional_t<(length_value>1),length_type,any_pack<head>>, typename run_length_impl< std::conditional_t< (length_value>1), typename any_pack<head,tail...>::template partial_tail_type<length_value>, any_pack<tail...> > >::type >; }; template<> struct run_length_impl<any_pack<>>{ using type=any_pack<>; }; } // inline namespace v1 } // inline namespace mpl } // namespace detail template<class Anypack> using run_length=typename detail::run_length_impl<Anypack>::type; } // namespace srook #endif <commit_msg>fix indent<commit_after>#ifndef INCLUDED_SROOK_CXX17_MPL_RUN_LENGTH_HPP #define INCLUDED_SROOK_CXX17_MPL_RUN_LENGTH_HPP #include<srook/cxx17/mpl/any_pack.hpp> namespace srook{ inline namespace mpl{ inline namespace v1{ namespace detail{ template<std::size_t,auto,class> struct search_length; template<std::size_t counter,auto search,auto... tail> struct search_length<counter,search,any_pack<search,tail...>>{ static constexpr std::size_t value=search_length<counter+1,search,any_pack<tail...>>::value; using type=typename search_length<counter+1,search,any_pack<tail...>>::type; }; template<std::size_t counter,auto search,auto head,auto... tail> struct search_length<counter,search,any_pack<head,tail...>>{ static constexpr std::size_t value=counter; using type=any_pack<search,counter>; }; template<std::size_t counter,auto search> struct search_length<counter,search,any_pack<>>{ static constexpr std::size_t value=counter; using type=any_pack<search,counter>; }; template<auto search,class Anypack> using search_length_t=typename search_length<0,search,Anypack>::type; template<auto search,class Anypack> constexpr std::size_t search_length_v=search_length<0,search,Anypack>::value; template<class> struct run_length_impl; template<auto head,auto... tail> struct run_length_impl<any_pack<head,tail...>>{ private: using length_type=search_length_t<head,any_pack<head,tail...>>; static constexpr std::size_t length_value=search_length_v<head,any_pack<head,tail...>>; public: using type= detail::concat_t< std::conditional_t<(length_value>1),length_type,any_pack<head>>, typename run_length_impl< std::conditional_t<(length_value>1),typename any_pack<head,tail...>::template partial_tail_type<length_value>,any_pack<tail...>>>::type >; }; template<> struct run_length_impl<any_pack<>>{ using type=any_pack<>; }; } // inline namespace v1 } // inline namespace mpl } // namespace detail template<class Anypack> using run_length=typename detail::run_length_impl<Anypack>::type; } // namespace srook #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_FUN_LOG_SUM_EXP_SIGNED_HPP #define STAN_MATH_PRIM_FUN_LOG_SUM_EXP_SIGNED_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/fun/constants.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/log1p_exp.hpp> #include <cmath> #include <vector> namespace stan { namespace math { /** * Return the log of the sum of the exponentiated values of the specified * matrix of values. The matrix may be a full matrix, a vector, * or a row vector. Additionally, a matching container of 'signs' indicates * whether the exponentiated input should be added or substracted * * The function is defined as follows to prevent overflow in exponential * calculations. * * \f$\log \sum_{n=1}^N \exp(x_n) = \max(x) + \log \sum_{n=1}^N \exp(x_n - * \max(x))\f$. * * @tparam T1 type of input vector or matrix * @tparam T2 type of signs vector or matrix * @param[in] x container of specified values * @param[in] signs container of signs * @return The log of the sum of the exponentiated vector values. */ template <typename T1, typename T2, require_container_st<std::is_arithmetic, T1>* = nullptr, require_container_st<std::is_integral, T2>* = nullptr> inline auto log_sum_exp_signed(const T1& x, const T2& signs) { return apply_vector_unary<T1>::reduce(x, [&](const auto& v) { if (v.size() == 0) { return NEGATIVE_INFTY; } const auto& v_ref = to_ref(to_vector(v)); const auto& signs_ref = to_ref(to_vector(signs)); const double max = v_ref.cwiseProduct(signs_ref).maxCoeff(); if (!std::isfinite(max)) { return max; } return max + std::log((v_ref.array() - max) .exp() .matrix() .cwiseProduct(signs_ref) .sum()); }); } } // namespace math } // namespace stan #endif <commit_msg>Include missed by header check<commit_after>#ifndef STAN_MATH_PRIM_FUN_LOG_SUM_EXP_SIGNED_HPP #define STAN_MATH_PRIM_FUN_LOG_SUM_EXP_SIGNED_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/fun/constants.hpp> #include <stan/math/prim/fun/to_vector.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/log1p_exp.hpp> #include <cmath> #include <vector> namespace stan { namespace math { /** * Return the log of the sum of the exponentiated values of the specified * matrix of values. The matrix may be a full matrix, a vector, * or a row vector. Additionally, a matching container of 'signs' indicates * whether the exponentiated input should be added or substracted * * The function is defined as follows to prevent overflow in exponential * calculations. * * \f$\log \sum_{n=1}^N \exp(x_n) = \max(x) + \log \sum_{n=1}^N \exp(x_n - * \max(x))\f$. * * @tparam T1 type of input vector or matrix * @tparam T2 type of signs vector or matrix * @param[in] x container of specified values * @param[in] signs container of signs * @return The log of the sum of the exponentiated vector values. */ template <typename T1, typename T2, require_container_st<std::is_arithmetic, T1>* = nullptr, require_container_st<std::is_integral, T2>* = nullptr> inline auto log_sum_exp_signed(const T1& x, const T2& signs) { return apply_vector_unary<T1>::reduce(x, [&](const auto& v) { if (v.size() == 0) { return NEGATIVE_INFTY; } const auto& v_ref = to_ref(to_vector(v)); const auto& signs_ref = to_ref(to_vector(signs)); const double max = v_ref.cwiseProduct(signs_ref).maxCoeff(); if (!std::isfinite(max)) { return max; } return max + std::log((v_ref.array() - max) .exp() .matrix() .cwiseProduct(signs_ref) .sum()); }); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>// // AppsFlyerBridge.hpp // ee_x_mobile_apps_flyer // // Created by eps on 6/26/18. // #ifndef EE_X_APPS_FLYER_BRIDGE_HPP #define EE_X_APPS_FLYER_BRIDGE_HPP #include "ee/CoreFwd.hpp" #include "ee/appsflyer/IAppsFlyerBridge.hpp" namespace ee { namespace appsflyer { class Bridge : public IBridge { public: Bridge(); virtual ~Bridge() override; virtual void initialize(const std::string& devKey, const std::string& appId) override; virtual std::string getDeviceId() const override; virtual void setDebugEnabled(bool enabled) override; virtual void trackEvent(const std::string& name, const std::map<std::string, std::string>& values) override; private: IMessageBridge& bridge_; }; } // namespace appsflyer } // namespace ee #endif /* EE_X_APPS_FLYER_BRIDGE_HPP */ <commit_msg>'[AUTO] :triumph: clang-format'<commit_after>// // AppsFlyerBridge.hpp // ee_x_mobile_apps_flyer // // Created by eps on 6/26/18. // #ifndef EE_X_APPS_FLYER_BRIDGE_HPP #define EE_X_APPS_FLYER_BRIDGE_HPP #include "ee/CoreFwd.hpp" #include "ee/appsflyer/IAppsFlyerBridge.hpp" namespace ee { namespace appsflyer { class Bridge : public IBridge { public: Bridge(); virtual ~Bridge() override; virtual void initialize(const std::string& devKey, const std::string& appId) override; virtual std::string getDeviceId() const override; virtual void setDebugEnabled(bool enabled) override; virtual void trackEvent(const std::string& name, const std::map<std::string, std::string>& values) override; private: IMessageBridge& bridge_; }; } // namespace appsflyer } // namespace ee #endif /* EE_X_APPS_FLYER_BRIDGE_HPP */ <|endoftext|>
<commit_before>#include "controller_node.h" #include <std_srvs/Empty.h> #include <iostream> Controller::Controller() : speedX_(0.05f), speedY_(0.05f), speedZ_(0.05f), speedYaw_(0.01f), goal_reached_(true), stick_to_plane_(false), sticking_distance_(1.0f) { std::cout << "Controller node started..." << std::endl; // get Ros parameters and set variables nh_.param("speedForward", speedX_, speedX_); nh_.param("speedRight", speedY_, speedY_); nh_.param("speedUp", speedZ_, speedZ_); nh_.param("speedYawn", speedYaw_, speedYaw_); // set subscriber and publisher sub_joy_ = nh_.subscribe<sensor_msgs::Joy>("joy", 10, &Controller::Callback, this); sub_mocap_pose_ = nh_.subscribe<geometry_msgs::TransformStamped>("euroc2/vrpn_client/estimated_transform", 10, &Controller::SetMocapPose, this); pub_pose_ = nh_.advertise<geometry_msgs::PoseStamped>("euroc2/command/pose", 1); // identity rotation matrix as quaternion tf::Quaternion q; q.setRPY(0,0,0); // init tf_mocap tf_mocap_.setOrigin( tf::Vector3(0,0,0) ); tf_mocap_.setRotation(q); // init transform transform_.setOrigin( tf::Vector3(0,0,0) ); transform_.setRotation(q); // TBD if we should be able to change this via launch file // init hover transform transform_hover_goal_.setOrigin( tf::Vector3(0,0,1) ); transform_hover_goal_.setRotation(q); } void Controller::SetMocapPose(const geometry_msgs::TransformStamped::ConstPtr& msg) { tf_mocap_.setOrigin( tf::Vector3(msg->transform.translation.x, msg->transform.translation.y, msg->transform.translation.z) ); tf_mocap_.setRotation( tf::Quaternion(msg->transform.rotation.x, msg->transform.rotation.y, msg->transform.rotation.z, msg->transform.rotation.w) ); if(!goal_reached_) { tf::Vector3 diff = transform_hover_goal_.getOrigin() - tf_mocap_.getOrigin(); if(diff.length() < 0.6f) { goal_reached_ = true; } else { if(diff.length() > 1.0f) { diff.normalize(); } transform_.setOrigin(diff); } } testPlanes(); // world transform tf::Transform curr_transform = tf_mocap_ * transform_; // convert tf into pose and publish the pose tf::Vector3 desired_pos = curr_transform.getOrigin(); tf::Quaternion desired_rot = curr_transform.getRotation(); geometry_msgs::PoseStamped pose; // set header pose.header.stamp = ros::Time::now(); pose.header.frame_id = "world"; // set pose pose.pose.position.x = desired_pos.x(); pose.pose.position.y = desired_pos.y(); pose.pose.position.z = desired_pos.z(); pose.pose.orientation.x = desired_rot.x(); pose.pose.orientation.y = desired_rot.y(); pose.pose.orientation.z = desired_rot.z(); pose.pose.orientation.w = desired_rot.w(); pub_pose_.publish(pose); // rviz debug br_tf_.sendTransform( tf::StampedTransform(curr_transform, ros::Time::now(), "world", "controller") ); } //void Controller::Callback(const sensor_msgs::Joy::ConstPtr& joy) { // prev_msg_ = joy; // // translation from controller axis // float jx = speedX_ * joy->axes[PS3_AXIS_STICK_RIGHT_UPWARDS]; // float jy = speedY_ * joy->axes[PS3_AXIS_STICK_RIGHT_LEFTWARDS]; // float jz = speedZ_ * joy->axes[PS3_AXIS_STICK_LEFT_UPWARDS]; // // yaw from axis // float jr = speedYaw_ * joy->axes[PS3_AXIS_STICK_LEFT_LEFTWARDS]; // // save only the latest relative transform in global transform // transform_.setOrigin( tf::Vector3(jx,jy,jz) ); // tf::Quaternion q; // q.setRPY(0, 0, jr); // transform_.setRotation(q); // // listen for take off button pressed // if(joy->buttons[PS3_BUTTON_PAIRING] || joy->buttons[PS3_BUTTON_START]) { // goal_reached_ = false; // TakeoffAndHover(); // } //} void Controller::Callback(const sensor_msgs::Joy::ConstPtr& joy) { prev_msg_ = joy; // translation from controller axis float jx = speedX_ * joy->axes[PS3_AXIS_STICK_RIGHT_UPWARDS]; float jy = speedY_ * joy->axes[PS3_AXIS_STICK_RIGHT_LEFTWARDS]; float jz = speedZ_ * joy->axes[PS3_AXIS_STICK_LEFT_UPWARDS]; // yaw from axis float jr = speedYaw_ * joy->axes[PS3_AXIS_STICK_LEFT_LEFTWARDS]; // save only the latest relative transform in global transform transform_.setOrigin( tf::Vector3(jx,jy,jz) ); tf::Quaternion q; q.setRPY(0, 0, jr); transform_.setRotation(q); // buttons if(joy->buttons[PS3_BUTTON_REAR_RIGHT_1]) { stick_to_plane_ = true; } if(joy->buttons[PS3_BUTTON_REAR_LEFT_1]) { stick_to_plane_ = false; } if(joy->buttons[PS3_BUTTON_CROSS_UP]) { sticking_distance_ -= 0.005f; } if(joy->buttons[PS3_BUTTON_CROSS_DOWN]) { sticking_distance_ += 0.005f; } if(stick_to_plane_) { Eigen::Vector3f proj_pos = testPlanes(); // world transform tf_mocap_.setOrigin( tf::Vector3(proj_pos.x(), proj_pos.y(), proj_pos.z()) ); tf_mocap_.setRotation( tf_mocap_.getRotation() * transform_.getRotation() ); } else { // world transform tf_mocap_ *= transform_; } // convert tf into pose and publish the pose tf::Vector3 desired_pos = tf_mocap_.getOrigin(); tf::Quaternion desired_rot = tf_mocap_.getRotation(); geometry_msgs::PoseStamped pose; // set header pose.header.stamp = ros::Time::now(); pose.header.frame_id = "world"; // set pose pose.pose.position.x = desired_pos.x(); pose.pose.position.y = desired_pos.y(); pose.pose.position.z = desired_pos.z(); pose.pose.orientation.x = desired_rot.x(); pose.pose.orientation.y = desired_rot.y(); pose.pose.orientation.z = desired_rot.z(); pose.pose.orientation.w = desired_rot.w(); pub_pose_.publish(pose); // rviz debug br_tf_.sendTransform( tf::StampedTransform(tf_mocap_, ros::Time::now(), "world", "controller") ); } void Controller::TakeoffAndHover() { std_srvs::Empty::Request request; std_srvs::Empty::Response response; if(ros::service::call("euroc2/takeoff", request, response)) { tf::Vector3 desired_pos = transform_hover_goal_.getOrigin(); tf::Quaternion desired_rot = transform_hover_goal_.getRotation(); geometry_msgs::PoseStamped pose; // set header pose.header.stamp = ros::Time::now(); pose.header.frame_id = "world"; // set pose pose.pose.position.x = desired_pos.x(); pose.pose.position.y = desired_pos.y(); pose.pose.position.z = desired_pos.z(); pose.pose.orientation.x = desired_rot.x(); pose.pose.orientation.y = desired_rot.y(); pose.pose.orientation.z = desired_rot.z(); pose.pose.orientation.w = desired_rot.w(); pub_pose_.publish(pose); } } void Controller::processPlaneMsg() { // TODO set active plane } // TODO rename // TBD maybe use tf instead of eigen for simplicity Eigen::Vector3f Controller::testPlanes() { // mav tf::Transform mav_tf = tf_mocap_ * transform_; Eigen::Vector3f mav_pos = Eigen::Vector3f( mav_tf.getOrigin().x(), mav_tf.getOrigin().y(), mav_tf.getOrigin().z()); Eigen::Quaternionf mav_rot = Eigen::Quaternionf( mav_tf.getRotation().x(), mav_tf.getRotation().y(), mav_tf.getRotation().z(), mav_tf.getRotation().w()); // rviz debug --> mav_tf.setOrigin( tf::Vector3(mav_pos.x(), mav_pos.y(), mav_pos.z()) ); br_tf_.sendTransform( tf::StampedTransform(mav_tf, ros::Time::now(), "world", "mav") ); // <-- // plane Eigen::Vector3f plane_pos = Eigen::Vector3f(2,0,0); tf::Quaternion plane_q; plane_q.setRPY(0,0,180.0f); Eigen::Quaternionf plane_rot = Eigen::Quaternionf(plane_q.x(),plane_q.y(),plane_q.z(),plane_q.w()); // rviz debug --> tf::Transform plane_tf; plane_tf.setOrigin( tf::Vector3(plane_pos.x(), plane_pos.y(), plane_pos.z()) ); plane_tf.setRotation(plane_q); br_tf_.sendTransform( tf::StampedTransform(plane_tf, ros::Time::now(), "world", "normal") ); // <-- // calculations Eigen::Vector3f normal = plane_rot*forward; Eigen::Vector3f proj_pos = mav_pos + (sticking_distance_-normal.dot(plane_pos-mav_pos))*normal; return proj_pos; } int main(int argc, char** argv) { ros::init(argc, argv, "te_joy_controller"); Controller rc; ros::spin(); } <commit_msg>Working version for position projection snapping for the controller.<commit_after>#include "controller_node.h" #include <std_srvs/Empty.h> #include <iostream> Controller::Controller() : speedX_(0.05f), speedY_(0.05f), speedZ_(0.05f), speedYaw_(0.01f), goal_reached_(true), stick_to_plane_(false), sticking_distance_(1.0f) { std::cout << "Controller node started..." << std::endl; // get Ros parameters and set variables nh_.param("speedForward", speedX_, speedX_); nh_.param("speedRight", speedY_, speedY_); nh_.param("speedUp", speedZ_, speedZ_); nh_.param("speedYawn", speedYaw_, speedYaw_); // set subscriber and publisher sub_joy_ = nh_.subscribe<sensor_msgs::Joy>("joy", 10, &Controller::Callback, this); sub_mocap_pose_ = nh_.subscribe<geometry_msgs::TransformStamped>("euroc2/vrpn_client/estimated_transform", 10, &Controller::SetMocapPose, this); pub_pose_ = nh_.advertise<geometry_msgs::PoseStamped>("euroc2/command/pose", 1); // identity rotation matrix as quaternion tf::Quaternion q; q.setRPY(0,0,0); // init tf_mocap tf_mocap_.setOrigin( tf::Vector3(0,0,0) ); tf_mocap_.setRotation(q); // init transform transform_.setOrigin( tf::Vector3(0,0,0) ); transform_.setRotation(q); // TBD if we should be able to change this via launch file // init hover transform transform_hover_goal_.setOrigin( tf::Vector3(0,0,1) ); transform_hover_goal_.setRotation(q); } void Controller::SetMocapPose(const geometry_msgs::TransformStamped::ConstPtr& msg) { tf_mocap_.setOrigin( tf::Vector3(msg->transform.translation.x, msg->transform.translation.y, msg->transform.translation.z) ); tf_mocap_.setRotation( tf::Quaternion(msg->transform.rotation.x, msg->transform.rotation.y, msg->transform.rotation.z, msg->transform.rotation.w) ); if(!goal_reached_) { tf::Vector3 diff = transform_hover_goal_.getOrigin() - tf_mocap_.getOrigin(); if(diff.length() < 0.6f) { goal_reached_ = true; } else { if(diff.length() > 1.0f) { diff.normalize(); } transform_.setOrigin(diff); } } testPlanes(); // world transform tf::Transform curr_transform = tf_mocap_ * transform_; // convert tf into pose and publish the pose tf::Vector3 desired_pos = curr_transform.getOrigin(); tf::Quaternion desired_rot = curr_transform.getRotation(); geometry_msgs::PoseStamped pose; // set header pose.header.stamp = ros::Time::now(); pose.header.frame_id = "world"; // set pose pose.pose.position.x = desired_pos.x(); pose.pose.position.y = desired_pos.y(); pose.pose.position.z = desired_pos.z(); pose.pose.orientation.x = desired_rot.x(); pose.pose.orientation.y = desired_rot.y(); pose.pose.orientation.z = desired_rot.z(); pose.pose.orientation.w = desired_rot.w(); pub_pose_.publish(pose); // rviz debug br_tf_.sendTransform( tf::StampedTransform(curr_transform, ros::Time::now(), "world", "controller") ); } //void Controller::Callback(const sensor_msgs::Joy::ConstPtr& joy) { // prev_msg_ = joy; // // translation from controller axis // float jx = speedX_ * joy->axes[PS3_AXIS_STICK_RIGHT_UPWARDS]; // float jy = speedY_ * joy->axes[PS3_AXIS_STICK_RIGHT_LEFTWARDS]; // float jz = speedZ_ * joy->axes[PS3_AXIS_STICK_LEFT_UPWARDS]; // // yaw from axis // float jr = speedYaw_ * joy->axes[PS3_AXIS_STICK_LEFT_LEFTWARDS]; // // save only the latest relative transform in global transform // transform_.setOrigin( tf::Vector3(jx,jy,jz) ); // tf::Quaternion q; // q.setRPY(0, 0, jr); // transform_.setRotation(q); // // listen for take off button pressed // if(joy->buttons[PS3_BUTTON_PAIRING] || joy->buttons[PS3_BUTTON_START]) { // goal_reached_ = false; // TakeoffAndHover(); // } //} void Controller::Callback(const sensor_msgs::Joy::ConstPtr& joy) { prev_msg_ = joy; // translation from controller axis float jx = speedX_ * joy->axes[PS3_AXIS_STICK_RIGHT_UPWARDS]; float jy = speedY_ * joy->axes[PS3_AXIS_STICK_RIGHT_LEFTWARDS]; float jz = speedZ_ * joy->axes[PS3_AXIS_STICK_LEFT_UPWARDS]; // yaw from axis float jr = speedYaw_ * joy->axes[PS3_AXIS_STICK_LEFT_LEFTWARDS]; // save only the latest relative transform in global transform transform_.setOrigin( tf::Vector3(jx,jy,jz) ); tf::Quaternion q; q.setRPY(0, 0, jr); transform_.setRotation(q); // buttons if(joy->buttons[PS3_BUTTON_REAR_RIGHT_1]) { stick_to_plane_ = true; } if(joy->buttons[PS3_BUTTON_REAR_LEFT_1]) { stick_to_plane_ = false; } if(joy->buttons[PS3_BUTTON_CROSS_UP]) { sticking_distance_ -= 0.005f; } if(joy->buttons[PS3_BUTTON_CROSS_DOWN]) { sticking_distance_ += 0.005f; } if(stick_to_plane_) { Eigen::Vector3f proj_pos = testPlanes(); // world transform // TODO } else { // world transform tf_mocap_ *= transform_; } // convert tf into pose and publish the pose tf::Vector3 desired_pos = tf_mocap_.getOrigin(); tf::Quaternion desired_rot = tf_mocap_.getRotation(); geometry_msgs::PoseStamped pose; // set header pose.header.stamp = ros::Time::now(); pose.header.frame_id = "world"; // set pose pose.pose.position.x = desired_pos.x(); pose.pose.position.y = desired_pos.y(); pose.pose.position.z = desired_pos.z(); pose.pose.orientation.x = desired_rot.x(); pose.pose.orientation.y = desired_rot.y(); pose.pose.orientation.z = desired_rot.z(); pose.pose.orientation.w = desired_rot.w(); pub_pose_.publish(pose); // rviz debug br_tf_.sendTransform( tf::StampedTransform(tf_mocap_, ros::Time::now(), "world", "controller") ); } void Controller::TakeoffAndHover() { std_srvs::Empty::Request request; std_srvs::Empty::Response response; if(ros::service::call("euroc2/takeoff", request, response)) { tf::Vector3 desired_pos = transform_hover_goal_.getOrigin(); tf::Quaternion desired_rot = transform_hover_goal_.getRotation(); geometry_msgs::PoseStamped pose; // set header pose.header.stamp = ros::Time::now(); pose.header.frame_id = "world"; // set pose pose.pose.position.x = desired_pos.x(); pose.pose.position.y = desired_pos.y(); pose.pose.position.z = desired_pos.z(); pose.pose.orientation.x = desired_rot.x(); pose.pose.orientation.y = desired_rot.y(); pose.pose.orientation.z = desired_rot.z(); pose.pose.orientation.w = desired_rot.w(); pub_pose_.publish(pose); } } void Controller::processPlaneMsg() { // TODO set active plane } // TODO rename // TBD maybe use tf instead of eigen for simplicity Eigen::Vector3f Controller::testPlanes() { // mav tf::Transform mav_tf = tf_mocap_ * transform_; Eigen::Vector3f mav_pos = Eigen::Vector3f( mav_tf.getOrigin().x(), mav_tf.getOrigin().y(), mav_tf.getOrigin().z()); Eigen::Quaternionf mav_rot = Eigen::Quaternionf( mav_tf.getRotation().x(), mav_tf.getRotation().y(), mav_tf.getRotation().z(), mav_tf.getRotation().w()); // rviz debug --> mav_tf.setOrigin( tf::Vector3(mav_pos.x(), mav_pos.y(), mav_pos.z()) ); br_tf_.sendTransform( tf::StampedTransform(mav_tf, ros::Time::now(), "world", "mav") ); // <-- // plane Eigen::Vector3f plane_pos = Eigen::Vector3f(2,0,0); tf::Quaternion plane_q; plane_q.setRPY(M_PI/18.0f,0,M_PI/180.0f); Eigen::Quaternionf plane_rot = Eigen::Quaternionf(plane_q.w(),plane_q.x(),plane_q.y(),plane_q.z()); // rviz debug --> tf::Transform plane_tf; plane_tf.setOrigin( tf::Vector3(plane_pos.x(), plane_pos.y(), plane_pos.z()) ); plane_tf.setRotation(plane_q); br_tf_.sendTransform( tf::StampedTransform(plane_tf, ros::Time::now(), "world", "normal") ); // <-- // calculations Eigen::Vector3f normal = plane_rot*forward; normal.normalize(); Eigen::Vector3f proj_pos = mav_pos + (sticking_distance_-normal.dot(mav_pos-plane_pos))*normal; // tmp here tf_mocap_.setOrigin( tf::Vector3(proj_pos.x(), proj_pos.y(), proj_pos.z()) ); tf_mocap_.setRotation( tf_mocap_.getRotation() * transform_.getRotation() ); return proj_pos; } int main(int argc, char** argv) { ros::init(argc, argv, "te_joy_controller"); Controller rc; ros::spin(); } <|endoftext|>
<commit_before>/** * Copyright (c) 2011-2018 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_NETWORK_PROTOCOL_HPP #define LIBBITCOIN_NETWORK_PROTOCOL_HPP #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <vector> #include <boost/date_time.hpp> #include <boost/filesystem.hpp> #include <bitcoin/bitcoin/constants.hpp> #include <bitcoin/bitcoin/config/authority.hpp> #include <bitcoin/bitcoin/config/endpoint.hpp> #include <bitcoin/bitcoin/define.hpp> #include <bitcoin/bitcoin/error.hpp> #include <bitcoin/bitcoin/message/network_address.hpp> #include <bitcoin/bitcoin/network/channel.hpp> #include <bitcoin/bitcoin/network/hosts.hpp> #include <bitcoin/bitcoin/network/initiator.hpp> #include <bitcoin/bitcoin/network/protocol_version.hpp> #include <bitcoin/bitcoin/network/seeder.hpp> #include <bitcoin/bitcoin/utility/subscriber.hpp> #include <bitcoin/bitcoin/utility/threadpool.hpp> namespace libbitcoin { namespace network { class BC_API protocol { public: typedef std::function<void(const code&)> completion_handler; typedef std::function<void(const code&, channel::ptr)> channel_handler; typedef std::function<void(const code&, channel::ptr)> broadcast_handler; typedef std::function<void(const code&, size_t)> fetch_connection_count_handler; protocol(threadpool& pool, hosts& hosts, initiator& network, uint16_t port=bc::protocol_port, bool relay=true, size_t max_outbound=8, size_t max_inbound=8, const config::endpoint::list& seeds=seeder::defaults, const config::authority& self=bc::unspecified_network_address, const timeout& timeouts=timeout::defaults); /// This class is not copyable. protocol(const protocol&) = delete; void operator=(const protocol&) = delete; void start(completion_handler handle_complete); void stop(completion_handler handle_complete); void blacklist(const config::authority& peer); void subscribe_channel(channel_handler handle_channel); void maintain_connection(const std::string& hostname, uint16_t port, bool relay=true, size_t retries=0); size_t connection_count() const; template <typename Message> void broadcast(const Message& packet, broadcast_handler handle_send) { dispatch_.queue( &protocol::do_broadcast<Message>, this, packet, handle_send); } private: typedef std::vector<channel::ptr> channel_ptr_list; typedef subscriber<const code&, channel::ptr> channel_subscriber; typedef channel_subscriber::ptr channel_subscriber_ptr; // Common to all connection types. void handle_handshake(const code& ec, channel::ptr node); void start_talking(channel::ptr node, channel_proxy::stop_handler handle_stop, bool relay); void remove_connection(channel_ptr_list& connections, channel::ptr node); // Inbound connections. void start_accepting(); void start_accept(const code& ec, acceptor::ptr accept); void handle_accept(const code& ec, channel::ptr node, acceptor::ptr accept); // Outbound connections. void new_connection(); void start_seeding(completion_handler handle_complete); void start_connecting(const code& ec, completion_handler handle_complete); void start_connect(const code& ec, const config::authority& peer); void handle_connect(const code& ec, channel::ptr node, const config::authority& peer); // Manual connections. void handle_manual_connect(const code& ec, channel::ptr node, const std::string& hostname, uint16_t port, bool relay, size_t retry); void retry_manual_connection(const config::endpoint& address, bool relay, size_t retry); // Remove channels from lists when disconnected. void inbound_channel_stopped(const code& ec, channel::ptr node, const std::string& hostname); void outbound_channel_stopped(const code& ec, channel::ptr node, const std::string& hostname); void manual_channel_stopped(const code& ec, channel::ptr node, const std::string& hostname, bool relay, size_t retries); // Channel metadata. bool is_blacklisted(const config::authority& peer) const; bool is_connected(const config::authority& peer) const; bool is_loopback(channel::ptr node) const; template <typename Message> void do_broadcast(const Message& packet, broadcast_handler handle_send) { for (const auto node: outbound_connections_) node->send(packet, [=](const code& ec){ handle_send(ec, node); }); for (const auto node: manual_connections_) node->send(packet, [=](const code& ec){ handle_send(ec, node); }); for (const auto node: inbound_connections_) node->send(packet, [=](const code& ec){ handle_send(ec, node); }); } dispatcher dispatch_; threadpool& pool_; hosts& hosts_; initiator& network_; std::shared_ptr<protocol_version> handshake_; channel_subscriber_ptr channel_subscriber_; // Configuration. const config::endpoint::list& seeds_; const config::authority self_; const timeout& timeouts_; uint16_t inbound_port_; size_t max_inbound_; size_t max_outbound_; bool relay_; channel_ptr_list manual_connections_; channel_ptr_list inbound_connections_; channel_ptr_list outbound_connections_; config::authority::list blacklisted_; }; } // namespace network } // namespace libbitcoin #endif <commit_msg>Restore MSVC generic lambda workaround.<commit_after>/** * Copyright (c) 2011-2018 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_NETWORK_PROTOCOL_HPP #define LIBBITCOIN_NETWORK_PROTOCOL_HPP #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <vector> #include <boost/date_time.hpp> #include <boost/filesystem.hpp> #include <bitcoin/bitcoin/constants.hpp> #include <bitcoin/bitcoin/config/authority.hpp> #include <bitcoin/bitcoin/config/endpoint.hpp> #include <bitcoin/bitcoin/define.hpp> #include <bitcoin/bitcoin/error.hpp> #include <bitcoin/bitcoin/message/network_address.hpp> #include <bitcoin/bitcoin/network/channel.hpp> #include <bitcoin/bitcoin/network/hosts.hpp> #include <bitcoin/bitcoin/network/initiator.hpp> #include <bitcoin/bitcoin/network/protocol_version.hpp> #include <bitcoin/bitcoin/network/seeder.hpp> #include <bitcoin/bitcoin/utility/subscriber.hpp> #include <bitcoin/bitcoin/utility/threadpool.hpp> namespace libbitcoin { namespace network { class BC_API protocol { public: typedef std::function<void(const code&)> completion_handler; typedef std::function<void(const code&, channel::ptr)> channel_handler; typedef std::function<void(const code&, channel::ptr)> broadcast_handler; typedef std::function<void(const code&, size_t)> fetch_connection_count_handler; protocol(threadpool& pool, hosts& hosts, initiator& network, uint16_t port=bc::protocol_port, bool relay=true, size_t max_outbound=8, size_t max_inbound=8, const config::endpoint::list& seeds=seeder::defaults, const config::authority& self=bc::unspecified_network_address, const timeout& timeouts=timeout::defaults); /// This class is not copyable. protocol(const protocol&) = delete; void operator=(const protocol&) = delete; void start(completion_handler handle_complete); void stop(completion_handler handle_complete); void blacklist(const config::authority& peer); void subscribe_channel(channel_handler handle_channel); void maintain_connection(const std::string& hostname, uint16_t port, bool relay=true, size_t retries=0); size_t connection_count() const; template <typename Message> void broadcast(const Message& packet, broadcast_handler handle_send) { // Intermediate variable is workaround for MSVC generic lambda issue. const auto lambda = &protocol::do_broadcast<Message>; dispatch_.queue(lambda, this, packet, handle_send); } private: typedef std::vector<channel::ptr> channel_ptr_list; typedef subscriber<const code&, channel::ptr> channel_subscriber; typedef channel_subscriber::ptr channel_subscriber_ptr; // Common to all connection types. void handle_handshake(const code& ec, channel::ptr node); void start_talking(channel::ptr node, channel_proxy::stop_handler handle_stop, bool relay); void remove_connection(channel_ptr_list& connections, channel::ptr node); // Inbound connections. void start_accepting(); void start_accept(const code& ec, acceptor::ptr accept); void handle_accept(const code& ec, channel::ptr node, acceptor::ptr accept); // Outbound connections. void new_connection(); void start_seeding(completion_handler handle_complete); void start_connecting(const code& ec, completion_handler handle_complete); void start_connect(const code& ec, const config::authority& peer); void handle_connect(const code& ec, channel::ptr node, const config::authority& peer); // Manual connections. void handle_manual_connect(const code& ec, channel::ptr node, const std::string& hostname, uint16_t port, bool relay, size_t retry); void retry_manual_connection(const config::endpoint& address, bool relay, size_t retry); // Remove channels from lists when disconnected. void inbound_channel_stopped(const code& ec, channel::ptr node, const std::string& hostname); void outbound_channel_stopped(const code& ec, channel::ptr node, const std::string& hostname); void manual_channel_stopped(const code& ec, channel::ptr node, const std::string& hostname, bool relay, size_t retries); // Channel metadata. bool is_blacklisted(const config::authority& peer) const; bool is_connected(const config::authority& peer) const; bool is_loopback(channel::ptr node) const; template <typename Message> void do_broadcast(const Message& packet, broadcast_handler handle_send) { for (const auto node: outbound_connections_) node->send(packet, [=](const code& ec){ handle_send(ec, node); }); for (const auto node: manual_connections_) node->send(packet, [=](const code& ec){ handle_send(ec, node); }); for (const auto node: inbound_connections_) node->send(packet, [=](const code& ec){ handle_send(ec, node); }); } dispatcher dispatch_; threadpool& pool_; hosts& hosts_; initiator& network_; std::shared_ptr<protocol_version> handshake_; channel_subscriber_ptr channel_subscriber_; // Configuration. const config::endpoint::list& seeds_; const config::authority self_; const timeout& timeouts_; uint16_t inbound_port_; size_t max_inbound_; size_t max_outbound_; bool relay_; channel_ptr_list manual_connections_; channel_ptr_list inbound_connections_; channel_ptr_list outbound_connections_; config::authority::list blacklisted_; }; } // namespace network } // namespace libbitcoin #endif <|endoftext|>
<commit_before>/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_NETWORK_SETTINGS_HPP #define LIBBITCOIN_NETWORK_SETTINGS_HPP #include <cstdint> #include <boost/filesystem.hpp> #include <bitcoin/bitcoin/config/authority.hpp> #include <bitcoin/bitcoin/config/endpoint.hpp> #include <bitcoin/bitcoin/define.hpp> namespace libbitcoin { namespace network { // This is in network vs. config because plan to move to libbitcoin-network. struct BC_API settings { uint32_t threads; uint16_t inbound_port; uint32_t inbound_connection_limit; uint32_t outbound_connections; uint32_t connect_timeout_seconds; uint32_t channel_handshake_seconds; uint32_t channel_revival_minutes; uint32_t channel_heartbeat_minutes; uint32_t channel_inactivity_minutes; uint32_t channel_expiration_minutes; uint32_t host_pool_capacity; bool relay_transactions; boost::filesystem::path hosts_file; boost::filesystem::path debug_file; boost::filesystem::path error_file; config::authority self; config::endpoint::list seeds; }; } // namespace network } // namespace libbitcoin #endif <commit_msg>Add germination to settings.<commit_after>/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_NETWORK_SETTINGS_HPP #define LIBBITCOIN_NETWORK_SETTINGS_HPP #include <cstdint> #include <boost/filesystem.hpp> #include <bitcoin/bitcoin/config/authority.hpp> #include <bitcoin/bitcoin/config/endpoint.hpp> #include <bitcoin/bitcoin/define.hpp> namespace libbitcoin { namespace network { // This is in network vs. config because plan to move to libbitcoin-network. struct BC_API settings { uint32_t threads; uint16_t inbound_port; uint32_t inbound_connection_limit; uint32_t outbound_connections; uint32_t connect_timeout_seconds; uint32_t channel_handshake_seconds; uint32_t channel_revival_minutes; uint32_t channel_heartbeat_minutes; uint32_t channel_inactivity_minutes; uint32_t channel_expiration_minutes; uint32_t channel_germination_seconds; uint32_t host_pool_capacity; bool relay_transactions; boost::filesystem::path hosts_file; boost::filesystem::path debug_file; boost::filesystem::path error_file; config::authority self; config::endpoint::list seeds; }; } // namespace network } // namespace libbitcoin #endif <|endoftext|>
<commit_before>/* ** Copyright 2009-2012 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cassert> #include <cstdlib> #include <memory> #include <QMutexLocker> #include <QQueue> #include <QVector> #include <utility> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/multiplexing/internal.hh" #include "com/centreon/broker/multiplexing/subscriber.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::multiplexing; /************************************** * * * Local Objects * * * **************************************/ // Hooks. static QVector<std::pair<hooker*, bool> > _hooks; static QVector<std::pair<hooker*, bool> >::iterator _hooks_begin; static QVector<std::pair<hooker*, bool> >::iterator _hooks_end; // Pointer. std::auto_ptr<engine> engine::_instance; // Data queue. static QQueue<misc::shared_ptr<io::data> > _kiew; // Mutex. static QMutex _mutex(QMutex::Recursive); // Processing flag. static bool _processing; /************************************** * * * Public Methods * * * **************************************/ /** * Destructor. */ engine::~engine() {} /** * Set a hook. * * @param[in] h Hook. * @param[in] data Write data to hook. */ void engine::hook(hooker& h, bool data) { QMutexLocker lock(&_mutex); _hooks.push_back(std::make_pair(&h, data)); _hooks_begin = _hooks.begin(); _hooks_end = _hooks.end(); return ; } /** * Get engine instance. * * @return Class instance. */ engine& engine::instance() { return (*_instance); } /** * Load engine instance. */ void engine::load() { _instance.reset(new engine); return ; } /** * Send an event to all subscribers. * * @param[in] e Event to publish. */ void engine::publish(misc::shared_ptr<io::data> const& e) { // Lock mutex. QMutexLocker lock(&_mutex); // Store object for further processing. _kiew.enqueue(e); // Processing function. (this->*_write_func)(e); return ; } /** * Start multiplexing. */ void engine::start() { if (_write_func != &engine::_write) { // Set writing method. logging::debug(logging::high) << "multiplexing: starting"; _write_func = &engine::_write; // Copy event queue. QMutexLocker lock(&_mutex); QQueue<misc::shared_ptr<io::data> > kiew(_kiew); _kiew.clear(); // Notify hooks of multiplexing loop start. for (QVector<std::pair<hooker*, bool> >::iterator it(_hooks_begin), end(_hooks_end); it != end; ++it) { it->first->starting(); // Read events from hook. misc::shared_ptr<io::data> d; it->first->read(d); while (!d.isNull()) { _kiew.enqueue(d); it->first->read(d); } } // Process events from hooks. _send_to_subscribers(); // Send events queued while multiplexing was stopped. while (!kiew.isEmpty()) { publish(kiew.head()); kiew.dequeue(); } } return ; } /** * Stop multiplexing. */ void engine::stop() { if (_write_func != &engine::_nop) { // Notify hooks of multiplexing loop end. logging::debug(logging::high) << "multiplexing: stopping"; QMutexLocker lock(&_mutex); for (QVector<std::pair<hooker*, bool> >::iterator it(_hooks_begin), end(_hooks_end); it != end; ++it) { it->first->stopping(); // Read events from hook. misc::shared_ptr<io::data> d; it->first->read(d); while (!d.isNull()) { _kiew.enqueue(d); it->first->read(d); } } // Process events from hooks. _send_to_subscribers(); // Set writing method. _write_func = &engine::_nop; } return ; } /** * Remove a hook. * * @param[in] h Hook. */ void engine::unhook(hooker& h) { QMutexLocker lock(&_mutex); for (QVector<std::pair<hooker*, bool> >::iterator it(_hooks_begin); it != _hooks.end();) if (it->first == &h) it = _hooks.erase(it); else ++it; _hooks_begin = _hooks.begin(); _hooks_end = _hooks.end(); return ; } /** * Unload class instance. */ void engine::unload() { _instance.reset(); return ; } /************************************** * * * Private Methods * * * **************************************/ /** * Default constructor. */ engine::engine() : _write_func(&engine::_nop) { // Initialize hook iterators. _hooks_begin = _hooks.begin(); _hooks_end = _hooks.end(); } /** * @brief Copy constructor. * * Any call to this constructor will result in a call to abort(). * * @param[in] e Unused. */ engine::engine(engine const& e) : QObject() { (void)e; assert(!"multiplexing engine is not copyable"); abort(); } /** * @brief Assignment operator. * * Any call to this method will result in a call to abort(). * * @param[in] e Unused. * * @return This object. */ engine& engine::operator=(engine const& p) { (void)p; assert(!"multiplexing engine is not copyable"); abort(); return (*this); } /** * Do nothing. * * @param[in] d Unused. */ void engine::_nop(misc::shared_ptr<io::data> const& d) { (void)d; return ; } /** * On hook object destruction. * * @param[in] obj Destroyed object. */ void engine::_on_hook_destroy(QObject* obj) { QMutexLocker lock(&_mutex); for (QVector<std::pair<hooker*, bool> >::iterator it = _hooks.begin(); it != _hooks.end();) if (it->first == obj) it = _hooks.erase(it); else ++it; return ; } /** * Send queued events to subscribers. */ void engine::_send_to_subscribers() { // Process all queued events. QMutexLocker lock(&gl_subscribersm); while (!_kiew.isEmpty()) { // Send object to every subscriber. for (QVector<subscriber*>::iterator it = gl_subscribers.begin(), end = gl_subscribers.end(); it != end; ++it) (*it)->write(_kiew.head()); _kiew.dequeue(); } return ; } /** * Publish event. * * @param[in] d Data to publish. */ void engine::_write(misc::shared_ptr<io::data> const& e) { if (!_processing) { // Set processing flag. _processing = true; try { // Send object to every hook. for (QVector<std::pair<hooker*, bool> >::iterator it(_hooks_begin), end(_hooks_end); it != end; ++it) if (it->second) { it->first->write(e); misc::shared_ptr<io::data> d; it->first->read(d); while (!d.isNull()) { _kiew.enqueue(d); it->first->read(d); } } // Send events to subscribers. _send_to_subscribers(); // Reset processing flag. _processing = false; } catch (...) { // Reset processing flag. _processing = false; throw ; } } return ; } <commit_msg>multiplexing: ignore exceptions when reading from hooks.<commit_after>/* ** Copyright 2009-2012 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cassert> #include <cstdlib> #include <memory> #include <QMutexLocker> #include <QQueue> #include <QVector> #include <utility> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/multiplexing/internal.hh" #include "com/centreon/broker/multiplexing/subscriber.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::multiplexing; /************************************** * * * Local Objects * * * **************************************/ // Hooks. static QVector<std::pair<hooker*, bool> > _hooks; static QVector<std::pair<hooker*, bool> >::iterator _hooks_begin; static QVector<std::pair<hooker*, bool> >::iterator _hooks_end; // Pointer. std::auto_ptr<engine> engine::_instance; // Data queue. static QQueue<misc::shared_ptr<io::data> > _kiew; // Mutex. static QMutex _mutex(QMutex::Recursive); // Processing flag. static bool _processing; /************************************** * * * Public Methods * * * **************************************/ /** * Destructor. */ engine::~engine() {} /** * Set a hook. * * @param[in] h Hook. * @param[in] data Write data to hook. */ void engine::hook(hooker& h, bool data) { QMutexLocker lock(&_mutex); _hooks.push_back(std::make_pair(&h, data)); _hooks_begin = _hooks.begin(); _hooks_end = _hooks.end(); return ; } /** * Get engine instance. * * @return Class instance. */ engine& engine::instance() { return (*_instance); } /** * Load engine instance. */ void engine::load() { _instance.reset(new engine); return ; } /** * Send an event to all subscribers. * * @param[in] e Event to publish. */ void engine::publish(misc::shared_ptr<io::data> const& e) { // Lock mutex. QMutexLocker lock(&_mutex); // Store object for further processing. _kiew.enqueue(e); // Processing function. (this->*_write_func)(e); return ; } /** * Start multiplexing. */ void engine::start() { if (_write_func != &engine::_write) { // Set writing method. logging::debug(logging::high) << "multiplexing: starting"; _write_func = &engine::_write; // Copy event queue. QMutexLocker lock(&_mutex); QQueue<misc::shared_ptr<io::data> > kiew(_kiew); _kiew.clear(); // Notify hooks of multiplexing loop start. for (QVector<std::pair<hooker*, bool> >::iterator it(_hooks_begin), end(_hooks_end); it != end; ++it) { it->first->starting(); // Read events from hook. misc::shared_ptr<io::data> d; it->first->read(d); while (!d.isNull()) { _kiew.enqueue(d); it->first->read(d); } } // Process events from hooks. _send_to_subscribers(); // Send events queued while multiplexing was stopped. while (!kiew.isEmpty()) { publish(kiew.head()); kiew.dequeue(); } } return ; } /** * Stop multiplexing. */ void engine::stop() { if (_write_func != &engine::_nop) { // Notify hooks of multiplexing loop end. logging::debug(logging::high) << "multiplexing: stopping"; QMutexLocker lock(&_mutex); for (QVector<std::pair<hooker*, bool> >::iterator it(_hooks_begin), end(_hooks_end); it != end; ++it) { it->first->stopping(); // Read events from hook. try { misc::shared_ptr<io::data> d; it->first->read(d); while (!d.isNull()) { _kiew.enqueue(d); it->first->read(d); } } catch (...) {} } // Process events from hooks. _send_to_subscribers(); // Set writing method. _write_func = &engine::_nop; } return ; } /** * Remove a hook. * * @param[in] h Hook. */ void engine::unhook(hooker& h) { QMutexLocker lock(&_mutex); for (QVector<std::pair<hooker*, bool> >::iterator it(_hooks_begin); it != _hooks.end();) if (it->first == &h) it = _hooks.erase(it); else ++it; _hooks_begin = _hooks.begin(); _hooks_end = _hooks.end(); return ; } /** * Unload class instance. */ void engine::unload() { _instance.reset(); return ; } /************************************** * * * Private Methods * * * **************************************/ /** * Default constructor. */ engine::engine() : _write_func(&engine::_nop) { // Initialize hook iterators. _hooks_begin = _hooks.begin(); _hooks_end = _hooks.end(); } /** * @brief Copy constructor. * * Any call to this constructor will result in a call to abort(). * * @param[in] e Unused. */ engine::engine(engine const& e) : QObject() { (void)e; assert(!"multiplexing engine is not copyable"); abort(); } /** * @brief Assignment operator. * * Any call to this method will result in a call to abort(). * * @param[in] e Unused. * * @return This object. */ engine& engine::operator=(engine const& p) { (void)p; assert(!"multiplexing engine is not copyable"); abort(); return (*this); } /** * Do nothing. * * @param[in] d Unused. */ void engine::_nop(misc::shared_ptr<io::data> const& d) { (void)d; return ; } /** * On hook object destruction. * * @param[in] obj Destroyed object. */ void engine::_on_hook_destroy(QObject* obj) { QMutexLocker lock(&_mutex); for (QVector<std::pair<hooker*, bool> >::iterator it = _hooks.begin(); it != _hooks.end();) if (it->first == obj) it = _hooks.erase(it); else ++it; return ; } /** * Send queued events to subscribers. */ void engine::_send_to_subscribers() { // Process all queued events. QMutexLocker lock(&gl_subscribersm); while (!_kiew.isEmpty()) { // Send object to every subscriber. for (QVector<subscriber*>::iterator it = gl_subscribers.begin(), end = gl_subscribers.end(); it != end; ++it) (*it)->write(_kiew.head()); _kiew.dequeue(); } return ; } /** * Publish event. * * @param[in] d Data to publish. */ void engine::_write(misc::shared_ptr<io::data> const& e) { if (!_processing) { // Set processing flag. _processing = true; try { // Send object to every hook. for (QVector<std::pair<hooker*, bool> >::iterator it(_hooks_begin), end(_hooks_end); it != end; ++it) if (it->second) { it->first->write(e); misc::shared_ptr<io::data> d; it->first->read(d); while (!d.isNull()) { _kiew.enqueue(d); it->first->read(d); } } // Send events to subscribers. _send_to_subscribers(); // Reset processing flag. _processing = false; } catch (...) { // Reset processing flag. _processing = false; throw ; } } return ; } <|endoftext|>
<commit_before>#ifndef __AJOKKI_CALLBACKS_HPP_INCLUDED #define __AJOKKI_CALLBACKS_HPP_INCLUDED #include "cpp/ylikuutio/common/any_value.hpp" #include "cpp/ylikuutio/callback_system/callback_parameter.hpp" #include "cpp/ylikuutio/callback_system/callback_object.hpp" #include "cpp/ylikuutio/callback_system/callback_engine.hpp" namespace ajokki { datatypes::AnyValue* glfwTerminate_cleanup( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* full_cleanup( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* exit_program( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*>); datatypes::AnyValue* exit_console( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* delete_suzanne_species( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* switch_to_new_material( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* transform_into_new_species( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); } #endif <commit_msg>Cleaning up: Added empty lines between function declarations.<commit_after>#ifndef __AJOKKI_CALLBACKS_HPP_INCLUDED #define __AJOKKI_CALLBACKS_HPP_INCLUDED #include "cpp/ylikuutio/common/any_value.hpp" #include "cpp/ylikuutio/callback_system/callback_parameter.hpp" #include "cpp/ylikuutio/callback_system/callback_object.hpp" #include "cpp/ylikuutio/callback_system/callback_engine.hpp" namespace ajokki { datatypes::AnyValue* glfwTerminate_cleanup( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* full_cleanup( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* exit_program( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*>); datatypes::AnyValue* exit_console( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* delete_suzanne_species( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* switch_to_new_material( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); datatypes::AnyValue* transform_into_new_species( callback_system::CallbackEngine*, callback_system::CallbackObject*, std::vector<callback_system::CallbackParameter*> input_parameters); } #endif <|endoftext|>
<commit_before>// Vsevolod Ivanov #include <string> #include <iostream> #include <opendht.h> #include <opendht/dht_proxy_client.h> int main(int argc, char * argv[]) { auto hash = dht::InfoHash::get(argv[1]); dht::DhtProxyClient client {[](){}, "127.0.0.1:8080", "client_id"}; auto &io_context = client.httpIOContext(); dht::Value::Filter filter; client.get(hash, [](const dht::Sp<dht::Value>& value){ printf("[get1::cb] value=%s\n", value->toString().c_str()); return true; },[](bool ok){ printf("[get1::donecb] ok=%i\n", ok); }, std::move(filter)); dht::Value value {"slenderman"}; client.put(hash, std::move(value), [&](bool ok){ printf("[put1::donecb] ok=%i\n", ok); }); client.listen(hash, [&](const std::vector<dht::Sp<dht::Value>>& values, bool expired){ printf("[listen1::cb] values = "); for (const auto &value: values) std::cout << value->toString() << " "; std::cout << std::endl; return true; }, std::move(filter)); client.listen(hash, [&](const std::vector<dht::Sp<dht::Value>>& values, bool expired){ printf("[listen2::cb] values = "); for (const auto &value: values) std::cout << value->toString() << " "; std::cout << std::endl; return true; }, std::move(filter)); dht::Value value2 {"spidergurl"}; client.put(hash, std::move(value2), [&](bool ok){ printf("[put2::donecb] ok=%i\n", ok); }); while (true) io_context.run(); return 0; } <commit_msg>cpp/opendht: add logger to async client<commit_after>// Vsevolod Ivanov #include <string> #include <iostream> #include <opendht.h> #include <opendht/log.h> #include <opendht/dht_proxy_client.h> int main(int argc, char * argv[]) { auto hash = dht::InfoHash::get(argv[1]); std::shared_ptr<dht::Logger> logger = dht::log::getStdLogger(); dht::DhtProxyClient client([](){}, "127.0.0.1:8080", "client_id", logger); auto &io_context = client.httpIOContext(); client.get(hash, [&](const dht::Sp<dht::Value>& value){ logger->d("[get1::cb] value=%s", value->toString().c_str()); return true; },[&](bool ok){ logger->d("[get1::donecb] ok=%i", ok); }); dht::Value value {"slenderman"}; client.put(hash, std::move(value), [&](bool ok){ logger->d("[put1::donecb] ok=%i", ok); }); client.listen(hash, [&](const std::vector<dht::Sp<dht::Value>>& values, bool expired){ std::stringstream ss; ss << "[listen1::cb] values = "; for (const auto &value: values) ss << value->toString() << " "; logger->d(ss.str().c_str()); return true; }); client.listen(hash, [&](const std::vector<dht::Sp<dht::Value>>& values, bool expired){ std::stringstream ss; ss << "[listen1::cb] values = "; for (const auto &value: values) ss << value->toString() << " "; logger->d(ss.str().c_str()); return true; }); dht::Value value2 {"spidergurl"}; client.put(hash, std::move(value2), [&](bool ok){ logger->d("[put2::donecb] ok=%i", ok); }); while (true) io_context.run(); return 0; } <|endoftext|>
<commit_before>#include "dacloud.hpp" #include <iostream> #include <sstream> #include <thread> using namespace Da; void threadop(size_t i, std::shared_ptr<DaCloud> dc, std::shared_ptr<DaCloudHeaders> dh, DaCloudProperties dp) { auto dd = std::make_shared<DaCloudDetect>(*dc, *dh, dp); std::cout << "thread " << i << ", model: " << dp["model"]->value.s << std::endl; } int main(int argc, char *argv[]) { if (argc < 2) exit(-1); std::string configpath(argv[1]); const std::string uakey = "user-agent"; const std::string uavalue = "iPhone"; auto dc = std::make_shared<DaCloud>(configpath); auto dh = std::make_shared<DaCloudHeaders>(); DaCloudProperties dp = DaCloudProperties(); dh->Add(uakey, uavalue); auto dd = std::make_shared<DaCloudDetect>(*dc, *dh, dp); for (auto p: dp) { std::cout << p.first << ": "; switch (p.second->type) { case DA_CLOUD_LONG: case DA_CLOUD_BOOL: std::cout << p.second->value.l << std::endl;; break; default: std::cout << p.second->value.s << std::endl; break; } } std::cout << dp.size() << " properties" << std::endl; std::cout << "cache key : " << dd->CacheKey() << std::endl; std::cout << "cache source : " << dd->CacheSource() << std::endl; std::thread td[2] { std::thread(threadop, 0, dc, dh, dp), std::thread(threadop, 1, dc, dh, dp) }; for (size_t i = 0; i < 2; i ++) td[i].join(); } <commit_msg>more threads for C++ wrapper<commit_after>#include "dacloud.hpp" #include <iostream> #include <sstream> #include <thread> using namespace Da; void threadop(size_t i, std::shared_ptr<DaCloud> dc, std::shared_ptr<DaCloudHeaders> dh, DaCloudProperties dp) { auto dd = std::make_shared<DaCloudDetect>(*dc, *dh, dp); std::cout << "thread " << i << ", model: " << dp["model"]->value.s << std::endl; } int main(int argc, char *argv[]) { if (argc < 2) exit(-1); std::string configpath(argv[1]); const std::string uakey = "user-agent"; const std::string uavalue = "iPhone"; auto dc = std::make_shared<DaCloud>(configpath); auto dh = std::make_shared<DaCloudHeaders>(); DaCloudProperties dp = DaCloudProperties(); dh->Add(uakey, uavalue); auto dd = std::make_shared<DaCloudDetect>(*dc, *dh, dp); for (auto p: dp) { std::cout << p.first << ": "; switch (p.second->type) { case DA_CLOUD_LONG: case DA_CLOUD_BOOL: std::cout << p.second->value.l << std::endl;; break; default: std::cout << p.second->value.s << std::endl; break; } } std::cout << dp.size() << " properties" << std::endl; std::cout << "cache key : " << dd->CacheKey() << std::endl; std::cout << "cache source : " << dd->CacheSource() << std::endl; std::thread td[10]; for (size_t i = 0; i < sizeof(td) / sizeof(td[0]); i ++) td[i] = std::thread(threadop, i, dc, dh, dp); for (size_t i = 0; i < sizeof(td) / sizeof(td[0]); i ++) td[i].join(); } <|endoftext|>
<commit_before>/** * Copyright (c) 2016, Loïc BLOT <loic.blot@unix-experience.fr> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. **/ #include <pwd.h> #include <unistd.h> #include <sys/param.h> #include <iostream> #include <sstream> #include <cstring> #include <stdlib.h> #include "host_utils.h" /* // normal mode %{^[[0;38;5;231;48;5;31;1m%} nerzhul %{^[[0;38;5;31;48;5;240;22m%} %{^[[0;38;5;252;48;5;240;1m%}~ %{^[[0;38;5;240;49;22m%} %{^[[0m%} // ssh mode %{^[[0;38;5;220;48;5;166m%}  Nerz-PC %{^[[0;38;5;166;48;5;31;22m%} %{^[[0;38;5;231;48;5;31;1m%}nerzhul %{^[[0;38;5;31;48;5;240;22m%} %{^[[0;38;5;252;48;5;240;1m%}~ %{^[[0;38;5;240;49;22m%} %{^[[0m%} // root mode %{^[[0;38;5;231;48;5;160;1m%} root %{^[[0;38;5;160;48;5;240;22m%} %{^[[0;38;5;252;48;5;240;1m%}~ %{^[[0;38;5;240;49;22m%} %{^[[0m%} // long path %{^[[0;38;5;220;48;5;166m%}  Nerz-PC %{^[[0;38;5;166;48;5;31;22m%} %{^[[0;38;5;231;48;5;31;1m%}nerzhul %{^[[0;38;5;31;48;5;240;22m%} %{^[[0;38;5;250;48;5;240m%}⋯ %{^[[0;38;5;245;48;5;240;22m%} %{^[[0;38;5;250;48;5;240m%}lib %{^[[0;38;5;245;48;5;240;22m%} %{^[[0;38;5;250;48;5;240m%}jvm %{^[[0;38;5;245;48;5;240;22m%} %{^[[0;38;5;252;48;5;240;1m%}java-8-openjdk %{^[[0;38;5;240;49;22m%} %{^[[0m%} */ void show_prompt () { struct passwd *pwd; uid_t uid = getuid(); const char* default_username = "?"; char* username; if ((pwd = getpwuid(getuid())) != NULL) { username = pwd->pw_name; } else { username = (char*) default_username; } char path_buf[MAXPATHLEN]; char* path = getcwd(path_buf, sizeof(path_buf)); std::string path_cpp11 = "?"; if (path != NULL) { uint16_t slash_count = 0; for (char *p = path; *p; ++p) { if (*p == '/') { slash_count++; } } // slash case is special if (strcmp(path, "/") == 0) { path_cpp11 = "%{\u001B[0;38;5;252;48;5;240;1m%}/"; } else { path_cpp11 = std::string(path, strlen(path)); size_t index = 0; while (true) { index = path_cpp11.find("/", index); if (index == std::string::npos) break; slash_count--; std::string replacement; if (slash_count == 0) { replacement = (index == 0) ? "%{\u001B[0;38;5;252;48;5;240;22m%}/  %{\u001B[0;38;5;250;48;5;240;1m%}" : "%{\u001B[0;38;5;252;48;5;240;22m%}  %{\u001B[0;38;5;250;48;5;240;1m%}"; } else { replacement = (index == 0) ? "%{\u001B[0;38;5;245;48;5;240;22m%}/  %{\u001B[0;38;5;250;48;5;240m%}" : "%{\u001B[0;38;5;245;48;5;240;22m%}  %{\u001B[0;38;5;250;48;5;240m%}"; } path_cpp11.replace(index, 1, replacement); index += replacement.length(); } } } static char remote_prefix[128] = ""; if (getenv("SSH_CONNECTION")) { static char hostname_buf[64]; get_hostname(hostname_buf, sizeof(hostname_buf)); sprintf(remote_prefix, "%%{\u001B[0;38;5;220;48;5;166m%%} \uE0A2 %s ", hostname_buf); } printf("%s%%{\u001B[0;38;5;231;48;5;%s;1m%%} %s %%{\u001B[0;38;5;%s" ";48;5;240;1m%%}\uE0B0 %s " "%%{\u001B[0;38;5;240;49;22m%%} %%{\u001B[0m%%}", remote_prefix, (uid == 0 ? "160" : "31"), username, (uid == 0 ? "160" : "31"), path_cpp11.c_str()); } void usage (const char* program_name) { printf("Usage: %s [prompt,rprompt]\n", program_name); } int main (int argc, const char* argv[]) { if (argc != 2) { usage(argv[0]); return 1; } if (strcmp(argv[1], "prompt") == 0) { show_prompt(); } else { usage(argv[0]); return 2; } return 0; } <commit_msg>Prepare rprompt detection and detect current git commit<commit_after>/** * Copyright (c) 2016, Loïc BLOT <loic.blot@unix-experience.fr> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. **/ #include <pwd.h> #include <unistd.h> #include <sys/param.h> #include <iostream> #include <sstream> #include <cstring> #include <stdlib.h> #include <regex.h> #include <git2/types.h> #include "host_utils.h" /* // normal mode %{^[[0;38;5;231;48;5;31;1m%} nerzhul %{^[[0;38;5;31;48;5;240;22m%} %{^[[0;38;5;252;48;5;240;1m%}~ %{^[[0;38;5;240;49;22m%} %{^[[0m%} // ssh mode %{^[[0;38;5;220;48;5;166m%}  Nerz-PC %{^[[0;38;5;166;48;5;31;22m%} %{^[[0;38;5;231;48;5;31;1m%}nerzhul %{^[[0;38;5;31;48;5;240;22m%} %{^[[0;38;5;252;48;5;240;1m%}~ %{^[[0;38;5;240;49;22m%} %{^[[0m%} // root mode %{^[[0;38;5;231;48;5;160;1m%} root %{^[[0;38;5;160;48;5;240;22m%} %{^[[0;38;5;252;48;5;240;1m%}~ %{^[[0;38;5;240;49;22m%} %{^[[0m%} // long path %{^[[0;38;5;220;48;5;166m%}  Nerz-PC %{^[[0;38;5;166;48;5;31;22m%} %{^[[0;38;5;231;48;5;31;1m%}nerzhul %{^[[0;38;5;31;48;5;240;22m%} %{^[[0;38;5;250;48;5;240m%}⋯ %{^[[0;38;5;245;48;5;240;22m%} %{^[[0;38;5;250;48;5;240m%}lib %{^[[0;38;5;245;48;5;240;22m%} %{^[[0;38;5;250;48;5;240m%}jvm %{^[[0;38;5;245;48;5;240;22m%} %{^[[0;38;5;252;48;5;240;1m%}java-8-openjdk %{^[[0;38;5;240;49;22m%} %{^[[0m%} */ void show_prompt () { struct passwd *pwd; uid_t uid = getuid(); const char* default_username = "?"; char* username; if ((pwd = getpwuid(getuid())) != NULL) { username = pwd->pw_name; } else { username = (char*) default_username; } char path_buf[MAXPATHLEN]; char* path = getcwd(path_buf, sizeof(path_buf)); std::string path_cpp11 = "?"; if (path != NULL) { uint16_t slash_count = 0; for (char *p = path; *p; ++p) { if (*p == '/') { slash_count++; } } // slash case is special if (strcmp(path, "/") == 0) { path_cpp11 = "%{\u001B[0;38;5;252;48;5;240;1m%}/"; } else { path_cpp11 = std::string(path, strlen(path)); size_t index = 0; while (true) { index = path_cpp11.find("/", index); if (index == std::string::npos) break; slash_count--; std::string replacement; if (slash_count == 0) { replacement = (index == 0) ? "%{\u001B[0;38;5;252;48;5;240;22m%}/  %{\u001B[0;38;5;250;48;5;240;1m%}" : "%{\u001B[0;38;5;252;48;5;240;22m%}  %{\u001B[0;38;5;250;48;5;240;1m%}"; } else { replacement = (index == 0) ? "%{\u001B[0;38;5;245;48;5;240;22m%}/  %{\u001B[0;38;5;250;48;5;240m%}" : "%{\u001B[0;38;5;245;48;5;240;22m%}  %{\u001B[0;38;5;250;48;5;240m%}"; } path_cpp11.replace(index, 1, replacement); index += replacement.length(); } } } static char remote_prefix[128] = ""; if (getenv("SSH_CONNECTION")) { static char hostname_buf[64]; get_hostname(hostname_buf, sizeof(hostname_buf)); sprintf(remote_prefix, "%%{\u001B[0;38;5;220;48;5;166m%%} \uE0A2 %s ", hostname_buf); } printf("%s%%{\u001B[0;38;5;231;48;5;%s;1m%%} %s %%{\u001B[0;38;5;%s" ";48;5;240;1m%%}\uE0B0 %s " "%%{\u001B[0;38;5;240;49;22m%%} %%{\u001B[0m%%}", remote_prefix, (uid == 0 ? "160" : "31"), username, (uid == 0 ? "160" : "31"), path_cpp11.c_str()); } void show_rprompt() { char git_commit[48]; bzero(git_commit, sizeof(git_commit)); // Search for git commit static char path_buf[MAXPATHLEN]; char* path = getcwd(path_buf, sizeof(path_buf)); if (path != NULL) { std::string path_str(path, strlen(path)); uint16_t slash_count = 0; for (char *p = path; *p; ++p) { if (*p == '/') { slash_count++; } } // Search .git/HEAD in current folder and upper for (uint16_t i = 0; i < slash_count; i++) { std::string git_path = path_str; for (uint16_t j = 0; j < i; j++) { git_path += "/.."; } git_path += "/.git/HEAD"; if (access(git_path.c_str(), F_OK) != -1) { FILE* f = fopen(git_path.c_str(), "r"); if (f == NULL) { break; } char* line_buf; size_t line_len; ssize_t read_len; // Read first line if ((read_len = getline(&line_buf, &line_len, f)) != -1) { // First check it's a git branch name regex_t regex; int regex_rs = regcomp(&regex, "^ref: refs/heads/(.+)\n", REG_EXTENDED); if (regex_rs != 0) { fprintf(stderr, "Non compilable regex for git!\n"); fclose(f); break; } size_t max_groups = 2; regmatch_t matches[max_groups]; regex_rs = regexec(&regex, (const char*)line_buf, max_groups, matches, 0); // Now verify it's a branch if (regex_rs == REG_NOERROR) { for (uint8_t g = 1; g < max_groups && matches[g].rm_so != -1; g++) { int ncpy_char = matches[g].rm_eo - matches[g].rm_so; // We shoud not copy more than 127 characters to have a consistent result if (ncpy_char > 47) { ncpy_char = 47; } strncpy(git_commit, line_buf + matches[g].rm_so, (size_t) ncpy_char); } } // This is a commit ID else if (read_len == 41) { strncpy(git_commit, line_buf, 7); } regfree(&regex); } fclose(f); // Leave the git search loop break; } } } std::cout << git_commit << std::endl; } void usage (const char* program_name) { printf("Usage: %s [prompt,rprompt]\n", program_name); } int main (int argc, const char* argv[]) { if (argc != 2) { usage(argv[0]); return 1; } if (strcmp(argv[1], "prompt") == 0) { show_prompt(); } else if (strcmp(argv[1], "rprompt") == 0) { show_rprompt(); } else { usage(argv[0]); return 2; } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #pragma once #include "core/shared_ptr.hh" #include "core/distributed.hh" class filter_tracker { lw_shared_ptr<distributed<filter_tracker>> _ptr; uint64_t false_positive; uint64_t true_positive; uint64_t last_false_positive = 0; uint64_t last_true_positive = 0; uint64_t local_false_positive() { return false_positive; } uint64_t local_true_positive() { return true_positive; } uint64_t local_recent_false_positive() { auto t = false_positive - last_false_positive; last_false_positive = false_positive; return t; } uint64_t local_recent_true_positive() { auto t = true_positive - last_true_positive; last_true_positive = true_positive; return t; } public: filter_tracker(lw_shared_ptr<distributed<filter_tracker>>&& ptr) : _ptr(std::move(ptr)) {} future<> stop() { return make_ready_future<>(); } void add_false_positive() { false_positive++; } void add_true_positive() { true_positive++; } future<uint64_t> get_false_positive() { return _ptr->map_reduce(adder<uint64_t>(), [] (auto& t) { return t.local_false_positive(); }); } future<uint64_t> get_true_positive() { return _ptr->map_reduce(adder<uint64_t>(), [] (auto& t) { return t.local_true_positive(); }); } future<uint64_t> get_recent_false_positive() { return _ptr->map_reduce(adder<uint64_t>(), [] (auto& t) { return t.local_recent_false_positive(); }); } future<uint64_t> get_recent_true_positive() { return _ptr->map_reduce(adder<uint64_t>(), [] (auto& t) { return t.local_recent_true_positive(); }); } }; <commit_msg>filter: initialize all statistics<commit_after>/* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #pragma once #include "core/shared_ptr.hh" #include "core/distributed.hh" class filter_tracker { lw_shared_ptr<distributed<filter_tracker>> _ptr; uint64_t false_positive = 0; uint64_t true_positive = 0; uint64_t last_false_positive = 0; uint64_t last_true_positive = 0; uint64_t local_false_positive() { return false_positive; } uint64_t local_true_positive() { return true_positive; } uint64_t local_recent_false_positive() { auto t = false_positive - last_false_positive; last_false_positive = false_positive; return t; } uint64_t local_recent_true_positive() { auto t = true_positive - last_true_positive; last_true_positive = true_positive; return t; } public: filter_tracker(lw_shared_ptr<distributed<filter_tracker>>&& ptr) : _ptr(std::move(ptr)) {} future<> stop() { return make_ready_future<>(); } void add_false_positive() { false_positive++; } void add_true_positive() { true_positive++; } future<uint64_t> get_false_positive() { return _ptr->map_reduce(adder<uint64_t>(), [] (auto& t) { return t.local_false_positive(); }); } future<uint64_t> get_true_positive() { return _ptr->map_reduce(adder<uint64_t>(), [] (auto& t) { return t.local_true_positive(); }); } future<uint64_t> get_recent_false_positive() { return _ptr->map_reduce(adder<uint64_t>(), [] (auto& t) { return t.local_recent_false_positive(); }); } future<uint64_t> get_recent_true_positive() { return _ptr->map_reduce(adder<uint64_t>(), [] (auto& t) { return t.local_recent_true_positive(); }); } }; <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * * bootstrap.cpp * file description * * Copyright(c) 2015, CMU * * /peloton/src/backend/bridge/bootstrap.cpp * *------------------------------------------------------------------------- */ #include <iostream> #include <sys/types.h> #include <unistd.h> #include <cassert> #include "backend/bridge/ddl/bridge.h" #include "backend/bridge/ddl/bootstrap.h" #include "backend/bridge/ddl/ddl_database.h" #include "backend/bridge/ddl/ddl_table.h" #include "backend/storage/database.h" #include "backend/common/logger.h" #include "access/heapam.h" #include "access/htup_details.h" #include "access/xact.h" #include "catalog/pg_attribute.h" #include "catalog/pg_constraint.h" #include "catalog/pg_class.h" #include "catalog/pg_database.h" #include "catalog/pg_namespace.h" #include "common/fe_memutils.h" #include "utils/ruleutils.h" #include "utils/builtins.h" #include "utils/lsyscache.h" #include "utils/snapmgr.h" #include "utils/syscache.h" namespace peloton { namespace bridge { std::vector<catalog::Column> Bootstrap::GetRelationColumns(Oid tuple_oid, Relation pg_attribute_rel){ HeapScanDesc pg_attribute_scan; HeapTuple pg_attribute_tuple; std::vector<catalog::Column> columns; // Scan the pg_attribute table for the relation oid we are interested in. pg_attribute_scan = heap_beginscan_catalog(pg_attribute_rel, 0, NULL); // Go over all attributes in "pg_attribute" looking for any entries // matching the given tuple oid. // For instance, this means the columns associated with a given relation oid. while (1) { Form_pg_attribute pg_attribute; // Get next <relation, attribute> tuple from pg_attribute table pg_attribute_tuple = heap_getnext(pg_attribute_scan, ForwardScanDirection); if(!HeapTupleIsValid(pg_attribute_tuple)) break; // Check the relation oid pg_attribute = (Form_pg_attribute) GETSTRUCT(pg_attribute_tuple); if( pg_attribute->attrelid == tuple_oid ) { // Skip system columns in the attribute list if( strcmp( NameStr(pg_attribute->attname),"cmax" ) && strcmp( NameStr(pg_attribute->attname),"cmin" ) && strcmp( NameStr(pg_attribute->attname),"ctid" ) && strcmp( NameStr(pg_attribute->attname),"xmax" ) && strcmp( NameStr(pg_attribute->attname),"xmin" ) && strcmp( NameStr(pg_attribute->attname),"tableoid" ) ) { std::vector<catalog::Constraint> constraint_infos; PostgresValueType postgresValueType = (PostgresValueType) pg_attribute->atttypid; ValueType value_type = PostgresValueTypeToPelotonValueType( postgresValueType ); int column_length = pg_attribute->attlen; bool is_inlined = true; if( pg_attribute->attlen == -1){ column_length = pg_attribute->atttypmod; is_inlined = false; } // NOT NULL constraint if( pg_attribute->attnotnull ){ catalog::Constraint constraint(CONSTRAINT_TYPE_NOTNULL ); constraint_infos.push_back(constraint); } // DEFAULT value constraint if( pg_attribute->atthasdef ){ catalog::Constraint constraint(CONSTRAINT_TYPE_DEFAULT ); constraint_infos.push_back(constraint); } catalog::Column column(value_type, column_length, NameStr(pg_attribute->attname), is_inlined); columns.push_back(column); } } } heap_endscan(pg_attribute_scan); return columns; } void Bootstrap::CreateIndexInfos(oid_t tuple_oid, char* relation_name, const std::vector<catalog::Column>& columns, std::vector<IndexInfo>& index_infos ){ Relation pg_index_rel; HeapScanDesc pg_index_scan; HeapTuple pg_index_tuple; pg_index_rel = heap_open(IndexRelationId, AccessShareLock); pg_index_scan = heap_beginscan_catalog(pg_index_rel, 0, NULL); // Go over the pg_index catalog table looking for indexes // that are associated with this table while (1) { Form_pg_index pg_index; pg_index_tuple = heap_getnext(pg_index_scan, ForwardScanDirection); if(!HeapTupleIsValid(pg_index_tuple)) break; pg_index = (Form_pg_index) GETSTRUCT(pg_index_tuple); // Search for the tuple in pg_index corresponding to our index if(pg_index->indexrelid == tuple_oid) { std::vector<std::string> key_column_names; for(auto column_info : columns ){ key_column_names.push_back( column_info.column_name); } IndexType method_type = INDEX_TYPE_BTREE_MULTIMAP; IndexConstraintType type; if( pg_index->indisprimary ){ type = INDEX_CONSTRAINT_TYPE_PRIMARY_KEY; }else if( pg_index->indisunique ){ type = INDEX_CONSTRAINT_TYPE_UNIQUE; }else{ type = INDEX_CONSTRAINT_TYPE_DEFAULT; } // Store all index information here // This is required because we can only create indexes at once // after all tables are created // The order of table and index entries in pg_class table can be arbitrary IndexInfo indexinfo(relation_name, pg_index->indexrelid, get_rel_name(pg_index->indrelid), method_type, type, pg_index->indisunique, key_column_names); index_infos.push_back(indexinfo); LOG_INFO("Create index %s on %s", indexinfo.GetIndexName().c_str(), indexinfo.GetTableName().c_str()); break; } } heap_endscan(pg_index_scan); heap_close(pg_index_rel, AccessShareLock); } void Bootstrap::CreatePelotonStructure(char relation_kind, char *relation_name, Oid tuple_oid, const std::vector<catalog::Column>& columns, std::vector<IndexInfo>& index_infos) { bool status = false; switch(relation_kind){ // Create the Peloton table case 'r': { status = DDLTable::CreateTable(tuple_oid, relation_name, columns); if(status == true) { elog(LOG, "Create Table \"%s\" in Peloton", relation_name); } else { elog(ERROR, "Create Table \"%s\" in Peloton", relation_name); } } break; // Create the Peloton index case 'i': { CreateIndexInfos(tuple_oid, relation_name, columns, index_infos); } break; default: elog(ERROR, "Invalid pg_class entry type : %c", relation_kind); break; } } void Bootstrap::LinkForeignKeys(void) { Relation pg_constraint_rel; HeapScanDesc pg_constraint_scan; HeapTuple pg_constraint_tuple; oid_t database_oid = Bridge::GetCurrentDatabaseOid(); assert(database_oid); pg_constraint_rel = heap_open( ConstraintRelationId, AccessShareLock); pg_constraint_scan = heap_beginscan_catalog(pg_constraint_rel, 0, NULL); // Go over the pg_constraint catalog table looking for foreign key constraints while (1) { Form_pg_constraint pg_constraint; pg_constraint_tuple = heap_getnext(pg_constraint_scan, ForwardScanDirection); if(!HeapTupleIsValid(pg_constraint_tuple)) break; pg_constraint = (Form_pg_constraint) GETSTRUCT(pg_constraint_tuple); // We only handle foreign key constraints here if( pg_constraint->contype != 'f') continue; //Extract oid Oid source_table_oid = pg_constraint->conrelid; assert(source_table_oid); Oid sink_table_oid = pg_constraint->confrelid; assert(sink_table_oid); auto& manager = catalog::Manager::GetInstance(); auto source_table = manager.GetTableWithOid(database_oid, source_table_oid); assert(source_table); auto sink_table = manager.GetTableWithOid(database_oid, sink_table_oid); assert(sink_table); // TODO :: Find better way.. bool isNull; Datum curr_datum = heap_getattr(pg_constraint_tuple, Anum_pg_constraint_conkey, RelationGetDescr(pg_constraint_rel), &isNull); Datum ref_datum = heap_getattr(pg_constraint_tuple, Anum_pg_constraint_confkey, RelationGetDescr(pg_constraint_rel), &isNull); ArrayType *curr_arr = DatumGetArrayTypeP(curr_datum); ArrayType *ref_arr = DatumGetArrayTypeP(ref_datum); int16 *curr_attnums = (int16 *) ARR_DATA_PTR(curr_arr); int16 *ref_attnums = (int16 *) ARR_DATA_PTR(ref_arr); int source_numkeys = ARR_DIMS(curr_arr)[0]; int ref_numkeys = ARR_DIMS(ref_arr)[0]; std::vector<std::string> pk_column_names; std::vector<std::string> fk_column_names; auto source_table_schema = source_table->GetSchema(); auto sink_table_schema = sink_table->GetSchema(); // Populate foreign key column names for (int source_key_itr = 0; source_key_itr < source_numkeys; source_key_itr++) { AttrNumber attnum = curr_attnums[source_key_itr]; catalog::Column column = source_table_schema->GetColumn(attnum-1); fk_column_names.push_back(column.GetName()); } // Populate primary key column names for (int sink_key_itr = 0; sink_key_itr < ref_numkeys; sink_key_itr++) { AttrNumber attnum = ref_attnums[sink_key_itr]; catalog::Column column = sink_table_schema->GetColumn(attnum-1); pk_column_names.push_back(column.GetName()); } std::string constraint_name = NameStr(pg_constraint->conname); auto foreign_key = new catalog::ForeignKey(sink_table_oid, pk_column_names, fk_column_names, pg_constraint->confupdtype, pg_constraint->confdeltype, constraint_name); source_table->AddForeignKey(foreign_key); } heap_endscan(pg_constraint_scan); heap_close(pg_constraint_rel, AccessShareLock); } /** * @brief create all databases using catalog table pg_database */ void Bootstrap::CreateDatabases() { Relation pg_database_rel; HeapScanDesc scan; HeapTuple tup; Bridge::PelotonStartTransactionCommand(); // Scan pg database table pg_database_rel = heap_open(DatabaseRelationId, AccessShareLock); scan = heap_beginscan_catalog(pg_database_rel, 0, NULL); while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection))) { Oid database_oid = HeapTupleHeaderGetOid(tup->t_data); DDLDatabase::CreateDatabase( database_oid ); } heap_endscan(scan); heap_close(pg_database_rel, AccessShareLock); Bridge::PelotonCommitTransactionCommand(); } bool Bootstrap::BootstrapPeloton(void) { // Create the new storage database and add it to the manager CreateDatabases(); // Relations for catalog tables Relation pg_class_rel; Relation pg_attribute_rel; HeapScanDesc pg_class_scan; HeapTuple pg_class_tuple; std::vector<IndexInfo> index_infos; bool status; elog(LOG, "Initializing Peloton"); StartTransactionCommand(); // Open the pg_class and pg_attribute catalog tables pg_class_rel = heap_open(RelationRelationId, AccessShareLock); pg_attribute_rel = heap_open(AttributeRelationId, AccessShareLock); pg_class_scan = heap_beginscan_catalog(pg_class_rel, 0, NULL); // Go over all tuples in "pg_class" // pg_class has info about tables and everything else that has columns or is otherwise similar to a table. // This includes indexes, sequences, views, composite types, and some kinds of special relation. // So, each tuple can correspond to a table, index, etc. while(1) { Form_pg_class pg_class; char *relation_name; char relation_kind; int attnum; // Get next tuple from pg_class pg_class_tuple = heap_getnext(pg_class_scan, ForwardScanDirection); if(!HeapTupleIsValid(pg_class_tuple)) break; pg_class = (Form_pg_class) GETSTRUCT(pg_class_tuple); relation_name = NameStr(pg_class->relname); relation_kind = pg_class->relkind; // Handle only user-defined structures, not pg-catalog structures if(pg_class->relnamespace != PG_PUBLIC_NAMESPACE) continue; // TODO: Currently, we only handle relations and indexes if(pg_class->relkind != 'r' && pg_class->relkind != 'i') { continue; } // We only support tables with atleast one attribute attnum = pg_class->relnatts; assert(attnum > 0); // Get the tuple oid // This can be a relation oid or index oid etc. Oid tuple_oid = HeapTupleHeaderGetOid(pg_class_tuple->t_data); auto columns = GetRelationColumns(tuple_oid, pg_attribute_rel); // Create peloton structure CreatePelotonStructure(relation_kind, relation_name, tuple_oid, columns, index_infos); } // Create Indexes status = DDLIndex::CreateIndexes(index_infos); if(status == false) { elog(LOG, "Could not create an index in Peloton"); } // Link foreign keys LinkForeignKeys(); //printf("Print all relation's schema information\n"); //storage::Database* db = storage::Database::GetDatabaseById( GetCurrentDatabaseOid() ); //std::cout << *db << std::endl; heap_endscan(pg_class_scan); heap_close(pg_attribute_rel, AccessShareLock); heap_close(pg_class_rel, AccessShareLock); CommitTransactionCommand(); elog(LOG, "Finished initializing Peloton"); return true; } } // namespace bridge } // namespace peloton <commit_msg>Use PelostonTransactionFunctions instead of using Postgres's functions<commit_after>/*------------------------------------------------------------------------- * * bootstrap.cpp * file description * * Copyright(c) 2015, CMU * * /peloton/src/backend/bridge/bootstrap.cpp * *------------------------------------------------------------------------- */ #include <iostream> #include <sys/types.h> #include <unistd.h> #include <cassert> #include "backend/bridge/ddl/bridge.h" #include "backend/bridge/ddl/bootstrap.h" #include "backend/bridge/ddl/ddl_database.h" #include "backend/bridge/ddl/ddl_table.h" #include "backend/storage/database.h" #include "backend/common/logger.h" #include "access/heapam.h" #include "access/htup_details.h" #include "access/xact.h" #include "catalog/pg_attribute.h" #include "catalog/pg_constraint.h" #include "catalog/pg_class.h" #include "catalog/pg_database.h" #include "catalog/pg_namespace.h" #include "common/fe_memutils.h" #include "utils/ruleutils.h" #include "utils/builtins.h" #include "utils/lsyscache.h" #include "utils/snapmgr.h" #include "utils/syscache.h" namespace peloton { namespace bridge { std::vector<catalog::Column> Bootstrap::GetRelationColumns(Oid tuple_oid, Relation pg_attribute_rel){ HeapScanDesc pg_attribute_scan; HeapTuple pg_attribute_tuple; std::vector<catalog::Column> columns; // Scan the pg_attribute table for the relation oid we are interested in. pg_attribute_scan = heap_beginscan_catalog(pg_attribute_rel, 0, NULL); // Go over all attributes in "pg_attribute" looking for any entries // matching the given tuple oid. // For instance, this means the columns associated with a given relation oid. while (1) { Form_pg_attribute pg_attribute; // Get next <relation, attribute> tuple from pg_attribute table pg_attribute_tuple = heap_getnext(pg_attribute_scan, ForwardScanDirection); if(!HeapTupleIsValid(pg_attribute_tuple)) break; // Check the relation oid pg_attribute = (Form_pg_attribute) GETSTRUCT(pg_attribute_tuple); if( pg_attribute->attrelid == tuple_oid ) { // Skip system columns in the attribute list if( strcmp( NameStr(pg_attribute->attname),"cmax" ) && strcmp( NameStr(pg_attribute->attname),"cmin" ) && strcmp( NameStr(pg_attribute->attname),"ctid" ) && strcmp( NameStr(pg_attribute->attname),"xmax" ) && strcmp( NameStr(pg_attribute->attname),"xmin" ) && strcmp( NameStr(pg_attribute->attname),"tableoid" ) ) { std::vector<catalog::Constraint> constraint_infos; PostgresValueType postgresValueType = (PostgresValueType) pg_attribute->atttypid; ValueType value_type = PostgresValueTypeToPelotonValueType( postgresValueType ); int column_length = pg_attribute->attlen; bool is_inlined = true; if( pg_attribute->attlen == -1){ column_length = pg_attribute->atttypmod; is_inlined = false; } // NOT NULL constraint if( pg_attribute->attnotnull ){ catalog::Constraint constraint(CONSTRAINT_TYPE_NOTNULL ); constraint_infos.push_back(constraint); } // DEFAULT value constraint if( pg_attribute->atthasdef ){ catalog::Constraint constraint(CONSTRAINT_TYPE_DEFAULT ); constraint_infos.push_back(constraint); } catalog::Column column(value_type, column_length, NameStr(pg_attribute->attname), is_inlined); columns.push_back(column); } } } heap_endscan(pg_attribute_scan); return columns; } void Bootstrap::CreateIndexInfos(oid_t tuple_oid, char* relation_name, const std::vector<catalog::Column>& columns, std::vector<IndexInfo>& index_infos ){ Relation pg_index_rel; HeapScanDesc pg_index_scan; HeapTuple pg_index_tuple; pg_index_rel = heap_open(IndexRelationId, AccessShareLock); pg_index_scan = heap_beginscan_catalog(pg_index_rel, 0, NULL); // Go over the pg_index catalog table looking for indexes // that are associated with this table while (1) { Form_pg_index pg_index; pg_index_tuple = heap_getnext(pg_index_scan, ForwardScanDirection); if(!HeapTupleIsValid(pg_index_tuple)) break; pg_index = (Form_pg_index) GETSTRUCT(pg_index_tuple); // Search for the tuple in pg_index corresponding to our index if(pg_index->indexrelid == tuple_oid) { std::vector<std::string> key_column_names; for(auto column_info : columns ){ key_column_names.push_back( column_info.column_name); } IndexType method_type = INDEX_TYPE_BTREE_MULTIMAP; IndexConstraintType type; if( pg_index->indisprimary ){ type = INDEX_CONSTRAINT_TYPE_PRIMARY_KEY; }else if( pg_index->indisunique ){ type = INDEX_CONSTRAINT_TYPE_UNIQUE; }else{ type = INDEX_CONSTRAINT_TYPE_DEFAULT; } // Store all index information here // This is required because we can only create indexes at once // after all tables are created // The order of table and index entries in pg_class table can be arbitrary IndexInfo indexinfo(relation_name, pg_index->indexrelid, get_rel_name(pg_index->indrelid), method_type, type, pg_index->indisunique, key_column_names); index_infos.push_back(indexinfo); LOG_INFO("Create index %s on %s", indexinfo.GetIndexName().c_str(), indexinfo.GetTableName().c_str()); break; } } heap_endscan(pg_index_scan); heap_close(pg_index_rel, AccessShareLock); } void Bootstrap::CreatePelotonStructure(char relation_kind, char *relation_name, Oid tuple_oid, const std::vector<catalog::Column>& columns, std::vector<IndexInfo>& index_infos) { bool status = false; switch(relation_kind){ // Create the Peloton table case 'r': { status = DDLTable::CreateTable(tuple_oid, relation_name, columns); if(status == true) { elog(LOG, "Create Table \"%s\" in Peloton", relation_name); } else { elog(ERROR, "Create Table \"%s\" in Peloton", relation_name); } } break; // Create the Peloton index case 'i': { CreateIndexInfos(tuple_oid, relation_name, columns, index_infos); } break; default: elog(ERROR, "Invalid pg_class entry type : %c", relation_kind); break; } } void Bootstrap::LinkForeignKeys(void) { Relation pg_constraint_rel; HeapScanDesc pg_constraint_scan; HeapTuple pg_constraint_tuple; oid_t database_oid = Bridge::GetCurrentDatabaseOid(); assert(database_oid); pg_constraint_rel = heap_open( ConstraintRelationId, AccessShareLock); pg_constraint_scan = heap_beginscan_catalog(pg_constraint_rel, 0, NULL); // Go over the pg_constraint catalog table looking for foreign key constraints while (1) { Form_pg_constraint pg_constraint; pg_constraint_tuple = heap_getnext(pg_constraint_scan, ForwardScanDirection); if(!HeapTupleIsValid(pg_constraint_tuple)) break; pg_constraint = (Form_pg_constraint) GETSTRUCT(pg_constraint_tuple); // We only handle foreign key constraints here if( pg_constraint->contype != 'f') continue; //Extract oid Oid source_table_oid = pg_constraint->conrelid; assert(source_table_oid); Oid sink_table_oid = pg_constraint->confrelid; assert(sink_table_oid); auto& manager = catalog::Manager::GetInstance(); auto source_table = manager.GetTableWithOid(database_oid, source_table_oid); assert(source_table); auto sink_table = manager.GetTableWithOid(database_oid, sink_table_oid); assert(sink_table); // TODO :: Find better way.. bool isNull; Datum curr_datum = heap_getattr(pg_constraint_tuple, Anum_pg_constraint_conkey, RelationGetDescr(pg_constraint_rel), &isNull); Datum ref_datum = heap_getattr(pg_constraint_tuple, Anum_pg_constraint_confkey, RelationGetDescr(pg_constraint_rel), &isNull); ArrayType *curr_arr = DatumGetArrayTypeP(curr_datum); ArrayType *ref_arr = DatumGetArrayTypeP(ref_datum); int16 *curr_attnums = (int16 *) ARR_DATA_PTR(curr_arr); int16 *ref_attnums = (int16 *) ARR_DATA_PTR(ref_arr); int source_numkeys = ARR_DIMS(curr_arr)[0]; int ref_numkeys = ARR_DIMS(ref_arr)[0]; std::vector<std::string> pk_column_names; std::vector<std::string> fk_column_names; auto source_table_schema = source_table->GetSchema(); auto sink_table_schema = sink_table->GetSchema(); // Populate foreign key column names for (int source_key_itr = 0; source_key_itr < source_numkeys; source_key_itr++) { AttrNumber attnum = curr_attnums[source_key_itr]; catalog::Column column = source_table_schema->GetColumn(attnum-1); fk_column_names.push_back(column.GetName()); } // Populate primary key column names for (int sink_key_itr = 0; sink_key_itr < ref_numkeys; sink_key_itr++) { AttrNumber attnum = ref_attnums[sink_key_itr]; catalog::Column column = sink_table_schema->GetColumn(attnum-1); pk_column_names.push_back(column.GetName()); } std::string constraint_name = NameStr(pg_constraint->conname); auto foreign_key = new catalog::ForeignKey(sink_table_oid, pk_column_names, fk_column_names, pg_constraint->confupdtype, pg_constraint->confdeltype, constraint_name); source_table->AddForeignKey(foreign_key); } heap_endscan(pg_constraint_scan); heap_close(pg_constraint_rel, AccessShareLock); } /** * @brief create all databases using catalog table pg_database */ void Bootstrap::CreateDatabases() { Relation pg_database_rel; HeapScanDesc scan; HeapTuple tup; Bridge::PelotonStartTransactionCommand(); // Scan pg database table pg_database_rel = heap_open(DatabaseRelationId, AccessShareLock); scan = heap_beginscan_catalog(pg_database_rel, 0, NULL); while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection))) { Oid database_oid = HeapTupleHeaderGetOid(tup->t_data); DDLDatabase::CreateDatabase( database_oid ); } heap_endscan(scan); heap_close(pg_database_rel, AccessShareLock); Bridge::PelotonCommitTransactionCommand(); } bool Bootstrap::BootstrapPeloton(void) { // Create the new storage database and add it to the manager CreateDatabases(); // Relations for catalog tables Relation pg_class_rel; Relation pg_attribute_rel; HeapScanDesc pg_class_scan; HeapTuple pg_class_tuple; std::vector<IndexInfo> index_infos; bool status; elog(LOG, "Initializing Peloton"); Bridge::PelotonStartTransactionCommand(); // Open the pg_class and pg_attribute catalog tables pg_class_rel = heap_open(RelationRelationId, AccessShareLock); pg_attribute_rel = heap_open(AttributeRelationId, AccessShareLock); pg_class_scan = heap_beginscan_catalog(pg_class_rel, 0, NULL); // Go over all tuples in "pg_class" // pg_class has info about tables and everything else that has columns or is otherwise similar to a table. // This includes indexes, sequences, views, composite types, and some kinds of special relation. // So, each tuple can correspond to a table, index, etc. while(1) { Form_pg_class pg_class; char *relation_name; char relation_kind; int attnum; // Get next tuple from pg_class pg_class_tuple = heap_getnext(pg_class_scan, ForwardScanDirection); if(!HeapTupleIsValid(pg_class_tuple)) break; pg_class = (Form_pg_class) GETSTRUCT(pg_class_tuple); relation_name = NameStr(pg_class->relname); relation_kind = pg_class->relkind; // Handle only user-defined structures, not pg-catalog structures if(pg_class->relnamespace != PG_PUBLIC_NAMESPACE) continue; // TODO: Currently, we only handle relations and indexes if(pg_class->relkind != 'r' && pg_class->relkind != 'i') { continue; } // We only support tables with atleast one attribute attnum = pg_class->relnatts; assert(attnum > 0); // Get the tuple oid // This can be a relation oid or index oid etc. Oid tuple_oid = HeapTupleHeaderGetOid(pg_class_tuple->t_data); auto columns = GetRelationColumns(tuple_oid, pg_attribute_rel); // Create peloton structure CreatePelotonStructure(relation_kind, relation_name, tuple_oid, columns, index_infos); } // Create Indexes status = DDLIndex::CreateIndexes(index_infos); if(status == false) { elog(LOG, "Could not create an index in Peloton"); } // Link foreign keys LinkForeignKeys(); //printf("Print all relation's schema information\n"); //storage::Database* db = storage::Database::GetDatabaseById( GetCurrentDatabaseOid() ); //std::cout << *db << std::endl; heap_endscan(pg_class_scan); heap_close(pg_attribute_rel, AccessShareLock); heap_close(pg_class_rel, AccessShareLock); Bridge::PelotonCommitTransactionCommand(); elog(LOG, "Finished initializing Peloton"); return true; } } // namespace bridge } // namespace peloton <|endoftext|>
<commit_before>#include <string> #include <iostream> #include "cTCP.h" namespace raven { namespace set { cTCP::cTCP() : myConnectSocket(INVALID_SOCKET), myfRetryServer(true) { } void cTCP::initWinSock() { WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData)) { throw std::runtime_error("Winsock init failed"); } } void cTCP::acceptClient() { if (isConnected()) throw std::runtime_error("second connection rejected"); if (myServerPort.empty()) throw std::runtime_error("Server not configured"); initWinSock(); struct addrinfo *result = NULL, hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; int error = getaddrinfo( NULL, myServerPort.c_str(), &hints, &result); if (error) { throw std::runtime_error( "getaddrinfo failed " + std::to_string(error)); } myAcceptSocket = ::socket( result->ai_family, result->ai_socktype, result->ai_protocol); if (myAcceptSocket == INVALID_SOCKET) { throw std::runtime_error("socket failed"); } if (::bind(myAcceptSocket, result->ai_addr, (int)result->ai_addrlen) == SOCKET_ERROR) { closesocket(myAcceptSocket); myAcceptSocket = INVALID_SOCKET; throw std::runtime_error("bind failed"); } if (::listen( myAcceptSocket, SOMAXCONN) == SOCKET_ERROR) { closesocket(myAcceptSocket); myAcceptSocket = INVALID_SOCKET; throw std::runtime_error("listen failed"); } std::cout << "listening for client on port " << myServerPort << "\n"; struct sockaddr_in client_info; int size = sizeof(client_info); SOCKET s = ::accept( myAcceptSocket, (sockaddr *)&client_info, &size); if (s == INVALID_SOCKET) { std::cout << "invalid socket\n"; return; } myConnectSocket = s; myRemoteAddress = inet_ntoa(client_info.sin_addr); closesocket(myAcceptSocket); std::cout << "client " << myRemoteAddress << " accepted\n"; } void cTCP::read() { if (!isConnected()) throw std::runtime_error("TCP read on invalid socket"); // clear old message ZeroMemory(myReadbuf, 1024); // wait to receive message int r = ::recv( myConnectSocket, (char *)myReadbuf, 1024, 0); // check for message received // if no message or error, assume connection closed if (r <= 0) { std::cout << "connection closed\n"; closesocket(myConnectSocket); myConnectSocket = INVALID_SOCKET; } } bool cTCP::serverWait() { while (1) { connectToServer(); if (isConnected()) { return true; } if( ! myfRetryServer ) return false; } } bool cTCP::connectToServer() { if (myServerPort.empty()) throw std::runtime_error("Server not configured"); initWinSock(); struct addrinfo *result = NULL, hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; if (getaddrinfo( myServerIP.c_str(), myServerPort.c_str(), &hints, &result)) { throw std::runtime_error("getaddrinfo failed"); } myConnectSocket = ::socket( result->ai_family, result->ai_socktype, result->ai_protocol); if (myConnectSocket == INVALID_SOCKET) { throw std::runtime_error("socket failed"); } // std::cout << "attempting connect\n"; if (::connect( myConnectSocket, result->ai_addr, (int)result->ai_addrlen) == SOCKET_ERROR) { int err = WSAGetLastError(); closesocket(myConnectSocket); myConnectSocket = INVALID_SOCKET; if (err == 10060) { std::cout << "connect timed out\n"; return false; } else if (err == 10061) { std::cout << "No connection could be made because the target machine actively refused it. " " Generally, it happens that something is preventing a connection to the port or hostname. " " Either there is a firewall blocking the connection " " or the process that is hosting the service is not listening on that specific port.\n"; return false; } else throw std::runtime_error( "connect failed error: " + std::to_string(err)); } return true; } void cTCP::send(const std::string &msg) { if (myConnectSocket == INVALID_SOCKET) throw std::runtime_error("send on invalid socket"); ::send( myConnectSocket, msg.c_str(), (int)msg.length(), 0); } void cTCP::send(const std::vector<unsigned char> &msg) { if (myConnectSocket == INVALID_SOCKET) throw std::runtime_error("send on invalid socket"); ::send( myConnectSocket, (char *)msg.data(), msg.size(), 0); } } } <commit_msg>On server connect fail display config<commit_after>#include <string> #include <iostream> #include "cTCP.h" namespace raven { namespace set { cTCP::cTCP() : myConnectSocket(INVALID_SOCKET), myfRetryServer(true) { } void cTCP::initWinSock() { WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData)) { throw std::runtime_error("Winsock init failed"); } } void cTCP::acceptClient() { if (isConnected()) throw std::runtime_error("second connection rejected"); if (myServerPort.empty()) throw std::runtime_error("Server not configured"); initWinSock(); struct addrinfo *result = NULL, hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; int error = getaddrinfo( NULL, myServerPort.c_str(), &hints, &result); if (error) { throw std::runtime_error( "getaddrinfo failed " + std::to_string(error)); } myAcceptSocket = ::socket( result->ai_family, result->ai_socktype, result->ai_protocol); if (myAcceptSocket == INVALID_SOCKET) { throw std::runtime_error("socket failed"); } if (::bind(myAcceptSocket, result->ai_addr, (int)result->ai_addrlen) == SOCKET_ERROR) { closesocket(myAcceptSocket); myAcceptSocket = INVALID_SOCKET; throw std::runtime_error("bind failed"); } if (::listen( myAcceptSocket, SOMAXCONN) == SOCKET_ERROR) { closesocket(myAcceptSocket); myAcceptSocket = INVALID_SOCKET; throw std::runtime_error("listen failed"); } std::cout << "listening for client on port " << myServerPort << "\n"; struct sockaddr_in client_info; int size = sizeof(client_info); SOCKET s = ::accept( myAcceptSocket, (sockaddr *)&client_info, &size); if (s == INVALID_SOCKET) { std::cout << "invalid socket\n"; return; } myConnectSocket = s; myRemoteAddress = inet_ntoa(client_info.sin_addr); closesocket(myAcceptSocket); std::cout << "client " << myRemoteAddress << " accepted\n"; } void cTCP::read() { if (!isConnected()) throw std::runtime_error("TCP read on invalid socket"); // clear old message ZeroMemory(myReadbuf, 1024); // wait to receive message int r = ::recv( myConnectSocket, (char *)myReadbuf, 1024, 0); // check for message received // if no message or error, assume connection closed if (r <= 0) { std::cout << "connection closed\n"; closesocket(myConnectSocket); myConnectSocket = INVALID_SOCKET; } } bool cTCP::serverWait() { while (1) { connectToServer(); if (isConnected()) { return true; } if( ! myfRetryServer ) return false; } } bool cTCP::connectToServer() { if (myServerPort.empty()) throw std::runtime_error("Server not configured"); initWinSock(); struct addrinfo *result = NULL, hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; if (getaddrinfo( myServerIP.c_str(), myServerPort.c_str(), &hints, &result)) { throw std::runtime_error("getaddrinfo failed"); } myConnectSocket = ::socket( result->ai_family, result->ai_socktype, result->ai_protocol); if (myConnectSocket == INVALID_SOCKET) { throw std::runtime_error("socket failed"); } // std::cout << "attempting connect\n"; if (::connect( myConnectSocket, result->ai_addr, (int)result->ai_addrlen) == SOCKET_ERROR) { int err = WSAGetLastError(); closesocket(myConnectSocket); myConnectSocket = INVALID_SOCKET; if (err == 10060) { std::cout << "connect timed out\n"; return false; } else if (err == 10061) { std::cout << myServerIP <<":" << myServerPort << " No connection could be made because the target machine actively refused it. " " Generally, it happens that something is preventing a connection to the port or hostname. " " Either there is a firewall blocking the connection " " or the process that is hosting the service is not listening on that specific port.\n"; return false; } else throw std::runtime_error( "connect failed error: " + std::to_string(err)); } return true; } void cTCP::send(const std::string &msg) { if (myConnectSocket == INVALID_SOCKET) throw std::runtime_error("send on invalid socket"); ::send( myConnectSocket, msg.c_str(), (int)msg.length(), 0); } void cTCP::send(const std::vector<unsigned char> &msg) { if (myConnectSocket == INVALID_SOCKET) throw std::runtime_error("send on invalid socket"); ::send( myConnectSocket, (char *)msg.data(), msg.size(), 0); } } } <|endoftext|>
<commit_before>typedef long double ld; const ld eps = 1e-8; const ld pi = acos(-1.0); // 点 typedef complex<ld> Point; namespace std { bool operator< (const Point& lhs, const Point& rhs) { return real(lhs) != real(rhs) ? real(lhs) < real(rhs) : imag(lhs) < imag(rhs); } } // 外積 ld cross (const Point& a, const Point& b) { return imag(conj(a) * b); } // 内積 ld dot (const Point& a, const Point& b) { return real(conj(a) * b); } // 2点a, bを通る直線 struct Line : public vector<Point> { Line (const Point& a, const Point& b) { push_back(a); push_back(b); } }; // 直線lに対する点pの射影 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A Point projection (const Line& l, const Point& p) { ld k = dot(l[1] - l[0], p - l[0]) / abs(l[1] - l[0]) / abs(l[1] - l[0]); return l[0] + k * (l[1] - l[0]); } // 直線lに対する点pの反射 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B Point reflection (const Line& l, const Point& p) { Point q = projection(l, p); return p + (ld)2.0 * (q - p); } // Counter-Clockwise (点の進行方向) // 3点a, b, cを、この順に進むとき、 // a, b で折れてcがaに対して反時計回りの方向 -> 1 // a, b で折れてcがaに対して時計回りの方向 -> -1 // a, b で逆を向いて、c が a より向こう側にある -> 2 // a, b, c の順 -> -2 // c は a, b を内分する -> 0 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C int ccw (Point a, Point b, Point c) { b -= a; c -= a; if (cross(b, c) > 0) return +1; if (cross(b, c) < 0) return -1; if (dot(b, c) < 0) return +2; if (norm(b) < norm(c)) return -2; return 0; } // 2直線l, mが平行であるかどうか // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A bool is_parallel (const Line& l, const Line& m) { return abs(cross(l[1] - l[0], m[1] - m[0])) < eps; } // 2直線l, mが垂直であるかどうか // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A bool is_orthogonal (const Line& l, const Line& m) { return abs(dot(l[1] - l[0], m[1] - m[0])) < eps; } // 2直線l, mが交差するかどうか bool intersectLL (const Line& l, const Line& m) { return !is_parallel(l, m) || abs(cross(l[1] - l[0], m[0] - l[0])) < eps; } // 直線lと線分sが交差するかどうか bool intersectLS (const Line& l, const Line& s) { return cross(l[1] - l[0], s[0] - l[0]) * cross(l[1] - l[0], s[1] - l[0]) < eps; } // 直線lと点pが交差する(上にある)かどうか bool intersectLP (const Line& l, const Point& p) { return abs(cross(l[1] - p, l[0] - p)) < eps; } // 2線分s, tが交差するかどうか // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B bool intersectSS (const Line& s, const Line& t) { return ccw(s[0], s[1], t[0]) * ccw(s[0], s[1], t[1]) <= 0 && ccw(t[0], t[1], s[0]) * ccw(t[0], t[1], s[1]) <= 0; } // 線分sと点pが交差する(上にある)かどうか // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D bool intersectSP (const Line& s, const Point& p) { return abs(s[0] - p) + abs(s[1] - p) - abs(s[1] - s[0]) < eps; } // 2直線l, mの交点 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C Point crosspointLL (const Line& l, const Line& m) { ld A = cross(l[1] - l[0], m[1] - m[0]); ld B = cross(l[1] - l[0], l[1] - m[0]); if (abs(A) < eps && abs(B) < eps) // 同一直線 return m[0]; if (abs(A) < eps) // 2直線は平行 assert(false); return m[0] + B / A * (m[1] - m[0]); } // 直線lと点pの距離 ld distanceLP (const Line& l, const Point& p) { return abs(p - projection(l, p)); } // 2直線l, mの距離 ld distanceLL (const Line& l, const Line& m) { return intersectLL(l, m) ? 0 : distanceLP(l, m[0]); } // 直線lと線分sの距離 ld distanceLS (const Line& l, const Line& s) { if (intersectLS(l, s)) return 0; return min(distanceLP(l, s[0]), distanceLP(l, s[1])); } // 線分sと点pの距離 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D ld distanceSP (const Line& s, const Point& p) { const Point r = projection(s, p); if (intersectSP(s, r)) return abs(r - p); return min(abs(s[0] - p), abs(s[1] - p)); } // 2線分s, tの距離 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D ld distanceSS (const Line& s, const Line& t) { if (intersectSS(s, t)) return 0; return min({distanceSP(s, t[0]), distanceSP(s, t[1]), distanceSP(t, s[0]), distanceSP(t, s[1])}); } // 多角形 // 点は反時計回り typedef vector<Point> Polygon; #define curr(P, i) P[(i) % (P.size())] #define next(P, i) P[(i + 1) % (P.size())] #define prev(P, i) P[(i - 1 + P.size()) % (P.size())] // 多角形の面積 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A ld area (const Polygon& p) { ld result = 0; for (int i = 0; i < p.size(); ++i) { result += cross(p[i], p[(i+1)%(p.size())]); } return result / 2.0; } // 円 struct Circle { Point p; ld r; Circle (const Point& p, ld r) : p(p), r(r) {} }; // 2円c1, c2の交点 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_E vector<Point> crosspointCC (const Circle& c1, const Circle& c2) { vector<Point> result; ld d = abs(c1.p - c2.p); ld rc = (d * d + c1.r * c1.r - c2.r * c2.r) / (2 * d); ld dfr = c1.r * c1.r - rc * rc; if (abs(dfr) < eps) dfr = 0.0; if (dfr < 0.0) return result; // 交点がない ld rs = sqrt(dfr); Point diff = (c2.p - c1.p) / d; result.push_back(c1.p + diff * Point(rc, rs)); if (dfr != 0.0) result.push_back(c1.p + diff * Point(rc, -rs)); sort(result.begin(), result.end()); return result; } // 円cと直線lの交点 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_D vector<Point> crosspointCL (const Circle& c, const Line& l) { vector<Point> result; ld d = distanceLP(l, c.p); if (d - c.r > eps) return result; // 交点がない ld len = (d > c.r) ? 0.0 : sqrt(c.r * c.r - d * d); Point nor = (l[0] - l[1]) / abs(l[0] - l[1]); result.push_back(projection(l, c.p) + len * nor); result.push_back(projection(l, c.p) - len * nor); sort(result.begin(), result.end()); return result; } int main(void) { vector<Circle> cs; REP(i,2){ ld cx, cy, r; cin >> cx >> cy >> r; cs.push_back(Circle(Point(cx, cy), r)); } vector<Point> result = crosspointCC(cs[0], cs[1]); cout << fixed << setprecision(15); cout << real(result[0]) << " " << imag(result[0]) << " "; cout << real(result[1]) << " " << imag(result[1]) << endl; return 0; } <commit_msg>2円の共通接線の本数、円と線分の交点<commit_after>typedef long double ld; const ld eps = 1e-8; const ld pi = acos(-1.0); // 点 typedef complex<ld> Point; namespace std { bool operator< (const Point& lhs, const Point& rhs) { return real(lhs) != real(rhs) ? real(lhs) < real(rhs) : imag(lhs) < imag(rhs); } } // 外積 ld cross (const Point& a, const Point& b) { return imag(conj(a) * b); } // 内積 ld dot (const Point& a, const Point& b) { return real(conj(a) * b); } // 2点a, bを通る直線 struct Line : public vector<Point> { Line (const Point& a, const Point& b) { push_back(a); push_back(b); } }; // 直線lに対する点pの射影 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A Point projection (const Line& l, const Point& p) { ld k = dot(l[1] - l[0], p - l[0]) / abs(l[1] - l[0]) / abs(l[1] - l[0]); return l[0] + k * (l[1] - l[0]); } // 直線lに対する点pの反射 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B Point reflection (const Line& l, const Point& p) { Point q = projection(l, p); return p + (ld)2.0 * (q - p); } // Counter-Clockwise (点の進行方向) // 3点a, b, cを、この順に進むとき、 // a, b で折れてcがaに対して反時計回りの方向 -> 1 // a, b で折れてcがaに対して時計回りの方向 -> -1 // a, b で逆を向いて、c が a より向こう側にある -> 2 // a, b, c の順 -> -2 // c は a, b を内分する -> 0 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C int ccw (Point a, Point b, Point c) { b -= a; c -= a; if (cross(b, c) > 0) return +1; if (cross(b, c) < 0) return -1; if (dot(b, c) < 0) return +2; if (norm(b) < norm(c)) return -2; return 0; } // 2直線l, mが平行であるかどうか // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A bool is_parallel (const Line& l, const Line& m) { return abs(cross(l[1] - l[0], m[1] - m[0])) < eps; } // 2直線l, mが垂直であるかどうか // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A bool is_orthogonal (const Line& l, const Line& m) { return abs(dot(l[1] - l[0], m[1] - m[0])) < eps; } // 2直線l, mが交差するかどうか bool intersectLL (const Line& l, const Line& m) { return !is_parallel(l, m) || abs(cross(l[1] - l[0], m[0] - l[0])) < eps; } // 直線lと線分sが交差するかどうか bool intersectLS (const Line& l, const Line& s) { return cross(l[1] - l[0], s[0] - l[0]) * cross(l[1] - l[0], s[1] - l[0]) < eps; } // 直線lと点pが交差する(上にある)かどうか bool intersectLP (const Line& l, const Point& p) { return abs(cross(l[1] - p, l[0] - p)) < eps; } // 2線分s, tが交差するかどうか // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B bool intersectSS (const Line& s, const Line& t) { return ccw(s[0], s[1], t[0]) * ccw(s[0], s[1], t[1]) <= 0 && ccw(t[0], t[1], s[0]) * ccw(t[0], t[1], s[1]) <= 0; } // 線分sと点pが交差する(上にある)かどうか // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D bool intersectSP (const Line& s, const Point& p) { return abs(s[0] - p) + abs(s[1] - p) - abs(s[1] - s[0]) < eps; } // 2直線l, mの交点 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C Point crosspointLL (const Line& l, const Line& m) { ld A = cross(l[1] - l[0], m[1] - m[0]); ld B = cross(l[1] - l[0], l[1] - m[0]); if (abs(A) < eps && abs(B) < eps) // 同一直線 return m[0]; if (abs(A) < eps) // 2直線は平行 assert(false); return m[0] + B / A * (m[1] - m[0]); } // 直線lと点pの距離 ld distanceLP (const Line& l, const Point& p) { return abs(p - projection(l, p)); } // 2直線l, mの距離 ld distanceLL (const Line& l, const Line& m) { return intersectLL(l, m) ? 0 : distanceLP(l, m[0]); } // 直線lと線分sの距離 ld distanceLS (const Line& l, const Line& s) { if (intersectLS(l, s)) return 0; return min(distanceLP(l, s[0]), distanceLP(l, s[1])); } // 線分sと点pの距離 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D ld distanceSP (const Line& s, const Point& p) { const Point r = projection(s, p); if (intersectSP(s, r)) return abs(r - p); return min(abs(s[0] - p), abs(s[1] - p)); } // 2線分s, tの距離 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D ld distanceSS (const Line& s, const Line& t) { if (intersectSS(s, t)) return 0; return min({distanceSP(s, t[0]), distanceSP(s, t[1]), distanceSP(t, s[0]), distanceSP(t, s[1])}); } // 多角形 // 点は反時計回り typedef vector<Point> Polygon; #define curr(P, i) P[(i) % (P.size())] #define next(P, i) P[(i + 1) % (P.size())] #define prev(P, i) P[(i - 1 + P.size()) % (P.size())] // 多角形の面積 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A ld area (const Polygon& p) { ld result = 0; for (int i = 0; i < p.size(); ++i) { result += cross(p[i], p[(i+1)%(p.size())]); } return result / 2.0; } // 円 struct Circle { Point p; ld r; Circle (const Point& p, ld r) : p(p), r(r) {} }; // 2円c1, c2の共通接線の本数(交差するかどうか) // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_A int intersectCC (const Circle& c1, const Circle& c2) { ld dist = abs(c1.p - c2.p); if (dist > c1.r + c2.r) return 4; if (abs(dist - (c1.r + c2.r)) < eps) return 3; if (dist < c1.r + c2.r && dist > abs(c1.r - c2.r)) return 2; if (abs(dist - abs(c1.r - c2.r)) < eps) return 1; return 0; } // 2円c1, c2の交点 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_E vector<Point> crosspointCC (const Circle& c1, const Circle& c2) { vector<Point> result; ld d = abs(c1.p - c2.p); ld rc = (d * d + c1.r * c1.r - c2.r * c2.r) / (2 * d); ld dfr = c1.r * c1.r - rc * rc; if (abs(dfr) < eps) dfr = 0.0; if (dfr < 0.0) return result; // 交点がない ld rs = sqrt(dfr); Point diff = (c2.p - c1.p) / d; result.push_back(c1.p + diff * Point(rc, rs)); if (dfr != 0.0) result.push_back(c1.p + diff * Point(rc, -rs)); sort(result.begin(), result.end()); return result; } // 円cと直線lの交点 // Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_D vector<Point> crosspointCL (const Circle& c, const Line& l) { vector<Point> result; ld d = distanceLP(l, c.p); if (d - c.r > eps) return result; // 交点がない ld len = (d > c.r) ? 0.0 : sqrt(c.r * c.r - d * d); Point nor = (l[0] - l[1]) / abs(l[0] - l[1]); result.push_back(projection(l, c.p) + len * nor); result.push_back(projection(l, c.p) - len * nor); sort(result.begin(), result.end()); return result; } // 円cと線分sの交点 vector<Point> crosspointCS (const Circle& c, const Line& s) { vector<Point> v = crosspointCL(c, s), result; for (int i = 0; i < v.size(); ++i) { if (ccw(s[0], v[i], s[1]) == 2) result.push_back(v[i]); } sort(result.begin(), result.end()); return result; } <|endoftext|>
<commit_before>// Copyright 2014 BVLC and contributors. #include <cstring> #include <vector> #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/vision_layers.hpp" #include "caffe/test/test_gradient_check_util.hpp" #include "caffe/test/test_caffe_main.hpp" namespace caffe { template <typename TypeParam> class ConcatLayerTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: ConcatLayerTest() : blob_bottom_0(new Blob<Dtype>(2, 3, 6, 5)), blob_bottom_1(new Blob<Dtype>(2, 5, 6, 5)), blob_bottom_2(new Blob<Dtype>(5, 3, 6, 5)), blob_top_(new Blob<Dtype>()) {} virtual void SetUp() { // fill the values FillerParameter filler_param; filler_param.set_value(1.); ConstantFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_0); filler_param.set_value(2.); filler.Fill(this->blob_bottom_1); filler_param.set_value(3.); filler.Fill(this->blob_bottom_2); blob_bottom_vec_0.push_back(blob_bottom_0); blob_bottom_vec_0.push_back(blob_bottom_1); blob_bottom_vec_1.push_back(blob_bottom_0); blob_bottom_vec_1.push_back(blob_bottom_2); blob_top_vec_.push_back(blob_top_); } virtual ~ConcatLayerTest() { delete blob_bottom_0; delete blob_bottom_1; delete blob_bottom_2; delete blob_top_; } Blob<Dtype>* const blob_bottom_0; Blob<Dtype>* const blob_bottom_1; Blob<Dtype>* const blob_bottom_2; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_0, blob_bottom_vec_1; vector<Blob<Dtype>*> blob_top_vec_; }; TYPED_TEST_CASE(ConcatLayerTest, TestDtypesAndDevices); TYPED_TEST(ConcatLayerTest, TestSetupNum) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; layer_param.mutable_concat_param()->set_concat_dim(0); ConcatLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_1, &(this->blob_top_vec_)); EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_0->num() + this->blob_bottom_2->num()); EXPECT_EQ(this->blob_top_->channels(), this->blob_bottom_0->channels()); EXPECT_EQ(this->blob_top_->height(), this->blob_bottom_0->height()); EXPECT_EQ(this->blob_top_->width(), this->blob_bottom_0->width()); } TYPED_TEST(ConcatLayerTest, TestSetupChannels) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConcatLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_0, &(this->blob_top_vec_)); EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_0->num()); EXPECT_EQ(this->blob_top_->channels(), this->blob_bottom_0->channels()+this->blob_bottom_1->channels()); EXPECT_EQ(this->blob_top_->height(), this->blob_bottom_0->height()); EXPECT_EQ(this->blob_top_->width(), this->blob_bottom_0->width()); } TYPED_TEST(ConcatLayerTest, TestNum) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConcatLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_0, &(this->blob_top_vec_)); layer.Forward(this->blob_bottom_vec_0, &(this->blob_top_vec_)); for (int n = 0; n < this->blob_top_->num(); ++n) { for (int c = 0; c < this->blob_bottom_0->channels(); ++c) { for (int h = 0; h < this->blob_top_->height(); ++h) { for (int w = 0; w < this->blob_top_->width(); ++w) { EXPECT_EQ(this->blob_top_->data_at(n, c, h, w), this->blob_bottom_vec_0[0]->data_at(n, c, h, w)); } } } for (int c = 0; c < this->blob_bottom_1->channels(); ++c) { for (int h = 0; h < this->blob_top_->height(); ++h) { for (int w = 0; w < this->blob_top_->width(); ++w) { EXPECT_EQ(this->blob_top_->data_at(n, c+3, h, w), this->blob_bottom_vec_0[1]->data_at(n, c, h, w)); } } } } } TYPED_TEST(ConcatLayerTest, TestGradient) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConcatLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradient(&layer, &(this->blob_bottom_vec_0), &(this->blob_top_vec_)); } } // namespace caffe <commit_msg>modified test_concat_layer.cpp<commit_after>// Copyright 2014 BVLC and contributors. #include <cstring> #include <vector> #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/vision_layers.hpp" #include "caffe/test/test_gradient_check_util.hpp" #include "caffe/test/test_caffe_main.hpp" namespace caffe { template <typename TypeParam> class ConcatLayerTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: ConcatLayerTest() : blob_bottom_0(new Blob<Dtype>(2, 3, 6, 5)), blob_bottom_1(new Blob<Dtype>(2, 5, 6, 5)), blob_bottom_2(new Blob<Dtype>(5, 3, 6, 5)), blob_top_(new Blob<Dtype>()) {} virtual void SetUp() { // fill the values shared_ptr<ConstantFiller<Dtype> > filler; FillerParameter filler_param; filler_param.set_value(1.); filler.reset(new ConstantFiller<Dtype>(filler_param)); filler->Fill(this->blob_bottom_0); filler_param.set_value(2.); filler.reset(new ConstantFiller<Dtype>(filler_param)); filler->Fill(this->blob_bottom_1); filler_param.set_value(3.); filler.reset(new ConstantFiller<Dtype>(filler_param)); filler->Fill(this->blob_bottom_2); blob_bottom_vec_0.push_back(blob_bottom_0); blob_bottom_vec_0.push_back(blob_bottom_1); blob_bottom_vec_1.push_back(blob_bottom_0); blob_bottom_vec_1.push_back(blob_bottom_2); blob_top_vec_.push_back(blob_top_); } virtual ~ConcatLayerTest() { delete blob_bottom_0; delete blob_bottom_1; delete blob_bottom_2; delete blob_top_; } Blob<Dtype>* const blob_bottom_0; Blob<Dtype>* const blob_bottom_1; Blob<Dtype>* const blob_bottom_2; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_0, blob_bottom_vec_1; vector<Blob<Dtype>*> blob_top_vec_; }; TYPED_TEST_CASE(ConcatLayerTest, TestDtypesAndDevices); TYPED_TEST(ConcatLayerTest, TestSetupNum) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; layer_param.mutable_concat_param()->set_concat_dim(0); ConcatLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_1, &(this->blob_top_vec_)); EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_0->num() + this->blob_bottom_2->num()); EXPECT_EQ(this->blob_top_->channels(), this->blob_bottom_0->channels()); EXPECT_EQ(this->blob_top_->height(), this->blob_bottom_0->height()); EXPECT_EQ(this->blob_top_->width(), this->blob_bottom_0->width()); } TYPED_TEST(ConcatLayerTest, TestSetupChannels) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConcatLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_0, &(this->blob_top_vec_)); EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_0->num()); EXPECT_EQ(this->blob_top_->channels(), this->blob_bottom_0->channels()+this->blob_bottom_1->channels()); EXPECT_EQ(this->blob_top_->height(), this->blob_bottom_0->height()); EXPECT_EQ(this->blob_top_->width(), this->blob_bottom_0->width()); } TYPED_TEST(ConcatLayerTest, TestNum) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConcatLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_0, &(this->blob_top_vec_)); layer.Forward(this->blob_bottom_vec_0, &(this->blob_top_vec_)); for (int n = 0; n < this->blob_top_->num(); ++n) { for (int c = 0; c < this->blob_bottom_0->channels(); ++c) { for (int h = 0; h < this->blob_top_->height(); ++h) { for (int w = 0; w < this->blob_top_->width(); ++w) { EXPECT_EQ(this->blob_top_->data_at(n, c, h, w), this->blob_bottom_vec_0[0]->data_at(n, c, h, w)); } } } for (int c = 0; c < this->blob_bottom_1->channels(); ++c) { for (int h = 0; h < this->blob_top_->height(); ++h) { for (int w = 0; w < this->blob_top_->width(); ++w) { EXPECT_EQ(this->blob_top_->data_at(n, c+3, h, w), this->blob_bottom_vec_0[1]->data_at(n, c, h, w)); } } } } } TYPED_TEST(ConcatLayerTest, TestGradient) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ConcatLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-2); checker.CheckGradient(&layer, &(this->blob_bottom_vec_0), &(this->blob_top_vec_)); } } // namespace caffe <|endoftext|>
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include "PropertyHDF5.hpp" #include <nix/util/util.hpp> #include <iostream> using namespace std; using namespace nix::base; namespace nix { //special to_data_type for our purporses (Value) template<> struct to_data_type<char *> { static const bool is_valid = true; static const DataType value = DataType::String; }; template<> struct to_data_type<const char *> { static const bool is_valid = true; static const DataType value = DataType::String; }; namespace hdf5 { PropertyHDF5::PropertyHDF5(const std::shared_ptr<IFile> &file, const DataSet &dataset) : entity_file(file) { this->entity_dataset = dataset; } PropertyHDF5::PropertyHDF5(const std::shared_ptr<IFile> &file, const DataSet &dataset, const string &id, const string &name) : PropertyHDF5(file, dataset, id, name, util::getTime()) { } PropertyHDF5::PropertyHDF5(const std::shared_ptr<IFile> &file, const DataSet &dataset, const string &id, const string &name, time_t time) : entity_file(file) { this->entity_dataset = dataset; // set name if (name.empty()) { throw EmptyString("name"); } else { dataset.setAttr("name", name); forceUpdatedAt(); } dataset.setAttr("entity_id", id); setUpdatedAt(); forceCreatedAt(time); } string PropertyHDF5::id() const { string t; if (dataset().hasAttr("entity_id")) { dataset().getAttr("entity_id", t); } else { throw runtime_error("Entity has no id!"); } return t; } time_t PropertyHDF5::updatedAt() const { string t; dataset().getAttr("updated_at", t); return util::strToTime(t); } void PropertyHDF5::setUpdatedAt() { if (!dataset().hasAttr("updated_at")) { time_t t = util::getTime(); dataset().setAttr("updated_at", util::timeToStr(t)); } } void PropertyHDF5::forceUpdatedAt() { time_t t = util::getTime(); dataset().setAttr("updated_at", util::timeToStr(t)); } time_t PropertyHDF5::createdAt() const { string t; dataset().getAttr("created_at", t); return util::strToTime(t); } void PropertyHDF5::setCreatedAt() { if (!dataset().hasAttr("created_at")) { time_t t = util::getTime(); dataset().setAttr("created_at", util::timeToStr(t)); } } void PropertyHDF5::forceCreatedAt(time_t t) { dataset().setAttr("created_at", util::timeToStr(t)); } string PropertyHDF5::name() const { string name; if (dataset().hasAttr("name")) { dataset().getAttr("name", name); return name; } else { throw MissingAttr("name"); } } void PropertyHDF5::definition(const string &definition) { dataset().setAttr("definition", definition); forceUpdatedAt(); } boost::optional<string> PropertyHDF5::definition() const { boost::optional<string> ret; string definition; bool have_attr = dataset().getAttr("definition", definition); if (have_attr) { ret = definition; } return ret; } void PropertyHDF5::definition(const nix::none_t t) { if (dataset().hasAttr("definition")) { dataset().removeAttr("definition"); } forceUpdatedAt(); } DataType PropertyHDF5::dataType() const { const h5x::DataType dtype = dataset().dataType(); return data_type_from_h5(dtype); } void PropertyHDF5::mapping(const string &mapping) { dataset().setAttr("mapping", mapping); forceUpdatedAt(); } boost::optional<string> PropertyHDF5::mapping() const { boost::optional<string> ret; string mapping; if (dataset().getAttr("mapping", mapping)) { ret = mapping; } return ret; } void PropertyHDF5::mapping(const nix::none_t t) { if (dataset().hasAttr("mapping")) { dataset().removeAttr("mapping"); forceUpdatedAt(); } } void PropertyHDF5::unit(const string &unit) { dataset().setAttr("unit", unit); forceUpdatedAt(); } boost::optional<string> PropertyHDF5::unit() const { boost::optional<std::string> ret; string unit; if (dataset().getAttr("unit", unit)) { ret = unit; } return ret; } void PropertyHDF5::unit(const nix::none_t t) { if (dataset().hasAttr("unit")) { dataset().removeAttr("unit"); } forceUpdatedAt(); } bool PropertyHDF5::isValidEntity() const { return dataset().referenceCount() > 0; } PropertyHDF5::~PropertyHDF5() {} /* Value related functions */ template<typename T> struct FileValue { T value; double uncertainty; char *reference; char *filename; char *encoder; char *checksum; //ctors FileValue() {} explicit FileValue(const T &vref) : value(vref) { } inline T val() const { return value; } }; template<> struct FileValue<bool> { unsigned char value; double uncertainty; char *reference; char *filename; char *encoder; char *checksum; //ctors FileValue() {} explicit FileValue(const bool &vref) : value(static_cast<unsigned char>(vref ? 1 : 0)) { } inline bool val() const { return value > 0; } }; // template<typename T> h5x::DataType h5_type_for_value(bool for_memory) { typedef FileValue<T> file_value_t; h5x::DataType ct = h5x::DataType::makeCompound(sizeof(file_value_t)); h5x::DataType strType = h5x::DataType::makeStrType(); h5x::DataType value_type = data_type_to_h5(to_data_type<T>::value, for_memory); h5x::DataType double_type = data_type_to_h5(DataType::Double, for_memory); ct.insert("value", HOFFSET(file_value_t, value), value_type); ct.insert("uncertainty", HOFFSET(file_value_t, uncertainty), double_type); ct.insert("reference", HOFFSET(file_value_t, reference), strType); ct.insert("filename", HOFFSET(file_value_t, filename), strType); ct.insert("encoder", HOFFSET(file_value_t, encoder), strType); ct.insert("checksum", HOFFSET(file_value_t, checksum), strType); return ct; } #if 0 //set to one to check that all supported DataTypes are handled #define CHECK_SUPOORTED_VALUES #endif #define DATATYPE_SUPPORT_NOT_IMPLEMENTED false h5x::DataType PropertyHDF5::fileTypeForValue(DataType dtype) { const bool for_memory = true; switch(dtype) { case DataType::Bool: return h5_type_for_value<bool>(for_memory); case DataType::Int32: return h5_type_for_value<int32_t>(for_memory); case DataType::UInt32: return h5_type_for_value<uint32_t>(for_memory); case DataType::Int64: return h5_type_for_value<int64_t>(for_memory); case DataType::UInt64: return h5_type_for_value<uint64_t>(for_memory); case DataType::Double: return h5_type_for_value<double>(for_memory); case DataType::String: return h5_type_for_value<char *>(for_memory); #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); break; #endif } return h5x::DataType{}; } template<typename T> void do_read_value(const DataSet &h5ds, size_t size, std::vector<Value> &values) { h5x::DataType memType = h5_type_for_value<T>(true); typedef FileValue<T> file_value_t; std::vector<file_value_t> fileValues; fileValues.resize(size); values.resize(size); h5ds.read(fileValues.data(), memType, H5S_ALL, H5S_ALL); std::transform(fileValues.begin(), fileValues.end(), values.begin(), [](const file_value_t &val) { Value temp(val.val()); temp.uncertainty = val.uncertainty; temp.reference = val.reference; temp.filename = val.filename; temp.encoder = val.encoder; temp.checksum = val.checksum; return temp; }); h5ds.vlenReclaim(memType, fileValues.data()); } #define NOT_IMPLEMENTED 1 template<typename T> void do_write_value(DataSet &h5ds, const std::vector<Value> &values) { typedef FileValue<T> file_value_t; std::vector<file_value_t> fileValues; fileValues.resize(values.size()); std::transform(values.begin(), values.end(), fileValues.begin(), [](const Value &val) { file_value_t fileVal(val.get<T>()); fileVal.uncertainty = val.uncertainty; fileVal.reference = const_cast<char *>(val.reference.c_str()); fileVal.filename = const_cast<char *>(val.filename.c_str()); fileVal.encoder = const_cast<char *>(val.encoder.c_str()); fileVal.checksum = const_cast<char *>(val.checksum.c_str()); return fileVal; }); h5x::DataType memType = h5_type_for_value<T>(true); h5ds.write(fileValues.data(), memType, H5S_ALL, H5S_ALL); } // value public API void PropertyHDF5::deleteValues() { dataset().setExtent({0}); } ndsize_t PropertyHDF5::valueCount() const { NDSize size = dataset().size(); return size[0]; } void PropertyHDF5::values(const std::vector<Value> &values) { if (values.size() < 1) { deleteValues(); return; } DataSet dset = dataset(); dset.setExtent(NDSize{values.size()}); if (values.size() < 1) { return; //nothing to do } switch(values[0].type()) { case DataType::Bool: do_write_value<bool>(dset, values); break; case DataType::Int32: do_write_value<int32_t>(dset, values); break; case DataType::UInt32: do_write_value<uint32_t>(dset, values); break; case DataType::Int64: do_write_value<int64_t>(dset, values); break; case DataType::UInt64: do_write_value<uint64_t>(dset, values); break; case DataType::String: do_write_value<const char *>(dset, values); break; case DataType::Double: do_write_value<double>(dset, values); break; #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } std::vector<Value> PropertyHDF5::values(void) const { std::vector<Value> values; DataSet dset = dataset(); DataType dtype = data_type_from_h5(dset.dataType()); NDSize shape = dset.size(); if (shape.size() < 1 || shape[0] < 1) { return values; } assert(shape.size() == 1); size_t nvalues = nix::check::fits_in_size_t(shape[0], "Can't resize: data to big for memory"); switch (dtype) { case DataType::Bool: do_read_value<bool>(dset, nvalues, values); break; case DataType::Int32: do_read_value<int32_t>(dset, nvalues, values); break; case DataType::UInt32: do_read_value<uint32_t>(dset, nvalues, values); break; case DataType::Int64: do_read_value<int64_t>(dset, nvalues, values); break; case DataType::UInt64: do_read_value<uint64_t>(dset, nvalues, values); break; case DataType::String: do_read_value<char *>(dset, nvalues, values); break; case DataType::Double: do_read_value<double>(dset, nvalues, values); break; #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } return values; } void PropertyHDF5::values(const nix::none_t t) { // TODO: rethink if we want two methods for same thing deleteValues(); } } // ns nix::hdf5 } // ns nix <commit_msg>[h5x] for_memory = false in fileTypeForValue<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include "PropertyHDF5.hpp" #include <nix/util/util.hpp> #include <iostream> using namespace std; using namespace nix::base; namespace nix { //special to_data_type for our purporses (Value) template<> struct to_data_type<char *> { static const bool is_valid = true; static const DataType value = DataType::String; }; template<> struct to_data_type<const char *> { static const bool is_valid = true; static const DataType value = DataType::String; }; namespace hdf5 { PropertyHDF5::PropertyHDF5(const std::shared_ptr<IFile> &file, const DataSet &dataset) : entity_file(file) { this->entity_dataset = dataset; } PropertyHDF5::PropertyHDF5(const std::shared_ptr<IFile> &file, const DataSet &dataset, const string &id, const string &name) : PropertyHDF5(file, dataset, id, name, util::getTime()) { } PropertyHDF5::PropertyHDF5(const std::shared_ptr<IFile> &file, const DataSet &dataset, const string &id, const string &name, time_t time) : entity_file(file) { this->entity_dataset = dataset; // set name if (name.empty()) { throw EmptyString("name"); } else { dataset.setAttr("name", name); forceUpdatedAt(); } dataset.setAttr("entity_id", id); setUpdatedAt(); forceCreatedAt(time); } string PropertyHDF5::id() const { string t; if (dataset().hasAttr("entity_id")) { dataset().getAttr("entity_id", t); } else { throw runtime_error("Entity has no id!"); } return t; } time_t PropertyHDF5::updatedAt() const { string t; dataset().getAttr("updated_at", t); return util::strToTime(t); } void PropertyHDF5::setUpdatedAt() { if (!dataset().hasAttr("updated_at")) { time_t t = util::getTime(); dataset().setAttr("updated_at", util::timeToStr(t)); } } void PropertyHDF5::forceUpdatedAt() { time_t t = util::getTime(); dataset().setAttr("updated_at", util::timeToStr(t)); } time_t PropertyHDF5::createdAt() const { string t; dataset().getAttr("created_at", t); return util::strToTime(t); } void PropertyHDF5::setCreatedAt() { if (!dataset().hasAttr("created_at")) { time_t t = util::getTime(); dataset().setAttr("created_at", util::timeToStr(t)); } } void PropertyHDF5::forceCreatedAt(time_t t) { dataset().setAttr("created_at", util::timeToStr(t)); } string PropertyHDF5::name() const { string name; if (dataset().hasAttr("name")) { dataset().getAttr("name", name); return name; } else { throw MissingAttr("name"); } } void PropertyHDF5::definition(const string &definition) { dataset().setAttr("definition", definition); forceUpdatedAt(); } boost::optional<string> PropertyHDF5::definition() const { boost::optional<string> ret; string definition; bool have_attr = dataset().getAttr("definition", definition); if (have_attr) { ret = definition; } return ret; } void PropertyHDF5::definition(const nix::none_t t) { if (dataset().hasAttr("definition")) { dataset().removeAttr("definition"); } forceUpdatedAt(); } DataType PropertyHDF5::dataType() const { const h5x::DataType dtype = dataset().dataType(); return data_type_from_h5(dtype); } void PropertyHDF5::mapping(const string &mapping) { dataset().setAttr("mapping", mapping); forceUpdatedAt(); } boost::optional<string> PropertyHDF5::mapping() const { boost::optional<string> ret; string mapping; if (dataset().getAttr("mapping", mapping)) { ret = mapping; } return ret; } void PropertyHDF5::mapping(const nix::none_t t) { if (dataset().hasAttr("mapping")) { dataset().removeAttr("mapping"); forceUpdatedAt(); } } void PropertyHDF5::unit(const string &unit) { dataset().setAttr("unit", unit); forceUpdatedAt(); } boost::optional<string> PropertyHDF5::unit() const { boost::optional<std::string> ret; string unit; if (dataset().getAttr("unit", unit)) { ret = unit; } return ret; } void PropertyHDF5::unit(const nix::none_t t) { if (dataset().hasAttr("unit")) { dataset().removeAttr("unit"); } forceUpdatedAt(); } bool PropertyHDF5::isValidEntity() const { return dataset().referenceCount() > 0; } PropertyHDF5::~PropertyHDF5() {} /* Value related functions */ template<typename T> struct FileValue { T value; double uncertainty; char *reference; char *filename; char *encoder; char *checksum; //ctors FileValue() {} explicit FileValue(const T &vref) : value(vref) { } inline T val() const { return value; } }; template<> struct FileValue<bool> { unsigned char value; double uncertainty; char *reference; char *filename; char *encoder; char *checksum; //ctors FileValue() {} explicit FileValue(const bool &vref) : value(static_cast<unsigned char>(vref ? 1 : 0)) { } inline bool val() const { return value > 0; } }; // template<typename T> h5x::DataType h5_type_for_value(bool for_memory) { typedef FileValue<T> file_value_t; h5x::DataType ct = h5x::DataType::makeCompound(sizeof(file_value_t)); h5x::DataType strType = h5x::DataType::makeStrType(); h5x::DataType value_type = data_type_to_h5(to_data_type<T>::value, for_memory); h5x::DataType double_type = data_type_to_h5(DataType::Double, for_memory); ct.insert("value", HOFFSET(file_value_t, value), value_type); ct.insert("uncertainty", HOFFSET(file_value_t, uncertainty), double_type); ct.insert("reference", HOFFSET(file_value_t, reference), strType); ct.insert("filename", HOFFSET(file_value_t, filename), strType); ct.insert("encoder", HOFFSET(file_value_t, encoder), strType); ct.insert("checksum", HOFFSET(file_value_t, checksum), strType); return ct; } #if 0 //set to one to check that all supported DataTypes are handled #define CHECK_SUPOORTED_VALUES #endif #define DATATYPE_SUPPORT_NOT_IMPLEMENTED false h5x::DataType PropertyHDF5::fileTypeForValue(DataType dtype) { const bool for_memory = false; switch(dtype) { case DataType::Bool: return h5_type_for_value<bool>(for_memory); case DataType::Int32: return h5_type_for_value<int32_t>(for_memory); case DataType::UInt32: return h5_type_for_value<uint32_t>(for_memory); case DataType::Int64: return h5_type_for_value<int64_t>(for_memory); case DataType::UInt64: return h5_type_for_value<uint64_t>(for_memory); case DataType::Double: return h5_type_for_value<double>(for_memory); case DataType::String: return h5_type_for_value<char *>(for_memory); #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); break; #endif } return h5x::DataType{}; } template<typename T> void do_read_value(const DataSet &h5ds, size_t size, std::vector<Value> &values) { h5x::DataType memType = h5_type_for_value<T>(true); typedef FileValue<T> file_value_t; std::vector<file_value_t> fileValues; fileValues.resize(size); values.resize(size); h5ds.read(fileValues.data(), memType, H5S_ALL, H5S_ALL); std::transform(fileValues.begin(), fileValues.end(), values.begin(), [](const file_value_t &val) { Value temp(val.val()); temp.uncertainty = val.uncertainty; temp.reference = val.reference; temp.filename = val.filename; temp.encoder = val.encoder; temp.checksum = val.checksum; return temp; }); h5ds.vlenReclaim(memType, fileValues.data()); } #define NOT_IMPLEMENTED 1 template<typename T> void do_write_value(DataSet &h5ds, const std::vector<Value> &values) { typedef FileValue<T> file_value_t; std::vector<file_value_t> fileValues; fileValues.resize(values.size()); std::transform(values.begin(), values.end(), fileValues.begin(), [](const Value &val) { file_value_t fileVal(val.get<T>()); fileVal.uncertainty = val.uncertainty; fileVal.reference = const_cast<char *>(val.reference.c_str()); fileVal.filename = const_cast<char *>(val.filename.c_str()); fileVal.encoder = const_cast<char *>(val.encoder.c_str()); fileVal.checksum = const_cast<char *>(val.checksum.c_str()); return fileVal; }); h5x::DataType memType = h5_type_for_value<T>(true); h5ds.write(fileValues.data(), memType, H5S_ALL, H5S_ALL); } // value public API void PropertyHDF5::deleteValues() { dataset().setExtent({0}); } ndsize_t PropertyHDF5::valueCount() const { NDSize size = dataset().size(); return size[0]; } void PropertyHDF5::values(const std::vector<Value> &values) { if (values.size() < 1) { deleteValues(); return; } DataSet dset = dataset(); dset.setExtent(NDSize{values.size()}); if (values.size() < 1) { return; //nothing to do } switch(values[0].type()) { case DataType::Bool: do_write_value<bool>(dset, values); break; case DataType::Int32: do_write_value<int32_t>(dset, values); break; case DataType::UInt32: do_write_value<uint32_t>(dset, values); break; case DataType::Int64: do_write_value<int64_t>(dset, values); break; case DataType::UInt64: do_write_value<uint64_t>(dset, values); break; case DataType::String: do_write_value<const char *>(dset, values); break; case DataType::Double: do_write_value<double>(dset, values); break; #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } std::vector<Value> PropertyHDF5::values(void) const { std::vector<Value> values; DataSet dset = dataset(); DataType dtype = data_type_from_h5(dset.dataType()); NDSize shape = dset.size(); if (shape.size() < 1 || shape[0] < 1) { return values; } assert(shape.size() == 1); size_t nvalues = nix::check::fits_in_size_t(shape[0], "Can't resize: data to big for memory"); switch (dtype) { case DataType::Bool: do_read_value<bool>(dset, nvalues, values); break; case DataType::Int32: do_read_value<int32_t>(dset, nvalues, values); break; case DataType::UInt32: do_read_value<uint32_t>(dset, nvalues, values); break; case DataType::Int64: do_read_value<int64_t>(dset, nvalues, values); break; case DataType::UInt64: do_read_value<uint64_t>(dset, nvalues, values); break; case DataType::String: do_read_value<char *>(dset, nvalues, values); break; case DataType::Double: do_read_value<double>(dset, nvalues, values); break; #ifndef CHECK_SUPOORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } return values; } void PropertyHDF5::values(const nix::none_t t) { // TODO: rethink if we want two methods for same thing deleteValues(); } } // ns nix::hdf5 } // ns nix <|endoftext|>
<commit_before><commit_msg>CID#738561 uninitialized member<commit_after><|endoftext|>
<commit_before>// Copyright (c) the JPEG XL Project 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 "lib/jxl/image.h" #include <algorithm> // swap #undef HWY_TARGET_INCLUDE #define HWY_TARGET_INCLUDE "lib/jxl/image.cc" #include <hwy/foreach_target.h> #include <hwy/highway.h> #include "lib/jxl/base/profiler.h" #include "lib/jxl/common.h" #include "lib/jxl/image_ops.h" #include "lib/jxl/sanitizers.h" HWY_BEFORE_NAMESPACE(); namespace jxl { namespace HWY_NAMESPACE { size_t GetVectorSize() { return HWY_LANES(uint8_t); } // NOLINTNEXTLINE(google-readability-namespace-comments) } // namespace HWY_NAMESPACE } // namespace jxl HWY_AFTER_NAMESPACE(); #if HWY_ONCE namespace jxl { namespace { HWY_EXPORT(GetVectorSize); // Local function. size_t VectorSize() { static size_t bytes = HWY_DYNAMIC_DISPATCH(GetVectorSize)(); return bytes; } // Returns distance [bytes] between the start of two consecutive rows, a // multiple of vector/cache line size but NOT CacheAligned::kAlias - see below. size_t BytesPerRow(const size_t xsize, const size_t sizeof_t) { const size_t vec_size = VectorSize(); size_t valid_bytes = xsize * sizeof_t; // Allow unaligned accesses starting at the last valid value - this may raise // msan errors unless the user calls InitializePaddingForUnalignedAccesses. // Skip for the scalar case because no extra lanes will be loaded. if (vec_size != 0) { valid_bytes += vec_size - sizeof_t; } // Round up to vector and cache line size. const size_t align = std::max(vec_size, CacheAligned::kAlignment); size_t bytes_per_row = RoundUpTo(valid_bytes, align); // During the lengthy window before writes are committed to memory, CPUs // guard against read after write hazards by checking the address, but // only the lower 11 bits. We avoid a false dependency between writes to // consecutive rows by ensuring their sizes are not multiples of 2 KiB. // Avoid2K prevents the same problem for the planes of an Image3. if (bytes_per_row % CacheAligned::kAlias == 0) { bytes_per_row += align; } JXL_ASSERT(bytes_per_row % align == 0); return bytes_per_row; } } // namespace PlaneBase::PlaneBase(const size_t xsize, const size_t ysize, const size_t sizeof_t) : xsize_(static_cast<uint32_t>(xsize)), ysize_(static_cast<uint32_t>(ysize)), orig_xsize_(static_cast<uint32_t>(xsize)), orig_ysize_(static_cast<uint32_t>(ysize)) { // (Can't profile CacheAligned itself because it is used by profiler.h) PROFILER_FUNC; JXL_CHECK(xsize == xsize_); JXL_CHECK(ysize == ysize_); JXL_ASSERT(sizeof_t == 1 || sizeof_t == 2 || sizeof_t == 4 || sizeof_t == 8); bytes_per_row_ = 0; // Dimensions can be zero, e.g. for lazily-allocated images. Only allocate // if nonzero, because "zero" bytes still have padding/bookkeeping overhead. if (xsize != 0 && ysize != 0) { bytes_per_row_ = BytesPerRow(xsize, sizeof_t); bytes_ = AllocateArray(bytes_per_row_ * ysize); JXL_CHECK(bytes_.get()); InitializePadding(sizeof_t, Padding::kRoundUp); } } void PlaneBase::InitializePadding(const size_t sizeof_t, Padding padding) { #if defined(MEMORY_SANITIZER) || HWY_IDE if (xsize_ == 0 || ysize_ == 0) return; const size_t vec_size = VectorSize(); if (vec_size == 0) return; // Scalar mode: no padding needed const size_t valid_size = xsize_ * sizeof_t; const size_t initialize_size = padding == Padding::kRoundUp ? RoundUpTo(valid_size, vec_size) : valid_size + vec_size - sizeof_t; if (valid_size == initialize_size) return; for (size_t y = 0; y < ysize_; ++y) { uint8_t* JXL_RESTRICT row = static_cast<uint8_t*>(VoidRow(y)); #if defined(__clang__) && (__clang_major__ <= 6) // There's a bug in msan in clang-6 when handling AVX2 operations. This // workaround allows tests to pass on msan, although it is slower and // prevents msan warnings from uninitialized images. std::fill(row, msan::kSanitizerSentinelByte, initialize_size); #else memset(row + valid_size, msan::kSanitizerSentinelByte, initialize_size - valid_size); #endif // clang6 } #endif // MEMORY_SANITIZER } void PlaneBase::Swap(PlaneBase& other) { std::swap(xsize_, other.xsize_); std::swap(ysize_, other.ysize_); std::swap(orig_xsize_, other.orig_xsize_); std::swap(orig_ysize_, other.orig_ysize_); std::swap(bytes_per_row_, other.bytes_per_row_); std::swap(bytes_, other.bytes_); } ImageB ImageFromPacked(const uint8_t* packed, const size_t xsize, const size_t ysize, const size_t bytes_per_row) { JXL_ASSERT(bytes_per_row >= xsize); ImageB image(xsize, ysize); PROFILER_FUNC; for (size_t y = 0; y < ysize; ++y) { uint8_t* const JXL_RESTRICT row = image.Row(y); const uint8_t* const JXL_RESTRICT packed_row = packed + y * bytes_per_row; memcpy(row, packed_row, xsize); } return image; } // Note that using mirroring here gives slightly worse results. ImageF PadImage(const ImageF& in, const size_t xsize, const size_t ysize) { JXL_ASSERT(xsize >= in.xsize()); JXL_ASSERT(ysize >= in.ysize()); ImageF out(xsize, ysize); size_t y = 0; for (; y < in.ysize(); ++y) { const float* JXL_RESTRICT row_in = in.ConstRow(y); float* JXL_RESTRICT row_out = out.Row(y); memcpy(row_out, row_in, in.xsize() * sizeof(row_in[0])); const int lastcol = in.xsize() - 1; const float lastval = row_out[lastcol]; for (size_t x = in.xsize(); x < xsize; ++x) { row_out[x] = lastval; } } // TODO(janwas): no need to copy if we can 'extend' image: if rows are // pointers to any memory? Or allocate larger image before IO? const int lastrow = in.ysize() - 1; for (; y < ysize; ++y) { const float* JXL_RESTRICT row_in = out.ConstRow(lastrow); float* JXL_RESTRICT row_out = out.Row(y); memcpy(row_out, row_in, xsize * sizeof(row_out[0])); } return out; } Image3F PadImageMirror(const Image3F& in, const size_t xborder, const size_t yborder) { size_t xsize = in.xsize(); size_t ysize = in.ysize(); Image3F out(xsize + 2 * xborder, ysize + 2 * yborder); if (xborder > xsize || yborder > ysize) { for (size_t c = 0; c < 3; c++) { for (int32_t y = 0; y < static_cast<int32_t>(out.ysize()); y++) { float* row_out = out.PlaneRow(c, y); const float* row_in = in.PlaneRow( c, Mirror(y - static_cast<int32_t>(yborder), in.ysize())); for (int32_t x = 0; x < static_cast<int32_t>(out.xsize()); x++) { int32_t xin = Mirror(x - static_cast<int32_t>(xborder), in.xsize()); row_out[x] = row_in[xin]; } } } return out; } CopyImageTo(in, Rect(xborder, yborder, xsize, ysize), &out); for (size_t c = 0; c < 3; c++) { // Horizontal pad. for (size_t y = 0; y < ysize; y++) { for (size_t x = 0; x < xborder; x++) { out.PlaneRow(c, y + yborder)[x] = in.ConstPlaneRow(c, y)[xborder - x - 1]; out.PlaneRow(c, y + yborder)[x + xsize + xborder] = in.ConstPlaneRow(c, y)[xsize - 1 - x]; } } // Vertical pad. for (size_t y = 0; y < yborder; y++) { memcpy(out.PlaneRow(c, y), out.ConstPlaneRow(c, 2 * yborder - 1 - y), out.xsize() * sizeof(float)); memcpy(out.PlaneRow(c, y + ysize + yborder), out.ConstPlaneRow(c, ysize + yborder - 1 - y), out.xsize() * sizeof(float)); } } return out; } Image3F PadImageToMultiple(const Image3F& in, const size_t N) { PROFILER_FUNC; const size_t xsize_blocks = DivCeil(in.xsize(), N); const size_t ysize_blocks = DivCeil(in.ysize(), N); const size_t xsize = N * xsize_blocks; const size_t ysize = N * ysize_blocks; ImageF out[3]; for (size_t c = 0; c < 3; ++c) { out[c] = PadImage(in.Plane(c), xsize, ysize); } return Image3F(std::move(out[0]), std::move(out[1]), std::move(out[2])); } void PadImageToBlockMultipleInPlace(Image3F* JXL_RESTRICT in) { PROFILER_FUNC; const size_t xsize_orig = in->xsize(); const size_t ysize_orig = in->ysize(); const size_t xsize = RoundUpToBlockDim(xsize_orig); const size_t ysize = RoundUpToBlockDim(ysize_orig); // Expands image size to the originally-allocated size. in->ShrinkTo(xsize, ysize); for (size_t c = 0; c < 3; c++) { for (size_t y = 0; y < ysize_orig; y++) { float* JXL_RESTRICT row = in->PlaneRow(c, y); for (size_t x = xsize_orig; x < xsize; x++) { row[x] = row[xsize_orig - 1]; } } const float* JXL_RESTRICT row_src = in->ConstPlaneRow(c, ysize_orig - 1); for (size_t y = ysize_orig; y < ysize; y++) { memcpy(in->PlaneRow(c, y), row_src, xsize * sizeof(float)); } } } float DotProduct(const ImageF& a, const ImageF& b) { double sum = 0.0; for (size_t y = 0; y < a.ysize(); ++y) { const float* const JXL_RESTRICT row_a = a.ConstRow(y); const float* const JXL_RESTRICT row_b = b.ConstRow(y); for (size_t x = 0; x < a.xsize(); ++x) { sum += row_a[x] * row_b[x]; } } return sum; } static void DownsampleImage(const ImageF& input, size_t factor, ImageF* output) { JXL_ASSERT(factor != 1); output->ShrinkTo(DivCeil(input.xsize(), factor), DivCeil(input.ysize(), factor)); size_t in_stride = input.PixelsPerRow(); for (size_t y = 0; y < output->ysize(); y++) { float* row_out = output->Row(y); const float* row_in = input.Row(factor * y); for (size_t x = 0; x < output->xsize(); x++) { size_t cnt = 0; float sum = 0; for (size_t iy = 0; iy < factor && iy + factor * y < input.ysize(); iy++) { for (size_t ix = 0; ix < factor && ix + factor * x < input.xsize(); ix++) { sum += row_in[iy * in_stride + x * factor + ix]; cnt++; } } row_out[x] = sum / cnt; } } } void DownsampleImage(ImageF* image, size_t factor) { // Allocate extra space to avoid a reallocation when padding. ImageF downsampled(DivCeil(image->xsize(), factor) + kBlockDim, DivCeil(image->ysize(), factor) + kBlockDim); DownsampleImage(*image, factor, &downsampled); *image = std::move(downsampled); } void DownsampleImage(Image3F* opsin, size_t factor) { JXL_ASSERT(factor != 1); // Allocate extra space to avoid a reallocation when padding. Image3F downsampled(DivCeil(opsin->xsize(), factor) + kBlockDim, DivCeil(opsin->ysize(), factor) + kBlockDim); downsampled.ShrinkTo(downsampled.xsize() - kBlockDim, downsampled.ysize() - kBlockDim); for (size_t c = 0; c < 3; c++) { DownsampleImage(opsin->Plane(c), factor, &downsampled.Plane(c)); } *opsin = std::move(downsampled); } } // namespace jxl #endif // HWY_ONCE <commit_msg>remove unused function in image.cc (#644)<commit_after>// Copyright (c) the JPEG XL Project 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 "lib/jxl/image.h" #include <algorithm> // swap #undef HWY_TARGET_INCLUDE #define HWY_TARGET_INCLUDE "lib/jxl/image.cc" #include <hwy/foreach_target.h> #include <hwy/highway.h> #include "lib/jxl/base/profiler.h" #include "lib/jxl/common.h" #include "lib/jxl/image_ops.h" #include "lib/jxl/sanitizers.h" HWY_BEFORE_NAMESPACE(); namespace jxl { namespace HWY_NAMESPACE { size_t GetVectorSize() { return HWY_LANES(uint8_t); } // NOLINTNEXTLINE(google-readability-namespace-comments) } // namespace HWY_NAMESPACE } // namespace jxl HWY_AFTER_NAMESPACE(); #if HWY_ONCE namespace jxl { namespace { HWY_EXPORT(GetVectorSize); // Local function. size_t VectorSize() { static size_t bytes = HWY_DYNAMIC_DISPATCH(GetVectorSize)(); return bytes; } // Returns distance [bytes] between the start of two consecutive rows, a // multiple of vector/cache line size but NOT CacheAligned::kAlias - see below. size_t BytesPerRow(const size_t xsize, const size_t sizeof_t) { const size_t vec_size = VectorSize(); size_t valid_bytes = xsize * sizeof_t; // Allow unaligned accesses starting at the last valid value - this may raise // msan errors unless the user calls InitializePaddingForUnalignedAccesses. // Skip for the scalar case because no extra lanes will be loaded. if (vec_size != 0) { valid_bytes += vec_size - sizeof_t; } // Round up to vector and cache line size. const size_t align = std::max(vec_size, CacheAligned::kAlignment); size_t bytes_per_row = RoundUpTo(valid_bytes, align); // During the lengthy window before writes are committed to memory, CPUs // guard against read after write hazards by checking the address, but // only the lower 11 bits. We avoid a false dependency between writes to // consecutive rows by ensuring their sizes are not multiples of 2 KiB. // Avoid2K prevents the same problem for the planes of an Image3. if (bytes_per_row % CacheAligned::kAlias == 0) { bytes_per_row += align; } JXL_ASSERT(bytes_per_row % align == 0); return bytes_per_row; } } // namespace PlaneBase::PlaneBase(const size_t xsize, const size_t ysize, const size_t sizeof_t) : xsize_(static_cast<uint32_t>(xsize)), ysize_(static_cast<uint32_t>(ysize)), orig_xsize_(static_cast<uint32_t>(xsize)), orig_ysize_(static_cast<uint32_t>(ysize)) { // (Can't profile CacheAligned itself because it is used by profiler.h) PROFILER_FUNC; JXL_CHECK(xsize == xsize_); JXL_CHECK(ysize == ysize_); JXL_ASSERT(sizeof_t == 1 || sizeof_t == 2 || sizeof_t == 4 || sizeof_t == 8); bytes_per_row_ = 0; // Dimensions can be zero, e.g. for lazily-allocated images. Only allocate // if nonzero, because "zero" bytes still have padding/bookkeeping overhead. if (xsize != 0 && ysize != 0) { bytes_per_row_ = BytesPerRow(xsize, sizeof_t); bytes_ = AllocateArray(bytes_per_row_ * ysize); JXL_CHECK(bytes_.get()); InitializePadding(sizeof_t, Padding::kRoundUp); } } void PlaneBase::InitializePadding(const size_t sizeof_t, Padding padding) { #if defined(MEMORY_SANITIZER) || HWY_IDE if (xsize_ == 0 || ysize_ == 0) return; const size_t vec_size = VectorSize(); if (vec_size == 0) return; // Scalar mode: no padding needed const size_t valid_size = xsize_ * sizeof_t; const size_t initialize_size = padding == Padding::kRoundUp ? RoundUpTo(valid_size, vec_size) : valid_size + vec_size - sizeof_t; if (valid_size == initialize_size) return; for (size_t y = 0; y < ysize_; ++y) { uint8_t* JXL_RESTRICT row = static_cast<uint8_t*>(VoidRow(y)); #if defined(__clang__) && (__clang_major__ <= 6) // There's a bug in msan in clang-6 when handling AVX2 operations. This // workaround allows tests to pass on msan, although it is slower and // prevents msan warnings from uninitialized images. std::fill(row, msan::kSanitizerSentinelByte, initialize_size); #else memset(row + valid_size, msan::kSanitizerSentinelByte, initialize_size - valid_size); #endif // clang6 } #endif // MEMORY_SANITIZER } void PlaneBase::Swap(PlaneBase& other) { std::swap(xsize_, other.xsize_); std::swap(ysize_, other.ysize_); std::swap(orig_xsize_, other.orig_xsize_); std::swap(orig_ysize_, other.orig_ysize_); std::swap(bytes_per_row_, other.bytes_per_row_); std::swap(bytes_, other.bytes_); } ImageB ImageFromPacked(const uint8_t* packed, const size_t xsize, const size_t ysize, const size_t bytes_per_row) { JXL_ASSERT(bytes_per_row >= xsize); ImageB image(xsize, ysize); PROFILER_FUNC; for (size_t y = 0; y < ysize; ++y) { uint8_t* const JXL_RESTRICT row = image.Row(y); const uint8_t* const JXL_RESTRICT packed_row = packed + y * bytes_per_row; memcpy(row, packed_row, xsize); } return image; } // Note that using mirroring here gives slightly worse results. ImageF PadImage(const ImageF& in, const size_t xsize, const size_t ysize) { JXL_ASSERT(xsize >= in.xsize()); JXL_ASSERT(ysize >= in.ysize()); ImageF out(xsize, ysize); size_t y = 0; for (; y < in.ysize(); ++y) { const float* JXL_RESTRICT row_in = in.ConstRow(y); float* JXL_RESTRICT row_out = out.Row(y); memcpy(row_out, row_in, in.xsize() * sizeof(row_in[0])); const int lastcol = in.xsize() - 1; const float lastval = row_out[lastcol]; for (size_t x = in.xsize(); x < xsize; ++x) { row_out[x] = lastval; } } // TODO(janwas): no need to copy if we can 'extend' image: if rows are // pointers to any memory? Or allocate larger image before IO? const int lastrow = in.ysize() - 1; for (; y < ysize; ++y) { const float* JXL_RESTRICT row_in = out.ConstRow(lastrow); float* JXL_RESTRICT row_out = out.Row(y); memcpy(row_out, row_in, xsize * sizeof(row_out[0])); } return out; } Image3F PadImageMirror(const Image3F& in, const size_t xborder, const size_t yborder) { size_t xsize = in.xsize(); size_t ysize = in.ysize(); Image3F out(xsize + 2 * xborder, ysize + 2 * yborder); if (xborder > xsize || yborder > ysize) { for (size_t c = 0; c < 3; c++) { for (int32_t y = 0; y < static_cast<int32_t>(out.ysize()); y++) { float* row_out = out.PlaneRow(c, y); const float* row_in = in.PlaneRow( c, Mirror(y - static_cast<int32_t>(yborder), in.ysize())); for (int32_t x = 0; x < static_cast<int32_t>(out.xsize()); x++) { int32_t xin = Mirror(x - static_cast<int32_t>(xborder), in.xsize()); row_out[x] = row_in[xin]; } } } return out; } CopyImageTo(in, Rect(xborder, yborder, xsize, ysize), &out); for (size_t c = 0; c < 3; c++) { // Horizontal pad. for (size_t y = 0; y < ysize; y++) { for (size_t x = 0; x < xborder; x++) { out.PlaneRow(c, y + yborder)[x] = in.ConstPlaneRow(c, y)[xborder - x - 1]; out.PlaneRow(c, y + yborder)[x + xsize + xborder] = in.ConstPlaneRow(c, y)[xsize - 1 - x]; } } // Vertical pad. for (size_t y = 0; y < yborder; y++) { memcpy(out.PlaneRow(c, y), out.ConstPlaneRow(c, 2 * yborder - 1 - y), out.xsize() * sizeof(float)); memcpy(out.PlaneRow(c, y + ysize + yborder), out.ConstPlaneRow(c, ysize + yborder - 1 - y), out.xsize() * sizeof(float)); } } return out; } Image3F PadImageToMultiple(const Image3F& in, const size_t N) { PROFILER_FUNC; const size_t xsize_blocks = DivCeil(in.xsize(), N); const size_t ysize_blocks = DivCeil(in.ysize(), N); const size_t xsize = N * xsize_blocks; const size_t ysize = N * ysize_blocks; ImageF out[3]; for (size_t c = 0; c < 3; ++c) { out[c] = PadImage(in.Plane(c), xsize, ysize); } return Image3F(std::move(out[0]), std::move(out[1]), std::move(out[2])); } void PadImageToBlockMultipleInPlace(Image3F* JXL_RESTRICT in) { PROFILER_FUNC; const size_t xsize_orig = in->xsize(); const size_t ysize_orig = in->ysize(); const size_t xsize = RoundUpToBlockDim(xsize_orig); const size_t ysize = RoundUpToBlockDim(ysize_orig); // Expands image size to the originally-allocated size. in->ShrinkTo(xsize, ysize); for (size_t c = 0; c < 3; c++) { for (size_t y = 0; y < ysize_orig; y++) { float* JXL_RESTRICT row = in->PlaneRow(c, y); for (size_t x = xsize_orig; x < xsize; x++) { row[x] = row[xsize_orig - 1]; } } const float* JXL_RESTRICT row_src = in->ConstPlaneRow(c, ysize_orig - 1); for (size_t y = ysize_orig; y < ysize; y++) { memcpy(in->PlaneRow(c, y), row_src, xsize * sizeof(float)); } } } static void DownsampleImage(const ImageF& input, size_t factor, ImageF* output) { JXL_ASSERT(factor != 1); output->ShrinkTo(DivCeil(input.xsize(), factor), DivCeil(input.ysize(), factor)); size_t in_stride = input.PixelsPerRow(); for (size_t y = 0; y < output->ysize(); y++) { float* row_out = output->Row(y); const float* row_in = input.Row(factor * y); for (size_t x = 0; x < output->xsize(); x++) { size_t cnt = 0; float sum = 0; for (size_t iy = 0; iy < factor && iy + factor * y < input.ysize(); iy++) { for (size_t ix = 0; ix < factor && ix + factor * x < input.xsize(); ix++) { sum += row_in[iy * in_stride + x * factor + ix]; cnt++; } } row_out[x] = sum / cnt; } } } void DownsampleImage(ImageF* image, size_t factor) { // Allocate extra space to avoid a reallocation when padding. ImageF downsampled(DivCeil(image->xsize(), factor) + kBlockDim, DivCeil(image->ysize(), factor) + kBlockDim); DownsampleImage(*image, factor, &downsampled); *image = std::move(downsampled); } void DownsampleImage(Image3F* opsin, size_t factor) { JXL_ASSERT(factor != 1); // Allocate extra space to avoid a reallocation when padding. Image3F downsampled(DivCeil(opsin->xsize(), factor) + kBlockDim, DivCeil(opsin->ysize(), factor) + kBlockDim); downsampled.ShrinkTo(downsampled.xsize() - kBlockDim, downsampled.ysize() - kBlockDim); for (size_t c = 0; c < 3; c++) { DownsampleImage(opsin->Plane(c), factor, &downsampled.Plane(c)); } *opsin = std::move(downsampled); } } // namespace jxl #endif // HWY_ONCE <|endoftext|>
<commit_before>//=-- lsan.cc -------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of LeakSanitizer. // Standalone LSan RTL. // //===----------------------------------------------------------------------===// #include "lsan.h" #include "sanitizer_common/sanitizer_flags.h" #include "sanitizer_common/sanitizer_stacktrace.h" #include "lsan_allocator.h" #include "lsan_common.h" #include "lsan_thread.h" namespace __lsan { static void InitializeCommonFlags() { CommonFlags *cf = common_flags(); cf->external_symbolizer_path = GetEnv("LSAN_SYMBOLIZER_PATH"); cf->symbolize = (cf->external_symbolizer_path && cf->external_symbolizer_path[0]); cf->strip_path_prefix = ""; cf->fast_unwind_on_malloc = true; cf->malloc_context_size = 30; ParseCommonFlagsFromString(GetEnv("LSAN_OPTIONS")); } void Init() { static bool inited; if (inited) return; inited = true; SanitizerToolName = "LeakSanitizer"; InitializeCommonFlags(); InitializeAllocator(); InitTlsSize(); InitializeInterceptors(); InitializeThreadRegistry(); u32 tid = ThreadCreate(0, 0, true); CHECK_EQ(tid, 0); ThreadStart(tid, GetTid()); // Start symbolizer process if necessary. const char* external_symbolizer = common_flags()->external_symbolizer_path; if (common_flags()->symbolize && external_symbolizer && external_symbolizer[0]) { InitializeExternalSymbolizer(external_symbolizer); } InitCommonLsan(); Atexit(DoLeakCheck); } } // namespace __lsan <commit_msg>[lsan] Set current_thread_tid correctly for main thread.<commit_after>//=-- lsan.cc -------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of LeakSanitizer. // Standalone LSan RTL. // //===----------------------------------------------------------------------===// #include "lsan.h" #include "sanitizer_common/sanitizer_flags.h" #include "sanitizer_common/sanitizer_stacktrace.h" #include "lsan_allocator.h" #include "lsan_common.h" #include "lsan_thread.h" namespace __lsan { static void InitializeCommonFlags() { CommonFlags *cf = common_flags(); cf->external_symbolizer_path = GetEnv("LSAN_SYMBOLIZER_PATH"); cf->symbolize = (cf->external_symbolizer_path && cf->external_symbolizer_path[0]); cf->strip_path_prefix = ""; cf->fast_unwind_on_malloc = true; cf->malloc_context_size = 30; ParseCommonFlagsFromString(GetEnv("LSAN_OPTIONS")); } void Init() { static bool inited; if (inited) return; inited = true; SanitizerToolName = "LeakSanitizer"; InitializeCommonFlags(); InitializeAllocator(); InitTlsSize(); InitializeInterceptors(); InitializeThreadRegistry(); u32 tid = ThreadCreate(0, 0, true); CHECK_EQ(tid, 0); ThreadStart(tid, GetTid()); SetCurrentThread(tid); // Start symbolizer process if necessary. const char* external_symbolizer = common_flags()->external_symbolizer_path; if (common_flags()->symbolize && external_symbolizer && external_symbolizer[0]) { InitializeExternalSymbolizer(external_symbolizer); } InitCommonLsan(); Atexit(DoLeakCheck); } } // namespace __lsan <|endoftext|>
<commit_before><commit_msg>fixed string fixed<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <fstream> #include <iterator> #include <zlib.h> #include "mszreader.hh" #include "math/dataset.hh" #include "math/forwardselection.hh" #include "math/ridgeregression.hh" using std::vector; using std::string; using std::cerr; using std::ofstream; using namespace iomsz; void outputModelHeader(const vector<double> &w, const vector<string> &labels, const string& path) { ofstream file; file.open(path.c_str()); // Generate Header Guard size_t slashpos = path.find_last_of("/"); string guard(path, slashpos+1); for(size_t i = 0; i < guard.size(); i++) { if(isalpha(guard[i])) guard[i] = toupper(guard[i]); else if(guard[i] == '.') guard[i] = '_'; } file << "#ifndef " << guard << "\n" << "#define " << guard << "\n" << "\n" << "static double w[] = {"; copy(w.begin(), w.end(), std::ostream_iterator<double>(file, ", ")); file << "};\n\n"; file << "static char* features[" << labels.size() << "] = {"; for(size_t i = 0; i < labels.size(); i++) { file << "\"" << labels[i] << "\""; if(i != labels.size() - 1) file << ", "; } file << "};\n\n"; file << "#endif"; file.close(); } /** * Main function for MaxSATzilla training. * This function received 3 arguments: * - Forward Selection Threshold; * - Ridge Regression Scalar Delta; * - Name of the file with training set; * - Prefix for header output; */ int main(int argc, char *argv[]) { if (argc <= 1 || argc >= 6) { cerr << "usage: coach <fsthreshold> <delta> <trainingset> <headerprefix>\n"; exit(EXIT_FAILURE); } unsigned int nbSolvers, nbFeatures, nbInstances, timeOut; string *solversNames; string *featuresNames; string *instancesNames; double **data; double threshold = atof(argv[1]); double delta = atof(argv[2]); char *inputFileName = argv[3]; char *headerPrefix = argv[4]; gzFile in=(inputFileName==NULL? gzdopen(0,"rb"): gzopen(inputFileName,"rb")); if (in==NULL) { cerr<<"Error: Could not open file: " <<(inputFileName==NULL? "<stdin>": inputFileName) <<endl; exit(1); } parse_DIMACS(in, nbSolvers, nbFeatures, nbInstances, timeOut, solversNames, featuresNames, instancesNames, data); cerr << "\n\n\nPOCM part... from now, all problems are MINE! :)\n"; cerr << "Read file: " << inputFileName << "\n" << "Number of Solvers: " << nbSolvers << "\n" << "Number of Features: " << nbFeatures << "\n" << "Number of Instances: " << nbInstances << "\n" << "Timeout: " << timeOut << "\n"; cerr << "Solver Names: "; for(size_t i = 0; i < nbSolvers; i++) cerr << solversNames[i] << " "; cerr << "\nFeature Names: "; for(size_t i = 0; i < nbFeatures; i++) cerr << featuresNames[i] << " "; cerr << "\nInstance Names: "; for(size_t i = 0; i < nbInstances; i++) cerr << instancesNames[i] << " "; cerr << "\n"; try { MSZDataSet *ds = createDataSet(data, nbInstances, nbFeatures+nbSolvers, nbSolvers); vector<string> snames; for(size_t s = 0; s < nbSolvers; s++) snames.push_back(solversNames[s]); ds->printSolverStats(timeOut, snames); // Lets create the plot files vector<string> labels; for(size_t i = 0; i < nbSolvers; i++) labels.push_back(solversNames[i]); for(size_t i = 0; i < nbFeatures; i++) labels.push_back(featuresNames[i]); cerr << "Created labels for solvers and features of size : " << labels.size() << "\n"; cerr << "features (" << nbFeatures << ") + solvers(" << nbSolvers << ") = " << labels.size() << "\n"; ds->dumpPlotFiles(labels, "./coach"); // Let's apply dataset transformations ds->standardize(); ds->standardizeOutputs(); //ds->expand(2); // always calls standardize() if you didn't before // Lets do a forward selection for(size_t s = 0; s < nbSolvers; s++) { ForwardSelection fs(*ds, s); vector<size_t> res = fs.run(threshold); MSZDataSet solverDS = *ds; solverDS.removeFeatures(res); RidgeRegression rr(solverDS); vector<double> w; w = rr.run(delta, s); vector<string> wlabels; for(size_t i = 0; i < res.size(); i++) wlabels.push_back(featuresNames[res[i]]); assert(w.size() == wlabels.size()); outputModelHeader(w, wlabels, string(headerPrefix)+snames[s]+".hh"); } // Let's not forget to delete the dataset delete ds; } catch(std::bad_alloc) { cerr << "Coach: Bad memory allocation or not enough memory on the system\n." << "Exiting peacefully...\n"; exit(EXIT_FAILURE); } return 0; } <commit_msg>Now coach writes a file with all the models.<commit_after>#include <iostream> #include <vector> #include <fstream> #include <iterator> #include <map> #include <zlib.h> #include "mszreader.hh" #include "math/dataset.hh" #include "math/forwardselection.hh" #include "math/ridgeregression.hh" using std::vector; using std::string; using std::cerr; using std::ofstream; using std::map; using namespace iomsz; #ifndef MODELHEADER #define MODELHEADER "msz_model.hh" #endif void outputModelHeader(const map<string, pair<vector<double>, vector<string> > > &m) { const string path(MODELHEADER); ofstream file; file.open(path.c_str()); // Generate Header Guard size_t slashpos = path.find_last_of("/"); string guard(path, slashpos+1); for(size_t i = 0; i < guard.size(); i++) { if(isalpha(guard[i])) guard[i] = toupper(guard[i]); else if(guard[i] == '.') guard[i] = '_'; } file << "#ifndef " << guard << "\n" << "#define " << guard << "\n" << "\n"; file << "enum Solver {"; for(map<string, pair<vector<double>, vector<string> > >::const_iterator it = m.begin(); it != m.end(); it++) { file << it->first << ", "; } file << " NUMSOLVERS};\n\n"; file << "size_t nbFeatures[] = {"; vector<size_t> nbFeatures; for(map<string, pair<vector<double>, vector<string> > >::const_iterator it = m.begin(); it != m.end(); it++) { nbFeatures.push_back(it->second.first.size()); } for(size_t i = 0; i < nbFeatures.size(); i++) { file << nbFeatures[i]; if(i != nbFeatures.size() - 1) file << ", "; } file << "};\n\n"; file << "double weights[" << m.size() << "][] = {"; size_t mindex = 0; for(map<string, pair<vector<double>, vector<string> > >::const_iterator it = m.begin(); it != m.end(); it++) { const bool last = (mindex++ == m.size()-1); const vector<double> &w = it->second.first; file << "{"; for(size_t i = 0; i < w.size(); i++) { file << w[i]; if(i != w.size()) file << ", "; } file << "}"; if(!last) file << ", "; } file << "};\n\n"; file << "char* features[" << m.size() << "][] = {"; mindex = 0; for(map<string, pair<vector<double>, vector<string> > >::const_iterator it = m.begin(); it != m.end(); it++) { const bool last = (mindex++ == m.size()-1); const vector<string> &l = it->second.second; file << "{"; for(size_t i = 0; i < l.size(); i++) { file << "\"" << l[i] << "\""; if(i != l.size() - 1) file << ", "; } file << "}"; if(!last) file << ", "; } file << "};\n\n"; file << "#endif"; file.close(); } /** * Main function for MaxSATzilla training. * This function received 3 arguments: * - Forward Selection Threshold; * - Ridge Regression Scalar Delta; * - Name of the file with training set; * - Prefix for header output; */ int main(int argc, char *argv[]) { if (argc != 4) { cerr << "usage: coach <fsthreshold> <delta> <trainingset>\n"; exit(EXIT_FAILURE); } unsigned int nbSolvers, nbFeatures, nbInstances, timeOut; string *solversNames; string *featuresNames; string *instancesNames; double **data; double threshold = atof(argv[1]); double delta = atof(argv[2]); char *inputFileName = argv[3]; gzFile in =(inputFileName == NULL ? gzdopen(0,"rb"): gzopen(inputFileName,"rb")); if (in == NULL) { cerr<<"Error: Could not open file: " <<(inputFileName==NULL? "<stdin>": inputFileName) <<endl; exit(1); } parse_DIMACS(in, nbSolvers, nbFeatures, nbInstances, timeOut, solversNames, featuresNames, instancesNames, data); cerr << "\n\n\nPOCM part... from now, all problems are MINE! :)\n"; cerr << "Read file: " << inputFileName << "\n" << "Number of Solvers: " << nbSolvers << "\n" << "Number of Features: " << nbFeatures << "\n" << "Number of Instances: " << nbInstances << "\n" << "Timeout: " << timeOut << "\n"; cerr << "Solver Names: "; for(size_t i = 0; i < nbSolvers; i++) cerr << solversNames[i] << " "; cerr << "\nFeature Names: "; for(size_t i = 0; i < nbFeatures; i++) cerr << featuresNames[i] << " "; cerr << "\nInstance Names: "; for(size_t i = 0; i < nbInstances; i++) cerr << instancesNames[i] << " "; cerr << "\n"; try { MSZDataSet *ds = createDataSet(data, nbInstances, nbFeatures+nbSolvers, nbSolvers); vector<string> snames; for(size_t s = 0; s < nbSolvers; s++) snames.push_back(solversNames[s]); ds->printSolverStats(timeOut, snames); // Lets create the plot files vector<string> labels; for(size_t i = 0; i < nbSolvers; i++) labels.push_back(solversNames[i]); for(size_t i = 0; i < nbFeatures; i++) labels.push_back(featuresNames[i]); cerr << "Created labels for solvers and features of size : " << labels.size() << "\n"; cerr << "features (" << nbFeatures << ") + solvers(" << nbSolvers << ") = " << labels.size() << "\n"; ds->dumpPlotFiles(labels, "./coach"); // Let's apply dataset transformations ds->standardize(); ds->standardizeOutputs(); //ds->expand(2); // always calls standardize() if you didn't before map<string, pair<vector<double>, vector<string> > > model; // Lets do a forward selection for(size_t s = 0; s < nbSolvers; s++) { ForwardSelection fs(*ds, s); vector<size_t> res = fs.run(threshold); MSZDataSet solverDS = *ds; solverDS.removeFeatures(res); RidgeRegression rr(solverDS); vector<double> w; w = rr.run(delta, s); vector<string> wlabels; for(size_t i = 0; i < res.size(); i++) wlabels.push_back(featuresNames[res[i]]); assert(w.size() == wlabels.size()); model[solversNames[s]] = make_pair(w, wlabels); } outputModelHeader(model); // Let's not forget to delete the dataset delete ds; } catch(std::bad_alloc) { cerr << "Coach: Bad memory allocation or not enough memory on the system\n." << "Exiting peacefully...\n"; exit(EXIT_FAILURE); } return 0; } <|endoftext|>
<commit_before>#include <assert.h> #include "Provider.h" #include "Dll.h" #pragma warning(push) #pragma warning(disable : 4995) #include <shlwapi.h> #pragma warning(pop) #include "Macros.h" #include "TileUiLogon.h" #include "TileUiUnlock.h" #include "ProviderGuid.h" #include "SerializationHelpers.h" #include <wincred.h> namespace pGina { namespace CredProv { IFACEMETHODIMP Provider::QueryInterface(__in REFIID riid, __deref_out void **ppv) { // And more crazy ass v-table madness, yay COM again! static const QITAB qit[] = { QITABENT(Provider, ICredentialProvider), {0}, }; return QISearch(this, qit, riid, ppv); } IFACEMETHODIMP_(ULONG) Provider::AddRef() { return InterlockedIncrement(&m_referenceCount); } IFACEMETHODIMP_(ULONG) Provider::Release() { LONG count = InterlockedDecrement(&m_referenceCount); if (!count) delete this; return count; } Provider::Provider() : m_referenceCount(1), m_usageScenario(CPUS_INVALID), m_logonUiCallbackEvents(NULL), m_logonUiCallbackContext(0), m_credential(NULL), m_usageFlags(0), m_setSerialization(NULL) { AddDllReference(); } Provider::~Provider() { UnAdvise(); ReleaseDllReference(); if(m_credential) { m_credential->Release(); m_credential = NULL; } if(m_setSerialization) { LocalFree(m_setSerialization); m_setSerialization = NULL; } } // Poorly named, should be QueryUsageScenarioSupport - LogonUI calls this to find out whether the provided // scenario is one which our provider supports. It also doubles as our shot to do anything before being // called for the scenario in question. IFACEMETHODIMP Provider::SetUsageScenario(__in CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus, __in DWORD dwFlags) { pDEBUG(L"Provider::SetUsageScenario(%d, 0x%08x)", cpus, dwFlags); // Returning E_NOTIMPL indicates no support for the requested scenario, otherwise S_OK suffices. switch(cpus) { case CPUS_LOGON: case CPUS_UNLOCK_WORKSTATION: case CPUS_CREDUI: m_usageScenario = cpus; m_usageFlags = dwFlags; return S_OK; case CPUS_CHANGE_PASSWORD: return E_NOTIMPL; // Todo: Support this case CPUS_PLAP: case CPUS_INVALID: return E_NOTIMPL; default: return E_INVALIDARG; // Say wha? } } IFACEMETHODIMP Provider::SetSerialization(__in const CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* pcpcs) { /*if ((CLSID_CpGinaProvider != pcpcs->clsidCredentialProvider) && (m_usageScenario == CPUS_CREDUI)) return E_INVALIDARG;*/ HRESULT result = E_NOTIMPL; // Must match our auth package (negotiate) ULONG authPackage = 0; result = Microsoft::Sample::RetrieveNegotiateAuthPackage(&authPackage); if(!SUCCEEDED(result)) return result; // Slightly modified behavior depending on flags provided to SetUsageScenario if(m_usageScenario == CPUS_CREDUI) { // Must support the auth package specified in CREDUIWIN_IN_CRED_ONLY and CREDUIWIN_AUTHPACKAGE_ONLY if( ((m_usageFlags & CREDUIWIN_IN_CRED_ONLY) || (m_usageFlags & CREDUIWIN_AUTHPACKAGE_ONLY)) && authPackage != pcpcs->ulAuthenticationPackage) return E_INVALIDARG; // CREDUIWIN_AUTHPACKAGE_ONLY should NOT return S_OK unless we can serialize correctly, // so we default to S_FALSE here and change to S_OK on success. if(m_usageFlags & CREDUIWIN_AUTHPACKAGE_ONLY) result = S_FALSE; } // As long as the package matches, and there is something to read from if(authPackage == pcpcs->ulAuthenticationPackage && pcpcs->cbSerialization > 0 && pcpcs->rgbSerialization) { KERB_INTERACTIVE_UNLOCK_LOGON* pkil = (KERB_INTERACTIVE_UNLOCK_LOGON*) pcpcs->rgbSerialization; if(pkil->Logon.MessageType == KerbInteractiveLogon) { // Must have a username if(pkil->Logon.UserName.Length && pkil->Logon.UserName.Buffer) { BYTE * nativeSerialization = NULL; DWORD nativeSerializationSize = 0; // Do we need to repack in native format? (32 bit client talking to 64 bit host or vice versa) if(m_usageScenario == CPUS_CREDUI && (CREDUIWIN_PACK_32_WOW & m_usageFlags)) { if(!SUCCEEDED(Microsoft::Sample::KerbInteractiveUnlockLogonRepackNative(pcpcs->rgbSerialization, pcpcs->cbSerialization, &nativeSerialization, &nativeSerializationSize))) { return result; } } else { nativeSerialization = (BYTE*) LocalAlloc(LMEM_ZEROINIT, pcpcs->cbSerialization); nativeSerializationSize = pcpcs->cbSerialization; if(!nativeSerialization) return E_OUTOFMEMORY; CopyMemory(nativeSerialization, pcpcs->rgbSerialization, pcpcs->cbSerialization); } Microsoft::Sample::KerbInteractiveUnlockLogonUnpackInPlace((KERB_INTERACTIVE_UNLOCK_LOGON *) nativeSerialization, nativeSerializationSize); if(m_setSerialization) LocalFree(m_setSerialization); m_setSerialization = (KERB_INTERACTIVE_UNLOCK_LOGON *) nativeSerialization; result = S_OK; // All is well! } } } return result; } IFACEMETHODIMP Provider::Advise(__in ICredentialProviderEvents* pcpe, __in UINT_PTR upAdviseContext) { // If we already have a callback handle, release our reference to it UnAdvise(); // Store what we've been given m_logonUiCallbackEvents = pcpe; m_logonUiCallbackContext = upAdviseContext; // Up ref count as we hold a pointer to this guy if(m_logonUiCallbackEvents) { pDEBUG(L"Provider::Advise(%p, %p) - provider events callback reference added", pcpe, upAdviseContext); m_logonUiCallbackEvents->AddRef(); } return S_OK; } IFACEMETHODIMP Provider::UnAdvise() { if(m_logonUiCallbackEvents) { pDEBUG(L"Provider::UnAdvise() - provider events callback reference released"); m_logonUiCallbackEvents->Release(); m_logonUiCallbackEvents = NULL; m_logonUiCallbackContext = 0; } return S_OK; } IFACEMETHODIMP Provider::GetFieldDescriptorCount(__out DWORD* pdwCount) { // # of fields depends on our usage scenario: switch(m_usageScenario) { case CPUS_LOGON: case CPUS_UNLOCK_WORKSTATION: case CPUS_CREDUI: *pdwCount = LUIFI_NUM_FIELDS; return S_OK; default: pERROR(L"Provider::GetFieldDescriptorCount: No UI known for the usage scenario: 0x%08x", m_usageScenario); return S_FALSE; } // Should never reach this assert(0); return S_FALSE; } IFACEMETHODIMP Provider::GetFieldDescriptorAt(__in DWORD dwIndex, __deref_out CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR** ppcpfd) { switch(m_usageScenario) { case CPUS_LOGON: case CPUS_CREDUI: return GetFieldDescriptorForUi(s_logonFields, dwIndex, ppcpfd); case CPUS_UNLOCK_WORKSTATION: return GetFieldDescriptorForUi(s_unlockFields, dwIndex, ppcpfd); default: return E_INVALIDARG; } // Should never reach this assert(0); return S_FALSE; } IFACEMETHODIMP Provider::GetCredentialCount(__out DWORD* pdwCount, __out_range(<,*pdwCount) DWORD* pdwDefault, __out BOOL* pbAutoLogonWithDefault) { // We currently always support only a single tile *pdwCount = 1; *pdwDefault = CREDENTIAL_PROVIDER_NO_DEFAULT; *pbAutoLogonWithDefault = FALSE; // If we were given creds via SetSerialization, and they appear complete, then we can // make that credential our default and attempt an autologon. if(SerializedCredsAppearComplete()) { *pdwDefault = 0; *pbAutoLogonWithDefault = TRUE; } return S_OK; } IFACEMETHODIMP Provider::GetCredentialAt(__in DWORD dwIndex, __deref_out ICredentialProviderCredential** ppcpc) { // Currently we have just the one, we lazy init it here when first requested if(!m_credential) { m_credential = new Credential(); pGina::Memory::ObjectCleanupPool cleanup; PWSTR serializedUser = NULL, serializedPass = NULL; if(SerializedCredsAppearComplete()) { GetSerializedCredentials(&serializedUser, &serializedPass, NULL); cleanup.Add(serializedUser, (void (*)(void *)) LocalFree); cleanup.Add(serializedPass, (void (*)(void *)) LocalFree); } switch(m_usageScenario) { case CPUS_LOGON: case CPUS_CREDUI: m_credential->Initialize(m_usageScenario, s_logonFields, m_usageFlags, serializedUser, serializedPass); break; case CPUS_UNLOCK_WORKSTATION: m_credential->Initialize(m_usageScenario, s_unlockFields, m_usageFlags, serializedUser, serializedPass); break; default: return E_INVALIDARG; } } // Did we fail to create it? OOM if(!m_credential) return E_OUTOFMEMORY; // Better be index 0 (we only have 1 currently) if(dwIndex != 0 || !ppcpc) return E_INVALIDARG; // Alright... QueryIface for ICredentialProviderCredential return m_credential->QueryInterface(IID_ICredentialProviderCredential, reinterpret_cast<void **>(ppcpc)); } IFACEMETHODIMP Provider::GetFieldDescriptorForUi(UI_FIELDS const& fields, DWORD index, CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR **ppcpfd) { // Must be in our count of fields, and we have to have somewhere to stuff the result if(index >= fields.fieldCount && ppcpfd) return E_INVALIDARG; // Should we fail, we want to return a NULL for result *ppcpfd = NULL; // Use CoTaskMemAlloc for the resulting value, then copy in our descriptor DWORD structSize = sizeof(**ppcpfd); CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *pcpfd = (CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *) CoTaskMemAlloc(structSize); if(pcpfd == NULL) return E_OUTOFMEMORY; // Use compilers struct copy, in case fields change down the road *pcpfd = fields.fields[index].fieldDescriptor; // But now we have to fixup the label, which is a ptr, we'll use SHStrDupW which does CoTask alloc if(pcpfd->pszLabel) { if(!SUCCEEDED(SHStrDupW(fields.fields[index].fieldDescriptor.pszLabel, &pcpfd->pszLabel))) { // Dup failed, free up what we've got so far, then get out CoTaskMemFree(pcpfd); return E_OUTOFMEMORY; } } // Got here? Then we win! *ppcpfd = pcpfd; return S_OK; } bool Provider::SerializedCredsAppearComplete() { // Did we get any creds? if(!m_setSerialization) return false; // Can we work out a username and a password at a minimum? if(m_setSerialization->Logon.UserName.Length && m_setSerialization->Logon.UserName.Buffer && m_setSerialization->Logon.Password.Length && m_setSerialization->Logon.Password.Buffer) return true; return false; } void Provider::GetSerializedCredentials(PWSTR *username, PWSTR *password, PWSTR *domain) { if(!SerializedCredsAppearComplete()) return; if(username) { *username = (PWSTR) LocalAlloc(LMEM_ZEROINIT, m_setSerialization->Logon.UserName.Length + sizeof(wchar_t)); CopyMemory(*username, m_setSerialization->Logon.UserName.Buffer, m_setSerialization->Logon.UserName.Length); } if(password) { *password = (PWSTR) LocalAlloc(LMEM_ZEROINIT, m_setSerialization->Logon.Password.Length + sizeof(wchar_t)); CopyMemory(*password, m_setSerialization->Logon.Password.Buffer, m_setSerialization->Logon.Password.Length); } if(domain) { if(m_setSerialization->Logon.LogonDomainName.Length && m_setSerialization->Logon.LogonDomainName.Buffer) { *domain = (PWSTR) LocalAlloc(LMEM_ZEROINIT, m_setSerialization->Logon.LogonDomainName.Length + sizeof(wchar_t)); CopyMemory(*domain, m_setSerialization->Logon.LogonDomainName.Buffer, m_setSerialization->Logon.LogonDomainName.Length); } } } } }<commit_msg>fix bug found during code review while writing up info... yay code review! hehe.<commit_after>#include <assert.h> #include "Provider.h" #include "Dll.h" #pragma warning(push) #pragma warning(disable : 4995) #include <shlwapi.h> #pragma warning(pop) #include "Macros.h" #include "TileUiLogon.h" #include "TileUiUnlock.h" #include "ProviderGuid.h" #include "SerializationHelpers.h" #include <wincred.h> namespace pGina { namespace CredProv { IFACEMETHODIMP Provider::QueryInterface(__in REFIID riid, __deref_out void **ppv) { // And more crazy ass v-table madness, yay COM again! static const QITAB qit[] = { QITABENT(Provider, ICredentialProvider), {0}, }; return QISearch(this, qit, riid, ppv); } IFACEMETHODIMP_(ULONG) Provider::AddRef() { return InterlockedIncrement(&m_referenceCount); } IFACEMETHODIMP_(ULONG) Provider::Release() { LONG count = InterlockedDecrement(&m_referenceCount); if (!count) delete this; return count; } Provider::Provider() : m_referenceCount(1), m_usageScenario(CPUS_INVALID), m_logonUiCallbackEvents(NULL), m_logonUiCallbackContext(0), m_credential(NULL), m_usageFlags(0), m_setSerialization(NULL) { AddDllReference(); } Provider::~Provider() { UnAdvise(); ReleaseDllReference(); if(m_credential) { m_credential->Release(); m_credential = NULL; } if(m_setSerialization) { LocalFree(m_setSerialization); m_setSerialization = NULL; } } // Poorly named, should be QueryUsageScenarioSupport - LogonUI calls this to find out whether the provided // scenario is one which our provider supports. It also doubles as our shot to do anything before being // called for the scenario in question. IFACEMETHODIMP Provider::SetUsageScenario(__in CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus, __in DWORD dwFlags) { pDEBUG(L"Provider::SetUsageScenario(%d, 0x%08x)", cpus, dwFlags); // Returning E_NOTIMPL indicates no support for the requested scenario, otherwise S_OK suffices. switch(cpus) { case CPUS_LOGON: case CPUS_UNLOCK_WORKSTATION: case CPUS_CREDUI: m_usageScenario = cpus; m_usageFlags = dwFlags; return S_OK; case CPUS_CHANGE_PASSWORD: return E_NOTIMPL; // Todo: Support this case CPUS_PLAP: case CPUS_INVALID: return E_NOTIMPL; default: return E_INVALIDARG; // Say wha? } } IFACEMETHODIMP Provider::SetSerialization(__in const CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* pcpcs) { /*if ((CLSID_CpGinaProvider != pcpcs->clsidCredentialProvider) && (m_usageScenario == CPUS_CREDUI)) return E_INVALIDARG;*/ HRESULT result = E_NOTIMPL; // Must match our auth package (negotiate) ULONG authPackage = 0; result = Microsoft::Sample::RetrieveNegotiateAuthPackage(&authPackage); if(!SUCCEEDED(result)) return result; // Slightly modified behavior depending on flags provided to SetUsageScenario if(m_usageScenario == CPUS_CREDUI) { // Must support the auth package specified in CREDUIWIN_IN_CRED_ONLY and CREDUIWIN_AUTHPACKAGE_ONLY if( ((m_usageFlags & CREDUIWIN_IN_CRED_ONLY) || (m_usageFlags & CREDUIWIN_AUTHPACKAGE_ONLY)) && authPackage != pcpcs->ulAuthenticationPackage) return E_INVALIDARG; // CREDUIWIN_AUTHPACKAGE_ONLY should NOT return S_OK unless we can serialize correctly, // so we default to S_FALSE here and change to S_OK on success. if(m_usageFlags & CREDUIWIN_AUTHPACKAGE_ONLY) result = S_FALSE; } // As long as the package matches, and there is something to read from if(authPackage == pcpcs->ulAuthenticationPackage && pcpcs->cbSerialization > 0 && pcpcs->rgbSerialization) { KERB_INTERACTIVE_UNLOCK_LOGON* pkil = (KERB_INTERACTIVE_UNLOCK_LOGON*) pcpcs->rgbSerialization; if(pkil->Logon.MessageType == KerbInteractiveLogon) { // Must have a username if(pkil->Logon.UserName.Length && pkil->Logon.UserName.Buffer) { BYTE * nativeSerialization = NULL; DWORD nativeSerializationSize = 0; // Do we need to repack in native format? (32 bit client talking to 64 bit host or vice versa) if(m_usageScenario == CPUS_CREDUI && (CREDUIWIN_PACK_32_WOW & m_usageFlags)) { if(!SUCCEEDED(Microsoft::Sample::KerbInteractiveUnlockLogonRepackNative(pcpcs->rgbSerialization, pcpcs->cbSerialization, &nativeSerialization, &nativeSerializationSize))) { return result; } } else { nativeSerialization = (BYTE*) LocalAlloc(LMEM_ZEROINIT, pcpcs->cbSerialization); nativeSerializationSize = pcpcs->cbSerialization; if(!nativeSerialization) return E_OUTOFMEMORY; CopyMemory(nativeSerialization, pcpcs->rgbSerialization, pcpcs->cbSerialization); } Microsoft::Sample::KerbInteractiveUnlockLogonUnpackInPlace((KERB_INTERACTIVE_UNLOCK_LOGON *) nativeSerialization, nativeSerializationSize); if(m_setSerialization) LocalFree(m_setSerialization); m_setSerialization = (KERB_INTERACTIVE_UNLOCK_LOGON *) nativeSerialization; result = S_OK; // All is well! } } } return result; } IFACEMETHODIMP Provider::Advise(__in ICredentialProviderEvents* pcpe, __in UINT_PTR upAdviseContext) { // If we already have a callback handle, release our reference to it UnAdvise(); // Store what we've been given m_logonUiCallbackEvents = pcpe; m_logonUiCallbackContext = upAdviseContext; // Up ref count as we hold a pointer to this guy if(m_logonUiCallbackEvents) { pDEBUG(L"Provider::Advise(%p, %p) - provider events callback reference added", pcpe, upAdviseContext); m_logonUiCallbackEvents->AddRef(); } return S_OK; } IFACEMETHODIMP Provider::UnAdvise() { if(m_logonUiCallbackEvents) { pDEBUG(L"Provider::UnAdvise() - provider events callback reference released"); m_logonUiCallbackEvents->Release(); m_logonUiCallbackEvents = NULL; m_logonUiCallbackContext = 0; } return S_OK; } IFACEMETHODIMP Provider::GetFieldDescriptorCount(__out DWORD* pdwCount) { // # of fields depends on our usage scenario: switch(m_usageScenario) { case CPUS_LOGON: case CPUS_CREDUI: *pdwCount = LUIFI_NUM_FIELDS; return S_OK; case CPUS_UNLOCK_WORKSTATION: *pdwCount = LOIFI_NUM_FIELDS; return S_OK; default: pERROR(L"Provider::GetFieldDescriptorCount: No UI known for the usage scenario: 0x%08x", m_usageScenario); return S_FALSE; } // Should never reach this assert(0); return S_FALSE; } IFACEMETHODIMP Provider::GetFieldDescriptorAt(__in DWORD dwIndex, __deref_out CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR** ppcpfd) { switch(m_usageScenario) { case CPUS_LOGON: case CPUS_CREDUI: return GetFieldDescriptorForUi(s_logonFields, dwIndex, ppcpfd); case CPUS_UNLOCK_WORKSTATION: return GetFieldDescriptorForUi(s_unlockFields, dwIndex, ppcpfd); default: return E_INVALIDARG; } // Should never reach this assert(0); return S_FALSE; } IFACEMETHODIMP Provider::GetCredentialCount(__out DWORD* pdwCount, __out_range(<,*pdwCount) DWORD* pdwDefault, __out BOOL* pbAutoLogonWithDefault) { // We currently always support only a single tile *pdwCount = 1; *pdwDefault = CREDENTIAL_PROVIDER_NO_DEFAULT; *pbAutoLogonWithDefault = FALSE; // If we were given creds via SetSerialization, and they appear complete, then we can // make that credential our default and attempt an autologon. if(SerializedCredsAppearComplete()) { *pdwDefault = 0; *pbAutoLogonWithDefault = TRUE; } return S_OK; } IFACEMETHODIMP Provider::GetCredentialAt(__in DWORD dwIndex, __deref_out ICredentialProviderCredential** ppcpc) { // Currently we have just the one, we lazy init it here when first requested if(!m_credential) { m_credential = new Credential(); pGina::Memory::ObjectCleanupPool cleanup; PWSTR serializedUser = NULL, serializedPass = NULL; if(SerializedCredsAppearComplete()) { GetSerializedCredentials(&serializedUser, &serializedPass, NULL); cleanup.Add(serializedUser, (void (*)(void *)) LocalFree); cleanup.Add(serializedPass, (void (*)(void *)) LocalFree); } switch(m_usageScenario) { case CPUS_LOGON: case CPUS_CREDUI: m_credential->Initialize(m_usageScenario, s_logonFields, m_usageFlags, serializedUser, serializedPass); break; case CPUS_UNLOCK_WORKSTATION: m_credential->Initialize(m_usageScenario, s_unlockFields, m_usageFlags, serializedUser, serializedPass); break; default: return E_INVALIDARG; } } // Did we fail to create it? OOM if(!m_credential) return E_OUTOFMEMORY; // Better be index 0 (we only have 1 currently) if(dwIndex != 0 || !ppcpc) return E_INVALIDARG; // Alright... QueryIface for ICredentialProviderCredential return m_credential->QueryInterface(IID_ICredentialProviderCredential, reinterpret_cast<void **>(ppcpc)); } IFACEMETHODIMP Provider::GetFieldDescriptorForUi(UI_FIELDS const& fields, DWORD index, CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR **ppcpfd) { // Must be in our count of fields, and we have to have somewhere to stuff the result if(index >= fields.fieldCount && ppcpfd) return E_INVALIDARG; // Should we fail, we want to return a NULL for result *ppcpfd = NULL; // Use CoTaskMemAlloc for the resulting value, then copy in our descriptor DWORD structSize = sizeof(**ppcpfd); CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *pcpfd = (CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *) CoTaskMemAlloc(structSize); if(pcpfd == NULL) return E_OUTOFMEMORY; // Use compilers struct copy, in case fields change down the road *pcpfd = fields.fields[index].fieldDescriptor; // But now we have to fixup the label, which is a ptr, we'll use SHStrDupW which does CoTask alloc if(pcpfd->pszLabel) { if(!SUCCEEDED(SHStrDupW(fields.fields[index].fieldDescriptor.pszLabel, &pcpfd->pszLabel))) { // Dup failed, free up what we've got so far, then get out CoTaskMemFree(pcpfd); return E_OUTOFMEMORY; } } // Got here? Then we win! *ppcpfd = pcpfd; return S_OK; } bool Provider::SerializedCredsAppearComplete() { // Did we get any creds? if(!m_setSerialization) return false; // Can we work out a username and a password at a minimum? if(m_setSerialization->Logon.UserName.Length && m_setSerialization->Logon.UserName.Buffer && m_setSerialization->Logon.Password.Length && m_setSerialization->Logon.Password.Buffer) return true; return false; } void Provider::GetSerializedCredentials(PWSTR *username, PWSTR *password, PWSTR *domain) { if(!SerializedCredsAppearComplete()) return; if(username) { *username = (PWSTR) LocalAlloc(LMEM_ZEROINIT, m_setSerialization->Logon.UserName.Length + sizeof(wchar_t)); CopyMemory(*username, m_setSerialization->Logon.UserName.Buffer, m_setSerialization->Logon.UserName.Length); } if(password) { *password = (PWSTR) LocalAlloc(LMEM_ZEROINIT, m_setSerialization->Logon.Password.Length + sizeof(wchar_t)); CopyMemory(*password, m_setSerialization->Logon.Password.Buffer, m_setSerialization->Logon.Password.Length); } if(domain) { if(m_setSerialization->Logon.LogonDomainName.Length && m_setSerialization->Logon.LogonDomainName.Buffer) { *domain = (PWSTR) LocalAlloc(LMEM_ZEROINIT, m_setSerialization->Logon.LogonDomainName.Length + sizeof(wchar_t)); CopyMemory(*domain, m_setSerialization->Logon.LogonDomainName.Buffer, m_setSerialization->Logon.LogonDomainName.Length); } } } } }<|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Quantum 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 "tensorflow_quantum/core/qsim/util.h" #include "gtest/gtest.h" namespace tfq { namespace qsim { namespace { TEST(Util, ComputeParity) { // Check parities for |11> <--> 3 uint64_t sample_01 = 3; absl::flat_hash_set<unsigned int> parity_(); absl::flat_hash_set<unsigned int> parity_0({0}); absl::flat_hash_set<unsigned int> parity_1({1}); absl::flat_hash_set<unsigned int> parity_01({0, 1}); ASSERT_EQ(ComputeParity(parity_, sample_01), 1); ASSERT_EQ(ComputeParity(parity_0, sample_01), -1); ASSERT_EQ(ComputeParity(parity_1, sample_01), -1); ASSERT_EQ(ComputeParity(parity_01, sample_01), 1); } } // namespace } // namespace qsim } // namespace tfq <commit_msg>tests added<commit_after>/* Copyright 2020 The TensorFlow Quantum 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 "tensorflow_quantum/core/qsim/util.h" #include "gtest/gtest.h" namespace tfq { namespace qsim { namespace { TEST(Util, ComputeParity) { // Check all parities for all two qubit states uint64_t sample_01; absl::flat_hash_set<unsigned int> parity_(); absl::flat_hash_set<unsigned int> parity_0({0}); absl::flat_hash_set<unsigned int> parity_1({1}); absl::flat_hash_set<unsigned int> parity_01({0, 1}); // |00> <--> 0 sample_01 = 0; ASSERT_EQ(ComputeParity(parity_, sample_01), 1); ASSERT_EQ(ComputeParity(parity_0, sample_01), 1); ASSERT_EQ(ComputeParity(parity_1, sample_01), 1); ASSERT_EQ(ComputeParity(parity_01, sample_01), 1); // |01> <--> 1 sample_01 = 1; ASSERT_EQ(ComputeParity(parity_, sample_01), 1); ASSERT_EQ(ComputeParity(parity_0, sample_01), -1); ASSERT_EQ(ComputeParity(parity_1, sample_01), 1); ASSERT_EQ(ComputeParity(parity_01, sample_01), -1); // |10> <--> 2 sample_01 = 2; ASSERT_EQ(ComputeParity(parity_, sample_01), 1); ASSERT_EQ(ComputeParity(parity_0, sample_01), 1); ASSERT_EQ(ComputeParity(parity_1, sample_01), -1); ASSERT_EQ(ComputeParity(parity_01, sample_01), -1); // |11> <--> 3 sample_01 = 3; ASSERT_EQ(ComputeParity(parity_, sample_01), 1); ASSERT_EQ(ComputeParity(parity_0, sample_01), -1); ASSERT_EQ(ComputeParity(parity_1, sample_01), -1); ASSERT_EQ(ComputeParity(parity_01, sample_01), 1); // Check all parities for a three qubit state // |101> <--> 5 uint64_t sample_012(5); absl::flat_hash_set<unsigned int> parity_2(); absl::flat_hash_set<unsigned int> parity_02({0, 2}); absl::flat_hash_set<unsigned int> parity_12({1, 2}); absl::flat_hash_set<unsigned int> parity_012({0, 1, 2}); ASSERT_EQ(ComputeParity(parity_, sample_012), 1); ASSERT_EQ(ComputeParity(parity_0, sample_012), -1); ASSERT_EQ(ComputeParity(parity_1, sample_012), 1); ASSERT_EQ(ComputeParity(parity_01, sample_012), -1); ASSERT_EQ(ComputeParity(parity_2, sample_012), -1); ASSERT_EQ(ComputeParity(parity_02, sample_012), 1); ASSERT_EQ(ComputeParity(parity_12, sample_012), -1); ASSERT_EQ(ComputeParity(parity_012, sample_012), 1); // Check a parity for a ten qubit state } } // namespace } // namespace qsim } // namespace tfq <|endoftext|>
<commit_before>#ifndef __GLOBALS_HPP_INCLUDED #define __GLOBALS_HPP_INCLUDED #include <string> #include <vector> // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #ifndef WINDOW_WIDTH #define WINDOW_WIDTH (1600.0f) #endif #ifndef WINDOW_HEIGHT #define WINDOW_HEIGHT (900.0f) #endif #ifndef ASPECT_RATIO #define ASPECT_RATIO (WINDOW_WIDTH / WINDOW_HEIGHT) #endif #ifndef PI #define PI 3.14159265359f #endif #ifndef EARTH_RADIUS #define EARTH_RADIUS 6371000.0f #endif #ifndef TEXT_SIZE #define TEXT_SIZE 40 #endif #ifndef FONT_SIZE #define FONT_SIZE 16 #endif #ifndef MAX_FPS #define MAX_FPS 60 #endif extern glm::vec3 position; extern double horizontalAngle; extern double verticalAngle; extern GLfloat initialFoV; extern double earth_radius; extern bool hasMouseEverMoved; extern bool is_invert_mouse_in_use; extern bool is_key_I_released; extern bool is_world_loaded; // no more than one world object can be loaded. TODO: check that no more than one world is loaded! extern bool is_world_spherical; typedef struct { std::string texture_file_format; std::string image_path; } TextureStruct; typedef struct { void *world_pointer; // pointer to the world (draw list). std::string vertex_shader; // filename of vertex shader. std::string fragment_shader; // filename of fragment shader. } ShaderStruct; typedef struct { uint32_t *node_data; } GraphStruct; typedef struct { GLuint nodeID; void* graph_pointer; glm::vec3 coordinate_vector; std::vector<uint32_t> neighbor_nodeIDs; } NodeStruct; typedef struct { glm::vec3 coordinate_vector; // coordinate vector. GLfloat rotate_angle; // rotate angle. glm::vec3 rotate_vector; // rotate vector. glm::vec3 translate_vector; // translate vector. glm::mat4 model_matrix; // model matrix. glm::mat4 MVP_matrix; // model view projection matrix. void *species_pointer; // pointer to the species. } ObjectStruct; typedef struct { // used for all files (for all species). void *shader_pointer; // pointer to the shader object. std::string model_file_format; // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`. // TODO: add support for `"SRTM"`. std::string texture_file_format; // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`. std::string texture_filename; // filename of the model file. std::string vertex_shader; // filename of vertex shader. std::string fragment_shader; // filename of fragment shader. glm::vec3 lightPos; // light position. std::vector<ObjectStruct> object_vector; // vector of individual objects of this species. bool is_world; // worlds currently do not rotate nor translate. std::string coordinate_system; // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`. // TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps. GLfloat world_radius; // radius of sea level in meters. used only for worlds. // for `"bmp"` model files. std::string model_filename; // filename of the model file. std::string color_channel; // color channel to use for altitude data. } SpeciesStruct; typedef struct { GLuint screen_width; GLuint screen_height; GLuint x; GLuint y; GLuint text_size; GLuint font_size; const char *text; const char *char_font_texture_file_format; const char *horizontal_alignment; const char *vertical_alignment; } PrintingStruct; typedef struct { double rho; double theta; double phi; } SphericalCoordinatesStruct; typedef struct { double southern_latitude; double northern_latitude; double western_longitude; double eastern_longitude; } SphericalWorldStruct; extern SphericalCoordinatesStruct spherical_position; #endif <commit_msg>`GLfloat world_radius` -> `double world_radius`. Ei vielä käytössä.<commit_after>#ifndef __GLOBALS_HPP_INCLUDED #define __GLOBALS_HPP_INCLUDED #include <string> #include <vector> // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #ifndef WINDOW_WIDTH #define WINDOW_WIDTH (1600.0f) #endif #ifndef WINDOW_HEIGHT #define WINDOW_HEIGHT (900.0f) #endif #ifndef ASPECT_RATIO #define ASPECT_RATIO (WINDOW_WIDTH / WINDOW_HEIGHT) #endif #ifndef PI #define PI 3.14159265359f #endif #ifndef EARTH_RADIUS #define EARTH_RADIUS 6371000.0f #endif #ifndef TEXT_SIZE #define TEXT_SIZE 40 #endif #ifndef FONT_SIZE #define FONT_SIZE 16 #endif #ifndef MAX_FPS #define MAX_FPS 60 #endif extern glm::vec3 position; extern double horizontalAngle; extern double verticalAngle; extern GLfloat initialFoV; extern double earth_radius; extern bool hasMouseEverMoved; extern bool is_invert_mouse_in_use; extern bool is_key_I_released; extern bool is_world_loaded; // no more than one world object can be loaded. TODO: check that no more than one world is loaded! extern bool is_world_spherical; typedef struct { std::string texture_file_format; std::string image_path; } TextureStruct; typedef struct { void *world_pointer; // pointer to the world (draw list). std::string vertex_shader; // filename of vertex shader. std::string fragment_shader; // filename of fragment shader. } ShaderStruct; typedef struct { uint32_t *node_data; } GraphStruct; typedef struct { GLuint nodeID; void* graph_pointer; glm::vec3 coordinate_vector; std::vector<uint32_t> neighbor_nodeIDs; } NodeStruct; typedef struct { glm::vec3 coordinate_vector; // coordinate vector. GLfloat rotate_angle; // rotate angle. glm::vec3 rotate_vector; // rotate vector. glm::vec3 translate_vector; // translate vector. glm::mat4 model_matrix; // model matrix. glm::mat4 MVP_matrix; // model view projection matrix. void *species_pointer; // pointer to the species. } ObjectStruct; typedef struct { // used for all files (for all species). void *shader_pointer; // pointer to the shader object. std::string model_file_format; // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`. // TODO: add support for `"SRTM"`. std::string texture_file_format; // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`. std::string texture_filename; // filename of the model file. std::string vertex_shader; // filename of vertex shader. std::string fragment_shader; // filename of fragment shader. glm::vec3 lightPos; // light position. std::vector<ObjectStruct> object_vector; // vector of individual objects of this species. bool is_world; // worlds currently do not rotate nor translate. std::string coordinate_system; // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`. // TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps. double world_radius; // radius of sea level in meters. used only for worlds. // for `"bmp"` model files. std::string model_filename; // filename of the model file. std::string color_channel; // color channel to use for altitude data. } SpeciesStruct; typedef struct { GLuint screen_width; GLuint screen_height; GLuint x; GLuint y; GLuint text_size; GLuint font_size; const char *text; const char *char_font_texture_file_format; const char *horizontal_alignment; const char *vertical_alignment; } PrintingStruct; typedef struct { double rho; double theta; double phi; } SphericalCoordinatesStruct; typedef struct { double southern_latitude; double northern_latitude; double western_longitude; double eastern_longitude; } SphericalWorldStruct; extern SphericalCoordinatesStruct spherical_position; #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2015-2016, Graphics Lab, Georgia Tech Research Corporation * Copyright (c) 2015-2016, Humanoid Lab, Georgia Tech Research Corporation * Copyright (c) 2016, Personal Robotics Lab, Carnegie Mellon University * All rights reserved. * * This file is provided under the following "BSD-style" License: * 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. */ #ifndef DART_COLLISION_FCL_FCLTTYPES_HPP_ #define DART_COLLISION_FCL_FCLTTYPES_HPP_ #include <Eigen/Dense> #include <fcl/math/vec_3f.h> #include <fcl/math/matrix_3f.h> #include <fcl/math/transform.h> #define FCL_VERSION_AT_LEAST(x,y,z) \ (FCL_MAJOR_VERSION > x || (FCL_MAJOR_VERSION >= x && \ (FCL_MINOR_VERSION > y || (FCL_MINOR_VERSION >= y && \ FCL_PATCH_VERSION >= z)))) #define FCL_MAJOR_MINOR_VERSION_AT_MOST(x,y) \ (FCL_MAJOR_VERSION < x || (FCL_MAJOR_VERSION <= x && \ (FCL_MINOR_VERSION < y || (FCL_MINOR_VERSION <= y)))) #if FCL_VERSION_AT_LEAST(0,5,0) template <class T> using fcl_shared_ptr = std::shared_ptr<T>; template <class T> using fcl_weak_ptr = std::weak_ptr<T>; #else template <class T> using fcl_shared_ptr = boost::shared_ptr<T>; template <class T> using fcl_weak_ptr = boost::weak_ptr<T>; #endif namespace dart { namespace collision { class FCLTypes { public: /// Convert FCL vector3 type to Eigen vector3 type static Eigen::Vector3d convertVector3(const fcl::Vec3f& _vec); /// Convert Eigen vector3 type to FCL vector3 type static fcl::Vec3f convertVector3(const Eigen::Vector3d& _vec); /// Convert FCL matrix3x3 type to Eigen matrix3x3 type static fcl::Matrix3f convertMatrix3x3(const Eigen::Matrix3d& _R); /// Convert FCL transformation type to Eigen transformation type static fcl::Transform3f convertTransform(const Eigen::Isometry3d& _T); }; } // namespace collision } // namespace dart #endif // DART_COLLISION_FCL_FCLTTYPES_HPP_ <commit_msg>Minor change: included <memory> from FCLTypes.hpp<commit_after>/* * Copyright (c) 2015-2016, Graphics Lab, Georgia Tech Research Corporation * Copyright (c) 2015-2016, Humanoid Lab, Georgia Tech Research Corporation * Copyright (c) 2016, Personal Robotics Lab, Carnegie Mellon University * All rights reserved. * * This file is provided under the following "BSD-style" License: * 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. */ #ifndef DART_COLLISION_FCL_FCLTTYPES_HPP_ #define DART_COLLISION_FCL_FCLTTYPES_HPP_ #include <Eigen/Dense> #include <fcl/math/vec_3f.h> #include <fcl/math/matrix_3f.h> #include <fcl/math/transform.h> #define FCL_VERSION_AT_LEAST(x,y,z) \ (FCL_MAJOR_VERSION > x || (FCL_MAJOR_VERSION >= x && \ (FCL_MINOR_VERSION > y || (FCL_MINOR_VERSION >= y && \ FCL_PATCH_VERSION >= z)))) #define FCL_MAJOR_MINOR_VERSION_AT_MOST(x,y) \ (FCL_MAJOR_VERSION < x || (FCL_MAJOR_VERSION <= x && \ (FCL_MINOR_VERSION < y || (FCL_MINOR_VERSION <= y)))) #if FCL_VERSION_AT_LEAST(0,5,0) #include <memory> template <class T> using fcl_shared_ptr = std::shared_ptr<T>; template <class T> using fcl_weak_ptr = std::weak_ptr<T>; #else template <class T> using fcl_shared_ptr = boost::shared_ptr<T>; template <class T> using fcl_weak_ptr = boost::weak_ptr<T>; #endif namespace dart { namespace collision { class FCLTypes { public: /// Convert FCL vector3 type to Eigen vector3 type static Eigen::Vector3d convertVector3(const fcl::Vec3f& _vec); /// Convert Eigen vector3 type to FCL vector3 type static fcl::Vec3f convertVector3(const Eigen::Vector3d& _vec); /// Convert FCL matrix3x3 type to Eigen matrix3x3 type static fcl::Matrix3f convertMatrix3x3(const Eigen::Matrix3d& _R); /// Convert FCL transformation type to Eigen transformation type static fcl::Transform3f convertTransform(const Eigen::Isometry3d& _T); }; } // namespace collision } // namespace dart #endif // DART_COLLISION_FCL_FCLTTYPES_HPP_ <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include "Myexception.h" #include "chain.h" using namespace std; void chain :: readAndStoreFromFile(char* fileName) { //This function reads integers from the file given by fileName then store them in the chain ifstream infile(fileName) ; string line; while(getline(infile, line)) { istringstream iss(line); int n; iss >> n; insert(listSize, n); } } void chain :: eraseModuloValue(int theInt) { //This function erases all the entries from the list which are multiple of theInt for(int i=0; i < listSize; i++) { int value = *this->get(i); if (value/theInt > 0 && value != theInt) erase(i); } } void chain :: oddAndEvenOrdering() { //This function reorders the list such a way that all odd numbers precede all even numbers. //Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering. } void chain :: reverse() { //Reverses the list for(int i=0; i < listSize; i++) { int value = *this->get(i); insert(0, value); } } chain :: chain(int initialCapacity) { //Constructor if(initialCapacity < 1) { ostringstream s; s << "Initial capacity = " << initialCapacity << " Must be > 0"; throw illegalParameterValue(s.str()); } firstNode = NULL; listSize = 0; } chain :: ~chain() { //Destructor. Delete all nodes in chain while(firstNode != NULL) { //delete firstNode chainNode* nextNode = firstNode->next; delete firstNode; firstNode = nextNode; } } int* chain :: get(int theIndex) const { //Return element whose index is theIndex. //Throw illegalIndex exception if no such element. try{ checkIndex(theIndex); } catch(illegalIndex &e){ e.outputMessage(); return NULL; } chainNode* currentNode = firstNode; for(int i=0;i<theIndex;i++) currentNode = currentNode->next; return &currentNode->element; } int chain :: indexOf(const int& theElement) const { //Return index of first occurrence of theElement. //Return -1 of theElement not in list. chainNode* currentNode = firstNode; int index = 0; while(currentNode != NULL && currentNode->element != theElement) { //move to the next node currentNode = currentNode->next; index++; } //make sure we found matching element if(currentNode == NULL) return -1; else return index; } void chain :: erase(int theIndex) { //Delete the element whose index is theIndex. //Throw illegalIndex exception if no such element. try{ checkIndex(theIndex); } catch(illegalIndex &e){ e.outputMessage(); return; } chainNode* deleteNode; if(theIndex == 0) { //remove first node from chain deleteNode = firstNode; firstNode = firstNode->next; } else { //use p to get to predecessor of desired node chainNode* p = firstNode; for(int i=0;i<theIndex-1;i++) p = p->next; deleteNode = p->next; p->next = p->next->next; //remove deleteNode from chain } listSize--; delete deleteNode; } void chain :: insert(int theIndex, const int& theElement) { //Insert theElement so that its index is theIndex. try{ if (theIndex < 0 || theIndex > listSize) {// invalid index ostringstream s; s << "index = " << theIndex << " size = " << listSize; throw illegalIndex(s.str()); } } catch(illegalIndex &e){ e.outputMessage(); return; } if(theIndex == 0) //insert at front firstNode = new chainNode(theElement, firstNode); else { chainNode *p = firstNode; for(int i=0;i<theIndex-1;i++) p = p->next; //insert after p p->next = new chainNode(theElement, p->next); } listSize++; } void chain :: output() const { //Put the list into the output. for(int i=0;i<listSize;i++) cout << *this->get(i) << " "; cout<<endl; } void chain::checkIndex(int theIndex) const { // Verify that theIndex is between 0 and // listSize - 1. if (theIndex < 0 || theIndex >= listSize){ ostringstream s; s << "index = " << theIndex << " size = " << listSize<<", the input index is invalid"; throw illegalIndex(s.str()); } } <commit_msg>testing<commit_after>#include <iostream> #include <fstream> #include <sstream> #include "Myexception.h" #include "chain.h" using namespace std; void chain :: readAndStoreFromFile(char* fileName) { //This function reads integers from the file given by fileName then store them in the chain ifstream infile(fileName) ; string line; while(getline(infile, line)) { istringstream iss(line); int n; iss >> n; insert(listSize, n); } } void chain :: eraseModuloValue(int theInt) { //This function erases all the entries from the list which are multiple of theInt for(int i=0; i < listSize; i++) { int value = *this->get(i); int remainder = value%theInt; cout << "value: " << value << ", Remainder: " << remainder << ", listSize: " << listSize << ", i: " << i << endl; output(); if (remainder == 0 && value > theInt) { erase(i); i--; listSize--; } } } void chain :: oddAndEvenOrdering() { //This function reorders the list such a way that all odd numbers precede all even numbers. //Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering. } void chain :: reverse() { //Reverses the list for(int i=0; i < listSize; i++) { int value = *this->get(i); insert(0, value); } } chain :: chain(int initialCapacity) { //Constructor if(initialCapacity < 1) { ostringstream s; s << "Initial capacity = " << initialCapacity << " Must be > 0"; throw illegalParameterValue(s.str()); } firstNode = NULL; listSize = 0; } chain :: ~chain() { //Destructor. Delete all nodes in chain while(firstNode != NULL) { //delete firstNode chainNode* nextNode = firstNode->next; delete firstNode; firstNode = nextNode; } } int* chain :: get(int theIndex) const { //Return element whose index is theIndex. //Throw illegalIndex exception if no such element. try{ checkIndex(theIndex); } catch(illegalIndex &e){ e.outputMessage(); return NULL; } chainNode* currentNode = firstNode; for(int i=0;i<theIndex;i++) currentNode = currentNode->next; return &currentNode->element; } int chain :: indexOf(const int& theElement) const { //Return index of first occurrence of theElement. //Return -1 of theElement not in list. chainNode* currentNode = firstNode; int index = 0; while(currentNode != NULL && currentNode->element != theElement) { //move to the next node currentNode = currentNode->next; index++; } //make sure we found matching element if(currentNode == NULL) return -1; else return index; } void chain :: erase(int theIndex) { //Delete the element whose index is theIndex. //Throw illegalIndex exception if no such element. try{ checkIndex(theIndex); } catch(illegalIndex &e){ e.outputMessage(); return; } chainNode* deleteNode; if(theIndex == 0) { //remove first node from chain deleteNode = firstNode; firstNode = firstNode->next; } else { //use p to get to predecessor of desired node chainNode* p = firstNode; for(int i=0;i<theIndex-1;i++) p = p->next; deleteNode = p->next; p->next = p->next->next; //remove deleteNode from chain } listSize--; delete deleteNode; } void chain :: insert(int theIndex, const int& theElement) { //Insert theElement so that its index is theIndex. try{ if (theIndex < 0 || theIndex > listSize) {// invalid index ostringstream s; s << "index = " << theIndex << " size = " << listSize; throw illegalIndex(s.str()); } } catch(illegalIndex &e){ e.outputMessage(); return; } if(theIndex == 0) //insert at front firstNode = new chainNode(theElement, firstNode); else { chainNode *p = firstNode; for(int i=0;i<theIndex-1;i++) p = p->next; //insert after p p->next = new chainNode(theElement, p->next); } listSize++; } void chain :: output() const { //Put the list into the output. for(int i=0;i<listSize;i++) cout << *this->get(i) << " "; cout<<endl; } void chain::checkIndex(int theIndex) const { // Verify that theIndex is between 0 and // listSize - 1. if (theIndex < 0 || theIndex >= listSize){ ostringstream s; s << "index = " << theIndex << " size = " << listSize<<", the input index is invalid"; throw illegalIndex(s.str()); } } <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Fons Rademakers 07/05/2000 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //////////////////////////////////////////////////////////////////////////////// // // // TInspector Imp // // // // ABC describing GUI independent object inspector (abstration mainly needed // // for Win32. On X11 systems it currently uses a standard TCanvas). // // // //////////////////////////////////////////////////////////////////////////////// #include "TInspectorImp.h" ClassImp(TInspectorImp) <commit_msg>Doxygen and spell check<commit_after>// @(#)root/base:$Id$ // Author: Fons Rademakers 07/05/2000 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /** \class TInspectorImp ABC describing GUI independent object inspector (abstraction mainly needed for Win32. On X11 systems it currently uses a standard TCanvas). */ #include "TInspectorImp.h" ClassImp(TInspectorImp) <|endoftext|>
<commit_before>// Sh: A GPU metaprogramming language. // // Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory // Project administrator: Michael D. McCool // Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa, // Bryan Chan, Michael D. McCool // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must // not claim that you wrote the original software. If you use this // software in a product, an acknowledgment in the product documentation // would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. ////////////////////////////////////////////////////////////////////////////// #ifndef SHUTIL_SHUTILLIB_HPP #define SHUTIL_SHUTILLIB_HPP #include <cmath> #include "ShAttrib.hpp" #include "ShConstant.hpp" #include "ShSwizzle.hpp" #include "ShVariable.hpp" namespace ShUtil { using namespace SH; //TODO extend to vector versions /** \file ShUtilLib.hpp * \brief A set of small Sh utility functions. */ /** \brief Clamps value between a and b. * a must be <= b. * Returns a if x < a, * b if b < x, * x otherwise */ //@{ template<typename T> ShVariableN<1, T> clamp(const ShVariableN<1, T>& a, const ShVariableN<1, T>& b, const ShVariableN<1, T>& x) { return min(max(x, a), b); } template<typename T> ShVariableN<1, T> clamp(T a, T b, const ShVariableN<1, T>& x) { return min(max(x, ShConstant<1,T>(a)), ShConstant<1,T>(b)); } //@} /** \brief Cubic interpolated step between 0 and 1. * Returns 0 if x < a, * 1 if x > b, * cubic interpolation between 0 and 1 otherwise */ template<typename T> ShVariableN<1, T> smoothstep(const ShVariableN<1, T>& a, const ShVariableN<1, T>& b, const ShVariableN<1, T> x) { ShVariableN<1, T> t = (x - a) / (b - a); t = clamp(0.0, 1.0, t); return t * t * mad(-2.0, t, ShConstant1f(3.0)); } /** \brief Euclidean distance between two points. */ template<int N, typename T> ShVariableN<1, T> distance(const ShVariableN<N, T>& a, const ShVariableN<N, T>& b) { return sqrt(dot(a, b)); } /** \brief L1 distance between two points * The L1 distance is a sum of the absolute component-wise differences. */ template<int N, typename T> ShVariableN<1, T> lOneDistance(const ShVariableN<N, T>& a, const ShVariableN<N, T>& b) { //TODO should use dot product with vector 1 ShVariableN<N, T> diff = abs(a - b); return dot(1.0, diff); } /** \brief Linfinity distance between two points * Linfinity distance is the maximum absolute component-wise difference. */ template<int N, typename T> ShVariableN<1, T> lInfDistance(const ShVariableN<N, T>& a, const ShVariableN<N, T>& b) { ShVariableN<N, T> diff = abs(a - b); ShVariableN<1, T> result = max(diff(0), diff(1)); for(int i = 2; i < N; ++i) result = max(result, diff(i)); return result; } static ShAttrib4f hasha(M_PI * M_PI * M_PI * M_PI, std::exp(4.0), std::pow(13.0, M_PI / 2.0), std::sqrt(1997.0)); static ShAttrib4f hashm(std::sqrt(2.0), 1.0 / M_PI, std::sqrt(3.0), std::exp(-1.0)); static const int LCG_REPS = 5; // total instructions for hashlcg will be LCG_REPS * 2 + 2 /** \brief Parallel linear congruential generator * * This does not work very well right now. Use hashmrg instead. * * \sa template<int N, typename T> ShVariableN<N, T> hashmrg(const ShVariableN<N, T>& p) */ // TODO: may not work as intended on 24-bit floats // since there may not be enough precision template<int N, typename T> ShVariableN<N, T> hashlcg(const ShVariableN<N, T>& p) { ShAttrib<N, SH_VAR_TEMP, T> result = frac(p * 0.01); ShVariableN<N, T> a(hasha.node(), ShSwizzle(N), false); ShVariableN<N, T> m(hashm.node(), ShSwizzle(N), false); for(int i = 0; i < LCG_REPS; ++i) { result = frac(mad(result, a, m)); } return result; } static const int MRG_REPS = 2; // total instructions for hashmrg will be MRG_REPS * N * 2 + 2 /** \brief MRG style pseudorandom vector generator * * Generates a random vector using a multiple-recursive generator style. (LCG on steroids) * Treat x,y,z,w as seeds a0, a1, a2, a3 * and repeatedly apply an = b * (an-1, an-2, an-3, an-4), where b is a vector * Take as output (an, an-1, an-2, an3) after suitable number of iterations. * * This appears to reduce correlation in the output components when input components are * similar, but the behaviour needs to be studied further. * * \sa template<int N, typename T> ShVariableN<N, T> hashlcg(const ShVariableN<N, T>& p) */ template<int N, typename T> ShVariableN<N, T> hashmrg(const ShVariableN<N, T>& p) { ShAttrib<N, SH_VAR_TEMP, T> result = frac(p * 0.01); ShVariableN<N, T> a(hasha.node(), ShSwizzle(N), false); // use only first N elements of hasha for(int i = 0; i < MRG_REPS; ++i) { for(int j = 0; j < N; ++j) { result(j) = frac(dot(result, a)); } } return result; } } #endif // SHUTIL_SHUTILLIB_HPP <commit_msg>fixed distance function<commit_after>// Sh: A GPU metaprogramming language. // // Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory // Project administrator: Michael D. McCool // Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa, // Bryan Chan, Michael D. McCool // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must // not claim that you wrote the original software. If you use this // software in a product, an acknowledgment in the product documentation // would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. ////////////////////////////////////////////////////////////////////////////// #ifndef SHUTIL_SHUTILLIB_HPP #define SHUTIL_SHUTILLIB_HPP #include <cmath> #include "ShAttrib.hpp" #include "ShConstant.hpp" #include "ShSwizzle.hpp" #include "ShVariable.hpp" namespace ShUtil { using namespace SH; //TODO extend to vector versions /** \file ShUtilLib.hpp * \brief A set of small Sh utility functions. */ /** \brief Clamps value between a and b. * a must be <= b. * Returns a if x < a, * b if b < x, * x otherwise */ //@{ template<typename T> ShVariableN<1, T> clamp(const ShVariableN<1, T>& a, const ShVariableN<1, T>& b, const ShVariableN<1, T>& x) { return min(max(x, a), b); } template<typename T> ShVariableN<1, T> clamp(T a, T b, const ShVariableN<1, T>& x) { return min(max(x, ShConstant<1,T>(a)), ShConstant<1,T>(b)); } //@} /** \brief Cubic interpolated step between 0 and 1. * Returns 0 if x < a, * 1 if x > b, * cubic interpolation between 0 and 1 otherwise */ template<typename T> ShVariableN<1, T> smoothstep(const ShVariableN<1, T>& a, const ShVariableN<1, T>& b, const ShVariableN<1, T> x) { ShVariableN<1, T> t = (x - a) / (b - a); t = clamp(0.0, 1.0, t); return t * t * mad(-2.0, t, ShConstant1f(3.0)); } /** \brief Euclidean distance between two points. */ template<int N, typename T> ShVariableN<1, T> distance(const ShVariableN<N, T>& a, const ShVariableN<N, T>& b) { ShVariableN<N, T> diff = abs(a - b); return sqrt(dot(diff, diff)); } /** \brief L1 distance between two points * The L1 distance is a sum of the absolute component-wise differences. */ template<int N, typename T> ShVariableN<1, T> lOneDistance(const ShVariableN<N, T>& a, const ShVariableN<N, T>& b) { //TODO should use dot product with vector 1 ShVariableN<N, T> diff = abs(a - b); return dot(1.0, diff); } /** \brief Linfinity distance between two points * Linfinity distance is the maximum absolute component-wise difference. */ template<int N, typename T> ShVariableN<1, T> lInfDistance(const ShVariableN<N, T>& a, const ShVariableN<N, T>& b) { ShVariableN<N, T> diff = abs(a - b); ShVariableN<1, T> result = max(diff(0), diff(1)); for(int i = 2; i < N; ++i) result = max(result, diff(i)); return result; } static ShAttrib4f hasha(M_PI * M_PI * M_PI * M_PI, std::exp(4.0), std::pow(13.0, M_PI / 2.0), std::sqrt(1997.0)); static ShAttrib4f hashm(std::sqrt(2.0), 1.0 / M_PI, std::sqrt(3.0), std::exp(-1.0)); static const int LCG_REPS = 5; // total instructions for hashlcg will be LCG_REPS * 2 + 2 /** \brief Parallel linear congruential generator * * This does not work very well right now. Use hashmrg instead. * * \sa template<int N, typename T> ShVariableN<N, T> hashmrg(const ShVariableN<N, T>& p) */ // TODO: may not work as intended on 24-bit floats // since there may not be enough precision template<int N, typename T> ShVariableN<N, T> hashlcg(const ShVariableN<N, T>& p) { ShAttrib<N, SH_VAR_TEMP, T> result = frac(p * 0.01); ShVariableN<N, T> a(hasha.node(), ShSwizzle(N), false); ShVariableN<N, T> m(hashm.node(), ShSwizzle(N), false); for(int i = 0; i < LCG_REPS; ++i) { result = frac(mad(result, a, m)); } return result; } static const int MRG_REPS = 2; // total instructions for hashmrg will be MRG_REPS * N * 2 + 2 /** \brief MRG style pseudorandom vector generator * * Generates a random vector using a multiple-recursive generator style. (LCG on steroids) * Treat x,y,z,w as seeds a0, a1, a2, a3 * and repeatedly apply an = b * (an-1, an-2, an-3, an-4), where b is a vector * Take as output (an, an-1, an-2, an3) after suitable number of iterations. * * This appears to reduce correlation in the output components when input components are * similar, but the behaviour needs to be studied further. * * \sa template<int N, typename T> ShVariableN<N, T> hashlcg(const ShVariableN<N, T>& p) */ template<int N, typename T> ShVariableN<N, T> hashmrg(const ShVariableN<N, T>& p) { ShAttrib<N, SH_VAR_TEMP, T> result = frac(p * 0.01); ShVariableN<N, T> a(hasha.node(), ShSwizzle(N), false); // use only first N elements of hasha for(int i = 0; i < MRG_REPS; ++i) { for(int j = 0; j < N; ++j) { result(j) = frac(dot(result, a)); } } return result; } } #endif // SHUTIL_SHUTILLIB_HPP <|endoftext|>
<commit_before>/************************************************************************* * * 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: bookmrk.hxx,v $ * $Revision: 1.10 $ * * 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 _BOOKMRK_HXX #define _BOOKMRK_HXX #include "hintids.hxx" //die Ids der Attribute, vor macitem damit die //die Attribut richtig angezogen werden. #include <svtools/macitem.hxx> #ifndef _KEYCOD_HXX //autogen #include <vcl/keycod.hxx> #endif #ifndef _TOOLS_REF_HXX #include <tools/ref.hxx> #endif #include <IDocumentBookmarkAccess.hxx> #include <calbck.hxx> #include <pam.hxx> #ifndef SW_DECL_SWSERVEROBJECT_DEFINED #define SW_DECL_SWSERVEROBJECT_DEFINED SV_DECL_REF( SwServerObject ) #endif struct SwPosition; // fwd Decl. wg. UI class SwBookmark : public SwModify { SwPosition *pPos1, *pPos2; // wird im CTOR gesetzt, im DTOR geloescht // pPos1 is always != 0, pPos2 may be 0 SwServerObjectRef refObj; // falls DataServer -> Pointer gesetzt protected: String aName; String aShortName; KeyCode aCode; IDocumentBookmarkAccess::BookmarkType eMarkType; SwBookmark( const SwPosition& aPos, const KeyCode& rCode, const String& rName, const String& rShortName); public: TYPEINFO(); SwBookmark( const SwPosition& aPos ); // --> OD 2007-09-26 #i81002# SwBookmark( const SwPaM& aPaM, const KeyCode& rCode, const String& rName, const String& rShortName); // <-- // Beim Loeschen von Text werden Bookmarks mitgeloescht! virtual ~SwBookmark(); // --> OD 2007-10-10 #i81002# // made virtual and thus no longer inline virtual const SwPosition& GetBookmarkPos() const; virtual const SwPosition* GetOtherBookmarkPos() const; // <-- // nicht undofaehig const String& GetName() const { return aName; } // nicht undofaehig const String& GetShortName() const { return aShortName; } // nicht undofaehig const KeyCode& GetKeyCode() const { return aCode; } // Vergleiche auf Basis der Dokumentposition BOOL operator < (const SwBookmark &) const; BOOL operator ==(const SwBookmark &) const; // falls man wirklich auf gleiche Position abfragen will. BOOL IsEqualPos( const SwBookmark &rBM ) const; BOOL IsBookMark() const { return IDocumentBookmarkAccess::BOOKMARK == eMarkType; } // // --> OD 2007-10-17 #TESTING# // BOOL IsBookMark() const // { // return IDocumentBookmarkAccess::BOOKMARK == eMarkType || // IsCrossRefMark(); // } // // <-- BOOL IsMark() const { return IDocumentBookmarkAccess::MARK == eMarkType; } BOOL IsUNOMark() const { return IDocumentBookmarkAccess::UNO_BOOKMARK == eMarkType; } // --> OD 2007-10-11 #i81002# - bookmark type for cross-references BOOL IsCrossRefMark() const { return IDocumentBookmarkAccess::CROSSREF_BOOKMARK == eMarkType; } // <-- void SetType( IDocumentBookmarkAccess::BookmarkType eNewType ) { eMarkType = eNewType; } IDocumentBookmarkAccess::BookmarkType GetType() const { return eMarkType; } // Daten Server-Methoden void SetRefObject( SwServerObject* pObj ); const SwServerObject* GetObject() const { return &refObj; } SwServerObject* GetObject() { return &refObj; } BOOL IsServer() const { return refObj.Is(); } // --> OD 2007-10-10 #i81002# // made virtual and thus no longer inline // to access start and end of a bookmark. // start and end may be the same virtual const SwPosition* BookmarkStart() const; virtual const SwPosition* BookmarkEnd() const; // <-- // --> OD 2007-09-26 #i81002# virtual void SetBookmarkPos( const SwPosition* pNewPos1 ); virtual void SetOtherBookmarkPos( const SwPosition* pNewPos2 ); // <-- private: // fuer METWARE: // es wird (vorerst) nicht kopiert und nicht zugewiesen SwBookmark(const SwBookmark &); SwBookmark &operator=(const SwBookmark &); }; class SwMark: public SwBookmark { public: SwMark( const SwPosition& aPos, const KeyCode& rCode, const String& rName, const String& rShortName); }; class SwUNOMark: public SwBookmark { public: // --> OD 2007-09-26 #i81002# SwUNOMark( const SwPaM& aPaM, const KeyCode& rCode, const String& rName, const String& rShortName); // <-- }; #endif <commit_msg>INTEGRATION: CWS swenhancedfields2 (1.9.42); FILE MERGED 2008/08/04 14:13:07 b_michaelsen 1.9.42.3: RESYNC: (1.9-1.10); FILE MERGED 2008/04/24 12:14:32 ama 1.9.42.2: #33737#: Enhanced fields 2008/04/23 11:05:36 ama 1.9.42.1: #i33737#: Enhanced fields<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: bookmrk.hxx,v $ * $Revision: 1.11 $ * * 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 _BOOKMRK_HXX #define _BOOKMRK_HXX #include "hintids.hxx" //die Ids der Attribute, vor macitem damit die //die Attribut richtig angezogen werden. #include <svtools/macitem.hxx> #ifndef _KEYCOD_HXX //autogen #include <vcl/keycod.hxx> #endif #ifndef _TOOLS_REF_HXX #include <tools/ref.hxx> #endif #include <IDocumentBookmarkAccess.hxx> #include <calbck.hxx> #include <pam.hxx> #ifndef SW_DECL_SWSERVEROBJECT_DEFINED #define SW_DECL_SWSERVEROBJECT_DEFINED SV_DECL_REF( SwServerObject ) #endif struct SwPosition; // fwd Decl. wg. UI class SwBookmark : public SwModify { SwPosition *pPos1, *pPos2; // wird im CTOR gesetzt, im DTOR geloescht // pPos1 is always != 0, pPos2 may be 0 SwServerObjectRef refObj; // falls DataServer -> Pointer gesetzt protected: String aName; String aShortName; KeyCode aCode; IDocumentBookmarkAccess::BookmarkType eMarkType; SwBookmark( const SwPosition& aPos, const KeyCode& rCode, const String& rName, const String& rShortName); public: TYPEINFO(); SwBookmark( const SwPosition& aPos ); // --> OD 2007-09-26 #i81002# SwBookmark( const SwPaM& aPaM, const KeyCode& rCode, const String& rName, const String& rShortName); // <-- // Beim Loeschen von Text werden Bookmarks mitgeloescht! virtual ~SwBookmark(); // --> OD 2007-10-10 #i81002# // made virtual and thus no longer inline virtual const SwPosition& GetBookmarkPos() const; virtual const SwPosition* GetOtherBookmarkPos() const; // <-- // nicht undofaehig const String& GetName() const { return aName; } // nicht undofaehig const String& GetShortName() const { return aShortName; } // nicht undofaehig const KeyCode& GetKeyCode() const { return aCode; } // Vergleiche auf Basis der Dokumentposition BOOL operator < (const SwBookmark &) const; BOOL operator ==(const SwBookmark &) const; // falls man wirklich auf gleiche Position abfragen will. BOOL IsEqualPos( const SwBookmark &rBM ) const; BOOL IsFormFieldMark() const { return IDocumentBookmarkAccess::FORM_FIELDMARK_TEXT == eMarkType || IDocumentBookmarkAccess::FORM_FIELDMARK_NO_TEXT == eMarkType; } BOOL IsBookMark() const { return IDocumentBookmarkAccess::BOOKMARK == eMarkType || IDocumentBookmarkAccess::FORM_FIELDMARK_TEXT == eMarkType || IDocumentBookmarkAccess::FORM_FIELDMARK_NO_TEXT == eMarkType; } // // --> OD 2007-10-17 #TESTING# // BOOL IsBookMark() const // { // return IDocumentBookmarkAccess::BOOKMARK == eMarkType || // IsCrossRefMark(); // } // // <-- BOOL IsMark() const { return IDocumentBookmarkAccess::MARK == eMarkType; } BOOL IsUNOMark() const { return IDocumentBookmarkAccess::UNO_BOOKMARK == eMarkType; } // --> OD 2007-10-11 #i81002# - bookmark type for cross-references BOOL IsCrossRefMark() const { return IDocumentBookmarkAccess::CROSSREF_BOOKMARK == eMarkType; } // <-- void SetType( IDocumentBookmarkAccess::BookmarkType eNewType ) { eMarkType = eNewType; } IDocumentBookmarkAccess::BookmarkType GetType() const { return eMarkType; } // Daten Server-Methoden void SetRefObject( SwServerObject* pObj ); const SwServerObject* GetObject() const { return &refObj; } SwServerObject* GetObject() { return &refObj; } BOOL IsServer() const { return refObj.Is(); } // --> OD 2007-10-10 #i81002# // made virtual and thus no longer inline // to access start and end of a bookmark. // start and end may be the same virtual const SwPosition* BookmarkStart() const; virtual const SwPosition* BookmarkEnd() const; // <-- // --> OD 2007-09-26 #i81002# virtual void SetBookmarkPos( const SwPosition* pNewPos1 ); virtual void SetOtherBookmarkPos( const SwPosition* pNewPos2 ); // <-- private: // fuer METWARE: // es wird (vorerst) nicht kopiert und nicht zugewiesen SwBookmark(const SwBookmark &); SwBookmark &operator=(const SwBookmark &); }; class SwMark: public SwBookmark { public: SwMark( const SwPosition& aPos, const KeyCode& rCode, const String& rName, const String& rShortName); }; class SwFieldBookmark : public SwBookmark { private: int fftype; // Type: 0 = Text, 1 = Check Box, 2 = List int ffres; bool ffprot; bool ffsize; // 0 = Auto, 1=Exact (see ffhps) int fftypetxt; // Type of text field: 0 = Regular text, 1 = Number, 2 = Date, 3 = Current date, 4 = Current time, 5 = Calculation bool ffrecalc; int ffmaxlen; // Number of characters for text field. Zero means unlimited. int ffhps; // Check box size (half-point sizes). String ffname; String ffhelptext; public: SwFieldBookmark(const SwPosition& aPos, const KeyCode& rCode, const String& rName, const String& rShortName, IDocumentBookmarkAccess::BookmarkType eMark); void SetFieldType(int fftype); int GetFieldType(); void SetChecked(bool checked); bool IsChecked(); void SetFFName(String aNewName) { this->ffname=aNewName; } String GetFFName() { return ffname; } int GetFFRes() { return ffres; } void SetFFRes(int nNew) { this->ffres=nNew; } void SetFFHelpText(String newffhelptext) { this->ffhelptext=newffhelptext; } String GetFFHelpText() { return ffhelptext; } }; class SwUNOMark: public SwBookmark { public: // --> OD 2007-09-26 #i81002# SwUNOMark( const SwPaM& aPaM, const KeyCode& rCode, const String& rName, const String& rShortName); // <-- }; #endif <|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. Some parts of this code are derived from ITK. See ITKCopyright.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 "otbWriterWatcherBase.h" namespace otb { WriterWatcherBase ::WriterWatcherBase() { // Initialize state m_Comment = "Not watching any object"; m_Process = 0; } WriterWatcherBase ::WriterWatcherBase(itk::ProcessObject* process, const char *comment) { // Initialize state m_Process = process; m_Comment = comment; // Create a series of commands m_StartWriterCommand = CommandType::New(); m_EndWriterCommand = CommandType::New(); m_ProgressWriterCommand = CommandType::New(); m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowFilterProgress); m_StartWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartWriter); m_EndWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndWriter); m_ProgressWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowWriterProgress); // Add the commands as observers m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), m_StartWriterCommand); m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), m_EndWriterCommand); m_ProgressWriterTag = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressWriterCommand); // Try to get the filter that is wired to m_Process. if (m_Process->GetInputs()[0]->GetSource()) { m_SourceProcess = m_Process->GetInputs()[0]->GetSource(); // Add the commands as observers m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), m_StartFilterCommand); m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), m_EndFilterCommand); m_ProgressFilterTag = m_SourceProcess->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); } } WriterWatcherBase ::WriterWatcherBase(itk::ProcessObject* process, itk::ProcessObject * source, const char *comment) { // Initialize state m_Process = process; m_Comment = comment; // Create a series of commands m_StartWriterCommand = CommandType::New(); m_EndWriterCommand = CommandType::New(); m_ProgressWriterCommand = CommandType::New(); m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowFilterProgress); m_StartWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartWriter); m_EndWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndWriter); m_ProgressWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowWriterProgress); // Add the commands as observers m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), m_StartWriterCommand); m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), m_EndWriterCommand); m_ProgressWriterTag = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressWriterCommand); m_SourceProcess = source; // Add the commands as observers m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), m_StartFilterCommand); m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), m_EndFilterCommand); m_ProgressFilterTag = m_SourceProcess->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); } WriterWatcherBase ::WriterWatcherBase(const WriterWatcherBase& watch) { // Remove any observers we have on the old process object if (m_Process) { if (m_StartWriterCommand) { m_Process->RemoveObserver(m_StartWriterTag); } if (m_EndWriterCommand) { m_Process->RemoveObserver(m_EndWriterTag); } if (m_ProgressWriterCommand) { m_Process->RemoveObserver(m_ProgressWriterTag); } } if (m_SourceProcess) { if (m_StartFilterCommand) { m_SourceProcess->RemoveObserver(m_StartFilterTag); } if (m_EndFilterCommand) { m_SourceProcess->RemoveObserver(m_EndFilterTag); } if (m_ProgressFilterCommand) { m_SourceProcess->RemoveObserver(m_ProgressFilterTag); } } // Initialize state m_TimeProbe = watch.m_TimeProbe; m_Process = watch.m_Process; m_SourceProcess = watch.m_SourceProcess; m_Comment = watch.m_Comment; m_StartFilterTag = 0; m_EndFilterTag = 0; m_ProgressFilterTag = 0; m_StartWriterTag = 0; m_EndWriterTag = 0; m_ProgressWriterTag = 0; // Create a series of commands if (m_Process) { m_StartWriterCommand = CommandType::New(); m_EndWriterCommand = CommandType::New(); m_ProgressWriterCommand = CommandType::New(); // Assign the callbacks m_StartWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartWriter); m_EndWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndWriter); m_ProgressWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowWriterProgress); // Add the commands as observers m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), m_StartWriterCommand); m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), m_EndWriterCommand); m_ProgressWriterTag = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressWriterCommand); } if (m_SourceProcess) { m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowFilterProgress); // Add the commands as observers m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), m_StartFilterCommand); m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), m_EndFilterCommand); m_ProgressFilterTag = m_SourceProcess->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); } } void WriterWatcherBase ::operator =(const WriterWatcherBase& watch) { // Remove any observers we have on the old process object if (m_Process) { if (m_StartWriterCommand) { m_Process->RemoveObserver(m_StartWriterTag); } if (m_EndWriterCommand) { m_Process->RemoveObserver(m_EndWriterTag); } if (m_ProgressWriterCommand) { m_Process->RemoveObserver(m_ProgressWriterTag); } } if (m_SourceProcess) { if (m_StartFilterCommand) { m_SourceProcess->RemoveObserver(m_StartFilterTag); } if (m_EndFilterCommand) { m_SourceProcess->RemoveObserver(m_EndFilterTag); } if (m_ProgressFilterCommand) { m_SourceProcess->RemoveObserver(m_ProgressFilterTag); } } // Initialize state m_TimeProbe = watch.m_TimeProbe; m_Process = watch.m_Process; m_SourceProcess = watch.m_SourceProcess; m_Comment = watch.m_Comment; m_StartFilterTag = 0; m_EndFilterTag = 0; m_ProgressFilterTag = 0; m_StartWriterTag = 0; m_EndWriterTag = 0; m_ProgressWriterTag = 0; // Create a series of commands if (m_Process) { m_StartWriterCommand = CommandType::New(); m_EndWriterCommand = CommandType::New(); m_ProgressWriterCommand = CommandType::New(); // Assign the callbacks m_StartWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartWriter); m_EndWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndWriter); m_ProgressWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowWriterProgress); // Add the commands as observers m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), m_StartWriterCommand); m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), m_EndWriterCommand); m_ProgressWriterTag = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressWriterCommand); } if (m_SourceProcess) { m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowFilterProgress); // Add the commands as observers m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), m_StartFilterCommand); m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), m_EndFilterCommand); m_ProgressFilterTag = m_SourceProcess->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); } } WriterWatcherBase ::~WriterWatcherBase() { // Remove any observers we have on the old process object if (m_Process) { if (m_StartWriterCommand) { m_Process->RemoveObserver(m_StartWriterTag); } if (m_EndWriterCommand) { m_Process->RemoveObserver(m_EndWriterTag); } if (m_ProgressWriterCommand) { m_Process->RemoveObserver(m_ProgressWriterTag); } } if (m_SourceProcess) { if (m_StartFilterCommand) { m_SourceProcess->RemoveObserver(m_StartFilterTag); } if (m_EndFilterCommand) { m_SourceProcess->RemoveObserver(m_EndFilterTag); } if (m_ProgressFilterCommand) { m_SourceProcess->RemoveObserver(m_ProgressFilterTag); } } } } // end namespace otb <commit_msg>COV: Fixing coverty issue 1221867 (Unintialized scalar field)<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. Some parts of this code are derived from ITK. See ITKCopyright.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 "otbWriterWatcherBase.h" namespace otb { WriterWatcherBase ::WriterWatcherBase() { // Initialize state m_Comment = "Not watching any object"; m_Process = 0; } WriterWatcherBase ::WriterWatcherBase(itk::ProcessObject* process, const char *comment) { // Initialize state m_Process = process; m_Comment = comment; // Create a series of commands m_StartWriterCommand = CommandType::New(); m_EndWriterCommand = CommandType::New(); m_ProgressWriterCommand = CommandType::New(); m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowFilterProgress); m_StartWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartWriter); m_EndWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndWriter); m_ProgressWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowWriterProgress); // Add the commands as observers m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), m_StartWriterCommand); m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), m_EndWriterCommand); m_ProgressWriterTag = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressWriterCommand); m_StartFilterTag = 0; m_EndFilterTag = 0; m_ProgressFilterTag = 0; // Try to get the filter that is wired to m_Process. if (m_Process->GetInputs()[0]->GetSource()) { m_SourceProcess = m_Process->GetInputs()[0]->GetSource(); // Add the commands as observers m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), m_StartFilterCommand); m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), m_EndFilterCommand); m_ProgressFilterTag = m_SourceProcess->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); } } WriterWatcherBase ::WriterWatcherBase(itk::ProcessObject* process, itk::ProcessObject * source, const char *comment) { // Initialize state m_Process = process; m_Comment = comment; // Create a series of commands m_StartWriterCommand = CommandType::New(); m_EndWriterCommand = CommandType::New(); m_ProgressWriterCommand = CommandType::New(); m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowFilterProgress); m_StartWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartWriter); m_EndWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndWriter); m_ProgressWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowWriterProgress); // Add the commands as observers m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), m_StartWriterCommand); m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), m_EndWriterCommand); m_ProgressWriterTag = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressWriterCommand); m_SourceProcess = source; // Add the commands as observers m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), m_StartFilterCommand); m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), m_EndFilterCommand); m_ProgressFilterTag = m_SourceProcess->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); } WriterWatcherBase ::WriterWatcherBase(const WriterWatcherBase& watch) { // Remove any observers we have on the old process object if (m_Process) { if (m_StartWriterCommand) { m_Process->RemoveObserver(m_StartWriterTag); } if (m_EndWriterCommand) { m_Process->RemoveObserver(m_EndWriterTag); } if (m_ProgressWriterCommand) { m_Process->RemoveObserver(m_ProgressWriterTag); } } if (m_SourceProcess) { if (m_StartFilterCommand) { m_SourceProcess->RemoveObserver(m_StartFilterTag); } if (m_EndFilterCommand) { m_SourceProcess->RemoveObserver(m_EndFilterTag); } if (m_ProgressFilterCommand) { m_SourceProcess->RemoveObserver(m_ProgressFilterTag); } } // Initialize state m_TimeProbe = watch.m_TimeProbe; m_Process = watch.m_Process; m_SourceProcess = watch.m_SourceProcess; m_Comment = watch.m_Comment; m_StartFilterTag = 0; m_EndFilterTag = 0; m_ProgressFilterTag = 0; m_StartWriterTag = 0; m_EndWriterTag = 0; m_ProgressWriterTag = 0; // Create a series of commands if (m_Process) { m_StartWriterCommand = CommandType::New(); m_EndWriterCommand = CommandType::New(); m_ProgressWriterCommand = CommandType::New(); // Assign the callbacks m_StartWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartWriter); m_EndWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndWriter); m_ProgressWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowWriterProgress); // Add the commands as observers m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), m_StartWriterCommand); m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), m_EndWriterCommand); m_ProgressWriterTag = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressWriterCommand); } if (m_SourceProcess) { m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowFilterProgress); // Add the commands as observers m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), m_StartFilterCommand); m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), m_EndFilterCommand); m_ProgressFilterTag = m_SourceProcess->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); } } void WriterWatcherBase ::operator =(const WriterWatcherBase& watch) { // Remove any observers we have on the old process object if (m_Process) { if (m_StartWriterCommand) { m_Process->RemoveObserver(m_StartWriterTag); } if (m_EndWriterCommand) { m_Process->RemoveObserver(m_EndWriterTag); } if (m_ProgressWriterCommand) { m_Process->RemoveObserver(m_ProgressWriterTag); } } if (m_SourceProcess) { if (m_StartFilterCommand) { m_SourceProcess->RemoveObserver(m_StartFilterTag); } if (m_EndFilterCommand) { m_SourceProcess->RemoveObserver(m_EndFilterTag); } if (m_ProgressFilterCommand) { m_SourceProcess->RemoveObserver(m_ProgressFilterTag); } } // Initialize state m_TimeProbe = watch.m_TimeProbe; m_Process = watch.m_Process; m_SourceProcess = watch.m_SourceProcess; m_Comment = watch.m_Comment; m_StartFilterTag = 0; m_EndFilterTag = 0; m_ProgressFilterTag = 0; m_StartWriterTag = 0; m_EndWriterTag = 0; m_ProgressWriterTag = 0; // Create a series of commands if (m_Process) { m_StartWriterCommand = CommandType::New(); m_EndWriterCommand = CommandType::New(); m_ProgressWriterCommand = CommandType::New(); // Assign the callbacks m_StartWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartWriter); m_EndWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndWriter); m_ProgressWriterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowWriterProgress); // Add the commands as observers m_StartWriterTag = m_Process->AddObserver(itk::StartEvent(), m_StartWriterCommand); m_EndWriterTag = m_Process->AddObserver(itk::EndEvent(), m_EndWriterCommand); m_ProgressWriterTag = m_Process->AddObserver(itk::ProgressEvent(), m_ProgressWriterCommand); } if (m_SourceProcess) { m_StartFilterCommand = CommandType::New(); m_EndFilterCommand = CommandType::New(); m_ProgressFilterCommand = CommandType::New(); // Assign the callbacks m_StartFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::StartFilter); m_EndFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::EndFilter); m_ProgressFilterCommand->SetCallbackFunction(this, &WriterWatcherBase::ShowFilterProgress); // Add the commands as observers m_StartFilterTag = m_SourceProcess->AddObserver(itk::StartEvent(), m_StartFilterCommand); m_EndFilterTag = m_SourceProcess->AddObserver(itk::EndEvent(), m_EndFilterCommand); m_ProgressFilterTag = m_SourceProcess->AddObserver(itk::ProgressEvent(), m_ProgressFilterCommand); } } WriterWatcherBase ::~WriterWatcherBase() { // Remove any observers we have on the old process object if (m_Process) { if (m_StartWriterCommand) { m_Process->RemoveObserver(m_StartWriterTag); } if (m_EndWriterCommand) { m_Process->RemoveObserver(m_EndWriterTag); } if (m_ProgressWriterCommand) { m_Process->RemoveObserver(m_ProgressWriterTag); } } if (m_SourceProcess) { if (m_StartFilterCommand) { m_SourceProcess->RemoveObserver(m_StartFilterTag); } if (m_EndFilterCommand) { m_SourceProcess->RemoveObserver(m_EndFilterTag); } if (m_ProgressFilterCommand) { m_SourceProcess->RemoveObserver(m_ProgressFilterTag); } } } } // end namespace otb <|endoftext|>
<commit_before>// $Id$ // // Copyright (C) 2003-2008 Greg Landrum and Rational Discovery LLC // // @@ All Rights Reserved @@ // #include <GraphMol/RDKitBase.h> #include <GraphMol/SmilesParse/SmilesParse.h> #include <GraphMol/SmilesParse/SmilesWrite.h> #include <GraphMol/Fingerprints/Fingerprints.h> #include <DataStructs/ExplicitBitVect.h> #include <DataStructs/BitOps.h> #include <RDGeneral/RDLog.h> #include <string> using namespace RDKit; void test1(){ BOOST_LOG(rdInfoLog) <<"testing basics" << std::endl; std::string smi = "C1=CC=CC=C1"; RWMol *m1 = SmilesToMol(smi); TEST_ASSERT(m1->getNumAtoms()==6); ExplicitBitVect *fp1=DaylightFingerprintMol(*m1); ExplicitBitVect *fp2=DaylightFingerprintMol(*m1); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>=0.0); smi = "C1=CC=CC=N1"; RWMol *m2 = SmilesToMol(smi); delete fp2; fp2=DaylightFingerprintMol(*m2); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); delete m1; delete m2; delete fp1; delete fp2; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } void test2(){ BOOST_LOG(rdInfoLog) <<"testing subgraph invariants" << std::endl; std::string smi = "CC(=O)COC"; RWMol *m1 = SmilesToMol(smi); TEST_ASSERT(m1->getNumAtoms()==6); BOOST_LOG(rdInfoLog) <<"-------------------- fp1 " << std::endl; ExplicitBitVect *fp1=DaylightFingerprintMol(*m1,1,4,2048,4,false); BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl; ExplicitBitVect *fp2=DaylightFingerprintMol(*m1,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0); INT_VECT::const_iterator i; INT_VECT v1,v2; fp1->GetOnBits(v1); //for(i=v1.begin();i!=v1.end();i++){ // BOOST_LOG(rdInfoLog) <<*i << " "; //} //BOOST_LOG(rdInfoLog) <<std::endl; RWMol *m2 = SmilesToMol("CC"); delete fp2; BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl; fp2=DaylightFingerprintMol(*m2,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0); delete m2; m2 = SmilesToMol("CC=O"); delete fp2; fp2=DaylightFingerprintMol(*m2,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0); delete m2; m2 = SmilesToMol("CCCOC"); delete fp2; fp2=DaylightFingerprintMol(*m2,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0); delete m1; delete m2; delete fp1; delete fp2; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } void test3(){ BOOST_LOG(rdInfoLog) <<"testing auto folding" << std::endl; RWMol *m = SmilesToMol("CCCOC"); ExplicitBitVect *fp1,*fp2; fp2=DaylightFingerprintMol(*m,1,4,2048,4,false, 0.3,256); TEST_ASSERT(fp2->GetNumBits()==256); delete m; delete fp2; m=SmilesToMol("CN(C)Cc1n-2c(nn1)CN=C(c1ccccc1)c1cc(Cl)ccc12"); fp1=DaylightFingerprintMol(*m,1,4,2048,4,false); TEST_ASSERT(fp1->GetNumBits()==2048); fp2=DaylightFingerprintMol(*m,1,4,2048,4,false,0.3,256); TEST_ASSERT(fp2->GetNumBits()<fp1->GetNumBits()); delete m; delete fp1; delete fp2; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } void test1alg2(){ BOOST_LOG(rdInfoLog) <<"testing basics alg2" << std::endl; std::string smi = "C1=CC=CC=C1"; RWMol *m1 = SmilesToMol(smi); TEST_ASSERT(m1->getNumAtoms()==6); ExplicitBitVect *fp1=RDKFingerprintMol(*m1); ExplicitBitVect *fp2=RDKFingerprintMol(*m1); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>=0.0); smi = "C1=CC=CC=N1"; RWMol *m2 = SmilesToMol(smi); delete fp2; fp2=RDKFingerprintMol(*m2); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); delete m1; delete m2; delete fp1; delete fp2; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } void test2alg2(){ BOOST_LOG(rdInfoLog) <<"testing subgraph invariants alg2" << std::endl; std::string smi = "CC(=O)COC"; RWMol *m1 = SmilesToMol(smi); TEST_ASSERT(m1->getNumAtoms()==6); BOOST_LOG(rdInfoLog) <<"-------------------- fp1 " << std::endl; ExplicitBitVect *fp1=RDKFingerprintMol(*m1,1,4,2048,4,false); BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl; ExplicitBitVect *fp2=RDKFingerprintMol(*m1,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0); INT_VECT::const_iterator i; INT_VECT v1,v2; fp1->GetOnBits(v1); //for(i=v1.begin();i!=v1.end();i++){ // BOOST_LOG(rdInfoLog) <<*i << " "; //} //BOOST_LOG(rdInfoLog) <<std::endl; RWMol *m2 = SmilesToMol("CC"); delete fp2; BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl; fp2=RDKFingerprintMol(*m2,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0); delete m2; m2 = SmilesToMol("CC=O"); delete fp2; fp2=RDKFingerprintMol(*m2,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0); delete m2; m2 = SmilesToMol("CCCOC"); delete fp2; fp2=RDKFingerprintMol(*m2,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0); delete m1; delete m2; delete fp1; delete fp2; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } void test4Trends(){ BOOST_LOG(rdInfoLog) <<"testing similarity trends" << std::endl; double sim1,sim2; RWMol *m; ExplicitBitVect *fp1,*fp2; m = SmilesToMol("CCC"); fp1=RDKFingerprintMol(*m); delete m; m = SmilesToMol("C1CC1"); fp2=RDKFingerprintMol(*m); sim1=TanimotoSimilarity(*fp1,*fp2); delete m; m = SmilesToMol("CCCC"); delete fp1; fp1=RDKFingerprintMol(*m); delete m; m = SmilesToMol("C1CCC1"); delete fp2; fp2=RDKFingerprintMol(*m); sim2=TanimotoSimilarity(*fp1,*fp2); TEST_ASSERT(sim2>sim1); sim2=sim1; delete m; m = SmilesToMol("CCCCC"); delete fp1; fp1=RDKFingerprintMol(*m); delete m; m = SmilesToMol("C1CCCC1"); delete fp2; fp2=RDKFingerprintMol(*m); sim2=TanimotoSimilarity(*fp1,*fp2); TEST_ASSERT(sim2>sim1); sim2=sim1; delete m; m = SmilesToMol("CCCCCC"); delete fp1; fp1=RDKFingerprintMol(*m); delete m; m = SmilesToMol("C1CCCCC1"); delete fp2; fp2=RDKFingerprintMol(*m); sim2=TanimotoSimilarity(*fp1,*fp2); TEST_ASSERT(sim2>sim1); sim2=sim1; delete m; m = SmilesToMol("CCCCCCC"); delete fp1; fp1=RDKFingerprintMol(*m); delete m; m = SmilesToMol("C1CCCCCC1"); delete fp2; fp2=RDKFingerprintMol(*m); sim2=TanimotoSimilarity(*fp1,*fp2); TEST_ASSERT(sim2>sim1); sim2=sim1; delete m; delete fp1; delete fp2; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } void test5BackwardsCompatibility(){ BOOST_LOG(rdInfoLog) <<"testing backwards compatibility of fingerprints" << std::endl; RWMol *m; ExplicitBitVect *fp1; m = SmilesToMol("CC"); fp1=RDKFingerprintMol(*m); TEST_ASSERT(fp1->GetNumOnBits()==4); TEST_ASSERT((*fp1)[951]); TEST_ASSERT((*fp1)[961]); TEST_ASSERT((*fp1)[1436]); TEST_ASSERT((*fp1)[1590]); delete fp1; #if 0 // boost 1.35.0 fp1=DaylightFingerprintMol(*m); CHECK_INVARIANT(fp1->GetNumOnBits()==4,"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[28],"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1243],"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1299],"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1606],"Fingerprint compatibility problem detected"); delete fp1; #else // boost 1.34.1 and earlier fp1=DaylightFingerprintMol(*m); CHECK_INVARIANT(fp1->GetNumOnBits()==4,"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1141],"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1317],"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1606],"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1952],"Fingerprint compatibility problem detected"); delete fp1; #endif delete m; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } int main(int argc,char *argv[]){ RDLog::InitLogs(); test1(); test2(); test3(); test1alg2(); test2alg2(); test4Trends(); test5BackwardsCompatibility(); return 0; } <commit_msg>this now passes with boost 1.35 instead of 1.34.1; edit to get 1.34.1 compatibility back<commit_after>// $Id$ // // Copyright (C) 2003-2008 Greg Landrum and Rational Discovery LLC // // @@ All Rights Reserved @@ // #include <GraphMol/RDKitBase.h> #include <GraphMol/SmilesParse/SmilesParse.h> #include <GraphMol/SmilesParse/SmilesWrite.h> #include <GraphMol/Fingerprints/Fingerprints.h> #include <DataStructs/ExplicitBitVect.h> #include <DataStructs/BitOps.h> #include <RDGeneral/RDLog.h> #include <string> using namespace RDKit; void test1(){ BOOST_LOG(rdInfoLog) <<"testing basics" << std::endl; std::string smi = "C1=CC=CC=C1"; RWMol *m1 = SmilesToMol(smi); TEST_ASSERT(m1->getNumAtoms()==6); ExplicitBitVect *fp1=DaylightFingerprintMol(*m1); ExplicitBitVect *fp2=DaylightFingerprintMol(*m1); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>=0.0); smi = "C1=CC=CC=N1"; RWMol *m2 = SmilesToMol(smi); delete fp2; fp2=DaylightFingerprintMol(*m2); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); delete m1; delete m2; delete fp1; delete fp2; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } void test2(){ BOOST_LOG(rdInfoLog) <<"testing subgraph invariants" << std::endl; std::string smi = "CC(=O)COC"; RWMol *m1 = SmilesToMol(smi); TEST_ASSERT(m1->getNumAtoms()==6); BOOST_LOG(rdInfoLog) <<"-------------------- fp1 " << std::endl; ExplicitBitVect *fp1=DaylightFingerprintMol(*m1,1,4,2048,4,false); BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl; ExplicitBitVect *fp2=DaylightFingerprintMol(*m1,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0); INT_VECT::const_iterator i; INT_VECT v1,v2; fp1->GetOnBits(v1); //for(i=v1.begin();i!=v1.end();i++){ // BOOST_LOG(rdInfoLog) <<*i << " "; //} //BOOST_LOG(rdInfoLog) <<std::endl; RWMol *m2 = SmilesToMol("CC"); delete fp2; BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl; fp2=DaylightFingerprintMol(*m2,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0); delete m2; m2 = SmilesToMol("CC=O"); delete fp2; fp2=DaylightFingerprintMol(*m2,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0); delete m2; m2 = SmilesToMol("CCCOC"); delete fp2; fp2=DaylightFingerprintMol(*m2,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0); delete m1; delete m2; delete fp1; delete fp2; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } void test3(){ BOOST_LOG(rdInfoLog) <<"testing auto folding" << std::endl; RWMol *m = SmilesToMol("CCCOC"); ExplicitBitVect *fp1,*fp2; fp2=DaylightFingerprintMol(*m,1,4,2048,4,false, 0.3,256); TEST_ASSERT(fp2->GetNumBits()==256); delete m; delete fp2; m=SmilesToMol("CN(C)Cc1n-2c(nn1)CN=C(c1ccccc1)c1cc(Cl)ccc12"); fp1=DaylightFingerprintMol(*m,1,4,2048,4,false); TEST_ASSERT(fp1->GetNumBits()==2048); fp2=DaylightFingerprintMol(*m,1,4,2048,4,false,0.3,256); TEST_ASSERT(fp2->GetNumBits()<fp1->GetNumBits()); delete m; delete fp1; delete fp2; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } void test1alg2(){ BOOST_LOG(rdInfoLog) <<"testing basics alg2" << std::endl; std::string smi = "C1=CC=CC=C1"; RWMol *m1 = SmilesToMol(smi); TEST_ASSERT(m1->getNumAtoms()==6); ExplicitBitVect *fp1=RDKFingerprintMol(*m1); ExplicitBitVect *fp2=RDKFingerprintMol(*m1); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>=0.0); smi = "C1=CC=CC=N1"; RWMol *m2 = SmilesToMol(smi); delete fp2; fp2=RDKFingerprintMol(*m2); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); delete m1; delete m2; delete fp1; delete fp2; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } void test2alg2(){ BOOST_LOG(rdInfoLog) <<"testing subgraph invariants alg2" << std::endl; std::string smi = "CC(=O)COC"; RWMol *m1 = SmilesToMol(smi); TEST_ASSERT(m1->getNumAtoms()==6); BOOST_LOG(rdInfoLog) <<"-------------------- fp1 " << std::endl; ExplicitBitVect *fp1=RDKFingerprintMol(*m1,1,4,2048,4,false); BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl; ExplicitBitVect *fp2=RDKFingerprintMol(*m1,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0); INT_VECT::const_iterator i; INT_VECT v1,v2; fp1->GetOnBits(v1); //for(i=v1.begin();i!=v1.end();i++){ // BOOST_LOG(rdInfoLog) <<*i << " "; //} //BOOST_LOG(rdInfoLog) <<std::endl; RWMol *m2 = SmilesToMol("CC"); delete fp2; BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl; fp2=RDKFingerprintMol(*m2,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0); delete m2; m2 = SmilesToMol("CC=O"); delete fp2; fp2=RDKFingerprintMol(*m2,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0); delete m2; m2 = SmilesToMol("CCCOC"); delete fp2; fp2=RDKFingerprintMol(*m2,1,4,2048,4,false); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0); TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0); TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0); delete m1; delete m2; delete fp1; delete fp2; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } void test4Trends(){ BOOST_LOG(rdInfoLog) <<"testing similarity trends" << std::endl; double sim1,sim2; RWMol *m; ExplicitBitVect *fp1,*fp2; m = SmilesToMol("CCC"); fp1=RDKFingerprintMol(*m); delete m; m = SmilesToMol("C1CC1"); fp2=RDKFingerprintMol(*m); sim1=TanimotoSimilarity(*fp1,*fp2); delete m; m = SmilesToMol("CCCC"); delete fp1; fp1=RDKFingerprintMol(*m); delete m; m = SmilesToMol("C1CCC1"); delete fp2; fp2=RDKFingerprintMol(*m); sim2=TanimotoSimilarity(*fp1,*fp2); TEST_ASSERT(sim2>sim1); sim2=sim1; delete m; m = SmilesToMol("CCCCC"); delete fp1; fp1=RDKFingerprintMol(*m); delete m; m = SmilesToMol("C1CCCC1"); delete fp2; fp2=RDKFingerprintMol(*m); sim2=TanimotoSimilarity(*fp1,*fp2); TEST_ASSERT(sim2>sim1); sim2=sim1; delete m; m = SmilesToMol("CCCCCC"); delete fp1; fp1=RDKFingerprintMol(*m); delete m; m = SmilesToMol("C1CCCCC1"); delete fp2; fp2=RDKFingerprintMol(*m); sim2=TanimotoSimilarity(*fp1,*fp2); TEST_ASSERT(sim2>sim1); sim2=sim1; delete m; m = SmilesToMol("CCCCCCC"); delete fp1; fp1=RDKFingerprintMol(*m); delete m; m = SmilesToMol("C1CCCCCC1"); delete fp2; fp2=RDKFingerprintMol(*m); sim2=TanimotoSimilarity(*fp1,*fp2); TEST_ASSERT(sim2>sim1); sim2=sim1; delete m; delete fp1; delete fp2; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } void test5BackwardsCompatibility(){ BOOST_LOG(rdInfoLog) <<"testing backwards compatibility of fingerprints" << std::endl; RWMol *m; ExplicitBitVect *fp1; m = SmilesToMol("CC"); fp1=RDKFingerprintMol(*m); TEST_ASSERT(fp1->GetNumOnBits()==4); TEST_ASSERT((*fp1)[951]); TEST_ASSERT((*fp1)[961]); TEST_ASSERT((*fp1)[1436]); TEST_ASSERT((*fp1)[1590]); delete fp1; #if 1 // boost 1.35.0 fp1=DaylightFingerprintMol(*m); CHECK_INVARIANT(fp1->GetNumOnBits()==4,"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[28],"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1243],"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1299],"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1606],"Fingerprint compatibility problem detected"); delete fp1; #else // boost 1.34.1 and earlier fp1=DaylightFingerprintMol(*m); CHECK_INVARIANT(fp1->GetNumOnBits()==4,"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1141],"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1317],"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1606],"Fingerprint compatibility problem detected"); CHECK_INVARIANT((*fp1)[1952],"Fingerprint compatibility problem detected"); delete fp1; #endif delete m; BOOST_LOG(rdInfoLog) <<"done" << std::endl; } int main(int argc,char *argv[]){ RDLog::InitLogs(); test1(); test2(); test3(); test1alg2(); test2alg2(); test4Trends(); test5BackwardsCompatibility(); return 0; } <|endoftext|>
<commit_before>// Rabin-Karp - String Matching + Hashing O(n+m) const int B = 31; char s[N], p[N]; int n, m; // n = strlen(s), m = strlen(p) void rabin() { if (n<m) return; int hp = 0, hs = 0, E = 1; for (int i = 0; i < m; ++i) hp = ((hp*B)%MOD + p[i])%MOD, hs = ((hs*B)%MOD + s[i])%MOD, E = (E*B)%MOD; if (hs == hp) { /* matching position 0 */ } for (int i = m; i < n; ++i) { hs = ((hs*B)%MOD + s[i])%MOD; hs = (hs + (MOD - (s[i-m]*E)%MOD)%MOD)%MOD; if (hs == hp) { /* matching position i-m+1 */ } } } <commit_msg>Fixed overflow issue<commit_after>// Rabin-Karp - String Matching + Hashing O(n+m) const int B = 31; char s[N], p[N]; int n, m; // n = strlen(s), m = strlen(p) void rabin() { if (n<m) return; ll hp = 0, hs = 0, E = 1; for (int i = 0; i < m; ++i) hp = ((hp*B)%MOD + p[i])%MOD, hs = ((hs*B)%MOD + s[i])%MOD, E = (E*B)%MOD; if (hs == hp) { /* matching position 0 */ } for (int i = m; i < n; ++i) { hs = ((hs*B)%MOD + s[i])%MOD; hs = (hs + (MOD - (s[i-m]*E)%MOD)%MOD)%MOD; if (hs == hp) { /* matching position i-m+1 */ } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: formbrowsertools.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 20:11:49 $ * * 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 _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_ #define _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_ #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_ #include <com/sun/star/beans/Property.hpp> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #include <functional> //............................................................................ namespace pcr { //............................................................................ ::rtl::OUString GetUIHeadlineName(sal_Int16 _nClassId, const ::com::sun::star::uno::Any& _rUnoObject); struct FindPropertyByHandle : public ::std::unary_function< ::com::sun::star::beans::Property, bool > { private: sal_Int32 m_nId; public: FindPropertyByHandle( sal_Int32 _nId ) : m_nId ( _nId ) { } bool operator()( const ::com::sun::star::beans::Property& _rProp ) const { return m_nId == _rProp.Handle; } }; struct LessPropertyByHandle : public ::std::binary_function< ::com::sun::star::beans::Property, ::com::sun::star::beans::Property, bool > { bool operator()( const ::com::sun::star::beans::Property& _rLHS, const ::com::sun::star::beans::Property& _rRHS ) const { return _rLHS.Handle < _rRHS.Handle; } }; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_ <commit_msg>INTEGRATION: CWS pbrwuno (1.3.158); FILE MERGED 2005/10/31 11:13:06 fs 1.3.158.3: teach the ComposedPropertyUIUpdate to handle missing properties 2005/10/05 06:56:08 fs 1.3.158.2: RESYNC: (1.3-1.4); FILE MERGED 2005/08/09 13:59:58 fs 1.3.158.1: #i53095# phase 1: - don't use strings to transver values between controls and introspectee, but Anys - first version of a dedicated property handler for form-component-related properties (not yet completed) known regressions over previous phase: - handlers for events not yet implemented, thus some assertions - click handlers for form-component-related properties do not yet work, thus the browse buttons mostly do not work<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: formbrowsertools.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2006-03-14 11:22:55 $ * * 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 _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_ #define _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_ #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_ #include <com/sun/star/beans/Property.hpp> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #include <functional> #include <set> //............................................................................ namespace pcr { //............................................................................ ::rtl::OUString GetUIHeadlineName(sal_Int16 _nClassId, const ::com::sun::star::uno::Any& _rUnoObject); //======================================================================== struct FindPropertyByHandle : public ::std::unary_function< ::com::sun::star::beans::Property, bool > { private: sal_Int32 m_nId; public: FindPropertyByHandle( sal_Int32 _nId ) : m_nId ( _nId ) { } bool operator()( const ::com::sun::star::beans::Property& _rProp ) const { return m_nId == _rProp.Handle; } }; //======================================================================== struct FindPropertyByName : public ::std::unary_function< ::com::sun::star::beans::Property, bool > { private: ::rtl::OUString m_sName; public: FindPropertyByName( const ::rtl::OUString& _rName ) : m_sName( _rName ) { } bool operator()( const ::com::sun::star::beans::Property& _rProp ) const { return m_sName == _rProp.Name; } }; //======================================================================== struct PropertyLessByName :public ::std::binary_function < ::com::sun::star::beans::Property, ::com::sun::star::beans::Property, bool > { bool operator() (::com::sun::star::beans::Property _rLhs, ::com::sun::star::beans::Property _rRhs) const { return _rLhs.Name < _rRhs.Name ? true : false; } }; //======================================================================== struct TypeLessByName :public ::std::binary_function < ::com::sun::star::uno::Type, ::com::sun::star::uno::Type, bool > { bool operator() (::com::sun::star::uno::Type _rLhs, ::com::sun::star::uno::Type _rRhs) const { return _rLhs.getTypeName() < _rRhs.getTypeName() ? true : false; } }; //======================================================================== typedef ::std::set< ::com::sun::star::beans::Property, PropertyLessByName > PropertyBag; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_ <|endoftext|>
<commit_before><commit_msg>fix explicit delete.<commit_after><|endoftext|>
<commit_before>//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements dead inst elimination and dead code elimination. // // Dead Inst Elimination performs a single pass over the function removing // instructions that are obviously dead. Dead Code Elimination is similar, but // it rechecks instructions that were used by removed instructions to see if // they are newly dead. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Instruction.h" #include "llvm/Pass.h" #include "llvm/Support/InstIterator.h" #include "llvm/ADT/Statistic.h" #include <set> using namespace llvm; namespace { Statistic<> DIEEliminated("die", "Number of insts removed"); Statistic<> DCEEliminated("dce", "Number of insts removed"); //===--------------------------------------------------------------------===// // DeadInstElimination pass implementation // struct DeadInstElimination : public BasicBlockPass { virtual bool runOnBasicBlock(BasicBlock &BB) { bool Changed = false; for (BasicBlock::iterator DI = BB.begin(); DI != BB.end(); ) if (dceInstruction(DI)) { Changed = true; ++DIEEliminated; } else ++DI; return Changed; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); } }; RegisterOpt<DeadInstElimination> X("die", "Dead Instruction Elimination"); } FunctionPass *llvm::createDeadInstEliminationPass() { return new DeadInstElimination(); } //===----------------------------------------------------------------------===// // DeadCodeElimination pass implementation // namespace { struct DCE : public FunctionPass { virtual bool runOnFunction(Function &F); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); } }; RegisterOpt<DCE> Y("dce", "Dead Code Elimination"); } bool DCE::runOnFunction(Function &F) { // Start out with all of the instructions in the worklist... std::vector<Instruction*> WorkList; for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) { WorkList.push_back(&*i); } std::set<Instruction*> DeadInsts; // Loop over the worklist finding instructions that are dead. If they are // dead make them drop all of their uses, making other instructions // potentially dead, and work until the worklist is empty. // while (!WorkList.empty()) { Instruction *I = WorkList.back(); WorkList.pop_back(); if (isInstructionTriviallyDead(I)) { // If the instruction is dead... // Loop over all of the values that the instruction uses, if there are // instructions being used, add them to the worklist, because they might // go dead after this one is removed. // for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) if (Instruction *Used = dyn_cast<Instruction>(*OI)) WorkList.push_back(Used); // Tell the instruction to let go of all of the values it uses... I->dropAllReferences(); // Keep track of this instruction, because we are going to delete it later DeadInsts.insert(I); } } // If we found no dead instructions, we haven't changed the function... if (DeadInsts.empty()) return false; // Otherwise, loop over the program, removing and deleting the instructions... for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) for (BasicBlock::iterator BI = I->begin(); BI != I->end(); ) if (DeadInsts.count(BI)) { // Is this instruction dead? BI = I->getInstList().erase(BI); // Yup, remove and delete inst ++DCEEliminated; } else { // This instruction is not dead ++BI; // Continue on to the next one... } return true; } FunctionPass *llvm::createDeadCodeEliminationPass() { return new DCE(); } <commit_msg>clean up and modernize this pass.<commit_after>//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements dead inst elimination and dead code elimination. // // Dead Inst Elimination performs a single pass over the function removing // instructions that are obviously dead. Dead Code Elimination is similar, but // it rechecks instructions that were used by removed instructions to see if // they are newly dead. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Instruction.h" #include "llvm/Pass.h" #include "llvm/Support/InstIterator.h" #include "llvm/ADT/Statistic.h" #include <set> using namespace llvm; namespace { Statistic<> DIEEliminated("die", "Number of insts removed"); Statistic<> DCEEliminated("dce", "Number of insts removed"); //===--------------------------------------------------------------------===// // DeadInstElimination pass implementation // struct DeadInstElimination : public BasicBlockPass { virtual bool runOnBasicBlock(BasicBlock &BB) { bool Changed = false; for (BasicBlock::iterator DI = BB.begin(); DI != BB.end(); ) if (dceInstruction(DI)) { Changed = true; ++DIEEliminated; } else ++DI; return Changed; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); } }; RegisterOpt<DeadInstElimination> X("die", "Dead Instruction Elimination"); } FunctionPass *llvm::createDeadInstEliminationPass() { return new DeadInstElimination(); } //===----------------------------------------------------------------------===// // DeadCodeElimination pass implementation // namespace { struct DCE : public FunctionPass { virtual bool runOnFunction(Function &F); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); } }; RegisterOpt<DCE> Y("dce", "Dead Code Elimination"); } bool DCE::runOnFunction(Function &F) { // Start out with all of the instructions in the worklist... std::vector<Instruction*> WorkList; for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) WorkList.push_back(&*i); // Loop over the worklist finding instructions that are dead. If they are // dead make them drop all of their uses, making other instructions // potentially dead, and work until the worklist is empty. // bool MadeChange = false; while (!WorkList.empty()) { Instruction *I = WorkList.back(); WorkList.pop_back(); if (isInstructionTriviallyDead(I)) { // If the instruction is dead. // Loop over all of the values that the instruction uses, if there are // instructions being used, add them to the worklist, because they might // go dead after this one is removed. // for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) if (Instruction *Used = dyn_cast<Instruction>(*OI)) WorkList.push_back(Used); // Remove the instruction. I->eraseFromParent(); // Remove the instruction from the worklist if it still exists in it. for (std::vector<Instruction*>::iterator WI = WorkList.begin(), E = WorkList.end(); WI != E; ++WI) if (*WI == I) { WorkList.erase(WI); --E; --WI; } MadeChange = true; ++DCEEliminated; } } return MadeChange; } FunctionPass *llvm::createDeadCodeEliminationPass() { return new DCE(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_VCL_INC_UNX_CAIROFONTIMPL_HXX #define INCLUDED_VCL_INC_UNX_CAIROFONTIMPL_HXX #include <tools/rational.hxx> #include <vcl/salgtype.hxx> #include <vcl/vclenum.hxx> #include <vcl/metric.hxx> #include "salgdi.hxx" #include "salglyphid.hxx" #include "fontsubset.hxx" class PspSalPrinter; class PspSalInfoPrinter; class ServerFont; class ImplLayoutArgs; class ServerFontLayout; class PhysicalFontCollection; class PhysicalFontFace; class TextRenderImpl { public: virtual ~TextRenderImpl() {} virtual void SetTextColor( SalColor nSalColor ) = 0; virtual sal_uInt16 SetFont( FontSelectPattern*, int nFallbackLevel ) = 0; virtual void GetFontMetric( ImplFontMetricData*, int nFallbackLevel ) = 0; virtual const FontCharMapPtr GetFontCharMap() const = 0; virtual bool GetFontCapabilities(vcl::FontCapabilities &rFontCapabilities) const = 0; virtual void GetDevFontList( PhysicalFontCollection* ) = 0; virtual void ClearDevFontCache() = 0; virtual bool AddTempDevFont( PhysicalFontCollection*, const OUString& rFileURL, const OUString& rFontName ) = 0; virtual bool CreateFontSubset( const OUString& rToFile, const PhysicalFontFace*, sal_GlyphId* pGlyphIDs, sal_uInt8* pEncoding, sal_Int32* pWidths, int nGlyphs, FontSubsetInfo& rInfo ) = 0; virtual const Ucs2SIntMap* GetFontEncodingVector( const PhysicalFontFace*, const Ucs2OStrMap** ppNonEncoded ) = 0; virtual const void* GetEmbedFontData( const PhysicalFontFace*, const sal_Ucs* pUnicodes, sal_Int32* pWidths, FontSubsetInfo& rInfo, long* pDataLen ) = 0; virtual void FreeEmbedFontData( const void* pData, long nDataLen ) = 0; virtual void GetGlyphWidths( const PhysicalFontFace*, bool bVertical, Int32Vector& rWidths, Ucs2UIntMap& rUnicodeEnc ) = 0; virtual bool GetGlyphBoundRect( sal_GlyphId nIndex, Rectangle& ) = 0; virtual bool GetGlyphOutline( sal_GlyphId nIndex, ::basegfx::B2DPolyPolygon& ) = 0; virtual SalLayout* GetTextLayout( ImplLayoutArgs&, int nFallbackLevel ) = 0; virtual void DrawServerFontLayout( const ServerFontLayout& ) = 0; virtual SystemFontData GetSysFontData( int nFallbackLevel ) const = 0; }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>fix build<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_VCL_INC_UNX_CAIROFONTIMPL_HXX #define INCLUDED_VCL_INC_UNX_CAIROFONTIMPL_HXX #include <sal/types.h> #include <vcl/salgtype.hxx> #include <vcl/vclenum.hxx> #include <vcl/metric.hxx> #include "salgdi.hxx" #include "salglyphid.hxx" #include "fontsubset.hxx" class PspSalPrinter; class PspSalInfoPrinter; class ServerFont; class ImplLayoutArgs; class ServerFontLayout; class PhysicalFontCollection; class PhysicalFontFace; class TextRenderImpl { public: virtual ~TextRenderImpl() {} virtual void SetTextColor( SalColor nSalColor ) = 0; virtual sal_uInt16 SetFont( FontSelectPattern*, int nFallbackLevel ) = 0; virtual void GetFontMetric( ImplFontMetricData*, int nFallbackLevel ) = 0; virtual const FontCharMapPtr GetFontCharMap() const = 0; virtual bool GetFontCapabilities(vcl::FontCapabilities &rFontCapabilities) const = 0; virtual void GetDevFontList( PhysicalFontCollection* ) = 0; virtual void ClearDevFontCache() = 0; virtual bool AddTempDevFont( PhysicalFontCollection*, const OUString& rFileURL, const OUString& rFontName ) = 0; virtual bool CreateFontSubset( const OUString& rToFile, const PhysicalFontFace*, sal_GlyphId* pGlyphIDs, sal_uInt8* pEncoding, sal_Int32* pWidths, int nGlyphs, FontSubsetInfo& rInfo ) = 0; virtual const Ucs2SIntMap* GetFontEncodingVector( const PhysicalFontFace*, const Ucs2OStrMap** ppNonEncoded ) = 0; virtual const void* GetEmbedFontData( const PhysicalFontFace*, const sal_Ucs* pUnicodes, sal_Int32* pWidths, FontSubsetInfo& rInfo, long* pDataLen ) = 0; virtual void FreeEmbedFontData( const void* pData, long nDataLen ) = 0; virtual void GetGlyphWidths( const PhysicalFontFace*, bool bVertical, Int32Vector& rWidths, Ucs2UIntMap& rUnicodeEnc ) = 0; virtual bool GetGlyphBoundRect( sal_GlyphId nIndex, Rectangle& ) = 0; virtual bool GetGlyphOutline( sal_GlyphId nIndex, ::basegfx::B2DPolyPolygon& ) = 0; virtual SalLayout* GetTextLayout( ImplLayoutArgs&, int nFallbackLevel ) = 0; virtual void DrawServerFontLayout( const ServerFontLayout& ) = 0; virtual SystemFontData GetSysFontData( int nFallbackLevel ) const = 0; }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scrwin.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-19 20:26:55 $ * * 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 _SCRWIN_HXX #define _SCRWIN_HXX #ifndef INCLUDED_SVTDLLAPI_H #include "svtools/svtdllapi.h" #endif #ifndef _SCRBAR_HXX //autogen #include <vcl/scrbar.hxx> #endif class DataChangedEvent; // ------------------------- // - ScrollableWindow-Type - // ------------------------- typedef USHORT ScrollableWindowFlags; #define SCRWIN_THUMBDRAGGING 1 #define SCRWIN_VCENTER 2 #define SCRWIN_HCENTER 4 #define SCRWIN_DEFAULT (SCRWIN_THUMBDRAGGING | SCRWIN_VCENTER | SCRWIN_HCENTER) // -------------------- // - ScrollableWindow - // -------------------- class SVT_DLLPUBLIC ScrollableWindow: public Window { private: Point aPixOffset; // offset to virtual window (pixel) Size aTotPixSz; // total size of virtual window (pixel) long nLinePixH; // size of a line/column (pixel) long nColumnPixW; ScrollBar aVScroll; // the scrollbars ScrollBar aHScroll; ScrollBarBox aCornerWin; // window in the bottom right corner BOOL bScrolling:1, // user controlled scrolling bHandleDragging:1, // scroll window while dragging bHCenter:1, bVCenter:1; #ifdef _SVT_SCRWIN_CXX SVT_DLLPRIVATE void ImpInitialize( ScrollableWindowFlags nFlags ); DECL_DLLPRIVATE_LINK( ScrollHdl, ScrollBar * ); DECL_DLLPRIVATE_LINK( EndScrollHdl, ScrollBar * ); #endif public: ScrollableWindow( Window* pParent, WinBits nBits = 0, ScrollableWindowFlags = SCRWIN_DEFAULT ); ScrollableWindow( Window* pParent, const ResId& rId, ScrollableWindowFlags = SCRWIN_DEFAULT ); virtual void Resize(); virtual void Command( const CommandEvent& rCEvt ); virtual void DataChanged( const DataChangedEvent& rDEvt ); virtual void StartScroll(); virtual void EndScroll( long nDeltaX, long nDeltaY ); using OutputDevice::SetMapMode; virtual void SetMapMode( const MapMode& rNewMapMode ); virtual MapMode GetMapMode() const; void SetTotalSize( const Size& rNewSize ); Size GetTotalSize() { return PixelToLogic( aTotPixSz ); } void SetVisibleSize( const Size& rNewSize ); BOOL MakeVisible( const Rectangle& rTarget, BOOL bSloppy = FALSE ); Rectangle GetVisibleArea() const; void SetLineSize( ULONG nHorz, ULONG nVert ); using Window::Scroll; virtual void Scroll( long nDeltaX, long nDeltaY, USHORT nFlags = 0 ); void ScrollLines( long nLinesX, long nLinesY ); void ScrollPages( long nPagesX, ULONG nOverlapX, long nPagesY, ULONG nOverlapY ); private: SVT_DLLPRIVATE Size GetOutputSizePixel() const; SVT_DLLPRIVATE Size GetOutputSize() const; }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.4.546); FILE MERGED 2008/04/01 12:43:08 thb 1.4.546.2: #i85898# Stripping all external header guards 2008/03/31 13:00:55 rt 1.4.546.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: scrwin.hxx,v $ * $Revision: 1.5 $ * * 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 _SCRWIN_HXX #define _SCRWIN_HXX #include "svtools/svtdllapi.h" #ifndef _SCRBAR_HXX //autogen #include <vcl/scrbar.hxx> #endif class DataChangedEvent; // ------------------------- // - ScrollableWindow-Type - // ------------------------- typedef USHORT ScrollableWindowFlags; #define SCRWIN_THUMBDRAGGING 1 #define SCRWIN_VCENTER 2 #define SCRWIN_HCENTER 4 #define SCRWIN_DEFAULT (SCRWIN_THUMBDRAGGING | SCRWIN_VCENTER | SCRWIN_HCENTER) // -------------------- // - ScrollableWindow - // -------------------- class SVT_DLLPUBLIC ScrollableWindow: public Window { private: Point aPixOffset; // offset to virtual window (pixel) Size aTotPixSz; // total size of virtual window (pixel) long nLinePixH; // size of a line/column (pixel) long nColumnPixW; ScrollBar aVScroll; // the scrollbars ScrollBar aHScroll; ScrollBarBox aCornerWin; // window in the bottom right corner BOOL bScrolling:1, // user controlled scrolling bHandleDragging:1, // scroll window while dragging bHCenter:1, bVCenter:1; #ifdef _SVT_SCRWIN_CXX SVT_DLLPRIVATE void ImpInitialize( ScrollableWindowFlags nFlags ); DECL_DLLPRIVATE_LINK( ScrollHdl, ScrollBar * ); DECL_DLLPRIVATE_LINK( EndScrollHdl, ScrollBar * ); #endif public: ScrollableWindow( Window* pParent, WinBits nBits = 0, ScrollableWindowFlags = SCRWIN_DEFAULT ); ScrollableWindow( Window* pParent, const ResId& rId, ScrollableWindowFlags = SCRWIN_DEFAULT ); virtual void Resize(); virtual void Command( const CommandEvent& rCEvt ); virtual void DataChanged( const DataChangedEvent& rDEvt ); virtual void StartScroll(); virtual void EndScroll( long nDeltaX, long nDeltaY ); using OutputDevice::SetMapMode; virtual void SetMapMode( const MapMode& rNewMapMode ); virtual MapMode GetMapMode() const; void SetTotalSize( const Size& rNewSize ); Size GetTotalSize() { return PixelToLogic( aTotPixSz ); } void SetVisibleSize( const Size& rNewSize ); BOOL MakeVisible( const Rectangle& rTarget, BOOL bSloppy = FALSE ); Rectangle GetVisibleArea() const; void SetLineSize( ULONG nHorz, ULONG nVert ); using Window::Scroll; virtual void Scroll( long nDeltaX, long nDeltaY, USHORT nFlags = 0 ); void ScrollLines( long nLinesX, long nLinesY ); void ScrollPages( long nPagesX, ULONG nOverlapX, long nPagesY, ULONG nOverlapY ); private: SVT_DLLPRIVATE Size GetOutputSizePixel() const; SVT_DLLPRIVATE Size GetOutputSize() const; }; #endif <|endoftext|>
<commit_before> namespace collections { shared_state::shared_state() : registry(nullptr) , aqueue(nullptr) { registry = new object_registry(); aqueue = new autorelease_queue(*registry); } shared_state::~shared_state() { delete registry; delete aqueue; } void shared_state::u_clearState() { /* Not good, but working solution. purpose: free allocated memory problem: regular delete call won't help as delete call will access memory of possible deleted object solution: isolate objects by nullifying cross-references, then delete objects all we need is just free all allocated memory but this will require track stl memory blocks */ aqueue->u_nullify(); for (auto& obj : registry->u_container()) { obj->u_nullifyObjects(); } for (auto& obj : registry->u_container()) { delete obj; } registry->u_clear(); aqueue->u_clear(); if (delegate) { delegate->u_cleanup(); } } void shared_state::clearState() { aqueue->stop(); { u_clearState(); } aqueue->start(); } object_base * shared_state::getObject(Handle hdl) { return registry->getObject(hdl); } object_stack_ref shared_state::getObjectRef(Handle hdl) { return registry->getObjectRef(hdl); } object_base * shared_state::u_getObject(Handle hdl) { return registry->u_getObject(hdl); } size_t shared_state::aqueueSize() { return aqueue->count(); } void shared_state::read_from_string(const std::string & data, int version) { namespace io = boost::iostreams; io::stream<io::array_source> stream( io::array_source(data.c_str(), data.size()) ); read_from_stream(stream, version); } void shared_state::read_from_stream(std::istream & stream, int version) { stream.flags(stream.flags() | std::ios::binary); aqueue->stop(); { // i have assumed that Skyrim devs are not idiots to run scripts in process of save game loading //write_lock g(_mutex); u_clearState(); if (stream.peek() != std::istream::traits_type::eof()) { boost::archive::binary_iarchive archive(stream); if (kJSerializationCurrentVersion < version) { _FATALERROR("plugin can not be compatible with future save version %u. plugin save vesrion is %u", version, kJSerializationCurrentVersion); assert(false); } try { archive >> *registry; archive >> *aqueue; if (delegate) { delegate->u_loadAdditional(archive); } } catch (const std::exception& exc) { _FATALERROR("caught exception (%s) during archive load - '%s'. forcing application to crash", typeid(exc).name(), exc.what()); //u_clearState(); // force whole app to crash assert(false); } catch (...) { _FATALERROR("caught unknown (non std::*) exception. forcing application to crash"); // force whole app to crash assert(false); } } u_applyUpdates(version); // deadlock possible u_postLoadMaintenance(version); _DMESSAGE("%lu objects total", registry->u_container().size()); _DMESSAGE("%lu objects in aqueue", aqueue->u_count()); } aqueue->start(); } std::string shared_state::write_to_string() { std::ostringstream stream; write_to_stream(stream); return stream.str(); } void shared_state::write_to_stream(std::ostream& stream) { stream.flags(stream.flags() | std::ios::binary); boost::archive::binary_oarchive arch(stream); aqueue->stop(); { // i have assumed that Skyrim devs are not idiots to run scripts in process of saving // but didn't dare to disable all that locks // do not lock as test shows that skyrim waits for completion of any native function running. // this _probably_ means that there is no any thread inside my code during save //read_lock g(_mutex); //all_objects_lock l(*registry); arch << *registry; arch << *aqueue; if (delegate) { delegate->u_saveAdditional(arch); } _DMESSAGE("%lu objects total", registry->u_container().size()); _DMESSAGE("%lu objects in aqueue", aqueue->u_count()); } aqueue->start(); } ////////////////////////////////////////////////////////////////////////// void shared_state::u_applyUpdates(int saveVersion) { } void shared_state::u_postLoadMaintenance(int saveVersion) { for (auto& obj : registry->u_container()) { obj->set_context(*this); obj->u_onLoaded(); } } } <commit_msg>assign context to all objects first, then do the rest<commit_after> namespace collections { shared_state::shared_state() : registry(nullptr) , aqueue(nullptr) { registry = new object_registry(); aqueue = new autorelease_queue(*registry); } shared_state::~shared_state() { delete registry; delete aqueue; } void shared_state::u_clearState() { /* Not good, but working solution. purpose: free allocated memory problem: regular delete call won't help as delete call will access memory of possible deleted object solution: isolate objects by nullifying cross-references, then delete objects all we need is just free all allocated memory but this will require track stl memory blocks */ aqueue->u_nullify(); for (auto& obj : registry->u_container()) { obj->u_nullifyObjects(); } for (auto& obj : registry->u_container()) { delete obj; } registry->u_clear(); aqueue->u_clear(); if (delegate) { delegate->u_cleanup(); } } void shared_state::clearState() { aqueue->stop(); { u_clearState(); } aqueue->start(); } object_base * shared_state::getObject(Handle hdl) { return registry->getObject(hdl); } object_stack_ref shared_state::getObjectRef(Handle hdl) { return registry->getObjectRef(hdl); } object_base * shared_state::u_getObject(Handle hdl) { return registry->u_getObject(hdl); } size_t shared_state::aqueueSize() { return aqueue->count(); } void shared_state::read_from_string(const std::string & data, int version) { namespace io = boost::iostreams; io::stream<io::array_source> stream( io::array_source(data.c_str(), data.size()) ); read_from_stream(stream, version); } void shared_state::read_from_stream(std::istream & stream, int version) { stream.flags(stream.flags() | std::ios::binary); aqueue->stop(); { // i have assumed that Skyrim devs are not idiots to run scripts in process of save game loading //write_lock g(_mutex); u_clearState(); if (stream.peek() != std::istream::traits_type::eof()) { boost::archive::binary_iarchive archive(stream); if (kJSerializationCurrentVersion < version) { _FATALERROR("plugin can not be compatible with future save version %u. plugin save vesrion is %u", version, kJSerializationCurrentVersion); assert(false); } try { archive >> *registry; archive >> *aqueue; if (delegate) { delegate->u_loadAdditional(archive); } } catch (const std::exception& exc) { _FATALERROR("caught exception (%s) during archive load - '%s'. forcing application to crash", typeid(exc).name(), exc.what()); //u_clearState(); // force whole app to crash assert(false); } catch (...) { _FATALERROR("caught unknown (non std::*) exception. forcing application to crash"); // force whole app to crash assert(false); } } u_applyUpdates(version); // deadlock possible u_postLoadMaintenance(version); _DMESSAGE("%lu objects total", registry->u_container().size()); _DMESSAGE("%lu objects in aqueue", aqueue->u_count()); } aqueue->start(); } std::string shared_state::write_to_string() { std::ostringstream stream; write_to_stream(stream); return stream.str(); } void shared_state::write_to_stream(std::ostream& stream) { stream.flags(stream.flags() | std::ios::binary); boost::archive::binary_oarchive arch(stream); aqueue->stop(); { // i have assumed that Skyrim devs are not idiots to run scripts in process of saving // but didn't dare to disable all that locks // do not lock as test shows that skyrim waits for completion of any native function running. // this _probably_ means that there is no any thread inside my code during save //read_lock g(_mutex); //all_objects_lock l(*registry); arch << *registry; arch << *aqueue; if (delegate) { delegate->u_saveAdditional(arch); } _DMESSAGE("%lu objects total", registry->u_container().size()); _DMESSAGE("%lu objects in aqueue", aqueue->u_count()); } aqueue->start(); } ////////////////////////////////////////////////////////////////////////// void shared_state::u_applyUpdates(int saveVersion) { } void shared_state::u_postLoadMaintenance(int saveVersion) { for (auto& obj : registry->u_container()) { obj->set_context(*this); } for (auto& obj : registry->u_container()) { obj->u_onLoaded(); } } } <|endoftext|>
<commit_before>#include "aofile.h" #include "../utils/fs.h" #include "inner_readers.h" #include <cassert> #include <cstring> #include <cstdio> #include <mutex> using namespace dariadb; using namespace dariadb::storage; class AOFile::Private { public: Private(const AOFile::Params &params) : _params(params){ _is_readonly = false; } Private(const AOFile::Params &params, const std::string &fname, bool readonly) : _params(params) { _is_readonly = readonly; } ~Private() { this->flush(); } Meas::MeasList appended; append_result append(const Meas &value) { assert(!_is_readonly); std::lock_guard<std::mutex> lock(_mutex); auto file=std::fopen(_params.path.c_str(), "ab"); if(file!=nullptr){ std::fwrite(&value,sizeof(Meas),size_t(1),file); appended.push_back(value); std::fclose(file); return append_result(1, 0); }else{ throw MAKE_EXCEPTION("aofile: append error."); } } Reader_ptr readInterval(const QueryInterval &q) { std::lock_guard<std::mutex> lock(_mutex); TP_Reader *raw = new TP_Reader; auto file=std::fopen(_params.path.c_str(), "rb"); if(file==nullptr){ throw MAKE_EXCEPTION("aof: file open error"); } std::map<dariadb::Id, std::set<Meas, meas_time_compare_less>> sub_result; if(file!=nullptr){ while(1){ Meas val=Meas::empty(); if(fread(&val,sizeof(Meas),size_t(1),file)==0){ break; } if(val.inQuery(q.ids,q.flag,q.from,q.to)){ sub_result[val.id].insert(val); } } std::fclose(file); } for (auto &kv : sub_result) { raw->_ids.push_back(kv.first); for (auto &m : kv.second) { raw->_values.push_back(m); } } raw->reset(); return Reader_ptr(raw); } Reader_ptr readInTimePoint(const QueryTimePoint &q) { std::lock_guard<std::mutex> lock(_mutex); return nullptr; } Reader_ptr currentValue(const IdArray &ids, const Flag &flag) { std::lock_guard<std::mutex> lock(_mutex); return readInTimePoint(QueryTimePoint(ids, flag, this->maxTime())); } dariadb::Time minTime() const { std::lock_guard<std::mutex> lock(_mutex); return dariadb::MAX_TIME; } dariadb::Time maxTime() const { std::lock_guard<std::mutex> lock(_mutex); return dariadb::MIN_TIME; } bool minMaxTime(dariadb::Id id, dariadb::Time *minResult, dariadb::Time *maxResult) { std::lock_guard<std::mutex> lock(_mutex); return false; } void flush() { std::lock_guard<std::mutex> lock(_mutex); // if (drop_future.valid()) { // drop_future.wait(); //} } void drop_to_stor(MeasWriter *stor) { } protected: AOFile::Params _params; // dariadb::utils::fs::MappedFile::MapperFile_ptr mmap; // AOFile::Header *_header; // uint8_t *_raw_data; mutable std::mutex _mutex; bool _is_readonly; }; AOFile::~AOFile() {} AOFile::AOFile(const Params &params) : _Impl(new AOFile::Private(params)) {} AOFile::AOFile(const AOFile::Params &params, const std::string &fname, bool readonly) : _Impl(new AOFile::Private(params, fname, readonly)) {} //AOFile::Header AOFile::readHeader(std::string file_name) { // std::ifstream istream; // istream.open(file_name, std::fstream::in | std::fstream::binary); // if (!istream.is_open()) { // std::stringstream ss; // ss << "can't open file. filename=" << file_name; // throw MAKE_EXCEPTION(ss.str()); // } // AOFile::Header result; // memset(&result, 0, sizeof(AOFile::Header)); // istream.read((char *)&result, sizeof(AOFile::Header)); // istream.close(); // return result; //} dariadb::Time AOFile::minTime() { return _Impl->minTime(); } dariadb::Time AOFile::maxTime() { return _Impl->maxTime(); } bool AOFile::minMaxTime(dariadb::Id id, dariadb::Time *minResult, dariadb::Time *maxResult) { return _Impl->minMaxTime(id, minResult, maxResult); } void AOFile::flush() { // write all to storage; _Impl->flush(); } append_result AOFile::append(const Meas &value) { return _Impl->append(value); } Reader_ptr AOFile::readInterval(const QueryInterval &q) { return _Impl->readInterval(q); } Reader_ptr AOFile::readInTimePoint(const QueryTimePoint &q) { return _Impl->readInTimePoint(q); } Reader_ptr AOFile::currentValue(const IdArray &ids, const Flag &flag) { return _Impl->currentValue(ids, flag); } void AOFile::drop_to_stor(MeasWriter *stor) { _Impl->drop_to_stor(stor); } <commit_msg>aofile: common test passed.<commit_after>#include "aofile.h" #include "../flags.h" #include "../utils/fs.h" #include "inner_readers.h" #include <algorithm> #include <cassert> #include <cstring> #include <cstdio> #include <mutex> using namespace dariadb; using namespace dariadb::storage; class AOFile::Private { public: Private(const AOFile::Params &params) : _params(params){ _is_readonly = false; } Private(const AOFile::Params &params, const std::string &fname, bool readonly) : _params(params) { _is_readonly = readonly; } ~Private() { this->flush(); } Meas::MeasList appended; append_result append(const Meas &value) { assert(!_is_readonly); std::lock_guard<std::mutex> lock(_mutex); auto file=std::fopen(_params.path.c_str(), "ab"); if(file!=nullptr){ std::fwrite(&value,sizeof(Meas),size_t(1),file); appended.push_back(value); std::fclose(file); return append_result(1, 0); }else{ throw MAKE_EXCEPTION("aofile: append error."); } } Reader_ptr readInterval(const QueryInterval &q) { std::lock_guard<std::mutex> lock(_mutex); TP_Reader *raw = new TP_Reader; auto file=std::fopen(_params.path.c_str(), "rb"); if(file==nullptr){ throw MAKE_EXCEPTION("aof: file open error"); } std::map<dariadb::Id, std::set<Meas, meas_time_compare_less>> sub_result; while(1){ Meas val=Meas::empty(); if(fread(&val,sizeof(Meas),size_t(1),file)==0){ break; } if(val.inQuery(q.ids,q.flag,q.from,q.to)){ sub_result[val.id].insert(val); } } std::fclose(file); for (auto &kv : sub_result) { raw->_ids.push_back(kv.first); for (auto &m : kv.second) { raw->_values.push_back(m); } } raw->reset(); return Reader_ptr(raw); } Reader_ptr readInTimePoint(const QueryTimePoint &q) { std::lock_guard<std::mutex> lock(_mutex); dariadb::IdSet readed_ids; dariadb::Meas::Id2Meas sub_res; auto file=std::fopen(_params.path.c_str(), "rb"); if(file==nullptr){ throw MAKE_EXCEPTION("aof: file open error"); } while(1){ Meas val=Meas::empty(); if(fread(&val,sizeof(Meas),size_t(1),file)==0){ break; } if (val.inQuery(q.ids, q.flag) && (val.time <= q.time_point)) { replace_if_older(sub_res, val); readed_ids.insert(val.id); } } std::fclose(file); if (!q.ids.empty() && readed_ids.size() != q.ids.size()) { for (auto id : q.ids) { if (readed_ids.find(id) == readed_ids.end()) { auto e = Meas::empty(id); e.flag = Flags::_NO_DATA; e.time = q.time_point; sub_res[id] = e; } } } TP_Reader *raw = new TP_Reader; for (auto kv : sub_res) { raw->_values.push_back(kv.second); raw->_ids.push_back(kv.first); } raw->reset(); return Reader_ptr(raw); } void replace_if_older(dariadb::Meas::Id2Meas &s, const dariadb::Meas &m) const { auto fres = s.find(m.id); if (fres == s.end()) { s.insert(std::make_pair(m.id, m)); } else { if (fres->second.time < m.time) { s.insert(std::make_pair(m.id, m)); } } } Reader_ptr currentValue(const IdArray &ids, const Flag &flag) { std::lock_guard<std::mutex> lock(_mutex); dariadb::Meas::Id2Meas sub_res; dariadb::IdSet readed_ids; auto file=std::fopen(_params.path.c_str(), "rb"); if(file==nullptr){ throw MAKE_EXCEPTION("aof: file open error"); } while(1){ Meas val=Meas::empty(); if(fread(&val,sizeof(Meas),size_t(1),file)==0){ break; } replace_if_older(sub_res, val); readed_ids.insert(val.id); } std::fclose(file); if (!ids.empty() && readed_ids.size() != ids.size()) { for (auto id : ids) { if (readed_ids.find(id) == readed_ids.end()) { auto e = Meas::empty(id); e.flag = Flags::_NO_DATA; e.time = dariadb::Time(0); sub_res[id] = e; } } } TP_Reader *raw = new TP_Reader; for (auto kv : sub_res) { raw->_values.push_back(kv.second); raw->_ids.push_back(kv.first); } raw->reset(); return Reader_ptr(raw); } dariadb::Time minTime() const { std::lock_guard<std::mutex> lock(_mutex); auto file=std::fopen(_params.path.c_str(), "rb"); if(file==nullptr){ throw MAKE_EXCEPTION("aof: file open error"); } dariadb::Time result=dariadb::MAX_TIME; while(1){ Meas val=Meas::empty(); if(fread(&val,sizeof(Meas),size_t(1),file)==0){ break; } result=std::min(val.time,result); } std::fclose(file); return result; } dariadb::Time maxTime() const { auto file=std::fopen(_params.path.c_str(), "rb"); if(file==nullptr){ throw MAKE_EXCEPTION("aof: file open error"); } dariadb::Time result=dariadb::MIN_TIME; while(1){ Meas val=Meas::empty(); if(fread(&val,sizeof(Meas),size_t(1),file)==0){ break; } result=std::max(val.time,result); } std::fclose(file); return result; } bool minMaxTime(dariadb::Id id, dariadb::Time *minResult, dariadb::Time *maxResult) { auto file=std::fopen(_params.path.c_str(), "rb"); if(file==nullptr){ throw MAKE_EXCEPTION("aof: file open error"); } *minResult=dariadb::MAX_TIME; *maxResult=dariadb::MIN_TIME; bool result=false; while(1){ Meas val=Meas::empty(); if(fread(&val,sizeof(Meas),size_t(1),file)==0){ break; } if(val.id==id){ result=true; *minResult=std::min(*minResult,val.time); *maxResult=std::max(*maxResult,val.time); } } std::fclose(file); return result; } void flush() { std::lock_guard<std::mutex> lock(_mutex); // if (drop_future.valid()) { // drop_future.wait(); //} } void drop_to_stor(MeasWriter *stor) { } protected: AOFile::Params _params; // dariadb::utils::fs::MappedFile::MapperFile_ptr mmap; // AOFile::Header *_header; // uint8_t *_raw_data; mutable std::mutex _mutex; bool _is_readonly; }; AOFile::~AOFile() {} AOFile::AOFile(const Params &params) : _Impl(new AOFile::Private(params)) {} AOFile::AOFile(const AOFile::Params &params, const std::string &fname, bool readonly) : _Impl(new AOFile::Private(params, fname, readonly)) {} //AOFile::Header AOFile::readHeader(std::string file_name) { // std::ifstream istream; // istream.open(file_name, std::fstream::in | std::fstream::binary); // if (!istream.is_open()) { // std::stringstream ss; // ss << "can't open file. filename=" << file_name; // throw MAKE_EXCEPTION(ss.str()); // } // AOFile::Header result; // memset(&result, 0, sizeof(AOFile::Header)); // istream.read((char *)&result, sizeof(AOFile::Header)); // istream.close(); // return result; //} dariadb::Time AOFile::minTime() { return _Impl->minTime(); } dariadb::Time AOFile::maxTime() { return _Impl->maxTime(); } bool AOFile::minMaxTime(dariadb::Id id, dariadb::Time *minResult, dariadb::Time *maxResult) { return _Impl->minMaxTime(id, minResult, maxResult); } void AOFile::flush() { // write all to storage; _Impl->flush(); } append_result AOFile::append(const Meas &value) { return _Impl->append(value); } Reader_ptr AOFile::readInterval(const QueryInterval &q) { return _Impl->readInterval(q); } Reader_ptr AOFile::readInTimePoint(const QueryTimePoint &q) { return _Impl->readInTimePoint(q); } Reader_ptr AOFile::currentValue(const IdArray &ids, const Flag &flag) { return _Impl->currentValue(ids, flag); } void AOFile::drop_to_stor(MeasWriter *stor) { _Impl->drop_to_stor(stor); } <|endoftext|>
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2005 Artem Pavlenko * * Mapnik 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 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. */ //$Id: shapefile.hh 33 2005-04-04 13:01:03Z pavlenko $ #ifndef SHAPEFILE_HH #define SHAPEFILE_HH #include <fstream> #include "envelope.hpp" using namespace mapnik; struct shape_record { char* data; size_t size; size_t pos; explicit shape_record(size_t size) : data(static_cast<char*>(::operator new(sizeof(char)*size))), size(size), pos(0) {} char* rawdata() { return &data[0]; } void skip(unsigned n) { pos+=n; } int read_ndr_integer() { int val=(data[pos] & 0xff) | (data[pos+1] & 0xff) << 8 | (data[pos+2] & 0xff) << 16 | (data[pos+3] & 0xff) << 24; pos+=4; return val; } int read_xdr_integer() { int val=(data[pos] & 0xff) << 24 | (data[pos+1] & 0xff) << 16 | (data[pos+2] & 0xff) << 8 | (data[pos+3] & 0xff); pos+=4; return val; } double read_double() { double val; #ifndef WORDS_BIGENDIAN std::memcpy(&val,&data[pos],8); #else long long bits = ((long long)data[pos] & 0xff) | ((long long)data[pos+1] & 0xff) << 8 | ((long long)data[pos+2] & 0xff) << 16 | ((long long)data[pos+3] & 0xff) << 24 | ((long long)data[pos+4] & 0xff) << 32 | ((long long)data[pos+5] & 0xff) << 40 | ((long long)data[pos+6] & 0xff) << 48 | ((long long)data[pos+7] & 0xff) << 56 ; std::memcpy(&val,&bits,8); #endif pos+=8; return val; } long remains() { return (size-pos); } ~shape_record() { ::operator delete(data); } }; class shape_file { std::ifstream file_; //static const int buffer_size = 16; //char buff_[buffer_size]; public: shape_file(); shape_file(const std::string& file_name); ~shape_file(); bool open(const std::string& file_name); bool is_open(); void close(); inline void shape_file::read_record(shape_record& rec) { file_.read(rec.rawdata(),rec.size); } inline int read_xdr_integer() { char b[4]; file_.read(b, 4); return b[3] & 0xffu | (b[2] & 0xffu) << 8 | (b[1] & 0xffu) << 16 | (b[0] & 0xffu) << 24; } inline int read_ndr_integer() { char b[4]; file_.read(b,4); return b[0]&0xffu | (b[1]&0xffu) << 8 | (b[2]&0xffu) << 16 | (b[3]&0xffu) << 24; } inline double read_double() { double val; #ifndef WORDS_BIGENDIAN file_.read(reinterpret_cast<char*>(&val),8); #else char b[8]; file_.read(b,8); long long bits = ((long long)b[0] & 0xff) | ((long long)b[1] & 0xff) << 8 | ((long long)b[2] & 0xff) << 16 | ((long long)b[3] & 0xff) << 24 | ((long long)b[4] & 0xff) << 32 | ((long long)b[5] & 0xff) << 40 | ((long long)b[6] & 0xff) << 48 | ((long long)b[7] & 0xff) << 56 ; memcpy(&val,&bits,8); #endif return val; } inline void read_envelope(Envelope<double>& envelope) { #ifndef WORDS_BIGENDIAN file_.read(reinterpret_cast<char*>(&envelope),sizeof(envelope)); #else double minx=read_double(); double miny=read_double(); double maxx=read_double(); double maxy=read_double(); envelope.init(minx,miny,maxx,maxy); #endif } inline void skip(std::streampos bytes) { file_.seekg(bytes,std::ios::cur); } inline void rewind() { seek(100); } inline void seek(std::streampos pos) { file_.seekg(pos,std::ios::beg); } inline std::streampos pos() { return file_.tellg(); } inline bool is_eof() { return file_.eof(); } private: shape_file(const shape_file&); shape_file& operator=(const shape_file&); }; #endif //SHAPEFILE_HH <commit_msg>fixed extra qualifier<commit_after>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2005 Artem Pavlenko * * Mapnik 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 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. */ //$Id: shapefile.hh 33 2005-04-04 13:01:03Z pavlenko $ #ifndef SHAPEFILE_HH #define SHAPEFILE_HH #include <fstream> #include "envelope.hpp" using namespace mapnik; struct shape_record { char* data; size_t size; size_t pos; explicit shape_record(size_t size) : data(static_cast<char*>(::operator new(sizeof(char)*size))), size(size), pos(0) {} char* rawdata() { return &data[0]; } void skip(unsigned n) { pos+=n; } int read_ndr_integer() { int val=(data[pos] & 0xff) | (data[pos+1] & 0xff) << 8 | (data[pos+2] & 0xff) << 16 | (data[pos+3] & 0xff) << 24; pos+=4; return val; } int read_xdr_integer() { int val=(data[pos] & 0xff) << 24 | (data[pos+1] & 0xff) << 16 | (data[pos+2] & 0xff) << 8 | (data[pos+3] & 0xff); pos+=4; return val; } double read_double() { double val; #ifndef WORDS_BIGENDIAN std::memcpy(&val,&data[pos],8); #else long long bits = ((long long)data[pos] & 0xff) | ((long long)data[pos+1] & 0xff) << 8 | ((long long)data[pos+2] & 0xff) << 16 | ((long long)data[pos+3] & 0xff) << 24 | ((long long)data[pos+4] & 0xff) << 32 | ((long long)data[pos+5] & 0xff) << 40 | ((long long)data[pos+6] & 0xff) << 48 | ((long long)data[pos+7] & 0xff) << 56 ; std::memcpy(&val,&bits,8); #endif pos+=8; return val; } long remains() { return (size-pos); } ~shape_record() { ::operator delete(data); } }; class shape_file { std::ifstream file_; //static const int buffer_size = 16; //char buff_[buffer_size]; public: shape_file(); shape_file(const std::string& file_name); ~shape_file(); bool open(const std::string& file_name); bool is_open(); void close(); inline void read_record(shape_record& rec) { file_.read(rec.rawdata(),rec.size); } inline int read_xdr_integer() { char b[4]; file_.read(b, 4); return b[3] & 0xffu | (b[2] & 0xffu) << 8 | (b[1] & 0xffu) << 16 | (b[0] & 0xffu) << 24; } inline int read_ndr_integer() { char b[4]; file_.read(b,4); return b[0]&0xffu | (b[1]&0xffu) << 8 | (b[2]&0xffu) << 16 | (b[3]&0xffu) << 24; } inline double read_double() { double val; #ifndef WORDS_BIGENDIAN file_.read(reinterpret_cast<char*>(&val),8); #else char b[8]; file_.read(b,8); long long bits = ((long long)b[0] & 0xff) | ((long long)b[1] & 0xff) << 8 | ((long long)b[2] & 0xff) << 16 | ((long long)b[3] & 0xff) << 24 | ((long long)b[4] & 0xff) << 32 | ((long long)b[5] & 0xff) << 40 | ((long long)b[6] & 0xff) << 48 | ((long long)b[7] & 0xff) << 56 ; memcpy(&val,&bits,8); #endif return val; } inline void read_envelope(Envelope<double>& envelope) { #ifndef WORDS_BIGENDIAN file_.read(reinterpret_cast<char*>(&envelope),sizeof(envelope)); #else double minx=read_double(); double miny=read_double(); double maxx=read_double(); double maxy=read_double(); envelope.init(minx,miny,maxx,maxy); #endif } inline void skip(std::streampos bytes) { file_.seekg(bytes,std::ios::cur); } inline void rewind() { seek(100); } inline void seek(std::streampos pos) { file_.seekg(pos,std::ios::beg); } inline std::streampos pos() { return file_.tellg(); } inline bool is_eof() { return file_.eof(); } private: shape_file(const shape_file&); shape_file& operator=(const shape_file&); }; #endif //SHAPEFILE_HH <|endoftext|>
<commit_before>/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ =========================================================================*/ #include <irtkImage.h> #include <irtkTransformation.h> #include <irtkRegistration.h> #include <Fl_RView.h> #include <Fl_RViewUI.h> #include <Fl_RView_Histogram.h> extern Fl_RViewUI *rviewUI; Fl_HistogramWindow::Fl_HistogramWindow(int x, int y, int w, int h, const char *name, irtkRView *viewer) : Fl_Window(x, y, w, h, name), _histogramWindow(viewer) { _v = viewer; } Fl_HistogramWindow::~Fl_HistogramWindow() { } void Fl_HistogramWindow::recalculate() { _histogramWindow.CalculateHistograms(); } void Fl_HistogramWindow::draw() { int i, j; char buffer[256], buffer2[256]; unsigned char r, g, b; double x, y, ox, oy; // Clear everything make_current(); fl_draw_box(FL_FLAT_BOX, 0, 0, w(), h(), FL_WHITE); // Draw horizontal axis fl_color(225,225,225); fl_line_style(FL_DOT, 0); fl_line(10, round((h()-30)*0.00)+10, w()-10, round((h()-30)*0.00+10)); fl_line(10, round((h()-30)*0.25)+10, w()-10, round((h()-30)*0.25+10)); fl_line(10, round((h()-30)*0.50)+10, w()-10, round((h()-30)*0.50+10)); fl_line(10, round((h()-30)*0.75)+10, w()-10, round((h()-30)*0.75+10)); fl_line(10, round((h()-30)*1.00)+10, w()-10, round((h()-30)*1.00+10)); // Draw vertical axis and labels for (i = 0; i <= HISTOGRAM_BINS; i += 32) { sprintf(buffer, "%d", i); fl_color(128,128,128); position(i, -1, x, y); fl_line(round(x), 10, round(x), h()-20); fl_draw(buffer, round(x)-5, h()-5); sprintf(buffer2, "%d", round(_histogramWindow._globalHistogram.BinToVal(i))); fl_draw(buffer2, round(x), h()-25); } // Compute maximum in histogram _maxHistogram = 0; for (int i = 0; i < HISTOGRAM_BINS; i++) { if (_histogramWindow._globalHistogram(i) > _maxHistogram) _maxHistogram = _histogramWindow._globalHistogram(i); } // Set up FL drawing colour and style fl_color(0,0,0); fl_line_style(FL_SOLID, 2); // Draw global histogram position(0,-1,x,y); for (int i = 1; i < HISTOGRAM_BINS; ++i) { ox = x; oy = y; position(i, -1, x, y); fl_line(round(ox), round(oy), round(x), round(y)); } // Draw histogram for each structure for (j = 0; j < SHRT_MAX+1; j++) { // Check if structure is visible if ((_v->GetSegmentTable()->GetVisibility(j)) && (_v->GetSegmentTable()->IsValid(j))) { // Set up FL drawing colour style _v->GetSegmentTable()->GetColor(j,&r,&g,&b); fl_color(r,g,b); fl_line_style(FL_SOLID, 0); // Draw histogram position(0,j,x,y); for (int i = 1; i < HISTOGRAM_BINS; ++i) { ox = x; oy = y; position(i, j, x, y); fl_line(round(ox), round(oy), round(x), round(y)); } } } } void Fl_HistogramWindow::position(int nbin, int nhistogram, double& x, double& y) { x = nbin; if (nhistogram == -1) { y = _histogramWindow._globalHistogram(nbin); } else { y = _histogramWindow._localHistogram[nhistogram](nbin); } x = (x/HISTOGRAM_BINS)*(w() - 20) + 10; y = ((_maxHistogram - y) /_maxHistogram)*(h() - 30) + 10; } <commit_msg>histogram details 1 allow float 2 the position of labels<commit_after>/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ =========================================================================*/ #include <irtkImage.h> #include <irtkTransformation.h> #include <irtkRegistration.h> #include <Fl_RView.h> #include <Fl_RViewUI.h> #include <Fl_RView_Histogram.h> extern Fl_RViewUI *rviewUI; Fl_HistogramWindow::Fl_HistogramWindow(int x, int y, int w, int h, const char *name, irtkRView *viewer) : Fl_Window(x, y, w, h, name), _histogramWindow(viewer) { _v = viewer; } Fl_HistogramWindow::~Fl_HistogramWindow() { } void Fl_HistogramWindow::recalculate() { _histogramWindow.CalculateHistograms(); } void Fl_HistogramWindow::draw() { int i, j; char buffer[256], buffer2[256]; unsigned char r, g, b; double x, y, ox, oy; // Clear everything make_current(); fl_draw_box(FL_FLAT_BOX, 0, 0, w(), h(), FL_WHITE); // Draw horizontal axis fl_color(225,225,225); fl_line_style(FL_DOT, 0); fl_line(10, round((h()-30)*0.00)+10, w()-10, round((h()-30)*0.00+10)); fl_line(10, round((h()-30)*0.25)+10, w()-10, round((h()-30)*0.25+10)); fl_line(10, round((h()-30)*0.50)+10, w()-10, round((h()-30)*0.50+10)); fl_line(10, round((h()-30)*0.75)+10, w()-10, round((h()-30)*0.75+10)); fl_line(10, round((h()-30)*1.00)+10, w()-10, round((h()-30)*1.00+10)); // Draw vertical axis and labels for (i = 0; i <= HISTOGRAM_BINS; i += 32) { sprintf(buffer, "%d", i); fl_color(128,128,128); position(i, -1, x, y); fl_line(round(x), 10, round(x), h()-20); fl_draw(buffer, round(x)-5, h()-5); sprintf(buffer2, "%.2f", _histogramWindow._globalHistogram.BinToVal(i)); fl_draw(buffer2, round(x)-15, h()-25); } // Compute maximum in histogram _maxHistogram = 0; for (int i = 0; i < HISTOGRAM_BINS; i++) { if (_histogramWindow._globalHistogram(i) > _maxHistogram) _maxHistogram = _histogramWindow._globalHistogram(i); } // Set up FL drawing colour and style fl_color(0,0,0); fl_line_style(FL_SOLID, 2); // Draw global histogram position(0,-1,x,y); for (int i = 1; i < HISTOGRAM_BINS; ++i) { ox = x; oy = y; position(i, -1, x, y); fl_line(round(ox), round(oy), round(x), round(y)); } // Draw histogram for each structure for (j = 0; j < SHRT_MAX+1; j++) { // Check if structure is visible if ((_v->GetSegmentTable()->GetVisibility(j)) && (_v->GetSegmentTable()->IsValid(j))) { // Set up FL drawing colour style _v->GetSegmentTable()->GetColor(j,&r,&g,&b); fl_color(r,g,b); fl_line_style(FL_SOLID, 0); // Draw histogram position(0,j,x,y); for (int i = 1; i < HISTOGRAM_BINS; ++i) { ox = x; oy = y; position(i, j, x, y); fl_line(round(ox), round(oy), round(x), round(y)); } } } } void Fl_HistogramWindow::position(int nbin, int nhistogram, double& x, double& y) { x = nbin; if (nhistogram == -1) { y = _histogramWindow._globalHistogram(nbin); } else { y = _histogramWindow._localHistogram[nhistogram](nbin); } x = (x/HISTOGRAM_BINS)*(w() - 20) + 10; y = ((_maxHistogram - y) /_maxHistogram)*(h() - 30) + 10; } <|endoftext|>
<commit_before>#include "Aircraft.hpp" #include "Math.hpp" #include <iostream> Aircraft::Aircraft(const AircraftTemplate &NewTemplate, map<string, sf::Texture> &Textures, map<string, sf::SoundBuffer> &Sounds, sf::Vector2f Pos, float Rot) : Template(NewTemplate), Land(0), State(FlyingIn), Direction(Aircraft::In) { Setup(Textures, Sounds, Pos, Rot); FlySound.play(); } Aircraft::Aircraft(const AircraftTemplate &NewTemplate, map<string, sf::Texture> &Textures, map<string, sf::SoundBuffer> &Sounds, sf::Vector2f Pos, float Rot, Runway *NewRunway, OutDirections NewOutDirection) : Template(NewTemplate), Land(NewRunway), State(TakingOff), Direction(Aircraft::Out), OutDirection(NewOutDirection) { Setup(Textures, Sounds, Pos, Rot); TakeoffSound.play(); } Aircraft::Aircraft(const AircraftTemplate &NewTemplate, map<string, sf::Texture> &Textures, map<string, sf::SoundBuffer> &Sounds, sf::Vector2f Pos, float Rot, Runway *NewRunway, States NewState, OutDirections NewOutDirection) : Template(NewTemplate), Land(NewRunway), State(NewState), Direction(Aircraft::Out), OutDirection(NewOutDirection) { Setup(Textures, Sounds, Pos, Rot); } Aircraft::Aircraft(const AircraftTemplate &NewTemplate, map<string, sf::Texture> &Textures, map<string, sf::SoundBuffer> &Sounds, sf::Vector2f Pos, float Rot, Runway *NewRunway, States NewState, sf::Vector2f NewLandPoint) : Template(NewTemplate), Land(NewRunway), State(NewState), Direction(Aircraft::In), LandPoint(NewLandPoint) { Setup(Textures, Sounds, Pos, Rot); } void Aircraft::Setup(map<string, sf::Texture> &Textures, map<string, sf::SoundBuffer> &Sounds, sf::Vector2f Pos, float Rot) { const sf::Texture &Texture = Textures[Template.Res]; if (Template.FrameSize.x >= 0 || Template.FrameSize.y >= 0) { Shape = AnimSprite(Texture, Template.FrameSize, Template.FrameRate); Shape.setOrigin(Template.FrameSize.x / 2.f, Template.FrameSize.y / 2.f); } else { Shape = AnimSprite(Texture, sf::Vector2i(Texture.getSize()), 0.f); Shape.setOrigin(sf::Vector2f(Texture.getSize()) / 2.f); } Shape.setPosition(Pos); Shape.setRotation(Rot); TakeoffSound.setBuffer(Sounds[Template.TakeoffRes]); TakeoffSound.setAttenuation(0.01f); FlySound.setBuffer(Sounds[Template.FlyRes]); FlySound.setLoop(true); FlySound.setAttenuation(0.01f); LandingSound.setBuffer(Sounds[Template.LandingRes]); LandingSound.setAttenuation(0.01f); Radius = Template.Radius; Speed = Template.Speed; Turn = Template.Turn; Time = 0.f; } const AircraftTemplate& Aircraft::GetTemplate() const { return Template; } sf::Vector2f Aircraft::GetPos() const { return Shape.getPosition(); } void Aircraft::SetPos(const sf::Vector2f &NewPos) { Shape.setPosition(NewPos); } float Aircraft::GetAngle() const { return Shape.getRotation(); } void Aircraft::SetAngle(const float &NewAngle) { Shape.setRotation(NewAngle); } Runway* const Aircraft::GetLand() const { return Land; } float Aircraft::GetRadius() const { return Radius; } float Aircraft::GetTime() const { return Time; } Path& Aircraft::GetPath() { return P; } bool Aircraft::OnMe(sf::Vector2f Pos) { const sf::Vector2f &Me = Shape.getPosition(); return InRange(Me, Pos, Radius); } bool Aircraft::Pathable() { return !OnRunway() && State != FlyingOut; } bool Aircraft::OnRunway() const { return State == Landing || State == TakingOff; } Aircraft::States Aircraft::GetState() { return State; } Aircraft::Directions Aircraft::GetDirection() { return Direction; } Aircraft::OutDirections Aircraft::GetOutDirection() { return OutDirection; } sf::Vector2f Aircraft::GetLandPoint() { return LandPoint; } bool Aircraft::Colliding(const Aircraft &Other) const { const sf::Vector2f &Me = Shape.getPosition(); const sf::Vector2f &Pos = Other.Shape.getPosition(); return OnRunway() == Other.OnRunway() && InRange(Me, Pos, (Radius + Other.Radius) / 1.3f); } bool Aircraft::Colliding(const Explosion &Exp) const { const sf::Vector2f &Me = Shape.getPosition(); const sf::Vector2f &Pos = Exp.Shape.getPosition(); return InRange(Me, Pos, (Radius + Exp.Radius) / 2.5f); } void Aircraft::SetRunway(Runway *NewLand) { Land = NewLand; } void Aircraft::Pause(bool Status) { if (Status) { TakeoffSound.pause(); FlySound.pause(); LandingSound.pause(); } else { if (TakeoffSound.getStatus() == sf::Sound::Paused) { TakeoffSound.play(); } if (FlySound.getStatus() == sf::Sound::Paused) { FlySound.play(); } if (LandingSound.getStatus() == sf::Sound::Paused) { LandingSound.play(); } } } bool Aircraft::Step(float FT, sf::Vector2f Wind) { bool Die = false; Time += FT; const sf::Vector2f &Me = Shape.getPosition(); TakeoffSound.setPosition(Me.x, Me.y, 0.f); FlySound.setPosition(Me.x, Me.y, 0.f); LandingSound.setPosition(Me.x, Me.y, 0.f); Shape.update(FT); float Turning = 0.f; switch (State) { case FlyingIn: { sf::Vector2f To(400.f, 300.f); Shape.setRotation(Angle(Me - To)); if (P.NumPoints() > 0) { State = FlyingPath; } else if (Me.x > 100 && Me.x < 700 && Me.y > 100 && Me.y < 500) { State = FlyingFree; Turning = 0.2f; } break; } case FlyingOut: { sf::Vector2f From(400.f, 300.f); Shape.rotate(AngleDiff(Shape.getRotation(), Angle(From - Me)) * FT); if (Me.x < -Radius || Me.x > (800 + Radius) || Me.y < -Radius || Me.y > (600 + Radius)) { Die = true; } break; } case FlyingFree: { float Angle = AngleFix(Shape.getRotation()), AddAngle; if ((Me.x < 100 && Angle > 180) || (Me.x > 700 && Angle < 180) || (Me.y < 100 && (Angle > 90 && Angle < 270)) || (Me.y > 500 && (Angle > 270 || Angle < 90))) { AddAngle = Turn; Turning = Turn / 10; } else if ((Me.x < 100 && Angle <= 180) || (Me.x > 700 && Angle >= 180) || (Me.y < 100 && (Angle <= 90 || Angle >= 270)) || (Me.y > 500 && (Angle <= 270 && Angle >= 90))) { AddAngle = -Turn; Turning = -Turn / 10; } else { AddAngle = Turning; } Angle += AddAngle; Shape.setRotation(AngleFix(Angle)); if (P.NumPoints() > 0) { State = FlyingPath; } else if (Direction == Out && ((OutDirection == OutUp && Me.y < 50) || (OutDirection == OutDown && Me.y > 550) || (OutDirection == OutLeft && Me.x < 50) || (OutDirection == OutRight && Me.x > 750))) { State = FlyingOut; } break; } case FlyingPath: { const sf::Vector2f To = P[0]; // might crash if (InRange(Me, To, 5)) P.RemovePoint(0); float Target = Angle(Me - To); Shape.setRotation(Target); if (Land && P.NumPoints() == 0 && /*Land->OnMe(Me) &&*/ P.Highlight /*abs(AngleDiff(GetAngle(), Land->GetAngle())) <= Land->GetTemplate().LandAngle*/) { FlySound.stop(); LandingSound.play(); State = Landing; LandPoint = Me; } else if (P.NumPoints() == 0) { State = FlyingFree; } break; } case Landing: { sf::Vector2f Runway = Land->GetPos() + PolarToRect(sf::Vector2f(Land->GetLength() * 1.5f, Land->GetAngle())); float Dist = Distance(Me, LandPoint); Speed = Map(Dist, 0.f, Land->GetLength() * 1.1f, Template.Speed, 0.f); if (Land->GetTemplate().Directional) { Shape.rotate(AngleDiff(Shape.getRotation(), Angle(Me - Runway)) * 3 * FT); } float Scale = Map2(Dist, 0.f, Land->GetLength() * 1.1f, 1.f, 0.65f); Shape.setScale(Scale, Scale); Radius = Template.Radius * Scale; if (Dist > Land->GetLength()) { Die = true; } break; } case TakingOff: { sf::Vector2f Runway = Land->GetPos() + PolarToRect(sf::Vector2f(Land->GetLength() * 1.5f, Land->GetAngle())); float Dist = Distance(Me, Land->GetPos()); Speed = Map(Dist, 0.f, Land->GetLength() * 1.1f, 10.f, Template.Speed); if (Land->GetTemplate().Directional) { Shape.rotate(AngleDiff(Shape.getRotation(), Angle(Me - Runway)) * 3 * FT); } float Scale = Map2(Dist, 0.f, Land->GetLength() * 1.1f, 0.65f, 1.f); Shape.setScale(Scale, Scale); Radius = Template.Radius * Scale; if (Dist > Land->GetLength()) { FlySound.play(); State = FlyingFree; Land = 0; } break; } } Shape.move(PolarToRect(sf::Vector2f(Speed, Shape.getRotation())) * FT); Shape.move(Wind * FT * Magnitude(Shape.getScale()) / sqrt(2.f)); return Die; } void Aircraft::Draw(sf::RenderWindow& App) { Shape.setColor(sf::Color::White); App.draw(Shape); } void Aircraft::DrawShadow(sf::RenderWindow &App) { Shape.setColor(sf::Color(0, 0, 0, 127)); float Scale = Map(Speed / Template.Speed, 0.f, 1.f, 1.f, 0.9f); sf::Transform Transform; Transform.scale(sf::Vector2f(Scale, Scale), sf::Vector2f(App.getSize().x / 2, App.getSize().y * 0.8f)); App.draw(Shape, Transform); } <commit_msg>Only fly out when explicitly pathed to<commit_after>#include "Aircraft.hpp" #include "Math.hpp" #include <iostream> Aircraft::Aircraft(const AircraftTemplate &NewTemplate, map<string, sf::Texture> &Textures, map<string, sf::SoundBuffer> &Sounds, sf::Vector2f Pos, float Rot) : Template(NewTemplate), Land(0), State(FlyingIn), Direction(Aircraft::In) { Setup(Textures, Sounds, Pos, Rot); FlySound.play(); } Aircraft::Aircraft(const AircraftTemplate &NewTemplate, map<string, sf::Texture> &Textures, map<string, sf::SoundBuffer> &Sounds, sf::Vector2f Pos, float Rot, Runway *NewRunway, OutDirections NewOutDirection) : Template(NewTemplate), Land(NewRunway), State(TakingOff), Direction(Aircraft::Out), OutDirection(NewOutDirection) { Setup(Textures, Sounds, Pos, Rot); TakeoffSound.play(); } Aircraft::Aircraft(const AircraftTemplate &NewTemplate, map<string, sf::Texture> &Textures, map<string, sf::SoundBuffer> &Sounds, sf::Vector2f Pos, float Rot, Runway *NewRunway, States NewState, OutDirections NewOutDirection) : Template(NewTemplate), Land(NewRunway), State(NewState), Direction(Aircraft::Out), OutDirection(NewOutDirection) { Setup(Textures, Sounds, Pos, Rot); } Aircraft::Aircraft(const AircraftTemplate &NewTemplate, map<string, sf::Texture> &Textures, map<string, sf::SoundBuffer> &Sounds, sf::Vector2f Pos, float Rot, Runway *NewRunway, States NewState, sf::Vector2f NewLandPoint) : Template(NewTemplate), Land(NewRunway), State(NewState), Direction(Aircraft::In), LandPoint(NewLandPoint) { Setup(Textures, Sounds, Pos, Rot); } void Aircraft::Setup(map<string, sf::Texture> &Textures, map<string, sf::SoundBuffer> &Sounds, sf::Vector2f Pos, float Rot) { const sf::Texture &Texture = Textures[Template.Res]; if (Template.FrameSize.x >= 0 || Template.FrameSize.y >= 0) { Shape = AnimSprite(Texture, Template.FrameSize, Template.FrameRate); Shape.setOrigin(Template.FrameSize.x / 2.f, Template.FrameSize.y / 2.f); } else { Shape = AnimSprite(Texture, sf::Vector2i(Texture.getSize()), 0.f); Shape.setOrigin(sf::Vector2f(Texture.getSize()) / 2.f); } Shape.setPosition(Pos); Shape.setRotation(Rot); TakeoffSound.setBuffer(Sounds[Template.TakeoffRes]); TakeoffSound.setAttenuation(0.01f); FlySound.setBuffer(Sounds[Template.FlyRes]); FlySound.setLoop(true); FlySound.setAttenuation(0.01f); LandingSound.setBuffer(Sounds[Template.LandingRes]); LandingSound.setAttenuation(0.01f); Radius = Template.Radius; Speed = Template.Speed; Turn = Template.Turn; Time = 0.f; } const AircraftTemplate& Aircraft::GetTemplate() const { return Template; } sf::Vector2f Aircraft::GetPos() const { return Shape.getPosition(); } void Aircraft::SetPos(const sf::Vector2f &NewPos) { Shape.setPosition(NewPos); } float Aircraft::GetAngle() const { return Shape.getRotation(); } void Aircraft::SetAngle(const float &NewAngle) { Shape.setRotation(NewAngle); } Runway* const Aircraft::GetLand() const { return Land; } float Aircraft::GetRadius() const { return Radius; } float Aircraft::GetTime() const { return Time; } Path& Aircraft::GetPath() { return P; } bool Aircraft::OnMe(sf::Vector2f Pos) { const sf::Vector2f &Me = Shape.getPosition(); return InRange(Me, Pos, Radius); } bool Aircraft::Pathable() { return !OnRunway() && State != FlyingOut; } bool Aircraft::OnRunway() const { return State == Landing || State == TakingOff; } Aircraft::States Aircraft::GetState() { return State; } Aircraft::Directions Aircraft::GetDirection() { return Direction; } Aircraft::OutDirections Aircraft::GetOutDirection() { return OutDirection; } sf::Vector2f Aircraft::GetLandPoint() { return LandPoint; } bool Aircraft::Colliding(const Aircraft &Other) const { const sf::Vector2f &Me = Shape.getPosition(); const sf::Vector2f &Pos = Other.Shape.getPosition(); return OnRunway() == Other.OnRunway() && InRange(Me, Pos, (Radius + Other.Radius) / 1.3f); } bool Aircraft::Colliding(const Explosion &Exp) const { const sf::Vector2f &Me = Shape.getPosition(); const sf::Vector2f &Pos = Exp.Shape.getPosition(); return InRange(Me, Pos, (Radius + Exp.Radius) / 2.5f); } void Aircraft::SetRunway(Runway *NewLand) { Land = NewLand; } void Aircraft::Pause(bool Status) { if (Status) { TakeoffSound.pause(); FlySound.pause(); LandingSound.pause(); } else { if (TakeoffSound.getStatus() == sf::Sound::Paused) { TakeoffSound.play(); } if (FlySound.getStatus() == sf::Sound::Paused) { FlySound.play(); } if (LandingSound.getStatus() == sf::Sound::Paused) { LandingSound.play(); } } } bool Aircraft::Step(float FT, sf::Vector2f Wind) { bool Die = false; Time += FT; const sf::Vector2f &Me = Shape.getPosition(); TakeoffSound.setPosition(Me.x, Me.y, 0.f); FlySound.setPosition(Me.x, Me.y, 0.f); LandingSound.setPosition(Me.x, Me.y, 0.f); Shape.update(FT); float Turning = 0.f; switch (State) { case FlyingIn: { sf::Vector2f To(400.f, 300.f); Shape.setRotation(Angle(Me - To)); if (P.NumPoints() > 0) { State = FlyingPath; } else if (Me.x > 100 && Me.x < 700 && Me.y > 100 && Me.y < 500) { State = FlyingFree; Turning = 0.2f; } break; } case FlyingOut: { sf::Vector2f From(400.f, 300.f); Shape.rotate(AngleDiff(Shape.getRotation(), Angle(From - Me)) * FT); if (Me.x < -Radius || Me.x > (800 + Radius) || Me.y < -Radius || Me.y > (600 + Radius)) { Die = true; } break; } case FlyingFree: { float Angle = AngleFix(Shape.getRotation()), AddAngle; if ((Me.x < 100 && Angle > 180) || (Me.x > 700 && Angle < 180) || (Me.y < 100 && (Angle > 90 && Angle < 270)) || (Me.y > 500 && (Angle > 270 || Angle < 90))) { AddAngle = Turn; Turning = Turn / 10; } else if ((Me.x < 100 && Angle <= 180) || (Me.x > 700 && Angle >= 180) || (Me.y < 100 && (Angle <= 90 || Angle >= 270)) || (Me.y > 500 && (Angle <= 270 && Angle >= 90))) { AddAngle = -Turn; Turning = -Turn / 10; } else { AddAngle = Turning; } Angle += AddAngle; Shape.setRotation(AngleFix(Angle)); if (P.NumPoints() > 0) { State = FlyingPath; } break; } case FlyingPath: { const sf::Vector2f To = P[0]; // might crash if (InRange(Me, To, 5)) P.RemovePoint(0); float Target = Angle(Me - To); Shape.setRotation(Target); if (Land && P.NumPoints() == 0 && /*Land->OnMe(Me) &&*/ P.Highlight /*abs(AngleDiff(GetAngle(), Land->GetAngle())) <= Land->GetTemplate().LandAngle*/) { FlySound.stop(); LandingSound.play(); State = Landing; LandPoint = Me; } else if (P.NumPoints() == 0) { if (Direction == Out && ((OutDirection == OutUp && To.y < 50) || (OutDirection == OutDown && To.y > 550) || (OutDirection == OutLeft && To.x < 50) || (OutDirection == OutRight && To.x > 750))) { State = FlyingOut; } else { State = FlyingFree; } } break; } case Landing: { sf::Vector2f Runway = Land->GetPos() + PolarToRect(sf::Vector2f(Land->GetLength() * 1.5f, Land->GetAngle())); float Dist = Distance(Me, LandPoint); Speed = Map(Dist, 0.f, Land->GetLength() * 1.1f, Template.Speed, 0.f); if (Land->GetTemplate().Directional) { Shape.rotate(AngleDiff(Shape.getRotation(), Angle(Me - Runway)) * 3 * FT); } float Scale = Map2(Dist, 0.f, Land->GetLength() * 1.1f, 1.f, 0.65f); Shape.setScale(Scale, Scale); Radius = Template.Radius * Scale; if (Dist > Land->GetLength()) { Die = true; } break; } case TakingOff: { sf::Vector2f Runway = Land->GetPos() + PolarToRect(sf::Vector2f(Land->GetLength() * 1.5f, Land->GetAngle())); float Dist = Distance(Me, Land->GetPos()); Speed = Map(Dist, 0.f, Land->GetLength() * 1.1f, 10.f, Template.Speed); if (Land->GetTemplate().Directional) { Shape.rotate(AngleDiff(Shape.getRotation(), Angle(Me - Runway)) * 3 * FT); } float Scale = Map2(Dist, 0.f, Land->GetLength() * 1.1f, 0.65f, 1.f); Shape.setScale(Scale, Scale); Radius = Template.Radius * Scale; if (Dist > Land->GetLength()) { FlySound.play(); State = FlyingFree; Land = 0; } break; } } Shape.move(PolarToRect(sf::Vector2f(Speed, Shape.getRotation())) * FT); Shape.move(Wind * FT * Magnitude(Shape.getScale()) / sqrt(2.f)); return Die; } void Aircraft::Draw(sf::RenderWindow& App) { Shape.setColor(sf::Color::White); App.draw(Shape); } void Aircraft::DrawShadow(sf::RenderWindow &App) { Shape.setColor(sf::Color(0, 0, 0, 127)); float Scale = Map(Speed / Template.Speed, 0.f, 1.f, 1.f, 0.9f); sf::Transform Transform; Transform.scale(sf::Vector2f(Scale, Scale), sf::Vector2f(App.getSize().x / 2, App.getSize().y * 0.8f)); App.draw(Shape, Transform); } <|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. ===================================================================*/ #include "mitkGL.h" #include "mitkGLMapper.h" mitk::GLMapper::GLMapper() { } mitk::GLMapper::~GLMapper() { } void mitk::GLMapper::MitkRender(mitk::BaseRenderer* renderer, mitk::VtkPropRenderer::RenderType /* type */) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if(!visible) return; // the if-condition ensures that Paint(renderer) is only called once, otherwise it will be called four times // it does not mean that OpenGL renders only an opaque scene if(type == mitk::VtkPropRenderer::Opaque) Paint(renderer); } bool mitk::GLMapper::IsVtkBased() const { return false; } void mitk::GLMapper::ApplyColorAndOpacityProperties(mitk::BaseRenderer* renderer, vtkActor* /*actor*/) { float rgba[4]={1.0f,1.0f,1.0f,1.0f}; // check for color prop and use it for rendering if it exists GetDataNode()->GetColor(rgba, renderer, "color"); // check for opacity prop and use it for rendering if it exists GetDataNode()->GetOpacity(rgba[3], renderer, "opacity"); glColor4fv(rgba); } <commit_msg>Fix OpenGL Rendering, uncommented variable<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. ===================================================================*/ #include "mitkGL.h" #include "mitkGLMapper.h" mitk::GLMapper::GLMapper() { } mitk::GLMapper::~GLMapper() { } void mitk::GLMapper::MitkRender(mitk::BaseRenderer* renderer, mitk::VtkPropRenderer::RenderType type ) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if(!visible) return; // the if-condition ensures that Paint(renderer) is only called once, otherwise it will be called four times // it does not mean that OpenGL renders only an opaque scene if(type == mitk::VtkPropRenderer::Opaque) Paint(renderer); } bool mitk::GLMapper::IsVtkBased() const { return false; } void mitk::GLMapper::ApplyColorAndOpacityProperties(mitk::BaseRenderer* renderer, vtkActor* /*actor*/) { float rgba[4]={1.0f,1.0f,1.0f,1.0f}; // check for color prop and use it for rendering if it exists GetDataNode()->GetColor(rgba, renderer, "color"); // check for opacity prop and use it for rendering if it exists GetDataNode()->GetOpacity(rgba[3], renderer, "opacity"); glColor4fv(rgba); } <|endoftext|>
<commit_before>#include "StdAfx.h" #include "DngDecoderSlices.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post 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 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 http://www.klauspost.com */ namespace RawSpeed { void *DecodeThread(void *_this) { DngDecoderThread* me = (DngDecoderThread*)_this; DngDecoderSlices* parent = me->parent; try { parent->decodeSlice(me); } catch (...) { parent->setError("DNGDEcodeThread: Caught exception."); } pthread_exit(NULL); return NULL; } DngDecoderSlices::DngDecoderSlices(FileMap* file, RawImage img) : mFile(file), mRaw(img) { mFixLjpeg = false; #ifdef WIN32 nThreads = pthread_num_processors_np(); #else nThreads = 2; // FIXME: Port this to unix #endif } DngDecoderSlices::~DngDecoderSlices(void) { } void DngDecoderSlices::addSlice(DngSliceElement slice) { slices.push(slice); } void DngDecoderSlices::startDecoding() { // Create threads int slicesPerThread = ((int)slices.size() + nThreads - 1) / nThreads; // decodedSlices = 0; pthread_attr_t attr; /* Initialize and set thread detached attribute */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&errMutex, NULL); for (guint i = 0; i < nThreads; i++) { DngDecoderThread* t = new DngDecoderThread(); for (int j = 0; j < slicesPerThread ; j++) { if (!slices.empty()) { t->slices.push(slices.front()); slices.pop(); } } t->parent = this; pthread_create(&t->threadid, &attr, DecodeThread, t); threads.push_back(t); } pthread_attr_destroy(&attr); void *status; for (guint i = 0; i < nThreads; i++) { pthread_join(threads[i]->threadid, &status); delete(threads[i]); } pthread_mutex_destroy(&errMutex); } void DngDecoderSlices::decodeSlice(DngDecoderThread* t) { while (!t->slices.empty()) { LJpegPlain l(mFile, mRaw); l.mDNGCompatible = mFixLjpeg; l.mUseBigtable = false; DngSliceElement e = t->slices.front(); t->slices.pop(); try { l.startDecoder(e.byteOffset, e.byteCount, e.offX, e.offY); } catch (RawDecoderException err) { setError(err.what()); } catch (IOException err) { setError("DngDecoderSlices::decodeSlice: IO error occurred."); } } } int DngDecoderSlices::size() { return (int)slices.size(); } void DngDecoderSlices::setError( const char* err ) { pthread_mutex_lock(&errMutex); errors.push_back(_strdup(err)); pthread_mutex_unlock(&errMutex); } } // namespace RawSpeed <commit_msg>Properly propagate Bigtable usage on DNG Slices.<commit_after>#include "StdAfx.h" #include "DngDecoderSlices.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post 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 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 http://www.klauspost.com */ namespace RawSpeed { void *DecodeThread(void *_this) { DngDecoderThread* me = (DngDecoderThread*)_this; DngDecoderSlices* parent = me->parent; try { parent->decodeSlice(me); } catch (...) { parent->setError("DNGDEcodeThread: Caught exception."); } pthread_exit(NULL); return NULL; } DngDecoderSlices::DngDecoderSlices(FileMap* file, RawImage img) : mFile(file), mRaw(img) { mFixLjpeg = false; #ifdef WIN32 nThreads = pthread_num_processors_np(); #else nThreads = 2; // FIXME: Port this to unix #endif } DngDecoderSlices::~DngDecoderSlices(void) { } void DngDecoderSlices::addSlice(DngSliceElement slice) { slices.push(slice); } void DngDecoderSlices::startDecoding() { // Create threads int slicesPerThread = ((int)slices.size() + nThreads - 1) / nThreads; // decodedSlices = 0; pthread_attr_t attr; /* Initialize and set thread detached attribute */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&errMutex, NULL); for (guint i = 0; i < nThreads; i++) { DngDecoderThread* t = new DngDecoderThread(); for (int j = 0; j < slicesPerThread ; j++) { if (!slices.empty()) { t->slices.push(slices.front()); slices.pop(); } } t->parent = this; pthread_create(&t->threadid, &attr, DecodeThread, t); threads.push_back(t); } pthread_attr_destroy(&attr); void *status; for (guint i = 0; i < nThreads; i++) { pthread_join(threads[i]->threadid, &status); delete(threads[i]); } pthread_mutex_destroy(&errMutex); } void DngDecoderSlices::decodeSlice(DngDecoderThread* t) { while (!t->slices.empty()) { LJpegPlain l(mFile, mRaw); l.mDNGCompatible = mFixLjpeg; DngSliceElement e = t->slices.front(); l.mUseBigtable = e.mUseBigtable; t->slices.pop(); try { l.startDecoder(e.byteOffset, e.byteCount, e.offX, e.offY); } catch (RawDecoderException err) { setError(err.what()); } catch (IOException err) { setError("DngDecoderSlices::decodeSlice: IO error occurred."); } } } int DngDecoderSlices::size() { return (int)slices.size(); } void DngDecoderSlices::setError( const char* err ) { pthread_mutex_lock(&errMutex); errors.push_back(_strdup(err)); pthread_mutex_unlock(&errMutex); } } // namespace RawSpeed <|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 "otbAtmosphericRadiativeTerms.h" namespace otb { /*********************************** AtmosphericRadiativeTermsSingleChannel***********************************************/ /**PrintSelf method */ void AtmosphericRadiativeTermsSingleChannel ::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os,indent); os << indent << "Intrinsic Atmospheric Reflectance: " << m_IntrinsicAtmosphericReflectance << std::endl; os << indent << "Shperical Albedo of the Atmosphere: " << m_SphericalAlbedo << std::endl; os << indent << "Total Gaseous Transmission: " << m_TotalGaseousTransmission << std::endl; os << indent << "Downward Transmittance of the Atmospher: " << m_DownwardTransmittance << std::endl; os << indent << "Upward Transmittance of the Atmospher: " << m_UpwardTransmittance << std::endl; } /*********************************** AtmosphericRadiativeTerms **********************************************************/ /**CONSTRUCTOR. */ AtmosphericRadiativeTerms ::AtmosphericRadiativeTerms() { m_Values.clear(); m_IsInitialized = false; } void AtmosphericRadiativeTerms ::ValuesInitialization(unsigned int nbChannel) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); for (unsigned int j=0; j<nbChannel; j++) { m_Values.push_back(temp); } m_IsInitialized = true; } /** SET ACCESSORS WITH VECTORS. */ void AtmosphericRadiativeTerms ::SetIntrinsicAtmosphericReflectances(const DataVectorType & vect) { if ( !m_IsInitialized) { this->ValuesInitialization(vect.size()); } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) { m_Values[nbChannel]->SetIntrinsicAtmosphericReflectance(vect[nbChannel]); } } void AtmosphericRadiativeTerms ::SetSphericalAlbedos(const DataVectorType & vect) { if ( !m_IsInitialized) { this->ValuesInitialization(vect.size()); } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) { m_Values[nbChannel]->SetSphericalAlbedo(vect[nbChannel]); } } void AtmosphericRadiativeTerms ::SetTotalGaseousTransmissions(const DataVectorType & vect) { if ( !m_IsInitialized) { this->ValuesInitialization(vect.size()); } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) { m_Values[nbChannel]->SetTotalGaseousTransmission(vect[nbChannel]); } } void AtmosphericRadiativeTerms ::SetDownwardTransmittances(const DataVectorType & vect) { if ( !m_IsInitialized) { this->ValuesInitialization(vect.size()); } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) { m_Values[nbChannel]->SetDownwardTransmittance(vect[nbChannel]); } } void AtmosphericRadiativeTerms ::SetUpwardTransmittances(const DataVectorType & vect) { if ( !m_IsInitialized) { this->ValuesInitialization(vect.size()); } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) { m_Values[nbChannel]->SetUpwardTransmittance(vect[nbChannel]); } } /** SET ACCESSORS WITH INDEX. */ void AtmosphericRadiativeTerms ::SetValueByIndex(unsigned int id, const ValueType & val) { if ( m_IsInitialized ) { if ( m_Values.size()<id+1 ) { for(unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } } m_Values[id] = val; } else { itkExceptionMacro(<< "Can't insert value before iniatilizing vector value..."<<std::endl); } } void AtmosphericRadiativeTerms ::SetIntrinsicAtmosphericReflectances(unsigned int id, const double & val) { if ( m_Values.size()<id+1 ) { for(unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } } m_Values[id]->SetIntrinsicAtmosphericReflectance(val); } void AtmosphericRadiativeTerms ::SetSphericalAlbedos(unsigned int id, const double & val) { if ( m_Values.size()<id+1 ) { for(unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } } m_Values[id]->SetSphericalAlbedo(val); } void AtmosphericRadiativeTerms ::SetTotalGaseousTransmissions(unsigned int id, const double & val) { if ( m_Values.size()<id+1 ) { for(unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } } m_Values[id]->SetTotalGaseousTransmission(val); } void AtmosphericRadiativeTerms ::SetDownwardTransmittances(unsigned int id, const double & val ) { if ( m_Values.size()<id+1 ) { for(unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } } m_Values[id]->SetDownwardTransmittance(val); } void AtmosphericRadiativeTerms ::SetUpwardTransmittances(unsigned int id, const double & val ) { if ( m_Values.size()<id+1 ) { for(unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } } m_Values[id]->SetUpwardTransmittance(val); } /** GET ACCESSORS WITH VECTORS. */ AtmosphericRadiativeTerms::DataVectorType AtmosphericRadiativeTerms ::GetIntrinsicAtmosphericReflectances() { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) { vect[nbChannel] = m_Values[nbChannel]->GetIntrinsicAtmosphericReflectance(); } return vect; } AtmosphericRadiativeTerms::DataVectorType AtmosphericRadiativeTerms ::GetSphericalAlbedos() { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) { vect[nbChannel] = m_Values[nbChannel]->GetIntrinsicAtmosphericReflectance(); } return vect; } AtmosphericRadiativeTerms::DataVectorType AtmosphericRadiativeTerms ::GetTotalGaseousTransmissions() { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) { vect[nbChannel] = m_Values[nbChannel]->GetIntrinsicAtmosphericReflectance(); } return vect; } AtmosphericRadiativeTerms::DataVectorType AtmosphericRadiativeTerms ::GetDownwardTransmittances() { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) { vect[nbChannel] = m_Values[nbChannel]->GetIntrinsicAtmosphericReflectance(); } return vect; } AtmosphericRadiativeTerms::DataVectorType AtmosphericRadiativeTerms ::GetUpwardTransmittances() { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) { vect[nbChannel] = m_Values[nbChannel]->GetIntrinsicAtmosphericReflectance(); } return vect; } /** GET ACCESSORS WITH INDEX. */ double AtmosphericRadiativeTerms ::GetIntrinsicAtmosphericReflectances(unsigned int id) { return m_Values[id]->GetIntrinsicAtmosphericReflectance(); } double AtmosphericRadiativeTerms ::GetSphericalAlbedos(unsigned int id) { return m_Values[id]->GetSphericalAlbedo(); } double AtmosphericRadiativeTerms ::GetTotalGaseousTransmissions(unsigned int id) { return m_Values[id]->GetTotalGaseousTransmission(); } double AtmosphericRadiativeTerms ::GetDownwardTransmittances(unsigned int id) { return m_Values[id]->GetDownwardTransmittance(); } double AtmosphericRadiativeTerms ::GetUpwardTransmittances(unsigned int id) { return m_Values[id]->GetUpwardTransmittance(); } const AtmosphericRadiativeTerms::ValueType AtmosphericRadiativeTerms ::GetValueByIndex(unsigned int id) const { return m_Values[id]; } /**PrintSelf method */ void AtmosphericRadiativeTerms ::PrintSelf(std::ostream& os, itk::Indent indent) const { for (unsigned int i=0; i<m_Values.size(); i++) { os << indent << "Channel "<< i << " : "<< std::endl; //ValueType::(os,indent); } } } // end namespace otb <commit_msg>Correction de code.<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 "otbAtmosphericRadiativeTerms.h" namespace otb { /*********************************** AtmosphericRadiativeTermsSingleChannel***********************************************/ /**PrintSelf method */ void AtmosphericRadiativeTermsSingleChannel ::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os,indent); os << indent << "Intrinsic Atmospheric Reflectance: " << m_IntrinsicAtmosphericReflectance << std::endl; os << indent << "Shperical Albedo of the Atmosphere: " << m_SphericalAlbedo << std::endl; os << indent << "Total Gaseous Transmission: " << m_TotalGaseousTransmission << std::endl; os << indent << "Downward Transmittance of the Atmospher: " << m_DownwardTransmittance << std::endl; os << indent << "Upward Transmittance of the Atmospher: " << m_UpwardTransmittance << std::endl; } /*********************************** AtmosphericRadiativeTerms **********************************************************/ /**CONSTRUCTOR. */ AtmosphericRadiativeTerms ::AtmosphericRadiativeTerms() { m_Values.clear(); m_IsInitialized = false; } void AtmosphericRadiativeTerms ::ValuesInitialization(unsigned int nbChannel) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); for (unsigned int j=0; j<nbChannel; j++) { m_Values.push_back(temp); } m_IsInitialized = true; } /** SET ACCESSORS WITH VECTORS. */ void AtmosphericRadiativeTerms ::SetIntrinsicAtmosphericReflectances(const DataVectorType & vect) { if ( !m_IsInitialized) { this->ValuesInitialization(vect.size()); } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) { m_Values[nbChannel]->SetIntrinsicAtmosphericReflectance(vect[nbChannel]); } } void AtmosphericRadiativeTerms ::SetSphericalAlbedos(const DataVectorType & vect) { if ( !m_IsInitialized) { this->ValuesInitialization(vect.size()); } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) { m_Values[nbChannel]->SetSphericalAlbedo(vect[nbChannel]); } } void AtmosphericRadiativeTerms ::SetTotalGaseousTransmissions(const DataVectorType & vect) { if ( !m_IsInitialized) { this->ValuesInitialization(vect.size()); } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) { m_Values[nbChannel]->SetTotalGaseousTransmission(vect[nbChannel]); } } void AtmosphericRadiativeTerms ::SetDownwardTransmittances(const DataVectorType & vect) { if ( !m_IsInitialized) { this->ValuesInitialization(vect.size()); } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) { m_Values[nbChannel]->SetDownwardTransmittance(vect[nbChannel]); } } void AtmosphericRadiativeTerms ::SetUpwardTransmittances(const DataVectorType & vect) { if ( !m_IsInitialized) { this->ValuesInitialization(vect.size()); } for (unsigned int nbChannel=0; nbChannel<vect.size(); nbChannel++) { m_Values[nbChannel]->SetUpwardTransmittance(vect[nbChannel]); } } /** SET ACCESSORS WITH INDEX. */ void AtmosphericRadiativeTerms ::SetValueByIndex(unsigned int id, const ValueType & val) { if ( m_IsInitialized ) { if ( m_Values.size()<id+1 ) { for(unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } } m_Values[id] = val; } else { itkExceptionMacro(<< "Can't insert value before iniatilizing vector value..."<<std::endl); } } void AtmosphericRadiativeTerms ::SetIntrinsicAtmosphericReflectances(unsigned int id, const double & val) { if ( m_Values.size()<id+1 ) { for(unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } } m_Values[id]->SetIntrinsicAtmosphericReflectance(val); } void AtmosphericRadiativeTerms ::SetSphericalAlbedos(unsigned int id, const double & val) { if ( m_Values.size()<id+1 ) { for(unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } } m_Values[id]->SetSphericalAlbedo(val); } void AtmosphericRadiativeTerms ::SetTotalGaseousTransmissions(unsigned int id, const double & val) { if ( m_Values.size()<id+1 ) { for(unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } } m_Values[id]->SetTotalGaseousTransmission(val); } void AtmosphericRadiativeTerms ::SetDownwardTransmittances(unsigned int id, const double & val ) { if ( m_Values.size()<id+1 ) { for(unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } } m_Values[id]->SetDownwardTransmittance(val); } void AtmosphericRadiativeTerms ::SetUpwardTransmittances(unsigned int id, const double & val ) { if ( m_Values.size()<id+1 ) { for(unsigned int j=0; j<(id+1-m_Values.size());j++) { ValueType temp = AtmosphericRadiativeTermsSingleChannel::New(); m_Values.push_back(temp); } } m_Values[id]->SetUpwardTransmittance(val); } /** GET ACCESSORS WITH VECTORS. */ AtmosphericRadiativeTerms::DataVectorType AtmosphericRadiativeTerms ::GetIntrinsicAtmosphericReflectances() { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) { vect[nbChannel] = m_Values[nbChannel]->GetIntrinsicAtmosphericReflectance(); } return vect; } AtmosphericRadiativeTerms::DataVectorType AtmosphericRadiativeTerms ::GetSphericalAlbedos() { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) { vect[nbChannel] = m_Values[nbChannel]->GetSphericalAlbedo(); } return vect; } AtmosphericRadiativeTerms::DataVectorType AtmosphericRadiativeTerms ::GetTotalGaseousTransmissions() { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) { vect[nbChannel] = m_Values[nbChannel]->GetTotalGaseousTransmission(); } return vect; } AtmosphericRadiativeTerms::DataVectorType AtmosphericRadiativeTerms ::GetDownwardTransmittances() { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) { vect[nbChannel] = m_Values[nbChannel]->GetDownwardTransmittance(); } return vect; } AtmosphericRadiativeTerms::DataVectorType AtmosphericRadiativeTerms ::GetUpwardTransmittances() { DataVectorType vect(m_Values.size(), 0); for (unsigned int nbChannel=0; nbChannel<m_Values.size(); nbChannel++) { vect[nbChannel] = m_Values[nbChannel]->GetUpwardTransmittance(); } return vect; } /** GET ACCESSORS WITH INDEX. */ double AtmosphericRadiativeTerms ::GetIntrinsicAtmosphericReflectances(unsigned int id) { return m_Values[id]->GetIntrinsicAtmosphericReflectance(); } double AtmosphericRadiativeTerms ::GetSphericalAlbedos(unsigned int id) { return m_Values[id]->GetSphericalAlbedo(); } double AtmosphericRadiativeTerms ::GetTotalGaseousTransmissions(unsigned int id) { return m_Values[id]->GetTotalGaseousTransmission(); } double AtmosphericRadiativeTerms ::GetDownwardTransmittances(unsigned int id) { return m_Values[id]->GetDownwardTransmittance(); } double AtmosphericRadiativeTerms ::GetUpwardTransmittances(unsigned int id) { return m_Values[id]->GetUpwardTransmittance(); } const AtmosphericRadiativeTerms::ValueType AtmosphericRadiativeTerms ::GetValueByIndex(unsigned int id) const { return m_Values[id]; } /**PrintSelf method */ void AtmosphericRadiativeTerms ::PrintSelf(std::ostream& os, itk::Indent indent) const { for (unsigned int i=0; i<m_Values.size(); i++) { os << indent << "Channel "<< i << " : "<< std::endl; //ValueType::(os,indent); } } } // end namespace otb <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkGeometry2DDataVtkMapper3D.h" #include "mitkPlaneGeometry.h" #include "mitkDataTree.h" #include "mitkImageMapper2D.h" #include "mitkSurface.h" #include "mitkGeometry2DDataToSurfaceFilter.h" #include "vtkActor.h" #include "vtkProperty.h" #include "vtkTexture.h" #include "vtkPlaneSource.h" #include "vtkPolyDataMapper.h" #include "vtkLookupTable.h" //#include "vtkImageMapToWindowLevelColors"; #include "mitkColorProperty.h" #include "mitkProperties.h" #include "mitkLookupTableProperty.h" #include "mitkLevelWindowProperty.h" #include "mitkSmartPointerProperty.h" #include "mitkWeakPointerProperty.h" #include <vtkActor.h> #include <vtkImageData.h> #include "pic2vtk.h" //##ModelId=3E691E09038E mitk::Geometry2DDataVtkMapper3D::Geometry2DDataVtkMapper3D() : m_DataTreeIterator(NULL), m_LastTextureUpdateTime(0) { m_VtkPlaneSource = vtkPlaneSource::New(); m_VtkPolyDataMapper = vtkPolyDataMapper::New(); m_VtkPolyDataMapper->ImmediateModeRenderingOn(); m_Actor = vtkActor::New(); m_Actor->SetMapper(m_VtkPolyDataMapper); m_Prop3D = m_Actor; m_Prop3D->Register(NULL); m_VtkLookupTable = vtkLookupTable::New(); m_VtkLookupTable->SetTableRange (-1024, 4096); m_VtkLookupTable->SetSaturationRange (0, 0); m_VtkLookupTable->SetHueRange (0, 0); m_VtkLookupTable->SetValueRange (0, 1); m_VtkLookupTable->Build (); m_VtkLookupTableDefault = m_VtkLookupTable; m_VtkTexture = vtkTexture::New(); m_VtkTexture->InterpolateOn(); m_VtkTexture->SetLookupTable(m_VtkLookupTable); m_VtkTexture->MapColorScalarsThroughLookupTableOn(); } //##ModelId=3E691E090394 mitk::Geometry2DDataVtkMapper3D::~Geometry2DDataVtkMapper3D() { m_VtkPlaneSource->Delete(); m_VtkPolyDataMapper->Delete(); m_Actor->Delete(); m_VtkLookupTable->Delete(); m_VtkTexture->Delete(); } //##ModelId=3E691E090380 const mitk::Geometry2DData *mitk::Geometry2DDataVtkMapper3D::GetInput() { return static_cast<const mitk::Geometry2DData * > ( GetData() ); } //##ModelId=3E6E874F0007 void mitk::Geometry2DDataVtkMapper3D::SetDataIteratorForTexture(const mitk::DataTreeIteratorBase* iterator) { if(m_DataTreeIterator != iterator) { m_DataTreeIterator = iterator; Modified(); } } //##ModelId=3EF19F850151 void mitk::Geometry2DDataVtkMapper3D::GenerateData(mitk::BaseRenderer* renderer) { if(IsVisible(renderer)==false) { m_Actor->VisibilityOff(); return; } m_Actor->VisibilityOn(); mitk::Geometry2DData::Pointer input = const_cast<mitk::Geometry2DData*>(this->GetInput()); if(input.IsNotNull()) { mitk::Geometry2DDataToSurfaceFilter::Pointer surfaceCreator; mitk::SmartPointerProperty::Pointer surfacecreatorprop; surfacecreatorprop=dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetProperty("surfacegeometry", renderer).GetPointer()); if( (surfacecreatorprop.IsNull()) || (surfacecreatorprop->GetSmartPointer().IsNull()) || ((surfaceCreator=dynamic_cast<mitk::Geometry2DDataToSurfaceFilter*>(surfacecreatorprop->GetSmartPointer().GetPointer())).IsNull()) ) { surfaceCreator = mitk::Geometry2DDataToSurfaceFilter::New(); surfacecreatorprop=new mitk::SmartPointerProperty(surfaceCreator); GetDataTreeNode()->SetProperty("surfacegeometry", surfacecreatorprop); } surfaceCreator->SetInput(input); int res; if(GetDataTreeNode()->GetIntProperty("xresolution", res, renderer)) surfaceCreator->SetXResolution(res); if(GetDataTreeNode()->GetIntProperty("yresolution", res, renderer)) surfaceCreator->SetYResolution(res); surfaceCreator->Update(); //@FIXME ohne das crash m_VtkPolyDataMapper->SetInput(surfaceCreator->GetOutput()->GetVtkPolyData()); bool texture=false; if(m_DataTreeIterator.IsNotNull()) { mitk::DataTreeIteratorClone it=m_DataTreeIterator.GetPointer(); while(!it->IsAtEnd()) { mitk::DataTreeNode* node=it->Get(); mitk::Mapper::Pointer mapper = node->GetMapper(1); mitk::ImageMapper2D* imagemapper = dynamic_cast<ImageMapper2D*>(mapper.GetPointer()); if((node->IsVisible(renderer)) && (imagemapper)) { mitk::WeakPointerProperty::Pointer rendererProp = dynamic_cast<mitk::WeakPointerProperty*>(GetDataTreeNode()->GetPropertyList()->GetProperty("renderer").GetPointer()); if(rendererProp.IsNotNull()) { mitk::BaseRenderer::Pointer renderer = dynamic_cast<mitk::BaseRenderer*>(rendererProp->GetWeakPointer().GetPointer()); if(renderer.IsNotNull()) { // check for LookupTable mitk::LookupTableProperty::Pointer LookupTableProb; LookupTableProb = dynamic_cast<mitk::LookupTableProperty*>(node->GetPropertyList()->GetProperty("LookupTable").GetPointer()); if (LookupTableProb.IsNotNull() ) { m_VtkLookupTable = LookupTableProb->GetLookupTable().GetVtkLookupTable(); m_VtkTexture->SetLookupTable(m_VtkLookupTable); // m_VtkTexture->Modified(); } else { m_VtkLookupTable = m_VtkLookupTableDefault; } // check for level window prop and use it for display if it exists mitk::LevelWindow levelWindow; if(node->GetLevelWindow(levelWindow, renderer)) m_VtkLookupTable->SetTableRange(levelWindow.GetMin(),levelWindow.GetMax()); //we have to do this before GenerateAllData() is called there may be //no RendererInfo for renderer yet, thus GenerateAllData won't update //the (non-existing) RendererInfo for renderer. By calling GetRendererInfo //a RendererInfo will be created for renderer (if it does not exist yet). const ImageMapper2D::RendererInfo* ri=imagemapper->GetRendererInfo(renderer); imagemapper->GenerateAllData(); if((ri!=NULL) && (m_LastTextureUpdateTime<ri->m_LastUpdateTime)) { ipPicDescriptor *p=ri->m_Pic; vtkImageData* vtkimage=Pic2vtk::convert(p); m_VtkTexture->SetInput(vtkimage); vtkimage->Delete(); vtkimage=NULL; m_Actor->SetTexture(m_VtkTexture); m_LastTextureUpdateTime=ri->m_LastUpdateTime; } texture = true; break; } } } ++it; } } if(texture==false) { m_Actor->SetTexture(NULL); } //apply properties read from the PropertyList ApplyProperties(m_Actor, renderer); } } <commit_msg>changed actors ambience to 0.5<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkGeometry2DDataVtkMapper3D.h" #include "mitkPlaneGeometry.h" #include "mitkDataTree.h" #include "mitkImageMapper2D.h" #include "mitkSurface.h" #include "mitkGeometry2DDataToSurfaceFilter.h" #include "vtkActor.h" #include "vtkProperty.h" #include "vtkTexture.h" #include "vtkPlaneSource.h" #include "vtkPolyDataMapper.h" #include "vtkLookupTable.h" //#include "vtkImageMapToWindowLevelColors"; #include "mitkColorProperty.h" #include "mitkProperties.h" #include "mitkLookupTableProperty.h" #include "mitkLevelWindowProperty.h" #include "mitkSmartPointerProperty.h" #include "mitkWeakPointerProperty.h" #include <vtkActor.h> #include <vtkImageData.h> #include "pic2vtk.h" //##ModelId=3E691E09038E mitk::Geometry2DDataVtkMapper3D::Geometry2DDataVtkMapper3D() : m_DataTreeIterator(NULL), m_LastTextureUpdateTime(0) { m_VtkPlaneSource = vtkPlaneSource::New(); m_VtkPolyDataMapper = vtkPolyDataMapper::New(); m_VtkPolyDataMapper->ImmediateModeRenderingOn(); m_Actor = vtkActor::New(); m_Actor->SetMapper(m_VtkPolyDataMapper); m_Actor->GetProperty()->SetAmbient(0.5); m_Prop3D = m_Actor; m_Prop3D->Register(NULL); m_VtkLookupTable = vtkLookupTable::New(); m_VtkLookupTable->SetTableRange (-1024, 4096); m_VtkLookupTable->SetSaturationRange (0, 0); m_VtkLookupTable->SetHueRange (0, 0); m_VtkLookupTable->SetValueRange (0, 1); m_VtkLookupTable->Build (); m_VtkLookupTableDefault = m_VtkLookupTable; m_VtkTexture = vtkTexture::New(); m_VtkTexture->InterpolateOn(); m_VtkTexture->SetLookupTable(m_VtkLookupTable); m_VtkTexture->MapColorScalarsThroughLookupTableOn(); } //##ModelId=3E691E090394 mitk::Geometry2DDataVtkMapper3D::~Geometry2DDataVtkMapper3D() { m_VtkPlaneSource->Delete(); m_VtkPolyDataMapper->Delete(); m_Actor->Delete(); m_VtkLookupTable->Delete(); m_VtkTexture->Delete(); } //##ModelId=3E691E090380 const mitk::Geometry2DData *mitk::Geometry2DDataVtkMapper3D::GetInput() { return static_cast<const mitk::Geometry2DData * > ( GetData() ); } //##ModelId=3E6E874F0007 void mitk::Geometry2DDataVtkMapper3D::SetDataIteratorForTexture(const mitk::DataTreeIteratorBase* iterator) { if(m_DataTreeIterator != iterator) { m_DataTreeIterator = iterator; Modified(); } } //##ModelId=3EF19F850151 void mitk::Geometry2DDataVtkMapper3D::GenerateData(mitk::BaseRenderer* renderer) { if(IsVisible(renderer)==false) { m_Actor->VisibilityOff(); return; } m_Actor->VisibilityOn(); mitk::Geometry2DData::Pointer input = const_cast<mitk::Geometry2DData*>(this->GetInput()); if(input.IsNotNull()) { mitk::Geometry2DDataToSurfaceFilter::Pointer surfaceCreator; mitk::SmartPointerProperty::Pointer surfacecreatorprop; surfacecreatorprop=dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetProperty("surfacegeometry", renderer).GetPointer()); if( (surfacecreatorprop.IsNull()) || (surfacecreatorprop->GetSmartPointer().IsNull()) || ((surfaceCreator=dynamic_cast<mitk::Geometry2DDataToSurfaceFilter*>(surfacecreatorprop->GetSmartPointer().GetPointer())).IsNull()) ) { surfaceCreator = mitk::Geometry2DDataToSurfaceFilter::New(); surfacecreatorprop=new mitk::SmartPointerProperty(surfaceCreator); GetDataTreeNode()->SetProperty("surfacegeometry", surfacecreatorprop); } surfaceCreator->SetInput(input); int res; if(GetDataTreeNode()->GetIntProperty("xresolution", res, renderer)) surfaceCreator->SetXResolution(res); if(GetDataTreeNode()->GetIntProperty("yresolution", res, renderer)) surfaceCreator->SetYResolution(res); surfaceCreator->Update(); //@FIXME ohne das crash m_VtkPolyDataMapper->SetInput(surfaceCreator->GetOutput()->GetVtkPolyData()); bool texture=false; if(m_DataTreeIterator.IsNotNull()) { mitk::DataTreeIteratorClone it=m_DataTreeIterator.GetPointer(); while(!it->IsAtEnd()) { mitk::DataTreeNode* node=it->Get(); mitk::Mapper::Pointer mapper = node->GetMapper(1); mitk::ImageMapper2D* imagemapper = dynamic_cast<ImageMapper2D*>(mapper.GetPointer()); if((node->IsVisible(renderer)) && (imagemapper)) { mitk::WeakPointerProperty::Pointer rendererProp = dynamic_cast<mitk::WeakPointerProperty*>(GetDataTreeNode()->GetPropertyList()->GetProperty("renderer").GetPointer()); if(rendererProp.IsNotNull()) { mitk::BaseRenderer::Pointer renderer = dynamic_cast<mitk::BaseRenderer*>(rendererProp->GetWeakPointer().GetPointer()); if(renderer.IsNotNull()) { // check for LookupTable mitk::LookupTableProperty::Pointer LookupTableProb; LookupTableProb = dynamic_cast<mitk::LookupTableProperty*>(node->GetPropertyList()->GetProperty("LookupTable").GetPointer()); if (LookupTableProb.IsNotNull() ) { m_VtkLookupTable = LookupTableProb->GetLookupTable().GetVtkLookupTable(); m_VtkTexture->SetLookupTable(m_VtkLookupTable); // m_VtkTexture->Modified(); } else { m_VtkLookupTable = m_VtkLookupTableDefault; } // check for level window prop and use it for display if it exists mitk::LevelWindow levelWindow; if(node->GetLevelWindow(levelWindow, renderer)) m_VtkLookupTable->SetTableRange(levelWindow.GetMin(),levelWindow.GetMax()); //we have to do this before GenerateAllData() is called there may be //no RendererInfo for renderer yet, thus GenerateAllData won't update //the (non-existing) RendererInfo for renderer. By calling GetRendererInfo //a RendererInfo will be created for renderer (if it does not exist yet). const ImageMapper2D::RendererInfo* ri=imagemapper->GetRendererInfo(renderer); imagemapper->GenerateAllData(); if((ri!=NULL) && (m_LastTextureUpdateTime<ri->m_LastUpdateTime)) { ipPicDescriptor *p=ri->m_Pic; vtkImageData* vtkimage=Pic2vtk::convert(p); m_VtkTexture->SetInput(vtkimage); vtkimage->Delete(); vtkimage=NULL; m_Actor->SetTexture(m_VtkTexture); m_LastTextureUpdateTime=ri->m_LastUpdateTime; } texture = true; break; } } } ++it; } } if(texture==false) { m_Actor->SetTexture(NULL); } //apply properties read from the PropertyList ApplyProperties(m_Actor, renderer); } } <|endoftext|>
<commit_before>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*- * * Quadra, an action puzzle game * Copyright (C) 1998-2000 Ludus Design * * This program 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 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 * 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 */ /* * Here's a post I made to the RZ forum (www.recognize.nu) about * making Quadra themes. Please ignore the part with the * ranting. Better yet: I'll cut it out for you :). * * This is Dada, one of the original Quadra programmers. I saw some * interrest in making Quadra themes so I'd like to clarify some stuff * and answer questions. First of all, I'd like to apologize for not * providing this information earlier. Somehow I thought people would * like to figure things out for themselves by digging thru 25000 * lines of bad C++, but I can see how that's not for everybody (there * was even somebody who had bytes and bits laughing at them? Really * sorry about that :)). Se here's a little summary: * * First of all, most (if not all) of what AngelGurl and logix have * figured out is right: the best way to make res files is with the * wadder.exe tool that can be built from any distribution of the * Quadra source code (the file format has never changed). I know it * would have been better if it had been a simple zip file, but the * wadder thing is not too hard to use either. * * One important capability (as far as themes go) that hasn't been * discovered yet is the possibility to make a patching res file. When * Quadra starts up, it reads in everything it finds from quadra.res, * but then goes on to read another quadraxyz.res file (where 'xyz' is * the Quadra version number of quadra.exe; for example, Quadra * version 1.1.5 tries to open quadra115.res), replacing like-named * resources that were found in the big quadra.res file with the ones * from the patching res. This patching res is the exact same format * as quadra.res so it can be built using wadder.exe too, but of * course it can be much smaller because it has to contain only the * resources you want to change. Besides, the patching resources * themselves don't have to be the same file size as the original * resources in quadra.res, which was needed when trying to patch the * quadra.res file itself with a hex editor (needless to say, I don't * recommend that approach; a patching res file is the best way to * make a theme pack). * * PS: The current version of Quadra only ever loads the main res file * (quadra.res) and a single patching res file (quadra115.res or * whatever the exe version number is). The reason is that the * patching feature was made to do just that: patches. We didn't think * about themes back then. However, I've just decided right this * moment that the next version will have a -patch command line option * allowing people to specify additional patching res file(s) to load * (while still loading the version-specific file if found). This * should make it much easier for most people to use a theme pack, if * somebody actually manage to produce one :). * * Ok, that was the good news. Now on to the bad news: the resources * themselves. * * As some of you have found out, Quadra is *really* picky about the * palettes found in it's many image resources. In practice, you have * to use a paint program (or image converter) that gives you direct * control over the 256-colors palette found in the png files. You * can't just scan in a background in Photoshop and save it as a 8-bit * paletted png, it won't look right at all (24-bit images are also * out of the question). Most of the palette is available to use for * the background images, but a good portion of it is used to draw the * blocks and the text in the chat window. You can customize these * colors too (and use them in the background image), but they have to * "make sense" to Quadra for you to get a correct display. Given the * proper image-editing tools with good palette control, you should be * able to make new backgrounds with customized block colors by * imitating the organization of the palettes in the default pngs that * come with the source code package (the simple and irrefutable proof * of that is that we could do it ourselves in the first place :)). * * One other piece of bad news: a lot of sound effects are re-used in * more than one scheme in various ways, so it is not possible to * fully customize all the sound effects for level 1 (for example) * without affecting the sound effects that will play on other * levels. Since most people only play multiplayer (where only one * scheme is visible) this isn't too much of an issue but I thought * I'd mention it anyway. * * Last bit of bad news: if you haven't figured it out from the * palette discussion above, it is not possible to customize the * appearance of blocks beyond their colors (the inside "fill" color * and the little shading/beveling/sunking perimeter lines). Quadra * itself does nearly everything that is possible to do over its 10 * levels as far as block customization is concerned. I know it is * limited, but that's how it is... * * Anyway, I hope that can help somebody. I'd like to see some Quadra * themes myself, if only for the sake of change :). */ #include <stdio.h> #include "stringtable.h" #include "res.h" RCSID("$Id$") char *usage = "usage: wadder <working directory> <output res> <input text>\n"; Resfile *wad; const char *basename(const char* f) { const char* p=(const char*)(f+strlen(f)); while(*p != '/' && *p != '\\' && p>=f) p--; return p+1; } void addfile(const char* fname) { Res_dos *res; char *data; printf("%s: ", fname); res = new Res_dos(fname, RES_TRY); data = new char[res->size()]; res->read(data, res->size()); wad->add(basename(fname), res->size(), data); delete res; delete data; printf("done\n"); } int main(int ARGC, char **ARGV, char **ENV) { Res_dos *res; Byte* data; if(ARGC < 4) { fprintf(stderr, "%s: %s", ARGV[0], usage); exit(1); } char wad_file[256]; sprintf(wad_file, "%s%s", ARGV[1], ARGV[2]); wad = new Resfile(wad_file, false); wad->clear(); char res_file[256]; sprintf(res_file, "%s%s", ARGV[1], ARGV[3]); res = new Res_dos(res_file, RES_READ); data = new Byte[res->size()+1]; memcpy(data, res->buf(), res->size()); Stringtable st(data, res->size()); for(int i=0; i<st.size(); i++) { char temp[256]; sprintf(temp, "%s%s", ARGV[1], st.get(i)); addfile(temp); } delete data; delete res; wad->freeze(); delete wad; return 0; } void start_game(void) { } <commit_msg>Make our definition of basename() conditional to the lack of it.<commit_after>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*- * * Quadra, an action puzzle game * Copyright (C) 1998-2000 Ludus Design * * This program 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 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 * 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 */ /* * Here's a post I made to the RZ forum (www.recognize.nu) about * making Quadra themes. Please ignore the part with the * ranting. Better yet: I'll cut it out for you :). * * This is Dada, one of the original Quadra programmers. I saw some * interrest in making Quadra themes so I'd like to clarify some stuff * and answer questions. First of all, I'd like to apologize for not * providing this information earlier. Somehow I thought people would * like to figure things out for themselves by digging thru 25000 * lines of bad C++, but I can see how that's not for everybody (there * was even somebody who had bytes and bits laughing at them? Really * sorry about that :)). Se here's a little summary: * * First of all, most (if not all) of what AngelGurl and logix have * figured out is right: the best way to make res files is with the * wadder.exe tool that can be built from any distribution of the * Quadra source code (the file format has never changed). I know it * would have been better if it had been a simple zip file, but the * wadder thing is not too hard to use either. * * One important capability (as far as themes go) that hasn't been * discovered yet is the possibility to make a patching res file. When * Quadra starts up, it reads in everything it finds from quadra.res, * but then goes on to read another quadraxyz.res file (where 'xyz' is * the Quadra version number of quadra.exe; for example, Quadra * version 1.1.5 tries to open quadra115.res), replacing like-named * resources that were found in the big quadra.res file with the ones * from the patching res. This patching res is the exact same format * as quadra.res so it can be built using wadder.exe too, but of * course it can be much smaller because it has to contain only the * resources you want to change. Besides, the patching resources * themselves don't have to be the same file size as the original * resources in quadra.res, which was needed when trying to patch the * quadra.res file itself with a hex editor (needless to say, I don't * recommend that approach; a patching res file is the best way to * make a theme pack). * * PS: The current version of Quadra only ever loads the main res file * (quadra.res) and a single patching res file (quadra115.res or * whatever the exe version number is). The reason is that the * patching feature was made to do just that: patches. We didn't think * about themes back then. However, I've just decided right this * moment that the next version will have a -patch command line option * allowing people to specify additional patching res file(s) to load * (while still loading the version-specific file if found). This * should make it much easier for most people to use a theme pack, if * somebody actually manage to produce one :). * * Ok, that was the good news. Now on to the bad news: the resources * themselves. * * As some of you have found out, Quadra is *really* picky about the * palettes found in it's many image resources. In practice, you have * to use a paint program (or image converter) that gives you direct * control over the 256-colors palette found in the png files. You * can't just scan in a background in Photoshop and save it as a 8-bit * paletted png, it won't look right at all (24-bit images are also * out of the question). Most of the palette is available to use for * the background images, but a good portion of it is used to draw the * blocks and the text in the chat window. You can customize these * colors too (and use them in the background image), but they have to * "make sense" to Quadra for you to get a correct display. Given the * proper image-editing tools with good palette control, you should be * able to make new backgrounds with customized block colors by * imitating the organization of the palettes in the default pngs that * come with the source code package (the simple and irrefutable proof * of that is that we could do it ourselves in the first place :)). * * One other piece of bad news: a lot of sound effects are re-used in * more than one scheme in various ways, so it is not possible to * fully customize all the sound effects for level 1 (for example) * without affecting the sound effects that will play on other * levels. Since most people only play multiplayer (where only one * scheme is visible) this isn't too much of an issue but I thought * I'd mention it anyway. * * Last bit of bad news: if you haven't figured it out from the * palette discussion above, it is not possible to customize the * appearance of blocks beyond their colors (the inside "fill" color * and the little shading/beveling/sunking perimeter lines). Quadra * itself does nearly everything that is possible to do over its 10 * levels as far as block customization is concerned. I know it is * limited, but that's how it is... * * Anyway, I hope that can help somebody. I'd like to see some Quadra * themes myself, if only for the sake of change :). */ #include <stdio.h> #include "stringtable.h" #include "res.h" RCSID("$Id$") char *usage = "usage: wadder <working directory> <output res> <input text>\n"; Resfile *wad; #ifndef HAVE_BASENAME const char *basename(const char* f) { const char* p=(const char*)(f+strlen(f)); while(*p != '/' && *p != '\\' && p>=f) p--; return p+1; } #endif void addfile(const char* fname) { Res_dos *res; char *data; printf("%s: ", fname); res = new Res_dos(fname, RES_TRY); data = new char[res->size()]; res->read(data, res->size()); wad->add(basename(fname), res->size(), data); delete res; delete data; printf("done\n"); } int main(int ARGC, char **ARGV, char **ENV) { Res_dos *res; Byte* data; if(ARGC < 4) { fprintf(stderr, "%s: %s", ARGV[0], usage); exit(1); } char wad_file[256]; sprintf(wad_file, "%s%s", ARGV[1], ARGV[2]); wad = new Resfile(wad_file, false); wad->clear(); char res_file[256]; sprintf(res_file, "%s%s", ARGV[1], ARGV[3]); res = new Res_dos(res_file, RES_READ); data = new Byte[res->size()+1]; memcpy(data, res->buf(), res->size()); Stringtable st(data, res->size()); for(int i=0; i<st.size(); i++) { char temp[256]; sprintf(temp, "%s%s", ARGV[1], st.get(i)); addfile(temp); } delete data; delete res; wad->freeze(); delete wad; return 0; } void start_game(void) { } <|endoftext|>
<commit_before>/* * main.cpp * * Created on: 2014-05-05 * Author: mathieu */ #include <QtNetwork/QNetworkInterface> #include <QtCore/QCoreApplication> #include "TcpClient.h" void showUsage() { printf("exampleTcpClient [hostname] port\n"); exit(-1); } int main(int argc, char * argv[]) { if(argc < 2 || argc > 3) { showUsage(); } QString ipAddress; quint16 port = 0; if(argc == 2) { port = std::atoi(argv[1]); } else if(argc == 3) { ipAddress = argv[1]; port = std::atoi(argv[2]); } if(ipAddress.isEmpty()) { // find out which IP to connect to QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses(); // use the first non-localhost IPv4 address for (int i = 0; i < ipAddressesList.size(); ++i) { if (ipAddressesList.at(i) != QHostAddress::LocalHost && ipAddressesList.at(i).toIPv4Address()) { ipAddress = ipAddressesList.at(i).toString(); break; } } // if we did not find one, use IPv4 localhost if (ipAddress.isEmpty()) { ipAddress = QHostAddress(QHostAddress::LocalHost).toString(); } } QCoreApplication app(argc, argv); printf("Connecting to \"%s:%d\"...\n", ipAddress.toStdString().c_str(), port); TcpClient client(ipAddress, port); if(client.waitForConnected()) { printf("Connecting to \"%s:%d\"... connected!\n", ipAddress.toStdString().c_str(), port); app.exec(); } else { printf("Connecting to \"%s:%d\"... connection failed!\n", ipAddress.toStdString().c_str(), port); } return 0; } <commit_msg>updated tcpClient usage<commit_after>/* * main.cpp * * Created on: 2014-05-05 * Author: mathieu */ #include <QtNetwork/QNetworkInterface> #include <QtCore/QCoreApplication> #include "TcpClient.h" void showUsage() { printf("tcpClient [hostname] port\n"); exit(-1); } int main(int argc, char * argv[]) { if(argc < 2 || argc > 3) { showUsage(); } QString ipAddress; quint16 port = 0; if(argc == 2) { port = std::atoi(argv[1]); } else if(argc == 3) { ipAddress = argv[1]; port = std::atoi(argv[2]); } if(ipAddress.isEmpty()) { // find out which IP to connect to QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses(); // use the first non-localhost IPv4 address for (int i = 0; i < ipAddressesList.size(); ++i) { if (ipAddressesList.at(i) != QHostAddress::LocalHost && ipAddressesList.at(i).toIPv4Address()) { ipAddress = ipAddressesList.at(i).toString(); break; } } // if we did not find one, use IPv4 localhost if (ipAddress.isEmpty()) { ipAddress = QHostAddress(QHostAddress::LocalHost).toString(); } } QCoreApplication app(argc, argv); printf("Connecting to \"%s:%d\"...\n", ipAddress.toStdString().c_str(), port); TcpClient client(ipAddress, port); if(client.waitForConnected()) { printf("Connecting to \"%s:%d\"... connected!\n", ipAddress.toStdString().c_str(), port); app.exec(); } else { printf("Connecting to \"%s:%d\"... connection failed!\n", ipAddress.toStdString().c_str(), port); } return 0; } <|endoftext|>
<commit_before>#include "../docbuilder.h" #define AVS_OFFICESTUDIO_FILE_DOCUMENT 0x0040 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCX AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0001 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_DOC AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0002 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_ODT AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0003 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_RTF AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0004 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_TXT AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0005 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_HTML AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0006 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_MHT AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0007 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_EPUB AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0008 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_FB2 AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0009 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_MOBI AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x000a #define AVS_OFFICESTUDIO_FILE_PRESENTATION 0x0080 #define AVS_OFFICESTUDIO_FILE_PRESENTATION_PPTX AVS_OFFICESTUDIO_FILE_PRESENTATION + 0x0001 #define AVS_OFFICESTUDIO_FILE_PRESENTATION_PPT AVS_OFFICESTUDIO_FILE_PRESENTATION + 0x0002 #define AVS_OFFICESTUDIO_FILE_PRESENTATION_ODP AVS_OFFICESTUDIO_FILE_PRESENTATION + 0x0003 #define AVS_OFFICESTUDIO_FILE_PRESENTATION_PPSX AVS_OFFICESTUDIO_FILE_PRESENTATION + 0x0004 #define AVS_OFFICESTUDIO_FILE_SPREADSHEET 0x0100 #define AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLSX AVS_OFFICESTUDIO_FILE_SPREADSHEET + 0x0001 #define AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLS AVS_OFFICESTUDIO_FILE_SPREADSHEET + 0x0002 #define AVS_OFFICESTUDIO_FILE_SPREADSHEET_ODS AVS_OFFICESTUDIO_FILE_SPREADSHEET + 0x0003 #define AVS_OFFICESTUDIO_FILE_SPREADSHEET_CSV AVS_OFFICESTUDIO_FILE_SPREADSHEET + 0x0004 #define AVS_OFFICESTUDIO_FILE_CROSSPLATFORM 0x0200 #define AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_PDF AVS_OFFICESTUDIO_FILE_CROSSPLATFORM + 0x0001 #define AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_DJVU AVS_OFFICESTUDIO_FILE_CROSSPLATFORM + 0x0003 #define AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_XPS AVS_OFFICESTUDIO_FILE_CROSSPLATFORM + 0x0004 #ifdef WIN32 int wmain(int argc, wchar_t *argv[]) #else int main(int argc, char *argv[]) #endif { if (argc <= 0) return 0; std::wstring sBuildFile(argv[argc - 1]); NSDoctRenderer::CDocBuilder oBuilder; oBuilder.Run(sBuildFile); #if 0 NSDoctRenderer::CDocBuilder oBuilder; // tmpfolder oBuilder.SetTmpFolder(L"D:/BuilderTest"); #if 1 oBuilder.CreateFile(AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCX); oBuilder.ExecuteCommand(L"Add_Text(\"Oleg\");"); #endif #if 0 oBuilder.OpenFile(L"D:/TESTFILES/images.docx", L""); #endif oBuilder.SaveFile(AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_PDF, L"D:/TESTFILES/images.pdf"); #endif return 0; } <commit_msg> <commit_after>#include "../docbuilder.h" #define AVS_OFFICESTUDIO_FILE_DOCUMENT 0x0040 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCX AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0001 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_DOC AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0002 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_ODT AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0003 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_RTF AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0004 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_TXT AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0005 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_HTML AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0006 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_MHT AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0007 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_EPUB AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0008 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_FB2 AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x0009 #define AVS_OFFICESTUDIO_FILE_DOCUMENT_MOBI AVS_OFFICESTUDIO_FILE_DOCUMENT + 0x000a #define AVS_OFFICESTUDIO_FILE_PRESENTATION 0x0080 #define AVS_OFFICESTUDIO_FILE_PRESENTATION_PPTX AVS_OFFICESTUDIO_FILE_PRESENTATION + 0x0001 #define AVS_OFFICESTUDIO_FILE_PRESENTATION_PPT AVS_OFFICESTUDIO_FILE_PRESENTATION + 0x0002 #define AVS_OFFICESTUDIO_FILE_PRESENTATION_ODP AVS_OFFICESTUDIO_FILE_PRESENTATION + 0x0003 #define AVS_OFFICESTUDIO_FILE_PRESENTATION_PPSX AVS_OFFICESTUDIO_FILE_PRESENTATION + 0x0004 #define AVS_OFFICESTUDIO_FILE_SPREADSHEET 0x0100 #define AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLSX AVS_OFFICESTUDIO_FILE_SPREADSHEET + 0x0001 #define AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLS AVS_OFFICESTUDIO_FILE_SPREADSHEET + 0x0002 #define AVS_OFFICESTUDIO_FILE_SPREADSHEET_ODS AVS_OFFICESTUDIO_FILE_SPREADSHEET + 0x0003 #define AVS_OFFICESTUDIO_FILE_SPREADSHEET_CSV AVS_OFFICESTUDIO_FILE_SPREADSHEET + 0x0004 #define AVS_OFFICESTUDIO_FILE_CROSSPLATFORM 0x0200 #define AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_PDF AVS_OFFICESTUDIO_FILE_CROSSPLATFORM + 0x0001 #define AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_DJVU AVS_OFFICESTUDIO_FILE_CROSSPLATFORM + 0x0003 #define AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_XPS AVS_OFFICESTUDIO_FILE_CROSSPLATFORM + 0x0004 #ifdef WIN32 int wmain(int argc, wchar_t *argv[]) #else int main(int argc, char *argv[]) #endif { if (argc <= 0) return 0; #ifdef WIN32 std::wstring sBuildFile(argv[argc - 1]); #else std::string sBuildFileA(argv[argc - 1]); std::wstring sBuildFile = NSFile::CUtf8Converter::GetUnicodeStringFromUTF8((BYTE*)sBuildFileA.c_str(), (LONG)sBuildFileA.length()); #endif NSDoctRenderer::CDocBuilder oBuilder; oBuilder.Run(sBuildFile); return 0; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ #include "AliMUONPreClusterFinder.h" #include "AliLog.h" #include "AliMUONCluster.h" #include "AliMpVSegmentation.h" #include "TClonesArray.h" #include "AliMpArea.h" #include "TVector2.h" #include "AliMUONPad.h" #include "AliMUONVDigit.h" #include "AliMUONVDigitStore.h" /// \class AliMUONPreClusterFinder /// /// Implementation of AliMUONVClusterFinder /// /// This class simply find adjacent pads to form clusters /// /// \author Laurent Aphecetche ClassImp(AliMUONPreClusterFinder) //_____________________________________________________________________________ AliMUONPreClusterFinder::AliMUONPreClusterFinder() : AliMUONVClusterFinder(), fClusters(0x0), fSegmentations(0x0), fDetElemId(0) { /// ctor for ( Int_t i = 0; i < 2; ++i ) { fPads[i] = 0x0; } } //_____________________________________________________________________________ AliMUONPreClusterFinder::~AliMUONPreClusterFinder() { /// dtor : note we're owner of the pads and the clusters, but not of /// the remaining objects (digits, segmentations) delete fClusters; for ( Int_t i = 0; i < 2; ++i ) { delete fPads[i]; } } //_____________________________________________________________________________ Bool_t AliMUONPreClusterFinder::UsePad(const AliMUONPad& pad) { /// Add a pad to the list of pads to be considered if ( pad.DetElemId() != fDetElemId ) { AliError(Form("Cannot add pad from DE %d to this cluster finder which is " "currently dealing with DE %d",pad.DetElemId(),fDetElemId)); return kFALSE; } new ((*fPads[pad.Cathode()])[fPads[pad.Cathode()]->GetLast()+1]) AliMUONPad(pad); // FIXME: should set the ClusterId of that new pad to be -1 return kTRUE; } //_____________________________________________________________________________ Bool_t AliMUONPreClusterFinder::Prepare(const AliMpVSegmentation* segmentations[2], const AliMUONVDigitStore& digitStore) // FIXME : add area on which to look for clusters here. { /// Prepare for clustering, by giving access to segmentations and digit lists fSegmentations = segmentations; delete fClusters; fClusters = new TClonesArray("AliMUONCluster"); for ( Int_t i = 0; i < 2; ++i ) { delete fPads[i]; fPads[i] = new TClonesArray("AliMUONPad"); } fDetElemId = -1; TIter next(digitStore.CreateIterator()); AliMUONVDigit* d; while ( ( d = static_cast<AliMUONVDigit*>(next()) ) ) { Int_t ix = d->PadX(); Int_t iy = d->PadY(); Int_t cathode = d->Cathode(); AliMpPad pad = fSegmentations[cathode]->PadByIndices(AliMpIntPair(ix,iy)); TClonesArray& padArray = *(fPads[cathode]); if ( fDetElemId == -1 ) { fDetElemId = d->DetElemId(); } else { if ( d->DetElemId() != fDetElemId ) { AliError("Something is seriously wrong with DE. Aborting clustering"); return kFALSE; } } AliMUONPad mpad(fDetElemId,cathode, ix,iy,pad.Position().X(),pad.Position().Y(), pad.Dimensions().X(),pad.Dimensions().Y(), d->Charge()); if ( d->IsSaturated() ) mpad.SetSaturated(kTRUE); new (padArray[padArray.GetLast()+1]) AliMUONPad(mpad); } if ( fPads[0]->GetLast() < 0 && fPads[1]->GetLast() < 0 ) { // no pad at all, nothing to do... return kFALSE; } return kTRUE; } //_____________________________________________________________________________ void AliMUONPreClusterFinder::AddPad(AliMUONCluster& cluster, AliMUONPad* pad) { /// Add a pad to a cluster cluster.AddPad(*pad); Int_t cathode = pad->Cathode(); TClonesArray& padArray = *fPads[cathode]; padArray.Remove(pad); //AZ padArray.Compress(); TIter next(&padArray); AliMUONPad* testPad; while ( ( testPad = static_cast<AliMUONPad*>(next()))) { if ( AliMUONPad::AreNeighbours(*testPad,*pad) ) { AddPad(cluster,testPad); } } } //_____________________________________________________________________________ Bool_t AreOverlapping(const AliMUONPad& pad, const AliMUONCluster& cluster) { /// Whether the pad overlaps with the cluster static Double_t precision = 1E-4; // cm static TVector2 precisionAdjustment(precision,precision);//-precision,-precision); for ( Int_t i = 0; i < cluster.Multiplicity(); ++i ) { AliMUONPad* testPad = cluster.Pad(i); // Note: we use negative precision numbers, meaning // the area of the pads will be *increased* by these small numbers // prior to check the overlap by the AreOverlapping method, // so pads touching only by the corners will be considered as // overlapping. if ( AliMUONPad::AreOverlapping(*testPad,pad,precisionAdjustment) ) { return kTRUE; } } return kFALSE; } //_____________________________________________________________________________ AliMUONCluster* AliMUONPreClusterFinder::NextCluster() { /// Builds the next cluster, and returns it. // Start a new cluster Int_t id = fClusters->GetLast()+1; AliMUONCluster* cluster = new ((*fClusters)[id]) AliMUONCluster; cluster->SetUniqueID(id); TIter next(fPads[0]); AliMUONPad* pad = static_cast<AliMUONPad*>(next()); if (!pad) // protection against no pad in first cathode, which might happen { // try other cathode TIter next(fPads[1]); pad = static_cast<AliMUONPad*>(next()); if (!pad) { // we are done. return 0x0; } // Builds (recursively) a cluster on second cathode only AddPad(*cluster,pad); } else { // Builds (recursively) a cluster on first cathode only AddPad(*cluster,pad); // On the 2nd cathode, only add pads overlapping with the current cluster TClonesArray& padArray = *fPads[1]; TIter next(&padArray); AliMUONPad* testPad; while ( ( testPad = static_cast<AliMUONPad*>(next()))) { if ( AreOverlapping(*testPad,*cluster) ) { AddPad(*cluster,testPad); } } } if ( cluster->Multiplicity() <= 1 ) { if ( cluster->Multiplicity() == 0 ) { // no pad is suspicious AliWarning("Got an empty cluster..."); } // else only 1 pad (not suspicious, but kind of useless, probably noise) // so we remove it from our list fClusters->Remove(cluster); fClusters->Compress(); // then proceed further return NextCluster(); } return cluster; } <commit_msg>Adding some important comments (Laurent)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ #include "AliMUONPreClusterFinder.h" #include "AliLog.h" #include "AliMUONCluster.h" #include "AliMpVSegmentation.h" #include "TClonesArray.h" #include "AliMpArea.h" #include "TVector2.h" #include "AliMUONPad.h" #include "AliMUONVDigit.h" #include "AliMUONVDigitStore.h" //#include "AliCodeTimer.h" /// \class AliMUONPreClusterFinder /// /// Implementation of AliMUONVClusterFinder /// /// This class simply find adjacent pads to form clusters /// /// \author Laurent Aphecetche ClassImp(AliMUONPreClusterFinder) //_____________________________________________________________________________ AliMUONPreClusterFinder::AliMUONPreClusterFinder() : AliMUONVClusterFinder(), fClusters(0x0), fSegmentations(0x0), fDetElemId(0) { /// ctor for ( Int_t i = 0; i < 2; ++i ) { fPads[i] = 0x0; } } //_____________________________________________________________________________ AliMUONPreClusterFinder::~AliMUONPreClusterFinder() { /// dtor : note we're owner of the pads and the clusters, but not of /// the remaining objects (digits, segmentations) delete fClusters; for ( Int_t i = 0; i < 2; ++i ) { delete fPads[i]; } } //_____________________________________________________________________________ Bool_t AliMUONPreClusterFinder::UsePad(const AliMUONPad& pad) { /// Add a pad to the list of pads to be considered if ( pad.DetElemId() != fDetElemId ) { AliError(Form("Cannot add pad from DE %d to this cluster finder which is " "currently dealing with DE %d",pad.DetElemId(),fDetElemId)); return kFALSE; } new ((*fPads[pad.Cathode()])[fPads[pad.Cathode()]->GetLast()+1]) AliMUONPad(pad); // FIXME: should set the ClusterId of that new pad to be -1 return kTRUE; } //_____________________________________________________________________________ Bool_t AliMUONPreClusterFinder::Prepare(const AliMpVSegmentation* segmentations[2], const AliMUONVDigitStore& digitStore) // FIXME : add area on which to look for clusters here. { /// Prepare for clustering, by giving access to segmentations and digit lists fSegmentations = segmentations; delete fClusters; fClusters = new TClonesArray("AliMUONCluster"); for ( Int_t i = 0; i < 2; ++i ) { delete fPads[i]; fPads[i] = new TClonesArray("AliMUONPad"); } fDetElemId = -1; TIter next(digitStore.CreateIterator()); AliMUONVDigit* d; while ( ( d = static_cast<AliMUONVDigit*>(next()) ) ) { Int_t ix = d->PadX(); Int_t iy = d->PadY(); Int_t cathode = d->Cathode(); AliMpPad pad = fSegmentations[cathode]->PadByIndices(AliMpIntPair(ix,iy)); TClonesArray& padArray = *(fPads[cathode]); if ( fDetElemId == -1 ) { fDetElemId = d->DetElemId(); } else { if ( d->DetElemId() != fDetElemId ) { AliError("Something is seriously wrong with DE. Aborting clustering"); return kFALSE; } } AliMUONPad mpad(fDetElemId,cathode, ix,iy,pad.Position().X(),pad.Position().Y(), pad.Dimensions().X(),pad.Dimensions().Y(), d->Charge()); if ( d->IsSaturated() ) mpad.SetSaturated(kTRUE); new (padArray[padArray.GetLast()+1]) AliMUONPad(mpad); } if ( fPads[0]->GetLast() < 0 && fPads[1]->GetLast() < 0 ) { // no pad at all, nothing to do... return kFALSE; } return kTRUE; } //_____________________________________________________________________________ void AliMUONPreClusterFinder::AddPad(AliMUONCluster& cluster, AliMUONPad* pad) { /// Add a pad to a cluster cluster.AddPad(*pad); Int_t cathode = pad->Cathode(); TClonesArray& padArray = *fPads[cathode]; // WARNING: this Remove method uses the AliMUONPad::IsEqual if that method is // present (otherwise just compares pointers) : so that one must be correct // if implemented ! padArray.Remove(pad); // TObject* o = padArray.Remove(pad); // if (!o) // { // AliFatal("Oups. Could not remove pad from pads to consider. Aborting as anyway " // " we'll get an infinite loop. Please check the AliMUONPad::IsEqual method" // " as the first suspect for failed remove"); // } TIter next(&padArray); AliMUONPad* testPad; while ( ( testPad = static_cast<AliMUONPad*>(next()))) { if ( AliMUONPad::AreNeighbours(*testPad,*pad) ) { AddPad(cluster,testPad); } } } //_____________________________________________________________________________ Bool_t AreOverlapping(const AliMUONPad& pad, const AliMUONCluster& cluster) { /// Whether the pad overlaps with the cluster static Double_t precision = 1E-4; // cm static TVector2 precisionAdjustment(precision,precision);//-precision,-precision); for ( Int_t i = 0; i < cluster.Multiplicity(); ++i ) { AliMUONPad* testPad = cluster.Pad(i); // Note: we use negative precision numbers, meaning // the area of the pads will be *increased* by these small numbers // prior to check the overlap by the AreOverlapping method, // so pads touching only by the corners will be considered as // overlapping. if ( AliMUONPad::AreOverlapping(*testPad,pad,precisionAdjustment) ) { return kTRUE; } } return kFALSE; } //_____________________________________________________________________________ AliMUONCluster* AliMUONPreClusterFinder::NextCluster() { /// Builds the next cluster, and returns it. // AliCodeTimerAuto("") // Start a new cluster Int_t id = fClusters->GetLast()+1; AliMUONCluster* cluster = new ((*fClusters)[id]) AliMUONCluster; cluster->SetUniqueID(id); TIter next(fPads[0]); AliMUONPad* pad = static_cast<AliMUONPad*>(next()); if (!pad) // protection against no pad in first cathode, which might happen { // try other cathode TIter next(fPads[1]); pad = static_cast<AliMUONPad*>(next()); if (!pad) { // we are done. return 0x0; } // Builds (recursively) a cluster on second cathode only AddPad(*cluster,pad); } else { // Builds (recursively) a cluster on first cathode only AddPad(*cluster,pad); // On the 2nd cathode, only add pads overlapping with the current cluster TClonesArray& padArray = *fPads[1]; TIter next(&padArray); AliMUONPad* testPad; while ( ( testPad = static_cast<AliMUONPad*>(next()))) { if ( AreOverlapping(*testPad,*cluster) ) { AddPad(*cluster,testPad); } } } if ( cluster->Multiplicity() <= 1 ) { if ( cluster->Multiplicity() == 0 ) { // no pad is suspicious AliWarning("Got an empty cluster..."); } // else only 1 pad (not suspicious, but kind of useless, probably noise) // so we remove it from our list fClusters->Remove(cluster); fClusters->Compress(); // then proceed further return NextCluster(); } return cluster; } <|endoftext|>
<commit_before><commit_msg>getting somewhere with this opencl lark!<commit_after><|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2009-2012, Willow Garage, Inc. * Copyright (c) 2012-, Open Perception, 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 the copyright holder(s) 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. * * $Id$ * */ #include <pcl/apps/in_hand_scanner/in_hand_scanner.h> #include <pcl/io/openni_grabber.h> #include <pcl/features/integral_image_normal.h> #include <pcl/filters/passthrough.h> #include <pcl/visualization/pcl_visualizer.h> //////////////////////////////////////////////////////////////////////////////// pcl::InHandScanner::InHandScanner () : mutex_ (), p_grabber_ (new Grabber ("#1")), p_visualizer_ (), p_normal_estimation_ (new NormalEstimation ()), p_pass_through_ (new PassThrough ()), p_drawn_cloud_ (new Cloud ()) { // Normal estimation p_normal_estimation_->setNormalEstimationMethod (NormalEstimation::AVERAGE_3D_GRADIENT); p_normal_estimation_->setMaxDepthChangeFactor (0.02f); p_normal_estimation_->setNormalSmoothingSize (10.0f); // Pass through } //////////////////////////////////////////////////////////////////////////////// pcl::InHandScanner::~InHandScanner () { if (p_grabber_->isRunning ()) { p_grabber_->stop (); } } //////////////////////////////////////////////////////////////////////////////// void pcl::InHandScanner::setVisualizer (const PCLVisualizerPtr& p_visualizer) { p_visualizer_ = p_visualizer; } //////////////////////////////////////////////////////////////////////////////// void pcl::InHandScanner::start () { boost::function<void (const CloudConstPtr&)> f = boost::bind (&pcl::InHandScanner::grabbedDataCallback, this, _1); /*boost::signals2::connection c = */ p_grabber_->registerCallback (f); p_grabber_->start (); } //////////////////////////////////////////////////////////////////////////////// void pcl::InHandScanner::draw () { if (!p_drawn_cloud_) { boost::this_thread::sleep (boost::posix_time::milliseconds (1)); return; } CloudPtr p_temp_cloud; { boost::mutex::scoped_lock locker (mutex_); p_temp_cloud.swap (p_drawn_cloud_); } if (!p_visualizer_->updatePointCloud (p_temp_cloud, "cloud")) { p_visualizer_->addPointCloud (p_temp_cloud, "cloud"); p_visualizer_->resetCameraViewpoint ("cloud"); } this->showFPS ("visualization"); } //////////////////////////////////////////////////////////////////////////////// void pcl::InHandScanner::grabbedDataCallback (const CloudConstPtr& p_cloud_in) { boost::mutex::scoped_lock locker (mutex_); // Calculate the normals CloudWithNormalsPtr p_cloud_with_normals (new CloudWithNormals ()); // p_normal_estimation_->setInputCloud (p_cloud_in); // p_normal_estimation_->compute (*p_cloud_with_normals); pcl::copyPointCloud (*p_cloud_in, *p_cloud_with_normals); // Adding '<Point, PointWithNormal>' does not help // // Pass through // PointCloudWithNormalsPtr p_cloud_pass_through (new PointCloudWithNormals ()); // p_pass_through_->setInputCloud (p_cloud_with_normals); // p_pass_through_->filter (*p_cloud_pass_through); // Set the cloud for visualization p_drawn_cloud_.reset (new Cloud ()); // pcl::copyPointCloud (*p_cloud_with_normals, *p_drawn_cloud_); // Adding '<PointWithNormal, Point>' does not help pcl::copyPointCloud (*p_cloud_in, *p_drawn_cloud_); // works this->showFPS ("computation"); } //////////////////////////////////////////////////////////////////////////////// void pcl::InHandScanner::showFPS (const std::string& what) const { static unsigned int count = 0; static double last = pcl::getTime (); double now = pcl::getTime (); ++count; if ((now-last) >= 1.) { const double fps = static_cast<double> (count) / (now - last); std::cerr << "Average framerate (" << what << ") = " << fps << "Hz\n"; count = 0; last = now; } } //////////////////////////////////////////////////////////////////////////////// <commit_msg>drawing black on black<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2009-2012, Willow Garage, Inc. * Copyright (c) 2012-, Open Perception, 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 the copyright holder(s) 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. * * $Id$ * */ #include <pcl/apps/in_hand_scanner/in_hand_scanner.h> #include <pcl/io/openni_grabber.h> #include <pcl/features/integral_image_normal.h> #include <pcl/filters/passthrough.h> #include <pcl/visualization/pcl_visualizer.h> //////////////////////////////////////////////////////////////////////////////// pcl::InHandScanner::InHandScanner () : mutex_ (), p_grabber_ (new Grabber ("#1")), p_visualizer_ (), p_normal_estimation_ (new NormalEstimation ()), p_pass_through_ (new PassThrough ()), p_drawn_cloud_ (new Cloud ()) { // Normal estimation p_normal_estimation_->setNormalEstimationMethod (NormalEstimation::AVERAGE_3D_GRADIENT); p_normal_estimation_->setMaxDepthChangeFactor (0.02f); p_normal_estimation_->setNormalSmoothingSize (10.0f); // Pass through } //////////////////////////////////////////////////////////////////////////////// pcl::InHandScanner::~InHandScanner () { if (p_grabber_->isRunning ()) { p_grabber_->stop (); } } //////////////////////////////////////////////////////////////////////////////// void pcl::InHandScanner::setVisualizer (const PCLVisualizerPtr& p_visualizer) { p_visualizer_ = p_visualizer; } //////////////////////////////////////////////////////////////////////////////// void pcl::InHandScanner::start () { boost::function<void (const CloudConstPtr&)> f = boost::bind (&pcl::InHandScanner::grabbedDataCallback, this, _1); /*boost::signals2::connection c = */ p_grabber_->registerCallback (f); p_grabber_->start (); } //////////////////////////////////////////////////////////////////////////////// void pcl::InHandScanner::draw () { if (!p_drawn_cloud_) { boost::this_thread::sleep (boost::posix_time::milliseconds (1)); return; } CloudPtr p_temp_cloud; { boost::mutex::scoped_lock locker (mutex_); p_temp_cloud.swap (p_drawn_cloud_); } p_visualizer_->setBackgroundColor (1.0, 1.0, 1.0); if (!p_visualizer_->updatePointCloud (p_temp_cloud, "cloud")) { p_visualizer_->addPointCloud (p_temp_cloud, "cloud"); p_visualizer_->resetCameraViewpoint ("cloud"); } this->showFPS ("visualization"); } //////////////////////////////////////////////////////////////////////////////// void pcl::InHandScanner::grabbedDataCallback (const CloudConstPtr& p_cloud_in) { boost::mutex::scoped_lock locker (mutex_); // Calculate the normals CloudWithNormalsPtr p_cloud_with_normals (new CloudWithNormals ()); // p_normal_estimation_->setInputCloud (p_cloud_in); // p_normal_estimation_->compute (*p_cloud_with_normals); pcl::copyPointCloud (*p_cloud_in, *p_cloud_with_normals); // Adding '<Point, PointWithNormal>' does not help // // Pass through // PointCloudWithNormalsPtr p_cloud_pass_through (new PointCloudWithNormals ()); // p_pass_through_->setInputCloud (p_cloud_with_normals); // p_pass_through_->filter (*p_cloud_pass_through); // Set the cloud for visualization p_drawn_cloud_.reset (new Cloud ()); pcl::copyPointCloud (*p_cloud_with_normals, *p_drawn_cloud_); // Adding '<PointWithNormal, Point>' does not help //pcl::copyPointCloud (*p_cloud_in, *p_drawn_cloud_); // works this->showFPS ("computation"); } //////////////////////////////////////////////////////////////////////////////// void pcl::InHandScanner::showFPS (const std::string& what) const { static unsigned int count = 0; static double last = pcl::getTime (); double now = pcl::getTime (); ++count; if ((now-last) >= 1.) { const double fps = static_cast<double> (count) / (now - last); std::cerr << "Average framerate (" << what << ") = " << fps << "Hz\n"; count = 0; last = now; } } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* -*- c++ -*- subscriptiondialog.cpp This file is part of KMail, the KDE mail client. Copyright (C) 2002 Carsten Burghardt <burghardt@kde.org> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail 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 In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "subscriptiondialog.h" #include "folderstorage.h" #include "listjob.h" #include "imapaccountbase.h" #include "accountmanager.h" #include <klocale.h> #include <kdebug.h> #include <kmessagebox.h> namespace KMail { SubscriptionDialogBase::SubscriptionDialogBase( QWidget *parent, const QString &caption, KAccount *acct, const QString &startPath ) : KSubscription( parent, caption, acct, User1, QString(), false ), mStartPath( startPath ), mSubscribed( false ), mForceSubscriptionEnable( false) { // hide unneeded checkboxes hideTreeCheckbox(); hideNewOnlyCheckbox(); // reload-list button connect(this, SIGNAL(user1Clicked()), SLOT(slotLoadFolders())); // get the folders, delayed execution style, otherwise there's bother // with virtuals from ctors and whatnot QTimer::singleShot(0, this, SLOT(slotLoadFolders())); } //------------------------------------------------------------------------------ void SubscriptionDialogBase::slotListDirectory( const QStringList& subfolderNames, const QStringList& subfolderPaths, const QStringList& subfolderMimeTypes, const QStringList& subfolderAttributes, const ImapAccountBase::jobData& jobData ) { mFolderNames = subfolderNames; mFolderPaths = subfolderPaths; mFolderMimeTypes = subfolderMimeTypes; mFolderAttributes = subfolderAttributes; mJobData = jobData; mCount = 0; processFolderListing(); } void SubscriptionDialogBase::slotButtonClicked( int button ) { if ( button == KDialog::Ok ) { if ( doSave() ) { accept(); } } else { KDialog::slotButtonClicked( button ); } } void SubscriptionDialogBase::moveChildrenToNewParent( GroupItem *oldItem, GroupItem *item ) { if ( !oldItem || !item ) return; Q3PtrList<Q3ListViewItem> itemsToMove; Q3ListViewItem * myChild = oldItem->firstChild(); while (myChild) { itemsToMove.append(myChild); myChild = myChild->nextSibling(); } Q3PtrListIterator<Q3ListViewItem> it( itemsToMove ); Q3ListViewItem *cur; while ((cur = it.current())) { oldItem->takeItem(cur); item->insertItem(cur); if ( cur->isSelected() ) // we have new parents so open them folderTree()->ensureItemVisible( cur ); ++it; } delete oldItem; itemsToMove.clear(); } void SubscriptionDialogBase::createListViewItem( int i ) { GroupItem *item = 0; GroupItem *parent = 0; // get the parent GroupItem *oldItem = 0; QString parentPath; findParentItem( mFolderNames[i], mFolderPaths[i], parentPath, &parent, &oldItem ); if (!parent && parentPath != "/") { // the parent is not available and it's no root-item // this happens when the folders do not arrive in hierarchical order // so we create each parent in advance QStringList folders = parentPath.split(mDelimiter); uint i = 0; for ( QStringList::Iterator it = folders.begin(); it != folders.end(); ++it ) { QString name = *it; if (name.startsWith('/')) name = name.right(name.length()-1); if (name.endsWith('/')) name.truncate(name.length()-1); KGroupInfo info(name); info.subscribed = false; QStringList tmpPath; for ( uint j = 0; j <= i; ++j ) tmpPath << folders[j]; QString path = tmpPath.join(mDelimiter); if (!path.startsWith('/')) path = '/' + path; if (!path.endsWith('/')) path = path + '/'; info.path = path; item = 0; if (folders.count() > 1) { // we have to create more then one level, so better check if this // folder already exists somewhere item = mItemDict[path]; } // as these items are "dummies" we create them non-checkable if (!item) { if (parent) item = new GroupItem(parent, info, this, false); else item = new GroupItem(folderTree(), info, this, false); mItemDict.insert(info.path, item); } parent = item; ++i; } // folders } // parent KGroupInfo info(mFolderNames[i]); if (mFolderNames[i].toUpper() == "INBOX" && mFolderPaths[i] == "/INBOX/") info.name = i18n("inbox"); info.subscribed = false; info.path = mFolderPaths[i]; // only checkable when the folder is selectable bool checkable = ( mFolderMimeTypes[i] == "inode/directory" ) ? false : true; // create a new item if (parent) item = new GroupItem(parent, info, this, checkable); else item = new GroupItem(folderTree(), info, this, checkable); if (oldItem) // remove old item mItemDict.remove(info.path); mItemDict.insert(info.path, item); if (oldItem) moveChildrenToNewParent( oldItem, item ); // select the start item if ( mFolderPaths[i] == mStartPath ) { item->setSelected( true ); folderTree()->ensureItemVisible( item ); } } //------------------------------------------------------------------------------ void SubscriptionDialogBase::findParentItem( QString &name, QString &path, QString &parentPath, GroupItem **parent, GroupItem **oldItem ) { // remove the name (and the separator) from the path to get the parent path int start = path.length() - (name.length()+2); int length = name.length()+1; if (start < 0) start = 0; parentPath = path; parentPath.remove(start, length); // find the parent by it's path QMap<QString, GroupItem*>::Iterator it = mItemDict.find( parentPath ); if ( it != mItemDict.end() ) *parent = ( *it ); // check if the item already exists it = mItemDict.find( path ); if ( it != mItemDict.end() ) *oldItem = ( *it ); } //------------------------------------------------------------------------------ void SubscriptionDialogBase::slotLoadFolders() { ImapAccountBase* ai = static_cast<ImapAccountBase*>(account()); // we need a connection if ( ai->makeConnection() == ImapAccountBase::Error ) { kWarning(5006) <<"SubscriptionDialog - got no connection"; return; } else if ( ai->makeConnection() == ImapAccountBase::Connecting ) { // We'll wait for the connectionResult signal from the account. kDebug(5006) <<"SubscriptionDialog - waiting for connection"; connect( ai, SIGNAL( connectionResult(int, const QString&) ), this, SLOT( slotConnectionResult(int, const QString&) ) ); return; } // clear the views KSubscription::slotLoadFolders(); mItemDict.clear(); mSubscribed = false; mLoading = true; // first step is to load a list of all available folders and create listview // items for them listAllAvailableAndCreateItems(); } //------------------------------------------------------------------------------ void SubscriptionDialogBase::processNext() { if ( mPrefixList.isEmpty() ) { if ( !mSubscribed ) { mSubscribed = true; initPrefixList(); if ( mPrefixList.isEmpty() ) { // still empty? then we have nothing to do here as this is an error loadingComplete(); return; } } else { loadingComplete(); return; } } ImapAccountBase* ai = static_cast<ImapAccountBase*>(account()); ImapAccountBase::ListType type = ( mSubscribed ? ImapAccountBase::ListSubscribedNoCheck : ImapAccountBase::List ); bool completeListing = true; mCurrentNamespace = mPrefixList.first(); mDelimiter = ai->delimiterForNamespace( mCurrentNamespace ); mPrefixList.pop_front(); if ( mCurrentNamespace == "/INBOX/" ) { type = mSubscribed ? ImapAccountBase::ListFolderOnlySubscribed : ImapAccountBase::ListFolderOnly; completeListing = false; } // kDebug(5006) <<"process" << mCurrentNamespace <<",subscribed=" << mSubscribed; ListJob* job = new ListJob( ai, type, 0, ai->addPathToNamespace( mCurrentNamespace ), completeListing ); connect( job, SIGNAL(receivedFolders(const QStringList&, const QStringList&, const QStringList&, const QStringList&, const ImapAccountBase::jobData&)), this, SLOT(slotListDirectory(const QStringList&, const QStringList&, const QStringList&, const QStringList&, const ImapAccountBase::jobData&))); job->start(); } void SubscriptionDialogBase::loadingComplete() { slotLoadingComplete(); } //------------------------------------------------------------------------------ // implementation for server side subscription //------------------------------------------------------------------------------ SubscriptionDialog::SubscriptionDialog( QWidget *parent, const QString &caption, KAccount *acct, const QString & startPath ) : SubscriptionDialogBase( parent, caption, acct, startPath ) { } /* virtual */ SubscriptionDialog::~SubscriptionDialog() { } /* virtual */ void SubscriptionDialog::listAllAvailableAndCreateItems() { initPrefixList(); processNext(); } //------------------------------------------------------------------------------ void SubscriptionDialogBase::initPrefixList() { ImapAccountBase* ai = static_cast<ImapAccountBase*>(account()); ImapAccountBase::nsMap map = ai->namespaces(); mPrefixList.clear(); bool hasInbox = false; const QStringList ns = map[ImapAccountBase::PersonalNS]; for ( QStringList::ConstIterator it = ns.begin(); it != ns.end(); ++it ) { if ( (*it).isEmpty() ) hasInbox = true; } if ( !hasInbox && !ns.isEmpty() ) { // the namespaces includes no listing for the root so start a special // listing for the INBOX to make sure we get it mPrefixList += "/INBOX/"; } mPrefixList += map[ImapAccountBase::PersonalNS]; mPrefixList += map[ImapAccountBase::OtherUsersNS]; mPrefixList += map[ImapAccountBase::SharedNS]; } void SubscriptionDialogBase::slotConnectionResult( int errorCode, const QString& errorMsg ) { Q_UNUSED( errorMsg ); if ( !errorCode ) slotLoadFolders(); } bool SubscriptionDialogBase::checkIfSubscriptionsEnabled() { KMail::ImapAccountBase *account = static_cast<KMail::ImapAccountBase*>(mAcct); if( !account ) return true; if( subscriptionOptionEnabled( account ) ) return true; int result = KMessageBox::questionYesNoCancel( this, subscriptionOptionQuestion( account->name() ), i18n("Enable Subscriptions?"), KGuiItem( i18n("Enable") ), KGuiItem( i18n("Do Not Enable") ) ); switch(result) { case KMessageBox::Yes: mForceSubscriptionEnable = true; break; case KMessageBox::No: break; case KMessageBox::Cancel: return false; break; } return true; } void SubscriptionDialogBase::show() { KDialog::show(); checkIfSubscriptionsEnabled(); } // ======= /* virtual */ void SubscriptionDialog::processFolderListing() { processItems(); } /* virtual */ bool SubscriptionDialog::doSave() { if ( !checkIfSubscriptionsEnabled() ) return false; bool somethingHappened = false; // subscribe Q3ListViewItemIterator it(subView); for ( ; it.current(); ++it) { static_cast<ImapAccountBase*>(account())->changeSubscription(true, static_cast<GroupItem*>(it.current())->info().path); somethingHappened = true; } // unsubscribe Q3ListViewItemIterator it2(unsubView); for ( ; it2.current(); ++it2) { static_cast<ImapAccountBase*>(account())->changeSubscription(false, static_cast<GroupItem*>(it2.current())->info().path); somethingHappened = true; } // Slight code duplication with LocalSubscriptionDialog follows! KMail::ImapAccountBase *a = static_cast<KMail::ImapAccountBase*>( mAcct ); if ( mForceSubscriptionEnable ) { a->setOnlySubscribedFolders( true ); } if ( somethingHappened && subscriptionOptionEnabled( a ) ) { kmkernel->acctMgr()->singleCheckMail( a, true ); } return true; } bool SubscriptionDialog::subscriptionOptionEnabled( const KMail::ImapAccountBase *account ) const { return account->onlySubscribedFolders(); } QString SubscriptionDialog::subscriptionOptionQuestion( const QString &accountName ) const { return i18nc( "@info", "Currently subscriptions are not used for server <resource>%1</resource>.<nl/>" "\nDo you want to enable subscriptions?", accountName ); } void SubscriptionDialog::processItems() { bool onlySubscribed = mJobData.onlySubscribed; uint done = 0; for (int i = mCount; i < mFolderNames.count(); ++i) { // give the dialog a chance to repaint if (done == 1000) { emit listChanged(); QTimer::singleShot(0, this, SLOT(processItems())); return; } ++mCount; ++done; if (!onlySubscribed && mFolderPaths.size() > 0) { createListViewItem( i ); } else if (onlySubscribed) { // find the item if ( mItemDict[mFolderPaths[i]] ) { GroupItem* item = mItemDict[mFolderPaths[i]]; item->setOn( true ); } } } processNext(); } } // namespace #include "subscriptiondialog.moc" <commit_msg>Don't show a strange empty root item in the subscription dialog.<commit_after>/* -*- c++ -*- subscriptiondialog.cpp This file is part of KMail, the KDE mail client. Copyright (C) 2002 Carsten Burghardt <burghardt@kde.org> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail 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 In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "subscriptiondialog.h" #include "folderstorage.h" #include "listjob.h" #include "imapaccountbase.h" #include "accountmanager.h" #include <klocale.h> #include <kdebug.h> #include <kmessagebox.h> namespace KMail { SubscriptionDialogBase::SubscriptionDialogBase( QWidget *parent, const QString &caption, KAccount *acct, const QString &startPath ) : KSubscription( parent, caption, acct, User1, QString(), false ), mStartPath( startPath ), mSubscribed( false ), mForceSubscriptionEnable( false) { // hide unneeded checkboxes hideTreeCheckbox(); hideNewOnlyCheckbox(); // reload-list button connect(this, SIGNAL(user1Clicked()), SLOT(slotLoadFolders())); // get the folders, delayed execution style, otherwise there's bother // with virtuals from ctors and whatnot QTimer::singleShot(0, this, SLOT(slotLoadFolders())); } //------------------------------------------------------------------------------ void SubscriptionDialogBase::slotListDirectory( const QStringList& subfolderNames, const QStringList& subfolderPaths, const QStringList& subfolderMimeTypes, const QStringList& subfolderAttributes, const ImapAccountBase::jobData& jobData ) { mFolderNames = subfolderNames; mFolderPaths = subfolderPaths; mFolderMimeTypes = subfolderMimeTypes; mFolderAttributes = subfolderAttributes; mJobData = jobData; mCount = 0; processFolderListing(); } void SubscriptionDialogBase::slotButtonClicked( int button ) { if ( button == KDialog::Ok ) { if ( doSave() ) { accept(); } } else { KDialog::slotButtonClicked( button ); } } void SubscriptionDialogBase::moveChildrenToNewParent( GroupItem *oldItem, GroupItem *item ) { if ( !oldItem || !item ) return; Q3PtrList<Q3ListViewItem> itemsToMove; Q3ListViewItem * myChild = oldItem->firstChild(); while (myChild) { itemsToMove.append(myChild); myChild = myChild->nextSibling(); } Q3PtrListIterator<Q3ListViewItem> it( itemsToMove ); Q3ListViewItem *cur; while ((cur = it.current())) { oldItem->takeItem(cur); item->insertItem(cur); if ( cur->isSelected() ) // we have new parents so open them folderTree()->ensureItemVisible( cur ); ++it; } delete oldItem; itemsToMove.clear(); } void SubscriptionDialogBase::createListViewItem( int i ) { GroupItem *item = 0; GroupItem *parent = 0; // get the parent GroupItem *oldItem = 0; QString parentPath; findParentItem( mFolderNames[i], mFolderPaths[i], parentPath, &parent, &oldItem ); if (!parent && parentPath != "/") { // the parent is not available and it's no root-item // this happens when the folders do not arrive in hierarchical order // so we create each parent in advance QStringList folders = parentPath.split( mDelimiter, QString::SkipEmptyParts ); uint i = 0; for ( QStringList::Iterator it = folders.begin(); it != folders.end(); ++it ) { QString name = *it; if (name.startsWith('/')) name = name.right(name.length()-1); if (name.endsWith('/')) name.truncate(name.length()-1); KGroupInfo info(name); info.subscribed = false; QStringList tmpPath; for ( uint j = 0; j <= i; ++j ) tmpPath << folders[j]; QString path = tmpPath.join(mDelimiter); if (!path.startsWith('/')) path = '/' + path; if (!path.endsWith('/')) path = path + '/'; info.path = path; item = 0; if (folders.count() > 1) { // we have to create more then one level, so better check if this // folder already exists somewhere item = mItemDict[path]; } // as these items are "dummies" we create them non-checkable if (!item) { if (parent) { item = new GroupItem(parent, info, this, false); } else { item = new GroupItem(folderTree(), info, this, false); } mItemDict.insert(info.path, item); } parent = item; ++i; } // folders } // parent KGroupInfo info(mFolderNames[i]); if (mFolderNames[i].toUpper() == "INBOX" && mFolderPaths[i] == "/INBOX/") info.name = i18n("inbox"); info.subscribed = false; info.path = mFolderPaths[i]; // only checkable when the folder is selectable bool checkable = ( mFolderMimeTypes[i] == "inode/directory" ) ? false : true; // create a new item if ( parent ) { item = new GroupItem(parent, info, this, checkable); } else { item = new GroupItem(folderTree(), info, this, checkable); } if (oldItem) // remove old item mItemDict.remove(info.path); mItemDict.insert(info.path, item); if (oldItem) moveChildrenToNewParent( oldItem, item ); // select the start item if ( mFolderPaths[i] == mStartPath ) { item->setSelected( true ); folderTree()->ensureItemVisible( item ); } } //------------------------------------------------------------------------------ void SubscriptionDialogBase::findParentItem( QString &name, QString &path, QString &parentPath, GroupItem **parent, GroupItem **oldItem ) { // remove the name (and the separator) from the path to get the parent path int start = path.length() - (name.length()+2); int length = name.length()+1; if (start < 0) start = 0; parentPath = path; parentPath.remove(start, length); // find the parent by it's path QMap<QString, GroupItem*>::Iterator it = mItemDict.find( parentPath ); if ( it != mItemDict.end() ) *parent = ( *it ); // check if the item already exists it = mItemDict.find( path ); if ( it != mItemDict.end() ) *oldItem = ( *it ); } //------------------------------------------------------------------------------ void SubscriptionDialogBase::slotLoadFolders() { ImapAccountBase* ai = static_cast<ImapAccountBase*>(account()); // we need a connection if ( ai->makeConnection() == ImapAccountBase::Error ) { kWarning(5006) <<"SubscriptionDialog - got no connection"; return; } else if ( ai->makeConnection() == ImapAccountBase::Connecting ) { // We'll wait for the connectionResult signal from the account. kDebug(5006) <<"SubscriptionDialog - waiting for connection"; connect( ai, SIGNAL( connectionResult(int, const QString&) ), this, SLOT( slotConnectionResult(int, const QString&) ) ); return; } // clear the views KSubscription::slotLoadFolders(); mItemDict.clear(); mSubscribed = false; mLoading = true; // first step is to load a list of all available folders and create listview // items for them listAllAvailableAndCreateItems(); } //------------------------------------------------------------------------------ void SubscriptionDialogBase::processNext() { if ( mPrefixList.isEmpty() ) { if ( !mSubscribed ) { mSubscribed = true; initPrefixList(); if ( mPrefixList.isEmpty() ) { // still empty? then we have nothing to do here as this is an error loadingComplete(); return; } } else { loadingComplete(); return; } } ImapAccountBase* ai = static_cast<ImapAccountBase*>(account()); ImapAccountBase::ListType type = ( mSubscribed ? ImapAccountBase::ListSubscribedNoCheck : ImapAccountBase::List ); bool completeListing = true; mCurrentNamespace = mPrefixList.first(); mDelimiter = ai->delimiterForNamespace( mCurrentNamespace ); mPrefixList.pop_front(); if ( mCurrentNamespace == "/INBOX/" ) { type = mSubscribed ? ImapAccountBase::ListFolderOnlySubscribed : ImapAccountBase::ListFolderOnly; completeListing = false; } ListJob* job = new ListJob( ai, type, 0, ai->addPathToNamespace( mCurrentNamespace ), completeListing ); connect( job, SIGNAL(receivedFolders(const QStringList&, const QStringList&, const QStringList&, const QStringList&, const ImapAccountBase::jobData&)), this, SLOT(slotListDirectory(const QStringList&, const QStringList&, const QStringList&, const QStringList&, const ImapAccountBase::jobData&))); job->start(); } void SubscriptionDialogBase::loadingComplete() { slotLoadingComplete(); } //------------------------------------------------------------------------------ // implementation for server side subscription //------------------------------------------------------------------------------ SubscriptionDialog::SubscriptionDialog( QWidget *parent, const QString &caption, KAccount *acct, const QString & startPath ) : SubscriptionDialogBase( parent, caption, acct, startPath ) { } /* virtual */ SubscriptionDialog::~SubscriptionDialog() { } /* virtual */ void SubscriptionDialog::listAllAvailableAndCreateItems() { initPrefixList(); processNext(); } //------------------------------------------------------------------------------ void SubscriptionDialogBase::initPrefixList() { ImapAccountBase* ai = static_cast<ImapAccountBase*>(account()); ImapAccountBase::nsMap map = ai->namespaces(); mPrefixList.clear(); bool hasInbox = false; const QStringList ns = map[ImapAccountBase::PersonalNS]; for ( QStringList::ConstIterator it = ns.begin(); it != ns.end(); ++it ) { if ( (*it).isEmpty() ) hasInbox = true; } if ( !hasInbox && !ns.isEmpty() ) { // the namespaces includes no listing for the root so start a special // listing for the INBOX to make sure we get it mPrefixList += "/INBOX/"; } mPrefixList += map[ImapAccountBase::PersonalNS]; mPrefixList += map[ImapAccountBase::OtherUsersNS]; mPrefixList += map[ImapAccountBase::SharedNS]; } void SubscriptionDialogBase::slotConnectionResult( int errorCode, const QString& errorMsg ) { Q_UNUSED( errorMsg ); if ( !errorCode ) slotLoadFolders(); } bool SubscriptionDialogBase::checkIfSubscriptionsEnabled() { KMail::ImapAccountBase *account = static_cast<KMail::ImapAccountBase*>(mAcct); if( !account ) return true; if( subscriptionOptionEnabled( account ) ) return true; int result = KMessageBox::questionYesNoCancel( this, subscriptionOptionQuestion( account->name() ), i18n("Enable Subscriptions?"), KGuiItem( i18n("Enable") ), KGuiItem( i18n("Do Not Enable") ) ); switch(result) { case KMessageBox::Yes: mForceSubscriptionEnable = true; break; case KMessageBox::No: break; case KMessageBox::Cancel: return false; break; } return true; } void SubscriptionDialogBase::show() { KDialog::show(); checkIfSubscriptionsEnabled(); } // ======= /* virtual */ void SubscriptionDialog::processFolderListing() { processItems(); } /* virtual */ bool SubscriptionDialog::doSave() { if ( !checkIfSubscriptionsEnabled() ) return false; bool somethingHappened = false; // subscribe Q3ListViewItemIterator it(subView); for ( ; it.current(); ++it) { static_cast<ImapAccountBase*>(account())->changeSubscription(true, static_cast<GroupItem*>(it.current())->info().path); somethingHappened = true; } // unsubscribe Q3ListViewItemIterator it2(unsubView); for ( ; it2.current(); ++it2) { static_cast<ImapAccountBase*>(account())->changeSubscription(false, static_cast<GroupItem*>(it2.current())->info().path); somethingHappened = true; } // Slight code duplication with LocalSubscriptionDialog follows! KMail::ImapAccountBase *a = static_cast<KMail::ImapAccountBase*>( mAcct ); if ( mForceSubscriptionEnable ) { a->setOnlySubscribedFolders( true ); } if ( somethingHappened && subscriptionOptionEnabled( a ) ) { kmkernel->acctMgr()->singleCheckMail( a, true ); } return true; } bool SubscriptionDialog::subscriptionOptionEnabled( const KMail::ImapAccountBase *account ) const { return account->onlySubscribedFolders(); } QString SubscriptionDialog::subscriptionOptionQuestion( const QString &accountName ) const { return i18nc( "@info", "Currently subscriptions are not used for server <resource>%1</resource>.<nl/>" "\nDo you want to enable subscriptions?", accountName ); } void SubscriptionDialog::processItems() { bool onlySubscribed = mJobData.onlySubscribed; uint done = 0; for (int i = mCount; i < mFolderNames.count(); ++i) { // give the dialog a chance to repaint if (done == 1000) { emit listChanged(); QTimer::singleShot(0, this, SLOT(processItems())); return; } ++mCount; ++done; if (!onlySubscribed && mFolderPaths.size() > 0) { createListViewItem( i ); } else if (onlySubscribed) { // find the item if ( mItemDict[mFolderPaths[i]] ) { GroupItem* item = mItemDict[mFolderPaths[i]]; item->setOn( true ); } } } processNext(); } } // namespace #include "subscriptiondialog.moc" <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org> Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.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 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. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "datenavigator.h" #include "koglobals.h" #include <kcalendarsystem.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> using namespace KCal; DateNavigator::DateNavigator( QObject *parent ) : QObject( parent ) { mSelectedDates.append( QDate::currentDate() ); } DateNavigator::~DateNavigator() { } DateList DateNavigator::selectedDates() { return mSelectedDates; } int DateNavigator::datesCount() const { return mSelectedDates.count(); } void DateNavigator::selectDates( const DateList &dateList ) { if ( dateList.count() > 0 ) { mSelectedDates = dateList; emitSelected(); } } void DateNavigator::selectDate( const QDate &date ) { QDate d = date; if ( !d.isValid() ) { kDebug() << "an invalid date was passed as a parameter!"; d = QDate::currentDate(); } mSelectedDates.clear(); mSelectedDates.append( d ); emitSelected(); } void DateNavigator::selectDates( int count ) { selectDates( mSelectedDates.first(), count ); } void DateNavigator::selectDates( const QDate &d, int count ) { DateList dates; int i; for ( i = 0; i < count; ++i ) { dates.append( d.addDays( i ) ); } mSelectedDates = dates; emitSelected(); } void DateNavigator::selectWeekByDay( int weekDay, const QDate &d ) { int dateCount = mSelectedDates.count(); bool weekStart = ( weekDay == KGlobal::locale()->weekStartDay() ); if ( weekStart && dateCount == 7 ) { selectWeek( d ); } else { selectDates( d, dateCount ); } } void DateNavigator::selectWeek() { selectWeek( mSelectedDates.first() ); } void DateNavigator::selectWeek( const QDate &d ) { int dayOfWeek = KOGlobals::self()->calendarSystem()->dayOfWeek( d ); int weekStart = KGlobal::locale()->weekStartDay(); QDate firstDate = d.addDays( weekStart - dayOfWeek ); if ( weekStart != 1 && dayOfWeek < weekStart ) { firstDate = firstDate.addDays( -7 ); } selectDates( firstDate, 7 ); } void DateNavigator::selectWorkWeek() { selectWorkWeek( mSelectedDates.first() ); } void DateNavigator::selectWorkWeek( const QDate &d ) { int weekStart = KGlobal::locale()->weekStartDay(); int dayOfWeek = KOGlobals::self()->calendarSystem()->dayOfWeek( d ); QDate currentDate = d.addDays( weekStart - dayOfWeek ); if ( weekStart != 1 && dayOfWeek < weekStart ) { currentDate = currentDate.addDays( -7 ); } mSelectedDates.clear(); int mask = KOGlobals::self()->getWorkWeekMask(); for ( int i = 0; i < 7; ++i ) { if ( ( 1 << ( ( i + weekStart + 6 ) % 7 ) ) & (mask) ) { mSelectedDates.append( currentDate.addDays( i ) ); } } emitSelected(); } void DateNavigator::selectToday() { QDate d = QDate::currentDate(); int dateCount = mSelectedDates.count(); if ( dateCount == 7 ) { selectWeek( d ); } else { selectDates( d, dateCount ); } } void DateNavigator::selectPreviousYear() { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); firstSelected = KOGlobals::self()->calendarSystem()->addYears( firstSelected, -1 ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectPreviousMonth() { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); firstSelected = KOGlobals::self()->calendarSystem()->addMonths( firstSelected, -1 ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectPreviousWeek() { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); firstSelected = KOGlobals::self()->calendarSystem()->addDays( firstSelected, -7 ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectNextWeek() { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); firstSelected = KOGlobals::self()->calendarSystem()->addDays( firstSelected, 7 ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectNextMonth() { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); firstSelected = KOGlobals::self()->calendarSystem()->addMonths( firstSelected, 1 ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectNextYear() { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); firstSelected = KOGlobals::self()->calendarSystem()->addYears( firstSelected, 1 ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectPrevious() { int offset = -7; if ( datesCount() == 1 ) { offset = -1; } selectDates( mSelectedDates.first().addDays( offset ), datesCount() ); } void DateNavigator::selectNext() { int offset = 7; if ( datesCount() == 1 ) { offset = 1; } selectDates( mSelectedDates.first().addDays( offset ), datesCount() ); } void DateNavigator::selectMonth( int month ) { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); const KCalendarSystem *calSys = KOGlobals::self()->calendarSystem(); int day = calSys->day( firstSelected ); calSys->setYMD( firstSelected, calSys->year( firstSelected ), month, 1 ); int days = calSys->daysInMonth( firstSelected ); // As day we use either the selected date, or if the month has less days // than that, we use the max day of that month if ( day > days ) { day = days; } calSys->setYMD( firstSelected, calSys->year( firstSelected ), month, day ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectYear( int year ) { QDate firstSelected = mSelectedDates.first(); int deltaYear = year - KOGlobals::self()->calendarSystem()->year( firstSelected ); firstSelected = KOGlobals::self()->calendarSystem()->addYears( firstSelected, deltaYear ); int weekDay = firstSelected.dayOfWeek(); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::emitSelected() { emit datesSelected( mSelectedDates ); } #include "datenavigator.moc" <commit_msg>When selecting a month from the navigator bar month menu, always direct the view to start at the first week in the month selected.<commit_after>/* This file is part of KOrganizer. Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org> Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.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 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. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "datenavigator.h" #include "koglobals.h" #include <kcalendarsystem.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> using namespace KCal; DateNavigator::DateNavigator( QObject *parent ) : QObject( parent ) { mSelectedDates.append( QDate::currentDate() ); } DateNavigator::~DateNavigator() { } DateList DateNavigator::selectedDates() { return mSelectedDates; } int DateNavigator::datesCount() const { return mSelectedDates.count(); } void DateNavigator::selectDates( const DateList &dateList ) { if ( dateList.count() > 0 ) { mSelectedDates = dateList; emitSelected(); } } void DateNavigator::selectDate( const QDate &date ) { QDate d = date; if ( !d.isValid() ) { kDebug() << "an invalid date was passed as a parameter!"; d = QDate::currentDate(); } mSelectedDates.clear(); mSelectedDates.append( d ); emitSelected(); } void DateNavigator::selectDates( int count ) { selectDates( mSelectedDates.first(), count ); } void DateNavigator::selectDates( const QDate &d, int count ) { DateList dates; int i; for ( i = 0; i < count; ++i ) { dates.append( d.addDays( i ) ); } mSelectedDates = dates; emitSelected(); } void DateNavigator::selectWeekByDay( int weekDay, const QDate &d ) { int dateCount = mSelectedDates.count(); bool weekStart = ( weekDay == KGlobal::locale()->weekStartDay() ); if ( weekStart && dateCount == 7 ) { selectWeek( d ); } else { selectDates( d, dateCount ); } } void DateNavigator::selectWeek() { selectWeek( mSelectedDates.first() ); } void DateNavigator::selectWeek( const QDate &d ) { int dayOfWeek = KOGlobals::self()->calendarSystem()->dayOfWeek( d ); int weekStart = KGlobal::locale()->weekStartDay(); QDate firstDate = d.addDays( weekStart - dayOfWeek ); if ( weekStart != 1 && dayOfWeek < weekStart ) { firstDate = firstDate.addDays( -7 ); } selectDates( firstDate, 7 ); } void DateNavigator::selectWorkWeek() { selectWorkWeek( mSelectedDates.first() ); } void DateNavigator::selectWorkWeek( const QDate &d ) { int weekStart = KGlobal::locale()->weekStartDay(); int dayOfWeek = KOGlobals::self()->calendarSystem()->dayOfWeek( d ); QDate currentDate = d.addDays( weekStart - dayOfWeek ); if ( weekStart != 1 && dayOfWeek < weekStart ) { currentDate = currentDate.addDays( -7 ); } mSelectedDates.clear(); int mask = KOGlobals::self()->getWorkWeekMask(); for ( int i = 0; i < 7; ++i ) { if ( ( 1 << ( ( i + weekStart + 6 ) % 7 ) ) & (mask) ) { mSelectedDates.append( currentDate.addDays( i ) ); } } emitSelected(); } void DateNavigator::selectToday() { QDate d = QDate::currentDate(); int dateCount = mSelectedDates.count(); if ( dateCount == 7 ) { selectWeek( d ); } else { selectDates( d, dateCount ); } } void DateNavigator::selectPreviousYear() { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); firstSelected = KOGlobals::self()->calendarSystem()->addYears( firstSelected, -1 ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectPreviousMonth() { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); firstSelected = KOGlobals::self()->calendarSystem()->addMonths( firstSelected, -1 ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectPreviousWeek() { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); firstSelected = KOGlobals::self()->calendarSystem()->addDays( firstSelected, -7 ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectNextWeek() { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); firstSelected = KOGlobals::self()->calendarSystem()->addDays( firstSelected, 7 ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectNextMonth() { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); firstSelected = KOGlobals::self()->calendarSystem()->addMonths( firstSelected, 1 ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectNextYear() { QDate firstSelected = mSelectedDates.first(); int weekDay = firstSelected.dayOfWeek(); firstSelected = KOGlobals::self()->calendarSystem()->addYears( firstSelected, 1 ); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::selectPrevious() { int offset = -7; if ( datesCount() == 1 ) { offset = -1; } selectDates( mSelectedDates.first().addDays( offset ), datesCount() ); } void DateNavigator::selectNext() { int offset = 7; if ( datesCount() == 1 ) { offset = 1; } selectDates( mSelectedDates.first().addDays( offset ), datesCount() ); } void DateNavigator::selectMonth( int month ) { // always display starting at the first week of the specified month QDate firstSelected = QDate( mSelectedDates.first().year(), month, 1 ); const KCalendarSystem *calSys = KOGlobals::self()->calendarSystem(); int day = calSys->day( firstSelected ); calSys->setYMD( firstSelected, calSys->year( firstSelected ), month, 1 ); int days = calSys->daysInMonth( firstSelected ); // As day we use either the selected date, or if the month has less days // than that, we use the max day of that month if ( day > days ) { day = days; } calSys->setYMD( firstSelected, calSys->year( firstSelected ), month, day ); selectWeekByDay( 1, firstSelected ); } void DateNavigator::selectYear( int year ) { QDate firstSelected = mSelectedDates.first(); int deltaYear = year - KOGlobals::self()->calendarSystem()->year( firstSelected ); firstSelected = KOGlobals::self()->calendarSystem()->addYears( firstSelected, deltaYear ); int weekDay = firstSelected.dayOfWeek(); selectWeekByDay( weekDay, firstSelected ); } void DateNavigator::emitSelected() { emit datesSelected( mSelectedDates ); } #include "datenavigator.moc" <|endoftext|>
<commit_before>#include "builder.h" #include <lambda_p_io/source.h> #include <lambda_p_io/builder.h> #include <lambda_p/routine.h> #include <lambda_p/expression.h> #include <lambda_p/reference.h> #include <lambda_p/expression.h> #include <boost/bind.hpp> void lambda_p_io_test::builder::run () { run_1 (); run_2 (); run_3 (); } void lambda_p_io_test::builder::run_1 () { lambda_p_io::builder builder; lambda_p_io::source source (boost::bind (&lambda_p_io::lexer::lexer::operator(), &builder.lexer, _1)); source (L"[:~]"); source (); assert (builder.errors->errors.empty ()); assert (builder.routines.size () == 1); auto routine (builder.routines [0]); assert (routine->body->dependencies.size () == 1); assert (routine->body->dependencies [0] == routine->parameters); assert (routine->parameters->dependencies.size () == 0); } void lambda_p_io_test::builder::run_2 () { lambda_p_io::builder builder; lambda_p_io::source source (boost::bind (&lambda_p_io::lexer::lexer::operator(), &builder.lexer, _1)); source (L"[:~]"); source (L"[:~]"); assert (builder.errors->errors.empty ()); assert (builder.routines.size () == 2); } void lambda_p_io_test::builder::run_3 () { lambda_p_io::builder builder; lambda_p_io::source source (boost::bind (&lambda_p_io::lexer::lexer::operator(), &builder.lexer, _1)); source (L"[[:~; a b c] a [a b c] c]"); assert (builder.errors->errors.empty ()); assert (builder.routines.size () == 1); auto routine (builder.routines [0]); assert (routine->body->dependencies.size () == 3); auto d1 (boost::dynamic_pointer_cast <lambda_p::reference> (routine->body->dependencies [0])); assert (d1.get () != nullptr); auto d2 (boost::dynamic_pointer_cast <lambda_p::expression> (routine->body->dependencies [1])); assert (d2.get () != nullptr); auto d3 (boost::dynamic_pointer_cast <lambda_p::reference> (routine->body->dependencies [2])); assert (d3.get () != nullptr); auto d11 (boost::dynamic_pointer_cast <lambda_p::expression> (d1->expression)); assert (d11.get () != nullptr); assert (d1->index == 0); assert (d11->dependencies.size () == 1); assert (d11->dependencies [0] == routine->parameters); assert (d2->dependencies.size () == 3); auto d21 (boost::dynamic_pointer_cast <lambda_p::reference> (d2->dependencies [0])); assert (d21.get () != nullptr); assert (d21->expression == d11); assert (d21->index == 0); auto d22 (boost::dynamic_pointer_cast <lambda_p::reference> (d2->dependencies [1])); assert (d22.get () != nullptr); assert (d22->expression == d11); assert (d22->index == 1); auto d23 (boost::dynamic_pointer_cast <lambda_p::reference> (d2->dependencies [2])); assert (d23.get () != nullptr); assert (d23->expression == d11); assert (d23->index == 2); assert (d3->expression == d11); assert (d3->index == 2); }<commit_msg>Added context tests for builder.<commit_after>#include "builder.h" #include <lambda_p_io/source.h> #include <lambda_p_io/builder.h> #include <lambda_p/routine.h> #include <lambda_p/expression.h> #include <lambda_p/reference.h> #include <lambda_p/expression.h> #include <boost/bind.hpp> void lambda_p_io_test::builder::run () { run_1 (); run_2 (); run_3 (); } void lambda_p_io_test::builder::run_1 () { lambda_p_io::builder builder; lambda_p_io::source source (boost::bind (&lambda_p_io::lexer::lexer::operator(), &builder.lexer, _1)); source (L"[:~]"); source (); assert (builder.errors->errors.empty ()); assert (builder.routines.size () == 1); auto routine (builder.routines [0]); assert (routine->body->dependencies.size () == 1); assert (routine->body->dependencies [0] == routine->parameters); assert (routine->parameters->dependencies.size () == 0); assert (routine->parameters->context == lambda_p::context (1, 1, 0, 1, 1, 0)); assert (routine->body->context == lambda_p::context (1, 1, 0, 1, 4, 3)); } void lambda_p_io_test::builder::run_2 () { lambda_p_io::builder builder; lambda_p_io::source source (boost::bind (&lambda_p_io::lexer::lexer::operator(), &builder.lexer, _1)); source (L"[:~]"); source (L"[:~]"); assert (builder.errors->errors.empty ()); assert (builder.routines.size () == 2); auto routine1 (builder.routines [0]); auto routine2 (builder.routines [1]); assert (routine1->parameters->context == lambda_p::context (1, 1, 0, 1, 1, 0)); assert (routine1->body->context == lambda_p::context (1, 1, 0, 1, 4, 3)); assert (routine2->parameters->context == lambda_p::context (1, 5, 4, 1, 5, 4)); assert (routine2->body->context == lambda_p::context (1, 5, 4, 1, 8, 7)); } void lambda_p_io_test::builder::run_3 () { lambda_p_io::builder builder; lambda_p_io::source source (boost::bind (&lambda_p_io::lexer::lexer::operator(), &builder.lexer, _1)); source (L"[[:~; a b c] a [a b c] c]"); assert (builder.errors->errors.empty ()); assert (builder.routines.size () == 1); auto routine (builder.routines [0]); assert (routine->body->context == lambda_p::context (1, 1, 0, 1, 25, 24)); assert (routine->body->dependencies.size () == 3); auto d1 (boost::dynamic_pointer_cast <lambda_p::reference> (routine->body->dependencies [0])); assert (d1.get () != nullptr); auto d2 (boost::dynamic_pointer_cast <lambda_p::expression> (routine->body->dependencies [1])); assert (d2.get () != nullptr); assert (d2->context == lambda_p::context (1, 16, 15, 1, 22, 21)); auto d3 (boost::dynamic_pointer_cast <lambda_p::reference> (routine->body->dependencies [2])); assert (d3.get () != nullptr); auto d11 (boost::dynamic_pointer_cast <lambda_p::expression> (d1->expression)); assert (d11.get () != nullptr); assert (d11->context == lambda_p::context (1, 2, 1, 1, 12, 11)); assert (d1->index == 0); assert (d11->dependencies.size () == 1); assert (d11->dependencies [0] == routine->parameters); assert (d2->dependencies.size () == 3); auto d21 (boost::dynamic_pointer_cast <lambda_p::reference> (d2->dependencies [0])); assert (d21.get () != nullptr); assert (d21->expression == d11); assert (d21->index == 0); auto d22 (boost::dynamic_pointer_cast <lambda_p::reference> (d2->dependencies [1])); assert (d22.get () != nullptr); assert (d22->expression == d11); assert (d22->index == 1); auto d23 (boost::dynamic_pointer_cast <lambda_p::reference> (d2->dependencies [2])); assert (d23.get () != nullptr); assert (d23->expression == d11); assert (d23->index == 2); assert (d3->expression == d11); assert (d3->index == 2); }<|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: HBondModel.C,v 1.3 2003/10/17 16:17:36 amoll Exp $ #include <BALL/VIEW/MODELS/HBondModel.h> #include <BALL/KERNEL/atom.h> #include <BALL/VIEW/PRIMITIVES/tube.h> using namespace std; namespace BALL { namespace VIEW { HBondModelProcessor::HBondModelProcessor() throw() : AtomBondModelBaseProcessor() { } HBondModelProcessor::HBondModelProcessor(const HBondModelProcessor& model) throw() : AtomBondModelBaseProcessor(model) { } HBondModelProcessor::~HBondModelProcessor() throw() { #ifdef BALL_VIEW_DEBUG Log.info() << "Destructing object " << (void *)this << " of class " << RTTI::getName<HBondModelProcessor>() << std::endl; #endif } void HBondModelProcessor::clear() throw() { AtomBondModelBaseProcessor::clear(); } void HBondModelProcessor::set(const HBondModelProcessor& model) throw() { AtomBondModelBaseProcessor::set(model); } const HBondModelProcessor &HBondModelProcessor::operator = (const HBondModelProcessor& model) throw() { set(model); return *this; } void HBondModelProcessor::swap(HBondModelProcessor& model) throw() { AtomBondModelBaseProcessor::swap(model); } bool HBondModelProcessor::finish() { return true; } Processor::Result HBondModelProcessor::operator() (Composite& composite) { if (!RTTI::isKindOf<Atom>(composite) || !((Atom*)&composite)->hasProperty("HBOND_DONOR")) { return Processor::CONTINUE; } Atom *atom = RTTI::castTo<Atom>(composite); Atom* partner = (Atom*) atom->getProperty("HBOND_DONOR").getObject(); if (!partner) return Processor::CONTINUE; // generate single colored tube Tube *tube = new Tube; if (tube == 0) throw Exception::OutOfMemory (__FILE__, __LINE__, sizeof(Tube)); tube->setRadius(0.3); tube->setComposite(atom); tube->setVertex1Address(atom->getPosition()); tube->setVertex2Address(partner->getPosition()); tube->setColor(ColorRGBA(0.0,0,0.5)); geometric_objects_.push_back(tube); return Processor::CONTINUE; } } } // namespaces <commit_msg>added radius_ modified: now using muliple tubes per bond<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: HBondModel.C,v 1.4 2003/11/10 15:55:09 amoll Exp $ #include <BALL/VIEW/MODELS/HBondModel.h> #include <BALL/KERNEL/atom.h> #include <BALL/VIEW/PRIMITIVES/tube.h> #include <BALL/VIEW/PRIMITIVES/disc.h> using namespace std; namespace BALL { namespace VIEW { HBondModelProcessor::HBondModelProcessor() throw() : AtomBondModelBaseProcessor(), radius_(0.3) { } HBondModelProcessor::HBondModelProcessor(const HBondModelProcessor& model) throw() : AtomBondModelBaseProcessor(model), radius_(model.radius_) { } HBondModelProcessor::~HBondModelProcessor() throw() { #ifdef BALL_VIEW_DEBUG Log.info() << "Destructing object " << (void *)this << " of class " << RTTI::getName<HBondModelProcessor>() << std::endl; #endif } void HBondModelProcessor::clear() throw() { AtomBondModelBaseProcessor::clear(); radius_ = 0.3; } void HBondModelProcessor::set(const HBondModelProcessor& model) throw() { AtomBondModelBaseProcessor::set(model); } const HBondModelProcessor &HBondModelProcessor::operator = (const HBondModelProcessor& model) throw() { set(model); return *this; } void HBondModelProcessor::swap(HBondModelProcessor& model) throw() { AtomBondModelBaseProcessor::swap(model); } bool HBondModelProcessor::finish() { return true; } Processor::Result HBondModelProcessor::operator() (Composite& composite) { if (!RTTI::isKindOf<Atom>(composite) || !((Atom*)&composite)->hasProperty("HBOND_DONOR")) { return Processor::CONTINUE; } Atom *atom = RTTI::castTo<Atom>(composite); Atom* partner = (Atom*) atom->getProperty("HBOND_DONOR").getObject(); if (!partner) return Processor::CONTINUE; // generate tubes Vector3 v = partner->getPosition() - atom->getPosition(); Vector3 last = atom->getPosition() + v / 4.5; for (Position p = 0; p < 3; p++) { Tube *tube = new Tube; if (tube == 0) throw Exception::OutOfMemory (__FILE__, __LINE__, sizeof(Tube)); tube->setRadius(radius_); tube->setComposite(atom); tube->setVertex1(last); tube->setVertex2(last + (v / 8)); geometric_objects_.push_back(tube); Disc* disc = new Disc(Circle3(last, v, radius_)); if (!disc) throw Exception::OutOfMemory (__FILE__, __LINE__, sizeof(Disc)); disc->setComposite(atom); geometric_objects_.push_back(disc); disc = new Disc(Circle3(last + (v / 8), v, radius_)); if (!disc) throw Exception::OutOfMemory (__FILE__, __LINE__, sizeof(Disc)); disc->setComposite(atom); geometric_objects_.push_back(disc); last += (v /4); } return Processor::CONTINUE; } } } // namespaces <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // Author: Steven Lamerton // Copyright: 2013 Steven Lamerton // License: MIT, see LICENSE /////////////////////////////////////////////////////////////////////////////// #include <vector> #include <iostream> #include <fstream> #include <png.h> #include "output.h" #include "dla.h" struct rgb { int r, g, b; }; rgb get_colour(int age) { rgb ret; double h = (age % 36000) / 6000.0, i, f, r, g, b; f = std::modf(h, &i); if(age == 0) { ret.r = 0; ret.g = 0; ret.b = 0; return ret; } if(i == 0) { r = 1; g = f; b = 0; } if(i == 1) { r = 1 - f; g = 1; b = 0; } if(i == 2) { r = 0; g = 1; b = f; } if(i == 3) { r = 0; g = 1 - f; b = 1; } if(i == 4) { r = f; g = 0; b = 1; } if(i == 5) { r = 1; g = 0; b = 1 - f; } ret.r = r * 255; ret.g = g * 255; ret.b = b * 255; return ret; } void to_png(const std::vector<std::vector<cell>> &grid, const std::string &name) { FILE* file; png_structp write_struct; png_infop info_struct; std::vector<unsigned char> data; std::string fullname = name + ".png"; file = fopen(fullname.c_str(), "wb"); if(!file) goto finish; write_struct = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if(!write_struct) goto finish; info_struct = png_create_info_struct(write_struct); if(!info_struct) goto finish; if(setjmp(png_jmpbuf(write_struct))) goto finish; png_init_io(write_struct, file); // We write in 8 byte RGB format png_set_IHDR(write_struct, info_struct, grid.size(), grid.size(), 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(write_struct, info_struct); for(auto i : grid) { data.clear(); for(auto j : i) { rgb val = get_colour(j.age); data.push_back(val.r); data.push_back(val.g); data.push_back(val.b); } png_write_row(write_struct, data.data()); } png_write_end(write_struct, NULL); finish: if(file) fclose(file); if(info_struct) png_free_data(write_struct, info_struct, PNG_FREE_ALL, -1); if(write_struct) png_destroy_write_struct(&write_struct, NULL); } void to_screen(const std::vector<std::vector<cell>> &grid) { for(auto i : grid) { for(auto j : i) { if(j.particle) std::cout << j.particle; else std::cout << " "; } std::cout << std::endl; } } <commit_msg>Add some detail about the colour creation<commit_after>/////////////////////////////////////////////////////////////////////////////// // Author: Steven Lamerton // Copyright: 2013 Steven Lamerton // License: MIT, see LICENSE /////////////////////////////////////////////////////////////////////////////// #include <vector> #include <iostream> #include <fstream> #include <png.h> #include "output.h" #include "dla.h" struct rgb { int r, g, b; }; rgb get_colour(int age) { rgb ret; // Scale the output to give a smoother gradient double h = (age % 36000) / 6000.0, i, f, r, g, b; f = std::modf(h, &i); if(age == 0) { ret.r = 0; ret.g = 0; ret.b = 0; return ret; } // Perform a hsv -> rgb conversion with v = s = 1 if(i == 0) { r = 1; g = f; b = 0; } if(i == 1) { r = 1 - f; g = 1; b = 0; } if(i == 2) { r = 0; g = 1; b = f; } if(i == 3) { r = 0; g = 1 - f; b = 1; } if(i == 4) { r = f; g = 0; b = 1; } if(i == 5) { r = 1; g = 0; b = 1 - f; } // Scale the output to 8 byte triplet ret.r = r * 255; ret.g = g * 255; ret.b = b * 255; return ret; } void to_png(const std::vector<std::vector<cell>> &grid, const std::string &name) { FILE* file; png_structp write_struct; png_infop info_struct; std::vector<unsigned char> data; std::string fullname = name + ".png"; file = fopen(fullname.c_str(), "wb"); if(!file) goto finish; write_struct = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if(!write_struct) goto finish; info_struct = png_create_info_struct(write_struct); if(!info_struct) goto finish; if(setjmp(png_jmpbuf(write_struct))) goto finish; png_init_io(write_struct, file); // We write in 8 byte RGB format png_set_IHDR(write_struct, info_struct, grid.size(), grid.size(), 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(write_struct, info_struct); for(auto i : grid) { data.clear(); for(auto j : i) { rgb val = get_colour(j.age); data.push_back(val.r); data.push_back(val.g); data.push_back(val.b); } png_write_row(write_struct, data.data()); } png_write_end(write_struct, NULL); finish: if(file) fclose(file); if(info_struct) png_free_data(write_struct, info_struct, PNG_FREE_ALL, -1); if(write_struct) png_destroy_write_struct(&write_struct, NULL); } void to_screen(const std::vector<std::vector<cell>> &grid) { for(auto i : grid) { for(auto j : i) { if(j.particle) std::cout << j.particle; else std::cout << " "; } std::cout << std::endl; } } <|endoftext|>
<commit_before> #include <glbinding/gl/gl.h> #include <globjects/globjects.h> #include <globjects/logging.h> #include <globjects/Buffer.h> #include <globjects/Program.h> #include <globjects/Shader.h> #include <globjects/VertexArray.h> #include <globjects/VertexAttributeBinding.h> #include <globjects/State.h> #include <common/Context.h> #include <common/ContextFormat.h> #include <common/Window.h> #include <common/WindowEventHandler.h> #include <common/events.h> using namespace gl; using namespace glm; using namespace globjects; class EventHandler : public WindowEventHandler { public: EventHandler() { } virtual ~EventHandler() { } virtual void initialize(Window & window) override { WindowEventHandler::initialize(window); glClearColor(0.2f, 0.3f, 0.4f, 1.f); m_defaultPointSizeState = new State(); m_defaultPointSizeState->pointSize(getFloat(GL_POINT_SIZE)); m_thinnestPointSizeState = new State(); m_thinnestPointSizeState->pointSize(2.0f); m_thinPointSizeState = new State(); m_thinPointSizeState->pointSize(5.0f); m_normalPointSizeState = new State(); m_normalPointSizeState->pointSize(10.0f); m_thickPointSizeState = new State(); m_thickPointSizeState->pointSize(20.0f); m_disableRasterizerState = new State(); m_disableRasterizerState->enable(GL_RASTERIZER_DISCARD); m_enableRasterizerState = new State(); m_enableRasterizerState->disable(GL_RASTERIZER_DISCARD); m_vao = new VertexArray(); m_buffer = new Buffer(); m_shaderProgram = new Program(); m_shaderProgram->attach( Shader::fromFile(GL_VERTEX_SHADER, "data/states/standard.vert") , Shader::fromFile(GL_FRAGMENT_SHADER, "data/states/standard.frag")); m_buffer->setData(std::vector<vec2>({ vec2(-0.8f, 0.8f), vec2(-0.4f, 0.8f), vec2( 0.0f, 0.8f), vec2( 0.4f, 0.8f), vec2( 0.8f, 0.8f) , vec2(-0.8f, 0.6f), vec2(-0.4f, 0.6f), vec2( 0.0f, 0.6f), vec2( 0.4f, 0.6f), vec2( 0.8f, 0.6f) , vec2(-0.8f, 0.4f), vec2(-0.4f, 0.4f), vec2( 0.0f, 0.4f), vec2( 0.4f, 0.4f), vec2( 0.8f, 0.4f) , vec2(-0.8f, 0.2f), vec2(-0.4f, 0.2f), vec2( 0.0f, 0.2f), vec2( 0.4f, 0.2f), vec2( 0.8f, 0.2f) , vec2(-0.8f, 0.0f), vec2(-0.4f, 0.0f), vec2( 0.0f, 0.0f), vec2( 0.4f, 0.0f), vec2( 0.8f, 0.0f) , vec2(-0.8f,-0.2f), vec2(-0.4f,-0.2f), vec2( 0.0f,-0.2f), vec2( 0.4f,-0.2f), vec2( 0.8f,-0.2f) , vec2(-0.8f,-0.4f), vec2(-0.4f,-0.4f), vec2( 0.0f,-0.4f), vec2( 0.4f,-0.4f), vec2( 0.8f,-0.4f) , vec2(-0.8f,-0.6f), vec2(-0.4f,-0.6f), vec2( 0.0f,-0.6f), vec2( 0.4f,-0.6f), vec2( 0.8f,-0.6f) , vec2(-0.8f,-0.8f), vec2(-0.4f,-0.8f), vec2( 0.0f,-0.8f), vec2( 0.4f,-0.8f), vec2( 0.8f,-0.8f) }) , GL_STATIC_DRAW ); m_vao->binding(0)->setAttribute(0); m_vao->binding(0)->setBuffer(m_buffer, 0, sizeof(vec2)); m_vao->binding(0)->setFormat(2, GL_FLOAT); m_vao->enable(0); } virtual void paintEvent(PaintEvent & event) override { WindowEventHandler::paintEvent(event); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_shaderProgram->use(); m_defaultPointSizeState->apply(); m_vao->drawArrays(GL_POINTS, 0, 5); m_thinnestPointSizeState->apply(); m_vao->drawArrays(GL_POINTS, 5, 5); m_thinPointSizeState->apply(); m_vao->drawArrays(GL_POINTS, 10, 5); m_normalPointSizeState->apply(); m_vao->drawArrays(GL_POINTS, 15, 5); m_thickPointSizeState->apply(); m_vao->drawArrays(GL_POINTS, 20, 1); m_disableRasterizerState->apply(); m_vao->drawArrays(GL_POINTS, 21, 1); m_enableRasterizerState->apply(); m_vao->drawArrays(GL_POINTS, 22, 1); m_disableRasterizerState->apply(); m_vao->drawArrays(GL_POINTS, 23, 1); m_enableRasterizerState->apply(); m_vao->drawArrays(GL_POINTS, 24, 1); m_normalPointSizeState->apply(); m_vao->drawArrays(GL_POINTS, 25, 5); m_thinPointSizeState->apply(); m_vao->drawArrays(GL_POINTS, 30, 5); m_thinnestPointSizeState->apply(); m_vao->drawArrays(GL_POINTS, 35, 5); m_defaultPointSizeState->apply(); m_vao->drawArrays(GL_POINTS, 35, 5); m_shaderProgram->release(); } protected: ref_ptr<VertexArray> m_vao; ref_ptr<Buffer> m_buffer; ref_ptr<Program> m_shaderProgram; ref_ptr<State> m_defaultPointSizeState; ref_ptr<State> m_thinnestPointSizeState; ref_ptr<State> m_thinPointSizeState; ref_ptr<State> m_normalPointSizeState; ref_ptr<State> m_thickPointSizeState; ref_ptr<State> m_disableRasterizerState; ref_ptr<State> m_enableRasterizerState; }; int main(int /*argc*/, char * /*argv*/[]) { info() << "Usage:"; info() << "\t" << "ESC" << "\t\t" << "Close example"; info() << "\t" << "ALT + Enter" << "\t" << "Toggle fullscreen"; info() << "\t" << "F11" << "\t\t" << "Toggle fullscreen"; info() << "\t" << "F10" << "\t\t" << "Toggle vertical sync"; ContextFormat format; format.setVersion(3, 1); format.setForwardCompatible(true); Window::init(); Window window; window.setEventHandler(new EventHandler()); if (!window.create(format, "OpenGL States Example")) return 1; window.show(); return MainLoop::run(); } <commit_msg>Rewrite states example to not use the common module anymore. #291<commit_after> #include <glm/glm.hpp> #include <glbinding/gl/gl.h> #include <glbinding/ContextInfo.h> #include <glbinding/Version.h> #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #include <globjects/globjects.h> #include <globjects/logging.h> #include <globjects/Buffer.h> #include <globjects/Program.h> #include <globjects/Shader.h> #include <globjects/VertexArray.h> #include <globjects/VertexAttributeBinding.h> #include <globjects/State.h> using namespace gl; using namespace glm; using namespace globjects; void key_callback(GLFWwindow * window, int key, int /*scancode*/, int action, int /*modes*/) { if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) glfwSetWindowShouldClose(window, true); } void draw(Program * shaderProgram, VertexArray * vao, State * thinnestPointSizeState, State * thinPointSizeState, State * normalPointSizeState, State * thickPointSizeState, State * disableRasterizerState, State * enableRasterizerState, State * defaultPointSizeState) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shaderProgram->use(); defaultPointSizeState->apply(); vao->drawArrays(GL_POINTS, 0, 5); thinnestPointSizeState->apply(); vao->drawArrays(GL_POINTS, 5, 5); thinPointSizeState->apply(); vao->drawArrays(GL_POINTS, 10, 5); normalPointSizeState->apply(); vao->drawArrays(GL_POINTS, 15, 5); thickPointSizeState->apply(); vao->drawArrays(GL_POINTS, 20, 1); disableRasterizerState->apply(); vao->drawArrays(GL_POINTS, 21, 1); enableRasterizerState->apply(); vao->drawArrays(GL_POINTS, 22, 1); disableRasterizerState->apply(); vao->drawArrays(GL_POINTS, 23, 1); enableRasterizerState->apply(); vao->drawArrays(GL_POINTS, 24, 1); normalPointSizeState->apply(); vao->drawArrays(GL_POINTS, 25, 5); thinPointSizeState->apply(); vao->drawArrays(GL_POINTS, 30, 5); thinnestPointSizeState->apply(); vao->drawArrays(GL_POINTS, 35, 5); defaultPointSizeState->apply(); vao->drawArrays(GL_POINTS, 35, 5); shaderProgram->release(); } int main(int /*argc*/, char * /*argv*/[]) { // Initialize GLFW with error callback and needed OpenGL version window hint glfwInit(); glfwSetErrorCallback( [] (int /*error*/, const char * description) { puts(description); } ); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); // Create a context and, if valid, make it current GLFWwindow * window = glfwCreateWindow(1024, 768, "", NULL, NULL); if (window == nullptr) { critical() << "Context creation failed. Terminate execution."; glfwTerminate(); return 1; } glfwMakeContextCurrent(window); // Create callback that when user presses ESC, the context should be destroyed and window closed glfwSetKeyCallback(window, key_callback); // Initialize globjects (internally initializes glbinding, and registers the current context) globjects::init(); // Dump information about context and graphics card info() << std::endl << "OpenGL Version: " << glbinding::ContextInfo::version() << std::endl << "OpenGL Vendor: " << glbinding::ContextInfo::vendor() << std::endl << "OpenGL Renderer: " << glbinding::ContextInfo::renderer() << std::endl; glClearColor(0.2f, 0.3f, 0.4f, 1.f); { // Initialize ref_ptr<State> defaultPointSizeState = new State(); defaultPointSizeState->pointSize(getFloat(GL_POINT_SIZE)); ref_ptr<State> thinnestPointSizeState = new State(); thinnestPointSizeState->pointSize(2.0f); ref_ptr<State> thinPointSizeState = new State(); thinPointSizeState->pointSize(5.0f); ref_ptr<State> normalPointSizeState = new State(); normalPointSizeState->pointSize(10.0f); ref_ptr<State> thickPointSizeState = new State(); thickPointSizeState->pointSize(20.0f); ref_ptr<State> disableRasterizerState = new State(); disableRasterizerState->enable(GL_RASTERIZER_DISCARD); ref_ptr<State> enableRasterizerState = new State(); enableRasterizerState->disable(GL_RASTERIZER_DISCARD); ref_ptr<VertexArray> vao = new VertexArray(); ref_ptr<Buffer> buffer = new Buffer(); ref_ptr<Program> shaderProgram = new Program(); shaderProgram->attach( Shader::fromFile(GL_VERTEX_SHADER, "data/states/standard.vert") , Shader::fromFile(GL_FRAGMENT_SHADER, "data/states/standard.frag")); buffer->setData(std::vector<vec2>({ vec2(-0.8f, 0.8f), vec2(-0.4f, 0.8f), vec2( 0.0f, 0.8f), vec2( 0.4f, 0.8f), vec2( 0.8f, 0.8f) , vec2(-0.8f, 0.6f), vec2(-0.4f, 0.6f), vec2( 0.0f, 0.6f), vec2( 0.4f, 0.6f), vec2( 0.8f, 0.6f) , vec2(-0.8f, 0.4f), vec2(-0.4f, 0.4f), vec2( 0.0f, 0.4f), vec2( 0.4f, 0.4f), vec2( 0.8f, 0.4f) , vec2(-0.8f, 0.2f), vec2(-0.4f, 0.2f), vec2( 0.0f, 0.2f), vec2( 0.4f, 0.2f), vec2( 0.8f, 0.2f) , vec2(-0.8f, 0.0f), vec2(-0.4f, 0.0f), vec2( 0.0f, 0.0f), vec2( 0.4f, 0.0f), vec2( 0.8f, 0.0f) , vec2(-0.8f,-0.2f), vec2(-0.4f,-0.2f), vec2( 0.0f,-0.2f), vec2( 0.4f,-0.2f), vec2( 0.8f,-0.2f) , vec2(-0.8f,-0.4f), vec2(-0.4f,-0.4f), vec2( 0.0f,-0.4f), vec2( 0.4f,-0.4f), vec2( 0.8f,-0.4f) , vec2(-0.8f,-0.6f), vec2(-0.4f,-0.6f), vec2( 0.0f,-0.6f), vec2( 0.4f,-0.6f), vec2( 0.8f,-0.6f) , vec2(-0.8f,-0.8f), vec2(-0.4f,-0.8f), vec2( 0.0f,-0.8f), vec2( 0.4f,-0.8f), vec2( 0.8f,-0.8f) }) , GL_STATIC_DRAW ); vao->binding(0)->setAttribute(0); vao->binding(0)->setBuffer(buffer, 0, sizeof(vec2)); vao->binding(0)->setFormat(2, GL_FLOAT); vao->enable(0); // Main loop while (!glfwWindowShouldClose(window)) { glfwPollEvents(); draw(shaderProgram, vao, thinnestPointSizeState, thinPointSizeState, normalPointSizeState, thickPointSizeState, disableRasterizerState, enableRasterizerState, defaultPointSizeState); glfwSwapBuffers(window); } } // Properly shutdown GLFW glfwTerminate(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: impdel.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-04-11 17:57:31 $ * * 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 _VCL_IMPDEL_HXX #define _VCL_IMPDEL_HXX #include <list> namespace vcl { class DeletionListener; class DeletionNotifier { std::list< DeletionListener* > m_aListeners; protected: DeletionNotifier() {} ~DeletionNotifier() { notifyDelete(); } inline void notifyDelete(); public: void addDel( DeletionListener* pListener ) { m_aListeners.push_back( pListener ); } void removeDel( DeletionListener* pListener ) { m_aListeners.remove( pListener ); } }; class DeletionListener { DeletionNotifier* m_pNotifier; public: DeletionListener( DeletionNotifier* pNotifier ) : m_pNotifier( pNotifier ) { if( m_pNotifier ) m_pNotifier->addDel( this ); } ~DeletionListener() { if( m_pNotifier ) m_pNotifier->removeDel( this ); } void deleted() { m_pNotifier = NULL; } bool isDeleted() { return m_pNotifier == NULL; } }; inline void DeletionNotifier::notifyDelete() { for( std::list< DeletionListener* >::const_iterator it = m_aListeners.begin(); it != m_aListeners.end(); ++it ) (*it)->deleted(); m_aListeners.clear(); } } // namespace vcl #endif // _VCL_IMPDEL_HXX <commit_msg>INTEGRATION: CWS vcl82 (1.2.126); FILE MERGED 2007/09/03 11:40:21 hdu 1.2.126.1: #146377# add dogtags in wnt's ImplSalShow()<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: impdel.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2007-09-26 15:05:42 $ * * 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 _VCL_IMPDEL_HXX #define _VCL_IMPDEL_HXX #include <list> namespace vcl { class DeletionListener; class DeletionNotifier { std::list< DeletionListener* > m_aListeners; protected: DeletionNotifier() {} ~DeletionNotifier() { notifyDelete(); } inline void notifyDelete(); public: void addDel( DeletionListener* pListener ) { m_aListeners.push_back( pListener ); } void removeDel( DeletionListener* pListener ) { m_aListeners.remove( pListener ); } }; class DeletionListener { DeletionNotifier* m_pNotifier; public: DeletionListener( DeletionNotifier* pNotifier ) : m_pNotifier( pNotifier ) { if( m_pNotifier ) m_pNotifier->addDel( this ); } ~DeletionListener() { if( m_pNotifier ) m_pNotifier->removeDel( this ); } void deleted() { m_pNotifier = NULL; } bool isDeleted() const { return (m_pNotifier == NULL); } }; inline void DeletionNotifier::notifyDelete() { for( std::list< DeletionListener* >::const_iterator it = m_aListeners.begin(); it != m_aListeners.end(); ++it ) (*it)->deleted(); m_aListeners.clear(); } } // namespace vcl #endif // _VCL_IMPDEL_HXX <|endoftext|>
<commit_before>//===--- ModuleNameLookup.cpp - Name lookup within a module ----*- c++ -*--===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "ModuleNameLookup.h" #include "swift/AST/AST.h" #include "swift/AST/LazyResolver.h" #include "llvm/Support/raw_ostream.h" using namespace swift; using namespace namelookup; namespace { using ModuleLookupCache = llvm::SmallDenseMap<Module::ImportedModule, TinyPtrVector<ValueDecl *>, 32>; class SortCanType { public: bool operator()(CanType lhs, CanType rhs) const { return std::less<TypeBase *>()(lhs.getPointer(), rhs.getPointer()); } }; using CanTypeSet = llvm::SmallSet<CanType, 4, SortCanType>; using NamedCanTypeSet = llvm::DenseMap<Identifier, std::pair<ResolutionKind, CanTypeSet>>; static_assert(ResolutionKind() == ResolutionKind::Overloadable, "Entries in NamedCanTypeSet should be overloadable initially"); } // end anonymous namespace /// Returns true if this particular ValueDecl is overloadable. static bool isOverloadable(const ValueDecl *VD) { return isa<FuncDecl>(VD) || isa<ConstructorDecl>(VD) || isa<SubscriptDecl>(VD); } static bool isValidOverload(CanTypeSet &overloads, const ValueDecl *VD) { if (!isOverloadable(VD)) return overloads.empty(); if (overloads.count(VD->getType()->getCanonicalType())) return false; return true; } static bool isValidOverload(NamedCanTypeSet &overloads, const ValueDecl *VD) { auto &entry = overloads[VD->getName()]; if (entry.first != ResolutionKind::Overloadable) return false; return isValidOverload(entry.second, VD); } /// Updates \p overloads with the types of the given decls. /// /// \returns true if all of the given decls are overloadable, false if not. static bool updateOverloadSet(CanTypeSet &overloads, ArrayRef<ValueDecl *> decls) { for (auto result : decls) { if (!isOverloadable(result)) return false; if (!result->hasType()) continue; overloads.insert(result->getType()->getCanonicalType()); } return true; } /// Updates \p overloads with the types of the given decls. /// /// \returns true, since there can always be more overloadable decls. static bool updateOverloadSet(NamedCanTypeSet &overloads, ArrayRef<ValueDecl *> decls) { for (auto result : decls) { auto &entry = overloads[result->getName()]; if (!isOverloadable(result)) entry.first = ResolutionKind::Exact; else if (!result->hasType()) continue; else entry.second.insert(result->getType()->getCanonicalType()); } return true; } /// After finding decls by name lookup, filter based on the given /// resolution kind and existing overload set and add them to \p results. template <typename OverloadSetTy> static ResolutionKind recordImportDecls(LazyResolver *typeResolver, SmallVectorImpl<ValueDecl *> &results, ArrayRef<ValueDecl *> newDecls, OverloadSetTy &overloads, ResolutionKind resolutionKind) { switch (resolutionKind) { case ResolutionKind::Overloadable: { // Add new decls if they provide a new overload. Note that the new decls // may be ambiguous with respect to each other, just not any existing decls. std::copy_if(newDecls.begin(), newDecls.end(), std::back_inserter(results), [&](ValueDecl *result) -> bool { if (!result->hasType()) { if (typeResolver) typeResolver->resolveDeclSignature(result); else return true; } return isValidOverload(overloads, result); }); // Update the overload set. bool stillOverloadable = updateOverloadSet(overloads, newDecls); return stillOverloadable ? ResolutionKind::Overloadable : ResolutionKind::Exact; } case ResolutionKind::Exact: // Add all decls. If they're ambiguous, they're ambiguous. results.append(newDecls.begin(), newDecls.end()); return ResolutionKind::Exact; case ResolutionKind::TypesOnly: // Add type decls only. If they're ambiguous, they're ambiguous. std::copy_if(newDecls.begin(), newDecls.end(), std::back_inserter(results), [](const ValueDecl *VD) { return isa<TypeDecl>(VD); }); return ResolutionKind::TypesOnly; } } /// Performs a qualified lookup into the given module and, if necessary, its /// reexports, observing proper shadowing rules. template <typename OverloadSetTy, typename CallbackTy> static void lookupInModule(Module *module, Module::AccessPathTy accessPath, SmallVectorImpl<ValueDecl *> &decls, ResolutionKind resolutionKind, bool canReturnEarly, LazyResolver *typeResolver, ModuleLookupCache &cache, const DeclContext *moduleScopeContext, bool respectAccessControl, ArrayRef<Module::ImportedModule> extraImports, CallbackTy callback) { ModuleLookupCache::iterator iter; bool isNew; std::tie(iter, isNew) = cache.insert({{accessPath, module}, {}}); if (!isNew) { decls.append(iter->second.begin(), iter->second.end()); return; } size_t initialCount = decls.size(); SmallVector<ValueDecl *, 4> localDecls; callback(module, accessPath, localDecls); if (respectAccessControl) { auto newEndIter = std::remove_if(localDecls.begin(), localDecls.end(), [=](ValueDecl *VD) { if (typeResolver) typeResolver->resolveDeclSignature(VD); if (!VD->hasAccessibility()) return false; if (!moduleScopeContext) return VD->getAccessibility() != Accessibility::Public; switch (VD->getAccessibility()) { case Accessibility::Private: { const DeclContext *DC = VD->getDeclContext(); return moduleScopeContext != DC->getModuleScopeContext(); } case Accessibility::Internal: return moduleScopeContext->getParentModule() != VD->getModuleContext(); case Accessibility::Public: return false; } }); localDecls.erase(newEndIter, localDecls.end()); } OverloadSetTy overloads; resolutionKind = recordImportDecls(typeResolver, decls, localDecls, overloads, resolutionKind); bool foundDecls = decls.size() > initialCount; if (!foundDecls || !canReturnEarly || resolutionKind == ResolutionKind::Overloadable) { SmallVector<Module::ImportedModule, 8> reexports; module->getImportedModules(reexports, Module::ImportFilter::Public); reexports.append(extraImports.begin(), extraImports.end()); // Prefer scoped imports (import func Swift.max) to whole-module imports. SmallVector<ValueDecl *, 8> unscopedValues; SmallVector<ValueDecl *, 8> scopedValues; for (auto next : reexports) { // Filter any whole-module imports, and skip specific-decl imports if the // import path doesn't match exactly. Module::AccessPathTy combinedAccessPath; if (accessPath.empty()) { combinedAccessPath = next.first; } else if (!next.first.empty() && !Module::isSameAccessPath(next.first, accessPath)) { // If we ever allow importing non-top-level decls, it's possible the // rule above isn't what we want. assert(next.first.size() == 1 && "import of non-top-level decl"); continue; } else { combinedAccessPath = accessPath; } auto &resultSet = next.first.empty() ? unscopedValues : scopedValues; lookupInModule<OverloadSetTy>(next.second, combinedAccessPath, resultSet, resolutionKind, canReturnEarly, typeResolver, cache, nullptr, respectAccessControl, {}, callback); } // Add the results from scoped imports. resolutionKind = recordImportDecls(typeResolver, decls, scopedValues, overloads, resolutionKind); // Add the results from unscoped imports. foundDecls = decls.size() > initialCount; if (!foundDecls || !canReturnEarly || resolutionKind == ResolutionKind::Overloadable) { resolutionKind = recordImportDecls(typeResolver, decls, unscopedValues, overloads, resolutionKind); } } std::sort(decls.begin() + initialCount, decls.end()); auto afterUnique = std::unique(decls.begin() + initialCount, decls.end()); decls.erase(afterUnique, decls.end()); auto &cachedValues = cache[{accessPath, module}]; cachedValues.insert(cachedValues.end(), decls.begin() + initialCount, decls.end()); } void namelookup::lookupInModule(Module *startModule, Module::AccessPathTy topAccessPath, DeclName name, SmallVectorImpl<ValueDecl *> &decls, NLKind lookupKind, ResolutionKind resolutionKind, LazyResolver *typeResolver, const DeclContext *moduleScopeContext, ArrayRef<Module::ImportedModule> extraImports) { assert(!moduleScopeContext || moduleScopeContext->isModuleScopeContext()); ModuleLookupCache cache; bool respectAccessControl = startModule->Ctx.LangOpts.EnableAccessControl; ::lookupInModule<CanTypeSet>(startModule, topAccessPath, decls, resolutionKind, /*canReturnEarly=*/true, typeResolver, cache, moduleScopeContext, respectAccessControl, extraImports, [=](Module *module, Module::AccessPathTy path, SmallVectorImpl<ValueDecl *> &localDecls) { module->lookupValue(path, name, lookupKind, localDecls); } ); } void namelookup::lookupVisibleDeclsInModule( Module *M, Module::AccessPathTy accessPath, SmallVectorImpl<ValueDecl *> &decls, NLKind lookupKind, ResolutionKind resolutionKind, LazyResolver *typeResolver, const DeclContext *moduleScopeContext, ArrayRef<Module::ImportedModule> extraImports) { assert(!moduleScopeContext || moduleScopeContext->isModuleScopeContext()); ModuleLookupCache cache; bool respectAccessControl = M->Ctx.LangOpts.EnableAccessControl; ::lookupInModule<NamedCanTypeSet>(M, accessPath, decls, resolutionKind, /*canReturnEarly=*/false, typeResolver, cache, moduleScopeContext, respectAccessControl, extraImports, [=](Module *module, Module::AccessPathTy path, SmallVectorImpl<ValueDecl *> &localDecls) { VectorDeclConsumer consumer(localDecls); module->lookupVisibleDecls(path, consumer, lookupKind); } ); } <commit_msg>Eliminate non-deterministic behavior when removing duplicate declarations after module lookup.<commit_after>//===--- ModuleNameLookup.cpp - Name lookup within a module ----*- c++ -*--===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "ModuleNameLookup.h" #include "swift/AST/AST.h" #include "swift/AST/LazyResolver.h" #include "llvm/Support/raw_ostream.h" using namespace swift; using namespace namelookup; namespace { using ModuleLookupCache = llvm::SmallDenseMap<Module::ImportedModule, TinyPtrVector<ValueDecl *>, 32>; class SortCanType { public: bool operator()(CanType lhs, CanType rhs) const { return std::less<TypeBase *>()(lhs.getPointer(), rhs.getPointer()); } }; using CanTypeSet = llvm::SmallSet<CanType, 4, SortCanType>; using NamedCanTypeSet = llvm::DenseMap<Identifier, std::pair<ResolutionKind, CanTypeSet>>; static_assert(ResolutionKind() == ResolutionKind::Overloadable, "Entries in NamedCanTypeSet should be overloadable initially"); } // end anonymous namespace /// Returns true if this particular ValueDecl is overloadable. static bool isOverloadable(const ValueDecl *VD) { return isa<FuncDecl>(VD) || isa<ConstructorDecl>(VD) || isa<SubscriptDecl>(VD); } static bool isValidOverload(CanTypeSet &overloads, const ValueDecl *VD) { if (!isOverloadable(VD)) return overloads.empty(); if (overloads.count(VD->getType()->getCanonicalType())) return false; return true; } static bool isValidOverload(NamedCanTypeSet &overloads, const ValueDecl *VD) { auto &entry = overloads[VD->getName()]; if (entry.first != ResolutionKind::Overloadable) return false; return isValidOverload(entry.second, VD); } /// Updates \p overloads with the types of the given decls. /// /// \returns true if all of the given decls are overloadable, false if not. static bool updateOverloadSet(CanTypeSet &overloads, ArrayRef<ValueDecl *> decls) { for (auto result : decls) { if (!isOverloadable(result)) return false; if (!result->hasType()) continue; overloads.insert(result->getType()->getCanonicalType()); } return true; } /// Updates \p overloads with the types of the given decls. /// /// \returns true, since there can always be more overloadable decls. static bool updateOverloadSet(NamedCanTypeSet &overloads, ArrayRef<ValueDecl *> decls) { for (auto result : decls) { auto &entry = overloads[result->getName()]; if (!isOverloadable(result)) entry.first = ResolutionKind::Exact; else if (!result->hasType()) continue; else entry.second.insert(result->getType()->getCanonicalType()); } return true; } /// After finding decls by name lookup, filter based on the given /// resolution kind and existing overload set and add them to \p results. template <typename OverloadSetTy> static ResolutionKind recordImportDecls(LazyResolver *typeResolver, SmallVectorImpl<ValueDecl *> &results, ArrayRef<ValueDecl *> newDecls, OverloadSetTy &overloads, ResolutionKind resolutionKind) { switch (resolutionKind) { case ResolutionKind::Overloadable: { // Add new decls if they provide a new overload. Note that the new decls // may be ambiguous with respect to each other, just not any existing decls. std::copy_if(newDecls.begin(), newDecls.end(), std::back_inserter(results), [&](ValueDecl *result) -> bool { if (!result->hasType()) { if (typeResolver) typeResolver->resolveDeclSignature(result); else return true; } return isValidOverload(overloads, result); }); // Update the overload set. bool stillOverloadable = updateOverloadSet(overloads, newDecls); return stillOverloadable ? ResolutionKind::Overloadable : ResolutionKind::Exact; } case ResolutionKind::Exact: // Add all decls. If they're ambiguous, they're ambiguous. results.append(newDecls.begin(), newDecls.end()); return ResolutionKind::Exact; case ResolutionKind::TypesOnly: // Add type decls only. If they're ambiguous, they're ambiguous. std::copy_if(newDecls.begin(), newDecls.end(), std::back_inserter(results), [](const ValueDecl *VD) { return isa<TypeDecl>(VD); }); return ResolutionKind::TypesOnly; } } /// Performs a qualified lookup into the given module and, if necessary, its /// reexports, observing proper shadowing rules. template <typename OverloadSetTy, typename CallbackTy> static void lookupInModule(Module *module, Module::AccessPathTy accessPath, SmallVectorImpl<ValueDecl *> &decls, ResolutionKind resolutionKind, bool canReturnEarly, LazyResolver *typeResolver, ModuleLookupCache &cache, const DeclContext *moduleScopeContext, bool respectAccessControl, ArrayRef<Module::ImportedModule> extraImports, CallbackTy callback) { ModuleLookupCache::iterator iter; bool isNew; std::tie(iter, isNew) = cache.insert({{accessPath, module}, {}}); if (!isNew) { decls.append(iter->second.begin(), iter->second.end()); return; } size_t initialCount = decls.size(); SmallVector<ValueDecl *, 4> localDecls; callback(module, accessPath, localDecls); if (respectAccessControl) { auto newEndIter = std::remove_if(localDecls.begin(), localDecls.end(), [=](ValueDecl *VD) { if (typeResolver) typeResolver->resolveDeclSignature(VD); if (!VD->hasAccessibility()) return false; if (!moduleScopeContext) return VD->getAccessibility() != Accessibility::Public; switch (VD->getAccessibility()) { case Accessibility::Private: { const DeclContext *DC = VD->getDeclContext(); return moduleScopeContext != DC->getModuleScopeContext(); } case Accessibility::Internal: return moduleScopeContext->getParentModule() != VD->getModuleContext(); case Accessibility::Public: return false; } }); localDecls.erase(newEndIter, localDecls.end()); } OverloadSetTy overloads; resolutionKind = recordImportDecls(typeResolver, decls, localDecls, overloads, resolutionKind); bool foundDecls = decls.size() > initialCount; if (!foundDecls || !canReturnEarly || resolutionKind == ResolutionKind::Overloadable) { SmallVector<Module::ImportedModule, 8> reexports; module->getImportedModules(reexports, Module::ImportFilter::Public); reexports.append(extraImports.begin(), extraImports.end()); // Prefer scoped imports (import func Swift.max) to whole-module imports. SmallVector<ValueDecl *, 8> unscopedValues; SmallVector<ValueDecl *, 8> scopedValues; for (auto next : reexports) { // Filter any whole-module imports, and skip specific-decl imports if the // import path doesn't match exactly. Module::AccessPathTy combinedAccessPath; if (accessPath.empty()) { combinedAccessPath = next.first; } else if (!next.first.empty() && !Module::isSameAccessPath(next.first, accessPath)) { // If we ever allow importing non-top-level decls, it's possible the // rule above isn't what we want. assert(next.first.size() == 1 && "import of non-top-level decl"); continue; } else { combinedAccessPath = accessPath; } auto &resultSet = next.first.empty() ? unscopedValues : scopedValues; lookupInModule<OverloadSetTy>(next.second, combinedAccessPath, resultSet, resolutionKind, canReturnEarly, typeResolver, cache, nullptr, respectAccessControl, {}, callback); } // Add the results from scoped imports. resolutionKind = recordImportDecls(typeResolver, decls, scopedValues, overloads, resolutionKind); // Add the results from unscoped imports. foundDecls = decls.size() > initialCount; if (!foundDecls || !canReturnEarly || resolutionKind == ResolutionKind::Overloadable) { resolutionKind = recordImportDecls(typeResolver, decls, unscopedValues, overloads, resolutionKind); } } // Remove duplicated declarations. llvm::SmallPtrSet<ValueDecl *, 4> knownDecls; decls.erase(std::remove_if(decls.begin() + initialCount, decls.end(), [&](ValueDecl *d) -> bool { return !knownDecls.insert(d); }), decls.end()); auto &cachedValues = cache[{accessPath, module}]; cachedValues.insert(cachedValues.end(), decls.begin() + initialCount, decls.end()); } void namelookup::lookupInModule(Module *startModule, Module::AccessPathTy topAccessPath, DeclName name, SmallVectorImpl<ValueDecl *> &decls, NLKind lookupKind, ResolutionKind resolutionKind, LazyResolver *typeResolver, const DeclContext *moduleScopeContext, ArrayRef<Module::ImportedModule> extraImports) { assert(!moduleScopeContext || moduleScopeContext->isModuleScopeContext()); ModuleLookupCache cache; bool respectAccessControl = startModule->Ctx.LangOpts.EnableAccessControl; ::lookupInModule<CanTypeSet>(startModule, topAccessPath, decls, resolutionKind, /*canReturnEarly=*/true, typeResolver, cache, moduleScopeContext, respectAccessControl, extraImports, [=](Module *module, Module::AccessPathTy path, SmallVectorImpl<ValueDecl *> &localDecls) { module->lookupValue(path, name, lookupKind, localDecls); } ); } void namelookup::lookupVisibleDeclsInModule( Module *M, Module::AccessPathTy accessPath, SmallVectorImpl<ValueDecl *> &decls, NLKind lookupKind, ResolutionKind resolutionKind, LazyResolver *typeResolver, const DeclContext *moduleScopeContext, ArrayRef<Module::ImportedModule> extraImports) { assert(!moduleScopeContext || moduleScopeContext->isModuleScopeContext()); ModuleLookupCache cache; bool respectAccessControl = M->Ctx.LangOpts.EnableAccessControl; ::lookupInModule<NamedCanTypeSet>(M, accessPath, decls, resolutionKind, /*canReturnEarly=*/false, typeResolver, cache, moduleScopeContext, respectAccessControl, extraImports, [=](Module *module, Module::AccessPathTy path, SmallVectorImpl<ValueDecl *> &localDecls) { VectorDeclConsumer consumer(localDecls); module->lookupVisibleDecls(path, consumer, lookupKind); } ); } <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Fons Rademakers 28/11/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TTimer // // // // Handles synchronous and a-synchronous timer events. // // 1. synchronous timer is registered into TSystem and is processed // // within the standard ROOT event-loop. // // 2. asynchronous timer is passed to the operating system which sends // // an external signal to ROOT and thus interrupts its event-loop. // // // // You can use this class in one of the following ways: // // - Sub-class TTimer and override the Notify() method. // // - Re-implement the TObject::HandleTimer() method in your class // // and pass a pointer to this object to timer, see the SetObject() // // method. // // - Pass an interpreter command to timer, see SetCommand() method. // // - Create a TTimer, connect its Timeout() signal to the // // appropriate methods. Then when the time is up it will emit a // // Timeout() signal and call connected slots. // // // // Minimum timeout interval is defined in TSystem::ESysConstants as // // kItimerResolution (currently 10 ms). // // // // Signal/slots example: // // TTimer *timer = new TTimer(); // // timer->Connect("Timeout()", "myObjectClassName", // // myObject, "TimerDone()"); // // timer->Start(2000, kTRUE); // 2 seconds single-shot // // // // To emit the Timeout signal repeadetly with minimum timeout: // // timer->Start(0, kFALSE); // // // ////////////////////////////////////////////////////////////////////////// #include "TTimer.h" #include "TSystem.h" #include "TROOT.h" ClassImp(TTimer) class TSingleShotCleaner : public TTimer { private: TList *fGarbage; public: TSingleShotCleaner() : TTimer(10, kTRUE) { fGarbage = new TList(); } virtual ~TSingleShotCleaner() { fGarbage->Delete(); delete fGarbage; } void TurnOn() { TObject *obj = (TObject*) gTQSender; fGarbage->Add(obj); Reset(); if (gSystem) gSystem->AddTimer(this); } Bool_t Notify() { fGarbage->Delete(); Reset(); if (gSystem) gSystem->RemoveTimer(this); return kTRUE; } }; TSingleShotCleaner gSingleShotCleaner; // single shot timer cleaner //______________________________________________________________________________ TTimer::TTimer(Long_t ms, Bool_t mode) : fTime(ms) { // Create timer that times out in ms milliseconds. If milliSec is 0 // then the timeout will be the minimum timeout (see TSystem::ESysConstants, // i.e. 10 ms). If mode == kTRUE then the timer is synchronous else // a-synchronous. The default is synchronous. Add a timer to the system // eventloop by calling TurnOn(). Set command to be executed from Notify() // or set the object whose HandleTimer() method will be called via Notify(), // derive from TTimer and override Notify() or connect slots to the // signals Timeout(), TurnOn() and TurnOff(). fObject = 0; fCommand = ""; fSync = mode; fIntSyscalls = kFALSE; Reset(); } //______________________________________________________________________________ TTimer::TTimer(TObject *obj, Long_t ms, Bool_t mode) : fTime(ms) { // Create timer that times out in ms milliseconds. If mode == kTRUE then // the timer is synchronous else a-synchronous. The default is synchronous. // Add a timer to the system eventloop by calling TurnOn(). // The object's HandleTimer() will be called by Notify(). fObject = obj; fCommand = ""; fSync = mode; fIntSyscalls = kFALSE; Reset(); } //______________________________________________________________________________ TTimer::TTimer(const char *command, Long_t ms, Bool_t mode) : fTime(ms) { // Create timer that times out in ms milliseconds. If mode == kTRUE then // the timer is synchronous else a-synchronous. The default is synchronous. // Add a timer to the system eventloop by calling TurnOn(). // The interpreter will execute command from Notify(). fObject = 0; fCommand = command; fSync = mode; fIntSyscalls = kFALSE; Reset(); } //______________________________________________________________________________ Bool_t TTimer::CheckTimer(const TTime &now) { // Check if timer timed out. // To prevent from time-drift related problems observed on some dual-processor // machines, we make the resolution proportional to the timeout period for // periods longer than 200s, with a proportionality factor of 5*10**-5 // hand-calculated to ensure 10ms (the minimal resolution) at transition. TTime xnow = TMath::Max((ULong_t)kItimerResolution, (ULong_t) (0.05 * (ULong_t)fTime)); xnow += now; if (fAbsTime <= xnow) { fTimeout = kTRUE; Notify(); return kTRUE; } return kFALSE; } //______________________________________________________________________________ Bool_t TTimer::Notify() { // Notify when timer times out. The timer is always reset. To stop // the timer call TurnOff(). Timeout(); // emit Timeout() signal if (fObject) fObject->HandleTimer(this); if (fCommand && fCommand.Length() > 0) gROOT->ProcessLine(fCommand); Reset(); return kTRUE; } //______________________________________________________________________________ void TTimer::Reset() { // Reset the timer. // make sure gSystem exists ROOT::GetROOT(); fTimeout = kFALSE; fAbsTime = fTime; if (gSystem) { fAbsTime += gSystem->Now(); if (!fSync) gSystem->ResetTimer(this); } } //______________________________________________________________________________ void TTimer::SetCommand(const char *command) { // Set the interpreter command to be executed at time out. Removes the // object to be notified (if it was set). fObject = 0; fCommand = command; } //______________________________________________________________________________ void TTimer::SetObject(TObject *object) { // Set the object to be notified at time out. Removes the command to // be executed (if it was set). fObject = object; fCommand = ""; } //______________________________________________________________________________ void TTimer::SetInterruptSyscalls(Bool_t set) { // When the argument is true the a-synchronous timer (SIGALRM) signal // handler is set so that interrupted syscalls will not be restarted // by the kernel. This is typically used in case one wants to put a // timeout on an I/O operation. By default interrupted syscalls will // be restarted. fIntSyscalls = set; } //___________________________________________________________________ void TTimer::Start(Long_t milliSec, Bool_t singleShot) { // Starts the timer with a milliSec timeout. If milliSec is 0 // then the timeout will be the minimum timeout (see TSystem::ESysConstants, // i.e. 10 ms), if milliSec is -1 then the time interval as previously // specified (in ctor or SetTime()) will be used. // If singleShot is kTRUE, the timer will be activated only once, // otherwise it will continue until it is stopped. // See also TurnOn(), Stop(), TurnOff(). if (milliSec >= 0) SetTime(milliSec); Reset(); TurnOn(); if (singleShot) Connect(this, "Timeout()", "TTimer", this, "TurnOff()"); else Disconnect(this, "Timeout()", this, "TurnOff()"); } //______________________________________________________________________________ void TTimer::TurnOff() { // Remove timer from system timer list. This requires that a timer // has been placed in the system timer list (using TurnOn()). // If a TTimer subclass is placed on another list, override TurnOff() to // remove the timer from the correct list. if (gSystem) if (gSystem->RemoveTimer(this)) Emit("TurnOff()"); } //______________________________________________________________________________ void TTimer::TurnOn() { // Add the timer to the system timer list. If a TTimer subclass has to be // placed on another list, override TurnOn() to add the timer to the correct // list. // might have been set in a previous Start() Disconnect(this, "Timeout()", this, "TurnOff()"); if (gSystem) { gSystem->AddTimer(this); Emit("TurnOn()"); } } //______________________________________________________________________________ void TTimer::SingleShot(Int_t milliSec, const char *receiver_class, void *receiver, const char *method) { // This static function calls a slot after a given time interval. // Created internal timer will be deleted after that. TTimer *singleShotTimer = new TTimer(milliSec); TQObject::Connect(singleShotTimer, "Timeout()", receiver_class, receiver, method); // gSingleShotCleaner will delete singleShotTimer a // short period after Timeout() signal is emitted TQObject::Connect(singleShotTimer, "Timeout()", "TTimer", &gSingleShotCleaner, "TurnOn()"); singleShotTimer->Start(milliSec, kTRUE); } <commit_msg>Delay the creation of the single short cleaner until it is really needed.<commit_after>// @(#)root/base:$Id$ // Author: Fons Rademakers 28/11/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TTimer // // // // Handles synchronous and a-synchronous timer events. // // 1. synchronous timer is registered into TSystem and is processed // // within the standard ROOT event-loop. // // 2. asynchronous timer is passed to the operating system which sends // // an external signal to ROOT and thus interrupts its event-loop. // // // // You can use this class in one of the following ways: // // - Sub-class TTimer and override the Notify() method. // // - Re-implement the TObject::HandleTimer() method in your class // // and pass a pointer to this object to timer, see the SetObject() // // method. // // - Pass an interpreter command to timer, see SetCommand() method. // // - Create a TTimer, connect its Timeout() signal to the // // appropriate methods. Then when the time is up it will emit a // // Timeout() signal and call connected slots. // // // // Minimum timeout interval is defined in TSystem::ESysConstants as // // kItimerResolution (currently 10 ms). // // // // Signal/slots example: // // TTimer *timer = new TTimer(); // // timer->Connect("Timeout()", "myObjectClassName", // // myObject, "TimerDone()"); // // timer->Start(2000, kTRUE); // 2 seconds single-shot // // // // To emit the Timeout signal repeadetly with minimum timeout: // // timer->Start(0, kFALSE); // // // ////////////////////////////////////////////////////////////////////////// #include "TTimer.h" #include "TSystem.h" #include "TROOT.h" ClassImp(TTimer) class TSingleShotCleaner : public TTimer { private: TList *fGarbage; public: TSingleShotCleaner() : TTimer(10, kTRUE) { fGarbage = new TList(); } virtual ~TSingleShotCleaner() { fGarbage->Delete(); delete fGarbage; } void TurnOn() { TObject *obj = (TObject*) gTQSender; fGarbage->Add(obj); Reset(); if (gSystem) gSystem->AddTimer(this); } Bool_t Notify() { fGarbage->Delete(); Reset(); if (gSystem) gSystem->RemoveTimer(this); return kTRUE; } }; //______________________________________________________________________________ TTimer::TTimer(Long_t ms, Bool_t mode) : fTime(ms) { // Create timer that times out in ms milliseconds. If milliSec is 0 // then the timeout will be the minimum timeout (see TSystem::ESysConstants, // i.e. 10 ms). If mode == kTRUE then the timer is synchronous else // a-synchronous. The default is synchronous. Add a timer to the system // eventloop by calling TurnOn(). Set command to be executed from Notify() // or set the object whose HandleTimer() method will be called via Notify(), // derive from TTimer and override Notify() or connect slots to the // signals Timeout(), TurnOn() and TurnOff(). fObject = 0; fCommand = ""; fSync = mode; fIntSyscalls = kFALSE; Reset(); } //______________________________________________________________________________ TTimer::TTimer(TObject *obj, Long_t ms, Bool_t mode) : fTime(ms) { // Create timer that times out in ms milliseconds. If mode == kTRUE then // the timer is synchronous else a-synchronous. The default is synchronous. // Add a timer to the system eventloop by calling TurnOn(). // The object's HandleTimer() will be called by Notify(). fObject = obj; fCommand = ""; fSync = mode; fIntSyscalls = kFALSE; Reset(); } //______________________________________________________________________________ TTimer::TTimer(const char *command, Long_t ms, Bool_t mode) : fTime(ms) { // Create timer that times out in ms milliseconds. If mode == kTRUE then // the timer is synchronous else a-synchronous. The default is synchronous. // Add a timer to the system eventloop by calling TurnOn(). // The interpreter will execute command from Notify(). fObject = 0; fCommand = command; fSync = mode; fIntSyscalls = kFALSE; Reset(); } //______________________________________________________________________________ Bool_t TTimer::CheckTimer(const TTime &now) { // Check if timer timed out. // To prevent from time-drift related problems observed on some dual-processor // machines, we make the resolution proportional to the timeout period for // periods longer than 200s, with a proportionality factor of 5*10**-5 // hand-calculated to ensure 10ms (the minimal resolution) at transition. TTime xnow = TMath::Max((ULong_t)kItimerResolution, (ULong_t) (0.05 * (ULong_t)fTime)); xnow += now; if (fAbsTime <= xnow) { fTimeout = kTRUE; Notify(); return kTRUE; } return kFALSE; } //______________________________________________________________________________ Bool_t TTimer::Notify() { // Notify when timer times out. The timer is always reset. To stop // the timer call TurnOff(). Timeout(); // emit Timeout() signal if (fObject) fObject->HandleTimer(this); if (fCommand && fCommand.Length() > 0) gROOT->ProcessLine(fCommand); Reset(); return kTRUE; } //______________________________________________________________________________ void TTimer::Reset() { // Reset the timer. // make sure gSystem exists ROOT::GetROOT(); fTimeout = kFALSE; fAbsTime = fTime; if (gSystem) { fAbsTime += gSystem->Now(); if (!fSync) gSystem->ResetTimer(this); } } //______________________________________________________________________________ void TTimer::SetCommand(const char *command) { // Set the interpreter command to be executed at time out. Removes the // object to be notified (if it was set). fObject = 0; fCommand = command; } //______________________________________________________________________________ void TTimer::SetObject(TObject *object) { // Set the object to be notified at time out. Removes the command to // be executed (if it was set). fObject = object; fCommand = ""; } //______________________________________________________________________________ void TTimer::SetInterruptSyscalls(Bool_t set) { // When the argument is true the a-synchronous timer (SIGALRM) signal // handler is set so that interrupted syscalls will not be restarted // by the kernel. This is typically used in case one wants to put a // timeout on an I/O operation. By default interrupted syscalls will // be restarted. fIntSyscalls = set; } //___________________________________________________________________ void TTimer::Start(Long_t milliSec, Bool_t singleShot) { // Starts the timer with a milliSec timeout. If milliSec is 0 // then the timeout will be the minimum timeout (see TSystem::ESysConstants, // i.e. 10 ms), if milliSec is -1 then the time interval as previously // specified (in ctor or SetTime()) will be used. // If singleShot is kTRUE, the timer will be activated only once, // otherwise it will continue until it is stopped. // See also TurnOn(), Stop(), TurnOff(). if (milliSec >= 0) SetTime(milliSec); Reset(); TurnOn(); if (singleShot) Connect(this, "Timeout()", "TTimer", this, "TurnOff()"); else Disconnect(this, "Timeout()", this, "TurnOff()"); } //______________________________________________________________________________ void TTimer::TurnOff() { // Remove timer from system timer list. This requires that a timer // has been placed in the system timer list (using TurnOn()). // If a TTimer subclass is placed on another list, override TurnOff() to // remove the timer from the correct list. if (gSystem) if (gSystem->RemoveTimer(this)) Emit("TurnOff()"); } //______________________________________________________________________________ void TTimer::TurnOn() { // Add the timer to the system timer list. If a TTimer subclass has to be // placed on another list, override TurnOn() to add the timer to the correct // list. // might have been set in a previous Start() Disconnect(this, "Timeout()", this, "TurnOff()"); if (gSystem) { gSystem->AddTimer(this); Emit("TurnOn()"); } } //______________________________________________________________________________ void TTimer::SingleShot(Int_t milliSec, const char *receiver_class, void *receiver, const char *method) { // This static function calls a slot after a given time interval. // Created internal timer will be deleted after that. TTimer *singleShotTimer = new TTimer(milliSec); TQObject::Connect(singleShotTimer, "Timeout()", receiver_class, receiver, method); static TSingleShotCleaner singleShotCleaner; // single shot timer cleaner // gSingleShotCleaner will delete singleShotTimer a // short period after Timeout() signal is emitted TQObject::Connect(singleShotTimer, "Timeout()", "TTimer", &singleShotCleaner, "TurnOn()"); singleShotTimer->Start(milliSec, kTRUE); } <|endoftext|>
<commit_before>// Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Validates correctness of atomic SPIR-V instructions. #include "source/val/validate.h" #include "source/diagnostic.h" #include "source/opcode.h" #include "source/spirv_target_env.h" #include "source/util/bitutils.h" #include "source/val/instruction.h" #include "source/val/validation_state.h" namespace spvtools { namespace val { // Validates Memory Scope operand. spv_result_t ValidateMemoryScope(ValidationState_t& _, const Instruction* inst, uint32_t id) { const SpvOp opcode = inst->opcode(); bool is_int32 = false, is_const_int32 = false; uint32_t value = 0; std::tie(is_int32, is_const_int32, value) = _.EvalInt32IfConst(id); if (!is_int32) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Scope to be 32-bit int"; } if (!is_const_int32) { return SPV_SUCCESS; } #if 0 // TODO(atgoo@github.com): this check fails Vulkan CTS, reenable once fixed. if (spvIsVulkanEnv(_.context()->target_env)) { if (value != SpvScopeDevice && value != SpvScopeWorkgroup && value != SpvScopeInvocation) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": in Vulkan environment memory scope is limited to Device, " "Workgroup and Invocation"; } } #endif // TODO(atgoo@github.com) Add checks for OpenCL and OpenGL environments. return SPV_SUCCESS; } // Validates a Memory Semantics operand. spv_result_t ValidateMemorySemantics(ValidationState_t& _, const Instruction* inst, uint32_t operand_index) { const SpvOp opcode = inst->opcode(); bool is_int32 = false, is_const_int32 = false; uint32_t flags = 0; auto memory_semantics_id = inst->GetOperandAs<const uint32_t>(operand_index); std::tie(is_int32, is_const_int32, flags) = _.EvalInt32IfConst(memory_semantics_id); if (!is_int32) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Memory Semantics to be 32-bit int"; } if (!is_const_int32) { return SPV_SUCCESS; } if (spvtools::utils::CountSetBits( flags & (SpvMemorySemanticsAcquireMask | SpvMemorySemanticsReleaseMask | SpvMemorySemanticsAcquireReleaseMask | SpvMemorySemanticsSequentiallyConsistentMask)) > 1) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": no more than one of the following Memory Semantics bits can " "be set at the same time: Acquire, Release, AcquireRelease or " "SequentiallyConsistent"; } if (flags & SpvMemorySemanticsUniformMemoryMask && !_.HasCapability(SpvCapabilityShader)) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": Memory Semantics UniformMemory requires capability Shader"; } if (flags & SpvMemorySemanticsAtomicCounterMemoryMask && !_.HasCapability(SpvCapabilityAtomicStorage)) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": Memory Semantics UniformMemory requires capability " "AtomicStorage"; } if (opcode == SpvOpAtomicFlagClear && (flags & SpvMemorySemanticsAcquireMask || flags & SpvMemorySemanticsAcquireReleaseMask)) { return _.diag(SPV_ERROR_INVALID_DATA) << "Memory Semantics Acquire and AcquireRelease cannot be used with " << spvOpcodeString(opcode); } if (opcode == SpvOpAtomicCompareExchange && operand_index == 5 && (flags & SpvMemorySemanticsReleaseMask || flags & SpvMemorySemanticsAcquireReleaseMask)) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": Memory Semantics Release and AcquireRelease cannot be used " "for operand Unequal"; } if (spvIsVulkanEnv(_.context()->target_env)) { if (opcode == SpvOpAtomicLoad && (flags & SpvMemorySemanticsReleaseMask || flags & SpvMemorySemanticsAcquireReleaseMask || flags & SpvMemorySemanticsSequentiallyConsistentMask)) { return _.diag(SPV_ERROR_INVALID_DATA) << "Vulkan spec disallows OpAtomicLoad with Memory Semantics " "Release, AcquireRelease and SequentiallyConsistent"; } if (opcode == SpvOpAtomicStore && (flags & SpvMemorySemanticsAcquireMask || flags & SpvMemorySemanticsAcquireReleaseMask || flags & SpvMemorySemanticsSequentiallyConsistentMask)) { return _.diag(SPV_ERROR_INVALID_DATA) << "Vulkan spec disallows OpAtomicStore with Memory Semantics " "Acquire, AcquireRelease and SequentiallyConsistent"; } } // TODO(atgoo@github.com) Add checks for OpenCL and OpenGL environments. return SPV_SUCCESS; } // Validates correctness of atomic instructions. spv_result_t AtomicsPass(ValidationState_t& _, const Instruction* inst) { const SpvOp opcode = inst->opcode(); const uint32_t result_type = inst->type_id(); switch (opcode) { case SpvOpAtomicLoad: case SpvOpAtomicStore: case SpvOpAtomicExchange: case SpvOpAtomicCompareExchange: case SpvOpAtomicCompareExchangeWeak: case SpvOpAtomicIIncrement: case SpvOpAtomicIDecrement: case SpvOpAtomicIAdd: case SpvOpAtomicISub: case SpvOpAtomicSMin: case SpvOpAtomicUMin: case SpvOpAtomicSMax: case SpvOpAtomicUMax: case SpvOpAtomicAnd: case SpvOpAtomicOr: case SpvOpAtomicXor: case SpvOpAtomicFlagTestAndSet: case SpvOpAtomicFlagClear: { if (_.HasCapability(SpvCapabilityKernel) && (opcode == SpvOpAtomicLoad || opcode == SpvOpAtomicExchange || opcode == SpvOpAtomicCompareExchange)) { if (!_.IsFloatScalarType(result_type) && !_.IsIntScalarType(result_type)) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Result Type to be int or float scalar type"; } } else if (opcode == SpvOpAtomicFlagTestAndSet) { if (!_.IsBoolScalarType(result_type)) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Result Type to be bool scalar type"; } } else if (opcode == SpvOpAtomicFlagClear || opcode == SpvOpAtomicStore) { assert(result_type == 0); } else { if (!_.IsIntScalarType(result_type)) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Result Type to be int scalar type"; } if (spvIsVulkanEnv(_.context()->target_env) && _.GetBitWidth(result_type) != 32) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": according to the Vulkan spec atomic Result Type needs " "to be a 32-bit int scalar type"; } } uint32_t operand_index = opcode == SpvOpAtomicFlagClear || opcode == SpvOpAtomicStore ? 0 : 2; const uint32_t pointer_type = _.GetOperandTypeId(inst, operand_index++); uint32_t data_type = 0; uint32_t storage_class = 0; if (!_.GetPointerTypeInfo(pointer_type, &data_type, &storage_class)) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Pointer to be of type OpTypePointer"; } switch (storage_class) { case SpvStorageClassUniform: case SpvStorageClassWorkgroup: case SpvStorageClassCrossWorkgroup: case SpvStorageClassGeneric: case SpvStorageClassAtomicCounter: case SpvStorageClassImage: case SpvStorageClassStorageBuffer: break; default: return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Pointer Storage Class to be Uniform, " "Workgroup, CrossWorkgroup, Generic, AtomicCounter, Image " "or StorageBuffer"; } if (opcode == SpvOpAtomicFlagTestAndSet || opcode == SpvOpAtomicFlagClear) { if (!_.IsIntScalarType(data_type) || _.GetBitWidth(data_type) != 32) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Pointer to point to a value of 32-bit int type"; } } else if (opcode == SpvOpAtomicStore) { if (!_.IsFloatScalarType(data_type) && !_.IsIntScalarType(data_type)) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Pointer to be a pointer to int or float " << "scalar type"; } } else { if (data_type != result_type) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Pointer to point to a value of type Result " "Type"; } } auto memory_scope = inst->GetOperandAs<const uint32_t>(operand_index++); if (auto error = ValidateMemoryScope(_, inst, memory_scope)) { return error; } if (auto error = ValidateMemorySemantics(_, inst, operand_index++)) return error; if (opcode == SpvOpAtomicCompareExchange || opcode == SpvOpAtomicCompareExchangeWeak) { if (auto error = ValidateMemorySemantics(_, inst, operand_index++)) return error; } if (opcode == SpvOpAtomicStore) { const uint32_t value_type = _.GetOperandTypeId(inst, 3); if (value_type != data_type) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Value type and the type pointed to by Pointer " "to" << " be the same"; } } else if (opcode != SpvOpAtomicLoad && opcode != SpvOpAtomicIIncrement && opcode != SpvOpAtomicIDecrement && opcode != SpvOpAtomicFlagTestAndSet && opcode != SpvOpAtomicFlagClear) { const uint32_t value_type = _.GetOperandTypeId(inst, operand_index++); if (value_type != result_type) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Value to be of type Result Type"; } } if (opcode == SpvOpAtomicCompareExchange || opcode == SpvOpAtomicCompareExchangeWeak) { const uint32_t comparator_type = _.GetOperandTypeId(inst, operand_index++); if (comparator_type != result_type) { return _.diag(SPV_ERROR_INVALID_DATA) << spvOpcodeString(opcode) << ": expected Comparator to be of type Result Type"; } } break; } default: break; } return SPV_SUCCESS; } } // namespace val } // namespace spvtools <commit_msg>Update diag() in validate_atomics (#1753)<commit_after>// Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Validates correctness of atomic SPIR-V instructions. #include "source/val/validate.h" #include "source/diagnostic.h" #include "source/opcode.h" #include "source/spirv_target_env.h" #include "source/util/bitutils.h" #include "source/val/instruction.h" #include "source/val/validation_state.h" namespace spvtools { namespace val { // Validates Memory Scope operand. spv_result_t ValidateMemoryScope(ValidationState_t& _, const Instruction* inst, uint32_t id) { const SpvOp opcode = inst->opcode(); bool is_int32 = false, is_const_int32 = false; uint32_t value = 0; std::tie(is_int32, is_const_int32, value) = _.EvalInt32IfConst(id); if (!is_int32) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Scope to be 32-bit int"; } if (!is_const_int32) { return SPV_SUCCESS; } #if 0 // TODO(atgoo@github.com): this check fails Vulkan CTS, reenable once fixed. if (spvIsVulkanEnv(_.context()->target_env)) { if (value != SpvScopeDevice && value != SpvScopeWorkgroup && value != SpvScopeInvocation) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": in Vulkan environment memory scope is limited to Device, " "Workgroup and Invocation"; } } #endif // TODO(atgoo@github.com) Add checks for OpenCL and OpenGL environments. return SPV_SUCCESS; } // Validates a Memory Semantics operand. spv_result_t ValidateMemorySemantics(ValidationState_t& _, const Instruction* inst, uint32_t operand_index) { const SpvOp opcode = inst->opcode(); bool is_int32 = false, is_const_int32 = false; uint32_t flags = 0; auto memory_semantics_id = inst->GetOperandAs<const uint32_t>(operand_index); std::tie(is_int32, is_const_int32, flags) = _.EvalInt32IfConst(memory_semantics_id); if (!is_int32) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Memory Semantics to be 32-bit int"; } if (!is_const_int32) { return SPV_SUCCESS; } if (spvtools::utils::CountSetBits( flags & (SpvMemorySemanticsAcquireMask | SpvMemorySemanticsReleaseMask | SpvMemorySemanticsAcquireReleaseMask | SpvMemorySemanticsSequentiallyConsistentMask)) > 1) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": no more than one of the following Memory Semantics bits can " "be set at the same time: Acquire, Release, AcquireRelease or " "SequentiallyConsistent"; } if (flags & SpvMemorySemanticsUniformMemoryMask && !_.HasCapability(SpvCapabilityShader)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": Memory Semantics UniformMemory requires capability Shader"; } if (flags & SpvMemorySemanticsAtomicCounterMemoryMask && !_.HasCapability(SpvCapabilityAtomicStorage)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": Memory Semantics UniformMemory requires capability " "AtomicStorage"; } if (opcode == SpvOpAtomicFlagClear && (flags & SpvMemorySemanticsAcquireMask || flags & SpvMemorySemanticsAcquireReleaseMask)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Memory Semantics Acquire and AcquireRelease cannot be used with " << spvOpcodeString(opcode); } if (opcode == SpvOpAtomicCompareExchange && operand_index == 5 && (flags & SpvMemorySemanticsReleaseMask || flags & SpvMemorySemanticsAcquireReleaseMask)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": Memory Semantics Release and AcquireRelease cannot be used " "for operand Unequal"; } if (spvIsVulkanEnv(_.context()->target_env)) { if (opcode == SpvOpAtomicLoad && (flags & SpvMemorySemanticsReleaseMask || flags & SpvMemorySemanticsAcquireReleaseMask || flags & SpvMemorySemanticsSequentiallyConsistentMask)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Vulkan spec disallows OpAtomicLoad with Memory Semantics " "Release, AcquireRelease and SequentiallyConsistent"; } if (opcode == SpvOpAtomicStore && (flags & SpvMemorySemanticsAcquireMask || flags & SpvMemorySemanticsAcquireReleaseMask || flags & SpvMemorySemanticsSequentiallyConsistentMask)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Vulkan spec disallows OpAtomicStore with Memory Semantics " "Acquire, AcquireRelease and SequentiallyConsistent"; } } // TODO(atgoo@github.com) Add checks for OpenCL and OpenGL environments. return SPV_SUCCESS; } // Validates correctness of atomic instructions. spv_result_t AtomicsPass(ValidationState_t& _, const Instruction* inst) { const SpvOp opcode = inst->opcode(); const uint32_t result_type = inst->type_id(); switch (opcode) { case SpvOpAtomicLoad: case SpvOpAtomicStore: case SpvOpAtomicExchange: case SpvOpAtomicCompareExchange: case SpvOpAtomicCompareExchangeWeak: case SpvOpAtomicIIncrement: case SpvOpAtomicIDecrement: case SpvOpAtomicIAdd: case SpvOpAtomicISub: case SpvOpAtomicSMin: case SpvOpAtomicUMin: case SpvOpAtomicSMax: case SpvOpAtomicUMax: case SpvOpAtomicAnd: case SpvOpAtomicOr: case SpvOpAtomicXor: case SpvOpAtomicFlagTestAndSet: case SpvOpAtomicFlagClear: { if (_.HasCapability(SpvCapabilityKernel) && (opcode == SpvOpAtomicLoad || opcode == SpvOpAtomicExchange || opcode == SpvOpAtomicCompareExchange)) { if (!_.IsFloatScalarType(result_type) && !_.IsIntScalarType(result_type)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Result Type to be int or float scalar type"; } } else if (opcode == SpvOpAtomicFlagTestAndSet) { if (!_.IsBoolScalarType(result_type)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Result Type to be bool scalar type"; } } else if (opcode == SpvOpAtomicFlagClear || opcode == SpvOpAtomicStore) { assert(result_type == 0); } else { if (!_.IsIntScalarType(result_type)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Result Type to be int scalar type"; } if (spvIsVulkanEnv(_.context()->target_env) && _.GetBitWidth(result_type) != 32) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": according to the Vulkan spec atomic Result Type needs " "to be a 32-bit int scalar type"; } } uint32_t operand_index = opcode == SpvOpAtomicFlagClear || opcode == SpvOpAtomicStore ? 0 : 2; const uint32_t pointer_type = _.GetOperandTypeId(inst, operand_index++); uint32_t data_type = 0; uint32_t storage_class = 0; if (!_.GetPointerTypeInfo(pointer_type, &data_type, &storage_class)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Pointer to be of type OpTypePointer"; } switch (storage_class) { case SpvStorageClassUniform: case SpvStorageClassWorkgroup: case SpvStorageClassCrossWorkgroup: case SpvStorageClassGeneric: case SpvStorageClassAtomicCounter: case SpvStorageClassImage: case SpvStorageClassStorageBuffer: break; default: return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Pointer Storage Class to be Uniform, " "Workgroup, CrossWorkgroup, Generic, AtomicCounter, Image " "or StorageBuffer"; } if (opcode == SpvOpAtomicFlagTestAndSet || opcode == SpvOpAtomicFlagClear) { if (!_.IsIntScalarType(data_type) || _.GetBitWidth(data_type) != 32) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Pointer to point to a value of 32-bit int type"; } } else if (opcode == SpvOpAtomicStore) { if (!_.IsFloatScalarType(data_type) && !_.IsIntScalarType(data_type)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Pointer to be a pointer to int or float " << "scalar type"; } } else { if (data_type != result_type) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Pointer to point to a value of type Result " "Type"; } } auto memory_scope = inst->GetOperandAs<const uint32_t>(operand_index++); if (auto error = ValidateMemoryScope(_, inst, memory_scope)) { return error; } if (auto error = ValidateMemorySemantics(_, inst, operand_index++)) return error; if (opcode == SpvOpAtomicCompareExchange || opcode == SpvOpAtomicCompareExchangeWeak) { if (auto error = ValidateMemorySemantics(_, inst, operand_index++)) return error; } if (opcode == SpvOpAtomicStore) { const uint32_t value_type = _.GetOperandTypeId(inst, 3); if (value_type != data_type) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Value type and the type pointed to by Pointer " "to" << " be the same"; } } else if (opcode != SpvOpAtomicLoad && opcode != SpvOpAtomicIIncrement && opcode != SpvOpAtomicIDecrement && opcode != SpvOpAtomicFlagTestAndSet && opcode != SpvOpAtomicFlagClear) { const uint32_t value_type = _.GetOperandTypeId(inst, operand_index++); if (value_type != result_type) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Value to be of type Result Type"; } } if (opcode == SpvOpAtomicCompareExchange || opcode == SpvOpAtomicCompareExchangeWeak) { const uint32_t comparator_type = _.GetOperandTypeId(inst, operand_index++); if (comparator_type != result_type) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Comparator to be of type Result Type"; } } break; } default: break; } return SPV_SUCCESS; } } // namespace val } // namespace spvtools <|endoftext|>
<commit_before>// Filename: milesAudioSound.cxx // Created by: skyler (June 6, 2001) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://www.panda3d.org/license.txt . // // To contact the maintainers of this program write to // panda3d@yahoogroups.com . // //////////////////////////////////////////////////////////////////// #include <pandabase.h> #ifdef HAVE_RAD_MSS //[ #include "milesAudioSound.h" #include "milesAudioManager.h" #if (MSS_MAJOR_VERSION <= 6) && (MSS_MINOR_VERSION < 5) #define NEED_MILES_LENGTH_WORKAROUND #endif //#define NEED_MILES_LENGTH_WORKAROUND #ifndef NDEBUG //[ namespace { char getStatusChar(HAUDIO audio) { if (!audio) { return '0'; // NULL. } switch (AIL_quick_status(audio)) { case QSTAT_LOADED: case QSTAT_DONE: return 'r'; // Ready. case QSTAT_PLAYING: return 'p'; // Playing. default: return 'x'; // bad. } } } #define miles_audio_debug(x) \ audio_debug("MilesAudioSound "<<getStatusChar(_audio)<<" \""<<get_name() \ <<"\" "<< x ) #else //][ #define miles_audio_debug(x) ((void)0) #endif //] MilesAudioSound:: MilesAudioSound(MilesAudioManager* manager, HAUDIO audio, string file_name, float length) : _manager(manager), _file_name(file_name), _start_time(0), _volume(1.0f), _balance(0), _loop_count(1), _length(length), _active(true), _paused(false) { nassertv(audio); nassertv(!file_name.empty()); audio_debug("MilesAudioSound(manager=0x"<<(void*)&manager <<", audio=0x"<<(void*)audio<<", file_name="<<file_name<<")"); // Make our own copy of the sound header data: _audio=AIL_quick_copy(audio); } MilesAudioSound:: ~MilesAudioSound() { miles_audio_debug("~MilesAudioSound()"); _manager->release_sound(this); AIL_quick_unload(_audio); } void MilesAudioSound:: play() { miles_audio_debug("play()"); if (_active) { // Start playing: if (AIL_quick_play(_audio, _loop_count)) { audio_debug(" started sound"); } else { audio_debug(" failed to play sound "<<AIL_last_error()); } } else { // In case _loop_count gets set to forever (zero): audio_debug(" paused"); _paused=true; } } void MilesAudioSound:: stop() { miles_audio_debug("stop()"); _paused=false; AIL_quick_halt(_audio); } void MilesAudioSound:: set_loop(bool loop) { miles_audio_debug("set_loop(loop="<<loop<<")"); set_loop_count((loop)?0:1); } bool MilesAudioSound:: get_loop() const { miles_audio_debug("get_loop() returning "<<(_loop_count==0)); return _loop_count == 0; } void MilesAudioSound:: set_loop_count(unsigned long loop_count) { miles_audio_debug("set_loop_count(loop_count="<<loop_count<<")"); if (_loop_count!=loop_count) { _loop_count=loop_count; if (status()==PLAYING) { // hack: // For now, the loop count is picked up when the sound starts playing. // There may be a way to change the loop count of a playing sound, but // I'm going to focus on other things. If you would like to change the // need to stop and start the sound, feel free. Or, maybe I'll spend // time on it in the future. Please set the loop option before starting // the sound. stop(); play(); } } } unsigned long MilesAudioSound:: get_loop_count() const { miles_audio_debug("get_loop_count() returning "<<_loop_count); return _loop_count; } void MilesAudioSound:: set_time(float start_time) { miles_audio_debug("set_time(start_time="<<start_time<<")"); _start_time=start_time; S32 milisecond_start_time=S32(1000*_start_time); AIL_quick_set_ms_position(_audio, milisecond_start_time); } float MilesAudioSound:: get_time() const { miles_audio_debug("get_time() returning "<<_start_time); return _start_time; } void MilesAudioSound:: set_volume(float volume) { miles_audio_debug("set_volume(volume="<<volume<<")"); // *Set the volume even if our volume is not changing, because the // *MilesAudioManager will call set_volume when *its* volume changes. // Set the volume: _volume=volume; // Account for the category of sound: volume*=_manager->get_volume(); // Change to Miles volume, range 0 to 127: S32 milesVolume=((S32)(127*volume))%128; // Account for type: S32 audioType=AIL_quick_type(_audio); if (audioType==AIL_QUICK_XMIDI_TYPE || audioType==AIL_QUICK_DLS_XMIDI_TYPE) { // ...it's a midi file. AIL_quick_set_volume(_audio, milesVolume, 0); // 0 delay. audio_debug(" volume for this midi is now "<<milesVolume); } else { // ...it's a wav or mp3. // Convert balance of -1.0..1.0 to 0..127: S32 milesBalance=((S32)(63.5f*(_balance+1.0f)))%128; AIL_quick_set_volume(_audio, milesVolume, milesBalance); audio_debug(" volume for this wav or mp3 is now "<<milesVolume <<", balance="<<milesBalance); } } float MilesAudioSound:: get_volume() const { miles_audio_debug("get_volume() returning "<<_volume); return _volume; } void MilesAudioSound:: set_active(bool active) { miles_audio_debug("set_active(active="<<active<<")"); if (_active!=active) { _active=active; if (_active) { // ...activate the sound. if (_paused && _loop_count==0) { // ...this sound was looping when it was paused. _paused=false; play(); } } else { // ...deactivate the sound. if (status()==PLAYING) { if (_loop_count==0) { // ...we're pausing a looping sound. _paused=true; } stop(); } } } } bool MilesAudioSound:: get_active() const { miles_audio_debug("get_active() returning "<<_active); return _active; } void MilesAudioSound:: set_balance(float balance_right) { miles_audio_debug("set_balance(balance_right="<<balance_right<<")"); _balance=balance_right; // Call set_volume to effect the change: set_volume(_volume); } float MilesAudioSound:: get_balance() const { audio_debug("MilesAudioSound::get_balance() returning "<<_balance); return _balance; } float MilesAudioSound:: length() const { if (_length == 0.0f) { #ifndef NEED_MILES_LENGTH_WORKAROUND _length=((float)AIL_quick_ms_length(_audio))*0.001f; #else // hack: // For now, the sound needs to be playing, in order to // get the right length. I'm in contact with RAD about the problem. I've // sent them example code. They've told me they're looking into it. // Until then, we'll play the sound to get the length. if (AIL_quick_status(_audio)==QSTAT_PLAYING) { _length=((float)AIL_quick_ms_length(_audio))*0.001f; } else { AIL_quick_play(_audio, 1); _length=((float)AIL_quick_ms_length(_audio))*0.001f; AIL_quick_halt(_audio); } #endif } //audio_cat->info() << "MilesAudioSound::length() returning " << _length << endl; audio_debug("MilesAudioSound::length() returning "<<_length); return _length; } const string& MilesAudioSound:: get_name() const { //audio_debug("MilesAudioSound::get_name() returning "<<_file_name); return _file_name; } AudioSound::SoundStatus MilesAudioSound:: status() const { if (!_audio) { return AudioSound::BAD; } switch (AIL_quick_status(_audio)) { case QSTAT_LOADED: case QSTAT_DONE: return AudioSound::READY; case QSTAT_PLAYING: return AudioSound::PLAYING; default: return AudioSound::BAD; } } #endif //] <commit_msg>miles is still broken, reinstate workaround<commit_after>// Filename: milesAudioSound.cxx // Created by: skyler (June 6, 2001) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://www.panda3d.org/license.txt . // // To contact the maintainers of this program write to // panda3d@yahoogroups.com . // //////////////////////////////////////////////////////////////////// #include <pandabase.h> #ifdef HAVE_RAD_MSS //[ #include "milesAudioSound.h" #include "milesAudioManager.h" #define NEED_MILES_LENGTH_WORKAROUND #ifndef NDEBUG //[ namespace { char getStatusChar(HAUDIO audio) { if (!audio) { return '0'; // NULL. } switch (AIL_quick_status(audio)) { case QSTAT_LOADED: case QSTAT_DONE: return 'r'; // Ready. case QSTAT_PLAYING: return 'p'; // Playing. default: return 'x'; // bad. } } } #define miles_audio_debug(x) \ audio_debug("MilesAudioSound "<<getStatusChar(_audio)<<" \""<<get_name() \ <<"\" "<< x ) #else //][ #define miles_audio_debug(x) ((void)0) #endif //] MilesAudioSound:: MilesAudioSound(MilesAudioManager* manager, HAUDIO audio, string file_name, float length) : _manager(manager), _file_name(file_name), _start_time(0), _volume(1.0f), _balance(0), _loop_count(1), _length(length), _active(true), _paused(false) { nassertv(audio); nassertv(!file_name.empty()); audio_debug("MilesAudioSound(manager=0x"<<(void*)&manager <<", audio=0x"<<(void*)audio<<", file_name="<<file_name<<")"); // Make our own copy of the sound header data: _audio=AIL_quick_copy(audio); } MilesAudioSound:: ~MilesAudioSound() { miles_audio_debug("~MilesAudioSound()"); _manager->release_sound(this); AIL_quick_unload(_audio); } void MilesAudioSound:: play() { miles_audio_debug("play()"); if (_active) { // Start playing: if (AIL_quick_play(_audio, _loop_count)) { audio_debug(" started sound"); } else { audio_debug(" failed to play sound "<<AIL_last_error()); } } else { // In case _loop_count gets set to forever (zero): audio_debug(" paused"); _paused=true; } } void MilesAudioSound:: stop() { miles_audio_debug("stop()"); _paused=false; AIL_quick_halt(_audio); } void MilesAudioSound:: set_loop(bool loop) { miles_audio_debug("set_loop(loop="<<loop<<")"); set_loop_count((loop)?0:1); } bool MilesAudioSound:: get_loop() const { miles_audio_debug("get_loop() returning "<<(_loop_count==0)); return _loop_count == 0; } void MilesAudioSound:: set_loop_count(unsigned long loop_count) { miles_audio_debug("set_loop_count(loop_count="<<loop_count<<")"); if (_loop_count!=loop_count) { _loop_count=loop_count; if (status()==PLAYING) { // hack: // For now, the loop count is picked up when the sound starts playing. // There may be a way to change the loop count of a playing sound, but // I'm going to focus on other things. If you would like to change the // need to stop and start the sound, feel free. Or, maybe I'll spend // time on it in the future. Please set the loop option before starting // the sound. stop(); play(); } } } unsigned long MilesAudioSound:: get_loop_count() const { miles_audio_debug("get_loop_count() returning "<<_loop_count); return _loop_count; } void MilesAudioSound:: set_time(float start_time) { miles_audio_debug("set_time(start_time="<<start_time<<")"); _start_time=start_time; S32 milisecond_start_time=S32(1000*_start_time); AIL_quick_set_ms_position(_audio, milisecond_start_time); } float MilesAudioSound:: get_time() const { miles_audio_debug("get_time() returning "<<_start_time); return _start_time; } void MilesAudioSound:: set_volume(float volume) { miles_audio_debug("set_volume(volume="<<volume<<")"); // *Set the volume even if our volume is not changing, because the // *MilesAudioManager will call set_volume when *its* volume changes. // Set the volume: _volume=volume; // Account for the category of sound: volume*=_manager->get_volume(); // Change to Miles volume, range 0 to 127: S32 milesVolume=((S32)(127*volume))%128; // Account for type: S32 audioType=AIL_quick_type(_audio); if (audioType==AIL_QUICK_XMIDI_TYPE || audioType==AIL_QUICK_DLS_XMIDI_TYPE) { // ...it's a midi file. AIL_quick_set_volume(_audio, milesVolume, 0); // 0 delay. audio_debug(" volume for this midi is now "<<milesVolume); } else { // ...it's a wav or mp3. // Convert balance of -1.0..1.0 to 0..127: S32 milesBalance=((S32)(63.5f*(_balance+1.0f)))%128; AIL_quick_set_volume(_audio, milesVolume, milesBalance); audio_debug(" volume for this wav or mp3 is now "<<milesVolume <<", balance="<<milesBalance); } } float MilesAudioSound:: get_volume() const { miles_audio_debug("get_volume() returning "<<_volume); return _volume; } void MilesAudioSound:: set_active(bool active) { miles_audio_debug("set_active(active="<<active<<")"); if (_active!=active) { _active=active; if (_active) { // ...activate the sound. if (_paused && _loop_count==0) { // ...this sound was looping when it was paused. _paused=false; play(); } } else { // ...deactivate the sound. if (status()==PLAYING) { if (_loop_count==0) { // ...we're pausing a looping sound. _paused=true; } stop(); } } } } bool MilesAudioSound:: get_active() const { miles_audio_debug("get_active() returning "<<_active); return _active; } void MilesAudioSound:: set_balance(float balance_right) { miles_audio_debug("set_balance(balance_right="<<balance_right<<")"); _balance=balance_right; // Call set_volume to effect the change: set_volume(_volume); } float MilesAudioSound:: get_balance() const { audio_debug("MilesAudioSound::get_balance() returning "<<_balance); return _balance; } float MilesAudioSound:: length() const { if (_length == 0.0f) { #ifndef NEED_MILES_LENGTH_WORKAROUND _length=((float)AIL_quick_ms_length(_audio))*0.001f; if (_length == 0.0f) { audio_error("ERROR: Miles returned length 0 for "<<_file_name << "!"); } #else // hack: // For now, the sound needs to be playing, in order to // get the right length. I'm in contact with RAD about the problem. I've // sent them example code. They've told me they're looking into it. // Until then, we'll play the sound to get the length. // Miles 6.5c note: seems to be fixed for .mid (but not 100% positive, // we have noticed problems with midi not playing). // definitely still not fixed for .mp3 files if (AIL_quick_status(_audio)==QSTAT_PLAYING) { _length=((float)AIL_quick_ms_length(_audio))*0.001f; } else { AIL_quick_play(_audio, 1); _length=((float)AIL_quick_ms_length(_audio))*0.001f; AIL_quick_halt(_audio); } #endif } //audio_cat->info() << "MilesAudioSound::length() returning " << _length << endl; audio_debug("MilesAudioSound::length() returning "<<_length); return _length; } const string& MilesAudioSound:: get_name() const { //audio_debug("MilesAudioSound::get_name() returning "<<_file_name); return _file_name; } AudioSound::SoundStatus MilesAudioSound:: status() const { if (!_audio) { return AudioSound::BAD; } switch (AIL_quick_status(_audio)) { case QSTAT_LOADED: case QSTAT_DONE: return AudioSound::READY; case QSTAT_PLAYING: return AudioSound::PLAYING; default: return AudioSound::BAD; } } #endif //] <|endoftext|>
<commit_before>// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/web_contents_zoom_controller.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/page_type.h" #include "content/public/common/page_zoom.h" #include "net/base/url_util.h" DEFINE_WEB_CONTENTS_USER_DATA_KEY(atom::WebContentsZoomController); namespace atom { WebContentsZoomController::WebContentsZoomController( content::WebContents* web_contents) : content::WebContentsObserver(web_contents), old_process_id_(-1), old_view_id_(-1), embedder_zoom_controller_(nullptr) { default_zoom_factor_ = content::kEpsilon; host_zoom_map_ = content::HostZoomMap::GetForWebContents(web_contents); zoom_subscription_ = host_zoom_map_->AddZoomLevelChangedCallback(base::Bind( &WebContentsZoomController::OnZoomLevelChanged, base::Unretained(this))); } WebContentsZoomController::~WebContentsZoomController() {} void WebContentsZoomController::AddObserver( WebContentsZoomController::Observer* observer) { observers_.AddObserver(observer); } void WebContentsZoomController::RemoveObserver( WebContentsZoomController::Observer* observer) { observers_.RemoveObserver(observer); } void WebContentsZoomController::SetEmbedderZoomController( WebContentsZoomController* controller) { embedder_zoom_controller_ = controller; } void WebContentsZoomController::SetZoomLevel(double level) { if (!web_contents()->GetRenderViewHost()->IsRenderViewLive() || content::ZoomValuesEqual(GetZoomLevel(), level)) return; int render_process_id = web_contents()->GetRenderProcessHost()->GetID(); int render_view_id = web_contents()->GetRenderViewHost()->GetRoutingID(); if (host_zoom_map_->UsesTemporaryZoomLevel(render_process_id, render_view_id)) { host_zoom_map_->ClearTemporaryZoomLevel(render_process_id, render_view_id); } auto new_zoom_factor = content::ZoomLevelToZoomFactor(level); content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); if (entry) { std::string host = net::GetHostOrSpecFromURL(entry->GetURL()); // When new zoom level varies from kZoomFactor, it takes preference. if (!content::ZoomValuesEqual(GetDefaultZoomFactor(), new_zoom_factor)) host_zoom_factor_[host] = new_zoom_factor; content::HostZoomMap::SetZoomLevel(web_contents(), level); // Notify observers of zoom level changes. for (Observer& observer : observers_) observer.OnZoomLevelChanged(web_contents(), level, false); } } double WebContentsZoomController::GetZoomLevel() { return content::HostZoomMap::GetZoomLevel(web_contents()); } void WebContentsZoomController::SetDefaultZoomFactor(double factor) { default_zoom_factor_ = factor; } double WebContentsZoomController::GetDefaultZoomFactor() { return default_zoom_factor_; } void WebContentsZoomController::SetTemporaryZoomLevel(double level) { old_process_id_ = web_contents()->GetRenderProcessHost()->GetID(); old_view_id_ = web_contents()->GetRenderViewHost()->GetRoutingID(); host_zoom_map_->SetTemporaryZoomLevel(old_process_id_, old_view_id_, level); // Notify observers of zoom level changes. for (Observer& observer : observers_) observer.OnZoomLevelChanged(web_contents(), level, true); } bool WebContentsZoomController::UsesTemporaryZoomLevel() { int render_process_id = web_contents()->GetRenderProcessHost()->GetID(); int render_view_id = web_contents()->GetRenderViewHost()->GetRoutingID(); return host_zoom_map_->UsesTemporaryZoomLevel(render_process_id, render_view_id); } void WebContentsZoomController::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame() || !navigation_handle->HasCommitted()) return; if (navigation_handle->IsErrorPage()) { content::HostZoomMap::SendErrorPageZoomLevelRefresh(web_contents()); return; } if (!navigation_handle->IsSamePage()) SetZoomFactorOnNavigationIfNeeded(navigation_handle->GetURL()); } void WebContentsZoomController::WebContentsDestroyed() { observers_.Clear(); host_zoom_factor_.clear(); embedder_zoom_controller_ = nullptr; } void WebContentsZoomController::RenderFrameHostChanged( content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // If our associated HostZoomMap changes, update our event subscription. content::HostZoomMap* new_host_zoom_map = content::HostZoomMap::GetForWebContents(web_contents()); if (new_host_zoom_map == host_zoom_map_) return; host_zoom_map_ = new_host_zoom_map; zoom_subscription_ = host_zoom_map_->AddZoomLevelChangedCallback(base::Bind( &WebContentsZoomController::OnZoomLevelChanged, base::Unretained(this))); } void WebContentsZoomController::SetZoomFactorOnNavigationIfNeeded( const GURL& url) { if (content::ZoomValuesEqual(GetDefaultZoomFactor(), content::kEpsilon)) return; if (host_zoom_map_->UsesTemporaryZoomLevel(old_process_id_, old_view_id_)) { host_zoom_map_->ClearTemporaryZoomLevel(old_process_id_, old_view_id_); } if (embedder_zoom_controller_ && embedder_zoom_controller_->UsesTemporaryZoomLevel()) { double level = embedder_zoom_controller_->GetZoomLevel(); SetTemporaryZoomLevel(level); return; } // When kZoomFactor is available, it takes precedence over // pref store values but if the host has zoom factor set explicitly // then it takes precendence. // pref store < kZoomFactor < setZoomLevel std::string host = net::GetHostOrSpecFromURL(url); double zoom_factor = GetDefaultZoomFactor(); auto it = host_zoom_factor_.find(host); if (it != host_zoom_factor_.end()) zoom_factor = it->second; auto level = content::ZoomFactorToZoomLevel(zoom_factor); if (content::ZoomValuesEqual(level, GetZoomLevel())) return; SetZoomLevel(level); } void WebContentsZoomController::OnZoomLevelChanged( const content::HostZoomMap::ZoomLevelChange& change) { if (change.mode == content::HostZoomMap::ZOOM_CHANGED_FOR_HOST) { auto it = host_zoom_factor_.find(change.host); if (it == host_zoom_factor_.end()) return; host_zoom_factor_.insert( it, std::make_pair(change.host, content::ZoomLevelToZoomFactor(change.zoom_level))); } } } // namespace atom <commit_msg>set zoom changes for in page navigaitons<commit_after>// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/web_contents_zoom_controller.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/page_type.h" #include "content/public/common/page_zoom.h" #include "net/base/url_util.h" DEFINE_WEB_CONTENTS_USER_DATA_KEY(atom::WebContentsZoomController); namespace atom { WebContentsZoomController::WebContentsZoomController( content::WebContents* web_contents) : content::WebContentsObserver(web_contents), old_process_id_(-1), old_view_id_(-1), embedder_zoom_controller_(nullptr) { default_zoom_factor_ = content::kEpsilon; host_zoom_map_ = content::HostZoomMap::GetForWebContents(web_contents); zoom_subscription_ = host_zoom_map_->AddZoomLevelChangedCallback(base::Bind( &WebContentsZoomController::OnZoomLevelChanged, base::Unretained(this))); } WebContentsZoomController::~WebContentsZoomController() {} void WebContentsZoomController::AddObserver( WebContentsZoomController::Observer* observer) { observers_.AddObserver(observer); } void WebContentsZoomController::RemoveObserver( WebContentsZoomController::Observer* observer) { observers_.RemoveObserver(observer); } void WebContentsZoomController::SetEmbedderZoomController( WebContentsZoomController* controller) { embedder_zoom_controller_ = controller; } void WebContentsZoomController::SetZoomLevel(double level) { if (!web_contents()->GetRenderViewHost()->IsRenderViewLive() || content::ZoomValuesEqual(GetZoomLevel(), level)) return; int render_process_id = web_contents()->GetRenderProcessHost()->GetID(); int render_view_id = web_contents()->GetRenderViewHost()->GetRoutingID(); if (host_zoom_map_->UsesTemporaryZoomLevel(render_process_id, render_view_id)) { host_zoom_map_->ClearTemporaryZoomLevel(render_process_id, render_view_id); } auto new_zoom_factor = content::ZoomLevelToZoomFactor(level); content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); if (entry) { std::string host = net::GetHostOrSpecFromURL(entry->GetURL()); // When new zoom level varies from kZoomFactor, it takes preference. if (!content::ZoomValuesEqual(GetDefaultZoomFactor(), new_zoom_factor)) host_zoom_factor_[host] = new_zoom_factor; content::HostZoomMap::SetZoomLevel(web_contents(), level); // Notify observers of zoom level changes. for (Observer& observer : observers_) observer.OnZoomLevelChanged(web_contents(), level, false); } } double WebContentsZoomController::GetZoomLevel() { return content::HostZoomMap::GetZoomLevel(web_contents()); } void WebContentsZoomController::SetDefaultZoomFactor(double factor) { default_zoom_factor_ = factor; } double WebContentsZoomController::GetDefaultZoomFactor() { return default_zoom_factor_; } void WebContentsZoomController::SetTemporaryZoomLevel(double level) { old_process_id_ = web_contents()->GetRenderProcessHost()->GetID(); old_view_id_ = web_contents()->GetRenderViewHost()->GetRoutingID(); host_zoom_map_->SetTemporaryZoomLevel(old_process_id_, old_view_id_, level); // Notify observers of zoom level changes. for (Observer& observer : observers_) observer.OnZoomLevelChanged(web_contents(), level, true); } bool WebContentsZoomController::UsesTemporaryZoomLevel() { int render_process_id = web_contents()->GetRenderProcessHost()->GetID(); int render_view_id = web_contents()->GetRenderViewHost()->GetRoutingID(); return host_zoom_map_->UsesTemporaryZoomLevel(render_process_id, render_view_id); } void WebContentsZoomController::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame() || !navigation_handle->HasCommitted()) return; if (navigation_handle->IsErrorPage()) { content::HostZoomMap::SendErrorPageZoomLevelRefresh(web_contents()); return; } SetZoomFactorOnNavigationIfNeeded(navigation_handle->GetURL()); } void WebContentsZoomController::WebContentsDestroyed() { observers_.Clear(); host_zoom_factor_.clear(); embedder_zoom_controller_ = nullptr; } void WebContentsZoomController::RenderFrameHostChanged( content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // If our associated HostZoomMap changes, update our event subscription. content::HostZoomMap* new_host_zoom_map = content::HostZoomMap::GetForWebContents(web_contents()); if (new_host_zoom_map == host_zoom_map_) return; host_zoom_map_ = new_host_zoom_map; zoom_subscription_ = host_zoom_map_->AddZoomLevelChangedCallback(base::Bind( &WebContentsZoomController::OnZoomLevelChanged, base::Unretained(this))); } void WebContentsZoomController::SetZoomFactorOnNavigationIfNeeded( const GURL& url) { if (content::ZoomValuesEqual(GetDefaultZoomFactor(), content::kEpsilon)) return; if (host_zoom_map_->UsesTemporaryZoomLevel(old_process_id_, old_view_id_)) { host_zoom_map_->ClearTemporaryZoomLevel(old_process_id_, old_view_id_); } if (embedder_zoom_controller_ && embedder_zoom_controller_->UsesTemporaryZoomLevel()) { double level = embedder_zoom_controller_->GetZoomLevel(); SetTemporaryZoomLevel(level); return; } // When kZoomFactor is available, it takes precedence over // pref store values but if the host has zoom factor set explicitly // then it takes precendence. // pref store < kZoomFactor < setZoomLevel std::string host = net::GetHostOrSpecFromURL(url); double zoom_factor = GetDefaultZoomFactor(); auto it = host_zoom_factor_.find(host); if (it != host_zoom_factor_.end()) zoom_factor = it->second; auto level = content::ZoomFactorToZoomLevel(zoom_factor); if (content::ZoomValuesEqual(level, GetZoomLevel())) return; SetZoomLevel(level); } void WebContentsZoomController::OnZoomLevelChanged( const content::HostZoomMap::ZoomLevelChange& change) { if (change.mode == content::HostZoomMap::ZOOM_CHANGED_FOR_HOST) { auto it = host_zoom_factor_.find(change.host); if (it == host_zoom_factor_.end()) return; host_zoom_factor_.insert( it, std::make_pair(change.host, content::ZoomLevelToZoomFactor(change.zoom_level))); } } } // namespace atom <|endoftext|>
<commit_before>/************************************************************************* * * 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: unopolypolygon.hxx,v $ * * $Revision: 1.3 $ * * 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 INCLUDED_BASEGFX_UNOPOLYPOLYGON_HXX #define INCLUDED_BASEGFX_UNOPOLYPOLYGON_HXX #include <cppuhelper/basemutex.hxx> #include <cppuhelper/compbase3.hxx> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/rendering/FillRule.hpp> #include <com/sun/star/rendering/XLinePolyPolygon2D.hpp> #include <com/sun/star/rendering/XBezierPolyPolygon2D.hpp> #include <basegfx/polygon/b2dpolypolygon.hxx> namespace basegfx { namespace unotools { typedef ::cppu::WeakComponentImplHelper3< ::com::sun::star::rendering::XLinePolyPolygon2D, ::com::sun::star::rendering::XBezierPolyPolygon2D, ::com::sun::star::lang::XServiceInfo > UnoPolyPolygonBase; class UnoPolyPolygon : private cppu::BaseMutex, public UnoPolyPolygonBase { public: explicit UnoPolyPolygon( const B2DPolyPolygon& ); // XPolyPolygon2D virtual void SAL_CALL addPolyPolygon( const ::com::sun::star::geometry::RealPoint2D& position, const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& polyPolygon ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getNumberOfPolygons( ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getNumberOfPolygonPoints( ::sal_Int32 polygon ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::rendering::FillRule SAL_CALL getFillRule( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setFillRule( ::com::sun::star::rendering::FillRule fillRule ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL isClosed( ::sal_Int32 index ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setClosed( ::sal_Int32 index, ::sal_Bool closedState ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // XLinePolyPolygon2D virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealPoint2D > > SAL_CALL getPoints( ::sal_Int32 nPolygonIndex, ::sal_Int32 nNumberOfPolygons, ::sal_Int32 nPointIndex, ::sal_Int32 nNumberOfPoints ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPoints( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealPoint2D > >& points, ::sal_Int32 nPolygonIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::geometry::RealPoint2D SAL_CALL getPoint( ::sal_Int32 nPolygonIndex, ::sal_Int32 nPointIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPoint( const ::com::sun::star::geometry::RealPoint2D& point, ::sal_Int32 nPolygonIndex, ::sal_Int32 nPointIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // XBezierPolyPolygon2D virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealBezierSegment2D > > SAL_CALL getBezierSegments( ::sal_Int32 nPolygonIndex, ::sal_Int32 nNumberOfPolygons, ::sal_Int32 nPointIndex, ::sal_Int32 nNumberOfPoints ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBezierSegments( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealBezierSegment2D > >& points, ::sal_Int32 nPolygonIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::geometry::RealBezierSegment2D SAL_CALL getBezierSegment( ::sal_Int32 nPolygonIndex, ::sal_Int32 nPointIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBezierSegment( const ::com::sun::star::geometry::RealBezierSegment2D& point, ::sal_Int32 nPolygonIndex, ::sal_Int32 nPointIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException ); B2DPolyPolygon getPolyPolygon() const; protected: /// Check whether index is a valid polygon index void checkIndex( sal_Int32 nIndex ) const // throw (::com::sun::star::lang::IndexOutOfBoundsException); { if( nIndex < 0 || nIndex >= static_cast<sal_Int32>(maPolyPoly.count()) ) throw ::com::sun::star::lang::IndexOutOfBoundsException(); } B2DPolyPolygon getSubsetPolyPolygon( sal_Int32 nPolygonIndex, sal_Int32 nNumberOfPolygons, sal_Int32 nPointIndex, sal_Int32 nNumberOfPoints ) const; /// Get cow copy of internal polygon. not thread-safe outside this object. B2DPolyPolygon getPolyPolygonUnsafe() const; /// Called whenever internal polypolygon gets modified virtual void modifying() const {} private: UnoPolyPolygon( const UnoPolyPolygon& ); UnoPolyPolygon& operator=( const UnoPolyPolygon& ); B2DPolyPolygon maPolyPoly; ::com::sun::star::rendering::FillRule meFillRule; }; } } #endif /* INCLUDED_BASEGFX_UNOPOLYPOLYGON_HXX */ <commit_msg>INTEGRATION: CWS aw033 (1.3.4); FILE MERGED 2008/05/27 14:08:44 aw 1.3.4.1: #i39532# changes DEV300 m12 resync corrections<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: unopolypolygon.hxx,v $ * * $Revision: 1.4 $ * * 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 INCLUDED_BASEGFX_UNOPOLYPOLYGON_HXX #define INCLUDED_BASEGFX_UNOPOLYPOLYGON_HXX #include <cppuhelper/basemutex.hxx> #include <cppuhelper/compbase3.hxx> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/rendering/FillRule.hpp> #include <com/sun/star/rendering/XLinePolyPolygon2D.hpp> #include <com/sun/star/rendering/XBezierPolyPolygon2D.hpp> #include <basegfx/polygon/b2dpolypolygon.hxx> namespace basegfx { namespace unotools { typedef ::cppu::WeakComponentImplHelper3< ::com::sun::star::rendering::XLinePolyPolygon2D, ::com::sun::star::rendering::XBezierPolyPolygon2D, ::com::sun::star::lang::XServiceInfo > UnoPolyPolygonBase; class UnoPolyPolygon : private cppu::BaseMutex, public UnoPolyPolygonBase { public: explicit UnoPolyPolygon( const B2DPolyPolygon& ); // XPolyPolygon2D virtual void SAL_CALL addPolyPolygon( const ::com::sun::star::geometry::RealPoint2D& position, const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& polyPolygon ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getNumberOfPolygons( ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Int32 SAL_CALL getNumberOfPolygonPoints( ::sal_Int32 polygon ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::rendering::FillRule SAL_CALL getFillRule( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setFillRule( ::com::sun::star::rendering::FillRule fillRule ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL isClosed( ::sal_Int32 index ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setClosed( ::sal_Int32 index, ::sal_Bool closedState ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // XLinePolyPolygon2D virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealPoint2D > > SAL_CALL getPoints( ::sal_Int32 nPolygonIndex, ::sal_Int32 nNumberOfPolygons, ::sal_Int32 nPointIndex, ::sal_Int32 nNumberOfPoints ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPoints( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealPoint2D > >& points, ::sal_Int32 nPolygonIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::geometry::RealPoint2D SAL_CALL getPoint( ::sal_Int32 nPolygonIndex, ::sal_Int32 nPointIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPoint( const ::com::sun::star::geometry::RealPoint2D& point, ::sal_Int32 nPolygonIndex, ::sal_Int32 nPointIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // XBezierPolyPolygon2D virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealBezierSegment2D > > SAL_CALL getBezierSegments( ::sal_Int32 nPolygonIndex, ::sal_Int32 nNumberOfPolygons, ::sal_Int32 nPointIndex, ::sal_Int32 nNumberOfPoints ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBezierSegments( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealBezierSegment2D > >& points, ::sal_Int32 nPolygonIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::geometry::RealBezierSegment2D SAL_CALL getBezierSegment( ::sal_Int32 nPolygonIndex, ::sal_Int32 nPointIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBezierSegment( const ::com::sun::star::geometry::RealBezierSegment2D& point, ::sal_Int32 nPolygonIndex, ::sal_Int32 nPointIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException ); B2DPolyPolygon getPolyPolygon() const; protected: /// Check whether index is a valid polygon index void checkIndex( sal_Int32 nIndex ) const // throw (::com::sun::star::lang::IndexOutOfBoundsException); { if( nIndex < 0 || nIndex >= static_cast<sal_Int32>(maPolyPoly.count()) ) throw ::com::sun::star::lang::IndexOutOfBoundsException(); } B2DPolyPolygon getSubsetPolyPolygon( sal_Int32 nPolygonIndex, sal_Int32 nNumberOfPolygons, sal_Int32 nPointIndex, sal_Int32 nNumberOfPoints ) const; /// Get cow copy of internal polygon. not thread-safe outside this object. B2DPolyPolygon getPolyPolygonUnsafe() const; /// Called whenever internal polypolygon gets modified virtual void modifying() const {} private: UnoPolyPolygon( const UnoPolyPolygon& ); UnoPolyPolygon& operator=( const UnoPolyPolygon& ); B2DPolyPolygon maPolyPoly; ::com::sun::star::rendering::FillRule meFillRule; }; } } #endif /* INCLUDED_BASEGFX_UNOPOLYPOLYGON_HXX */ <|endoftext|>
<commit_before>//===--- LivePhysRegs.cpp - Live Physical Register Set --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the LivePhysRegs utility for tracking liveness of // physical registers across machine instructions in forward or backward order. // A more detailed description can be found in the corresponding header file. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/LivePhysRegs.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBundle.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; /// \brief Remove all registers from the set that get clobbered by the register /// mask. /// The clobbers set will be the list of live registers clobbered /// by the regmask. void LivePhysRegs::removeRegsInMask(const MachineOperand &MO, SmallVectorImpl<std::pair<unsigned, const MachineOperand*>> *Clobbers) { SparseSet<unsigned>::iterator LRI = LiveRegs.begin(); while (LRI != LiveRegs.end()) { if (MO.clobbersPhysReg(*LRI)) { if (Clobbers) Clobbers->push_back(std::make_pair(*LRI, &MO)); LRI = LiveRegs.erase(LRI); } else ++LRI; } } /// Simulates liveness when stepping backwards over an instruction(bundle): /// Remove Defs, add uses. This is the recommended way of calculating liveness. void LivePhysRegs::stepBackward(const MachineInstr &MI) { // Remove defined registers and regmask kills from the set. for (ConstMIBundleOperands O(MI); O.isValid(); ++O) { if (O->isReg()) { if (!O->isDef()) continue; unsigned Reg = O->getReg(); if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue; removeReg(Reg); } else if (O->isRegMask()) removeRegsInMask(*O, nullptr); } // Add uses to the set. for (ConstMIBundleOperands O(MI); O.isValid(); ++O) { if (!O->isReg() || !O->readsReg()) continue; unsigned Reg = O->getReg(); if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue; addReg(Reg); } } /// Simulates liveness when stepping forward over an instruction(bundle): Remove /// killed-uses, add defs. This is the not recommended way, because it depends /// on accurate kill flags. If possible use stepBackward() instead of this /// function. void LivePhysRegs::stepForward(const MachineInstr &MI, SmallVectorImpl<std::pair<unsigned, const MachineOperand*>> &Clobbers) { // Remove killed registers from the set. for (ConstMIBundleOperands O(MI); O.isValid(); ++O) { if (O->isReg()) { unsigned Reg = O->getReg(); if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue; if (O->isDef()) { // Note, dead defs are still recorded. The caller should decide how to // handle them. Clobbers.push_back(std::make_pair(Reg, &*O)); } else { if (!O->isKill()) continue; assert(O->isUse()); removeReg(Reg); } } else if (O->isRegMask()) removeRegsInMask(*O, &Clobbers); } // Add defs to the set. for (auto Reg : Clobbers) { // Skip dead defs. They shouldn't be added to the set. if (Reg.second->isReg() && Reg.second->isDead()) continue; addReg(Reg.first); } } /// Prin the currently live registers to OS. void LivePhysRegs::print(raw_ostream &OS) const { OS << "Live Registers:"; if (!TRI) { OS << " (uninitialized)\n"; return; } if (empty()) { OS << " (empty)\n"; return; } for (const_iterator I = begin(), E = end(); I != E; ++I) OS << " " << PrintReg(*I, TRI); OS << "\n"; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void LivePhysRegs::dump() const { dbgs() << " " << *this; } #endif bool LivePhysRegs::available(const MachineRegisterInfo &MRI, unsigned Reg) const { if (LiveRegs.count(Reg)) return false; if (MRI.isReserved(Reg)) return false; for (MCRegAliasIterator R(Reg, TRI, false); R.isValid(); ++R) { if (LiveRegs.count(*R)) return false; } return true; } /// Add live-in registers of basic block \p MBB to \p LiveRegs. void LivePhysRegs::addBlockLiveIns(const MachineBasicBlock &MBB) { for (const auto &LI : MBB.liveins()) { MCSubRegIndexIterator S(LI.PhysReg, TRI); if (LI.LaneMask.all() || (LI.LaneMask.any() && !S.isValid())) { addReg(LI.PhysReg); continue; } for (; S.isValid(); ++S) { unsigned SI = S.getSubRegIndex(); if ((LI.LaneMask & TRI->getSubRegIndexLaneMask(SI)).any()) addReg(S.getSubReg()); } } } /// Adds all callee saved registers to \p LiveRegs. static void addCalleeSavedRegs(LivePhysRegs &LiveRegs, const MachineFunction &MF) { const MachineRegisterInfo &MRI = MF.getRegInfo(); for (const MCPhysReg *CSR = MRI.getCalleeSavedRegs(); CSR && *CSR; ++CSR) LiveRegs.addReg(*CSR); } /// Adds pristine registers to the given \p LiveRegs. Pristine registers are /// callee saved registers that are unused in the function. static void addPristines(LivePhysRegs &LiveRegs, const MachineFunction &MF) { const MachineFrameInfo &MFI = MF.getFrameInfo(); if (!MFI.isCalleeSavedInfoValid()) return; /// Add all callee saved regs, then remove the ones that are saved+restored. addCalleeSavedRegs(LiveRegs, MF); /// Remove the ones that are not saved/restored; they are pristine. for (const CalleeSavedInfo &Info : MFI.getCalleeSavedInfo()) LiveRegs.removeReg(Info.getReg()); } void LivePhysRegs::addLiveOutsNoPristines(const MachineBasicBlock &MBB) { if (!MBB.succ_empty()) { // To get the live-outs we simply merge the live-ins of all successors. for (const MachineBasicBlock *Succ : MBB.successors()) addBlockLiveIns(*Succ); } else if (MBB.isReturnBlock()) { // For the return block: Add all callee saved registers that are saved and // restored (somewhere); This does not include callee saved registers that // are unused and hence not saved and restored; they are called pristine. const MachineFunction &MF = *MBB.getParent(); const MachineFrameInfo &MFI = MF.getFrameInfo(); if (MFI.isCalleeSavedInfoValid()) { for (const CalleeSavedInfo &Info : MFI.getCalleeSavedInfo()) addReg(Info.getReg()); } } } void LivePhysRegs::addLiveOuts(const MachineBasicBlock &MBB) { if (!MBB.succ_empty()) { addLiveOutsNoPristines(MBB); const MachineFunction &MF = *MBB.getParent(); addPristines(*this, MF); } else if (MBB.isReturnBlock()) { // For the return block: Add all callee saved registers. const MachineFunction &MF = *MBB.getParent(); const MachineFrameInfo &MFI = MF.getFrameInfo(); if (MFI.isCalleeSavedInfoValid()) addCalleeSavedRegs(*this, MF); } } void LivePhysRegs::addLiveIns(const MachineBasicBlock &MBB) { const MachineFunction &MF = *MBB.getParent(); addPristines(*this, MF); addBlockLiveIns(MBB); } void llvm::computeLiveIns(LivePhysRegs &LiveRegs, const MachineRegisterInfo &MRI, MachineBasicBlock &MBB) { const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); assert(MBB.livein_empty()); LiveRegs.init(TRI); LiveRegs.addLiveOutsNoPristines(MBB); for (MachineInstr &MI : make_range(MBB.rbegin(), MBB.rend())) LiveRegs.stepBackward(MI); for (unsigned Reg : LiveRegs) { if (MRI.isReserved(Reg)) continue; // Skip the register if we are about to add one of its super registers. bool ContainsSuperReg = false; for (MCSuperRegIterator SReg(Reg, &TRI); SReg.isValid(); ++SReg) { if (LiveRegs.contains(*SReg)) { ContainsSuperReg = true; break; } } if (ContainsSuperReg) continue; MBB.addLiveIn(Reg); } } <commit_msg>LivePhysRegs: Follow-up to r303937<commit_after>//===--- LivePhysRegs.cpp - Live Physical Register Set --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the LivePhysRegs utility for tracking liveness of // physical registers across machine instructions in forward or backward order. // A more detailed description can be found in the corresponding header file. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/LivePhysRegs.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBundle.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; /// \brief Remove all registers from the set that get clobbered by the register /// mask. /// The clobbers set will be the list of live registers clobbered /// by the regmask. void LivePhysRegs::removeRegsInMask(const MachineOperand &MO, SmallVectorImpl<std::pair<unsigned, const MachineOperand*>> *Clobbers) { SparseSet<unsigned>::iterator LRI = LiveRegs.begin(); while (LRI != LiveRegs.end()) { if (MO.clobbersPhysReg(*LRI)) { if (Clobbers) Clobbers->push_back(std::make_pair(*LRI, &MO)); LRI = LiveRegs.erase(LRI); } else ++LRI; } } /// Simulates liveness when stepping backwards over an instruction(bundle): /// Remove Defs, add uses. This is the recommended way of calculating liveness. void LivePhysRegs::stepBackward(const MachineInstr &MI) { // Remove defined registers and regmask kills from the set. for (ConstMIBundleOperands O(MI); O.isValid(); ++O) { if (O->isReg()) { if (!O->isDef()) continue; unsigned Reg = O->getReg(); if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue; removeReg(Reg); } else if (O->isRegMask()) removeRegsInMask(*O, nullptr); } // Add uses to the set. for (ConstMIBundleOperands O(MI); O.isValid(); ++O) { if (!O->isReg() || !O->readsReg()) continue; unsigned Reg = O->getReg(); if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue; addReg(Reg); } } /// Simulates liveness when stepping forward over an instruction(bundle): Remove /// killed-uses, add defs. This is the not recommended way, because it depends /// on accurate kill flags. If possible use stepBackward() instead of this /// function. void LivePhysRegs::stepForward(const MachineInstr &MI, SmallVectorImpl<std::pair<unsigned, const MachineOperand*>> &Clobbers) { // Remove killed registers from the set. for (ConstMIBundleOperands O(MI); O.isValid(); ++O) { if (O->isReg()) { unsigned Reg = O->getReg(); if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue; if (O->isDef()) { // Note, dead defs are still recorded. The caller should decide how to // handle them. Clobbers.push_back(std::make_pair(Reg, &*O)); } else { if (!O->isKill()) continue; assert(O->isUse()); removeReg(Reg); } } else if (O->isRegMask()) removeRegsInMask(*O, &Clobbers); } // Add defs to the set. for (auto Reg : Clobbers) { // Skip dead defs. They shouldn't be added to the set. if (Reg.second->isReg() && Reg.second->isDead()) continue; addReg(Reg.first); } } /// Prin the currently live registers to OS. void LivePhysRegs::print(raw_ostream &OS) const { OS << "Live Registers:"; if (!TRI) { OS << " (uninitialized)\n"; return; } if (empty()) { OS << " (empty)\n"; return; } for (const_iterator I = begin(), E = end(); I != E; ++I) OS << " " << PrintReg(*I, TRI); OS << "\n"; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void LivePhysRegs::dump() const { dbgs() << " " << *this; } #endif bool LivePhysRegs::available(const MachineRegisterInfo &MRI, unsigned Reg) const { if (LiveRegs.count(Reg)) return false; if (MRI.isReserved(Reg)) return false; for (MCRegAliasIterator R(Reg, TRI, false); R.isValid(); ++R) { if (LiveRegs.count(*R)) return false; } return true; } /// Add live-in registers of basic block \p MBB to \p LiveRegs. void LivePhysRegs::addBlockLiveIns(const MachineBasicBlock &MBB) { for (const auto &LI : MBB.liveins()) { MCSubRegIndexIterator S(LI.PhysReg, TRI); if (LI.LaneMask.all() || (LI.LaneMask.any() && !S.isValid())) { addReg(LI.PhysReg); continue; } for (; S.isValid(); ++S) { unsigned SI = S.getSubRegIndex(); if ((LI.LaneMask & TRI->getSubRegIndexLaneMask(SI)).any()) addReg(S.getSubReg()); } } } /// Adds all callee saved registers to \p LiveRegs. static void addCalleeSavedRegs(LivePhysRegs &LiveRegs, const MachineFunction &MF) { const MachineRegisterInfo &MRI = MF.getRegInfo(); for (const MCPhysReg *CSR = MRI.getCalleeSavedRegs(); CSR && *CSR; ++CSR) LiveRegs.addReg(*CSR); } /// Adds pristine registers to the given \p LiveRegs. Pristine registers are /// callee saved registers that are unused in the function. static void addPristines(LivePhysRegs &LiveRegs, const MachineFunction &MF) { const MachineFrameInfo &MFI = MF.getFrameInfo(); if (!MFI.isCalleeSavedInfoValid()) return; /// Add all callee saved regs, then remove the ones that are saved+restored. addCalleeSavedRegs(LiveRegs, MF); /// Remove the ones that are not saved/restored; they are pristine. for (const CalleeSavedInfo &Info : MFI.getCalleeSavedInfo()) LiveRegs.removeReg(Info.getReg()); } void LivePhysRegs::addLiveOutsNoPristines(const MachineBasicBlock &MBB) { if (!MBB.succ_empty()) { // To get the live-outs we simply merge the live-ins of all successors. for (const MachineBasicBlock *Succ : MBB.successors()) addBlockLiveIns(*Succ); } else if (MBB.isReturnBlock()) { // For the return block: Add all callee saved registers that are saved and // restored (somewhere); This does not include callee saved registers that // are unused and hence not saved and restored; they are called pristine. const MachineFunction &MF = *MBB.getParent(); const MachineFrameInfo &MFI = MF.getFrameInfo(); if (MFI.isCalleeSavedInfoValid()) { for (const CalleeSavedInfo &Info : MFI.getCalleeSavedInfo()) addReg(Info.getReg()); } } } void LivePhysRegs::addLiveOuts(const MachineBasicBlock &MBB) { if (!MBB.succ_empty()) { addLiveOutsNoPristines(MBB); const MachineFunction &MF = *MBB.getParent(); addPristines(*this, MF); } else if (MBB.isReturnBlock()) { // For the return block: Add all callee saved registers. const MachineFunction &MF = *MBB.getParent(); const MachineFrameInfo &MFI = MF.getFrameInfo(); if (MFI.isCalleeSavedInfoValid()) addCalleeSavedRegs(*this, MF); } } void LivePhysRegs::addLiveIns(const MachineBasicBlock &MBB) { const MachineFunction &MF = *MBB.getParent(); addPristines(*this, MF); addBlockLiveIns(MBB); } void llvm::computeLiveIns(LivePhysRegs &LiveRegs, const MachineRegisterInfo &MRI, MachineBasicBlock &MBB) { const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); assert(MBB.livein_empty()); LiveRegs.init(TRI); LiveRegs.addLiveOutsNoPristines(MBB); for (MachineInstr &MI : make_range(MBB.rbegin(), MBB.rend())) LiveRegs.stepBackward(MI); for (unsigned Reg : LiveRegs) { if (MRI.isReserved(Reg)) continue; // Skip the register if we are about to add one of its super registers. bool ContainsSuperReg = false; for (MCSuperRegIterator SReg(Reg, &TRI); SReg.isValid(); ++SReg) { if (LiveRegs.contains(*SReg) && !MRI.isReserved(*SReg)) { ContainsSuperReg = true; break; } } if (ContainsSuperReg) continue; MBB.addLiveIn(Reg); } } <|endoftext|>
<commit_before>/***************************************************************************//** * context.cpp * * The main root structure of cmgui. */ /* OpenCMISS-Zinc Library * * 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/. */ #if !defined (CONTEXT_H) #define CONTEXT_H #include <list> #include "opencmiss/zinc/context.h" #include "opencmiss/zinc/status.h" #include "general/message_log.hpp" #include "general/manager.h" struct cmzn_graphics_module; struct cmzn_context { friend struct Element_point_ranges_selection *cmzn_context_get_element_point_ranges_selection( cmzn_context *context); friend struct IO_stream_package *cmzn_context_get_default_IO_stream_package( cmzn_context *context); private: const char *id; cmzn_logger *logger; cmzn_region *defaultRegion; struct Element_point_ranges_selection *element_point_ranges_selection; //-- struct Event_dispatcher *event_dispatcher; struct IO_stream_package *io_stream_package; cmzn_timekeepermodule *timekeepermodule; std::list<cmzn_region *> allRegions; // list of all regions created for context, not accessed cmzn_graphics_module *graphics_module; int access_count; cmzn_context(const char *idIn); ~cmzn_context(); public: inline cmzn_context *access() { ++access_count; return this; } static inline int deaccess(cmzn_context*& context) { if (context) { --(context->access_count); if (context->access_count <= 0) delete context; context = 0; return CMZN_OK; } return CMZN_ERROR_ARGUMENT; } static cmzn_context *create(const char *id); cmzn_region *createRegion(); void removeRegion(cmzn_region *region); cmzn_graphics_module *getGraphicsmodule() { return this->graphics_module; } /** Get any region from context from which to copy FE_region information */ cmzn_region *getBaseRegion() const { return (this->allRegions.size() > 0) ? this->allRegions.front() : nullptr; } /** Get default region or nullptr if none */ cmzn_region *getDefaultRegion() const { return this->defaultRegion; } /** Set default region if you wish context to manage it */ int cmzn_context::setDefaultRegion(cmzn_region *regionIn); cmzn_logger *getLogger() const { return this->logger; } const std::list<cmzn_region *>& getRegionsList() const { return this->allRegions; } cmzn_timekeepermodule *getTimekeepermodule() const { return this->timekeepermodule; } }; /***************************************************************************//** * Return the element point ranges selection in context. * * @param context Pointer to a cmiss_context object. * @return the Element_point_ranges_selection if successfully, otherwise NULL. */ struct Element_point_ranges_selection *cmzn_context_get_element_point_ranges_selection( cmzn_context *context); /***************************************************************************//** * Return the IO_stream_package in context. Used by Cmgui only. * * @param context Pointer to a cmiss_context object. * @return the default IO_stream_package if successfully, otherwise NULL. */ struct IO_stream_package *cmzn_context_get_default_IO_stream_package( cmzn_context *context); #endif /* !defined (CONTEXT_H) */ <commit_msg>Remove class qualification from declaration setDefualtRegion.<commit_after>/***************************************************************************//** * context.cpp * * The main root structure of cmgui. */ /* OpenCMISS-Zinc Library * * 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/. */ #if !defined (CONTEXT_H) #define CONTEXT_H #include <list> #include "opencmiss/zinc/context.h" #include "opencmiss/zinc/status.h" #include "general/message_log.hpp" #include "general/manager.h" struct cmzn_graphics_module; struct cmzn_context { friend struct Element_point_ranges_selection *cmzn_context_get_element_point_ranges_selection( cmzn_context *context); friend struct IO_stream_package *cmzn_context_get_default_IO_stream_package( cmzn_context *context); private: const char *id; cmzn_logger *logger; cmzn_region *defaultRegion; struct Element_point_ranges_selection *element_point_ranges_selection; //-- struct Event_dispatcher *event_dispatcher; struct IO_stream_package *io_stream_package; cmzn_timekeepermodule *timekeepermodule; std::list<cmzn_region *> allRegions; // list of all regions created for context, not accessed cmzn_graphics_module *graphics_module; int access_count; cmzn_context(const char *idIn); ~cmzn_context(); public: inline cmzn_context *access() { ++access_count; return this; } static inline int deaccess(cmzn_context*& context) { if (context) { --(context->access_count); if (context->access_count <= 0) delete context; context = 0; return CMZN_OK; } return CMZN_ERROR_ARGUMENT; } static cmzn_context *create(const char *id); cmzn_region *createRegion(); void removeRegion(cmzn_region *region); cmzn_graphics_module *getGraphicsmodule() { return this->graphics_module; } /** Get any region from context from which to copy FE_region information */ cmzn_region *getBaseRegion() const { return (this->allRegions.size() > 0) ? this->allRegions.front() : nullptr; } /** Get default region or nullptr if none */ cmzn_region *getDefaultRegion() const { return this->defaultRegion; } /** Set default region if you wish context to manage it */ int setDefaultRegion(cmzn_region *regionIn); cmzn_logger *getLogger() const { return this->logger; } const std::list<cmzn_region *>& getRegionsList() const { return this->allRegions; } cmzn_timekeepermodule *getTimekeepermodule() const { return this->timekeepermodule; } }; /***************************************************************************//** * Return the element point ranges selection in context. * * @param context Pointer to a cmiss_context object. * @return the Element_point_ranges_selection if successfully, otherwise NULL. */ struct Element_point_ranges_selection *cmzn_context_get_element_point_ranges_selection( cmzn_context *context); /***************************************************************************//** * Return the IO_stream_package in context. Used by Cmgui only. * * @param context Pointer to a cmiss_context object. * @return the default IO_stream_package if successfully, otherwise NULL. */ struct IO_stream_package *cmzn_context_get_default_IO_stream_package( cmzn_context *context); #endif /* !defined (CONTEXT_H) */ <|endoftext|>
<commit_before>/* Copyright 2016 The TensorFlow 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 "tensorflow/java/src/main/native/operation_builder_jni.h" #include <memory> #include "tensorflow/c/c_api.h" #include "tensorflow/java/src/main/native/exception_jni.h" namespace { TF_OperationDescription* requireHandle(JNIEnv* env, jlong handle) { if (handle == 0) { throwException(env, kIllegalStateException, "Operation has already been built"); return 0; } return reinterpret_cast<TF_OperationDescription*>(handle); } bool resolveOutput(JNIEnv* env, jlong op_handle, jint index, TF_Output* out) { if (op_handle == 0) { throwException(env, kIllegalStateException, "close() was called on the Graph"); return false; } out->oper = reinterpret_cast<TF_Operation*>(op_handle); out->index = static_cast<int>(index); return true; } TF_Tensor* requireTensor(JNIEnv* env, jlong handle) { if (handle == 0) { throwException(env, kIllegalStateException, "close() has been called on the Tensor"); return nullptr; } return reinterpret_cast<TF_Tensor*>(handle); } } // namespace JNIEXPORT jlong JNICALL Java_org_tensorflow_OperationBuilder_allocate( JNIEnv* env, jclass clazz, jlong graph_handle, jstring type, jstring name) { if (graph_handle == 0) { throwException(env, kIllegalStateException, "close() has been called on the Graph"); return 0; } TF_Graph* graph = reinterpret_cast<TF_Graph*>(graph_handle); const char* op_type = env->GetStringUTFChars(type, nullptr); const char* op_name = env->GetStringUTFChars(name, nullptr); TF_OperationDescription* d = TF_NewOperation(graph, op_type, op_name); env->ReleaseStringUTFChars(name, op_name); env->ReleaseStringUTFChars(type, op_type); static_assert(sizeof(jlong) >= sizeof(TF_OperationDescription*), "Cannot represent a C TF_OperationDescription as a Java long"); return reinterpret_cast<jlong>(d); } JNIEXPORT jlong JNICALL Java_org_tensorflow_OperationBuilder_finish( JNIEnv* env, jclass clazz, jlong handle) { TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return 0; TF_Status* status = TF_NewStatus(); TF_Operation* op = TF_FinishOperation(d, status); if (throwExceptionIfNotOK(env, status)) { return reinterpret_cast<jlong>(op); } return 0; } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_addInput( JNIEnv* env, jclass clazz, jlong handle, jlong op_handle, jint index) { TF_Output out; if (!resolveOutput(env, op_handle, index, &out)) return; TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; TF_AddInput(d, out); } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_addInputList( JNIEnv* env, jclass clazz, jlong handle, jlongArray op_handles, jintArray indices) { TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; const size_t n = static_cast<size_t>(env->GetArrayLength(op_handles)); if (env->GetArrayLength(indices) != n) { throwException(env, kIllegalArgumentException, "mismatch in number of Operations (%d) and output indices " "(%d) provided", n, env->GetArrayLength(indices)); return; } std::unique_ptr<TF_Output[]> o(new TF_Output[n]); jlong* oph = env->GetLongArrayElements(op_handles, nullptr); jint* idx = env->GetIntArrayElements(indices, nullptr); bool ok = true; for (int i = 0; i < n && ok; ++i) { ok = resolveOutput(env, oph[i], idx[i], &o[i]); } env->ReleaseIntArrayElements(indices, idx, JNI_ABORT); env->ReleaseLongArrayElements(op_handles, oph, JNI_ABORT); if (!ok) return; TF_AddInputList(d, o.get(), n); } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_addControlInput( JNIEnv* env, jclass clazz, jlong handle, jlong op_handle) { if (op_handle == 0) { throwException(env, kIllegalStateException, "control input is not valid, " "perhaps the Graph containing it has been closed()?"); return; } TF_Operation* control = reinterpret_cast<TF_Operation*>(op_handle); TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; TF_AddControlInput(d, control); } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_setDevice( JNIEnv* env, jclass clazz, jlong handle, jstring device) { TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; const char* cdevice = env->GetStringUTFChars(device, nullptr); TF_SetDevice(d, cdevice); env->ReleaseStringUTFChars(device, cdevice); } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_setAttrString( JNIEnv* env, jclass clazz, jlong handle, jstring name, jbyteArray value) { static_assert(sizeof(jbyte) == 1, "Require Java byte to be represented as a single byte"); TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; const char* cname = env->GetStringUTFChars(name, nullptr); jbyte* cvalue = env->GetByteArrayElements(value, nullptr); TF_SetAttrString(d, cname, cvalue, env->GetArrayLength(value)); env->ReleaseByteArrayElements(value, cvalue, JNI_ABORT); env->ReleaseStringUTFChars(name, cname); } #define DEFINE_SET_ATTR_SCALAR(name, jtype, ctype) \ JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_setAttr##name( \ JNIEnv* env, jclass clazz, jlong handle, jstring name, jtype value) { \ static_assert( \ sizeof(ctype) >= sizeof(jtype), \ "Information loss when converting between Java and C types"); \ TF_OperationDescription* d = requireHandle(env, handle); \ if (d == nullptr) return; \ const char* cname = env->GetStringUTFChars(name, nullptr); \ TF_SetAttr##name(d, cname, static_cast<ctype>(value)); \ env->ReleaseStringUTFChars(name, cname); \ } #define DEFINE_SET_ATTR_LIST(name, jname, jtype, ctype) \ JNIEXPORT void JNICALL \ Java_org_tensorflow_OperationBuilder_setAttr##name##List( \ JNIEnv* env, jclass clazz, jlong handle, jstring name, \ jtype##Array value) { \ TF_OperationDescription* d = requireHandle(env, handle); \ if (d == nullptr) return; \ const char* cname = env->GetStringUTFChars(name, nullptr); \ /* Make a copy of the array to paper over any differences */ \ /* in byte representations of the jtype and ctype */ \ /* For example, jint vs TF_DataType. */ \ /* If this copy turns out to be a problem in practice */ \ /* can avoid it for many types. */ \ const int n = env->GetArrayLength(value); \ std::unique_ptr<ctype[]> cvalue(new ctype[n]); \ jtype* elems = env->Get##jname##ArrayElements(value, nullptr); \ for (int i = 0; i < n; ++i) { \ cvalue[i] = static_cast<ctype>(elems[i]); \ } \ TF_SetAttr##name##List(d, cname, cvalue.get(), n); \ env->Release##jname##ArrayElements(value, elems, JNI_ABORT); \ env->ReleaseStringUTFChars(name, cname); \ } #define DEFINE_SET_ATTR(name, jname, jtype, ctype) \ DEFINE_SET_ATTR_SCALAR(name, jtype, ctype) \ DEFINE_SET_ATTR_LIST(name, jname, jtype, ctype) DEFINE_SET_ATTR(Int, Long, jlong, int64_t); DEFINE_SET_ATTR(Float, Float, jfloat, float); DEFINE_SET_ATTR(Bool, Boolean, jboolean, unsigned char); DEFINE_SET_ATTR(Type, Int, jint, TF_DataType); #undef DEFINE_SET_ATTR #undef DEFINE_SET_ATTR_LIST #undef DEFINE_SET_ATTR_SCALAR JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_setAttrTensor( JNIEnv* env, jclass clazz, jlong handle, jstring name, jlong tensor_handle) { TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; TF_Tensor* t = requireTensor(env, tensor_handle); if (t == nullptr) return; const char* cname = env->GetStringUTFChars(name, nullptr); TF_Status* status = TF_NewStatus(); TF_SetAttrTensor(d, cname, t, status); throwExceptionIfNotOK(env, status); env->ReleaseStringUTFChars(name, cname); } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_setAttrTensorList( JNIEnv* env, jclass clazz, jlong handle, jstring name, jlongArray tensor_handles) { TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; const int n = env->GetArrayLength(tensor_handles); std::unique_ptr<TF_Tensor* []> tensors(new TF_Tensor*[n]); jlong* jhandles = env->GetLongArrayElements(tensor_handles, nullptr); bool ok = true; for (int i = 0; i < n && ok; ++i) { tensors[i] = requireTensor(env, jhandles[i]); ok = !env->ExceptionCheck(); } env->ReleaseLongArrayElements(tensor_handles, jhandles, JNI_ABORT); if (!ok) return; const char* cname = env->GetStringUTFChars(name, nullptr); TF_Status* status = TF_NewStatus(); TF_SetAttrTensorList(d, cname, tensors.get(), n, status); throwExceptionIfNotOK(env, status); env->ReleaseStringUTFChars(name, cname); } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_setAttrShape( JNIEnv* env, jclass clazz, jlong handle, jstring name, jlongArray shape, jint num_dims) { TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; std::unique_ptr<int64_t[]> cvalue; // num_dims and env->GetArrayLength(shape) are assumed to be consistent. // i.e., either num_dims < 0 or num_dims == env->GetArrayLength(shape). if (num_dims > 0) { cvalue.reset(new int64_t[num_dims]); jlong* elems = env->GetLongArrayElements(shape, nullptr); for (int i = 0; i < num_dims; ++i) { cvalue[i] = static_cast<int64_t>(elems[i]); } env->ReleaseLongArrayElements(shape, elems, JNI_ABORT); } const char* cname = env->GetStringUTFChars(name, nullptr); TF_SetAttrShape(d, cname, cvalue.get(), static_cast<int>(num_dims)); env->ReleaseStringUTFChars(name, cname); } <commit_msg>Use "nullptr" for null pointer values<commit_after>/* Copyright 2016 The TensorFlow 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 "tensorflow/java/src/main/native/operation_builder_jni.h" #include <memory> #include "tensorflow/c/c_api.h" #include "tensorflow/java/src/main/native/exception_jni.h" namespace { TF_OperationDescription* requireHandle(JNIEnv* env, jlong handle) { if (handle == 0) { throwException(env, kIllegalStateException, "Operation has already been built"); return nullptr; } return reinterpret_cast<TF_OperationDescription*>(handle); } bool resolveOutput(JNIEnv* env, jlong op_handle, jint index, TF_Output* out) { if (op_handle == 0) { throwException(env, kIllegalStateException, "close() was called on the Graph"); return false; } out->oper = reinterpret_cast<TF_Operation*>(op_handle); out->index = static_cast<int>(index); return true; } TF_Tensor* requireTensor(JNIEnv* env, jlong handle) { if (handle == 0) { throwException(env, kIllegalStateException, "close() has been called on the Tensor"); return nullptr; } return reinterpret_cast<TF_Tensor*>(handle); } } // namespace JNIEXPORT jlong JNICALL Java_org_tensorflow_OperationBuilder_allocate( JNIEnv* env, jclass clazz, jlong graph_handle, jstring type, jstring name) { if (graph_handle == 0) { throwException(env, kIllegalStateException, "close() has been called on the Graph"); return 0; } TF_Graph* graph = reinterpret_cast<TF_Graph*>(graph_handle); const char* op_type = env->GetStringUTFChars(type, nullptr); const char* op_name = env->GetStringUTFChars(name, nullptr); TF_OperationDescription* d = TF_NewOperation(graph, op_type, op_name); env->ReleaseStringUTFChars(name, op_name); env->ReleaseStringUTFChars(type, op_type); static_assert(sizeof(jlong) >= sizeof(TF_OperationDescription*), "Cannot represent a C TF_OperationDescription as a Java long"); return reinterpret_cast<jlong>(d); } JNIEXPORT jlong JNICALL Java_org_tensorflow_OperationBuilder_finish( JNIEnv* env, jclass clazz, jlong handle) { TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return 0; TF_Status* status = TF_NewStatus(); TF_Operation* op = TF_FinishOperation(d, status); if (throwExceptionIfNotOK(env, status)) { return reinterpret_cast<jlong>(op); } return 0; } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_addInput( JNIEnv* env, jclass clazz, jlong handle, jlong op_handle, jint index) { TF_Output out; if (!resolveOutput(env, op_handle, index, &out)) return; TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; TF_AddInput(d, out); } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_addInputList( JNIEnv* env, jclass clazz, jlong handle, jlongArray op_handles, jintArray indices) { TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; const size_t n = static_cast<size_t>(env->GetArrayLength(op_handles)); if (env->GetArrayLength(indices) != n) { throwException(env, kIllegalArgumentException, "mismatch in number of Operations (%d) and output indices " "(%d) provided", n, env->GetArrayLength(indices)); return; } std::unique_ptr<TF_Output[]> o(new TF_Output[n]); jlong* oph = env->GetLongArrayElements(op_handles, nullptr); jint* idx = env->GetIntArrayElements(indices, nullptr); bool ok = true; for (int i = 0; i < n && ok; ++i) { ok = resolveOutput(env, oph[i], idx[i], &o[i]); } env->ReleaseIntArrayElements(indices, idx, JNI_ABORT); env->ReleaseLongArrayElements(op_handles, oph, JNI_ABORT); if (!ok) return; TF_AddInputList(d, o.get(), n); } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_addControlInput( JNIEnv* env, jclass clazz, jlong handle, jlong op_handle) { if (op_handle == 0) { throwException(env, kIllegalStateException, "control input is not valid, " "perhaps the Graph containing it has been closed()?"); return; } TF_Operation* control = reinterpret_cast<TF_Operation*>(op_handle); TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; TF_AddControlInput(d, control); } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_setDevice( JNIEnv* env, jclass clazz, jlong handle, jstring device) { TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; const char* cdevice = env->GetStringUTFChars(device, nullptr); TF_SetDevice(d, cdevice); env->ReleaseStringUTFChars(device, cdevice); } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_setAttrString( JNIEnv* env, jclass clazz, jlong handle, jstring name, jbyteArray value) { static_assert(sizeof(jbyte) == 1, "Require Java byte to be represented as a single byte"); TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; const char* cname = env->GetStringUTFChars(name, nullptr); jbyte* cvalue = env->GetByteArrayElements(value, nullptr); TF_SetAttrString(d, cname, cvalue, env->GetArrayLength(value)); env->ReleaseByteArrayElements(value, cvalue, JNI_ABORT); env->ReleaseStringUTFChars(name, cname); } #define DEFINE_SET_ATTR_SCALAR(name, jtype, ctype) \ JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_setAttr##name( \ JNIEnv* env, jclass clazz, jlong handle, jstring name, jtype value) { \ static_assert( \ sizeof(ctype) >= sizeof(jtype), \ "Information loss when converting between Java and C types"); \ TF_OperationDescription* d = requireHandle(env, handle); \ if (d == nullptr) return; \ const char* cname = env->GetStringUTFChars(name, nullptr); \ TF_SetAttr##name(d, cname, static_cast<ctype>(value)); \ env->ReleaseStringUTFChars(name, cname); \ } #define DEFINE_SET_ATTR_LIST(name, jname, jtype, ctype) \ JNIEXPORT void JNICALL \ Java_org_tensorflow_OperationBuilder_setAttr##name##List( \ JNIEnv* env, jclass clazz, jlong handle, jstring name, \ jtype##Array value) { \ TF_OperationDescription* d = requireHandle(env, handle); \ if (d == nullptr) return; \ const char* cname = env->GetStringUTFChars(name, nullptr); \ /* Make a copy of the array to paper over any differences */ \ /* in byte representations of the jtype and ctype */ \ /* For example, jint vs TF_DataType. */ \ /* If this copy turns out to be a problem in practice */ \ /* can avoid it for many types. */ \ const int n = env->GetArrayLength(value); \ std::unique_ptr<ctype[]> cvalue(new ctype[n]); \ jtype* elems = env->Get##jname##ArrayElements(value, nullptr); \ for (int i = 0; i < n; ++i) { \ cvalue[i] = static_cast<ctype>(elems[i]); \ } \ TF_SetAttr##name##List(d, cname, cvalue.get(), n); \ env->Release##jname##ArrayElements(value, elems, JNI_ABORT); \ env->ReleaseStringUTFChars(name, cname); \ } #define DEFINE_SET_ATTR(name, jname, jtype, ctype) \ DEFINE_SET_ATTR_SCALAR(name, jtype, ctype) \ DEFINE_SET_ATTR_LIST(name, jname, jtype, ctype) DEFINE_SET_ATTR(Int, Long, jlong, int64_t); DEFINE_SET_ATTR(Float, Float, jfloat, float); DEFINE_SET_ATTR(Bool, Boolean, jboolean, unsigned char); DEFINE_SET_ATTR(Type, Int, jint, TF_DataType); #undef DEFINE_SET_ATTR #undef DEFINE_SET_ATTR_LIST #undef DEFINE_SET_ATTR_SCALAR JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_setAttrTensor( JNIEnv* env, jclass clazz, jlong handle, jstring name, jlong tensor_handle) { TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; TF_Tensor* t = requireTensor(env, tensor_handle); if (t == nullptr) return; const char* cname = env->GetStringUTFChars(name, nullptr); TF_Status* status = TF_NewStatus(); TF_SetAttrTensor(d, cname, t, status); throwExceptionIfNotOK(env, status); env->ReleaseStringUTFChars(name, cname); } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_setAttrTensorList( JNIEnv* env, jclass clazz, jlong handle, jstring name, jlongArray tensor_handles) { TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; const int n = env->GetArrayLength(tensor_handles); std::unique_ptr<TF_Tensor* []> tensors(new TF_Tensor*[n]); jlong* jhandles = env->GetLongArrayElements(tensor_handles, nullptr); bool ok = true; for (int i = 0; i < n && ok; ++i) { tensors[i] = requireTensor(env, jhandles[i]); ok = !env->ExceptionCheck(); } env->ReleaseLongArrayElements(tensor_handles, jhandles, JNI_ABORT); if (!ok) return; const char* cname = env->GetStringUTFChars(name, nullptr); TF_Status* status = TF_NewStatus(); TF_SetAttrTensorList(d, cname, tensors.get(), n, status); throwExceptionIfNotOK(env, status); env->ReleaseStringUTFChars(name, cname); } JNIEXPORT void JNICALL Java_org_tensorflow_OperationBuilder_setAttrShape( JNIEnv* env, jclass clazz, jlong handle, jstring name, jlongArray shape, jint num_dims) { TF_OperationDescription* d = requireHandle(env, handle); if (d == nullptr) return; std::unique_ptr<int64_t[]> cvalue; // num_dims and env->GetArrayLength(shape) are assumed to be consistent. // i.e., either num_dims < 0 or num_dims == env->GetArrayLength(shape). if (num_dims > 0) { cvalue.reset(new int64_t[num_dims]); jlong* elems = env->GetLongArrayElements(shape, nullptr); for (int i = 0; i < num_dims; ++i) { cvalue[i] = static_cast<int64_t>(elems[i]); } env->ReleaseLongArrayElements(shape, elems, JNI_ABORT); } const char* cname = env->GetStringUTFChars(name, nullptr); TF_SetAttrShape(d, cname, cvalue.get(), static_cast<int>(num_dims)); env->ReleaseStringUTFChars(name, cname); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** 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, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "meegosensorbase.h" SensorManagerInterface* meegosensorbase::m_remoteSensorManager = 0; const float meegosensorbase::GRAVITY_EARTH = 9.80665; const float meegosensorbase::GRAVITY_EARTH_THOUSANDTH = 0.00980665; const int meegosensorbase::KErrNotFound=-1; const int meegosensorbase::KErrInUse=-14; const char* const meegosensorbase::ALWAYS_ON = "alwaysOn"; const char* const meegosensorbase::BUFFER_SIZE = "bufferSize"; const char* const meegosensorbase::MAX_BUFFER_SIZE = "maxBufferSize"; const char* const meegosensorbase::EFFICIENT_BUFFER_SIZE = "efficientBufferSize"; meegosensorbase::meegosensorbase(QSensor *sensor) : QSensorBackend(sensor), m_sensorInterface(0), m_bufferSize(-1), m_prevOutputRange(0), m_efficientBufferSize(1), m_maxBufferSize(1) { if (!m_remoteSensorManager) m_remoteSensorManager = &SensorManagerInterface::instance(); } meegosensorbase::~meegosensorbase() { if (m_sensorInterface) { stop(); QObject::disconnect(m_sensorInterface); delete m_sensorInterface, m_sensorInterface = 0; } } void meegosensorbase::start() { if (m_sensorInterface) { // dataRate int dataRate = sensor()->dataRate(); if (dataRate > 0) { int interval = 1000 / dataRate; // for testing maximum speed //interval = 1; //dataRate = 1000; qDebug() << "Setting data rate" << dataRate << "Hz (interval" << interval << "ms) for" << sensor()->identifier(); m_sensorInterface->setInterval(interval); } // outputRange int currentRange = sensor()->outputRange(); int l = sensor()->outputRanges().size(); if (l>1){ if (currentRange != m_prevOutputRange){ bool isOk = m_sensorInterface->setDataRangeIndex(currentRange); //NOTE THAT THE CHANGE MIGHT NOT SUCCEED, FIRST COME FIRST SERVED if (!isOk) sensorError(KErrInUse); else m_prevOutputRange = currentRange; } } // always on QVariant alwaysOn = sensor()->property(ALWAYS_ON); alwaysOn.isValid()? m_sensorInterface->setStandbyOverride(alwaysOn.toBool()): m_sensorInterface->setStandbyOverride(false); // connects after buffering checks doConnectAfterCheck(); int returnCode = m_sensorInterface->start().error().type(); if (returnCode==0) return; qWarning()<<"m_sensorInterface did not start, error code:"<<returnCode; } sensorStopped(); } void meegosensorbase::stop() { if (m_sensorInterface) m_sensorInterface->stop(); } void meegosensorbase::setRanges(qreal correctionFactor){ if (!m_sensorInterface) return; QList<DataRange> ranges = m_sensorInterface->getAvailableDataRanges(); for (int i=0, l=ranges.size(); i<l; i++){ DataRange range = ranges.at(i); qreal rangeMin = range.min * correctionFactor; qreal rangeMax = range.max * correctionFactor; qreal resolution = range.resolution * correctionFactor; addOutputRange(rangeMin, rangeMax, resolution); } } bool meegosensorbase::doConnectAfterCheck(){ if (!m_sensorInterface) return false; // buffer size int size = bufferSize(); if (size == m_bufferSize) return true; m_sensorInterface->setBufferSize(size); // if multiple->single or single->multiple or if uninitialized if ((m_bufferSize>1 && size==1) || (m_bufferSize==1 && size>1) || m_bufferSize==-1){ m_bufferSize = size; disconnect(this); if (!doConnect()){ qWarning() << "Unable to connect "<< sensorName(); return false; } return true; } m_bufferSize = size; return true; } const int meegosensorbase::bufferSize(){ QVariant bufferVariant = sensor()->property(BUFFER_SIZE); int bufferSize = bufferVariant.isValid()?bufferVariant.toInt():1; if (bufferSize==1) return 1; // otherwise check validity if (bufferSize<1){ qWarning()<<"bufferSize cannot be "<<bufferSize<<", must be a positive number"; return m_bufferSize>0?m_bufferSize:1; } if (bufferSize>m_maxBufferSize){ qWarning()<<"bufferSize cannot be "<<bufferSize<<", MAX value is "<<m_maxBufferSize; return m_bufferSize>0?m_bufferSize:1; } return bufferSize; } const qreal meegosensorbase::correctionFactor(){return 1;} <commit_msg>temp fix to be removed when sensord>=0.6.39 is integrated in meego env<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** 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, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "meegosensorbase.h" SensorManagerInterface* meegosensorbase::m_remoteSensorManager = 0; const float meegosensorbase::GRAVITY_EARTH = 9.80665; const float meegosensorbase::GRAVITY_EARTH_THOUSANDTH = 0.00980665; const int meegosensorbase::KErrNotFound=-1; const int meegosensorbase::KErrInUse=-14; const char* const meegosensorbase::ALWAYS_ON = "alwaysOn"; const char* const meegosensorbase::BUFFER_SIZE = "bufferSize"; const char* const meegosensorbase::MAX_BUFFER_SIZE = "maxBufferSize"; const char* const meegosensorbase::EFFICIENT_BUFFER_SIZE = "efficientBufferSize"; meegosensorbase::meegosensorbase(QSensor *sensor) : QSensorBackend(sensor), m_sensorInterface(0), m_bufferSize(-1), m_prevOutputRange(0), m_efficientBufferSize(1), m_maxBufferSize(1) { if (!m_remoteSensorManager) m_remoteSensorManager = &SensorManagerInterface::instance(); } meegosensorbase::~meegosensorbase() { if (m_sensorInterface) { stop(); QObject::disconnect(m_sensorInterface); delete m_sensorInterface, m_sensorInterface = 0; } } void meegosensorbase::start() { if (m_sensorInterface) { // dataRate int dataRate = sensor()->dataRate(); if (dataRate > 0) { int interval = 1000 / dataRate; // for testing maximum speed //interval = 1; //dataRate = 1000; qDebug() << "Setting data rate" << dataRate << "Hz (interval" << interval << "ms) for" << sensor()->identifier(); m_sensorInterface->setInterval(interval); } // outputRange int currentRange = sensor()->outputRange(); int l = sensor()->outputRanges().size(); if (l>1){ if (currentRange != m_prevOutputRange){ #ifdef Q_WS_MAEMO6 bool isOk = m_sensorInterface->setDataRangeIndex(currentRange); //NOTE THAT THE CHANGE MIGHT NOT SUCCEED, FIRST COME FIRST SERVED if (!isOk) sensorError(KErrInUse); else m_prevOutputRange = currentRange; #else // TODO: remove when sensord integrated, in MeeGo env there is a delay qoutputrange range = sensor()->outputRanges().at(currentRange); qreal correction = 1/correctionFactor(); DataRange range1(range.minimum*correction, range.maximum*correction, range.accuracy*correction); m_sensorInterface->requestDataRange(range1); m_prevOutputRange = currentRange; #endif } } // always on QVariant alwaysOn = sensor()->property(ALWAYS_ON); alwaysOn.isValid()? m_sensorInterface->setStandbyOverride(alwaysOn.toBool()): m_sensorInterface->setStandbyOverride(false); // connects after buffering checks doConnectAfterCheck(); int returnCode = m_sensorInterface->start().error().type(); if (returnCode==0) return; qWarning()<<"m_sensorInterface did not start, error code:"<<returnCode; } sensorStopped(); } void meegosensorbase::stop() { if (m_sensorInterface) m_sensorInterface->stop(); } void meegosensorbase::setRanges(qreal correctionFactor){ if (!m_sensorInterface) return; QList<DataRange> ranges = m_sensorInterface->getAvailableDataRanges(); for (int i=0, l=ranges.size(); i<l; i++){ DataRange range = ranges.at(i); qreal rangeMin = range.min * correctionFactor; qreal rangeMax = range.max * correctionFactor; qreal resolution = range.resolution * correctionFactor; addOutputRange(rangeMin, rangeMax, resolution); } } bool meegosensorbase::doConnectAfterCheck(){ if (!m_sensorInterface) return false; // buffer size int size = bufferSize(); if (size == m_bufferSize) return true; m_sensorInterface->setBufferSize(size); // if multiple->single or single->multiple or if uninitialized if ((m_bufferSize>1 && size==1) || (m_bufferSize==1 && size>1) || m_bufferSize==-1){ m_bufferSize = size; disconnect(this); if (!doConnect()){ qWarning() << "Unable to connect "<< sensorName(); return false; } return true; } m_bufferSize = size; return true; } const int meegosensorbase::bufferSize(){ QVariant bufferVariant = sensor()->property(BUFFER_SIZE); int bufferSize = bufferVariant.isValid()?bufferVariant.toInt():1; if (bufferSize==1) return 1; // otherwise check validity if (bufferSize<1){ qWarning()<<"bufferSize cannot be "<<bufferSize<<", must be a positive number"; return m_bufferSize>0?m_bufferSize:1; } if (bufferSize>m_maxBufferSize){ qWarning()<<"bufferSize cannot be "<<bufferSize<<", MAX value is "<<m_maxBufferSize; return m_bufferSize>0?m_bufferSize:1; } return bufferSize; } const qreal meegosensorbase::correctionFactor(){return 1;} <|endoftext|>
<commit_before>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #pragma once #include <functional> #include "common.hh" #include "container_utils.hh" namespace wrencc { template <typename T> class ArrayList final : private UnCopyable { static constexpr sz_t kDefCapacity = 0x10; sz_t size_{}; sz_t capacity_{kDefCapacity}; T* data_{}; public: ArrayList(sz_t capacity = kDefCapacity) noexcept : capacity_(capacity < kDefCapacity ? kDefCapacity : capacity) { data_ = Alloc<T>::allocate(capacity_); } ~ArrayList() noexcept { clear(); Alloc<T>::deallocate(data_); } ArrayList(const T& value, sz_t count) noexcept : size_(count) , capacity_(count < kDefCapacity ? kDefCapacity : count) { data_ = Alloc<T>::allocate(capacity_); fill_n(data_, count, value); } inline bool empty() const noexcept { return size_ == 0; } inline sz_t size() const noexcept { return size_; } inline sz_t capacity() const noexcept { return capacity_; } inline const T* data() const noexcept { return data_; } inline T& at(sz_t i) noexcept { return data_[i]; } inline const T& at(sz_t i) const noexcept { return data_[i]; } inline T& operator[](sz_t i) noexcept { return data_[i]; } inline const T& operator[](sz_t i) const noexcept { return data_[i]; } inline T& first() noexcept { return data_[0]; } inline const T& first() const noexcept { return data_[0]; } inline T& last() noexcept { return data_[size_ - 1]; } inline const T& last() const noexcept { return data_[size_ - 1]; } void clear() noexcept { destroy(data_, data_ + size_); } void resize(sz_t size); void resize_capacity(sz_t capacity); void append(const T& x); void append(T&& x); T erase(sz_t i); void for_each(std::function<void (T&)>&& fn); void for_each(std::function<void (const T&)>&& fn); }; } <commit_msg>:construction: chore(array): add array list for wrencc<commit_after>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #pragma once #include <functional> #include "common.hh" #include "container_utils.hh" namespace wrencc { template <typename T> class ArrayList final : private UnCopyable { static constexpr sz_t kDefCapacity = 0x10; sz_t size_{}; sz_t capacity_{kDefCapacity}; T* data_{}; void regrow(sz_t new_capacity = 0) { if (new_capacity == 0) new_capacity = capacity_ * 3 / 2; T* new_data = SimpleAlloc<T>::allocate(new_capacity); try { uninitialized_copy(data_, data_ + size_, new_data); } catch (...) { destroy(new_data, new_data + size_); SimpleAlloc<T>::deallocate(new_data); throw; } destroy(data_, data_ + size_); SimpleAlloc<T>::deallocate(data_); capacity_ = new_capacity; data_ = new_data; } public: ArrayList(sz_t capacity = kDefCapacity) noexcept : capacity_(capacity < kDefCapacity ? kDefCapacity : capacity) { data_ = SimpleAlloc<T>::allocate(capacity_); } ~ArrayList() noexcept { clear(); SimpleAlloc<T>::deallocate(data_); } ArrayList(sz_t count, const T& value) noexcept : size_(count) , capacity_(count < kDefCapacity ? kDefCapacity : count) { data_ = SimpleAlloc<T>::allocate(capacity_); uninitialized_fill(data_, size_, value); } inline bool empty() const noexcept { return size_ == 0; } inline sz_t size() const noexcept { return size_; } inline sz_t capacity() const noexcept { return capacity_; } inline T* data() noexcept { return data_; } inline const T* data() const noexcept { return data_; } inline T& at(sz_t i) noexcept { return data_[i]; } inline const T& at(sz_t i) const noexcept { return data_[i]; } inline T& operator[](sz_t i) noexcept { return data_[i]; } inline const T& operator[](sz_t i) const noexcept { return data_[i]; } inline T& first() noexcept { return data_[0]; } inline const T& first() const noexcept { return data_[0]; } inline T& last() noexcept { return data_[size_ - 1]; } inline const T& last() const noexcept { return data_[size_ - 1]; } inline void clear() noexcept { destroy(data_, data_ + size_); size_ = 0; } template <typename Function> void for_each(Function&& fn) noexcept { for (sz_t i = 0; i < size_; ++i) fn(i, data_[i]); } void resize(sz_t size) { if (size > size_) { regrow(size * 3 / 2); } else if (size < size_) { destroy(data_ + size, data_ + size_); size_ = size; } } void append(const T& x) { if (size_ >= capacity_) regrow(); construct(&data_[size_++], x); } void append(T&& x) { if (size_ >= capacity_) regrow(); construct(&data_[size_++], std::move(x)); } template <typename... Args> void append(Args&&... args) { if (size_ >= capacity_) regrow(); construct(&data_[size_++], std::forward<Args>(args)...); } T pop() { T r = data_[size_ - 1]; destroy(&data_[--size_]); return r; } }; } <|endoftext|>
<commit_before>#pragma GCC target("lzcnt") #include <immintrin.h> #include <bits/stdc++.h> #include <utility> using namespace std; template<class T, class F = function<T(const T &, const T &)>> struct SparseTable { int n; vector<vector<T>> t; F func; SparseTable(const vector<T> &a, F f) : n(a.size()), t(32 - _lzcnt_u32(n)), func(std::move(f)) { t[0] = a; for (size_t i = 1; i < t.size(); i++) { t[i].resize(n - (1 << i) + 1); for (size_t j = 0; j < t[i].size(); j++) t[i][j] = func(t[i - 1][j], t[i - 1][j + (1 << (i - 1))]); } } T get(int from, int to) const { assert(0 <= from && from <= to && to <= n - 1); int k = 31 - _lzcnt_u32(to - from + 1); return func(t[k][from], t[k][to - (1 << k) + 1]); } }; // usage example int main() { vector<int> a{3, 2, 1}; SparseTable<int> st(a, [](int i, int j) { return min(i, j); }); cout << st.get(0, 2) << endl; cout << st.get(0, 1) << endl; } <commit_msg>update<commit_after>#pragma GCC target("lzcnt") #include <immintrin.h> #include <bits/stdc++.h> #include <utility> using namespace std; template<class T, class F = function<T(const T &, const T &)>> struct SparseTable { vector<vector<T>> t; F func; SparseTable(const vector<T> &a, F f) : t(32 - _lzcnt_u32(a.size())), func(std::move(f)) { t[0] = a; for (size_t i = 1; i < t.size(); i++) { t[i].resize(a.size() - (1 << i) + 1); for (size_t j = 0; j < t[i].size(); j++) t[i][j] = func(t[i - 1][j], t[i - 1][j + (1 << (i - 1))]); } } T get(int from, int to) const { assert(0 <= from && from <= to && to <= (int) t[0].size() - 1); int k = 31 - _lzcnt_u32(to - from + 1); return func(t[k][from], t[k][to - (1 << k) + 1]); } }; // usage example int main() { vector<int> a{3, 2, 1}; SparseTable<int> st(a, [](int i, int j) { return min(i, j); }); cout << st.get(0, 2) << endl; cout << st.get(0, 1) << endl; } <|endoftext|>
<commit_before>// Copyright (C) 2011, 2012 Strahinja Val Markovic <val@markovic.io> // // This file is part of YouCompleteMe. // // YouCompleteMe 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. // // YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. #include "IdentifierCompleter.h" #include "standard.h" #include "CandidateRepository.h" #include "Candidate.h" #include "Result.h" #include "Utils.h" #include "IdentifierUtils.h" #include <boost/unordered_set.hpp> #include <boost/bind.hpp> #include <boost/make_shared.hpp> #include <algorithm> using boost::packaged_task; using boost::bind; using boost::unique_future; using boost::make_shared; using boost::shared_ptr; using boost::bind; using boost::thread; namespace YouCompleteMe { typedef boost::function< std::vector< std::string >() > FunctionReturnsStringVector; extern const unsigned int MAX_ASYNC_THREADS = 4; extern const unsigned int MIN_ASYNC_THREADS = 2; namespace { void QueryThreadMain( IdentifierCompleter::LatestQueryTask &latest_query_task ) { while ( true ) { try { ( *latest_query_task.Get() )(); } catch ( boost::thread_interrupted & ) { return; } } } void BufferIdentifiersThreadMain( IdentifierCompleter::BufferIdentifiersTaskStack &buffer_identifiers_task_stack ) { while ( true ) { try { ( *buffer_identifiers_task_stack.Pop() )(); } catch ( boost::thread_interrupted & ) { return; } } } } // unnamed namespace IdentifierCompleter::IdentifierCompleter() : candidate_repository_( CandidateRepository::Instance() ), threading_enabled_( false ) { } IdentifierCompleter::IdentifierCompleter( const std::vector< std::string > &candidates ) : candidate_repository_( CandidateRepository::Instance() ), threading_enabled_( false ) { AddCandidatesToDatabase( candidates, "", "" ); } IdentifierCompleter::IdentifierCompleter( const std::vector< std::string > &candidates, const std::string &filetype, const std::string &filepath ) : candidate_repository_( CandidateRepository::Instance() ), threading_enabled_( false ) { AddCandidatesToDatabase( candidates, filetype, filepath ); } IdentifierCompleter::~IdentifierCompleter() { query_threads_.interrupt_all(); query_threads_.join_all(); if ( buffer_identifiers_thread_ ) { buffer_identifiers_thread_->interrupt(); buffer_identifiers_thread_->join(); } } // We need this mostly so that we can not use it in tests. Apparently the // GoogleTest framework goes apeshit on us if we enable threads by default. void IdentifierCompleter::EnableThreading() { threading_enabled_ = true; InitThreads(); } void IdentifierCompleter::AddCandidatesToDatabase( const std::vector< std::string > &new_candidates, const std::string &filetype, const std::string &filepath ) { std::list< const Candidate *> &candidates = GetCandidateList( filetype, filepath ); std::vector< const Candidate * > repository_candidates = candidate_repository_.GetCandidatesForStrings( new_candidates ); candidates.insert( candidates.end(), repository_candidates.begin(), repository_candidates.end() ); } void IdentifierCompleter::AddCandidatesToDatabaseFromBuffer( const std::string &buffer_contents, const std::string &filetype, const std::string &filepath, bool collect_from_comments_and_strings ) { ClearCandidatesStoredForFile( filetype, filepath ); std::string new_contents = collect_from_comments_and_strings ? buffer_contents : RemoveIdentifierFreeText( buffer_contents ); AddCandidatesToDatabase( ExtractIdentifiersFromText( new_contents ), filetype, filepath ); } void IdentifierCompleter::AddCandidatesToDatabaseFromBufferAsync( std::string buffer_contents, std::string filetype, std::string filepath, bool collect_from_comments_and_strings ) { // TODO: throw exception when threading is not enabled and this is called if ( !threading_enabled_ ) return; boost::function< void() > functor = bind( &IdentifierCompleter::AddCandidatesToDatabaseFromBuffer, boost::ref( *this ), boost::move( buffer_contents ), boost::move( filetype ), boost::move( filepath ), collect_from_comments_and_strings ); buffer_identifiers_task_stack_.Push( make_shared< packaged_task< void > >( boost::move( functor ) ) ); } std::vector< std::string > IdentifierCompleter::CandidatesForQuery( const std::string &query ) const { return CandidatesForQueryAndType( query, "" ); } std::vector< std::string > IdentifierCompleter::CandidatesForQueryAndType( const std::string &query, const std::string &filetype ) const { std::vector< Result > results; ResultsForQueryAndType( query, filetype, results ); std::vector< std::string > candidates; candidates.reserve( results.size() ); foreach ( const Result & result, results ) { candidates.push_back( *result.Text() ); } return candidates; } Future< AsyncResults > IdentifierCompleter::CandidatesForQueryAndTypeAsync( const std::string &query, const std::string &filetype ) const { // TODO: throw exception when threading is not enabled and this is called if ( !threading_enabled_ ) return Future< AsyncResults >(); FunctionReturnsStringVector functor = bind( &IdentifierCompleter::CandidatesForQueryAndType, boost::cref( *this ), query, filetype ); QueryTask task = make_shared< packaged_task< AsyncResults > >( bind( ReturnValueAsShared< std::vector< std::string > >, boost::move( functor ) ) ); unique_future< AsyncResults > future = task->get_future(); latest_query_task_.Set( task ); return Future< AsyncResults >( boost::move( future ) ); } void IdentifierCompleter::ResultsForQueryAndType( const std::string &query, const std::string &filetype, std::vector< Result > &results ) const { FiletypeMap::const_iterator it = filetype_map_.find( filetype ); if ( it == filetype_map_.end() || query.empty() ) return; Bitset query_bitset = LetterBitsetFromString( query ); boost::unordered_set< const Candidate * > seen_candidates; seen_candidates.reserve( candidate_repository_.NumStoredCandidates() ); foreach ( const FilepathToCandidates::value_type & path_and_candidates, *it->second ) { foreach ( const Candidate * candidate, *path_and_candidates.second ) { if ( ContainsKey( seen_candidates, candidate ) ) continue; else seen_candidates.insert( candidate ); if ( !candidate->MatchesQueryBitset( query_bitset ) ) continue; Result result = candidate->QueryMatchResult( query ); if ( result.IsSubsequence() ) results.push_back( result ); } } std::sort( results.begin(), results.end() ); } void IdentifierCompleter::ClearCandidatesStoredForFile( const std::string &filetype, const std::string &filepath ) { GetCandidateList( filetype, filepath ).clear(); } std::list< const Candidate * > &IdentifierCompleter::GetCandidateList( const std::string &filetype, const std::string &filepath ) { boost::shared_ptr< FilepathToCandidates > &path_to_candidates = filetype_map_[ filetype ]; if ( !path_to_candidates ) path_to_candidates.reset( new FilepathToCandidates() ); boost::shared_ptr< std::list< const Candidate * > > &candidates = ( *path_to_candidates )[ filepath ]; if ( !candidates ) candidates.reset( new std::list< const Candidate * >() ); return *candidates; } void IdentifierCompleter::InitThreads() { int query_threads_to_create = std::max( MIN_ASYNC_THREADS, std::min( MAX_ASYNC_THREADS, thread::hardware_concurrency() ) ); for ( int i = 0; i < query_threads_to_create; ++i ) { query_threads_.create_thread( bind( QueryThreadMain, boost::ref( latest_query_task_ ) ) ); } buffer_identifiers_thread_.reset( new boost::thread( BufferIdentifiersThreadMain, boost::ref( buffer_identifiers_task_stack_ ) ) ); } } // namespace YouCompleteMe <commit_msg>ycm_core now compiles cleanly with MSVC<commit_after>// Copyright (C) 2011, 2012 Strahinja Val Markovic <val@markovic.io> // // This file is part of YouCompleteMe. // // YouCompleteMe 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. // // YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. #include "IdentifierCompleter.h" #include "standard.h" #include "CandidateRepository.h" #include "Candidate.h" #include "Result.h" #include "Utils.h" #include "IdentifierUtils.h" #include <boost/unordered_set.hpp> #include <boost/bind.hpp> #include <boost/make_shared.hpp> #include <algorithm> using boost::packaged_task; using boost::unique_future; using boost::shared_ptr; using boost::thread; namespace YouCompleteMe { typedef boost::function< std::vector< std::string >() > FunctionReturnsStringVector; extern const unsigned int MAX_ASYNC_THREADS = 4; extern const unsigned int MIN_ASYNC_THREADS = 2; namespace { void QueryThreadMain( IdentifierCompleter::LatestQueryTask &latest_query_task ) { while ( true ) { try { ( *latest_query_task.Get() )(); } catch ( boost::thread_interrupted & ) { return; } } } void BufferIdentifiersThreadMain( IdentifierCompleter::BufferIdentifiersTaskStack &buffer_identifiers_task_stack ) { while ( true ) { try { ( *buffer_identifiers_task_stack.Pop() )(); } catch ( boost::thread_interrupted & ) { return; } } } } // unnamed namespace IdentifierCompleter::IdentifierCompleter() : candidate_repository_( CandidateRepository::Instance() ), threading_enabled_( false ) { } IdentifierCompleter::IdentifierCompleter( const std::vector< std::string > &candidates ) : candidate_repository_( CandidateRepository::Instance() ), threading_enabled_( false ) { AddCandidatesToDatabase( candidates, "", "" ); } IdentifierCompleter::IdentifierCompleter( const std::vector< std::string > &candidates, const std::string &filetype, const std::string &filepath ) : candidate_repository_( CandidateRepository::Instance() ), threading_enabled_( false ) { AddCandidatesToDatabase( candidates, filetype, filepath ); } IdentifierCompleter::~IdentifierCompleter() { query_threads_.interrupt_all(); query_threads_.join_all(); if ( buffer_identifiers_thread_ ) { buffer_identifiers_thread_->interrupt(); buffer_identifiers_thread_->join(); } } // We need this mostly so that we can not use it in tests. Apparently the // GoogleTest framework goes apeshit on us if we enable threads by default. void IdentifierCompleter::EnableThreading() { threading_enabled_ = true; InitThreads(); } void IdentifierCompleter::AddCandidatesToDatabase( const std::vector< std::string > &new_candidates, const std::string &filetype, const std::string &filepath ) { std::list< const Candidate *> &candidates = GetCandidateList( filetype, filepath ); std::vector< const Candidate * > repository_candidates = candidate_repository_.GetCandidatesForStrings( new_candidates ); candidates.insert( candidates.end(), repository_candidates.begin(), repository_candidates.end() ); } void IdentifierCompleter::AddCandidatesToDatabaseFromBuffer( const std::string &buffer_contents, const std::string &filetype, const std::string &filepath, bool collect_from_comments_and_strings ) { ClearCandidatesStoredForFile( filetype, filepath ); std::string new_contents = collect_from_comments_and_strings ? buffer_contents : RemoveIdentifierFreeText( buffer_contents ); AddCandidatesToDatabase( ExtractIdentifiersFromText( new_contents ), filetype, filepath ); } void IdentifierCompleter::AddCandidatesToDatabaseFromBufferAsync( std::string buffer_contents, std::string filetype, std::string filepath, bool collect_from_comments_and_strings ) { // TODO: throw exception when threading is not enabled and this is called if ( !threading_enabled_ ) return; boost::function< void() > functor = boost::bind( &IdentifierCompleter::AddCandidatesToDatabaseFromBuffer, boost::ref( *this ), boost::move( buffer_contents ), boost::move( filetype ), boost::move( filepath ), collect_from_comments_and_strings ); buffer_identifiers_task_stack_.Push( boost::make_shared< packaged_task< void > >( boost::move( functor ) ) ); } std::vector< std::string > IdentifierCompleter::CandidatesForQuery( const std::string &query ) const { return CandidatesForQueryAndType( query, "" ); } std::vector< std::string > IdentifierCompleter::CandidatesForQueryAndType( const std::string &query, const std::string &filetype ) const { std::vector< Result > results; ResultsForQueryAndType( query, filetype, results ); std::vector< std::string > candidates; candidates.reserve( results.size() ); foreach ( const Result & result, results ) { candidates.push_back( *result.Text() ); } return candidates; } Future< AsyncResults > IdentifierCompleter::CandidatesForQueryAndTypeAsync( const std::string &query, const std::string &filetype ) const { // TODO: throw exception when threading is not enabled and this is called if ( !threading_enabled_ ) return Future< AsyncResults >(); FunctionReturnsStringVector functor = boost::bind( &IdentifierCompleter::CandidatesForQueryAndType, boost::cref( *this ), query, filetype ); QueryTask task = boost::make_shared< packaged_task< AsyncResults > >( boost::bind( ReturnValueAsShared< std::vector< std::string > >, boost::move( functor ) ) ); unique_future< AsyncResults > future = task->get_future(); latest_query_task_.Set( task ); return Future< AsyncResults >( boost::move( future ) ); } void IdentifierCompleter::ResultsForQueryAndType( const std::string &query, const std::string &filetype, std::vector< Result > &results ) const { FiletypeMap::const_iterator it = filetype_map_.find( filetype ); if ( it == filetype_map_.end() || query.empty() ) return; Bitset query_bitset = LetterBitsetFromString( query ); boost::unordered_set< const Candidate * > seen_candidates; seen_candidates.reserve( candidate_repository_.NumStoredCandidates() ); foreach ( const FilepathToCandidates::value_type & path_and_candidates, *it->second ) { foreach ( const Candidate * candidate, *path_and_candidates.second ) { if ( ContainsKey( seen_candidates, candidate ) ) continue; else seen_candidates.insert( candidate ); if ( !candidate->MatchesQueryBitset( query_bitset ) ) continue; Result result = candidate->QueryMatchResult( query ); if ( result.IsSubsequence() ) results.push_back( result ); } } std::sort( results.begin(), results.end() ); } void IdentifierCompleter::ClearCandidatesStoredForFile( const std::string &filetype, const std::string &filepath ) { GetCandidateList( filetype, filepath ).clear(); } std::list< const Candidate * > &IdentifierCompleter::GetCandidateList( const std::string &filetype, const std::string &filepath ) { boost::shared_ptr< FilepathToCandidates > &path_to_candidates = filetype_map_[ filetype ]; if ( !path_to_candidates ) path_to_candidates.reset( new FilepathToCandidates() ); boost::shared_ptr< std::list< const Candidate * > > &candidates = ( *path_to_candidates )[ filepath ]; if ( !candidates ) candidates.reset( new std::list< const Candidate * >() ); return *candidates; } void IdentifierCompleter::InitThreads() { int query_threads_to_create = std::max( MIN_ASYNC_THREADS, std::min( MAX_ASYNC_THREADS, thread::hardware_concurrency() ) ); for ( int i = 0; i < query_threads_to_create; ++i ) { query_threads_.create_thread( boost::bind( QueryThreadMain, boost::ref( latest_query_task_ ) ) ); } buffer_identifiers_thread_.reset( new boost::thread( BufferIdentifiersThreadMain, boost::ref( buffer_identifiers_task_stack_ ) ) ); } } // namespace YouCompleteMe <|endoftext|>
<commit_before>//===-- PluginLoader.cpp - Implement -load command line option ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the -load <plugin> command line option processor. When // linked into a program, this new command line option is available that allows // users to load shared objects into the running program. // // Note that there are no symbols exported by the .o file generated for this // .cpp file. Because of this, a program must link against support.o instead of // support.a: otherwise this translation unit will not be included. // //===----------------------------------------------------------------------===// #include "Support/DynamicLinker.h" #include "Support/CommandLine.h" #include "Config/config.h" #include <iostream> using namespace llvm; namespace { struct PluginLoader { void operator=(const std::string &Filename) { std::string ErrorMessage; if (LinkDynamicObject (Filename.c_str (), &ErrorMessage)) std::cerr << "Error opening '" << Filename << "': " << ErrorMessage << "\n -load request ignored.\n"; } }; } // This causes operator= above to be invoked for every -load option. static cl::opt<PluginLoader, false, cl::parser<std::string> > LoadOpt("load", cl::ZeroOrMore, cl::value_desc("plugin" SHLIBEXT), cl::desc("Load the specified plugin")); <commit_msg>Implicitly getting a new option by linking to support.o instead of support.a is a bad idea. Make tools that want the option #include PluginSupport.h explicitly.<commit_after>//===-- PluginLoader.cpp - Implement -load command line option ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the -load <plugin> command line option handler. // //===----------------------------------------------------------------------===// #define DONT_GET_PLUGIN_LOADER_OPTION #include "Support/PluginLoader.h" #include "Support/DynamicLinker.h" #include <iostream> using namespace llvm; void PluginLoader::operator=(const std::string &Filename) { std::string ErrorMessage; if (LinkDynamicObject(Filename.c_str(), &ErrorMessage)) std::cerr << "Error opening '" << Filename << "': " << ErrorMessage << "\n -load request ignored.\n"; } <|endoftext|>