commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
cbe285dd9628422c787acd763fc4f7e1e857d0b8
src/mem/ast/node/VarDecl.cpp
src/mem/ast/node/VarDecl.cpp
#include "mem/ast/node/VarDecl.hpp" namespace mem { namespace ast { namespace node { VarDecl::VarDecl () { _type = Kind::VARIABLE_DECLARATION; } void VarDecl::isValid (NodeValidator* v) { // Check self Node::isValid(v); v->ensure(ChildCount() <= 3, "VarDecl must have at most 3 children"); v->ensure(hasExprType(), "VarDecl must have an expression type"); v->ensure(hasBoundSymbol(), "VarDecl must have a bound symbol"); if (NameNode() != NULL) { // Check NAME node v->ensure(NameNode()->hasBoundSymbol(), "VarDecl : Name node must have a bound symbol"); v->ensure(NameNode()->isIdNode(), "VarDecl : Name node must be an ID"); } if (TypeNode() != NULL) { // Check TYPE node v->ensure(TypeNode()->hasExprType(), "VarDecl : Type node must have an expression type"); v->ensure(TypeNode()->hasBoundSymbol(), "VarDecl : Type node must have a bound symbol"); v->ensure(TypeNode()->isFinalIdNode(), "VarDecl : Type node must be a FINAL ID"); } } } } }
#include "mem/ast/node/VarDecl.hpp" namespace mem { namespace ast { namespace node { VarDecl::VarDecl () { _type = Kind::VARIABLE_DECLARATION; } void VarDecl::isValid (NodeValidator* v) { // Check self Node::isValid(v); v->ensure(ChildCount() <= 3, "VarDecl must have at most 3 children"); v->ensure(hasExprType(), "VarDecl must have an expression type"); v->ensure(hasBoundSymbol(), "VarDecl must have a bound symbol"); if (NameNode() != NULL) { // Check NAME node v->ensure(NameNode()->hasBoundSymbol(), "VarDecl : Name node must have a bound symbol"); v->ensure(NameNode()->isIdNode(), "VarDecl : Name node must be an ID"); } if (TypeNode() != NULL) { // Check TYPE node v->ensure(TypeNode()->hasExprType(), "VarDecl : Type node must have an expression type"); v->ensure(TypeNode()->hasBoundSymbol(), "VarDecl : Type node must have a bound symbol"); } } } } }
Fix bad VarDecl ast node validation
Fix bad VarDecl ast node validation
C++
mit
ThQ/memc,ThQ/memc,ThQ/memc,ThQ/memc
4cbe2abcc04ba91e4c26d0647187a08797098667
libtests/cxx11.cc
libtests/cxx11.cc
#include <iostream> #include <cassert> #include <cstring> #include <functional> #include <type_traits> #include <cstdint> #include <vector> #include <map> #include <memory> #include <regex> // Functional programming // Function that returns a callable in the form of a lambda std::function<int (int)> make_adder(int x) { return ([=](int a) -> int{ return x + a; }); } void do_functional() { // Lambda with no capture auto simple_lambda = [](int a){ return a + 3; }; assert(simple_lambda(5) == 8); // Capture by value int x = 5; auto by_value = [x](int a){ return a + x; }; assert(by_value(1) == 6); x = 7; // change not seen by lambda assert(by_value(1) == 6); // Also >> at end of template assert((std::is_convertible<decltype(by_value), std::function<int(int)>>::value)); // Capture by reference auto by_reference = [&x](int a){ return a + x; }; assert(by_reference(1) == 8); x = 8; // change seen my lambda assert(by_reference(1) == 9); // Get a callable from a function auto add3 = make_adder(3); assert(add3(5) == 8); auto make_addr_lambda = [](int a) { return [a](int b) { return a + b; }; }; assert(make_addr_lambda(6)(8) == 14); } // Integer types, type traits template <typename T> void check_size(size_t size, bool is_signed) { assert(sizeof(T) == size); assert(std::is_signed<T>::value == is_signed); } void do_inttypes() { // static_assert is a compile-time check static_assert(1 == sizeof(int8_t), "int8_t check"); check_size<int8_t>(1, true); check_size<uint8_t>(1, false); check_size<int16_t>(2, true); check_size<uint16_t>(2, false); check_size<int32_t>(4, true); check_size<uint32_t>(4, false); check_size<int64_t>(8, true); check_size<uint64_t>(8, false); // auto, decltype auto x = 5LL; check_size<decltype(x)>(8, true); assert((std::is_same<long long, decltype(x)>::value)); } class A { public: static constexpr auto def_value = 5; A(int x) : x(x) { } // Constructor delegation A() : A(def_value) { } int getX() const { return x; } private: int x; }; void do_iteration() { // Initializers, foreach syntax, auto for iterators std::vector<int> v = { 1, 2, 3, 4 }; assert(v.size() == 4); int sum = 0; for (auto& i: v) { sum += i; } assert(10 == sum); for (auto i = v.begin(); i != v.end(); ++i) { sum += *i; } assert(20 == sum); std::vector<A> v2 = { A(), A(3) }; assert(5 == v2.at(0).getX()); assert(3 == v2.at(1).getX()); } // Variadic template template<class A1> void variadic1(A1 const& a1) { assert(a1 == 12); } template<class A1, class A2> void variadic1(A1 const& a1, A2 const& a2) { assert(a1 == a2); } template<class ...Args> void variadic(Args... args) { variadic1(args...); } template<class A> bool pairwise_equal(A const& a, A const& b) { return (a == b); } template<class T, class ...Rest> bool pairwise_equal(T const& a, T const& b, Rest... rest) { return pairwise_equal(a, b) && pairwise_equal(rest...); } void do_variadic() { variadic(15, 15); variadic(12); assert(pairwise_equal(5, 5, 2.0, 2.0, std::string("a"), std::string("a"))); assert(! pairwise_equal(5, 5, 2.0, 3.0)); } // deleted, default class B { public: B(int x) : x(x) { } B() : B(5) { } int getX() const { return x; } virtual ~B() = default; B(B const&) = delete; B& operator=(B const&) = delete; private: int x; }; void do_default_deleted() { B b1; assert(5 == b1.getX()); assert(std::is_copy_constructible<A>::value); assert(! std::is_copy_constructible<B>::value); } // smart pointers class C { public: C(int id = 0) : id(id) { incr(id); } ~C() { decr(id); } C(C const& rhs) : C(rhs.id) { } C& operator=(C const& rhs) { if (&rhs != this) { decr(id); id = rhs.id; incr(id); } return *this; } static void check(size_t size, int v, int count) { assert(m.size() == size); auto p = m.find(v); if (p != m.end()) { assert(p->second == count); } } private: void incr(int i) { ++m[i]; } void decr(int i) { if (--m[i] == 0) { m.erase(i); } } static std::map<int, int> m; int id; }; std::map<int, int> C::m; std::shared_ptr<C> make_c(int id) { return std::make_shared<C>(id); } std::shared_ptr<C> make_c_array(std::vector<int> const& is) { auto p = std::shared_ptr<C>(new C[is.size()], std::default_delete<C[]>()); C* pp = p.get(); for (size_t i = 0; i < is.size(); ++i) { pp[i] = C(is.at(i)); } return p; } void do_smart_pointers() { auto p1 = make_c(1); C::check(1, 1, 1); auto p2 = make_c_array({2, 3, 4, 5}); for (auto i: {1, 2, 3, 4, 5}) { C::check(5, i, 1); } { C::check(5, 1, 1); C c3(*p1); C::check(5, 1, 2); } C::check(5, 1, 1); p1 = nullptr; C::check(4, 1, 0); p2 = nullptr; C::check(0, 0, 0); { std::unique_ptr<C> p3(new C(6)); C::check(1, 6, 1); } C::check(0, 0, 0); } // Regular expressions void do_regex() { // Basic match/search. Match matches whole string; search searches // within string. Use std::smatch for matching std::string and // std::cmatch for matching char const*. std::regex expr1("([0-9]+)"); std::regex expr2("([0-9]+)\\s*([a-z]+)[[:space:]]*([0-9]+)"); std::string str1("one 234 fifth 678 nine"); std::string str2("234 five 678 nine"); std::string str3("one 234 five 678"); std::string str4("234"); std::string str5("234 five 678"); std::smatch match1; assert(! std::regex_match(str1, match1, expr1)); assert(! std::regex_match(str2, match1, expr1)); assert(! std::regex_match(str3, match1, expr1)); assert(std::regex_match(str4, match1, expr1)); assert(match1[0].first == match1[1].first); assert(match1[0].second == match1[1].second); std::string s; s.assign(match1[1].first, match1[1].second); assert("234" == s); assert(s == match1[1].str()); assert(std::regex_match(str5, match1, expr2)); assert("234 five 678" == match1[0].str()); assert("234" == match1[1].str()); assert("five" == match1[2].str()); assert("678" == match1[3].str()); assert(std::regex_search(str1, match1, expr2)); assert("234 fifth 678" == match1[0].str()); assert("234" == match1[1].str()); assert("fifth" == match1[2].str()); assert("678" == match1[3].str()); // Iterator std::regex expr3("[[:digit:]]+"); std::string str6 = "asdf234erasdf9453.kgdl423asdf"; std::sregex_iterator m1(str6.begin(), str6.end(), expr3); std::sregex_iterator m2; s.clear(); for (std::sregex_iterator iter = m1; iter != m2; ++iter) { std::smatch const& match2 = *iter; s += match2[0].str() + "|"; } assert("234|9453|423|" == s); // Submatches std::regex expr4("(?:(asdf)|(qwer))"); char const* str7 = "0asdf1qwer2"; std::cregex_iterator m3(str7, str7 + std::strlen(str7), expr4); assert("asdf" == (*m3)[0].str()); assert((*m3)[1].matched); assert(! (*m3)[2].matched); ++m3; assert("qwer" == (*m3)[0].str()); assert(! (*m3)[1].matched); assert((*m3)[2].matched); } int main() { do_functional(); do_inttypes(); do_iteration(); do_variadic(); do_default_deleted(); do_smart_pointers(); do_regex(); std::cout << "assertions passed\n"; return 0; }
#include <iostream> #include <cassert> #include <cstring> #include <functional> #include <type_traits> #include <cstdint> #include <vector> #include <map> #include <memory> #include <regex> // Functional programming // Function that returns a callable in the form of a lambda std::function<int (int)> make_adder(int x) { return ([=](int a) -> int{ return x + a; }); } void do_functional() { // Lambda with no capture auto simple_lambda = [](int a){ return a + 3; }; assert(simple_lambda(5) == 8); // Capture by value int x = 5; auto by_value = [x](int a){ return a + x; }; assert(by_value(1) == 6); x = 7; // change not seen by lambda assert(by_value(1) == 6); // Also >> at end of template assert((std::is_convertible<decltype(by_value), std::function<int(int)>>::value)); // Capture by reference auto by_reference = [&x](int a){ return a + x; }; assert(by_reference(1) == 8); x = 8; // change seen my lambda assert(by_reference(1) == 9); // Get a callable from a function auto add3 = make_adder(3); assert(add3(5) == 8); auto make_addr_lambda = [](int a) { return [a](int b) { return a + b; }; }; assert(make_addr_lambda(6)(8) == 14); // nullptr and {} are empty functions std::function<void()> f1 = {}; assert(! f1); std::function<void()> f2 = nullptr; assert(! f2); } // Integer types, type traits template <typename T> void check_size(size_t size, bool is_signed) { assert(sizeof(T) == size); assert(std::is_signed<T>::value == is_signed); } void do_inttypes() { // static_assert is a compile-time check static_assert(1 == sizeof(int8_t), "int8_t check"); check_size<int8_t>(1, true); check_size<uint8_t>(1, false); check_size<int16_t>(2, true); check_size<uint16_t>(2, false); check_size<int32_t>(4, true); check_size<uint32_t>(4, false); check_size<int64_t>(8, true); check_size<uint64_t>(8, false); // auto, decltype auto x = 5LL; check_size<decltype(x)>(8, true); assert((std::is_same<long long, decltype(x)>::value)); } class A { public: static constexpr auto def_value = 5; A(int x) : x(x) { } // Constructor delegation A() : A(def_value) { } int getX() const { return x; } private: int x; }; void do_iteration() { // Initializers, foreach syntax, auto for iterators std::vector<int> v = { 1, 2, 3, 4 }; assert(v.size() == 4); int sum = 0; for (auto& i: v) { sum += i; } assert(10 == sum); for (auto i = v.begin(); i != v.end(); ++i) { sum += *i; } assert(20 == sum); std::vector<A> v2 = { A(), A(3) }; assert(5 == v2.at(0).getX()); assert(3 == v2.at(1).getX()); } // Variadic template template<class A1> void variadic1(A1 const& a1) { assert(a1 == 12); } template<class A1, class A2> void variadic1(A1 const& a1, A2 const& a2) { assert(a1 == a2); } template<class ...Args> void variadic(Args... args) { variadic1(args...); } template<class A> bool pairwise_equal(A const& a, A const& b) { return (a == b); } template<class T, class ...Rest> bool pairwise_equal(T const& a, T const& b, Rest... rest) { return pairwise_equal(a, b) && pairwise_equal(rest...); } void do_variadic() { variadic(15, 15); variadic(12); assert(pairwise_equal(5, 5, 2.0, 2.0, std::string("a"), std::string("a"))); assert(! pairwise_equal(5, 5, 2.0, 3.0)); } // deleted, default class B { public: B(int x) : x(x) { } B() : B(5) { } int getX() const { return x; } virtual ~B() = default; B(B const&) = delete; B& operator=(B const&) = delete; private: int x; }; void do_default_deleted() { B b1; assert(5 == b1.getX()); assert(std::is_copy_constructible<A>::value); assert(! std::is_copy_constructible<B>::value); } // smart pointers class C { public: C(int id = 0) : id(id) { incr(id); } ~C() { decr(id); } C(C const& rhs) : C(rhs.id) { } C& operator=(C const& rhs) { if (&rhs != this) { decr(id); id = rhs.id; incr(id); } return *this; } static void check(size_t size, int v, int count) { assert(m.size() == size); auto p = m.find(v); if (p != m.end()) { assert(p->second == count); } } private: void incr(int i) { ++m[i]; } void decr(int i) { if (--m[i] == 0) { m.erase(i); } } static std::map<int, int> m; int id; }; std::map<int, int> C::m; std::shared_ptr<C> make_c(int id) { return std::make_shared<C>(id); } std::shared_ptr<C> make_c_array(std::vector<int> const& is) { auto p = std::shared_ptr<C>(new C[is.size()], std::default_delete<C[]>()); C* pp = p.get(); for (size_t i = 0; i < is.size(); ++i) { pp[i] = C(is.at(i)); } return p; } void do_smart_pointers() { auto p1 = make_c(1); C::check(1, 1, 1); auto p2 = make_c_array({2, 3, 4, 5}); for (auto i: {1, 2, 3, 4, 5}) { C::check(5, i, 1); } { C::check(5, 1, 1); C c3(*p1); C::check(5, 1, 2); } C::check(5, 1, 1); p1 = nullptr; C::check(4, 1, 0); p2 = nullptr; C::check(0, 0, 0); { std::unique_ptr<C> p3(new C(6)); C::check(1, 6, 1); } C::check(0, 0, 0); } // Regular expressions void do_regex() { // Basic match/search. Match matches whole string; search searches // within string. Use std::smatch for matching std::string and // std::cmatch for matching char const*. std::regex expr1("([0-9]+)"); std::regex expr2("([0-9]+)\\s*([a-z]+)[[:space:]]*([0-9]+)"); std::string str1("one 234 fifth 678 nine"); std::string str2("234 five 678 nine"); std::string str3("one 234 five 678"); std::string str4("234"); std::string str5("234 five 678"); std::smatch match1; assert(! std::regex_match(str1, match1, expr1)); assert(! std::regex_match(str2, match1, expr1)); assert(! std::regex_match(str3, match1, expr1)); assert(std::regex_match(str4, match1, expr1)); assert(match1[0].first == match1[1].first); assert(match1[0].second == match1[1].second); std::string s; s.assign(match1[1].first, match1[1].second); assert("234" == s); assert(s == match1[1].str()); assert(std::regex_match(str5, match1, expr2)); assert("234 five 678" == match1[0].str()); assert("234" == match1[1].str()); assert("five" == match1[2].str()); assert("678" == match1[3].str()); assert(std::regex_search(str1, match1, expr2)); assert("234 fifth 678" == match1[0].str()); assert("234" == match1[1].str()); assert("fifth" == match1[2].str()); assert("678" == match1[3].str()); // Iterator std::regex expr3("[[:digit:]]+"); std::string str6 = "asdf234erasdf9453.kgdl423asdf"; std::sregex_iterator m1(str6.begin(), str6.end(), expr3); std::sregex_iterator m2; s.clear(); for (std::sregex_iterator iter = m1; iter != m2; ++iter) { std::smatch const& match2 = *iter; s += match2[0].str() + "|"; } assert("234|9453|423|" == s); // Submatches std::regex expr4("(?:(asdf)|(qwer))"); char const* str7 = "0asdf1qwer2"; std::cregex_iterator m3(str7, str7 + std::strlen(str7), expr4); assert("asdf" == (*m3)[0].str()); assert((*m3)[1].matched); assert(! (*m3)[2].matched); ++m3; assert("qwer" == (*m3)[0].str()); assert(! (*m3)[1].matched); assert((*m3)[2].matched); } int main() { do_functional(); do_inttypes(); do_iteration(); do_variadic(); do_default_deleted(); do_smart_pointers(); do_regex(); std::cout << "assertions passed\n"; return 0; }
Test empty function detection
Test empty function detection
C++
apache-2.0
qpdf/qpdf,qpdf/qpdf,qpdf/qpdf,jberkenbilt/qpdf,jberkenbilt/qpdf,jberkenbilt/qpdf,jberkenbilt/qpdf,qpdf/qpdf,qpdf/qpdf,jberkenbilt/qpdf
47e35ae86ce60f54f7148f6ae1fe870e0be195ba
src/mimecontentformatter.cpp
src/mimecontentformatter.cpp
/* Copyright (c) 2011-2012 - Tőkés Attila This file is part of SmtpClient for Qt. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. See the LICENSE file for more details. */ #include "mimecontentformatter.h" using namespace SimpleMail; MimeContentFormatter::MimeContentFormatter(int max_length) : max_length(max_length) { } QByteArray MimeContentFormatter::format(const QByteArray &content, int &chars) const { QByteArray out; for (int i = 0; i < content.length() ; ++i) { chars++; if (chars > max_length) { out.append(QByteArrayLiteral("\r\n")); chars = 1; } out.append(content[i]); } return out; } QByteArray MimeContentFormatter::formatQuotedPrintable(const QByteArray &content, int &chars) const { QByteArray out; for (int i = 0; i < content.length() ; ++i) { chars++; if (content[i] == '\n') { // new line out.append(content[i]); chars = 0; continue; } if ((chars > max_length - 1) || ((content[i] == '=') && (chars > max_length - 3) )) { out.append(QByteArrayLiteral("=\r\n")); chars = 1; } out.append(content[i]); } return out; } void MimeContentFormatter::setMaxLength(int l) { max_length = l; } int MimeContentFormatter::maxLength() const { return max_length; }
/* Copyright (c) 2011-2012 - Tőkés Attila This file is part of SmtpClient for Qt. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. See the LICENSE file for more details. */ #include "mimecontentformatter.h" using namespace SimpleMail; MimeContentFormatter::MimeContentFormatter(int max_length) : max_length(max_length) { } QByteArray MimeContentFormatter::format(const QByteArray &content, int &chars) const { QByteArray out; out.reserve(6000); for (int i = 0, size = content.length(); i < size; i+=max_length) { out.append(content.mid(i,max_length)); out.append(QByteArrayLiteral("\r\n")); chars += i; } return out; } QByteArray MimeContentFormatter::formatQuotedPrintable(const QByteArray &content, int &chars) const { QByteArray out; for (int i = 0; i < content.length() ; ++i) { chars++; if (content[i] == '\n') { // new line out.append(content[i]); chars = 0; continue; } if ((chars > max_length - 1) || ((content[i] == '=') && (chars > max_length - 3) )) { out.append(QByteArrayLiteral("=\r\n")); chars = 1; } out.append(content[i]); } return out; } void MimeContentFormatter::setMaxLength(int l) { max_length = l; } int MimeContentFormatter::maxLength() const { return max_length; }
Improve base format (#39)
Improve base format (#39) * MimeContentFormatter::format optimize way append content Co-authored-by: Manu <[email protected]>
C++
lgpl-2.1
cutelyst/simple-mail,cutelyst/simple-mail
e26ec8af31040da31b744b4e53afbdd8cacb8ef9
include/easynet/shared_buffer.hpp
include/easynet/shared_buffer.hpp
// Copyright (c) 2013,2014 niXman (i dotty nixman doggy gmail dotty com) // All rights reserved. // // This file is part of EASYNET(https://github.com/niXman/easynet) project. // // 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 {organization} nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _easynet__shared_buffer_hpp #define _easynet__shared_buffer_hpp #include <memory> #include <cstring> #include <cassert> namespace easynet { /***************************************************************************/ struct shared_buffer { std::shared_ptr<char> data; size_t size; }; /***************************************************************************/ inline shared_buffer buffer_alloc(size_t size) { if ( !size ) return shared_buffer(); return { {new char[size], std::default_delete<char[]>()}, size }; } inline shared_buffer buffer_clone(const shared_buffer& buffer) { if ( !buffer.size ) return shared_buffer(); shared_buffer result = { {new char[buffer.size], std::default_delete<char[]>()}, buffer.size }; std::memcpy(result.data.get(), buffer.data.get(), buffer.size); return result; } inline shared_buffer buffer_clone(const shared_buffer& buffer, size_t size) { assert(size <= buffer.size); shared_buffer result = { {new char[size], std::default_delete<char[]>()}, size }; std::memcpy(result.data.get(), buffer.data.get(), size); return result; } inline shared_buffer buffer_clone(const shared_buffer& buffer, size_t from, size_t size) { assert(size > 0 && size <= buffer.size && from <= buffer.size && from+size <= buffer.size); shared_buffer result = { {new char[size], std::default_delete<char[]>()}, size }; std::memcpy(result.data.get(), buffer.data.get()+from, size); return result; } inline shared_buffer buffer_clone(const void* ptr, size_t size) { assert(ptr && size); shared_buffer result = { {new char[size], std::default_delete<char[]>()}, size }; memcpy(result.data.get(), ptr, size); return result; } inline shared_buffer buffer_shift(const shared_buffer& buffer, size_t bytes) { shared_buffer result = { {buffer.data, buffer.data.get()+bytes} ,buffer.size-bytes }; return result; } /***************************************************************************/ inline size_t buffer_size(const shared_buffer& buffer) { return buffer.size; } inline char* buffer_data(const shared_buffer& buffer) { return (char*)buffer.data.get(); } inline size_t buffer_refs(const shared_buffer& buffer) { return buffer.data.use_count(); } /***************************************************************************/ } // namespace easynet #endif // _easynet__shared_buffer_hpp
// Copyright (c) 2013,2014 niXman (i dotty nixman doggy gmail dotty com) // All rights reserved. // // This file is part of EASYNET(https://github.com/niXman/easynet) project. // // 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 {organization} nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _easynet__shared_buffer_hpp #define _easynet__shared_buffer_hpp #include <memory> #include <cstring> #include <cassert> namespace easynet { /***************************************************************************/ struct shared_buffer { std::shared_ptr<char> data; size_t size; }; /***************************************************************************/ inline shared_buffer buffer_alloc(size_t size) { if ( !size ) return shared_buffer(); return { {new char[size], std::default_delete<char[]>()}, size }; } inline shared_buffer buffer_clone(const shared_buffer& buffer) { if ( !buffer.size ) return shared_buffer(); shared_buffer result = { {new char[buffer.size], std::default_delete<char[]>()}, buffer.size }; std::memcpy(result.data.get(), buffer.data.get(), buffer.size); return result; } inline shared_buffer buffer_clone(const shared_buffer& buffer, size_t size) { assert(size <= buffer.size); shared_buffer result = { {new char[size], std::default_delete<char[]>()}, size }; std::memcpy(result.data.get(), buffer.data.get(), size); return result; } inline shared_buffer buffer_clone(const shared_buffer& buffer, size_t from, size_t size) { assert(size > 0 && size <= buffer.size && from <= buffer.size && from+size <= buffer.size); shared_buffer result = { {new char[size], std::default_delete<char[]>()}, size }; std::memcpy(result.data.get(), buffer.data.get()+from, size); return result; } inline shared_buffer buffer_clone(const void* ptr, size_t size) { assert(ptr && size); shared_buffer result = { {new char[size], std::default_delete<char[]>()}, size }; std::memcpy(result.data.get(), ptr, size); return result; } inline shared_buffer buffer_shift(const shared_buffer& buffer, size_t bytes) { shared_buffer result = { {buffer.data, buffer.data.get()+bytes} ,buffer.size-bytes }; return result; } /***************************************************************************/ inline size_t buffer_size(const shared_buffer& buffer) { return buffer.size; } inline char* buffer_data(const shared_buffer& buffer) { return (char*)buffer.data.get(); } inline size_t buffer_refs(const shared_buffer& buffer) { return buffer.data.use_count(); } /***************************************************************************/ } // namespace easynet #endif // _easynet__shared_buffer_hpp
Update shared_buffer.hpp
Update shared_buffer.hpp fixes
C++
mit
niXman/easynet
d358c76f75502b72e58d333168b625a6df66c162
include/libtorrent/ssl_stream.hpp
include/libtorrent/ssl_stream.hpp
/* Copyright (c) 2008-2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_SSL_STREAM_HPP_INCLUDED #define TORRENT_SSL_STREAM_HPP_INCLUDED #ifdef TORRENT_USE_OPENSSL #include "libtorrent/socket.hpp" #include <boost/bind.hpp> #if BOOST_VERSION < 103500 #include <asio/ssl.hpp> #else #include <boost/asio/ssl.hpp> #endif // openssl seems to believe it owns // this name in every single scope #undef set_key namespace libtorrent { template <class Stream> class ssl_stream { public: explicit ssl_stream(io_service& io_service, asio::ssl::context& ctx) : m_sock(io_service, ctx) { } typedef typename asio::ssl::stream<Stream> sock_type; typedef typename sock_type::next_layer_type next_layer_type; typedef typename Stream::lowest_layer_type lowest_layer_type; typedef typename Stream::endpoint_type endpoint_type; typedef typename Stream::protocol_type protocol_type; void set_host_name(std::string name) { #if OPENSSL_VERSION_NUMBER >= 0x90812f SSL_set_tlsext_host_name(m_sock.native_handle(), name.c_str()); #endif } template <class T> void set_verify_callback(T const& fun, error_code& ec) { m_sock.set_verify_callback(fun, ec); } #if BOOST_VERSION >= 104700 SSL* native_handle() { return m_sock.native_handle(); } #endif typedef boost::function<void(error_code const&)> handler_type; template <class Handler> void async_connect(endpoint_type const& endpoint, Handler const& handler) { // the connect is split up in the following steps: // 1. connect to peer // 2. perform SSL client handshake // to avoid unnecessary copying of the handler, // store it in a shared_ptr boost::shared_ptr<handler_type> h(new handler_type(handler)); m_sock.next_layer().async_connect(endpoint , boost::bind(&ssl_stream::connected, this, _1, h)); } template <class Handler> void async_accept_handshake(Handler const& handler) { // this is used for accepting SSL connections boost::shared_ptr<handler_type> h(new handler_type(handler)); m_sock.async_handshake(asio::ssl::stream_base::server , boost::bind(&ssl_stream::handshake, this, _1, h)); } void accept_handshake(error_code& ec) { // this is used for accepting SSL connections m_sock.handshake(asio::ssl::stream_base::server, ec); } template <class Handler> void async_shutdown(Handler const& handler) { error_code ec; m_sock.next_layer().cancel(ec); m_sock.async_shutdown(handler); } void shutdown(error_code& ec) { m_sock.shutdown(ec); } template <class Mutable_Buffers, class Handler> void async_read_some(Mutable_Buffers const& buffers, Handler const& handler) { m_sock.async_read_some(buffers, handler); } template <class Mutable_Buffers> std::size_t read_some(Mutable_Buffers const& buffers, error_code& ec) { return m_sock.read_some(buffers, ec); } #ifndef BOOST_NO_EXCEPTIONS template <class SettableSocketOption> void set_option(SettableSocketOption const& opt) { m_sock.next_layer().set_option(opt); } #endif template <class SettableSocketOption> error_code set_option(SettableSocketOption const& opt, error_code& ec) { return m_sock.next_layer().set_option(opt, ec); } #ifndef BOOST_NO_EXCEPTIONS template <class GettableSocketOption> void get_option(GettableSocketOption& opt) { m_sock.next_layer().get_option(opt); } #endif template <class GettableSocketOption> error_code get_option(GettableSocketOption& opt, error_code& ec) { return m_sock.next_layer().get_option(opt, ec); } #ifndef BOOST_NO_EXCEPTIONS template <class Mutable_Buffers> std::size_t read_some(Mutable_Buffers const& buffers) { return m_sock.read_some(buffers); } template <class IO_Control_Command> void io_control(IO_Control_Command& ioc) { m_sock.next_layer().io_control(ioc); } #endif template <class IO_Control_Command> void io_control(IO_Control_Command& ioc, error_code& ec) { m_sock.next_layer().io_control(ioc, ec); } template <class Const_Buffers, class Handler> void async_write_some(Const_Buffers const& buffers, Handler const& handler) { m_sock.async_write_some(buffers, handler); } template <class Const_Buffers> std::size_t write_some(Const_Buffers const& buffers, error_code& ec) { return m_sock.write_some(buffers, ec); } #ifndef BOOST_NO_EXCEPTIONS std::size_t available() const { return const_cast<sock_type&>(m_sock).next_layer().available(); } #endif std::size_t available(error_code& ec) const { return const_cast<sock_type&>(m_sock).next_layer().available(ec); } #ifndef BOOST_NO_EXCEPTIONS void bind(endpoint_type const& endpoint) { m_sock.next_layer().bind(endpoint); } #endif void bind(endpoint_type const& endpoint, error_code& ec) { m_sock.next_layer().bind(endpoint, ec); } #ifndef BOOST_NO_EXCEPTIONS void open(protocol_type const& p) { m_sock.next_layer().open(p); } #endif void open(protocol_type const& p, error_code& ec) { m_sock.next_layer().open(p, ec); } bool is_open() const { return const_cast<sock_type&>(m_sock).next_layer().is_open(); } #ifndef BOOST_NO_EXCEPTIONS void close() { m_sock.next_layer().close(); } #endif void close(error_code& ec) { m_sock.next_layer().close(ec); } #ifndef BOOST_NO_EXCEPTIONS endpoint_type remote_endpoint() const { return const_cast<sock_type&>(m_sock).next_layer().remote_endpoint(); } #endif endpoint_type remote_endpoint(error_code& ec) const { return const_cast<sock_type&>(m_sock).next_layer().remote_endpoint(ec); } #ifndef BOOST_NO_EXCEPTIONS endpoint_type local_endpoint() const { return const_cast<sock_type&>(m_sock).next_layer().local_endpoint(); } #endif endpoint_type local_endpoint(error_code& ec) const { return const_cast<sock_type&>(m_sock).next_layer().local_endpoint(ec); } io_service& get_io_service() { return m_sock.get_io_service(); } lowest_layer_type& lowest_layer() { return m_sock.lowest_layer(); } next_layer_type& next_layer() { return m_sock.next_layer(); } private: void connected(error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); return; } m_sock.async_handshake(asio::ssl::stream_base::client , boost::bind(&ssl_stream::handshake, this, _1, h)); } void handshake(error_code const& e, boost::shared_ptr<handler_type> h) { (*h)(e); } asio::ssl::stream<Stream> m_sock; }; } #endif // TORRENT_USE_OPENSSL #endif
/* Copyright (c) 2008-2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_SSL_STREAM_HPP_INCLUDED #define TORRENT_SSL_STREAM_HPP_INCLUDED #ifdef TORRENT_USE_OPENSSL #include "libtorrent/socket.hpp" #include <boost/bind.hpp> #if BOOST_VERSION < 103500 #include <asio/ssl.hpp> #else #include <boost/asio/ssl.hpp> #endif // openssl seems to believe it owns // this name in every single scope #undef set_key namespace libtorrent { template <class Stream> class ssl_stream { public: explicit ssl_stream(io_service& io_service, asio::ssl::context& ctx) : m_sock(io_service, ctx) { } typedef typename asio::ssl::stream<Stream> sock_type; typedef typename sock_type::next_layer_type next_layer_type; typedef typename Stream::lowest_layer_type lowest_layer_type; typedef typename Stream::endpoint_type endpoint_type; typedef typename Stream::protocol_type protocol_type; void set_host_name(std::string name) { #if OPENSSL_VERSION_NUMBER >= 0x90812f SSL_set_tlsext_host_name(m_sock.native_handle(), name.c_str()); #endif } template <class T> void set_verify_callback(T const& fun, error_code& ec) { m_sock.set_verify_callback(fun, ec); } #if BOOST_VERSION >= 104700 SSL* native_handle() { return m_sock.native_handle(); } #endif typedef boost::function<void(error_code const&)> handler_type; template <class Handler> void async_connect(endpoint_type const& endpoint, Handler const& handler) { // the connect is split up in the following steps: // 1. connect to peer // 2. perform SSL client handshake // to avoid unnecessary copying of the handler, // store it in a shared_ptr boost::shared_ptr<handler_type> h(new handler_type(handler)); m_sock.next_layer().async_connect(endpoint , boost::bind(&ssl_stream::connected, this, _1, h)); } template <class Handler> void async_accept_handshake(Handler const& handler) { // this is used for accepting SSL connections boost::shared_ptr<handler_type> h(new handler_type(handler)); m_sock.async_handshake(asio::ssl::stream_base::server , boost::bind(&ssl_stream::handshake, this, _1, h)); } void accept_handshake(error_code& ec) { // this is used for accepting SSL connections m_sock.handshake(asio::ssl::stream_base::server, ec); } template <class Handler> void async_shutdown(Handler const& handler) { error_code ec; m_sock.next_layer().cancel(ec); m_sock.async_shutdown(handler); } void shutdown(error_code& ec) { m_sock.shutdown(ec); } template <class Mutable_Buffers, class Handler> void async_read_some(Mutable_Buffers const& buffers, Handler const& handler) { m_sock.async_read_some(buffers, handler); } template <class Mutable_Buffers> std::size_t read_some(Mutable_Buffers const& buffers, error_code& ec) { return m_sock.read_some(buffers, ec); } #ifndef BOOST_NO_EXCEPTIONS template <class SettableSocketOption> void set_option(SettableSocketOption const& opt) { m_sock.next_layer().set_option(opt); } #endif template <class SettableSocketOption> error_code set_option(SettableSocketOption const& opt, error_code& ec) { return m_sock.next_layer().set_option(opt, ec); } #ifndef BOOST_NO_EXCEPTIONS template <class GettableSocketOption> void get_option(GettableSocketOption& opt) { m_sock.next_layer().get_option(opt); } #endif template <class GettableSocketOption> error_code get_option(GettableSocketOption& opt, error_code& ec) { return m_sock.next_layer().get_option(opt, ec); } #ifndef BOOST_NO_EXCEPTIONS template <class Mutable_Buffers> std::size_t read_some(Mutable_Buffers const& buffers) { return m_sock.read_some(buffers); } template <class IO_Control_Command> void io_control(IO_Control_Command& ioc) { m_sock.next_layer().io_control(ioc); } #endif template <class IO_Control_Command> void io_control(IO_Control_Command& ioc, error_code& ec) { m_sock.next_layer().io_control(ioc, ec); } template <class Const_Buffers, class Handler> void async_write_some(Const_Buffers const& buffers, Handler const& handler) { m_sock.async_write_some(buffers, handler); } template <class Const_Buffers> std::size_t write_some(Const_Buffers const& buffers, error_code& ec) { return m_sock.write_some(buffers, ec); } // the SSL stream may cache 17 kiB internally, and there's no way of // asking how large its buffer is. 17 kiB isn't very much though, so it // seems fine to potentially over-estimate the number of bytes available. #ifndef BOOST_NO_EXCEPTIONS std::size_t available() const { return 17 * 1024 + const_cast<sock_type&>(m_sock).next_layer().available(); } #endif std::size_t available(error_code& ec) const { return 17 * 1024 + const_cast<sock_type&>(m_sock).next_layer().available(ec); } #ifndef BOOST_NO_EXCEPTIONS void bind(endpoint_type const& endpoint) { m_sock.next_layer().bind(endpoint); } #endif void bind(endpoint_type const& endpoint, error_code& ec) { m_sock.next_layer().bind(endpoint, ec); } #ifndef BOOST_NO_EXCEPTIONS void open(protocol_type const& p) { m_sock.next_layer().open(p); } #endif void open(protocol_type const& p, error_code& ec) { m_sock.next_layer().open(p, ec); } bool is_open() const { return const_cast<sock_type&>(m_sock).next_layer().is_open(); } #ifndef BOOST_NO_EXCEPTIONS void close() { m_sock.next_layer().close(); } #endif void close(error_code& ec) { m_sock.next_layer().close(ec); } #ifndef BOOST_NO_EXCEPTIONS endpoint_type remote_endpoint() const { return const_cast<sock_type&>(m_sock).next_layer().remote_endpoint(); } #endif endpoint_type remote_endpoint(error_code& ec) const { return const_cast<sock_type&>(m_sock).next_layer().remote_endpoint(ec); } #ifndef BOOST_NO_EXCEPTIONS endpoint_type local_endpoint() const { return const_cast<sock_type&>(m_sock).next_layer().local_endpoint(); } #endif endpoint_type local_endpoint(error_code& ec) const { return const_cast<sock_type&>(m_sock).next_layer().local_endpoint(ec); } io_service& get_io_service() { return m_sock.get_io_service(); } lowest_layer_type& lowest_layer() { return m_sock.lowest_layer(); } next_layer_type& next_layer() { return m_sock.next_layer(); } private: void connected(error_code const& e, boost::shared_ptr<handler_type> h) { if (e) { (*h)(e); return; } m_sock.async_handshake(asio::ssl::stream_base::client , boost::bind(&ssl_stream::handshake, this, _1, h)); } void handshake(error_code const& e, boost::shared_ptr<handler_type> h) { (*h)(e); } asio::ssl::stream<Stream> m_sock; }; } #endif // TORRENT_USE_OPENSSL #endif
fix available() function on ssl_stream
fix available() function on ssl_stream git-svn-id: 4f0141143c3c635d33f1b9f02fcb2b6c73e45c89@10376 a83610d8-ad2a-0410-a6ab-fc0612d85776
C++
bsd-3-clause
svn2github/libtorrent-rasterbar-trunk,svn2github/libtorrent-rasterbar-trunk,svn2github/libtorrent-rasterbar-trunk,svn2github/libtorrent-rasterbar-trunk
de9587b520d98d37aedc33174f29af31ebda810d
include/tao/seq/type_by_index.hpp
include/tao/seq/type_by_index.hpp
// Copyright (c) 2015-2018 Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/sequences/ #ifndef TAOCPP_SEQUENCES_INCLUDE_TYPE_BY_INDEX_HPP #define TAOCPP_SEQUENCES_INCLUDE_TYPE_BY_INDEX_HPP #include <cstddef> #include <type_traits> #include "make_integer_sequence.hpp" namespace tao { namespace seq { // based on http://stackoverflow.com/questions/18942322 namespace impl { template< std::size_t > struct any { any( ... ); }; template< typename > struct wrapper; template< typename > struct unwrap; template< typename T > struct unwrap< wrapper< T > > { using type = T; }; template< typename > struct get_nth; template< std::size_t... Is > struct get_nth< index_sequence< Is... > > { template< typename T > static T deduce( any< Is & 0 >..., T*, ... ); }; } // namespace impl template< std::size_t I, typename... Ts > using type_by_index = impl::unwrap< decltype( impl::get_nth< make_index_sequence< I > >::deduce( std::declval< impl::wrapper< Ts >* >()... ) ) >; template< std::size_t I, typename... Ts > using type_by_index_t = typename type_by_index< I, Ts... >::type; } // namespace seq } // namespace tao #endif
// Copyright (c) 2015-2018 Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/sequences/ #ifndef TAOCPP_SEQUENCES_INCLUDE_TYPE_BY_INDEX_HPP #define TAOCPP_SEQUENCES_INCLUDE_TYPE_BY_INDEX_HPP #include <cstddef> #include <type_traits> #include "make_integer_sequence.hpp" namespace tao { namespace seq { namespace impl { template< typename T > struct identity { using type = T; }; template< std::size_t, typename T > struct indexed_type { using type = T; }; template< typename, typename... > struct type_union; template< std::size_t... Is, typename... Ts > struct type_union< index_sequence< Is... >, Ts... > : indexed_type< Is, Ts >... { }; template< std::size_t I, typename T > identity< T > select_type( const indexed_type< I, T >& ); } // namespace impl template< std::size_t I, typename... Ts > using type_by_index = decltype( impl::select_type< I >( impl::type_union< index_sequence_for< Ts... >, Ts... >{} ) ); template< std::size_t I, typename... Ts > using type_by_index_t = typename type_by_index< I, Ts... >::type; } // namespace seq } // namespace tao #endif
Simplify implementation of type_by_index
Simplify implementation of type_by_index
C++
mit
taocpp/sequences,taocpp/sequences
c819aff6dc2eee223917e8382bd0fba20a113152
ModuleFactory.cxx
ModuleFactory.cxx
/****************************************************************************** This source file is part of the TEM tomography project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "ModuleFactory.h" #ifdef DAX_DEVICE_ADAPTER # include "dax/ModuleStreamingContour.h" #endif #include "ModuleContour.h" #include "ModuleOrthogonalSlice.h" #include "ModuleOutline.h" #include "ModuleThreshold.h" #include "ModuleVolume.h" #include "pqView.h" #include "Utilities.h" #include "vtkSMViewProxy.h" #include <QtAlgorithms> namespace TEM { //----------------------------------------------------------------------------- ModuleFactory::ModuleFactory() { } //----------------------------------------------------------------------------- ModuleFactory::~ModuleFactory() { } //----------------------------------------------------------------------------- QList<QString> ModuleFactory::moduleTypes( vtkSMSourceProxy* dataSource, vtkSMViewProxy* view) { QList<QString> reply; if (dataSource && view) { // based on the data type and view, return module types. reply << "Outline" << "Volume" << "Contour" << "Threshold" << "Orthogonal Slice"; qSort(reply); } return reply; } //----------------------------------------------------------------------------- Module* ModuleFactory::createModule( const QString& type, vtkSMSourceProxy* dataSource, vtkSMViewProxy* view) { Module* module = NULL; if (type == "Outline") { module = new ModuleOutline(); } else if (type == "Contour") { #ifdef DAX_DEVICE_ADAPTER module = new ModuleContour(); #else module = new ModuleContour(); #endif } else if (type == "Volume") { module = new ModuleVolume(); } else if (type == "Orthogonal Slice") { module = new ModuleOrthogonalSlice(); } else if (type == "Threshold") { module = new ModuleThreshold(); } if (module) { if (!module->initialize(dataSource, view)) { delete module; return NULL; } pqView* pqview = TEM::convert<pqView*>(view); pqview->resetDisplay(); pqview->render(); } return module; } } // end of namespace TEM
/****************************************************************************** This source file is part of the TEM tomography project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "ModuleFactory.h" #ifdef DAX_DEVICE_ADAPTER # include "dax/ModuleStreamingContour.h" #endif #include "ModuleContour.h" #include "ModuleOrthogonalSlice.h" #include "ModuleOutline.h" #include "ModuleThreshold.h" #include "ModuleVolume.h" #include "pqView.h" #include "Utilities.h" #include "vtkSMViewProxy.h" #include <QtAlgorithms> namespace TEM { //----------------------------------------------------------------------------- ModuleFactory::ModuleFactory() { } //----------------------------------------------------------------------------- ModuleFactory::~ModuleFactory() { } //----------------------------------------------------------------------------- QList<QString> ModuleFactory::moduleTypes( vtkSMSourceProxy* dataSource, vtkSMViewProxy* view) { QList<QString> reply; if (dataSource && view) { // based on the data type and view, return module types. reply << "Outline" << "Volume" << "Contour" << "Threshold" << "Orthogonal Slice"; qSort(reply); } return reply; } //----------------------------------------------------------------------------- Module* ModuleFactory::createModule( const QString& type, vtkSMSourceProxy* dataSource, vtkSMViewProxy* view) { Module* module = NULL; if (type == "Outline") { module = new ModuleOutline(); } else if (type == "Contour") { #ifdef DAX_DEVICE_ADAPTER module = new ModuleStreamingContour(); #else module = new ModuleContour(); #endif } else if (type == "Volume") { module = new ModuleVolume(); } else if (type == "Orthogonal Slice") { module = new ModuleOrthogonalSlice(); } else if (type == "Threshold") { module = new ModuleThreshold(); } if (module) { if (!module->initialize(dataSource, view)) { delete module; return NULL; } pqView* pqview = TEM::convert<pqView*>(view); pqview->resetDisplay(); pqview->render(); } return module; } } // end of namespace TEM
Enable the Streaming Contour Module.
Enable the Streaming Contour Module.
C++
bsd-3-clause
OpenChemistry/tomviz,cjh1/tomviz,OpenChemistry/tomviz,yijiang1/tomviz,thewtex/tomviz,Hovden/tomviz,thewtex/tomviz,cryos/tomviz,yijiang1/tomviz,cjh1/tomviz,OpenChemistry/tomviz,cjh1/tomviz,Hovden/tomviz,mathturtle/tomviz,thewtex/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,cryos/tomviz,cryos/tomviz,mathturtle/tomviz
49bddd2127a6052587207d139c35149c9d34a8eb
OpenCV/OpenCV.cpp
OpenCV/OpenCV.cpp
#include <opencv/cv.h> #include <opencv2/opencv.hpp> #include <opencv2/ocl/ocl.hpp> #include <chrono> #include <iomanip> struct Timing { Timing(const std::chrono::milliseconds& cpu, const std::chrono::milliseconds& gpu) : cpu(cpu) , gpu(gpu) {} std::chrono::milliseconds cpu; std::chrono::milliseconds gpu; }; Timing time_cvtColor(const cv::Mat& host_img, size_t iterations) { cv::Mat host_gray; const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::cvtColor(host_img, host_gray, CV_RGB2GRAY); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_gray; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::cvtColor(gpu_img, gpu_gray, CV_RGB2GRAY); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_gray - gpu_gray; assert( cv::norm(difference, cv::NORM_INF) <.01 ); #endif return Timing(cpu_time, gpu_time); } Timing time_boxFilter(const cv::Mat& host_img, size_t iterations) { cv::Mat host_filtered(host_img.size(), host_img.type()); const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::boxFilter(host_img, host_filtered, -1, cv::Size(5,5)); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_filtered(gpu_img.size(), gpu_img.type()); const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::boxFilter(gpu_img, gpu_filtered, -1, cv::Size(5,5)); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_filtered - gpu_filtered; assert( cv::norm(difference, cv::NORM_INF) <= 1.0 ); #endif return Timing(cpu_time, gpu_time); } Timing time_integral(const cv::Mat& img, size_t iterations) { cv::Mat host_img; { cv::Mat img_gray; cv::cvtColor(img, img_gray, CV_RGB2GRAY); cv::resize(img_gray, host_img, cv::Size(500, 500)); } cv::Mat host_integral; const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::integral(host_img, host_integral, CV_32F); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_integral; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::integral(gpu_img, gpu_integral); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_integral - gpu_integral; assert( cv::norm(difference, cv::NORM_INF) <= 1e-5 ); #endif return Timing(cpu_time, gpu_time); } Timing time_dilate(const cv::Mat& host_img, size_t iterations) { cv::Mat host_dilate; cv::Mat element = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(7,7)); const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::dilate(host_img, host_dilate, element); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_dilate; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::dilate(gpu_img, gpu_dilate,element); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_dilate - gpu_dilate; assert( cv::norm(difference, cv::NORM_INF) <= 1e-5 ); #endif return Timing(cpu_time, gpu_time); } Timing time_convolve(const cv::Mat& img, size_t iterations) { //cv::ocl only support CV_32FC1 images cv::Mat host_img; { cv::Mat img_gray; cv::cvtColor(img, img_gray, CV_BGR2GRAY); img_gray.convertTo(host_img, CV_32F, 1.0/255.0); } cv::Mat host_convolve; float kernel_data[] = {-1, -1, -1 , 0, 0, 0 , 1, 1, 1 }; cv::Mat kernel_cpu(3, 3, CV_32F, kernel_data); const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::filter2D(host_img, host_convolve, -1, kernel_cpu, cv::Point(-1,-1), 0.0, cv::BORDER_REPLICATE); //cv::ocl has only a convolve functions, with the extra parameters working like this const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); const cv::ocl::oclMat kernel_gpu(kernel_cpu); cv::ocl::oclMat gpu_convolve; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::convolve(gpu_img, kernel_gpu, gpu_convolve); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_convolve - gpu_convolve; assert( cv::norm(difference, cv::NORM_INF) <= 1e-5 ); #endif return Timing(cpu_time, gpu_time); } Timing time_gaussian(const cv::Mat& img, size_t iterations) { cv::Mat host_img; cv::resize(img, host_img, cv::Size(500, 500)); cv::Mat host_gaussian; const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::GaussianBlur(host_img, host_gaussian, cv::Size(5,5), 0, 0, cv::BORDER_REPLICATE); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_gaussian; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::GaussianBlur(gpu_img, gpu_gaussian, cv::Size(5,5), 0, 0, cv::BORDER_REPLICATE); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_gaussian - gpu_gaussian; assert( cv::norm(difference, cv::NORM_INF) <= 1 ); #endif return Timing(cpu_time, gpu_time); } Timing time_resize(const cv::Mat& host_img, size_t iterations) { cv::Mat host_resize; const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::resize(host_img, host_resize, cv::Size(1000,1000)); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_resize; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::resize(gpu_img, gpu_resize, cv::Size(1000,1000)); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_resize - gpu_resize; assert( cv::norm(difference, cv::NORM_INF) <= 1 ); #endif return Timing(cpu_time, gpu_time); } Timing time_warpAffine(const cv::Mat& host_img, size_t iterations) { cv::Mat host_warp; float transform_data[] = { 2.0f , 0.5f, -500.0f , 0.333f, 3.0f, -500.0f }; cv::Mat transform(2, 3, CV_32F, transform_data); const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::warpAffine(host_img, host_warp, transform, cv::Size(1000,1000)); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_warp; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::warpAffine(gpu_img, gpu_warp, transform, cv::Size(1000,1000)); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_warp - gpu_warp; assert( cv::norm(difference, cv::NORM_INF) <= 1 ); #endif return Timing(cpu_time, gpu_time); } int main() { const cv::Mat img_large = cv::imread("c:/Work/CARP/test1.jpg"); cv::Mat img; cv::resize(img_large, img, cv::Size(5792, 5792)); //Larger: cv::ocl::cvtColor doesn't work (returns memory garbage on some parts of the picture) #ifdef _DEBUG size_t num_iterations = 1; #else size_t num_iterations = 100; #endif std::cout << " Operator - CPU_time - GPU_time" << std::endl; const auto boxFilter_times = time_boxFilter (img, num_iterations); std::cout << " boxFilter - " << std::setw(6) << boxFilter_times.cpu.count() << "ms - " << std::setw(6) << boxFilter_times.gpu.count() << "ms" << std::endl; const auto integral_times = time_integral (img, num_iterations); std::cout << " integral - " << std::setw(6) << integral_times.cpu.count() << "ms - " << std::setw(6) << integral_times.gpu.count() << "ms" << std::endl; const auto cvtColor_times = time_cvtColor (img, num_iterations); std::cout << " cvtColor - " << std::setw(6) << cvtColor_times.cpu.count() << "ms - " << std::setw(6) << cvtColor_times.gpu.count() << "ms" << std::endl; const auto dilate_times = time_dilate (img, num_iterations); std::cout << " dilate - " << std::setw(6) << dilate_times.cpu.count() << "ms - " << std::setw(6) << dilate_times.gpu.count() << "ms" << std::endl; const auto convolve_times = time_convolve (img, num_iterations); std::cout << " filter2D - " << std::setw(6) << convolve_times.cpu.count() << "ms - " << std::setw(6) << convolve_times.gpu.count() << "ms" << std::endl; const auto gaussian_times = time_gaussian (img, num_iterations); std::cout << " gaussian - " << std::setw(6) << gaussian_times.cpu.count() << "ms - " << std::setw(6) << gaussian_times.gpu.count() << "ms" << std::endl; const auto resize_times = time_resize (img, num_iterations); std::cout << " resize - " << std::setw(6) << resize_times.cpu.count() << "ms - " << std::setw(6) << resize_times.gpu.count() << "ms" << std::endl; const auto affine_times = time_warpAffine(img, num_iterations); std::cout << "warpAffine - " << std::setw(6) << affine_times.cpu.count() << "ms - " << std::setw(6) << affine_times.gpu.count() << "ms" << std::endl; int i = 5; }
#include <opencv/cv.h> #include <opencv2/opencv.hpp> #include <opencv2/ocl/ocl.hpp> #include <chrono> #include <iomanip> #include <string> struct Timing { Timing(const std::string& name, const std::chrono::milliseconds& cpu, const std::chrono::milliseconds& gpu) : name(name) , cpu(cpu) , gpu(gpu) {} std::string name; std::chrono::milliseconds cpu; std::chrono::milliseconds gpu; static void printHeader() { std::cout << " Operator - CPU_time - GPU_time - speedup" << std::endl; } void print() const { auto speedup = (double)cpu.count()/(double)gpu.count(); std::cout << std::setw(12) << name << " - " << std::setw(6) << cpu.count() << "ms - " << std::setw(6) << gpu.count() << "ms - " << std::setw(7) << std::fixed << std::setprecision(3) << speedup << 'x' << std::endl; } }; Timing time_cvtColor(const cv::Mat& host_img, size_t iterations) { cv::Mat host_gray; const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::cvtColor(host_img, host_gray, CV_RGB2GRAY); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_gray; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::cvtColor(gpu_img, gpu_gray, CV_RGB2GRAY); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_gray - gpu_gray; assert( cv::norm(difference, cv::NORM_INF) <.01 ); #endif return Timing("cvtColor", cpu_time, gpu_time); } Timing time_boxFilter(const cv::Mat& host_img, size_t iterations) { cv::Mat host_filtered(host_img.size(), host_img.type()); const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::boxFilter(host_img, host_filtered, -1, cv::Size(5,5)); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_filtered(gpu_img.size(), gpu_img.type()); const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::boxFilter(gpu_img, gpu_filtered, -1, cv::Size(5,5)); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_filtered - gpu_filtered; assert( cv::norm(difference, cv::NORM_INF) <= 1.0 ); #endif return Timing("boxFilter", cpu_time, gpu_time); } Timing time_integral(const cv::Mat& img, size_t iterations) { cv::Mat host_img; { cv::Mat img_gray; cv::cvtColor(img, img_gray, CV_RGB2GRAY); cv::resize(img_gray, host_img, cv::Size(500, 500)); } cv::Mat host_integral; const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::integral(host_img, host_integral, CV_32F); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_integral; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::integral(gpu_img, gpu_integral); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_integral - gpu_integral; assert( cv::norm(difference, cv::NORM_INF) <= 1e-5 ); #endif return Timing("integral", cpu_time, gpu_time); } Timing time_dilate(const cv::Mat& host_img, size_t iterations) { cv::Mat host_dilate; cv::Mat element = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(7,7)); const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::dilate(host_img, host_dilate, element); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_dilate; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::dilate(gpu_img, gpu_dilate,element); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_dilate - gpu_dilate; assert( cv::norm(difference, cv::NORM_INF) <= 1e-5 ); #endif return Timing("dilate", cpu_time, gpu_time); } Timing time_convolve(const cv::Mat& img, size_t iterations) { //cv::ocl only support CV_32FC1 images cv::Mat host_img; { cv::Mat img_gray; cv::cvtColor(img, img_gray, CV_BGR2GRAY); img_gray.convertTo(host_img, CV_32F, 1.0/255.0); } cv::Mat host_convolve; float kernel_data[] = {-1, -1, -1 , 0, 0, 0 , 1, 1, 1 }; cv::Mat kernel_cpu(3, 3, CV_32F, kernel_data); const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::filter2D(host_img, host_convolve, -1, kernel_cpu, cv::Point(-1,-1), 0.0, cv::BORDER_REPLICATE); //cv::ocl has only a convolve functions, with the extra parameters working like this const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); const cv::ocl::oclMat kernel_gpu(kernel_cpu); cv::ocl::oclMat gpu_convolve; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::convolve(gpu_img, kernel_gpu, gpu_convolve); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_convolve - gpu_convolve; assert( cv::norm(difference, cv::NORM_INF) <= 1e-5 ); #endif return Timing("filter2D", cpu_time, gpu_time); } Timing time_gaussian(const cv::Mat& img, size_t iterations) { cv::Mat host_img; cv::resize(img, host_img, cv::Size(500, 500)); cv::Mat host_gaussian; const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::GaussianBlur(host_img, host_gaussian, cv::Size(5,5), 0, 0, cv::BORDER_REPLICATE); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_gaussian; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::GaussianBlur(gpu_img, gpu_gaussian, cv::Size(5,5), 0, 0, cv::BORDER_REPLICATE); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_gaussian - gpu_gaussian; assert( cv::norm(difference, cv::NORM_INF) <= 1 ); #endif return Timing("GaussianBlur", cpu_time, gpu_time); } Timing time_resize(const cv::Mat& host_img, size_t iterations) { cv::Mat host_resize; const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::resize(host_img, host_resize, cv::Size(1000,1000)); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_resize; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::resize(gpu_img, gpu_resize, cv::Size(1000,1000)); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_resize - gpu_resize; assert( cv::norm(difference, cv::NORM_INF) <= 1 ); #endif return Timing("resize", cpu_time, gpu_time); } Timing time_warpAffine(const cv::Mat& host_img, size_t iterations) { cv::Mat host_warp; float transform_data[] = { 2.0f , 0.5f, -500.0f , 0.333f, 3.0f, -500.0f }; cv::Mat transform(2, 3, CV_32F, transform_data); const auto cpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::warpAffine(host_img, host_warp, transform, cv::Size(1000,1000)); const auto cpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - cpu_start); const cv::ocl::oclMat gpu_img(host_img); cv::ocl::oclMat gpu_warp; const auto gpu_start = std::chrono::high_resolution_clock::now(); for(int i = 1; i <= iterations; ++i) cv::ocl::warpAffine(gpu_img, gpu_warp, transform, cv::Size(1000,1000)); const auto gpu_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - gpu_start); #ifdef _DEBUG cv::Mat difference = host_warp - gpu_warp; assert( cv::norm(difference, cv::NORM_INF) <= 1 ); #endif return Timing("warpAffine", cpu_time, gpu_time); } int main(int argc, char* argv[]) { const cv::Mat img_large = cv::imread("test1.jpg"); cv::Mat img; cv::resize(img_large, img, cv::Size(5792, 5792)); //Larger: cv::ocl::cvtColor doesn't work (returns memory garbage on some parts of the picture) size_t num_iterations = 1; if (argc > 1) num_iterations = std::stoi(argv[1]); Timing::printHeader(); time_boxFilter (img, num_iterations).print(); time_integral (img, num_iterations).print(); time_cvtColor (img, num_iterations).print(); time_dilate (img, num_iterations).print(); time_convolve (img, num_iterations).print(); time_gaussian (img, num_iterations).print(); time_resize (img, num_iterations).print(); time_warpAffine(img, num_iterations).print(); int i = 5; }
Simplify printing, add speedup multipliers, add number of iterations as a parameter.
Simplify printing, add speedup multipliers, add number of iterations as a parameter.
C++
mit
dividiti/pencil-benchmark,rbaghdadi/pencil-benchmark,dividiti/pencil-benchmark,dividiti/pencil-benchmark,rbaghdadi/pencil-benchmark,pencil-language/pencil-benchmark,pencil-language/pencil-benchmark,pencil-language/pencil-benchmark,rbaghdadi/pencil-benchmark
45eb65b8d38b470f54fb1fd26d7ee3bf47637ed5
ase.cpp
ase.cpp
#include "ase.hpp" #include <stdint.h> #include <fstream> #if defined(_MSC_VER) #include <intrin.h> #define SWAP32(x) _byteswap_ulong(x) #define SWAP16(x) _byteswap_ushort(x) #elif defined(__GNUC__) || defined(__clang__) #define SWAP32(x) __builtin_bswap32(x) #define SWAP16(x) __builtin_bswap16(x) #else inline uint16_t SWAP16(uint16_t x) { return ( ((x & 0x00FF) << 8) | ((x & 0xFF00) >> 8) ); } inline uint32_t SWAP32(uint32_t x) { return( ((x & 0x000000FF) << 24) | ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8) | ((x & 0xFF000000) >> 24) ); } #endif namespace ase { enum BlockClass : uint16_t { ColorEntry = 0x0001, GroupBegin = 0xC001, GroupEnd = 0xC002 }; enum ColorModel : uint32_t { // Big Endian CMYK = 'CMYK', RGB = 'RGB ', LAB = 'LAB ', GRAY = 'Gray' }; enum ColorType : uint16_t { Global = 0, Spot = 1, Normal = 2 }; bool LoadFromFile( ColorCallback& Callback, const char* FileName ) { std::ifstream SwatchFile; SwatchFile.open( FileName, std::ios::binary ); return LoadFromStream(Callback, SwatchFile); } bool LoadFromStream( ColorCallback& Callback, std::istream &Stream ) { if( !Stream ) { return false; } uint32_t Magic; Stream.read( reinterpret_cast<char*>(&Magic), sizeof(uint32_t) ); Magic = SWAP32(Magic); if( Magic != 'ASEF' ) { return false; } uint16_t Version[2]; uint32_t BlockCount; Stream.read( reinterpret_cast<char*>(&Version[0]), sizeof(uint16_t) ); Stream.read( reinterpret_cast<char*>(&Version[1]), sizeof(uint16_t) ); Stream.read( reinterpret_cast<char*>(&BlockCount), sizeof(uint32_t) ); Version[0] = SWAP16(Version[0]); Version[1] = SWAP16(Version[1]); BlockCount = SWAP32(BlockCount); uint16_t CurBlockClass; uint32_t CurBlockSize; // Process stream while( BlockCount-- ) { Stream.read( reinterpret_cast<char*>(&CurBlockClass), sizeof(uint16_t) ); CurBlockClass = SWAP16(CurBlockClass); switch( CurBlockClass ) { case BlockClass::ColorEntry: case BlockClass::GroupBegin: { Stream.read( reinterpret_cast<char*>(&CurBlockSize), sizeof(uint32_t) ); CurBlockSize = SWAP32(CurBlockSize); std::u16string EntryName; uint16_t EntryNameLength; Stream.read( reinterpret_cast<char*>(&EntryNameLength), sizeof(uint16_t) ); EntryNameLength = SWAP16(EntryNameLength); EntryName.clear(); EntryName.resize(EntryNameLength); Stream.read( reinterpret_cast<char*>(&EntryName[0]), EntryNameLength * 2 ); // Endian swap each character for( size_t i = 0; i < EntryNameLength; i++ ) { EntryName[i] = SWAP16(EntryName[i]); } if( CurBlockClass == BlockClass::GroupBegin ) { Callback.GroupBegin( EntryName ); } else if( CurBlockClass == BlockClass::ColorEntry ) { uint32_t ColorModel; Stream.read( reinterpret_cast<char*>(&ColorModel), sizeof(uint32_t) ); ColorModel = SWAP32(ColorModel); float Channels[4]; switch( ColorModel ) { case ColorModel::CMYK: { Stream.read( reinterpret_cast<char*>(Channels), sizeof(float) * 4 ); *reinterpret_cast<uint32_t*>(&Channels[0]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[0])); *reinterpret_cast<uint32_t*>(&Channels[1]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[1])); *reinterpret_cast<uint32_t*>(&Channels[2]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[2])); *reinterpret_cast<uint32_t*>(&Channels[3]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[3])); Callback.ColorCYMK( EntryName, Channels[0], Channels[1], Channels[2], Channels[3] ); break; } case ColorModel::RGB: { Stream.read( reinterpret_cast<char*>(Channels), sizeof(float) * 3 ); *reinterpret_cast<uint32_t*>(&Channels[0]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[0])); *reinterpret_cast<uint32_t*>(&Channels[1]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[1])); *reinterpret_cast<uint32_t*>(&Channels[2]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[2])); Callback.ColorRGB( EntryName, Channels[0], Channels[1], Channels[2] ); break; } case ColorModel::LAB: { Stream.read( reinterpret_cast<char*>(Channels), sizeof(float) * 3 ); *reinterpret_cast<uint32_t*>(&Channels[0]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[0])); *reinterpret_cast<uint32_t*>(&Channels[1]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[1])); *reinterpret_cast<uint32_t*>(&Channels[2]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[2])); Callback.ColorLAB( EntryName, Channels[0], Channels[1], Channels[2] ); break; } case ColorModel::GRAY: { Stream.read( reinterpret_cast<char*>(Channels), sizeof(float) * 1 ); *reinterpret_cast<uint32_t*>(&Channels[0]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[0])); Callback.ColorGray( EntryName, Channels[0] ); break; } } uint16_t ColorType; Stream.read( reinterpret_cast<char*>(&ColorType), sizeof(uint16_t) ); ColorType = SWAP16(ColorType); } break; } case BlockClass::GroupEnd: { Callback.GroupEnd(); break; } } } return true; } template< typename T > inline T ReadType(const void* &Pointer) { const T *Temp = static_cast<const T*>(Pointer); Pointer = static_cast<const T*>(Pointer) + static_cast<ptrdiff_t>(1); return *Temp; } template<> inline uint32_t ReadType<uint32_t>(const void* &Pointer) { const uint32_t *Temp = static_cast<const uint32_t*>(Pointer); Pointer = static_cast<const uint32_t*>(Pointer) + static_cast<ptrdiff_t>(1); return SWAP32(*Temp); } template<> inline uint16_t ReadType<uint16_t>(const void* &Pointer) { const uint16_t *Temp = static_cast<const uint16_t*>(Pointer); Pointer = static_cast<const uint16_t*>(Pointer) + static_cast<ptrdiff_t>(1); return SWAP16(*Temp); } template<> inline float ReadType<float>(const void* &Pointer) { uint32_t Temp = SWAP32(*static_cast<const uint32_t*>(Pointer)); Pointer = static_cast<const float*>(Pointer) + static_cast<ptrdiff_t>(1); return *reinterpret_cast<float*>(&Temp); } inline void Read(const void* &Pointer, void* Dest, size_t Count) { Dest = memcpy(Dest, Pointer, Count); Pointer = static_cast<const uint8_t*>(Pointer) + Count; } bool LoadFromMemory( ColorCallback& Callback, const void* Buffer, size_t Size ) { if( Buffer == nullptr ) { return false; } const void* ReadPoint = Buffer; uint32_t Magic = ReadType<uint32_t>(ReadPoint); if( Magic != 'ASEF' ) { return false; } uint16_t Version[2]; uint32_t BlockCount; Version[0] = ReadType<uint16_t>(ReadPoint); Version[1] = ReadType<uint16_t>(ReadPoint); BlockCount = ReadType<uint32_t>(ReadPoint); uint16_t CurBlockClass; uint32_t CurBlockSize; // Process stream while( BlockCount-- ) { CurBlockClass = ReadType<uint16_t>(ReadPoint); switch( CurBlockClass ) { case BlockClass::ColorEntry: case BlockClass::GroupBegin: { CurBlockSize = ReadType<uint32_t>(ReadPoint); uint16_t EntryNameLength; EntryNameLength = ReadType<uint16_t>(ReadPoint); std::u16string EntryName; EntryName.resize(EntryNameLength); // Endian swap each character for( size_t i = 0; i < EntryNameLength; i++ ) { EntryName[i] = ReadType<uint16_t>(ReadPoint); } if( CurBlockClass == BlockClass::GroupBegin ) { Callback.GroupBegin( EntryName ); } else if( CurBlockClass == BlockClass::ColorEntry ) { uint32_t ColorModel; ColorModel = ReadType<uint32_t>(ReadPoint); float Channels[4]; switch( ColorModel ) { case ColorModel::CMYK: { Channels[0] = ReadType<float>(ReadPoint); Channels[1] = ReadType<float>(ReadPoint); Channels[2] = ReadType<float>(ReadPoint); Channels[3] = ReadType<float>(ReadPoint); Callback.ColorCYMK( EntryName, Channels[0], Channels[1], Channels[2], Channels[3] ); break; } case ColorModel::RGB: { Channels[0] = ReadType<float>(ReadPoint); Channels[1] = ReadType<float>(ReadPoint); Channels[2] = ReadType<float>(ReadPoint); Callback.ColorRGB( EntryName, Channels[0], Channels[1], Channels[2] ); break; } case ColorModel::LAB: { Channels[0] = ReadType<float>(ReadPoint); Channels[1] = ReadType<float>(ReadPoint); Channels[2] = ReadType<float>(ReadPoint); Callback.ColorLAB( EntryName, Channels[0], Channels[1], Channels[2] ); break; } case ColorModel::GRAY: { Channels[0] = ReadType<float>(ReadPoint); Callback.ColorGray( EntryName, Channels[0] ); break; } } uint16_t ColorType; ColorType = ReadType<uint16_t>(ReadPoint); } break; } case BlockClass::GroupEnd: { Callback.GroupEnd(); break; } } } return true; } }
#include "ase.hpp" #include <stdint.h> #include <fstream> #if defined(_MSC_VER) #include <intrin.h> #define SWAP32(x) _byteswap_ulong(x) #define SWAP16(x) _byteswap_ushort(x) #elif defined(__GNUC__) || defined(__clang__) #define SWAP32(x) __builtin_bswap32(x) #define SWAP16(x) __builtin_bswap16(x) #else inline uint16_t SWAP16(uint16_t x) { return ( ((x & 0x00FF) << 8) | ((x & 0xFF00) >> 8) ); } inline uint32_t SWAP32(uint32_t x) { return( ((x & 0x000000FF) << 24) | ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8) | ((x & 0xFF000000) >> 24) ); } #endif namespace ase { enum BlockClass : uint16_t { ColorEntry = 0x0001, GroupBegin = 0xC001, GroupEnd = 0xC002 }; enum ColorModel : uint32_t { // Big Endian CMYK = 'CMYK', RGB = 'RGB ', LAB = 'LAB ', GRAY = 'Gray' }; enum ColorType : uint16_t { Global = 0, Spot = 1, Normal = 2 }; bool LoadFromFile( ColorCallback& Callback, const char* FileName ) { std::ifstream SwatchFile; SwatchFile.open( FileName, std::ios::binary ); return LoadFromStream(Callback, SwatchFile); } bool LoadFromStream( ColorCallback& Callback, std::istream &Stream ) { if( !Stream ) { return false; } uint32_t Magic; Stream.read( reinterpret_cast<char*>(&Magic), sizeof(uint32_t) ); Magic = SWAP32(Magic); if( Magic != 'ASEF' ) { return false; } uint16_t Version[2]; uint32_t BlockCount; Stream.read( reinterpret_cast<char*>(&Version[0]), sizeof(uint16_t) ); Stream.read( reinterpret_cast<char*>(&Version[1]), sizeof(uint16_t) ); Stream.read( reinterpret_cast<char*>(&BlockCount), sizeof(uint32_t) ); Version[0] = SWAP16(Version[0]); Version[1] = SWAP16(Version[1]); BlockCount = SWAP32(BlockCount); uint16_t CurBlockClass; uint32_t CurBlockSize; // Process stream while( BlockCount-- && Stream ) { Stream.read( reinterpret_cast<char*>(&CurBlockClass), sizeof(uint16_t) ); CurBlockClass = SWAP16(CurBlockClass); switch( CurBlockClass ) { case BlockClass::ColorEntry: case BlockClass::GroupBegin: { Stream.read( reinterpret_cast<char*>(&CurBlockSize), sizeof(uint32_t) ); CurBlockSize = SWAP32(CurBlockSize); std::u16string EntryName; uint16_t EntryNameLength; Stream.read( reinterpret_cast<char*>(&EntryNameLength), sizeof(uint16_t) ); EntryNameLength = SWAP16(EntryNameLength); EntryName.clear(); EntryName.resize(EntryNameLength); Stream.read( reinterpret_cast<char*>(&EntryName[0]), EntryNameLength * 2 ); // Endian swap each character for( size_t i = 0; i < EntryNameLength; i++ ) { EntryName[i] = SWAP16(EntryName[i]); } if( CurBlockClass == BlockClass::GroupBegin ) { Callback.GroupBegin( EntryName ); } else if( CurBlockClass == BlockClass::ColorEntry ) { uint32_t ColorModel; Stream.read( reinterpret_cast<char*>(&ColorModel), sizeof(uint32_t) ); ColorModel = SWAP32(ColorModel); float Channels[4]; switch( ColorModel ) { case ColorModel::CMYK: { Stream.read( reinterpret_cast<char*>(Channels), sizeof(float) * 4 ); *reinterpret_cast<uint32_t*>(&Channels[0]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[0])); *reinterpret_cast<uint32_t*>(&Channels[1]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[1])); *reinterpret_cast<uint32_t*>(&Channels[2]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[2])); *reinterpret_cast<uint32_t*>(&Channels[3]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[3])); Callback.ColorCYMK( EntryName, Channels[0], Channels[1], Channels[2], Channels[3] ); break; } case ColorModel::RGB: { Stream.read( reinterpret_cast<char*>(Channels), sizeof(float) * 3 ); *reinterpret_cast<uint32_t*>(&Channels[0]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[0])); *reinterpret_cast<uint32_t*>(&Channels[1]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[1])); *reinterpret_cast<uint32_t*>(&Channels[2]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[2])); Callback.ColorRGB( EntryName, Channels[0], Channels[1], Channels[2] ); break; } case ColorModel::LAB: { Stream.read( reinterpret_cast<char*>(Channels), sizeof(float) * 3 ); *reinterpret_cast<uint32_t*>(&Channels[0]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[0])); *reinterpret_cast<uint32_t*>(&Channels[1]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[1])); *reinterpret_cast<uint32_t*>(&Channels[2]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[2])); Callback.ColorLAB( EntryName, Channels[0], Channels[1], Channels[2] ); break; } case ColorModel::GRAY: { Stream.read( reinterpret_cast<char*>(Channels), sizeof(float) * 1 ); *reinterpret_cast<uint32_t*>(&Channels[0]) = SWAP32(*reinterpret_cast<uint32_t*>(&Channels[0])); Callback.ColorGray( EntryName, Channels[0] ); break; } } uint16_t ColorType; Stream.read( reinterpret_cast<char*>(&ColorType), sizeof(uint16_t) ); ColorType = SWAP16(ColorType); } break; } case BlockClass::GroupEnd: { Callback.GroupEnd(); break; } } } return true; } template< typename T > inline T ReadType(const void* &Pointer) { const T *Temp = static_cast<const T*>(Pointer); Pointer = static_cast<const T*>(Pointer) + static_cast<ptrdiff_t>(1); return *Temp; } template<> inline uint32_t ReadType<uint32_t>(const void* &Pointer) { const uint32_t *Temp = static_cast<const uint32_t*>(Pointer); Pointer = static_cast<const uint32_t*>(Pointer) + static_cast<ptrdiff_t>(1); return SWAP32(*Temp); } template<> inline uint16_t ReadType<uint16_t>(const void* &Pointer) { const uint16_t *Temp = static_cast<const uint16_t*>(Pointer); Pointer = static_cast<const uint16_t*>(Pointer) + static_cast<ptrdiff_t>(1); return SWAP16(*Temp); } template<> inline float ReadType<float>(const void* &Pointer) { uint32_t Temp = SWAP32(*static_cast<const uint32_t*>(Pointer)); Pointer = static_cast<const float*>(Pointer) + static_cast<ptrdiff_t>(1); return *reinterpret_cast<float*>(&Temp); } inline void Read(const void* &Pointer, void* Dest, size_t Count) { Dest = memcpy(Dest, Pointer, Count); Pointer = static_cast<const uint8_t*>(Pointer) + Count; } bool LoadFromMemory( ColorCallback& Callback, const void* Buffer, size_t Size ) { if( Buffer == nullptr ) { return false; } const void* ReadPoint = Buffer; uint32_t Magic = ReadType<uint32_t>(ReadPoint); if( Magic != 'ASEF' ) { return false; } uint16_t Version[2]; uint32_t BlockCount; Version[0] = ReadType<uint16_t>(ReadPoint); Version[1] = ReadType<uint16_t>(ReadPoint); BlockCount = ReadType<uint32_t>(ReadPoint); uint16_t CurBlockClass; uint32_t CurBlockSize; // Process stream while( BlockCount-- ) { CurBlockClass = ReadType<uint16_t>(ReadPoint); switch( CurBlockClass ) { case BlockClass::ColorEntry: case BlockClass::GroupBegin: { CurBlockSize = ReadType<uint32_t>(ReadPoint); uint16_t EntryNameLength; EntryNameLength = ReadType<uint16_t>(ReadPoint); std::u16string EntryName; EntryName.resize(EntryNameLength); // Endian swap each character for( size_t i = 0; i < EntryNameLength; i++ ) { EntryName[i] = ReadType<uint16_t>(ReadPoint); } if( CurBlockClass == BlockClass::GroupBegin ) { Callback.GroupBegin( EntryName ); } else if( CurBlockClass == BlockClass::ColorEntry ) { uint32_t ColorModel; ColorModel = ReadType<uint32_t>(ReadPoint); float Channels[4]; switch( ColorModel ) { case ColorModel::CMYK: { Channels[0] = ReadType<float>(ReadPoint); Channels[1] = ReadType<float>(ReadPoint); Channels[2] = ReadType<float>(ReadPoint); Channels[3] = ReadType<float>(ReadPoint); Callback.ColorCYMK( EntryName, Channels[0], Channels[1], Channels[2], Channels[3] ); break; } case ColorModel::RGB: { Channels[0] = ReadType<float>(ReadPoint); Channels[1] = ReadType<float>(ReadPoint); Channels[2] = ReadType<float>(ReadPoint); Callback.ColorRGB( EntryName, Channels[0], Channels[1], Channels[2] ); break; } case ColorModel::LAB: { Channels[0] = ReadType<float>(ReadPoint); Channels[1] = ReadType<float>(ReadPoint); Channels[2] = ReadType<float>(ReadPoint); Callback.ColorLAB( EntryName, Channels[0], Channels[1], Channels[2] ); break; } case ColorModel::GRAY: { Channels[0] = ReadType<float>(ReadPoint); Callback.ColorGray( EntryName, Channels[0] ); break; } } uint16_t ColorType; ColorType = ReadType<uint16_t>(ReadPoint); } break; } case BlockClass::GroupEnd: { Callback.GroupEnd(); break; } } } return true; } }
Add check for stream validity during loop
Add check for stream validity during loop
C++
mit
Wunkolo/libase
35013ff02b0ba51e23a50531c454b9f8ec533d7c
test/unit/math/rev/mat/functor/gradient_test.cpp
test/unit/math/rev/mat/functor/gradient_test.cpp
#include <stan/math/rev/mat.hpp> #include <gtest/gtest.h> #include <stdexcept> using Eigen::Dynamic; using Eigen::Matrix; // fun1(x, y) = (x^2 * y) + (3 * y^2) struct fun1 { template <typename T> inline T operator()(const Matrix<T, Dynamic, 1>& x) const { return x(0) * x(0) * x(1) + 3.0 * x(1) * x(1); } }; TEST(AgradAutoDiff, gradient) { fun1 f; Matrix<double, Dynamic, 1> x(2); x << 5, 7; double fx; Matrix<double, Dynamic, 1> grad_fx; stan::math::gradient(f, x, fx, grad_fx); EXPECT_FLOAT_EQ(5 * 5 * 7 + 3 * 7 * 7, fx); EXPECT_EQ(2, grad_fx.size()); EXPECT_FLOAT_EQ(2 * x(0) * x(1), grad_fx(0)); EXPECT_FLOAT_EQ(x(0) * x(0) + 3 * 2 * x(1), grad_fx(1)); } stan::math::var sum_and_throw(const Matrix<stan::math::var, Dynamic, 1>& x) { stan::math::var y = 0; for (int i = 0; i < x.size(); ++i) y += x(i); throw std::domain_error("fooey"); return y; } TEST(AgradAutoDiff, RecoverMemory) { using Eigen::VectorXd; for (int i = 0; i < 100000; ++i) { try { VectorXd x(5); x << 1, 2, 3, 4, 5; double fx; VectorXd grad_fx; stan::math::gradient(sum_and_throw, x, fx, grad_fx); } catch (const std::domain_error& e) { // ignore me } } // depends on starting allocation of 65K not being exceeded // without recovery_memory in autodiff::apply_recover(), takes 67M EXPECT_LT(stan::math::ChainableStack::memalloc_.bytes_allocated(), 100000); }
#include <stan/math/rev/mat.hpp> #include <gtest/gtest.h> #include <stdexcept> #include <vector> #include <thread> #include <future> using Eigen::Dynamic; using Eigen::Matrix; using Eigen::MatrixXd; using Eigen::VectorXd; // fun1(x, y) = (x^2 * y) + (3 * y^2) struct fun1 { template <typename T> inline T operator()(const Matrix<T, Dynamic, 1>& x) const { return x(0) * x(0) * x(1) + 3.0 * x(1) * x(1); } }; TEST(AgradAutoDiff, gradient) { fun1 f; Matrix<double, Dynamic, 1> x(2); x << 5, 7; double fx; Matrix<double, Dynamic, 1> grad_fx; stan::math::gradient(f, x, fx, grad_fx); EXPECT_FLOAT_EQ(5 * 5 * 7 + 3 * 7 * 7, fx); EXPECT_EQ(2, grad_fx.size()); EXPECT_FLOAT_EQ(2 * x(0) * x(1), grad_fx(0)); EXPECT_FLOAT_EQ(x(0) * x(0) + 3 * 2 * x(1), grad_fx(1)); } // test threaded AD TEST(AgradAutoDiff, gradient_threaded) { fun1 f; Matrix<double, Dynamic, 1> x(2); x << 5, 7; double fx_ref; Matrix<double, Dynamic, 1> grad_fx_ref; stan::math::gradient(f, x, fx_ref, grad_fx_ref); EXPECT_FLOAT_EQ(5 * 5 * 7 + 3 * 7 * 7, fx_ref); EXPECT_EQ(2, grad_fx_ref.size()); EXPECT_FLOAT_EQ(2 * x(0) * x(1), grad_fx_ref(0)); EXPECT_FLOAT_EQ(x(0) * x(0) + 3 * 2 * x(1), grad_fx_ref(1)); auto thread_job = [&]() { double fx; VectorXd grad_fx; stan::math::gradient(fun1(), x, fx, grad_fx); VectorXd res(1+grad_fx.size()); res(0) = fx; res.tail(grad_fx.size()) = grad_fx; return res; }; std::vector<std::future<VectorXd>> ad_futures; for (std::size_t i=0; i < 100; i++) { // the use pattern in stan-math will be to defer the first job in // order to make the main thread to some work which is why we // alter the execution policy here ad_futures.emplace_back(std::async( i == 0 ? std::launch::deferred : std::launch::async, thread_job)); } for (std::size_t i=0; i < 100; i++) { const VectorXd& ad_result = ad_futures[i].get(); double fx_job = ad_result(0); VectorXd grad_fx_job = ad_result.tail(ad_result.size()-1); EXPECT_FLOAT_EQ(fx_ref, fx_job); EXPECT_EQ(grad_fx_ref.size(), grad_fx_job.size()); EXPECT_FLOAT_EQ(grad_fx_ref(0), grad_fx_job(0)); EXPECT_FLOAT_EQ(grad_fx_ref(1), grad_fx_job(1)); } } stan::math::var sum_and_throw(const Matrix<stan::math::var, Dynamic, 1>& x) { stan::math::var y = 0; for (int i = 0; i < x.size(); ++i) y += x(i); throw std::domain_error("fooey"); return y; } TEST(AgradAutoDiff, RecoverMemory) { using Eigen::VectorXd; for (int i = 0; i < 100000; ++i) { try { VectorXd x(5); x << 1, 2, 3, 4, 5; double fx; VectorXd grad_fx; stan::math::gradient(sum_and_throw, x, fx, grad_fx); } catch (const std::domain_error& e) { // ignore me } } // depends on starting allocation of 65K not being exceeded // without recovery_memory in autodiff::apply_recover(), takes 67M EXPECT_LT(stan::math::ChainableStack::context().memalloc_.bytes_allocated(), 100000); }
add threaded gradient test
add threaded gradient test
C++
bsd-3-clause
stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math
24cb681861aba393db1b061acc77cab8a9dfc651
dstar-lite/src/dstar_from_input.cpp
dstar-lite/src/dstar_from_input.cpp
#include <iostream> #include "dstar_lite/dstar.h" #ifdef MACOS #else #include <GL/glut.h> #include <GL/gl.h> #include <GL/glu.h> #endif #include <stdlib.h> #include <unistd.h> #include <zmq.hpp> #include <string> #include <iostream> #include <sstream> #include <array> #ifndef _WIN32 #include <unistd.h> #else #include <windows.h> #define sleep(n) Sleep(n) #endif #include "dstar_lite/dstar.h" bool constexpr debug_gui = false; int hh, ww; int window; Dstar *dstar; int scale = 30; int mbutton = 0; int mstate = 0; bool b_autoreplan = true; #ifdef MACOS #else void InitGL(int Width, int Height) { hh = Height; ww = Width; glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0); glViewport(0,0,Width,Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,Width,0,Height,-100,100); glMatrixMode(GL_MODELVIEW); } void ReSizeGLScene(int Width, int Height) { hh = Height; ww = Width; glViewport(0,0,Width,Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,Width,0,Height,-100,100); glMatrixMode(GL_MODELVIEW); } void DrawGLScene() { usleep(100); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glLoadIdentity(); glPushMatrix(); glScaled(scale,scale,1); if (b_autoreplan) dstar->replan(); dstar->draw(); glPopMatrix(); glutSwapBuffers(); } void keyPressed(unsigned char key, int x, int y) { usleep(100); switch(key) { case 'q': case 'Q': glutDestroyWindow(window); exit(0); break; case 'r': case 'R': dstar->replan(); break; case 'a': case 'A': b_autoreplan = !b_autoreplan; break; case 'c': case 'C': dstar->init(40,50,140, 90); break; } } void mouseFunc(int button, int state, int x, int y) { y = hh -y+scale/2; x += scale/2; mbutton = button; if ((mstate = state) == GLUT_DOWN) { if (button == GLUT_LEFT_BUTTON) { dstar->updateCell(x/scale, y/scale, -1); } else if (button == GLUT_RIGHT_BUTTON) { dstar->updateStart(x/scale, y/scale); } else if (button == GLUT_MIDDLE_BUTTON) { dstar->updateGoal(x/scale, y/scale); } } } void mouseMotionFunc(int x, int y) { y = hh -y+scale/2; x += scale/2; y /= scale; x /= scale; if (mstate == GLUT_DOWN) { if (mbutton == GLUT_LEFT_BUTTON) { dstar->updateCell(x, y, -1); } else if (mbutton == GLUT_RIGHT_BUTTON) { dstar->updateStart(x, y); } else if (mbutton == GLUT_MIDDLE_BUTTON) { dstar->updateGoal(x, y); } } } #endif int main(int argc, char **argv) { // Prepare our context and socket // for request/reply communication with client. zmq::context_t context (1); zmq::socket_t socket (context, ZMQ_REP); socket.bind ("tcp://*:5555"); // Check that there are 3 arguments, aka argc == 4. if (argc != 4) { std::cerr << "Terminating. Incorrect number of arguments." << "Expected 3." << std::endl; return EXIT_FAILURE; } // Parse grid. std::string flat_grid = argv[3]; // Construct a grid. const uint grid_size = (uint)std::sqrt(flat_grid.size()); std::vector<std::vector<int>> occupancy_grid (grid_size, vector<int>(grid_size)); // Parse input // Retrieve start position const uint start = std::atoi(argv[1]); std::array<uint, 2> start_indices; start_indices[0] = std::floor(start / grid_size); //x index start_indices[1] = start - start_indices[0] * grid_size; //y index // Retrieve goal position const uint goal = std::atoi(argv[2]); std::array<uint, 2> goal_indices; goal_indices[0] = std::floor(goal / grid_size); //x index goal_indices[1] = goal - goal_indices[0] * grid_size; //y index // Reshape input to a grid with x, y coordinates for (uint i = 0, j = 0, k = 0; k < flat_grid.size(); k++) { j = k % grid_size; // Check that we are not out of bounds. if ( i < grid_size && j < grid_size) { const int a = 1 - ((int)flat_grid.at(k) - 48); occupancy_grid[i][j] = a; } else { std::cerr << "Index out of bounds, check that" " input grid is squared." << std::endl; return EXIT_FAILURE; } if (j == (grid_size - 1)) { i++; } } dstar = new Dstar(); dstar->init(start_indices[0], start_indices[1] , goal_indices[0], goal_indices[1]); for (uint i = 0; i < occupancy_grid.size(); i++) { for (uint j = 0; j < occupancy_grid.at(i).size(); j++) { if (occupancy_grid.at(i).at(j) == 1) { dstar->updateCell(i, j, -1); } } } uint replan_counter = 0; uint update_counter = 0; while (true) { zmq::message_t request; // Wait for next request from client socket.recv(&request); std::string rpl = std::string( static_cast<char*>(request.data()), request.size()); if (rpl == "replan") { replan_counter++; std::cout << "[Dstar cpp] Requested to replan [" << replan_counter << "]" << std::endl; if (!dstar->replan()) { std::cerr << "No found path to goal." << std::endl; return EXIT_FAILURE; } // Parse calculated path. list<state> path = dstar->getPath(); std::string path_string; std::ostringstream convert; // stream used for the conversion for(const state& waypoint: path) { // Make message reply. convert << waypoint.x * grid_size + waypoint.y << '.'; } path_string = convert.str(); // Send reply back to client zmq::message_t reply (path_string.size()); memcpy (reply.data (), path_string.c_str(), path_string.size()); socket.send (reply); } else if (rpl == "update") { update_counter++; std::cout << "[Dstar cpp] Requested to update cell [" << update_counter << "]" << std::endl; // Send reply back to client to acknowledge request. zmq::message_t reply (2); memcpy (reply.data (), "go", 2); socket.send (reply); // Wait for cell coordinates to be updated. socket.recv(&request); std::string rpl = std::string( static_cast<char*>(request.data()), request.size()); istringstream iss(rpl); vector<string> x_y_coords{istream_iterator<string>{iss}, istream_iterator<string>{}}; if (x_y_coords.size() != 2) { // Send reply back to client with error. zmq::message_t reply (2); memcpy (reply.data (), "Expected 2 coordinates", 2); socket.send (reply); } else { dstar->updateCell(std::atoi(x_y_coords.at(0).c_str()), std::atoi(x_y_coords.at(1).c_str()), -1); // Send reply back to client of success. zmq::message_t reply (2); memcpy (reply.data (), "ok", 2); socket.send (reply); } } else { std::cerr << "[Dstar cpp] Error, could not understand command: " << rpl << std::endl; // Send reply back to client zmq::message_t reply (5); memcpy (reply.data (), "fail", 5); socket.send (reply); } } #ifdef MACOS #else if (debug_gui) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(1000, 800); glutInitWindowPosition(50, 20); window = glutCreateWindow("Dstar Visualizer"); glutDisplayFunc(&DrawGLScene); glutIdleFunc(&DrawGLScene); glutReshapeFunc(&ReSizeGLScene); glutKeyboardFunc(&keyPressed); glutMouseFunc(&mouseFunc); glutMotionFunc(&mouseMotionFunc); InitGL(800, 600); dstar->draw(); glutMainLoop(); } #endif return EXIT_SUCCESS; }
#include <iostream> #include "dstar_lite/dstar.h" #ifdef MACOS #else #include <GL/glut.h> #include <GL/gl.h> #include <GL/glu.h> #endif #include <stdlib.h> #include <unistd.h> #include <zmq.hpp> #include <string> #include <iostream> #include <sstream> #include <array> #ifndef _WIN32 #include <unistd.h> #else #include <windows.h> #define sleep(n) Sleep(n) #endif #include "dstar_lite/dstar.h" bool constexpr debug_gui = false; int hh, ww; int window; Dstar *dstar; int scale = 30; int mbutton = 0; int mstate = 0; bool b_autoreplan = true; #ifdef MACOS #else void InitGL(int Width, int Height) { hh = Height; ww = Width; glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0); glViewport(0,0,Width,Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,Width,0,Height,-100,100); glMatrixMode(GL_MODELVIEW); } void ReSizeGLScene(int Width, int Height) { hh = Height; ww = Width; glViewport(0,0,Width,Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,Width,0,Height,-100,100); glMatrixMode(GL_MODELVIEW); } void DrawGLScene() { usleep(100); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glLoadIdentity(); glPushMatrix(); glScaled(scale,scale,1); if (b_autoreplan) dstar->replan(); dstar->draw(); glPopMatrix(); glutSwapBuffers(); } void keyPressed(unsigned char key, int x, int y) { usleep(100); switch(key) { case 'q': case 'Q': glutDestroyWindow(window); exit(0); break; case 'r': case 'R': dstar->replan(); break; case 'a': case 'A': b_autoreplan = !b_autoreplan; break; case 'c': case 'C': dstar->init(40,50,140, 90); break; } } void mouseFunc(int button, int state, int x, int y) { y = hh -y+scale/2; x += scale/2; mbutton = button; if ((mstate = state) == GLUT_DOWN) { if (button == GLUT_LEFT_BUTTON) { dstar->updateCell(x/scale, y/scale, -1); } else if (button == GLUT_RIGHT_BUTTON) { dstar->updateStart(x/scale, y/scale); } else if (button == GLUT_MIDDLE_BUTTON) { dstar->updateGoal(x/scale, y/scale); } } } void mouseMotionFunc(int x, int y) { y = hh -y+scale/2; x += scale/2; y /= scale; x /= scale; if (mstate == GLUT_DOWN) { if (mbutton == GLUT_LEFT_BUTTON) { dstar->updateCell(x, y, -1); } else if (mbutton == GLUT_RIGHT_BUTTON) { dstar->updateStart(x, y); } else if (mbutton == GLUT_MIDDLE_BUTTON) { dstar->updateGoal(x, y); } } } #endif int main(int argc, char **argv) { // Prepare our context and socket // for request/reply communication with client. zmq::context_t context (1); zmq::socket_t socket (context, ZMQ_REP); socket.bind ("tcp://*:5555"); // Check that there are 3 arguments, aka argc == 4. if (argc != 4) { std::cerr << "Terminating. Incorrect number of arguments." << "Expected 3." << std::endl; return EXIT_FAILURE; } // Parse grid. std::string flat_grid = argv[3]; // Construct a grid. const uint grid_size = (uint)std::sqrt(flat_grid.size()); std::vector<std::vector<int>> occupancy_grid (grid_size, vector<int>(grid_size)); // Parse input // Retrieve start position const uint start = std::atoi(argv[1]); std::array<uint, 2> start_indices; start_indices[0] = std::floor(start / grid_size); //x index start_indices[1] = start - start_indices[0] * grid_size; //y index // Retrieve goal position const uint goal = std::atoi(argv[2]); std::array<uint, 2> goal_indices; goal_indices[0] = std::floor(goal / grid_size); //x index goal_indices[1] = goal - goal_indices[0] * grid_size; //y index // Reshape input to a grid with x, y coordinates for (uint i = 0, j = 0, k = 0; k < flat_grid.size(); k++) { j = k % grid_size; // Check that we are not out of bounds. if ( i < grid_size && j < grid_size) { const int a = 1 - ((int)flat_grid.at(k) - 48); occupancy_grid[i][j] = a; } else { std::cerr << "Index out of bounds, check that" " input grid is squared." << std::endl; return EXIT_FAILURE; } if (j == (grid_size - 1)) { i++; } } dstar = new Dstar(); dstar->init(start_indices[0], start_indices[1] , goal_indices[0], goal_indices[1]); for (uint i = 0; i < occupancy_grid.size(); i++) { for (uint j = 0; j < occupancy_grid.at(i).size(); j++) { if (occupancy_grid.at(i).at(j) == 1) { dstar->updateCell(i, j, -1); } } } uint replan_counter = 0; uint update_counter = 0; while (true) { zmq::message_t request; // Wait for next request from client socket.recv(&request); std::string rpl = std::string( static_cast<char*>(request.data()), request.size()); if (rpl == "replan") { replan_counter++; std::cout << "[Dstar cpp] Requested to replan [" << replan_counter << "]" << std::endl; if (!dstar->replan()) { std::cerr << "No found path to goal." << std::endl; return EXIT_FAILURE; } // Parse calculated path. list<state> path = dstar->getPath(); std::string path_string; std::ostringstream convert; // stream used for the conversion for(const state& waypoint: path) { // Make message reply. convert << waypoint.x * grid_size + waypoint.y << '.'; } path_string = convert.str(); // Send reply back to client zmq::message_t reply (path_string.size()); memcpy (reply.data (), path_string.c_str(), path_string.size()); socket.send (reply); } else if (rpl == "update") { update_counter++; std::cout << "[Dstar cpp] Requested to update cell [" << update_counter << "]" << std::endl; // Send reply back to client to acknowledge request. zmq::message_t reply (2); memcpy (reply.data (), "go", 2); socket.send (reply); // Wait for cell coordinates to be updated. socket.recv(&request); std::string rpl = std::string( static_cast<char*>(request.data()), request.size()); istringstream iss(rpl); vector<string> x_y_coords{istream_iterator<string>{iss}, istream_iterator<string>{}}; if (x_y_coords.size() != 2) { // Send reply back to client with error. zmq::message_t reply (2); memcpy (reply.data (), "Expected 2 coordinates", 2); socket.send (reply); } else { // Dstar has an inverted representation of x y coords (y x instead). dstar->updateCell(std::atoi(x_y_coords.at(1).c_str()), std::atoi(x_y_coords.at(0).c_str()), -1); // Send reply back to client of success. zmq::message_t reply (2); memcpy (reply.data (), "ok", 2); socket.send (reply); } } else { std::cerr << "[Dstar cpp] Error, could not understand command: " << rpl << std::endl; // Send reply back to client zmq::message_t reply (5); memcpy (reply.data (), "fail", 5); socket.send (reply); } } #ifdef MACOS #else if (debug_gui) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(1000, 800); glutInitWindowPosition(50, 20); window = glutCreateWindow("Dstar Visualizer"); glutDisplayFunc(&DrawGLScene); glutIdleFunc(&DrawGLScene); glutReshapeFunc(&ReSizeGLScene); glutKeyboardFunc(&keyPressed); glutMouseFunc(&mouseFunc); glutMotionFunc(&mouseMotionFunc); InitGL(800, 600); dstar->draw(); glutMainLoop(); } #endif return EXIT_SUCCESS; }
Fix index issue in grid
Fix index issue in grid
C++
mit
ToniRV/Learning-to-navigate-without-a-map,ToniRV/Learning-to-navigate-without-a-map
dd09334ff03f48d02f5e87da697fef95ca1a0246
DueTimer.cpp
DueTimer.cpp
/* DueTimer.cpp - Implementation of Timers defined on DueTimer.h For instructions, go to https://github.com/ivanseidel/DueTimer Created by Ivan Seidel Gomes, March, 2013. Thanks to stimmer (from Arduino forum), for coding the "timer soul" (Register stuff) Released into the public domain. */ #include "DueTimer.h" const DueTimer::Timer DueTimer::Timers[9] = { {TC0,0,TC0_IRQn}, {TC0,1,TC1_IRQn}, {TC0,2,TC2_IRQn}, {TC1,0,TC3_IRQn}, {TC1,1,TC4_IRQn}, {TC1,2,TC5_IRQn}, {TC2,0,TC6_IRQn}, {TC2,1,TC7_IRQn}, {TC2,2,TC8_IRQn}, }; void (*DueTimer::callbacks[9])() = {}; double DueTimer::_frequency[9] = {1,1,1,1,1,1,1,1,1}; /* Initialize all timers, so you can use it like: Timer0.start(); */ DueTimer Timer(0); DueTimer Timer0(0); DueTimer Timer1(1); DueTimer Timer2(2); DueTimer Timer3(3); DueTimer Timer4(4); DueTimer Timer5(5); DueTimer Timer6(6); DueTimer Timer7(7); DueTimer Timer8(8); // Constructor DueTimer::DueTimer(int _timer){ timer = _timer; // Initialize Default frequency setFrequency(_frequency[_timer]); } // Get the first timer without any callbacks DueTimer DueTimer::getAvailable(){ for(int i = 0; i < 9; i++){ if(!callbacks[i]) return DueTimer(i); } // Default, return Timer0; return DueTimer(0); } // Links the function passed as argument to the timer of the object DueTimer DueTimer::attachInterrupt(void (*isr)()){ callbacks[timer] = isr; return *this; } // Links the function passed as argument to the timer of the object DueTimer DueTimer::detachInterrupt(){ // Stop running timer stop(); callbacks[timer] = NULL; return *this; } // Start the timer // If a period is set, then sets the period and start the timer DueTimer DueTimer::start(long microseconds){ if(microseconds > 0) setPeriod(microseconds); NVIC_EnableIRQ(Timers[timer].irq); return *this; } // Stop the timer DueTimer DueTimer::stop(){ NVIC_DisableIRQ(Timers[timer].irq); return *this; } // Pick the best Clock // It uses Black magic to do this, thanks to Ogle Basil Hall! uint8_t DueTimer::bestClock(double frequency, uint32_t& retRC){ /* Timer Definition TIMER_CLOCK1 MCK/2 TIMER_CLOCK2 MCK/8 TIMER_CLOCK3 MCK/32 TIMER_CLOCK4 MCK/128 */ struct { uint8_t flag; uint8_t divisor; } clockConfig[] = { { TC_CMR_TCCLKS_TIMER_CLOCK1, 2 }, { TC_CMR_TCCLKS_TIMER_CLOCK2, 8 }, { TC_CMR_TCCLKS_TIMER_CLOCK3, 32 }, { TC_CMR_TCCLKS_TIMER_CLOCK4, 128 } }; float ticks; float error; int clkId = 3; int bestClock = 3; float bestError = 1.0; do { ticks = (float) VARIANT_MCK / frequency / (float) clockConfig[clkId].divisor; error = abs(ticks - round(ticks)); if (abs(error) < bestError) { bestClock = clkId; bestError = error; } } while (clkId-- > 0); ticks = (float) VARIANT_MCK / frequency / (float) clockConfig[bestClock].divisor; retRC = (uint32_t) round(ticks); return clockConfig[bestClock].flag; } // Set the frequency (in Hz) DueTimer DueTimer::setFrequency(double frequency){ //prevent negative frequencies if(frequency <= 0) { frequency = 1; } // Saves current frequency _frequency[timer] = frequency; // Get current timer configurations Timer t = Timers[timer]; uint32_t rc = 0; uint8_t clock; // Yes, we don't want pmc protected! pmc_set_writeprotect(false); // Enable clock for the timer pmc_enable_periph_clk((uint32_t)Timers[timer].irq); // Do magic, and find's best clock clock = bestClock(frequency, rc); TC_Configure(t.tc, t.channel, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | clock); // Pwm stuff TC_SetRA(t.tc, t.channel, rc/2); //50% high, 50% low TC_SetRC(t.tc, t.channel, rc); TC_Start(t.tc, t.channel); t.tc->TC_CHANNEL[t.channel].TC_IER=TC_IER_CPCS; t.tc->TC_CHANNEL[t.channel].TC_IDR=~TC_IER_CPCS; return *this; } // Set the period of the timer (in microseconds) DueTimer DueTimer::setPeriod(long microseconds){ double frequency = 1000000.0 / microseconds; setFrequency(frequency); // Convert from period in microseconds to frequency in Hz return *this; } // Get current time frequency double DueTimer::getFrequency(){ return _frequency[timer]; } // Get current time period long DueTimer::getPeriod(){ return 1.0/getFrequency()*1000000; } /* Default timers callbacks DO NOT CHANGE! */ void TC0_Handler(){ TC_GetStatus(TC0, 0); DueTimer::callbacks[0](); } void TC1_Handler(){ TC_GetStatus(TC0, 1); DueTimer::callbacks[1](); } void TC2_Handler(){ TC_GetStatus(TC0, 2); DueTimer::callbacks[2](); } void TC3_Handler(){ TC_GetStatus(TC1, 0); DueTimer::callbacks[3](); } void TC4_Handler(){ TC_GetStatus(TC1, 1); DueTimer::callbacks[4](); } void TC5_Handler(){ TC_GetStatus(TC1, 2); DueTimer::callbacks[5](); } void TC6_Handler(){ TC_GetStatus(TC2, 0); DueTimer::callbacks[6](); } void TC7_Handler(){ TC_GetStatus(TC2, 1); DueTimer::callbacks[7](); } void TC8_Handler(){ TC_GetStatus(TC2, 2); DueTimer::callbacks[8](); }
/* DueTimer.cpp - Implementation of Timers defined on DueTimer.h For instructions, go to https://github.com/ivanseidel/DueTimer Created by Ivan Seidel Gomes, March, 2013. Thanks to stimmer (from Arduino forum), for coding the "timer soul" (Register stuff) Released into the public domain. */ #include "DueTimer.h" const DueTimer::Timer DueTimer::Timers[9] = { {TC0,0,TC0_IRQn}, {TC0,1,TC1_IRQn}, {TC0,2,TC2_IRQn}, {TC1,0,TC3_IRQn}, {TC1,1,TC4_IRQn}, {TC1,2,TC5_IRQn}, {TC2,0,TC6_IRQn}, {TC2,1,TC7_IRQn}, {TC2,2,TC8_IRQn}, }; void (*DueTimer::callbacks[9])() = {}; double DueTimer::_frequency[9] = {1,1,1,1,1,1,1,1,1}; /* Initialize all timers, so you can use it like: Timer0.start(); */ DueTimer Timer(0); DueTimer Timer0(0); DueTimer Timer1(1); DueTimer Timer2(2); DueTimer Timer3(3); DueTimer Timer4(4); DueTimer Timer5(5); DueTimer Timer6(6); DueTimer Timer7(7); DueTimer Timer8(8); // Constructor DueTimer::DueTimer(int _timer){ timer = _timer; // Initialize Default frequency setFrequency(_frequency[_timer]); } // Get the first timer without any callbacks DueTimer DueTimer::getAvailable(){ for(int i = 0; i < 9; i++){ if(!callbacks[i]) return DueTimer(i); } // Default, return Timer0; return DueTimer(0); } // Links the function passed as argument to the timer of the object DueTimer DueTimer::attachInterrupt(void (*isr)()){ callbacks[timer] = isr; return *this; } // Links the function passed as argument to the timer of the object DueTimer DueTimer::detachInterrupt(){ // Stop running timer stop(); callbacks[timer] = NULL; return *this; } // Start the timer // If a period is set, then sets the period and start the timer DueTimer DueTimer::start(long microseconds){ if(microseconds > 0) setPeriod(microseconds); NVIC_ClearPendingIRQ(Timers[timer].irq); NVIC_EnableIRQ(Timers[timer].irq); return *this; } // Stop the timer DueTimer DueTimer::stop(){ NVIC_DisableIRQ(Timers[timer].irq); return *this; } // Pick the best Clock // It uses Black magic to do this, thanks to Ogle Basil Hall! uint8_t DueTimer::bestClock(double frequency, uint32_t& retRC){ /* Timer Definition TIMER_CLOCK1 MCK/2 TIMER_CLOCK2 MCK/8 TIMER_CLOCK3 MCK/32 TIMER_CLOCK4 MCK/128 */ struct { uint8_t flag; uint8_t divisor; } clockConfig[] = { { TC_CMR_TCCLKS_TIMER_CLOCK1, 2 }, { TC_CMR_TCCLKS_TIMER_CLOCK2, 8 }, { TC_CMR_TCCLKS_TIMER_CLOCK3, 32 }, { TC_CMR_TCCLKS_TIMER_CLOCK4, 128 } }; float ticks; float error; int clkId = 3; int bestClock = 3; float bestError = 1.0; do { ticks = (float) VARIANT_MCK / frequency / (float) clockConfig[clkId].divisor; error = abs(ticks - round(ticks)); if (abs(error) < bestError) { bestClock = clkId; bestError = error; } } while (clkId-- > 0); ticks = (float) VARIANT_MCK / frequency / (float) clockConfig[bestClock].divisor; retRC = (uint32_t) round(ticks); return clockConfig[bestClock].flag; } // Set the frequency (in Hz) DueTimer DueTimer::setFrequency(double frequency){ //prevent negative frequencies if(frequency <= 0) { frequency = 1; } // Saves current frequency _frequency[timer] = frequency; // Get current timer configurations Timer t = Timers[timer]; uint32_t rc = 0; uint8_t clock; // Yes, we don't want pmc protected! pmc_set_writeprotect(false); // Enable clock for the timer pmc_enable_periph_clk((uint32_t)Timers[timer].irq); // Do magic, and find's best clock clock = bestClock(frequency, rc); TC_Configure(t.tc, t.channel, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | clock); // Pwm stuff TC_SetRA(t.tc, t.channel, rc/2); //50% high, 50% low TC_SetRC(t.tc, t.channel, rc); TC_Start(t.tc, t.channel); t.tc->TC_CHANNEL[t.channel].TC_IER=TC_IER_CPCS; t.tc->TC_CHANNEL[t.channel].TC_IDR=~TC_IER_CPCS; return *this; } // Set the period of the timer (in microseconds) DueTimer DueTimer::setPeriod(long microseconds){ double frequency = 1000000.0 / microseconds; setFrequency(frequency); // Convert from period in microseconds to frequency in Hz return *this; } // Get current time frequency double DueTimer::getFrequency(){ return _frequency[timer]; } // Get current time period long DueTimer::getPeriod(){ return 1.0/getFrequency()*1000000; } /* Default timers callbacks DO NOT CHANGE! */ void TC0_Handler(){ TC_GetStatus(TC0, 0); DueTimer::callbacks[0](); } void TC1_Handler(){ TC_GetStatus(TC0, 1); DueTimer::callbacks[1](); } void TC2_Handler(){ TC_GetStatus(TC0, 2); DueTimer::callbacks[2](); } void TC3_Handler(){ TC_GetStatus(TC1, 0); DueTimer::callbacks[3](); } void TC4_Handler(){ TC_GetStatus(TC1, 1); DueTimer::callbacks[4](); } void TC5_Handler(){ TC_GetStatus(TC1, 2); DueTimer::callbacks[5](); } void TC6_Handler(){ TC_GetStatus(TC2, 0); DueTimer::callbacks[6](); } void TC7_Handler(){ TC_GetStatus(TC2, 1); DueTimer::callbacks[7](); } void TC8_Handler(){ TC_GetStatus(TC2, 2); DueTimer::callbacks[8](); }
Clear pending IRQ before "start()" re-enables IRQ
Clear pending IRQ before "start()" re-enables IRQ This change prevents the event handler from being called immediately if there is a pending interrupt (because a period has elapsed) when calling start.
C++
mit
ivankravets/DueTimer,ivanseidel/DueTimer
adbca39fef3402e5ce3b3b906c844fcd5a1d0472
plugins/map_matching.hpp
plugins/map_matching.hpp
/* Copyright (c) 2015, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 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 MAP_MATCHING_HPP #define MAP_MATCHING_HPP #include "plugin_base.hpp" #include "../algorithms/bayes_classifier.hpp" #include "../algorithms/object_encoder.hpp" #include "../data_structures/search_engine.hpp" #include "../descriptors/descriptor_base.hpp" #include "../descriptors/gpx_descriptor.hpp" #include "../descriptors/json_descriptor.hpp" #include "../routing_algorithms/map_matching.hpp" #include "../util/compute_angle.hpp" #include "../util/integer_range.hpp" #include "../util/simple_logger.hpp" #include "../util/string_util.hpp" #include <cstdlib> #include <algorithm> #include <memory> #include <string> #include <vector> template <class DataFacadeT> class MapMatchingPlugin : public BasePlugin { private: std::unordered_map<std::string, unsigned> descriptor_table; std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr; using ClassifierT = BayesClassifier<LaplaceDistribution, LaplaceDistribution, double>; using TraceClassification = ClassifierT::ClassificationT; public: MapMatchingPlugin(DataFacadeT *facade) : descriptor_string("match") , facade(facade) // the values where derived from fitting a laplace distribution // to the values of manually classified traces , classifier(LaplaceDistribution(0.0057154021891018675, 0.020294704891166186), LaplaceDistribution(0.11467696742821254, 0.49918444000368756), 0.7977883096366508) // valid apriori probability { descriptor_table.emplace("json", 0); search_engine_ptr = std::make_shared<SearchEngine<DataFacadeT>>(facade); } virtual ~MapMatchingPlugin() { } const std::string GetDescriptor() const final { return descriptor_string; } TraceClassification classify(float trace_length, float matched_length, int removed_points) const { double distance_feature = -std::log(trace_length) + std::log(matched_length); // matched to the same point if (!std::isfinite(distance_feature)) { return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0); } auto label_with_confidence = classifier.classify(distance_feature); // "second stage classifier": if we need to remove points there is something fishy if (removed_points > 0) { return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0); } return label_with_confidence; } bool get_candiates(const std::vector<FixedPointCoordinate>& input_coords, std::vector<double>& sub_trace_lengths, Matching::CandidateLists& candidates_lists) { double last_distance = coordinate_calculation::great_circle_distance( input_coords[0], input_coords[1]); sub_trace_lengths.resize(input_coords.size()); sub_trace_lengths[0] = 0; for (const auto current_coordinate : osrm::irange<std::size_t>(0, input_coords.size())) { bool allow_uturn = false; if (0 < current_coordinate) { last_distance = coordinate_calculation::great_circle_distance( input_coords[current_coordinate - 1], input_coords[current_coordinate]); sub_trace_lengths[current_coordinate] += sub_trace_lengths[current_coordinate-1] + last_distance; } if (input_coords.size()-1 > current_coordinate && 0 < current_coordinate) { double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates( input_coords[current_coordinate-1], input_coords[current_coordinate], input_coords[current_coordinate+1]); // sharp turns indicate a possible uturn if (turn_angle < 100.0 || turn_angle > 260.0) { allow_uturn = true; } } std::vector<std::pair<PhantomNode, double>> candidates; if (!facade->IncrementalFindPhantomNodeForCoordinateWithMaxDistance( input_coords[current_coordinate], candidates, last_distance/2.0, 5, Matching::max_number_of_candidates)) { return false; } if (allow_uturn) { candidates_lists.push_back(candidates); } else { unsigned compact_size = candidates.size(); for (const auto i : osrm::irange(0u, compact_size)) { // Split edge if it is bidirectional and append reverse direction to end of list if (candidates[i].first.forward_node_id != SPECIAL_NODEID && candidates[i].first.reverse_node_id != SPECIAL_NODEID) { PhantomNode reverse_node(candidates[i].first); reverse_node.forward_node_id = SPECIAL_NODEID; candidates.push_back(std::make_pair(reverse_node, candidates[i].second)); candidates[i].first.reverse_node_id = SPECIAL_NODEID; } } candidates_lists.push_back(candidates); } } return true; } int HandleRequest(const RouteParameters &route_parameters, osrm::json::Object &json_result) final { // check number of parameters if (!check_all_coordinates(route_parameters.coordinates)) { return 400; } std::vector<double> sub_trace_lengths; Matching::CandidateLists candidates_lists; const auto& input_coords = route_parameters.coordinates; const auto& input_timestamps = route_parameters.timestamps; if (input_timestamps.size() > 0 && input_coords.size() != input_timestamps.size()) { return 400; } bool found_candidates = get_candiates(input_coords, sub_trace_lengths, candidates_lists); if (!found_candidates) { return 400; } // call the actual map matching osrm::json::Object debug_info; Matching::SubMatchingList sub_matchings; search_engine_ptr->map_matching(candidates_lists, input_coords, input_timestamps, sub_matchings, debug_info); if (1 > sub_matchings.size()) { return 400; } osrm::json::Array matchings; for (auto& sub : sub_matchings) { // classify result double trace_length = sub_trace_lengths[sub.indices.back()] - sub_trace_lengths[sub.indices.front()]; TraceClassification classification = classify(trace_length, sub.length, (sub.indices.back() - sub.indices.front() + 1) - sub.nodes.size()); if (classification.first == ClassifierT::ClassLabel::POSITIVE) { sub.confidence = classification.second; } else { sub.confidence = 1-classification.second; } BOOST_ASSERT(sub.nodes.size() > 1); // FIXME this is a pretty bad hack. Geometries should obtained directly // from map_matching. // run shortest path routing to obtain geometry InternalRouteResult raw_route; PhantomNodes current_phantom_node_pair; for (unsigned i = 0; i < sub.nodes.size() - 1; ++i) { current_phantom_node_pair.source_phantom = sub.nodes[i]; current_phantom_node_pair.target_phantom = sub.nodes[i + 1]; raw_route.segment_end_coordinates.emplace_back(current_phantom_node_pair); } search_engine_ptr->shortest_path( raw_route.segment_end_coordinates, std::vector<bool>(raw_route.segment_end_coordinates.size(), true), raw_route); DescriptorConfig descriptor_config; auto iter = descriptor_table.find(route_parameters.output_format); unsigned descriptor_type = (iter != descriptor_table.end() ? iter->second : 0); descriptor_config.zoom_level = route_parameters.zoom_level; descriptor_config.instructions = false; descriptor_config.geometry = route_parameters.geometry; descriptor_config.encode_geometry = route_parameters.compression; std::shared_ptr<BaseDescriptor<DataFacadeT>> descriptor; switch (descriptor_type) { // case 0: // descriptor = std::make_shared<JSONDescriptor<DataFacadeT>>(); // break; case 1: descriptor = std::make_shared<GPXDescriptor<DataFacadeT>>(facade); break; // case 2: // descriptor = std::make_shared<GEOJSONDescriptor<DataFacadeT>>(); // break; default: descriptor = std::make_shared<JSONDescriptor<DataFacadeT>>(facade); break; } osrm::json::Object temp_result; descriptor->SetConfig(descriptor_config); descriptor->Run(raw_route, temp_result); osrm::json::Array indices; for (const auto& i : sub.indices) { indices.values.emplace_back(i); } osrm::json::Object subtrace; subtrace.values["geometry"] = temp_result.values["route_geometry"]; subtrace.values["confidence"] = sub.confidence; subtrace.values["indices"] = indices; subtrace.values["matched_points"] = temp_result.values["via_points"]; matchings.values.push_back(subtrace); } json_result.values["debug"] = debug_info; json_result.values["matchings"] = matchings; return 200; } private: std::string descriptor_string; DataFacadeT *facade; ClassifierT classifier; }; #endif /* MAP_MATCHING_HPP */
/* Copyright (c) 2015, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 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 MAP_MATCHING_PLUGIN_HPP #define MAP_MATCHING_PLUGIN_HPP #include "plugin_base.hpp" #include "../algorithms/bayes_classifier.hpp" #include "../algorithms/object_encoder.hpp" #include "../data_structures/search_engine.hpp" #include "../descriptors/descriptor_base.hpp" #include "../descriptors/gpx_descriptor.hpp" #include "../descriptors/json_descriptor.hpp" #include "../routing_algorithms/map_matching.hpp" #include "../util/compute_angle.hpp" #include "../util/integer_range.hpp" #include "../util/simple_logger.hpp" #include "../util/string_util.hpp" #include <cstdlib> #include <algorithm> #include <memory> #include <string> #include <vector> template <class DataFacadeT> class MapMatchingPlugin : public BasePlugin { private: std::unordered_map<std::string, unsigned> descriptor_table; std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr; using ClassifierT = BayesClassifier<LaplaceDistribution, LaplaceDistribution, double>; using TraceClassification = ClassifierT::ClassificationT; public: MapMatchingPlugin(DataFacadeT *facade) : descriptor_string("match") , facade(facade) // the values where derived from fitting a laplace distribution // to the values of manually classified traces , classifier(LaplaceDistribution(0.0057154021891018675, 0.020294704891166186), LaplaceDistribution(0.11467696742821254, 0.49918444000368756), 0.7977883096366508) // valid apriori probability { descriptor_table.emplace("json", 0); search_engine_ptr = std::make_shared<SearchEngine<DataFacadeT>>(facade); } virtual ~MapMatchingPlugin() { } const std::string GetDescriptor() const final { return descriptor_string; } TraceClassification classify(float trace_length, float matched_length, int removed_points) const { double distance_feature = -std::log(trace_length) + std::log(matched_length); // matched to the same point if (!std::isfinite(distance_feature)) { return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0); } auto label_with_confidence = classifier.classify(distance_feature); // "second stage classifier": if we need to remove points there is something fishy if (removed_points > 0) { return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0); } return label_with_confidence; } bool get_candiates(const std::vector<FixedPointCoordinate>& input_coords, std::vector<double>& sub_trace_lengths, Matching::CandidateLists& candidates_lists) { double last_distance = coordinate_calculation::great_circle_distance( input_coords[0], input_coords[1]); sub_trace_lengths.resize(input_coords.size()); sub_trace_lengths[0] = 0; for (const auto current_coordinate : osrm::irange<std::size_t>(0, input_coords.size())) { bool allow_uturn = false; if (0 < current_coordinate) { last_distance = coordinate_calculation::great_circle_distance( input_coords[current_coordinate - 1], input_coords[current_coordinate]); sub_trace_lengths[current_coordinate] += sub_trace_lengths[current_coordinate-1] + last_distance; } if (input_coords.size()-1 > current_coordinate && 0 < current_coordinate) { double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates( input_coords[current_coordinate-1], input_coords[current_coordinate], input_coords[current_coordinate+1]); // sharp turns indicate a possible uturn if (turn_angle < 100.0 || turn_angle > 260.0) { allow_uturn = true; } } std::vector<std::pair<PhantomNode, double>> candidates; if (!facade->IncrementalFindPhantomNodeForCoordinateWithMaxDistance( input_coords[current_coordinate], candidates, last_distance/2.0, 5, Matching::max_number_of_candidates)) { return false; } if (allow_uturn) { candidates_lists.push_back(candidates); } else { unsigned compact_size = candidates.size(); for (const auto i : osrm::irange(0u, compact_size)) { // Split edge if it is bidirectional and append reverse direction to end of list if (candidates[i].first.forward_node_id != SPECIAL_NODEID && candidates[i].first.reverse_node_id != SPECIAL_NODEID) { PhantomNode reverse_node(candidates[i].first); reverse_node.forward_node_id = SPECIAL_NODEID; candidates.push_back(std::make_pair(reverse_node, candidates[i].second)); candidates[i].first.reverse_node_id = SPECIAL_NODEID; } } candidates_lists.push_back(candidates); } } return true; } int HandleRequest(const RouteParameters &route_parameters, osrm::json::Object &json_result) final { // check number of parameters if (!check_all_coordinates(route_parameters.coordinates)) { return 400; } std::vector<double> sub_trace_lengths; Matching::CandidateLists candidates_lists; const auto& input_coords = route_parameters.coordinates; const auto& input_timestamps = route_parameters.timestamps; if (input_timestamps.size() > 0 && input_coords.size() != input_timestamps.size()) { return 400; } bool found_candidates = get_candiates(input_coords, sub_trace_lengths, candidates_lists); if (!found_candidates) { return 400; } // call the actual map matching osrm::json::Object debug_info; Matching::SubMatchingList sub_matchings; search_engine_ptr->map_matching(candidates_lists, input_coords, input_timestamps, sub_matchings, debug_info); if (1 > sub_matchings.size()) { return 400; } osrm::json::Array matchings; for (auto& sub : sub_matchings) { // classify result double trace_length = sub_trace_lengths[sub.indices.back()] - sub_trace_lengths[sub.indices.front()]; TraceClassification classification = classify(trace_length, sub.length, (sub.indices.back() - sub.indices.front() + 1) - sub.nodes.size()); if (classification.first == ClassifierT::ClassLabel::POSITIVE) { sub.confidence = classification.second; } else { sub.confidence = 1-classification.second; } BOOST_ASSERT(sub.nodes.size() > 1); // FIXME this is a pretty bad hack. Geometries should obtained directly // from map_matching. // run shortest path routing to obtain geometry InternalRouteResult raw_route; PhantomNodes current_phantom_node_pair; for (unsigned i = 0; i < sub.nodes.size() - 1; ++i) { current_phantom_node_pair.source_phantom = sub.nodes[i]; current_phantom_node_pair.target_phantom = sub.nodes[i + 1]; raw_route.segment_end_coordinates.emplace_back(current_phantom_node_pair); } search_engine_ptr->shortest_path( raw_route.segment_end_coordinates, std::vector<bool>(raw_route.segment_end_coordinates.size(), true), raw_route); DescriptorConfig descriptor_config; auto iter = descriptor_table.find(route_parameters.output_format); unsigned descriptor_type = (iter != descriptor_table.end() ? iter->second : 0); descriptor_config.zoom_level = route_parameters.zoom_level; descriptor_config.instructions = false; descriptor_config.geometry = route_parameters.geometry; descriptor_config.encode_geometry = route_parameters.compression; std::shared_ptr<BaseDescriptor<DataFacadeT>> descriptor; switch (descriptor_type) { // case 0: // descriptor = std::make_shared<JSONDescriptor<DataFacadeT>>(); // break; case 1: descriptor = std::make_shared<GPXDescriptor<DataFacadeT>>(facade); break; // case 2: // descriptor = std::make_shared<GEOJSONDescriptor<DataFacadeT>>(); // break; default: descriptor = std::make_shared<JSONDescriptor<DataFacadeT>>(facade); break; } osrm::json::Object temp_result; descriptor->SetConfig(descriptor_config); descriptor->Run(raw_route, temp_result); osrm::json::Array indices; for (const auto& i : sub.indices) { indices.values.emplace_back(i); } osrm::json::Object subtrace; subtrace.values["geometry"] = temp_result.values["route_geometry"]; subtrace.values["confidence"] = sub.confidence; subtrace.values["indices"] = indices; subtrace.values["matched_points"] = temp_result.values["via_points"]; matchings.values.push_back(subtrace); } json_result.values["debug"] = debug_info; json_result.values["matchings"] = matchings; return 200; } private: std::string descriptor_string; DataFacadeT *facade; ClassifierT classifier; }; #endif /* MAP_MATCHING_HPP */
Fix include guard
Fix include guard
C++
bsd-2-clause
deniskoronchik/osrm-backend,Tristramg/osrm-backend,beemogmbh/osrm-backend,hydrays/osrm-backend,prembasumatary/osrm-backend,Tristramg/osrm-backend,KnockSoftware/osrm-backend,nagyistoce/osrm-backend,bitsteller/osrm-backend,bjtaylor1/osrm-backend,yuryleb/osrm-backend,neilbu/osrm-backend,Project-OSRM/osrm-backend,skyborla/osrm-backend,Conggge/osrm-backend,bjtaylor1/osrm-backend,prembasumatary/osrm-backend,jpizarrom/osrm-backend,yuryleb/osrm-backend,yuryleb/osrm-backend,Project-OSRM/osrm-backend,prembasumatary/osrm-backend,jpizarrom/osrm-backend,oxidase/osrm-backend,nagyistoce/osrm-backend,bitsteller/osrm-backend,Project-OSRM/osrm-backend,tkhaxton/osrm-backend,duizendnegen/osrm-backend,atsuyim/osrm-backend,deniskoronchik/osrm-backend,alex85k/Project-OSRM,neilbu/osrm-backend,raymond0/osrm-backend,ammeurer/osrm-backend,agruss/osrm-backend,hydrays/osrm-backend,ammeurer/osrm-backend,tkhaxton/osrm-backend,ammeurer/osrm-backend,agruss/osrm-backend,ammeurer/osrm-backend,skyborla/osrm-backend,oxidase/osrm-backend,felixguendling/osrm-backend,frodrigo/osrm-backend,atsuyim/osrm-backend,chaupow/osrm-backend,arnekaiser/osrm-backend,deniskoronchik/osrm-backend,hydrays/osrm-backend,oxidase/osrm-backend,raymond0/osrm-backend,frodrigo/osrm-backend,frodrigo/osrm-backend,alex85k/Project-OSRM,skyborla/osrm-backend,neilbu/osrm-backend,antoinegiret/osrm-geovelo,agruss/osrm-backend,chaupow/osrm-backend,beemogmbh/osrm-backend,bjtaylor1/osrm-backend,KnockSoftware/osrm-backend,alex85k/Project-OSRM,deniskoronchik/osrm-backend,Tristramg/osrm-backend,yuryleb/osrm-backend,tkhaxton/osrm-backend,oxidase/osrm-backend,felixguendling/osrm-backend,ammeurer/osrm-backend,ammeurer/osrm-backend,arnekaiser/osrm-backend,raymond0/osrm-backend,antoinegiret/osrm-geovelo,beemogmbh/osrm-backend,hydrays/osrm-backend,beemogmbh/osrm-backend,neilbu/osrm-backend,duizendnegen/osrm-backend,ammeurer/osrm-backend,raymond0/osrm-backend,bitsteller/osrm-backend,antoinegiret/osrm-geovelo,chaupow/osrm-backend,Project-OSRM/osrm-backend,arnekaiser/osrm-backend,felixguendling/osrm-backend,Conggge/osrm-backend,frodrigo/osrm-backend,KnockSoftware/osrm-backend,Conggge/osrm-backend,duizendnegen/osrm-backend,arnekaiser/osrm-backend,atsuyim/osrm-backend,duizendnegen/osrm-backend,nagyistoce/osrm-backend,ramyaragupathy/osrm-backend,bjtaylor1/osrm-backend,KnockSoftware/osrm-backend,ramyaragupathy/osrm-backend,Conggge/osrm-backend,jpizarrom/osrm-backend,ramyaragupathy/osrm-backend
430c4a730a1c0e3ebf73059b5e28fb56a00ccdfd
src/arch/arm/miscregs.hh
src/arch/arm/miscregs.hh
/* * Copyright (c) 2010 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2009 The Regents of The University of Michigan * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __ARCH_ARM_MISCREGS_HH__ #define __ARCH_ARM_MISCREGS_HH__ #include "base/bitunion.hh" namespace ArmISA { enum ConditionCode { COND_EQ = 0, COND_NE, // 1 COND_CS, // 2 COND_CC, // 3 COND_MI, // 4 COND_PL, // 5 COND_VS, // 6 COND_VC, // 7 COND_HI, // 8 COND_LS, // 9 COND_GE, // 10 COND_LT, // 11 COND_GT, // 12 COND_LE, // 13 COND_AL, // 14 COND_UC // 15 }; enum MiscRegIndex { MISCREG_CPSR = 0, MISCREG_SPSR, MISCREG_SPSR_FIQ, MISCREG_SPSR_IRQ, MISCREG_SPSR_SVC, MISCREG_SPSR_MON, MISCREG_SPSR_UND, MISCREG_SPSR_ABT, MISCREG_FPSR, MISCREG_FPSID, MISCREG_FPSCR, MISCREG_FPEXC, MISCREG_MVFR0, MISCREG_MVFR1, MISCREG_SEV_MAILBOX, // CP15 registers MISCREG_CP15_START, MISCREG_SCTLR = MISCREG_CP15_START, MISCREG_DCCISW, MISCREG_DCCIMVAC, MISCREG_DCCMVAC, MISCREG_CONTEXTIDR, MISCREG_TPIDRURW, MISCREG_TPIDRURO, MISCREG_TPIDRPRW, MISCREG_CP15ISB, MISCREG_CP15DSB, MISCREG_CP15DMB, MISCREG_CPACR, MISCREG_CLIDR, MISCREG_CCSIDR, MISCREG_CSSELR, MISCREG_ICIALLUIS, MISCREG_ICIALLU, MISCREG_ICIMVAU, MISCREG_BPIMVA, MISCREG_BPIALLIS, MISCREG_BPIALL, MISCREG_MIDR, MISCREG_TTBR0, MISCREG_TTBR1, MISCREG_TLBTR, MISCREG_DACR, MISCREG_TLBIALLIS, MISCREG_TLBIMVAIS, MISCREG_TLBIASIDIS, MISCREG_TLBIMVAAIS, MISCREG_ITLBIALL, MISCREG_ITLBIMVA, MISCREG_ITLBIASID, MISCREG_DTLBIALL, MISCREG_DTLBIMVA, MISCREG_DTLBIASID, MISCREG_TLBIALL, MISCREG_TLBIMVA, MISCREG_TLBIASID, MISCREG_TLBIMVAA, MISCREG_CP15_UNIMP_START, MISCREG_CTR = MISCREG_CP15_UNIMP_START, MISCREG_TCMTR, MISCREG_MPIDR, MISCREG_ID_PFR0, MISCREG_ID_PFR1, MISCREG_ID_DFR0, MISCREG_ID_AFR0, MISCREG_ID_MMFR0, MISCREG_ID_MMFR1, MISCREG_ID_MMFR2, MISCREG_ID_MMFR3, MISCREG_ID_ISAR0, MISCREG_ID_ISAR1, MISCREG_ID_ISAR2, MISCREG_ID_ISAR3, MISCREG_ID_ISAR4, MISCREG_ID_ISAR5, MISCREG_PAR, MISCREG_AIDR, MISCREG_ACTLR, MISCREG_DFSR, MISCREG_IFSR, MISCREG_ADFSR, MISCREG_AIFSR, MISCREG_DFAR, MISCREG_IFAR, MISCREG_DCIMVAC, MISCREG_DCISW, MISCREG_MCCSW, MISCREG_DCCMVAU, MISCREG_SCR, MISCREG_SDER, MISCREG_NSACR, MISCREG_TTBCR, MISCREG_V2PCWPR, MISCREG_V2PCWPW, MISCREG_V2PCWUR, MISCREG_V2PCWUW, MISCREG_V2POWPR, MISCREG_V2POWPW, MISCREG_V2POWUR, MISCREG_V2POWUW, MISCREG_PRRR, MISCREG_NMRR, MISCREG_VBAR, MISCREG_MVBAR, MISCREG_ISR, MISCREG_FCEIDR, MISCREG_CP15_END, // Dummy indices MISCREG_NOP = MISCREG_CP15_END, MISCREG_RAZ, NUM_MISCREGS }; MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1, unsigned crm, unsigned opc2); const char * const miscRegName[NUM_MISCREGS] = { "cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc", "spsr_mon", "spsr_und", "spsr_abt", "fpsr", "fpsid", "fpscr", "fpexc", "mvfr0", "mvfr1", "sev_mailbox", "sctlr", "dccisw", "dccimvac", "dccmvac", "contextidr", "tpidrurw", "tpidruro", "tpidrprw", "cp15isb", "cp15dsb", "cp15dmb", "cpacr", "clidr", "ccsidr", "csselr", "icialluis", "iciallu", "icimvau", "bpimva", "bpiallis", "bpiall", "midr", "ttbr0", "ttbr1", "tlbtr", "dacr", "tlbiallis", "tlbimvais", "tlbiasidis", "tlbimvaais", "itlbiall", "itlbimva", "itlbiasid", "dtlbiall", "dtlbimva", "dtlbiasid", "tlbiall", "tlbimva", "tlbiasid", "tlbimvaa", "ctr", "tcmtr", "mpidr", "id_pfr0", "id_pfr1", "id_dfr0", "id_afr0", "id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3", "id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5", "par", "aidr", "actlr", "dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar", "dcimvac", "dcisw", "mccsw", "dccmvau", "scr", "sder", "nsacr", "ttbcr", "v2pcwpr", "v2pcwpw", "v2pcwur", "v2pcwuw", "v2powpr", "v2powpw", "v2powur", "v2powuw", "prrr", "nmrr", "vbar", "mvbar", "isr", "fceidr", "nop", "raz" }; BitUnion32(CPSR) Bitfield<31> n; Bitfield<30> z; Bitfield<29> c; Bitfield<28> v; Bitfield<27> q; Bitfield<26,25> it1; Bitfield<24> j; Bitfield<19, 16> ge; Bitfield<15,10> it2; Bitfield<9> e; Bitfield<8> a; Bitfield<7> i; Bitfield<6> f; Bitfield<5> t; Bitfield<4, 0> mode; EndBitUnion(CPSR) // This mask selects bits of the CPSR that actually go in the CondCodes // integer register to allow renaming. static const uint32_t CondCodesMask = 0xF80F0000; BitUnion32(SCTLR) Bitfield<30> te; // Thumb Exception Enable Bitfield<29> afe; // Access flag enable Bitfield<28> tre; // TEX Remap bit Bitfield<27> nmfi;// Non-maskable fast interrupts enable Bitfield<25> ee; // Exception Endianness bit Bitfield<24> ve; // Interrupt vectors enable Bitfield<23> rao1;// Read as one Bitfield<22> u; // Alignment (now unused) Bitfield<21> fi; // Fast interrupts configuration enable Bitfield<18> rao2;// Read as one Bitfield<17> ha; // Hardware access flag enable Bitfield<16> rao3;// Read as one Bitfield<14> rr; // Round robin cache replacement Bitfield<13> v; // Base address for exception vectors Bitfield<12> i; // instruction cache enable Bitfield<11> z; // branch prediction enable bit Bitfield<10> sw; // Enable swp/swpb Bitfield<6,3> rao4;// Read as one Bitfield<7> b; // Endianness support (unused) Bitfield<2> c; // Cache enable bit Bitfield<1> a; // Alignment fault checking Bitfield<0> m; // MMU enable bit EndBitUnion(SCTLR) BitUnion32(CPACR) Bitfield<1, 0> cp0; Bitfield<3, 2> cp1; Bitfield<5, 4> cp2; Bitfield<7, 6> cp3; Bitfield<9, 8> cp4; Bitfield<11, 10> cp5; Bitfield<13, 12> cp6; Bitfield<15, 14> cp7; Bitfield<17, 16> cp8; Bitfield<19, 18> cp9; Bitfield<21, 20> cp10; Bitfield<23, 22> cp11; Bitfield<25, 24> cp12; Bitfield<27, 26> cp13; Bitfield<30> d32dis; Bitfield<31> asedis; EndBitUnion(CPACR) }; #endif // __ARCH_ARM_MISCREGS_HH__
/* * Copyright (c) 2010 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2009 The Regents of The University of Michigan * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __ARCH_ARM_MISCREGS_HH__ #define __ARCH_ARM_MISCREGS_HH__ #include "base/bitunion.hh" namespace ArmISA { enum ConditionCode { COND_EQ = 0, COND_NE, // 1 COND_CS, // 2 COND_CC, // 3 COND_MI, // 4 COND_PL, // 5 COND_VS, // 6 COND_VC, // 7 COND_HI, // 8 COND_LS, // 9 COND_GE, // 10 COND_LT, // 11 COND_GT, // 12 COND_LE, // 13 COND_AL, // 14 COND_UC // 15 }; enum MiscRegIndex { MISCREG_CPSR = 0, MISCREG_SPSR, MISCREG_SPSR_FIQ, MISCREG_SPSR_IRQ, MISCREG_SPSR_SVC, MISCREG_SPSR_MON, MISCREG_SPSR_UND, MISCREG_SPSR_ABT, MISCREG_FPSR, MISCREG_FPSID, MISCREG_FPSCR, MISCREG_FPEXC, MISCREG_MVFR0, MISCREG_MVFR1, MISCREG_SEV_MAILBOX, // CP15 registers MISCREG_CP15_START, MISCREG_SCTLR = MISCREG_CP15_START, MISCREG_DCCISW, MISCREG_DCCIMVAC, MISCREG_DCCMVAC, MISCREG_CONTEXTIDR, MISCREG_TPIDRURW, MISCREG_TPIDRURO, MISCREG_TPIDRPRW, MISCREG_CP15ISB, MISCREG_CP15DSB, MISCREG_CP15DMB, MISCREG_CPACR, MISCREG_CLIDR, MISCREG_CCSIDR, MISCREG_CSSELR, MISCREG_ICIALLUIS, MISCREG_ICIALLU, MISCREG_ICIMVAU, MISCREG_BPIMVA, MISCREG_BPIALLIS, MISCREG_BPIALL, MISCREG_MIDR, MISCREG_TTBR0, MISCREG_TTBR1, MISCREG_TLBTR, MISCREG_DACR, MISCREG_TLBIALLIS, MISCREG_TLBIMVAIS, MISCREG_TLBIASIDIS, MISCREG_TLBIMVAAIS, MISCREG_ITLBIALL, MISCREG_ITLBIMVA, MISCREG_ITLBIASID, MISCREG_DTLBIALL, MISCREG_DTLBIMVA, MISCREG_DTLBIASID, MISCREG_TLBIALL, MISCREG_TLBIMVA, MISCREG_TLBIASID, MISCREG_TLBIMVAA, MISCREG_CP15_UNIMP_START, MISCREG_CTR = MISCREG_CP15_UNIMP_START, MISCREG_TCMTR, MISCREG_MPIDR, MISCREG_ID_PFR0, MISCREG_ID_PFR1, MISCREG_ID_DFR0, MISCREG_ID_AFR0, MISCREG_ID_MMFR0, MISCREG_ID_MMFR1, MISCREG_ID_MMFR2, MISCREG_ID_MMFR3, MISCREG_ID_ISAR0, MISCREG_ID_ISAR1, MISCREG_ID_ISAR2, MISCREG_ID_ISAR3, MISCREG_ID_ISAR4, MISCREG_ID_ISAR5, MISCREG_PAR, MISCREG_AIDR, MISCREG_ACTLR, MISCREG_DFSR, MISCREG_IFSR, MISCREG_ADFSR, MISCREG_AIFSR, MISCREG_DFAR, MISCREG_IFAR, MISCREG_DCIMVAC, MISCREG_DCISW, MISCREG_MCCSW, MISCREG_DCCMVAU, MISCREG_SCR, MISCREG_SDER, MISCREG_NSACR, MISCREG_TTBCR, MISCREG_V2PCWPR, MISCREG_V2PCWPW, MISCREG_V2PCWUR, MISCREG_V2PCWUW, MISCREG_V2POWPR, MISCREG_V2POWPW, MISCREG_V2POWUR, MISCREG_V2POWUW, MISCREG_PRRR, MISCREG_NMRR, MISCREG_VBAR, MISCREG_MVBAR, MISCREG_ISR, MISCREG_FCEIDR, MISCREG_CP15_END, // Dummy indices MISCREG_NOP = MISCREG_CP15_END, MISCREG_RAZ, NUM_MISCREGS }; MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1, unsigned crm, unsigned opc2); const char * const miscRegName[NUM_MISCREGS] = { "cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc", "spsr_mon", "spsr_und", "spsr_abt", "fpsr", "fpsid", "fpscr", "fpexc", "mvfr0", "mvfr1", "sev_mailbox", "sctlr", "dccisw", "dccimvac", "dccmvac", "contextidr", "tpidrurw", "tpidruro", "tpidrprw", "cp15isb", "cp15dsb", "cp15dmb", "cpacr", "clidr", "ccsidr", "csselr", "icialluis", "iciallu", "icimvau", "bpimva", "bpiallis", "bpiall", "midr", "ttbr0", "ttbr1", "tlbtr", "dacr", "tlbiallis", "tlbimvais", "tlbiasidis", "tlbimvaais", "itlbiall", "itlbimva", "itlbiasid", "dtlbiall", "dtlbimva", "dtlbiasid", "tlbiall", "tlbimva", "tlbiasid", "tlbimvaa", "ctr", "tcmtr", "mpidr", "id_pfr0", "id_pfr1", "id_dfr0", "id_afr0", "id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3", "id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5", "par", "aidr", "actlr", "dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar", "dcimvac", "dcisw", "mccsw", "dccmvau", "scr", "sder", "nsacr", "ttbcr", "v2pcwpr", "v2pcwpw", "v2pcwur", "v2pcwuw", "v2powpr", "v2powpw", "v2powur", "v2powuw", "prrr", "nmrr", "vbar", "mvbar", "isr", "fceidr", "nop", "raz" }; BitUnion32(CPSR) Bitfield<31> n; Bitfield<30> z; Bitfield<29> c; Bitfield<28> v; Bitfield<27> q; Bitfield<26,25> it1; Bitfield<24> j; Bitfield<19, 16> ge; Bitfield<15,10> it2; Bitfield<9> e; Bitfield<8> a; Bitfield<7> i; Bitfield<6> f; Bitfield<5> t; Bitfield<4, 0> mode; EndBitUnion(CPSR) // This mask selects bits of the CPSR that actually go in the CondCodes // integer register to allow renaming. static const uint32_t CondCodesMask = 0xF80F0000; BitUnion32(SCTLR) Bitfield<31> ie; // Instruction endianness Bitfield<30> te; // Thumb Exception Enable Bitfield<29> afe; // Access flag enable Bitfield<28> tre; // TEX Remap bit Bitfield<27> nmfi;// Non-maskable fast interrupts enable Bitfield<25> ee; // Exception Endianness bit Bitfield<24> ve; // Interrupt vectors enable Bitfield<23> rao1;// Read as one Bitfield<22> u; // Alignment (now unused) Bitfield<21> fi; // Fast interrupts configuration enable Bitfield<19> dz; // Divide by Zero fault enable bit Bitfield<18> rao2;// Read as one Bitfield<17> br; // Background region bit Bitfield<16> rao3;// Read as one Bitfield<14> rr; // Round robin cache replacement Bitfield<13> v; // Base address for exception vectors Bitfield<12> i; // instruction cache enable Bitfield<11> z; // branch prediction enable bit Bitfield<10> sw; // Enable swp/swpb Bitfield<6,3> rao4;// Read as one Bitfield<7> b; // Endianness support (unused) Bitfield<2> c; // Cache enable bit Bitfield<1> a; // Alignment fault checking Bitfield<0> m; // MMU enable bit EndBitUnion(SCTLR) BitUnion32(CPACR) Bitfield<1, 0> cp0; Bitfield<3, 2> cp1; Bitfield<5, 4> cp2; Bitfield<7, 6> cp3; Bitfield<9, 8> cp4; Bitfield<11, 10> cp5; Bitfield<13, 12> cp6; Bitfield<15, 14> cp7; Bitfield<17, 16> cp8; Bitfield<19, 18> cp9; Bitfield<21, 20> cp10; Bitfield<23, 22> cp11; Bitfield<25, 24> cp12; Bitfield<27, 26> cp13; Bitfield<30> d32dis; Bitfield<31> asedis; EndBitUnion(CPACR) }; #endif // __ARCH_ARM_MISCREGS_HH__
Add in some missing SCTLR fields.
ARM: Add in some missing SCTLR fields.
C++
bsd-3-clause
haowu4682/gem5,LingxiaoJIA/gem5,haowu4682/gem5,haowu4682/gem5,LingxiaoJIA/gem5,haowu4682/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,haowu4682/gem5,haowu4682/gem5,LingxiaoJIA/gem5,haowu4682/gem5,haowu4682/gem5,haowu4682/gem5
fc740a3e7ec90829c142f5a7a9f409b5c849cd00
examples/demo_retrieve_images.cpp
examples/demo_retrieve_images.cpp
// Copyright 2014 kloudkl@github // // This program takes in a trained network and an input blob, and then // extract features of the input blobs produced by the net to retrieve similar images. // Usage: // retrieve_image pretrained_net_param input_blob output_filename top_k_results [CPU/GPU] [DEVICE_ID=0] #include <stdio.h> // for snprintf #include <fstream> // for std::ofstream #include <queue> // for std::priority_queue #include <cuda_runtime.h> #include <google/protobuf/text_format.h> #include <leveldb/db.h> #include <leveldb/write_batch.h> #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/vision_layers.hpp" #include "caffe/net.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/io.hpp" #include "caffe/util/math_functions.hpp" using namespace caffe; template<typename Dtype> inline int sign(const Dtype val) { return (Dtype(0) < val) - (val < Dtype(0)); } template<typename Dtype> void binarize(const int n, const Dtype* real_valued_feature, Dtype* binary_code); template<typename Dtype> void binarize(const shared_ptr<Blob<Dtype> > real_valued_features, shared_ptr<Blob<Dtype> > binary_codes); template<typename Dtype> void similarity_search(const shared_ptr<Blob<Dtype> > sample_images_feature, const shared_ptr<Blob<Dtype> > query_image_feature, const int top_k_results, shared_ptr<Blob<Dtype> > retrieval_results); template<typename Dtype> int image_retrieval_pipeline(int argc, char** argv); int main(int argc, char** argv) { return image_retrieval_pipeline<float>(argc, argv); // return image_retrieval_pipeline<double>(argc, argv); } template<typename Dtype> int image_retrieval_pipeline(int argc, char** argv) { const int num_required_args = 7; if (argc < num_required_args) { LOG(ERROR)<< "retrieve_image pretrained_net_param extract__feature_blob_name" " sample_images_feature_blob_binaryproto data_prototxt data_layer_name" " save_feature_leveldb_name save_retrieval_result_filename" " [top_k_results=1] [CPU/GPU] [DEVICE_ID=0]"; return 1; } int arg_pos = num_required_args; int top_k_results; if (argc <= num_required_args) { top_k_results = 1; } else { top_k_results = atoi(argv[arg_pos]); CHECK_GE(top_k_results, 0); } arg_pos = num_required_args + 1; if (argc > arg_pos && strcmp(argv[arg_pos], "GPU") == 0) { LOG(ERROR)<< "Using GPU"; uint device_id = 0; if (argc > arg_pos) { device_id = atoi(argv[arg_pos]); } LOG(ERROR) << "Using Device_id=" << device_id; Caffe::SetDevice(device_id); Caffe::set_mode(Caffe::GPU); } else { LOG(ERROR) << "Using CPU"; Caffe::set_mode(Caffe::CPU); } Caffe::set_phase(Caffe::TEST); NetParameter pretrained_net_param; arg_pos = 0; // the name of the executable // We directly load the net param from trained file string pretrained_binary_proto(argv[++arg_pos]); ReadProtoFromBinaryFile(pretrained_binary_proto.c_str(), &pretrained_net_param); shared_ptr<Net<Dtype> > feature_extraction_net( new Net<Dtype>(pretrained_net_param)); string extract_feature_blob_name(argv[++arg_pos]); if (!feature_extraction_net->HasBlob(extract_feature_blob_name)) { LOG(ERROR)<< "Unknown feature blob name " << extract_feature_blob_name << " in trained network " << pretrained_binary_proto; return 1; } string sample_images_feature_blob_binaryproto(argv[++arg_pos]); BlobProto sample_images_feature_blob_proto; ReadProtoFromBinaryFile(argv[++arg_pos], &sample_images_feature_blob_proto); shared_ptr<Blob<Dtype> > sample_images_feature_blob(new Blob<Dtype>()); sample_images_feature_blob->FromProto(sample_images_feature_blob_proto); // Expected prototxt contains at least one data layer as the query images. /* layers { layer { name: "query_images" type: "data" source: "/path/to/your/images/to/extract/feature/and/retrieve/similar/images_leveldb" meanfile: "/path/to/your/image_mean.binaryproto" batchsize: 128 cropsize: 115 mirror: false } top: "query_images" top: "ground_truth_labels" // TODO: Add MultiLabelDataLayer support for image retrieval, annotations etc. } */ string data_prototxt(argv[++arg_pos]); string data_layer_name(argv[++arg_pos]); NetParameter data_net_param; ReadProtoFromTextFile(data_prototxt.c_str(), &data_net_param); LayerParameter data_layer_param; int num_layer; for (num_layer = 0; num_layer < data_net_param.layers_size(); ++num_layer) { if (data_layer_name == data_net_param.layers(num_layer).layer().name()) { data_layer_param = data_net_param.layers(num_layer).layer(); break; } } if (num_layer = data_net_param.layers_size()) { LOG(ERROR) << "Unknow data layer name " << data_layer_name << " in prototxt " << data_prototxt; } string save_feature_leveldb_name(argv[++arg_pos]); leveldb::DB* db; leveldb::Options options; options.error_if_exists = true; options.create_if_missing = true; options.write_buffer_size = 268435456; LOG(INFO) << "Opening leveldb " << argv[3]; leveldb::Status status = leveldb::DB::Open( options, save_feature_leveldb_name.c_str(), &db); CHECK(status.ok()) << "Failed to open leveldb " << save_feature_leveldb_name; string save_retrieval_result_filename(argv[++arg_pos]); std::ofstream retrieval_result_ofs(save_retrieval_result_filename.c_str(), std::ofstream::out); LOG(ERROR)<< "Extacting Features and retrieving images"; DataLayer<Dtype> data_layer(data_layer_param); vector<Blob<Dtype>*> bottom_vec_that_data_layer_does_not_need_; vector<Blob<Dtype>*> top_vec; data_layer.Forward(bottom_vec_that_data_layer_does_not_need_, &top_vec); int batch_index = 0; shared_ptr<Blob<Dtype> > feature_binary_codes; shared_ptr<Blob<Dtype> > retrieval_results; int query_image_index = 0; Datum datum; leveldb::WriteBatch* batch = new leveldb::WriteBatch(); const int max_key_str_length = 100; char key_str[max_key_str_length]; int num_bytes_of_binary_code = sizeof(Dtype); int count_query_images = 0; while (top_vec.size()) { // data_layer still outputs data LOG(ERROR)<< "Batch " << batch_index << " feature extraction"; feature_extraction_net->Forward(top_vec); const shared_ptr<Blob<Dtype> > feature_blob = feature_extraction_net->GetBlob(extract_feature_blob_name); feature_binary_codes.reset(new Blob<Dtype>()); binarize<Dtype>(feature_blob, feature_binary_codes); LOG(ERROR) << "Batch " << batch_index << " save extracted features"; const Dtype* retrieval_results_data = retrieval_results->cpu_data(); int num_features = feature_binary_codes->num(); int dim_features = feature_binary_codes->count() / num_features; for (int n = 0; n < num_features; ++n) { datum.set_height(dim_features); datum.set_width(1); datum.set_channels(1); datum.clear_data(); datum.clear_float_data(); string* datum_string = datum.mutable_data(); for (int d = 0; d < dim_features; ++d) { const Dtype data = feature_binary_codes->data_at(n, d, 0, 0); const char* data_byte = reinterpret_cast<const char*>(&data); for(int i = 0; i < num_bytes_of_binary_code; ++i) { datum_string->push_back(data_byte[i]); } } string value; datum.SerializeToString(&value); snprintf(key_str, max_key_str_length, "%d", query_image_index); batch->Put(string(key_str), value); if (++count_query_images % 1000 == 0) { db->Write(leveldb::WriteOptions(), batch); LOG(ERROR) << "Extracted features of " << count_query_images << " query images."; delete batch; batch = new leveldb::WriteBatch(); } } // write the last batch if (count_query_images % 1000 != 0) { db->Write(leveldb::WriteOptions(), batch); LOG(ERROR) << "Extracted features of " << count_query_images << " query images."; delete batch; batch = new leveldb::WriteBatch(); } LOG(ERROR) << "Batch " << batch_index << " image retrieval"; similarity_search<Dtype>(sample_images_feature_blob, feature_binary_codes, top_k_results, retrieval_results); LOG(ERROR) << "Batch " << batch_index << " save image retrieval results"; int num_results = retrieval_results->num(); int dim_results = retrieval_results->count() / num_results; for (int i = 0; i < num_results; ++i) { retrieval_result_ofs << query_image_index; for (int k = 0; k < dim_results; ++k) { retrieval_result_ofs << " " << retrieval_results->data_at(i, k, 0, 0); } retrieval_result_ofs << "\n"; } ++query_image_index; data_layer.Forward(bottom_vec_that_data_layer_does_not_need_, &top_vec); ++batch_index; } // while (top_vec.size()) { delete batch; delete db; retrieval_result_ofs.close(); LOG(ERROR)<< "Successfully ended!"; return 0; } template<typename Dtype> void binarize(const int n, const Dtype* real_valued_feature, Dtype* binary_codes) { // TODO: more advanced binarization algorithm such as bilinear projection // Yunchao Gong, Sanjiv Kumar, Henry A. Rowley, and Svetlana Lazebnik. // Learning Binary Codes for High-Dimensional Data Using Bilinear Projections. // In IEEE International Conference on Computer Vision and Pattern Recognition (CVPR), 2013. // http://www.unc.edu/~yunchao/bpbc.htm int size_of_code = sizeof(Dtype) * 8; CHECK_EQ(n % size_of_code, 0); int num_binary_codes = n / size_of_code; uint64_t code; int offset; for (int i = 0; i < num_binary_codes; ++i) { code = 0; offset = i * size_of_code; for (int j = 0; j < size_of_code; ++j) { code |= sign(real_valued_feature[offset + j]); code << 1; } binary_codes[i] = static_cast<Dtype>(code); } } template<typename Dtype> void binarize(const shared_ptr<Blob<Dtype> > real_valued_features, shared_ptr<Blob<Dtype> > binary_codes) { int num = real_valued_features->num(); int dim = real_valued_features->count() / num; int size_of_code = sizeof(Dtype) * 8; CHECK_EQ(dim % size_of_code, 0); binary_codes->Reshape(num, dim / size_of_code, 1, 1); const Dtype* real_valued_features_data = real_valued_features->cpu_data(); Dtype* binary_codes_data = binary_codes->mutable_cpu_data(); for (int n = 0; n < num; ++n) { binarize<Dtype>(dim, real_valued_features_data + real_valued_features->offset(n), binary_codes_data + binary_codes->offset(n)); } } class MinHeapComparison { public: bool operator()(const std::pair<int, int>& lhs, const std::pair<int, int>&rhs) const { return (lhs.first > rhs.first); } }; template<typename Dtype> void similarity_search(const shared_ptr<Blob<Dtype> > sample_images_feature, const shared_ptr<Blob<Dtype> > query_image_feature, const int top_k_results, shared_ptr<Blob<Dtype> > retrieval_results) { int num_samples = sample_images_feature->num(); int num_queries = query_image_feature->num(); int dim = query_image_feature->count() / num_queries; retrieval_results->Reshape(num_queries, std::min(num_samples, top_k_results), 1, 1); Dtype* retrieval_results_data = retrieval_results->mutable_cpu_data(); int hamming_dist; for (int i = 0; i < num_queries; ++i) { std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int> >, MinHeapComparison> results; for (int j = 0; j < num_samples; ++j) { hamming_dist = caffe_hamming_distance( dim, query_image_feature->cpu_data() + query_image_feature->offset(i), sample_images_feature->cpu_data() + sample_images_feature->offset(j)); if (results.empty()) { results.push(std::make_pair(-hamming_dist, j)); } else if (-hamming_dist > results.top().first) { // smaller hamming dist results.push(std::make_pair(-hamming_dist, j)); if (results.size() > top_k_results) { results.pop(); } } } // for (int j = 0; j < num_samples; ++j) { retrieval_results_data += retrieval_results->offset(i); for (int k = 0; k < results.size(); ++k) { retrieval_results_data[k] = results.top().second; results.pop(); } } // for (int i = 0; i < num_queries; ++i) { }
// Copyright 2014 kloudkl@github #include <fstream> // for std::ofstream #include <queue> // for std::priority_queue #include <cuda_runtime.h> #include <google/protobuf/text_format.h> #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/vision_layers.hpp" #include "caffe/net.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/io.hpp" #include "caffe/util/math_functions.hpp" using namespace caffe; template<typename Dtype> void similarity_search( const vector<shared_ptr<Blob<Dtype> > >& sample_binary_feature_blobs, const shared_ptr<Blob<Dtype> > query_binary_feature, const int top_k_results, shared_ptr<Blob<Dtype> > retrieval_results); template<typename Dtype> int image_retrieval_pipeline(int argc, char** argv); int main(int argc, char** argv) { return image_retrieval_pipeline<float>(argc, argv); // return image_retrieval_pipeline<double>(argc, argv); } template<typename Dtype> int image_retrieval_pipeline(int argc, char** argv) { const int num_required_args = 4; if (argc < num_required_args) { LOG(ERROR)<< "This program takes in binarized features of query images and sample images" " extracted by Caffe to retrieve similar images." "Usage: demo_retrieve_images sample_binary_features_binaryproto_file" " query_binary_features_binaryproto_file save_retrieval_result_filename" " [top_k_results=1] [CPU/GPU] [DEVICE_ID=0]"; return 1; } int arg_pos = num_required_args; int top_k_results; if (argc <= num_required_args) { top_k_results = 1; } else { top_k_results = atoi(argv[arg_pos]); CHECK_GE(top_k_results, 0); } arg_pos = num_required_args + 1; if (argc > arg_pos && strcmp(argv[arg_pos], "GPU") == 0) { LOG(ERROR)<< "Using GPU"; uint device_id = 0; if (argc > arg_pos + 1) { device_id = atoi(argv[arg_pos + 1]); } LOG(ERROR) << "Using Device_id=" << device_id; Caffe::SetDevice(device_id); Caffe::set_mode(Caffe::GPU); } else { LOG(ERROR) << "Using CPU"; Caffe::set_mode(Caffe::CPU); } Caffe::set_phase(Caffe::TEST); NetParameter pretrained_net_param; arg_pos = 0; // the name of the executable string sample_binary_features_binaryproto_file(argv[++arg_pos]); BlobProtoVector sample_binary_features; ReadProtoFromBinaryFile(sample_binary_features_binaryproto_file, &sample_binary_features); vector<shared_ptr<Blob<Dtype> > > sample_binary_feature_blobs; int num_samples; for (int i = 0; i < sample_binary_features.blobs_size(); ++i) { shared_ptr<Blob<Dtype> > blob(new Blob<Dtype>()); blob->FromProto(sample_binary_features.blobs(i)); sample_binary_feature_blobs.push_back(blob); num_samples += blob->num(); } if (top_k_results > num_samples) { top_k_results = num_samples; } string query_images_feature_blob_binaryproto(argv[++arg_pos]); BlobProtoVector query_images_features; ReadProtoFromBinaryFile(query_images_feature_blob_binaryproto, &query_images_features); vector<shared_ptr<Blob<Dtype> > > query_binary_feature_blobs; for (int i = 0; i < sample_binary_features.blobs_size(); ++i) { shared_ptr<Blob<Dtype> > blob(new Blob<Dtype>()); blob->FromProto(query_images_features.blobs(i)); query_binary_feature_blobs.push_back(blob); } string save_retrieval_result_filename(argv[++arg_pos]); std::ofstream retrieval_result_ofs(save_retrieval_result_filename.c_str(), std::ofstream::out); LOG(ERROR)<< "Retrieving images"; shared_ptr<Blob<Dtype> > retrieval_results; int query_image_index = 0; int num_bytes_of_binary_code = sizeof(Dtype); int num_query_batches = query_binary_feature_blobs.size(); for (int batch_index = 0; batch_index < num_query_batches; ++batch_index) { LOG(ERROR)<< "Batch " << batch_index << " image retrieval"; similarity_search<Dtype>(sample_binary_feature_blobs, query_binary_feature_blobs[batch_index], top_k_results, retrieval_results); LOG(ERROR) << "Batch " << batch_index << " save image retrieval results"; int num_results = retrieval_results->num(); const Dtype* retrieval_results_data = retrieval_results->cpu_data(); for (int i = 0; i < num_results; ++i) { retrieval_result_ofs << ++query_image_index; retrieval_results_data += retrieval_results->offset(i); for (int j = 0; j < top_k_results; ++j) { retrieval_result_ofs << " " << retrieval_results_data[j]; } retrieval_result_ofs << "\n"; } } // for (int batch_index = 0; batch_index < num_query_batches; ++batch_index) { retrieval_result_ofs.close(); LOG(ERROR)<< "Successfully ended!"; return 0; } template<typename Dtype> void binarize(const int n, const Dtype* real_valued_feature, Dtype* binary_codes) { // TODO: more advanced binarization algorithm such as bilinear projection // Yunchao Gong, Sanjiv Kumar, Henry A. Rowley, and Svetlana Lazebnik. // Learning Binary Codes for High-Dimensional Data Using Bilinear Projections. // In IEEE International Conference on Computer Vision and Pattern Recognition (CVPR), 2013. // http://www.unc.edu/~yunchao/bpbc.htm int size_of_code = sizeof(Dtype) * 8; CHECK_EQ(n % size_of_code, 0); int num_binary_codes = n / size_of_code; uint64_t code; int offset; for (int i = 0; i < num_binary_codes; ++i) { code = 0; offset = i * size_of_code; for (int j = 0; j < size_of_code; ++j) { code |= sign(real_valued_feature[offset + j]); code << 1; } binary_codes[i] = static_cast<Dtype>(code); } } template<typename Dtype> void binarize(const shared_ptr<Blob<Dtype> > real_valued_features, shared_ptr<Blob<Dtype> > binary_codes) { int num = real_valued_features->num(); int dim = real_valued_features->count() / num; int size_of_code = sizeof(Dtype) * 8; CHECK_EQ(dim % size_of_code, 0); binary_codes->Reshape(num, dim / size_of_code, 1, 1); const Dtype* real_valued_features_data = real_valued_features->cpu_data(); Dtype* binary_codes_data = binary_codes->mutable_cpu_data(); for (int n = 0; n < num; ++n) { binarize<Dtype>(dim, real_valued_features_data + real_valued_features->offset(n), binary_codes_data + binary_codes->offset(n)); } } class MinHeapComparison { public: bool operator()(const std::pair<int, int>& lhs, const std::pair<int, int>&rhs) const { return (lhs.first > rhs.first); } }; template<typename Dtype> void similarity_search( const vector<shared_ptr<Blob<Dtype> > >& sample_images_feature_blobs, const shared_ptr<Blob<Dtype> > query_image_feature, const int top_k_results, shared_ptr<Blob<Dtype> > retrieval_results) { int num_queries = query_image_feature->num(); int dim = query_image_feature->count() / num_queries; int hamming_dist; retrieval_results->Reshape(num_queries, top_k_results, 1, 1); Dtype* retrieval_results_data = retrieval_results->mutable_cpu_data(); for (int i = 0; i < num_queries; ++i) { std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int> >, MinHeapComparison> results; for (int num_sample_blob; num_sample_blob < sample_images_feature_blobs.size(); ++num_sample_blob) { shared_ptr<Blob<Dtype> > sample_images_feature = sample_images_feature_blobs[num_sample_blob]; int num_samples = sample_images_feature->num(); for (int j = 0; j < num_samples; ++j) { hamming_dist = caffe_hamming_distance( dim, query_image_feature->cpu_data() + query_image_feature->offset(i), sample_images_feature->cpu_data() + sample_images_feature->offset(j)); if (results.size() < top_k_results) { results.push(std::make_pair(-hamming_dist, j)); } else if (-hamming_dist > results.top().first) { // smaller hamming dist results.pop(); results.push(std::make_pair(-hamming_dist, j)); } } // for (int j = 0; j < num_samples; ++j) { retrieval_results_data += retrieval_results->offset(i); for (int k = 0; k < results.size(); ++k) { retrieval_results_data[k] = results.top().second; results.pop(); } } // for(...; sample_images_feature_blobs.size(); ...) } // for (int i = 0; i < num_queries; ++i) { }
Simplify image retrieval example to use binary features directly
Simplify image retrieval example to use binary features directly
C++
bsd-2-clause
tackgeun/caffe,bharath272/sds_eccv2014,gnina/gnina,naeluh/caffe,vibhav-vineet/caffe,dculibrk/boosted_pooling,CVML/sds_eccv2014,suixudongi8/caffe,minghuam/caffe,flickr/caffe,liuxianming/caffe_feedback,dculibrk/boosted_pooling,shiquanwang/caffe,niuzhiheng/caffe,Hilovaiserillis/caffe,gnina/gnina,naeluh/caffe,dylansun/caffe,gnina/gnina,CZCV/s-dilation-caffe,CZCV/s-dilation-caffe,pcoving/caffe,shiquanwang/caffe,dylansun/caffe,minghuam/caffe,MoskalenkoViktor/caffe,flickr/caffe,longjon/caffe,dculibrk/boosted_pooling,orentadmor/caffe,Hilovaiserillis/caffe,tackgeun/caffe,suixudongi8/caffe,MoskalenkoViktor/caffe,longjon/caffe,shiquanwang/caffe,wangg12/caffe,vibhav-vineet/caffe,shuimulinxi/caffe,xidianwlc/caffe,yikeliu/caffe-future,longjon/caffe,Hilovaiserillis/caffe,MoskalenkoViktor/caffe,xidianwlc/caffe,shiquanwang/caffe,gnina/gnina,niuzhiheng/caffe,dylansun/caffe,yikeliu/caffe-future,audtlr24/caffe,gogartom/caffe-textmaps,gnina/gnina,MoskalenkoViktor/caffe,yikeliu/caffe-future,vibhav-vineet/caffe,gnina/gnina,naeluh/caffe,flickr/caffe,xidianwlc/caffe,shuimulinxi/caffe,gogartom/caffe-textmaps,minghuam/caffe,tackgeun/caffe,pcoving/caffe,vibhav-vineet/caffe,xidianwlc/caffe,orentadmor/caffe,nicodjimenez/caffe,audtlr24/caffe,audtlr24/caffe,shuimulinxi/caffe,shuimulinxi/caffe,minghuam/caffe,naeluh/caffe,sichenucsd/caffe_si,sichenucsd/caffe_si,wangg12/caffe,pcoving/caffe,orentadmor/caffe,nicodjimenez/caffe,dylansun/caffe,dculibrk/boosted_pooling,suixudongi8/caffe,tackgeun/caffe,niuzhiheng/caffe,nicodjimenez/caffe,nicodjimenez/caffe,dculibrk/boosted_pooling,niuzhiheng/caffe,flickr/caffe,longjon/caffe,pcoving/caffe,nicodjimenez/caffe,liuxianming/caffe_feedback,naeluh/caffe,yikeliu/caffe-future,wangg12/caffe,gogartom/caffe-textmaps,sichenucsd/caffe_si,MoskalenkoViktor/caffe,shuimulinxi/caffe,flickr/caffe,sichenucsd/caffe_si,gogartom/caffe-textmaps,pcoving/caffe,orentadmor/caffe,Hilovaiserillis/caffe,Hilovaiserillis/caffe,audtlr24/caffe,liuxianming/caffe_feedback,CZCV/s-dilation-caffe,dylansun/caffe,audtlr24/caffe,wangg12/caffe,CZCV/s-dilation-caffe,liuxianming/caffe_feedback,liuxianming/caffe_feedback,suixudongi8/caffe,niuzhiheng/caffe
d890976c3c597575d5bac0e9f3c24865c643be3a
tests/auto/declarative/examples/tst_examples.cpp
tests/auto/declarative/examples/tst_examples.cpp
#include <qtest.h> #include <QLibraryInfo> #include <QDir> #include <QProcess> class tst_examples : public QObject { Q_OBJECT public: tst_examples(); private slots: void examples_data(); void examples(); void namingConvention(); private: QString qmlviewer; void namingConvention(const QDir &); QStringList findQmlFiles(const QDir &); }; tst_examples::tst_examples() { QString binaries = QLibraryInfo::location(QLibraryInfo::BinariesPath); #if defined(Q_WS_MAC) qmlviewer = QDir(binaries).absoluteFilePath("qmlviewer.app/Contents/MacOS/qmlviewer"); #elif defined(Q_WS_WIN) qmlviewer = QDir(binaries).absoluteFilePath("qmlviewer.exe"); #else qmlviewer = QDir(binaries).absoluteFilePath("qmlviewer"); #endif } /* This tests that the demos and examples follow the naming convention required to have them tested by the examples() test. */ void tst_examples::namingConvention(const QDir &d) { QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"), QDir::Files); bool seenQml = !files.isEmpty(); bool seenLowercase = false; foreach (const QString &file, files) { if (file.at(0).isLower()) seenLowercase = true; } if (!seenQml) { QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); namingConvention(sub); } } else if(!seenLowercase) { QTest::qFail(QString("Directory " + d.absolutePath() + " violates naming convention").toLatin1().constData(), __FILE__, __LINE__); } } void tst_examples::namingConvention() { QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath); QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath); namingConvention(QDir(examples)); namingConvention(QDir(demos)); } QStringList tst_examples::findQmlFiles(const QDir &d) { QStringList rv; QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"), QDir::Files); foreach (const QString &file, files) { if (file.at(0).isLower()) { rv << d.absoluteFilePath(file); } } QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); rv << findQmlFiles(sub); } return rv; } /* This test runs all the examples in the declarative UI source tree and ensures that they start and exit cleanly. Examples are any .qml files under the examples/ or demos/ directory that start with a lower case letter. */ void tst_examples::examples_data() { QTest::addColumn<QString>("file"); QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath); QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath); QStringList files; files << findQmlFiles(QDir(examples)); files << findQmlFiles(QDir(demos)); foreach (const QString &file, files) QTest::newRow(file.toLatin1().constData()) << file; } void tst_examples::examples() { QFETCH(QString, file); QStringList arguments; arguments << "-script" << "data/dummytest" << "-scriptopts" << "play,exitoncomplete,exitonfailure" << file; QProcess p; p.start(qmlviewer, arguments); QVERIFY(p.waitForFinished()); QCOMPARE(p.exitStatus(), QProcess::NormalExit); QCOMPARE(p.exitCode(), 0); } QTEST_MAIN(tst_examples) #include "tst_examples.moc"
#include <qtest.h> #include <QLibraryInfo> #include <QDir> #include <QProcess> class tst_examples : public QObject { Q_OBJECT public: tst_examples(); private slots: void examples_data(); void examples(); void namingConvention(); private: QString qmlviewer; QStringList excludedDirs; void namingConvention(const QDir &); QStringList findQmlFiles(const QDir &); }; tst_examples::tst_examples() { QString binaries = QLibraryInfo::location(QLibraryInfo::BinariesPath); #if defined(Q_WS_MAC) qmlviewer = QDir(binaries).absoluteFilePath("qmlviewer.app/Contents/MacOS/qmlviewer"); #elif defined(Q_WS_WIN) qmlviewer = QDir(binaries).absoluteFilePath("qmlviewer.exe"); #else qmlviewer = QDir(binaries).absoluteFilePath("qmlviewer"); #endif // Add directories you want excluded here excludedDirs << "examples/declarative/extending"; } /* This tests that the demos and examples follow the naming convention required to have them tested by the examples() test. */ void tst_examples::namingConvention(const QDir &d) { for (int ii = 0; ii < excludedDirs.count(); ++ii) { QString s = QDir::toNativeSeparators(excludedDirs.at(ii)); if (d.absolutePath().endsWith(s)) return; } QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"), QDir::Files); bool seenQml = !files.isEmpty(); bool seenLowercase = false; foreach (const QString &file, files) { if (file.at(0).isLower()) seenLowercase = true; } if (!seenQml) { QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); namingConvention(sub); } } else if(!seenLowercase) { QTest::qFail(QString("Directory " + d.absolutePath() + " violates naming convention").toLatin1().constData(), __FILE__, __LINE__); } } void tst_examples::namingConvention() { QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath); QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath); namingConvention(QDir(examples)); namingConvention(QDir(demos)); } QStringList tst_examples::findQmlFiles(const QDir &d) { for (int ii = 0; ii < excludedDirs.count(); ++ii) { QString s = QDir::toNativeSeparators(excludedDirs.at(ii)); if (d.absolutePath().endsWith(s)) return QStringList(); } QStringList rv; QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"), QDir::Files); foreach (const QString &file, files) { if (file.at(0).isLower()) { rv << d.absoluteFilePath(file); } } QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); rv << findQmlFiles(sub); } return rv; } /* This test runs all the examples in the declarative UI source tree and ensures that they start and exit cleanly. Examples are any .qml files under the examples/ or demos/ directory that start with a lower case letter. */ void tst_examples::examples_data() { QTest::addColumn<QString>("file"); QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath); QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath); QStringList files; files << findQmlFiles(QDir(examples)); files << findQmlFiles(QDir(demos)); foreach (const QString &file, files) QTest::newRow(file.toLatin1().constData()) << file; } void tst_examples::examples() { QFETCH(QString, file); QStringList arguments; arguments << "-script" << "data/dummytest" << "-scriptopts" << "play,exitoncomplete,exitonfailure" << file; QProcess p; p.start(qmlviewer, arguments); QVERIFY(p.waitForFinished()); QCOMPARE(p.exitStatus(), QProcess::NormalExit); QCOMPARE(p.exitCode(), 0); } QTEST_MAIN(tst_examples) #include "tst_examples.moc"
Allow paths to be excluded from test
Allow paths to be excluded from test
C++
lgpl-2.1
igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk
3537d1f46f7279965526e05ded21830050661472
amgcl/mpi/util.hpp
amgcl/mpi/util.hpp
#ifndef AMGCL_MPI_UTIL_HPP #define AMGCL_MPI_UTIL_HPP /* The MIT License Copyright (c) 2012-2022 Denis Demidov <[email protected]> Copyright (c) 2014, Riccardo Rossi, CIMNE (International Center for Numerical Methods in Engineering) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file amgcl/mpi/util.hpp * \author Denis Demidov <[email protected]> * \brief MPI utilities. */ #include <vector> #include <numeric> #include <complex> #include <type_traits> #include <amgcl/value_type/interface.hpp> #include <mpi.h> namespace amgcl { namespace mpi { /// Converts C type to MPI datatype. template <class T, class Enable = void> struct datatype_impl { static MPI_Datatype get() { static const MPI_Datatype t = create(); return t; } static MPI_Datatype create() { typedef typename math::scalar_of<T>::type S; MPI_Datatype t; int n = sizeof(T) / sizeof(S); MPI_Type_contiguous(n, datatype_impl<S>::get(), &t); MPI_Type_commit(&t); return t; } }; template <> struct datatype_impl<float> { static MPI_Datatype get() { return MPI_FLOAT; } }; template <> struct datatype_impl<double> { static MPI_Datatype get() { return MPI_DOUBLE; } }; template <> struct datatype_impl<long double> { static MPI_Datatype get() { return MPI_LONG_DOUBLE; } }; template <> struct datatype_impl<int> { static MPI_Datatype get() { return MPI_INT; } }; template <> struct datatype_impl<unsigned> { static MPI_Datatype get() { return MPI_UNSIGNED; } }; template <> struct datatype_impl<long long> { static MPI_Datatype get() { return MPI_LONG_LONG_INT; } }; template <> struct datatype_impl<unsigned long long> { static MPI_Datatype get() { return MPI_UNSIGNED_LONG_LONG; } }; template <> struct datatype_impl< std::complex<double> > { static MPI_Datatype get() { return MPI_CXX_DOUBLE_COMPLEX; } }; template <> struct datatype_impl< std::complex<float> > { static MPI_Datatype get() { return MPI_CXX_FLOAT_COMPLEX; } }; template <typename T> struct datatype_impl<T, typename std::enable_if< std::is_same<T, ptrdiff_t>::value && !std::is_same<ptrdiff_t, long long>::value && !std::is_same<ptrdiff_t, int>::value >::type > : std::conditional< sizeof(ptrdiff_t) == sizeof(int), datatype_impl<int>, datatype_impl<long long> >::type {}; template <typename T> struct datatype_impl<T, typename std::enable_if< std::is_same<T, size_t>::value && !std::is_same<size_t, unsigned long long>::value && !std::is_same<ptrdiff_t, unsigned int>::value >::type > : std::conditional< sizeof(size_t) == sizeof(unsigned), datatype_impl<unsigned>, datatype_impl<unsigned long long> >::type {}; template <> struct datatype_impl<char> { static MPI_Datatype get() { return MPI_CHAR; } }; template <typename T> MPI_Datatype datatype() { return datatype_impl<T>::get(); } /// Convenience wrapper around MPI_Init/MPI_Finalize. struct init { init(int* argc, char ***argv) { MPI_Init(argc, argv); } ~init() { MPI_Finalize(); } }; /// Convenience wrapper around MPI_Init_threads/MPI_Finalize. struct init_thread { init_thread(int* argc, char ***argv) { int _; MPI_Init_thread(argc, argv, MPI_THREAD_MULTIPLE, &_); } ~init_thread() { MPI_Finalize(); } }; /// Convenience wrapper around MPI_Comm. struct communicator { MPI_Comm comm; int rank; int size; communicator() {} communicator(MPI_Comm comm) : comm(comm) { MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); }; operator MPI_Comm() const { return comm; } /// Exclusive sum over mpi communicator template <typename T> std::vector<T> exclusive_sum(T n) const { std::vector<T> v(size + 1); v[0] = 0; MPI_Allgather(&n, 1, datatype<T>(), &v[1], 1, datatype<T>(), comm); std::partial_sum(v.begin(), v.end(), v.begin()); return v; } template <typename T> T reduce(MPI_Op op, const T &lval) const { const int elems = math::static_rows<T>::value * math::static_cols<T>::value; T gval; MPI_Allreduce((void*)&lval, &gval, elems, datatype<T>(), op, comm); return gval; } /// Communicator-wise condition checking. /** * Checks conditions at each process in the communicator; * * If the condition is false on any of the participating processes, outputs the * provided message together with the ranks of the offending process. * After that each process in the communicator throws. */ template <class Condition, class Message> void check(const Condition &cond, const Message &message) { int lc = static_cast<int>(cond); int gc = reduce(MPI_PROD, lc); if (!gc) { std::vector<int> c(size); MPI_Gather(&lc, 1, MPI_INT, &c[0], size, MPI_INT, 0, comm); if (rank == 0) { std::cerr << "Failed assumption: " << message << std::endl; std::cerr << "Offending processes:"; for (int i = 0; i < size; ++i) if (!c[i]) std::cerr << " " << i; std::cerr << std::endl; } MPI_Barrier(comm); throw std::runtime_error(message); } } }; } // namespace mpi } // namespace amgcl #endif
#ifndef AMGCL_MPI_UTIL_HPP #define AMGCL_MPI_UTIL_HPP /* The MIT License Copyright (c) 2012-2022 Denis Demidov <[email protected]> Copyright (c) 2014, Riccardo Rossi, CIMNE (International Center for Numerical Methods in Engineering) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file amgcl/mpi/util.hpp * \author Denis Demidov <[email protected]> * \brief MPI utilities. */ #include <vector> #include <numeric> #include <complex> #include <type_traits> #include <amgcl/value_type/interface.hpp> #include <mpi.h> namespace amgcl { namespace mpi { /// Converts C type to MPI datatype. template <class T, class Enable = void> struct datatype_impl { static MPI_Datatype get() { static const MPI_Datatype t = create(); return t; } static MPI_Datatype create() { typedef typename math::scalar_of<T>::type S; MPI_Datatype t; int n = sizeof(T) / sizeof(S); MPI_Type_contiguous(n, datatype_impl<S>::get(), &t); MPI_Type_commit(&t); return t; } }; template <> struct datatype_impl<float> { static MPI_Datatype get() { return MPI_FLOAT; } }; template <> struct datatype_impl<double> { static MPI_Datatype get() { return MPI_DOUBLE; } }; template <> struct datatype_impl<long double> { static MPI_Datatype get() { return MPI_LONG_DOUBLE; } }; template <> struct datatype_impl<int> { static MPI_Datatype get() { return MPI_INT; } }; template <> struct datatype_impl<unsigned> { static MPI_Datatype get() { return MPI_UNSIGNED; } }; template <> struct datatype_impl<long long> { static MPI_Datatype get() { return MPI_LONG_LONG_INT; } }; template <> struct datatype_impl<unsigned long long> { static MPI_Datatype get() { return MPI_UNSIGNED_LONG_LONG; } }; #if (MPI_VERSION > 2) || (MPI_VERSION == 2 && MPI_SUBVERSION >= 2) template <> struct datatype_impl< std::complex<double> > { static MPI_Datatype get() { return MPI_CXX_DOUBLE_COMPLEX; } }; template <> struct datatype_impl< std::complex<float> > { static MPI_Datatype get() { return MPI_CXX_FLOAT_COMPLEX; } }; #endif template <typename T> struct datatype_impl<T, typename std::enable_if< std::is_same<T, ptrdiff_t>::value && !std::is_same<ptrdiff_t, long long>::value && !std::is_same<ptrdiff_t, int>::value >::type > : std::conditional< sizeof(ptrdiff_t) == sizeof(int), datatype_impl<int>, datatype_impl<long long> >::type {}; template <typename T> struct datatype_impl<T, typename std::enable_if< std::is_same<T, size_t>::value && !std::is_same<size_t, unsigned long long>::value && !std::is_same<ptrdiff_t, unsigned int>::value >::type > : std::conditional< sizeof(size_t) == sizeof(unsigned), datatype_impl<unsigned>, datatype_impl<unsigned long long> >::type {}; template <> struct datatype_impl<char> { static MPI_Datatype get() { return MPI_CHAR; } }; template <typename T> MPI_Datatype datatype() { return datatype_impl<T>::get(); } /// Convenience wrapper around MPI_Init/MPI_Finalize. struct init { init(int* argc, char ***argv) { MPI_Init(argc, argv); } ~init() { MPI_Finalize(); } }; /// Convenience wrapper around MPI_Init_threads/MPI_Finalize. struct init_thread { init_thread(int* argc, char ***argv) { int _; MPI_Init_thread(argc, argv, MPI_THREAD_MULTIPLE, &_); } ~init_thread() { MPI_Finalize(); } }; /// Convenience wrapper around MPI_Comm. struct communicator { MPI_Comm comm; int rank; int size; communicator() {} communicator(MPI_Comm comm) : comm(comm) { MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); }; operator MPI_Comm() const { return comm; } /// Exclusive sum over mpi communicator template <typename T> std::vector<T> exclusive_sum(T n) const { std::vector<T> v(size + 1); v[0] = 0; MPI_Allgather(&n, 1, datatype<T>(), &v[1], 1, datatype<T>(), comm); std::partial_sum(v.begin(), v.end(), v.begin()); return v; } template <typename T> T reduce(MPI_Op op, const T &lval) const { const int elems = math::static_rows<T>::value * math::static_cols<T>::value; T gval; MPI_Allreduce((void*)&lval, &gval, elems, datatype<T>(), op, comm); return gval; } /// Communicator-wise condition checking. /** * Checks conditions at each process in the communicator; * * If the condition is false on any of the participating processes, outputs the * provided message together with the ranks of the offending process. * After that each process in the communicator throws. */ template <class Condition, class Message> void check(const Condition &cond, const Message &message) { int lc = static_cast<int>(cond); int gc = reduce(MPI_PROD, lc); if (!gc) { std::vector<int> c(size); MPI_Gather(&lc, 1, MPI_INT, &c[0], size, MPI_INT, 0, comm); if (rank == 0) { std::cerr << "Failed assumption: " << message << std::endl; std::cerr << "Offending processes:"; for (int i = 0; i < size; ++i) if (!c[i]) std::cerr << " " << i; std::cerr << std::endl; } MPI_Barrier(comm); throw std::runtime_error(message); } } }; } // namespace mpi } // namespace amgcl #endif
Check if MPI supports MPI_CXX_*_COMPLEX datatypes
Check if MPI supports MPI_CXX_*_COMPLEX datatypes
C++
mit
ddemidov/amgcl,ddemidov/amgcl,ddemidov/amgcl,ddemidov/amgcl
0d3f32a6c86aba5ee9e03ff35e1717220b320682
NaoTHSoccer/Source/Motion/Engine/InverseKinematicsMotion/Motions/IKParameters.cpp
NaoTHSoccer/Source/Motion/Engine/InverseKinematicsMotion/Motions/IKParameters.cpp
/** * @file IKParameters.cpp * * @author <a href="mailto:[email protected]">Xu, Yuan</a> * Implement of parameters for IK motion */ #include "IKParameters.h" IKParameters::IKParameters() :ParameterList("IKParameters") { PARAMETER_REGISTER(footOffsetY) = 0; // stand parameter PARAMETER_REGISTER(stand.speed) = 0.04; PARAMETER_REGISTER(stand.enableStabilization) = false; PARAMETER_REGISTER(stand.stiffness) = 0.7; PARAMETER_ANGLE_REGISTER(stand.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(stand.hipOffsetX) = 15; // relax PARAMETER_REGISTER(stand.relax.enable) = true; PARAMETER_REGISTER(stand.relax.allowedDeviation) = 5; // [mm] PARAMETER_REGISTER(stand.relax.allowedRotationDeviation) = Math::fromDegrees(5);// [rad] todo: PARAMETER_ANGLE_REGISTER PARAMETER_REGISTER(stand.relax.timeBonusForCorrection) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.enable) = true; PARAMETER_REGISTER(stand.relax.jointOffsetTuning.deadTime) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.currentThreshold) = 0.3; // [A] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.minimalJointStep) = 0.0013962634; // [rad] PARAMETER_REGISTER(stand.relax.stiffnessControl.enable) = true; PARAMETER_REGISTER(stand.relax.stiffnessControl.deadTime) = 100; // [ms] PARAMETER_REGISTER(stand.relax.stiffnessControl.minAngle) = 0.08; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.maxAngle) = 2; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.minStiffness) = 0.3; PARAMETER_REGISTER(stand.relax.stiffnessControl.maxStiffness) = 1.0; // walk parameter: // General PARAMETER_ANGLE_REGISTER(walk.general.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(walk.general.hipOffsetX) = 15; PARAMETER_REGISTER(walk.general.stiffness) = 0.7; PARAMETER_REGISTER(walk.general.useArm) = false; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorLeft) = 0.4; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorRight) = 0.4; // hip trajectory geometry PARAMETER_REGISTER(walk.hip.comHeight) = 260; PARAMETER_REGISTER(walk.hip.comHeightOffset) = 0.18; PARAMETER_REGISTER(walk.hip.comRotationOffsetX) = 0; PARAMETER_REGISTER(walk.hip.ZMPOffsetY) = 5; PARAMETER_REGISTER(walk.hip.ZMPOffsetYByCharacter) = 0; // step geometry PARAMETER_REGISTER(walk.step.duration) = 300; PARAMETER_REGISTER(walk.step.doubleSupportTime) = 40; PARAMETER_REGISTER(walk.step.stepHeight) = 10; // step limits PARAMETER_REGISTER(walk.limits.maxTurnInner) = 10; PARAMETER_REGISTER(walk.limits.maxStepTurn) = 30; PARAMETER_REGISTER(walk.limits.maxStepLength) = 50; PARAMETER_REGISTER(walk.limits.maxStepLengthBack) = 50; PARAMETER_REGISTER(walk.limits.maxStepWidth) = 50; PARAMETER_REGISTER(walk.limits.maxStepChange) = 0.5; // step control PARAMETER_REGISTER(walk.limits.maxCtrlTurn) = 30; PARAMETER_REGISTER(walk.limits.maxCtrlLength) = 80; PARAMETER_REGISTER(walk.limits.maxCtrlWidth) = 50; // Stabilization //PARAMETER_REGISTER(walk.stabilization.enableFSRProtection) = true; //PARAMETER_REGISTER(walk.stabilization.enableWaitLanding) = false; //PARAMETER_REGISTER(walk.stabilization.minFSRProtectionCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxUnsupportedCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxWaitLandingCount) = 20; PARAMETER_REGISTER(walk.stabilization.emergencyStopError) = 500; PARAMETER_REGISTER(walk.stabilization.rotationStabilize) = true; PARAMETER_REGISTER(walk.stabilization.rotationP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.y) = 0; PARAMETER_REGISTER(walk.stabilization.stabilizeFeet) = true; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.x) = 0.04; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.y) = 0.035; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.x) = -0.4; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.y) = -0.3; PARAMETER_REGISTER(walk.stabilization.dynamicStepsize) = true; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeP) = -1; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeD) = 0.5; // rotation stabilize parameter PARAMETER_REGISTER(rotationStabilize.k.x) = -0.5; PARAMETER_REGISTER(rotationStabilize.k.y) = -0.2; PARAMETER_REGISTER(rotationStabilize.threshold.x) = 2; PARAMETER_REGISTER(rotationStabilize.threshold.y) = 3; // arm parameter PARAMETER_REGISTER(arm.shoulderPitchInterialSensorRate) = -10; PARAMETER_REGISTER(arm.shoulderRollInterialSensorRate) = -10; PARAMETER_REGISTER(arm.maxSpeed) = 60; PARAMETER_REGISTER(arm.alwaysEnabled) = false; PARAMETER_REGISTER(arm.kickEnabled) = true; PARAMETER_REGISTER(arm.walkEnabled) = true; PARAMETER_REGISTER(arm.takeBack) = false; PARAMETER_REGISTER(balanceCoM.kP) = 0; PARAMETER_REGISTER(balanceCoM.kI) = 0; PARAMETER_REGISTER(balanceCoM.kD) = 0; PARAMETER_REGISTER(balanceCoM.threshold) = 10; syncWithConfig(); } IKParameters::~IKParameters() { }
/** * @file IKParameters.cpp * * @author <a href="mailto:[email protected]">Xu, Yuan</a> * Implement of parameters for IK motion */ #include "IKParameters.h" IKParameters::IKParameters() :ParameterList("IKParameters") { PARAMETER_REGISTER(footOffsetY) = 0; // stand parameter PARAMETER_REGISTER(stand.speed) = 0.01; PARAMETER_REGISTER(stand.enableStabilization) = false; PARAMETER_REGISTER(stand.stiffness) = 0.7; PARAMETER_ANGLE_REGISTER(stand.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(stand.hipOffsetX) = 15; // relax PARAMETER_REGISTER(stand.relax.enable) = true; PARAMETER_REGISTER(stand.relax.allowedDeviation) = 5; // [mm] PARAMETER_REGISTER(stand.relax.allowedRotationDeviation) = Math::fromDegrees(5);// [rad] todo: PARAMETER_ANGLE_REGISTER PARAMETER_REGISTER(stand.relax.timeBonusForCorrection) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.enable) = true; PARAMETER_REGISTER(stand.relax.jointOffsetTuning.deadTime) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.currentThreshold) = 0.3; // [A] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.minimalJointStep) = 0.0013962634; // [rad] PARAMETER_REGISTER(stand.relax.stiffnessControl.enable) = true; PARAMETER_REGISTER(stand.relax.stiffnessControl.deadTime) = 100; // [ms] PARAMETER_REGISTER(stand.relax.stiffnessControl.minAngle) = 0.08; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.maxAngle) = 2; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.minStiffness) = 0.3; PARAMETER_REGISTER(stand.relax.stiffnessControl.maxStiffness) = 1.0; // walk parameter: // General PARAMETER_ANGLE_REGISTER(walk.general.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(walk.general.hipOffsetX) = 15; PARAMETER_REGISTER(walk.general.stiffness) = 0.7; PARAMETER_REGISTER(walk.general.useArm) = false; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorLeft) = 0.4; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorRight) = 0.4; // hip trajectory geometry PARAMETER_REGISTER(walk.hip.comHeight) = 260; PARAMETER_REGISTER(walk.hip.comHeightOffset) = 0.18; PARAMETER_REGISTER(walk.hip.comRotationOffsetX) = 0; PARAMETER_REGISTER(walk.hip.ZMPOffsetY) = 5; PARAMETER_REGISTER(walk.hip.ZMPOffsetYByCharacter) = 0; // step geometry PARAMETER_REGISTER(walk.step.duration) = 300; PARAMETER_REGISTER(walk.step.doubleSupportTime) = 40; PARAMETER_REGISTER(walk.step.stepHeight) = 10; // step limits PARAMETER_REGISTER(walk.limits.maxTurnInner) = 10; PARAMETER_REGISTER(walk.limits.maxStepTurn) = 30; PARAMETER_REGISTER(walk.limits.maxStepLength) = 50; PARAMETER_REGISTER(walk.limits.maxStepLengthBack) = 50; PARAMETER_REGISTER(walk.limits.maxStepWidth) = 50; PARAMETER_REGISTER(walk.limits.maxStepChange) = 0.5; // step control PARAMETER_REGISTER(walk.limits.maxCtrlTurn) = 30; PARAMETER_REGISTER(walk.limits.maxCtrlLength) = 80; PARAMETER_REGISTER(walk.limits.maxCtrlWidth) = 50; // Stabilization //PARAMETER_REGISTER(walk.stabilization.enableFSRProtection) = true; //PARAMETER_REGISTER(walk.stabilization.enableWaitLanding) = false; //PARAMETER_REGISTER(walk.stabilization.minFSRProtectionCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxUnsupportedCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxWaitLandingCount) = 20; PARAMETER_REGISTER(walk.stabilization.emergencyStopError) = 500; PARAMETER_REGISTER(walk.stabilization.rotationStabilize) = true; PARAMETER_REGISTER(walk.stabilization.rotationP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.y) = 0; PARAMETER_REGISTER(walk.stabilization.stabilizeFeet) = true; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.x) = 0.04; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.y) = 0.035; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.x) = -0.4; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.y) = -0.3; PARAMETER_REGISTER(walk.stabilization.dynamicStepsize) = true; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeP) = -1; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeD) = 0.5; // rotation stabilize parameter PARAMETER_REGISTER(rotationStabilize.k.x) = -0.5; PARAMETER_REGISTER(rotationStabilize.k.y) = -0.2; PARAMETER_REGISTER(rotationStabilize.threshold.x) = 2; PARAMETER_REGISTER(rotationStabilize.threshold.y) = 3; // arm parameter PARAMETER_REGISTER(arm.shoulderPitchInterialSensorRate) = -10; PARAMETER_REGISTER(arm.shoulderRollInterialSensorRate) = -10; PARAMETER_REGISTER(arm.maxSpeed) = 60; PARAMETER_REGISTER(arm.alwaysEnabled) = false; PARAMETER_REGISTER(arm.kickEnabled) = true; PARAMETER_REGISTER(arm.walkEnabled) = true; PARAMETER_REGISTER(arm.takeBack) = false; PARAMETER_REGISTER(balanceCoM.kP) = 0; PARAMETER_REGISTER(balanceCoM.kI) = 0; PARAMETER_REGISTER(balanceCoM.kD) = 0; PARAMETER_REGISTER(balanceCoM.threshold) = 10; syncWithConfig(); } IKParameters::~IKParameters() { }
change stand motion speed
change stand motion speed
C++
apache-2.0
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
7f0f6dbc27d1dc92284c463dce1bf320d1f256de
tests/unit-and-behavior/test-unit-arg-struct.cpp
tests/unit-and-behavior/test-unit-arg-struct.cpp
/* Copyright (C) 2016, Szilard Ledan <[email protected]> * 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. */ #include "test-unit.hpp" #include "arg-parse.hpp" #include <assert.h> namespace testargparse { namespace { using namespace argparse; TestContext::Return testConstructors(TestContext* ctx) { TAP_VALUE_STR_TEST_CASES(nameCases); TAP_REQUIRED_TEST_CASES(requiredCases); TAP_VALUE_STR_TEST_CASES(valueStrCases); for (size_t nameCase = 0; nameCase < TAP_ARRAY_SIZE(nameCases); ++nameCase) for (size_t requiredCase = 0; requiredCase < TAP_ARRAY_SIZE(requiredCases); ++requiredCase) for (size_t valueStrCase = 0; valueStrCase < TAP_ARRAY_SIZE(valueStrCases); ++valueStrCase) { const bool required = requiredCases[requiredCase].required; const std:: string testStr = valueStrCases[valueStrCase].str; const std:: string testValueName = "value-name"; const std:: string testValueDescription = "value-description"; TAP_VALUE_TEST_CASES(valueCases, testStr, required, testValueName, testValueDescription); for (size_t valueCase = 0; valueCase < TAP_ARRAY_SIZE(valueCases); ++valueCase) { const Value value = valueCases[valueCase].value; const std::string testName = nameCases[nameCase].str; const std::string testDescription = "description"; struct { Arg defined; struct { bool isRequired; bool isSet; std::string str; std::vector<std::string> _chooseList; std::string _name; std::string _description; bool isDefined; } expected; } test = { { Arg() }, { false, false, "", {}, "", "", false } }, testCases[] = { { { Arg() }, { false, false, "", {}, "", "", false } }, { { Arg(testName) }, { false, false, "", {}, testName, "", !testName.empty() } }, { { Arg(testName, testDescription) }, { false, false, "", {}, testName, testDescription, !testName.empty() } }, { { Arg(testName, testDescription, required) }, { required, false, "", {}, testName, testDescription, !testName.empty() } }, { { Arg(testName, testDescription, required, value) }, { required, false, value.str, value._chooseList, testName, testDescription, !testName.empty() } }, { { Arg(value) }, { false, false, value.str, value._chooseList, "", "", false } }, }; for (size_t testCase = 0; testCase < TAP_ARRAY_SIZE(testCases); ++testCase) { assert((sizeof(testCases[0].defined) == sizeof(testCases[0].expected)) && "Structs size are differents."); test.defined = testCases[testCase].defined; test.expected = testCases[testCase].expected; const std::string caseName = TAP_CASE_NAME(testCase, TAP_ARG_TO_STR(test.defined)); if (TAP_CHECK(ctx, test.defined.isRequired != test.expected.isRequired)) return TAP_FAIL(ctx, caseName + "!!!"); if (TAP_CHECK(ctx, test.defined.isSet != test.expected.isSet)) return TAP_FAIL(ctx, caseName + "!!!"); if (TAP_CHECK(ctx, test.defined.str != test.expected.str)) return TAP_FAIL(ctx, caseName + "!!!"); if (TAP_CHECK(ctx, test.defined._chooseList.size() != test.expected._chooseList.size())) { return TAP_FAIL(ctx, caseName + "!!!"); } else if (test.defined._chooseList.size()) { for (size_t i = 0; i < test.defined._chooseList.size(); ++i) if (TAP_CHECK(ctx, test.defined._chooseList[i] != test.expected._chooseList[i])) return TAP_FAIL(ctx, caseName + "!!!"); } if (TAP_CHECK(ctx, test.defined._name != test.expected._name)) return TAP_FAIL(ctx, caseName + "!!!"); if (TAP_CHECK(ctx, test.defined._description != test.expected._description)) return TAP_FAIL(ctx, caseName + "!!!"); if (TAP_CHECK(ctx, test.defined.isDefined != test.expected.isDefined)) return TAP_FAIL(ctx, caseName + "!!!"); } } } return TAP_PASS(ctx, "The Arg::Arg(...) constructors test."); } } // namespace anonymous void unitArgStructTests(TestContext* ctx) { ctx->add(testConstructors); } } // namespace testargparse
/* Copyright (C) 2016, Szilard Ledan <[email protected]> * 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. */ #include "test-unit.hpp" #include "arg-parse.hpp" #include <assert.h> namespace testargparse { namespace { using namespace argparse; TestContext::Return testConstructors(TestContext* ctx) { TAP_VALUE_STR_TEST_CASES(nameCases); TAP_REQUIRED_TEST_CASES(requiredCases); TAP_VALUE_STR_TEST_CASES(valueStrCases); for (size_t nameCase = 0; nameCase < TAP_ARRAY_SIZE(nameCases); ++nameCase) for (size_t requiredCase = 0; requiredCase < TAP_ARRAY_SIZE(requiredCases); ++requiredCase) for (size_t valueStrCase = 0; valueStrCase < TAP_ARRAY_SIZE(valueStrCases); ++valueStrCase) { const bool required = requiredCases[requiredCase].required; const std:: string testStr = valueStrCases[valueStrCase].str; const std:: string testValueName = "value-name"; const std:: string testValueDescription = "value-description"; TAP_VALUE_TEST_CASES(valueCases, testStr, required, testValueName, testValueDescription); for (size_t valueCase = 0; valueCase < TAP_ARRAY_SIZE(valueCases); ++valueCase) { const Value value = valueCases[valueCase].value; const std::string testName = nameCases[nameCase].str; const std::string testDescription = "description"; struct { Arg defined; struct { bool isRequired; bool isSet; std::string str; std::vector<std::string> _chooseList; std::string _name; std::string _description; bool isDefined; } expected; } test = { { Arg() }, { false, false, "", {}, "", "", false } }, testCases[] = { { { Arg() }, { false, false, "", {}, "", "", false } }, { { Arg(testName) }, { !testName.empty(), false, "", {}, testName, "", !testName.empty() } }, { { Arg(testName, testDescription) }, { !testName.empty(), false, "", {}, testName, testDescription, !testName.empty() } }, { { Arg(testName, testDescription, required) }, { required, false, "", {}, testName, testDescription, !testName.empty() } }, { { Arg(testName, testDescription, required, value) }, { required, false, value.str, value._chooseList, testName, testDescription, !testName.empty() } }, { { Arg(value) }, { false, false, value.str, value._chooseList, "", "", false } }, }; for (size_t testCase = 0; testCase < TAP_ARRAY_SIZE(testCases); ++testCase) { assert((sizeof(testCases[0].defined) == sizeof(testCases[0].expected)) && "Structs size are differents."); test.defined = testCases[testCase].defined; test.expected = testCases[testCase].expected; const std::string caseName = TAP_CASE_NAME(testCase, TAP_ARG_TO_STR(test.defined)); if (TAP_CHECK(ctx, test.defined.isRequired != test.expected.isRequired)) return TAP_FAIL(ctx, caseName + "!!!"); if (TAP_CHECK(ctx, test.defined.isSet != test.expected.isSet)) return TAP_FAIL(ctx, caseName + "!!!"); if (TAP_CHECK(ctx, test.defined.str != test.expected.str)) return TAP_FAIL(ctx, caseName + "!!!"); if (TAP_CHECK(ctx, test.defined._chooseList.size() != test.expected._chooseList.size())) { return TAP_FAIL(ctx, caseName + "!!!"); } else if (test.defined._chooseList.size()) { for (size_t i = 0; i < test.defined._chooseList.size(); ++i) if (TAP_CHECK(ctx, test.defined._chooseList[i] != test.expected._chooseList[i])) return TAP_FAIL(ctx, caseName + "!!!"); } if (TAP_CHECK(ctx, test.defined._name != test.expected._name)) return TAP_FAIL(ctx, caseName + "!!!"); if (TAP_CHECK(ctx, test.defined._description != test.expected._description)) return TAP_FAIL(ctx, caseName + "!!!"); if (TAP_CHECK(ctx, test.defined.isDefined != test.expected.isDefined)) return TAP_FAIL(ctx, caseName + "!!!"); } } } return TAP_PASS(ctx, "The Arg::Arg(...) constructors test."); } } // namespace anonymous void unitArgStructTests(TestContext* ctx) { ctx->add(testConstructors); } } // namespace testargparse
Fix tests after added new Arg constructor
Fix tests after added new Arg constructor Signed-off-by: Szilard Ledan <[email protected]>
C++
bsd-2-clause
szledan/arg-parse,szledan/arg-parse
8b64b6f4f7f238b729b5252bc57e79a401a334a8
src/base/application.cpp
src/base/application.cpp
//! @file application.cpp #include "application.h" #include "cantera/base/ctml.h" #include "cantera/base/stringUtils.h" #include "units.h" #include <fstream> #include <sstream> #include <mutex> using std::string; using std::endl; #ifdef _WIN32 #include <windows.h> #else #include <sys/stat.h> #endif #ifdef _MSC_VER #pragma comment(lib, "advapi32") #endif namespace Cantera { //! Mutex for input directory access static std::mutex dir_mutex; //! Mutex for creating singletons within the application object static std::mutex app_mutex; //! Mutex for controlling access to XML file storage static std::mutex xml_mutex; static int get_modified_time(const std::string& path) { #ifdef _WIN32 HANDLE hFile = CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) { throw CanteraError("get_modified_time", "Couldn't open file:" + path); } FILETIME modified; GetFileTime(hFile, NULL, NULL, &modified); CloseHandle(hFile); return static_cast<int>(modified.dwLowDateTime); #else struct stat attrib; stat(path.c_str(), &attrib); return static_cast<int>(attrib.st_mtime); #endif } Application::Messages::Messages() { // install a default logwriter that writes to standard // output / standard error logwriter.reset(new Logger()); } Application::Messages::Messages(const Messages& r) : errorMessage(r.errorMessage) { // install a default logwriter that writes to standard // output / standard error logwriter.reset(new Logger(*r.logwriter)); } Application::Messages& Application::Messages::operator=(const Messages& r) { if (this == &r) { return *this; } errorMessage = r.errorMessage; logwriter.reset(new Logger(*r.logwriter)); return *this; } void Application::Messages::addError(const std::string& r, const std::string& msg) { if (msg.size() != 0) { errorMessage.push_back( "\n\n************************************************\n" " Cantera Error! \n" "************************************************\n\n" "Procedure: " + r + "\nError: " + msg + "\n"); } else { errorMessage.push_back(msg); } } int Application::Messages::getErrorCount() { return static_cast<int>(errorMessage.size()); } void Application::Messages::setLogger(Logger* _logwriter) { logwriter.reset(_logwriter); } void Application::Messages::writelog(const std::string& msg) { logwriter->write(msg); } void Application::Messages::writelogendl() { logwriter->writeendl(); } //! Mutex for access to string messages static std::mutex msg_mutex; Application::Messages* Application::ThreadMessages::operator ->() { std::unique_lock<std::mutex> msgLock(msg_mutex); std::thread::id curId = std::this_thread::get_id(); auto iter = m_threadMsgMap.find(curId); if (iter != m_threadMsgMap.end()) { return iter->second.get(); } pMessages_t pMsgs(new Messages()); m_threadMsgMap.insert({curId, pMsgs}); return pMsgs.get(); } void Application::ThreadMessages::removeThreadMessages() { std::unique_lock<std::mutex> msgLock(msg_mutex); std::thread::id curId = std::this_thread::get_id(); auto iter = m_threadMsgMap.find(curId); if (iter != m_threadMsgMap.end()) { m_threadMsgMap.erase(iter); } } Application::Application() : m_suppress_deprecation_warnings(false) { // install a default logwriter that writes to standard // output / standard error setDefaultDirectories(); Unit::units(); } Application* Application::Instance() { std::unique_lock<std::mutex> appLock(app_mutex); if (Application::s_app == 0) { Application::s_app = new Application(); } return s_app; } Application::~Application() { for (auto& f : xmlfiles) { f.second.first->unlock(); delete f.second.first; f.second.first = 0; } } void Application::ApplicationDestroy() { std::unique_lock<std::mutex> appLock(app_mutex); if (Application::s_app != 0) { delete Application::s_app; Application::s_app = 0; } } void Application::warn_deprecated(const std::string& method, const std::string& extra) { if (m_suppress_deprecation_warnings || warnings.count(method)) { return; } warnings.insert(method); writelog("WARNING: '" + method + "' is deprecated. " + extra); writelogendl(); } void Application::thread_complete() { pMessenger.removeThreadMessages(); } XML_Node* Application::get_XML_File(const std::string& file, int debug) { std::unique_lock<std::mutex> xmlLock(xml_mutex); std::string path = ""; path = findInputFile(file); int mtime = get_modified_time(path); if (xmlfiles.find(path) != xmlfiles.end()) { // Already have a parsed XML tree for this file cached. Check the // last-modified time. std::pair<XML_Node*, int> cache = xmlfiles[path]; if (cache.second == mtime) { return cache.first; } } // Check whether or not the file is XML (based on the file extension). If // not, it will be first processed with the preprocessor. string::size_type idot = path.rfind('.'); string ext; if (idot != string::npos) { ext = path.substr(idot, path.size()); } else { ext = ""; } XML_Node* x = new XML_Node("doc"); if (ext != ".xml" && ext != ".ctml") { // Assume that we are trying to open a cti file. Do the conversion to XML. std::stringstream phase_xml(ct2ctml_string(path)); x->build(phase_xml); } else { std::ifstream s(path.c_str()); if (s) { x->build(s); } else { throw CanteraError("get_XML_File", "cannot open "+file+" for reading.\n" "Note, this error indicates a possible configuration problem."); } } x->lock(); xmlfiles[path] = {x, mtime}; return x; } XML_Node* Application::get_XML_from_string(const std::string& text) { std::unique_lock<std::mutex> xmlLock(xml_mutex); std::pair<XML_Node*, int>& entry = xmlfiles[text]; if (entry.first) { // Return existing cached XML tree return entry.first; } std::stringstream s; size_t start = text.find_first_not_of(" \t\r\n"); if (text.substr(start,1) == "<") { s << text; } else { s << ct_string2ctml_string(text.substr(start)); } entry.first = new XML_Node(); entry.first->build(s); return entry.first; } void Application::close_XML_File(const std::string& file) { std::unique_lock<std::mutex> xmlLock(xml_mutex); if (file == "all") { for (const auto& f : xmlfiles) { f.second.first->unlock(); delete f.second.first; } xmlfiles.clear(); } else if (xmlfiles.find(file) != xmlfiles.end()) { xmlfiles[file].first->unlock(); delete xmlfiles[file].first; xmlfiles.erase(file); } } #ifdef _WIN32 long int Application::readStringRegistryKey(const std::string& keyName, const std::string& valueName, std::string& value, const std::string& defaultValue) { HKEY key; long open_error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName.c_str(), 0, KEY_READ, &key); if (open_error != ERROR_SUCCESS) { return open_error; } value = defaultValue; CHAR buffer[1024]; DWORD bufferSize = sizeof(buffer); ULONG error; error = RegQueryValueEx(key, valueName.c_str(), 0, NULL, (LPBYTE) buffer, &bufferSize); if (ERROR_SUCCESS == error) { value = buffer; } RegCloseKey(key); return error; } #endif void Application::Messages::popError() { if (!errorMessage.empty()) { errorMessage.pop_back(); } } std::string Application::Messages::lastErrorMessage() { if (!errorMessage.empty()) { return errorMessage.back(); } else { return "<no Cantera error>"; } } void Application::Messages::getErrors(std::ostream& f) { for (size_t j = 0; j < errorMessage.size(); j++) { f << errorMessage[j] << endl; } errorMessage.clear(); } void Application::Messages::logErrors() { for (size_t j = 0; j < errorMessage.size(); j++) { writelog(errorMessage[j]); writelogendl(); } errorMessage.clear(); } void Application::setDefaultDirectories() { std::vector<string>& dirs = inputDirs; // always look in the local directory first dirs.push_back("."); #ifdef _WIN32 // Under Windows, the Cantera setup utility records the installation // directory in the registry. Data files are stored in the 'data' // subdirectory of the main installation directory. std::string installDir; readStringRegistryKey("SOFTWARE\\Cantera\\Cantera " CANTERA_SHORT_VERSION, "InstallDir", installDir, ""); if (installDir != "") { dirs.push_back(installDir + "data"); // Scripts for converting mechanisms to CTI and CMTL are installed in // the 'bin' subdirectory. Add that directory to the PYTHONPATH. const char* old_pythonpath = getenv("PYTHONPATH"); std::string pythonpath = "PYTHONPATH=" + installDir + "\\bin"; if (old_pythonpath) { pythonpath += ";"; pythonpath.append(old_pythonpath); } putenv(pythonpath.c_str()); } #endif #ifdef DARWIN // add a default data location for Mac OS X dirs.push_back("/Applications/Cantera/data"); #endif // if environment variable CANTERA_DATA is defined, then add it to the // search path. CANTERA_DATA may include multiple directory, separated by // the OS-dependent path separator (in the same manner as the PATH // environment variable). #ifdef _WIN32 std::string pathsep = ";"; #else std::string pathsep = ":"; #endif if (getenv("CANTERA_DATA") != 0) { string s = string(getenv("CANTERA_DATA")); size_t start = 0; size_t end = s.find(pathsep); while(end != npos) { dirs.push_back(s.substr(start, end-start)); start = end + 1; end = s.find(pathsep, start); } dirs.push_back(s.substr(start,end)); } // CANTERA_DATA is defined in file config.h. This file is written during the // build process (unix), and points to the directory specified by the // 'prefix' option to 'configure', or else to /usr/local/cantera. #ifdef CANTERA_DATA string datadir = string(CANTERA_DATA); dirs.push_back(datadir); #endif } void Application::addDataDirectory(const std::string& dir) { std::unique_lock<std::mutex> dirLock(dir_mutex); if (inputDirs.empty()) { setDefaultDirectories(); } string d = stripnonprint(dir); // Remove any existing entry for this directory auto iter = std::find(inputDirs.begin(), inputDirs.end(), d); if (iter != inputDirs.end()) { inputDirs.erase(iter); } // Insert this directory at the beginning of the search path inputDirs.insert(inputDirs.begin(), d); } std::string Application::findInputFile(const std::string& name) { std::unique_lock<std::mutex> dirLock(dir_mutex); string::size_type islash = name.find('/'); string::size_type ibslash = name.find('\\'); string inname; std::vector<string>& dirs = inputDirs; // Expand "~/" to user's home directory, if possible if (name.find("~/") == 0) { char* home = getenv("HOME"); // POSIX systems if (!home) { home = getenv("USERPROFILE"); // Windows systems } if (home) { return home + name.substr(1, npos); } } if (islash == string::npos && ibslash == string::npos) { size_t nd = dirs.size(); inname = ""; for (size_t i = 0; i < nd; i++) { inname = dirs[i] + "/" + name; std::ifstream fin(inname); if (fin) { return inname; } } string msg; msg = "\nInput file " + name + " not found in director"; msg += (nd == 1 ? "y " : "ies "); for (size_t i = 0; i < nd; i++) { msg += "\n'" + dirs[i] + "'"; if (i+1 < nd) { msg += ", "; } } msg += "\n\n"; msg += "To fix this problem, either:\n"; msg += " a) move the missing files into the local directory;\n"; msg += " b) define environment variable CANTERA_DATA to\n"; msg += " point to the directory containing the file."; throw CanteraError("findInputFile", msg); } return name; } Application* Application::s_app = 0; } // namespace Cantera
//! @file application.cpp #include "application.h" #include "cantera/base/ctml.h" #include "cantera/base/stringUtils.h" #include "units.h" #include <fstream> #include <sstream> #include <mutex> using std::string; using std::endl; #ifdef _WIN32 #include <windows.h> #else #include <sys/stat.h> #endif #ifdef _MSC_VER #pragma comment(lib, "advapi32") #endif namespace Cantera { //! Mutex for input directory access static std::mutex dir_mutex; //! Mutex for creating singletons within the application object static std::mutex app_mutex; //! Mutex for controlling access to XML file storage static std::mutex xml_mutex; static int get_modified_time(const std::string& path) { #ifdef _WIN32 HANDLE hFile = CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) { throw CanteraError("get_modified_time", "Couldn't open file:" + path); } FILETIME modified; GetFileTime(hFile, NULL, NULL, &modified); CloseHandle(hFile); return static_cast<int>(modified.dwLowDateTime); #else struct stat attrib; stat(path.c_str(), &attrib); return static_cast<int>(attrib.st_mtime); #endif } Application::Messages::Messages() { // install a default logwriter that writes to standard // output / standard error logwriter.reset(new Logger()); } Application::Messages::Messages(const Messages& r) : errorMessage(r.errorMessage) { // install a default logwriter that writes to standard // output / standard error logwriter.reset(new Logger(*r.logwriter)); } Application::Messages& Application::Messages::operator=(const Messages& r) { if (this == &r) { return *this; } errorMessage = r.errorMessage; logwriter.reset(new Logger(*r.logwriter)); return *this; } void Application::Messages::addError(const std::string& r, const std::string& msg) { if (msg.size() != 0) { errorMessage.push_back( "\n\n************************************************\n" " Cantera Error! \n" "************************************************\n\n" "Procedure: " + r + "\nError: " + msg + "\n"); } else { errorMessage.push_back(r); } } int Application::Messages::getErrorCount() { return static_cast<int>(errorMessage.size()); } void Application::Messages::setLogger(Logger* _logwriter) { logwriter.reset(_logwriter); } void Application::Messages::writelog(const std::string& msg) { logwriter->write(msg); } void Application::Messages::writelogendl() { logwriter->writeendl(); } //! Mutex for access to string messages static std::mutex msg_mutex; Application::Messages* Application::ThreadMessages::operator ->() { std::unique_lock<std::mutex> msgLock(msg_mutex); std::thread::id curId = std::this_thread::get_id(); auto iter = m_threadMsgMap.find(curId); if (iter != m_threadMsgMap.end()) { return iter->second.get(); } pMessages_t pMsgs(new Messages()); m_threadMsgMap.insert({curId, pMsgs}); return pMsgs.get(); } void Application::ThreadMessages::removeThreadMessages() { std::unique_lock<std::mutex> msgLock(msg_mutex); std::thread::id curId = std::this_thread::get_id(); auto iter = m_threadMsgMap.find(curId); if (iter != m_threadMsgMap.end()) { m_threadMsgMap.erase(iter); } } Application::Application() : m_suppress_deprecation_warnings(false) { // install a default logwriter that writes to standard // output / standard error setDefaultDirectories(); Unit::units(); } Application* Application::Instance() { std::unique_lock<std::mutex> appLock(app_mutex); if (Application::s_app == 0) { Application::s_app = new Application(); } return s_app; } Application::~Application() { for (auto& f : xmlfiles) { f.second.first->unlock(); delete f.second.first; f.second.first = 0; } } void Application::ApplicationDestroy() { std::unique_lock<std::mutex> appLock(app_mutex); if (Application::s_app != 0) { delete Application::s_app; Application::s_app = 0; } } void Application::warn_deprecated(const std::string& method, const std::string& extra) { if (m_suppress_deprecation_warnings || warnings.count(method)) { return; } warnings.insert(method); writelog("WARNING: '" + method + "' is deprecated. " + extra); writelogendl(); } void Application::thread_complete() { pMessenger.removeThreadMessages(); } XML_Node* Application::get_XML_File(const std::string& file, int debug) { std::unique_lock<std::mutex> xmlLock(xml_mutex); std::string path = ""; path = findInputFile(file); int mtime = get_modified_time(path); if (xmlfiles.find(path) != xmlfiles.end()) { // Already have a parsed XML tree for this file cached. Check the // last-modified time. std::pair<XML_Node*, int> cache = xmlfiles[path]; if (cache.second == mtime) { return cache.first; } } // Check whether or not the file is XML (based on the file extension). If // not, it will be first processed with the preprocessor. string::size_type idot = path.rfind('.'); string ext; if (idot != string::npos) { ext = path.substr(idot, path.size()); } else { ext = ""; } XML_Node* x = new XML_Node("doc"); if (ext != ".xml" && ext != ".ctml") { // Assume that we are trying to open a cti file. Do the conversion to XML. std::stringstream phase_xml(ct2ctml_string(path)); x->build(phase_xml); } else { std::ifstream s(path.c_str()); if (s) { x->build(s); } else { throw CanteraError("get_XML_File", "cannot open "+file+" for reading.\n" "Note, this error indicates a possible configuration problem."); } } x->lock(); xmlfiles[path] = {x, mtime}; return x; } XML_Node* Application::get_XML_from_string(const std::string& text) { std::unique_lock<std::mutex> xmlLock(xml_mutex); std::pair<XML_Node*, int>& entry = xmlfiles[text]; if (entry.first) { // Return existing cached XML tree return entry.first; } std::stringstream s; size_t start = text.find_first_not_of(" \t\r\n"); if (text.substr(start,1) == "<") { s << text; } else { s << ct_string2ctml_string(text.substr(start)); } entry.first = new XML_Node(); entry.first->build(s); return entry.first; } void Application::close_XML_File(const std::string& file) { std::unique_lock<std::mutex> xmlLock(xml_mutex); if (file == "all") { for (const auto& f : xmlfiles) { f.second.first->unlock(); delete f.second.first; } xmlfiles.clear(); } else if (xmlfiles.find(file) != xmlfiles.end()) { xmlfiles[file].first->unlock(); delete xmlfiles[file].first; xmlfiles.erase(file); } } #ifdef _WIN32 long int Application::readStringRegistryKey(const std::string& keyName, const std::string& valueName, std::string& value, const std::string& defaultValue) { HKEY key; long open_error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName.c_str(), 0, KEY_READ, &key); if (open_error != ERROR_SUCCESS) { return open_error; } value = defaultValue; CHAR buffer[1024]; DWORD bufferSize = sizeof(buffer); ULONG error; error = RegQueryValueEx(key, valueName.c_str(), 0, NULL, (LPBYTE) buffer, &bufferSize); if (ERROR_SUCCESS == error) { value = buffer; } RegCloseKey(key); return error; } #endif void Application::Messages::popError() { if (!errorMessage.empty()) { errorMessage.pop_back(); } } std::string Application::Messages::lastErrorMessage() { if (!errorMessage.empty()) { return errorMessage.back(); } else { return "<no Cantera error>"; } } void Application::Messages::getErrors(std::ostream& f) { for (size_t j = 0; j < errorMessage.size(); j++) { f << errorMessage[j] << endl; } errorMessage.clear(); } void Application::Messages::logErrors() { for (size_t j = 0; j < errorMessage.size(); j++) { writelog(errorMessage[j]); writelogendl(); } errorMessage.clear(); } void Application::setDefaultDirectories() { std::vector<string>& dirs = inputDirs; // always look in the local directory first dirs.push_back("."); #ifdef _WIN32 // Under Windows, the Cantera setup utility records the installation // directory in the registry. Data files are stored in the 'data' // subdirectory of the main installation directory. std::string installDir; readStringRegistryKey("SOFTWARE\\Cantera\\Cantera " CANTERA_SHORT_VERSION, "InstallDir", installDir, ""); if (installDir != "") { dirs.push_back(installDir + "data"); // Scripts for converting mechanisms to CTI and CMTL are installed in // the 'bin' subdirectory. Add that directory to the PYTHONPATH. const char* old_pythonpath = getenv("PYTHONPATH"); std::string pythonpath = "PYTHONPATH=" + installDir + "\\bin"; if (old_pythonpath) { pythonpath += ";"; pythonpath.append(old_pythonpath); } putenv(pythonpath.c_str()); } #endif #ifdef DARWIN // add a default data location for Mac OS X dirs.push_back("/Applications/Cantera/data"); #endif // if environment variable CANTERA_DATA is defined, then add it to the // search path. CANTERA_DATA may include multiple directory, separated by // the OS-dependent path separator (in the same manner as the PATH // environment variable). #ifdef _WIN32 std::string pathsep = ";"; #else std::string pathsep = ":"; #endif if (getenv("CANTERA_DATA") != 0) { string s = string(getenv("CANTERA_DATA")); size_t start = 0; size_t end = s.find(pathsep); while(end != npos) { dirs.push_back(s.substr(start, end-start)); start = end + 1; end = s.find(pathsep, start); } dirs.push_back(s.substr(start,end)); } // CANTERA_DATA is defined in file config.h. This file is written during the // build process (unix), and points to the directory specified by the // 'prefix' option to 'configure', or else to /usr/local/cantera. #ifdef CANTERA_DATA string datadir = string(CANTERA_DATA); dirs.push_back(datadir); #endif } void Application::addDataDirectory(const std::string& dir) { std::unique_lock<std::mutex> dirLock(dir_mutex); if (inputDirs.empty()) { setDefaultDirectories(); } string d = stripnonprint(dir); // Remove any existing entry for this directory auto iter = std::find(inputDirs.begin(), inputDirs.end(), d); if (iter != inputDirs.end()) { inputDirs.erase(iter); } // Insert this directory at the beginning of the search path inputDirs.insert(inputDirs.begin(), d); } std::string Application::findInputFile(const std::string& name) { std::unique_lock<std::mutex> dirLock(dir_mutex); string::size_type islash = name.find('/'); string::size_type ibslash = name.find('\\'); string inname; std::vector<string>& dirs = inputDirs; // Expand "~/" to user's home directory, if possible if (name.find("~/") == 0) { char* home = getenv("HOME"); // POSIX systems if (!home) { home = getenv("USERPROFILE"); // Windows systems } if (home) { return home + name.substr(1, npos); } } if (islash == string::npos && ibslash == string::npos) { size_t nd = dirs.size(); inname = ""; for (size_t i = 0; i < nd; i++) { inname = dirs[i] + "/" + name; std::ifstream fin(inname); if (fin) { return inname; } } string msg; msg = "\nInput file " + name + " not found in director"; msg += (nd == 1 ? "y " : "ies "); for (size_t i = 0; i < nd; i++) { msg += "\n'" + dirs[i] + "'"; if (i+1 < nd) { msg += ", "; } } msg += "\n\n"; msg += "To fix this problem, either:\n"; msg += " a) move the missing files into the local directory;\n"; msg += " b) define environment variable CANTERA_DATA to\n"; msg += " point to the directory containing the file."; throw CanteraError("findInputFile", msg); } return name; } Application* Application::s_app = 0; } // namespace Cantera
Fix printing of error messages
[Matlab] Fix printing of error messages
C++
bsd-3-clause
imitrichev/cantera,imitrichev/cantera,imitrichev/cantera,imitrichev/cantera,imitrichev/cantera,imitrichev/cantera
72c5d8abec7baf282dafb89663045a9414a71be3
example/DemoLevel.hpp
example/DemoLevel.hpp
#pragma once #include <Annwvyn.h> #include <memory> #include "DemoUtils.hpp" using namespace Annwvyn; //Hub to select Demos class DemoHub : LEVEL, LISTENER { public: DemoHub() : constructLevel(), constructListener(), panelDpi(18) { } ~DemoHub() { AnnDebug() << "Demo hub destructed!"; } void load() override { //Register ourselves as event listener AnnGetEventManager()->addListener(getSharedListener()); //Add static geometry auto Ground = addGameObject("floorplane.mesh"); Ground->setUpPhysics(); auto StoneDemo0 = addGameObject("DemoStone.mesh"); StoneDemo0->setPosition({ -3, 0, -5 }); StoneDemo0->setOrientation(AnnQuaternion(AnnDegree(45), AnnVect3::UNIT_Y)); StoneDemo0->setUpPhysics(); auto TextPane = std::make_shared<Ann3DTextPlane>(2.f, 1.f, "Demo 0\nDemo the loading of a demo... xD", 512, panelDpi); TextPane->setTextAlign(Ann3DTextPlane::ALIGN_CENTER); TextPane->setTextColor(AnnColor{ 0, 0, 0 }); TextPane->setPosition(StoneDemo0->getPosition() + StoneDemo0->getOrientation()* AnnVect3 { 0, 2, -0.35 }); TextPane->setOrientation(StoneDemo0->getOrientation()); TextPane->update(); addManualMovableObject(TextPane); auto Demo0Trigger = std::static_pointer_cast<AnnSphericalTriggerObject>(addTrggerObject()); Demo0Trigger->setThreshold(1.5f); Demo0Trigger->setPosition(StoneDemo0->getPosition() + AnnVect3(0, 0.5f, 0)); demo0trig = Demo0Trigger; auto StoneTestLevel = addGameObject("DemoStone.mesh"); StoneTestLevel->setPosition({ +3, 0, -5 }); StoneTestLevel->setOrientation(AnnQuaternion(AnnDegree(-45), AnnVect3::UNIT_Y)); StoneTestLevel->setUpPhysics(); auto TestLevelText = std::make_shared<Ann3DTextPlane>(2.f, 1.f, "TestLevel\nA simple test level", 512, panelDpi); TestLevelText->setTextAlign(Ann3DTextPlane::ALIGN_CENTER); TestLevelText->setTextColor(AnnColor{ 0, 0, 0 }); TestLevelText->setPosition(StoneTestLevel->getPosition() + StoneTestLevel->getOrientation()* AnnVect3 { 0, 2, -0.35 }); TestLevelText->setOrientation(StoneTestLevel->getOrientation()); TestLevelText->update(); addManualMovableObject(TestLevelText); auto TestLevelTrigger = std::static_pointer_cast<AnnSphericalTriggerObject>(addTrggerObject()); TestLevelTrigger->setThreshold(1.5f); TestLevelTrigger->setPosition(StoneTestLevel->getPosition() + AnnVect3(0, 0.5f, 0)); testLevelTrig = TestLevelTrigger; auto Sun = addLightObject(); Sun->setType(AnnLightObject::ANN_LIGHT_DIRECTIONAL); Sun->setDirection({ 0, -1, -0.5 }); AnnGetSceneryManager()->setAmbientLight(AnnColor(0.15f, 0.15f, 0.15f)); AnnGetPlayer()->teleport({ 0, 5, 0 }, 0); AnnDebug() << "Ground Level is : " << Ground->getPosition().y; AnnGetPlayer()->regroundOnPhysicsBody(); } //Called at each frame void runLogic() override { //auto povPos{ AnnGetEngine()->getPlayerPovNode()->getPosition() }; //auto headPos{ AnnGetVRRenderer()->trackedHeadPose.position }; //AnnDebug() << "player pov node position" << povPos; //AnnDebug() << "headset Position " << headPos; //AnnDebug() << "y offset : " << headPos.y - povPos.y; for (auto i : { 0,1 }) if (auto controller = AnnGetVRRenderer()->getHandControllerArray()[i]) controller->rumbleStop(); } void unload() override { //Unregister the listener AnnGetEventManager()->removeListener(getSharedListener()); AnnLevel::unload(); } void TriggerEvent(AnnTriggerEvent e) override { if (e.getContactStatus()) jumpToLevelTriggeredBy(e.getSender()); } void jumpToLevelTriggeredBy(AnnTriggerObject* trigger) const { if (demo0trig.get() == trigger) { AnnGetLevelManager()->jump(getDemo(0)); return; } if (testLevelTrig.get() == trigger) { AnnGetLevelManager()->jump(getDemo(1)); } } static level_id getDemo(level_id id) { return 1 + id; } private: std::shared_ptr<AnnTriggerObject> demo0trig; std::shared_ptr<AnnTriggerObject> testLevelTrig; float panelDpi; }; class Demo0 : LEVEL { public: Demo0() : constructLevel() { } void load() override { AnnGetEventManager()->addListener(goBackListener = std::make_shared<GoBackToDemoHub>()); auto Ground = addGameObject("Ground.mesh"); Ground->setUpPhysics(); auto MyObject = addGameObject("MyObject.mesh"); MyObject->setPosition({ 0, 1, -5 }); MyObject->setUpPhysics(200, convexShape); auto objectQueryFromNode = AnnGetGameObjectManager()->getFromNode(MyObject->getNode()); auto Sun = addLightObject(); Sun->setType(AnnLightObject::ANN_LIGHT_DIRECTIONAL); Sun->setDirection({ 0, 1, -0.75 }); AnnGetPlayer()->teleport({ 0, 1, 0 }, 0); } void unload() override { AnnGetEventManager()->removeListener(goBackListener); goBackListener.reset(); AnnLevel::unload(); } void triggerEventCallback(AnnTriggerEvent e) { } void runLogic() override { for(auto controller : AnnGetVRRenderer()->getHandControllerArray()) if(controller) controller->rumbleStart(1); /* auto object = AnnGetGameObjectManager()->playerLookingAt(); if (object) { AnnDebug() << "looking at " << object->getName(); } else { AnnDebug() << "No object"; } */ } private: std::shared_ptr<GoBackToDemoHub> goBackListener; };
#pragma once #include <Annwvyn.h> #include <memory> #include "DemoUtils.hpp" using namespace Annwvyn; //Hub to select Demos class DemoHub : LEVEL, LISTENER { public: DemoHub() : constructLevel(), constructListener(), panelDpi(18) { } ~DemoHub() { AnnDebug() << "Demo hub destructed!"; } void load() override { //Register ourselves as event listener AnnGetEventManager()->addListener(getSharedListener()); //Add static geometry auto Ground = addGameObject("floorplane.mesh"); Ground->setUpPhysics(); auto StoneDemo0 = addGameObject("DemoStone.mesh"); StoneDemo0->setPosition({ -3, 0, -5 }); StoneDemo0->setOrientation(AnnQuaternion(AnnDegree(45), AnnVect3::UNIT_Y)); StoneDemo0->setUpPhysics(); auto TextPane = std::make_shared<Ann3DTextPlane>(2.f, 1.f, "Demo 0\nDemo the loading of a demo... xD", 512, panelDpi); TextPane->setTextAlign(Ann3DTextPlane::ALIGN_CENTER); TextPane->setTextColor(AnnColor{ 0, 0, 0 }); TextPane->setPosition(StoneDemo0->getPosition() + StoneDemo0->getOrientation()* AnnVect3 { 0, 2, -0.35 }); TextPane->setOrientation(StoneDemo0->getOrientation()); TextPane->update(); addManualMovableObject(TextPane); auto Demo0Trigger = std::static_pointer_cast<AnnSphericalTriggerObject>(addTrggerObject()); Demo0Trigger->setThreshold(1.5f); Demo0Trigger->setPosition(StoneDemo0->getPosition() + AnnVect3(0, 0.5f, 0)); demo0trig = Demo0Trigger; auto StoneTestLevel = addGameObject("DemoStone.mesh"); StoneTestLevel->setPosition({ +3, 0, -5 }); StoneTestLevel->setOrientation(AnnQuaternion(AnnDegree(-45), AnnVect3::UNIT_Y)); StoneTestLevel->setUpPhysics(); auto TestLevelText = std::make_shared<Ann3DTextPlane>(2.f, 1.f, "TestLevel\nA simple test level", 512, panelDpi); TestLevelText->setTextAlign(Ann3DTextPlane::ALIGN_CENTER); TestLevelText->setTextColor(AnnColor{ 0, 0, 0 }); TestLevelText->setPosition(StoneTestLevel->getPosition() + StoneTestLevel->getOrientation()* AnnVect3 { 0, 2, -0.35 }); TestLevelText->setOrientation(StoneTestLevel->getOrientation()); TestLevelText->update(); addManualMovableObject(TestLevelText); auto TestLevelTrigger = std::static_pointer_cast<AnnSphericalTriggerObject>(addTrggerObject()); TestLevelTrigger->setThreshold(1.5f); TestLevelTrigger->setPosition(StoneTestLevel->getPosition() + AnnVect3(0, 0.5f, 0)); testLevelTrig = TestLevelTrigger; auto Sun = addLightObject(); Sun->setType(AnnLightObject::ANN_LIGHT_DIRECTIONAL); Sun->setDirection({ 0, -1, -0.5 }); AnnGetSceneryManager()->setAmbientLight(AnnColor(0.15f, 0.15f, 0.15f)); AnnGetPlayer()->teleport({ 0, 5, 0 }, 0); AnnDebug() << "Ground Level is : " << Ground->getPosition().y; AnnGetPlayer()->regroundOnPhysicsBody(); } //Called at each frame void runLogic() override { //auto povPos{ AnnGetEngine()->getPlayerPovNode()->getPosition() }; //auto headPos{ AnnGetVRRenderer()->trackedHeadPose.position }; //AnnDebug() << "player pov node position" << povPos; //AnnDebug() << "headset Position " << headPos; //AnnDebug() << "y offset : " << headPos.y - povPos.y; for (auto i : { 0,1 }) if (auto controller = AnnGetVRRenderer()->getHandControllerArray()[i]) controller->rumbleStop(); } void unload() override { //Unregister the listener AnnGetEventManager()->removeListener(getSharedListener()); AnnLevel::unload(); } void TriggerEvent(AnnTriggerEvent e) override { if (e.getContactStatus()) jumpToLevelTriggeredBy(e.getSender()); } void jumpToLevelTriggeredBy(AnnTriggerObject* trigger) const { if (demo0trig.get() == trigger) { AnnGetLevelManager()->jump(getDemo(0)); return; } if (testLevelTrig.get() == trigger) { AnnGetLevelManager()->jump(getDemo(1)); } } static level_id getDemo(level_id id) { return 1 + id; } private: std::shared_ptr<AnnTriggerObject> demo0trig; std::shared_ptr<AnnTriggerObject> testLevelTrig; float panelDpi; }; class Demo0 : LEVEL { public: Demo0() : constructLevel() { } void load() override { AnnGetEventManager()->addListener(goBackListener = std::make_shared<GoBackToDemoHub>()); auto Ground = addGameObject("Ground.mesh"); Ground->setUpPhysics(); auto MyObject = addGameObject("MyObject.mesh", "MyObject"); MyObject->setPosition({ 0, 1, -5 }); MyObject->setUpPhysics(200, convexShape); auto objectQueryFromNode = AnnGetGameObjectManager()->getFromNode(MyObject->getNode()); auto Sun = addLightObject(); Sun->setType(AnnLightObject::ANN_LIGHT_DIRECTIONAL); Sun->setDirection({ 0, 1, -0.75 }); AnnGetPlayer()->teleport({ 0, 1, 0 }, 0); } void unload() override { AnnGetEventManager()->removeListener(goBackListener); goBackListener.reset(); AnnLevel::unload(); } void triggerEventCallback(AnnTriggerEvent e) { } void runLogic() override { for (auto controller : AnnGetVRRenderer()->getHandControllerArray()) if (controller) controller->rumbleStart(1); /* auto object = AnnGetGameObjectManager()->playerLookingAt(); if (object) { AnnDebug() << "looking at " << object->getName(); } else { AnnDebug() << "No object"; } */ } private: std::shared_ptr<GoBackToDemoHub> goBackListener; };
set object name
set object name
C++
mit
Ybalrid/Annwvyn,Ybalrid/Annwvyn,Ybalrid/Annwvyn
9caf35aa3574cd0f1c02965c7e75247304aedb9b
SimModule/Geo.cpp
SimModule/Geo.cpp
#include "Geo.h" #include <iostream> #include <cmath> //-----------------POINT--------------------------------------------- Point::Point() { x=y=z=0; } Point::Point(double xc,double yc, double zc) { x=xc; y=yc; z=zc; } Point::~Point() {} //Accessors--------------------------------------------------------------- double Point::getX() { return x; } double Point::getY() { return y; } double Point::getZ() { return z; } //Display------------------------------------------------------------------- void Point::show() { std::cout<<"x:"<<x<<'\n'<<"y:"<<y<<'\n'<<"z:"<<z<<'\n'; } //Modifier------------------------------------------------------------------- void Point::place(double xe,double ye, double ze) //** { x=xe; y=ye; z=ze; } void Point::nullify() //** { x=y=z=0; } //Algebraic operator------------------------------------------------------------- Point Point::operator +( Point B ) // Coordinates addition { Point P; P.place(x + B.x, y + B.y, z + B.z); return P; } Point Point::operator *( double a) //multiplication by a scalar { Point P; P.place(x*a , y*a, z*a); return P; } Point Point::operator /( double a) //scalar division ** { Point P; P.place(x/a, y/a, z/a); return P; } //.................................End Point...................................... //================================================================================ //================================================================================ //----------------------------------- Vector ------------------------------------- //constructors and destructor Vector::Vector() {} Vector::Vector( double x, double y, double z) { xcomp=x; ycomp=y; zcomp=z; } Vector::~Vector() {} //--------------------Accessors------------------------------- double Vector::getx() {return xcomp;} double Vector::gety() {return ycomp;} double Vector::getz() {return zcomp;} //Modifiers---------------------------------------------------- void Vector::setVector( double x, double y, double z) { xcomp=x; ycomp=y; zcomp=z; } void Vector::setVector( Vector C) { xcomp=C.getx(); ycomp=C.gety(); zcomp=C.getz(); } void Vector::nullify() { setVector(0,0,0); } void Vector::show() { std::cout<<" x: "<<xcomp <<'\n'; std::cout<<" y: "<<ycomp <<'\n'; std::cout<<" z: "<<zcomp <<'\n'; } //Operators definition--------------------------------------------------------- Vector Vector::operator +( Vector &B ) {Vector v; v.xcomp=xcomp+B.xcomp; v.ycomp=ycomp+B.ycomp; v.zcomp=zcomp+B.zcomp; return v; } Vector Vector::operator ^( Vector &B ) //produit vectoriel {Vector v; v.xcomp= ycomp*B.zcomp-zcomp*B.ycomp; v.ycomp= zcomp*B.xcomp-xcomp*B.zcomp; v.zcomp= xcomp*B.ycomp-ycomp*B.xcomp; return v; } Vector Vector::operator * (double a) //multiplication by a scalar {Vector v; v.xcomp=a*xcomp; v.ycomp=a*ycomp; v.zcomp=a*zcomp; return v; } double Vector::operator *(Vector &B) //dot product { double s; s=xcomp*B.xcomp+ycomp*B.ycomp+zcomp*B.zcomp; return s; } //derived values Vector Vector::unitarized() { Vector u; double sq= *this * (*this); sq=sqrt(sq); u.setVector(getx()/sq,gety()/sq,getz()/sq); return u; }
#include "Geo.h" #include <iostream> #include <cmath> //----------------------------- Cartesian element ------------------------------------ CartesianElement::CartesianElement() { X = Y = Z = 0; } CartesianElement::CartesianElement(double x, double y, double z) { X = x; Y = y; Z = z; } CartesianElement::~CartesianElement(){} //accessor double CartesianElement::getX() { return X; } //** double double CartesianElement::getY() { return Y; } //** double CartesianElement::getZ() { return Z; } //** //Display void CartesianElement::show() { std::cout << "x:" << X << '\n' << "y:" << Y << '\n' << "z:" << Z << '\n'; } //Modifier void CartesianElement::set(double x, double y, double z) // place the point a the coordinates (x,y,z) ** { X = x; Y = y; Z = z; } void CartesianElement::set(CartesianElement C) { X = C.X; Y = C.Y; Z = C.Z; } void CartesianElement::nullify() // set the point at the origin, to use as initializer ** { X = Y = Z = 0; } //Algebraic operator CartesianElement CartesianElement ::operator +(CartesianElement B) { CartesianElement C(X + B.X, Y + B.Y, Z + B.Z); return C; } CartesianElement CartesianElement ::operator -() { CartesianElement C; C.X = -X; C.Y = -Y; C.Z = -Z; return C; } CartesianElement CartesianElement ::operator *(double a) //multiplication by a scalar { CartesianElement C(X *a, Y *a, Z *a); return C; } CartesianElement CartesianElement ::operator /(double a) //division by a scalar ** { CartesianElement C; if (a == 0) { C.nullify(); throw "divideByZero"; } C.set(X / a, Y / a, Z / a); return C; } //logical operator bool CartesianElement ::operator ==(CartesianElement B) { return (X == B.X) && (Y == B.Y) && (Z == B.Z); } //-------------------------------------------------------------------------------------------------- //-----------------POINT------------------------------------------------------------------------------ Point::Point() {} Point::Point(double x,double y, double z):CartesianElement(x,y,z) {/*that's pretty it*/} Point::Point(CartesianElement C) { set(C); } Point::Point(Vect V) //creates a point at the end of the instance of V starting at the origin { set(V); } Point::Point(Point P, Vect V) //creates a point at the end of the instance of V starting at point P { set(P + V); } Point::~Point() {} //.................................End Point...................................... //================================================================================ //================================================================================ //----------------------------------- Vect ------------------------------------- //constructors and destructor Vect::Vect() {} Vect::Vect(double x, double y, double z) :CartesianElement(x, y, z) {/*that's pretty it*/} Vect::Vect(CartesianElement C) { set(C); } Vect::Vect(Point P) { set(P); } Vect::Vect(Point start, Point end) { set(end + (-start)); } Vect::~Vect() {} Vect Vect::operator ^( Vect &B ) //produit Vectiel { double x, y, z; x = getY()*B.getZ()- getZ()*B.getY(); y = getZ()*B.getX() - getX()*B.getZ(); z = getX()*B.getY() - getY()*B.getX(); Vect v(x, y, z); return v; } double Vect::operator *(Vect &B) //dot product { double s; s= getX()*B.getX() + getY()*B.getY() + getZ()*B.getZ(); return s; } //derived values double Vect::norm() { double sq = *this * (*this); sq = sqrt(sq); return sq; } Vect Vect::unitarized() { Vect u; u = (*this) / norm(); return u; }
Update Geo.cpp
Update Geo.cpp
C++
mit
doplusplus/PointSimulator,doplusplus/Physics_Simulator,doplusplus/Physics_Simulator,doplusplus/PointSimulator,doplusplus/Physics_Simulator
3cb7a4e04ec13066890c24c73f9d62c943648285
Socket/Socket.hpp
Socket/Socket.hpp
#ifndef SOCKET_HPP #define SOCKET_HPP #ifdef _WIN32 //_WIN64 #include <winsock2.h> #elif __linux //|| __unix //or __APPLE__ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> /* close */ #include <netdb.h> /* gethostbyname */ #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define closesocket(s) close(s) typedef int SOCKET; typedef struct sockaddr_in SOCKADDR_IN; typedef struct sockaddr SOCKADDR; typedef struct in_addr IN_ADDR; #else #error not defined for this platform #endif #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string> #include <exception> #define CRLF "\r\n" #define BUF_SIZE 1024 #define PORT 3987 namespace ntw { class SocketExeption: public std::exception { public: SocketExeption(std::string error) : msg(error) {}; ~SocketExeption() throw() {}; virtual const char* what() const throw() { return msg.c_str(); }; private: std::string msg; }; class SocketSerialized; class Socket { public: static int max_id; enum Dommaine {IP=AF_INET, LOCAL=AF_UNIX}; enum Type {TCP=SOCK_STREAM, UDP=SOCK_DGRAM}; enum Down {SEND=0,RECIVE=1,BOTH=2}; Socket(Dommaine dommaine,Type type,int protocole=0); ~Socket(); Socket& operator=(const Socket&) = delete; const SOCKET Id(){return sock;} void Connect(std::string host,int port=PORT); void Bind(); void Listen(const int max_connexion); void ServeurMode(const int max_connexion=5,std::string host="",int port=PORT);//init sock_cfg + bind + listen Socket Accept(); void Accept(Socket& client); void Shutdown(Down mode=Down::BOTH); template<typename T> inline void Send(const T* data,const size_t size,const int flags=0) const { if(send(sock,data,size,flags) == SOCKET_ERROR) { perror("Send()"); throw SocketExeption("Sending message fail"); } } template<typename T> inline int Receive(T* buffer,const size_t size,const int flags=0) const { return recv(sock,buffer,size,flags); }; protected: friend class SocketSerialized; Socket();// intern use only; inline void _close(){if(sock != INVALID_SOCKET)closesocket(sock);}; //socket SOCKET sock; //configuration SOCKADDR_IN sock_cfg; }; }; #endif
#ifndef SOCKET_HPP #define SOCKET_HPP #ifdef _WIN32 //_WIN64 #include <winsock2.h> #elif __linux //|| __unix //or __APPLE__ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> /* close */ #include <netdb.h> /* gethostbyname */ #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define closesocket(s) close(s) typedef int SOCKET; typedef struct sockaddr_in SOCKADDR_IN; typedef struct sockaddr SOCKADDR; typedef struct in_addr IN_ADDR; #else #error not defined for this platform #endif #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string> #include <exception> #define CRLF "\r\n" #define BUF_SIZE 1024 #define NTW_PORT 3987 namespace ntw { class SocketExeption: public std::exception { public: SocketExeption(std::string error) : msg(error) {}; ~SocketExeption() throw() {}; virtual const char* what() const throw() { return msg.c_str(); }; private: std::string msg; }; class SocketSerialized; class Socket { public: static int max_id; enum Dommaine {IP=AF_INET, LOCAL=AF_UNIX}; enum Type {TCP=SOCK_STREAM, UDP=SOCK_DGRAM}; enum Down {SEND=0,RECIVE=1,BOTH=2}; Socket(Dommaine dommaine,Type type,int protocole=0); ~Socket(); Socket& operator=(const Socket&) = delete; const SOCKET Id(){return sock;} void Connect(std::string host,int port=NTW_PORT); void Bind(); void Listen(const int max_connexion); void ServeurMode(const int max_connexion=5,std::string host="",int port=NTW_PORT);//init sock_cfg + bind + listen Socket Accept(); void Accept(Socket& client); void Shutdown(Down mode=Down::BOTH); template<typename T> inline void Send(const T* data,const size_t size,const int flags=0) const { if(send(sock,data,size,flags) == SOCKET_ERROR) { perror("Send()"); throw SocketExeption("Sending message fail"); } } template<typename T> inline int Receive(T* buffer,const size_t size,const int flags=0) const { return recv(sock,buffer,size,flags); }; protected: friend class SocketSerialized; Socket();// intern use only; inline void _close(){if(sock != INVALID_SOCKET)closesocket(sock);}; //socket SOCKET sock; //configuration SOCKADDR_IN sock_cfg; }; }; #endif
add namspace on PORT
add namspace on PORT
C++
bsd-2-clause
Krozark/cpp-Socket
6b3fe0262981f67b4bc9256f478bc85b15be96db
sources/parser.cpp
sources/parser.cpp
#include "parser.h" #include "stdio.h" #undef DEBUG Parser::Parser( ) { // TODO: Set up all the functions/variables... :-S }; Parser::~Parser( ) { }; int Parser::runParse( ) { std::string file; this->running = true; while( 1 ){ printf( "Program? -> " ); std::cin >> file; std::transform(file.begin(), file.end(), file.begin(), ::tolower); if( file.compare( std::string( "exit" ) ) == 0 ){ exit( 0 ); } else if( file.compare( std::string( "load" ) ) == 0 ){ std::cin >> file; // TODO: RESET if( this->openFile( file ) == -1 ){ printf( "Could not open file %s\n", file.c_str() ); } } else if( file.compare( std::string( "run" ) ) == 0 ){ // TODO: runProg() } else if( file.compare( std::string( "clear" ) ) == 0 ){ // TODO: reset() } else if( file.compare( std::string( "list" ) ) == 0 ){ // TODO: for each line, print the line } else if( file.compare( std::string( "help" ) ) == 0 ){ printf( "Commands: EXIT, LOAD, RUN, CLEAR, LIST, HELP\n" ); } } return 0; }; void Parser::reset( ) { this->file.close( ); while( ! this->vStack.empty( ) ) this->vStack.pop( ); this->cStack.erase( this->cStack.begin( ), this->cStack.end( ) ); // TODO: CLEAR ALL VARIABLES }; int Parser::openFile( std::string& filename ){ #ifdef DEBUG char buf[ 12 ]; #endif char fchar; bool mark = true; // Save filename this->filename = filename; // Open the file, debug print // MSVC 2008 DOESNT SUPPORT C++11 OH MY GAWD this->file.open( this->filename.c_str( ), std::fstream::in ); #ifdef DEBUG printf( "%d\n", this->file.is_open( ) == true ? 1 : 0 ); #endif if( ! this->file.is_open( ) ) return -1; // Get line starts this->linestarts.clear( ); this->linestarts.push_back( 0 ); this->file.get(fchar); while( !this->file.eof() ){ if( mark && fchar != 13 ){ mark = false; this->linestarts.push_back( (unsigned short) this->file.tellg( ) - 1 ); } if( fchar == 10 ){ mark = true; } this->file.get( fchar ); } // Reset the file after eof // NOTE: TEST THIS, ITS POSSIBLY A WINDOWS ONLY THING :( this->file.clear( ); #ifdef DEBUG for( unsigned i = 1; i < this->linestarts.size(); ++i ){ this->file.seekg( this->linestarts[ i ], this->file.beg ); this->file.get( buf, 12 ); if( this->file.rdstate( ) == this->file.goodbit ){ printf( "Line: %d\nPosition: %d\n-> %s\n", i, this->linestarts[ i ], buf ); } else { printf( "FAILURE reading line: %d ->%d%d%d%d\n", i, (this->file.good())?1:0, (this->file.eof())?1:0, (this->file.fail())?1:0, (this->file.bad())?1:0 ); } } #endif // Return line count return this->linestarts.size( ); }; int Parser::runFile( ) { // TODO: This is the python function runProg(...) // while true: // if line number is out of bounds, exit good // try to parseLine a line // catch and print syntax errors // if running false // break // else // increment line counter return 0; }; int Parser::parseLine( unsigned linenum ) { // TODO: This is the python function parseRPN(...) // getline the line // while not endofline // line >> oper // seach cStack for if // -1 if not one, index else // if index -1, branch is true, or is ELSE or is ENDIF // check operator list for oper // run if in // check variable list for oper // add to stack if in // check for float conversion // add to stack if in // if is REM // return // if is PRINT // print line number // else // SyntaxError // else // continue return 0; };
#include "parser.h" #include "stdio.h" #define DEBUG Parser::Parser( ) { // TODO: Set up all the functions... :-S // Thats gonna be a lot of oList calls... char cChar; for( cChar = 65; cChar < 91; ++cChar ){ this->vList[ cChar ] = 0.0; } }; Parser::~Parser( ) { }; int Parser::runParse( ) { std::string file; this->running = true; while( 1 ){ printf( "Clever prompt -> " ); std::cin >> file; std::transform(file.begin(), file.end(), file.begin(), ::tolower); if( file.compare( std::string( "exit" ) ) == 0 ){ exit( 0 ); } else if( file.compare( std::string( "load" ) ) == 0 ){ printf( "Loading" ); std::cin >> file; if( this->openFile( file ) == -1 ){ printf( "\nCould not open file %s", file.c_str() ); } printf( "\n" ); } else if( file.compare( std::string( "run" ) ) == 0 ){ this->runFile( ); } else if( file.compare( std::string( "clear" ) ) == 0 ){ this->reset( ); } else if( file.compare( std::string( "list" ) ) == 0 ){ this->listProg( ); } else if( file.compare( std::string( "help" ) ) == 0 ){ printf( "Commands: EXIT, LOAD, RUN, CLEAR, LIST, HELP\n" ); } } return 0; }; void Parser::reset( ) { this->file.close( ); this->vStack.erase( this->vStack.begin( ), this->vStack.end( ) ); this->cStack.erase( this->cStack.begin( ), this->cStack.end( ) ); // TODO: CLEAR ALL VARIABLES }; int Parser::openFile( std::string& filename ){ char fchar; bool mark = true; // Close file if already open if( this->file.is_open( ) ) this->reset( ); // Save filename this->filename = filename; // Open the file, debug print // MSVC 2008 DOESNT SUPPORT C++11 OH MY GAWD this->file.open( this->filename.c_str( ), std::fstream::in ); if( ! this->file.is_open( ) ) return -1; // Get line starts this->linestarts.clear( ); this->linestarts.push_back( 0 ); this->file.get(fchar); while( !this->file.eof() ){ if( mark && fchar != 13 ){ mark = false; this->linestarts.push_back( (unsigned short) this->file.tellg( ) - 1 ); printf( "." ); } if( fchar == 10 ){ mark = true; } this->file.get( fchar ); } // Reset the file after eof // NOTE: TEST THIS, ITS POSSIBLY A WINDOWS ONLY THING :( this->file.clear( ); // Return line count return this->linestarts.size( ); }; void Parser::listProg( ){ unsigned i; std::string line; // QUESTION: Print an error message here? if( ! this->file.is_open( ) ) return; if( this->file.eof( ) ) this->file.clear( ); for( i = 1; i < this->linestarts.size( ); ++i ){ this->file.seekg( this->linestarts[ i ], this->file.beg ); if( getline( this->file, line ) ){ std::cout << i << ": " << line << std::endl; } else break; } }; int Parser::runFile( ) { unsigned line = 1; unsigned lncnt = this->linestarts.size( ) - 1; while( 1 ){ if( line > lncnt || line < 1 ) break; try{ this->parseLine( line ); } catch( SyntaxError e ){ std::cout << e.what( ) << " At line:" << line << std::endl; return -1; } if( this->running == false ) break; else ++line; } printf( "Program terminated successfully.\n" ); return 0; }; int Parser::parseLine( unsigned linenum ) { std::stringstream line; std::string oper; std::deque<Parser::Control>::reverse_iterator criter; bool printing = false; // If the file is still good if( ! this->file.is_open( ) ){ this->running = false; return -1; } // If we hit eof, reset the file if( this->file.eof( ) ) this->file.clear( ); // Seek to the proper position this->file.seekg( this->linestarts[ linenum ] ); // Get a line std::getline( this->file, oper ); line << oper; // Check for empty line if( oper.find_first_not_of( std::string( " " ) ) == oper.npos ) return 0; while( ! line.eof( ) ){ bool lastifbranch = true; line >> oper; // Oper is a comment marker if( oper.compare( std::string( "REM" ) ) == 0 ) return 0; if( printing ){ std::cout << oper << " "; continue; } // Find the topmost if statement for( criter = this->cStack.rbegin( ); criter != this->cStack.rend( ); ++criter ){ if( criter->type == Parser::CONTROL_IF ){ // If there is one, get the branch we are on lastifbranch = criter->branch; break; } } // Check for ELSE/ENDIF unconditionally if( oper.compare( std::string( "ELSE" ) ) == 0 ) {} else if( oper.compare( std::string( "ENDIF" ) ) == 0 ) {} if( lastifbranch == true ){ printf( "\n:%d:%s:", linenum, oper.c_str( ) ); // Oper is a print statement if( oper.compare( std::string( "PRINT" ) ) == 0 ) { std::cout << std::endl; printing = true; continue; } // Oper is quitting execution else if( oper.compare( std::string( "QUIT" ) ) == 0 ) { this->running = false; return 0; } // check oper for control statements /* def ret_(): def if_(): def else_(): def endif_(): def while_(): def loop_(): def break_(): */ // check operator list for oper // run if in // Oper is a variable else if( oper.length( ) == 1 && this->vList.find( oper.c_str( )[ 0 ] ) != this->vList.end( ) ) this->vStack.push_back( Value::Variable( oper.c_str( )[ 0 ] ) ); // check for float conversion // add to stack if good // Oper is bad, and should feel bad else throw( SyntaxError( "Invalid operator!" ) ); } else continue; } printf( "\n" ); return 0; };
Update parser.cpp
Update parser.cpp - Finish most of the parsing functions - Add skeleton for operators - Add in variable support
C++
bsd-2-clause
DweebsUnited/Parser,DweebsUnited/Parser
8acba400b54a86c9155765b7df90a8bfbe7120d6
examples/bsoncxx/view_and_value.cpp
examples/bsoncxx/view_and_value.cpp
#include <algorithm> #include <iostream> #include <iterator> #include <vector> #include <bsoncxx/array/view.hpp> #include <bsoncxx/array/view.hpp> #include <bsoncxx/builder/basic/array.hpp> #include <bsoncxx/builder/basic/document.hpp> #include <bsoncxx/builder/basic/kvp.hpp> #include <bsoncxx/document/value.hpp> #include <bsoncxx/document/view.hpp> #include <bsoncxx/json.hpp> #include <bsoncxx/stdx/string_view.hpp> #include <bsoncxx/types.hpp> using namespace bsoncxx; int main(int, char**) { // This example will cover the read-only BSON interface. // Lets first build up a non-trivial BSON document using the builder interface. using builder::basic::kvp; using builder::basic::sub_array; auto doc = builder::basic::document{}; doc.append(kvp("team", "platforms"), kvp("id", types::b_oid{oid(oid::init_tag)}), kvp("members", [](sub_array sa) { sa.append("tyler", "jason", "drew", "sam", "ernie", "john", "mark", "crystal"); }) ); // document::value is an owning bson document conceptually similar to string. document::value value{doc.extract()}; // document::view is a non-owning bson document conceptually similar to string_view. document::view view{value.view()}; // Note: array::view and array::value are the corresponding classes for arrays. // we can print a view using to_json std::cout << to_json(view) << std::endl; // note that all of the interesting methods for reading BSON are defined on the view type. // iterate over the elements in a bson document for (document::element ele : view) { // element is non owning view of a key-value pair within a document. // we can use the key() method to get a string_view of the key. stdx::string_view field_key{ele.key()}; std::cout << "Got key, key = " << field_key << std::endl; // we can use type() to get the type of the value. switch (ele.type()) { case type::k_utf8: std::cout << "Got String!" << std::endl; break; case type::k_oid: std::cout << "Got ObjectId!" << std::endl; break; case type::k_array: { std::cout << "Got Array!" << std::endl; // if we have a subarray, we can access it by getting a view of it. array::view subarr{ele.get_array().value}; for (array::element ele : subarr) { std::cout << "array element: " << to_json(ele.get_value()) << std::endl; } break; } default: std::cout << "We messed up!" << std::endl; } // usually we don't need to actually use a switch statement, because we can also // get a variant 'value' that can hold any BSON type. types::value ele_val{ele.get_value()}; // if we need to print an arbitrary value, we can use to_json, which provides // a suitable overload. std::cout << "the value is " << to_json(ele_val) << std::endl;; } // If we want to search for an element we can use operator[] // (we also provide a find() method that returns an iterator) // Note, this does a linear search so it is O(n) in the length of the BSON document. document::element ele{view["team"]}; if (ele) { // this block will execute if ele was actually found std::cout << "as expected, we have a team of " << to_json(ele.get_value()) << std::endl; } // Because view implements begin(), end(), we can also use standard STL algorithms. // i.e. if we want to find the number of keys in a document we can use std::distance using std::begin; using std::end; auto num_keys = std::distance(begin(view), end(view)); std::cout << "document has " << num_keys << " keys." << std::endl; // i.e. if we want a vector of all the keys in a document, we can use std::transform std::vector<std::string> doc_keys; std::transform(begin(view), end(view), std::back_inserter(doc_keys), [](document::element ele) { // note that key() returns a string_view return ele.key().to_string(); }); std::cout << "document keys are: " << std::endl; for (auto key : doc_keys) { std::cout << key << " " << std::endl; } std::cout << std::endl; }
#include <algorithm> #include <iostream> #include <iterator> #include <vector> #include <bsoncxx/array/view.hpp> #include <bsoncxx/array/view.hpp> #include <bsoncxx/builder/basic/array.hpp> #include <bsoncxx/builder/basic/document.hpp> #include <bsoncxx/builder/basic/kvp.hpp> #include <bsoncxx/document/value.hpp> #include <bsoncxx/document/view.hpp> #include <bsoncxx/json.hpp> #include <bsoncxx/stdx/string_view.hpp> #include <bsoncxx/types.hpp> #include <bsoncxx/types/value.hpp> using namespace bsoncxx; int main(int, char**) { // This example will cover the read-only BSON interface. // Lets first build up a non-trivial BSON document using the builder interface. using builder::basic::kvp; using builder::basic::sub_array; auto doc = builder::basic::document{}; doc.append(kvp("team", "platforms"), kvp("id", types::b_oid{oid(oid::init_tag)}), kvp("members", [](sub_array sa) { sa.append("tyler", "jason", "drew", "sam", "ernie", "john", "mark", "crystal"); }) ); // document::value is an owning bson document conceptually similar to string. document::value value{doc.extract()}; // document::view is a non-owning bson document conceptually similar to string_view. document::view view{value.view()}; // Note: array::view and array::value are the corresponding classes for arrays. // we can print a view using to_json std::cout << to_json(view) << std::endl; // note that all of the interesting methods for reading BSON are defined on the view type. // iterate over the elements in a bson document for (document::element ele : view) { // element is non owning view of a key-value pair within a document. // we can use the key() method to get a string_view of the key. stdx::string_view field_key{ele.key()}; std::cout << "Got key, key = " << field_key << std::endl; // we can use type() to get the type of the value. switch (ele.type()) { case type::k_utf8: std::cout << "Got String!" << std::endl; break; case type::k_oid: std::cout << "Got ObjectId!" << std::endl; break; case type::k_array: { std::cout << "Got Array!" << std::endl; // if we have a subarray, we can access it by getting a view of it. array::view subarr{ele.get_array().value}; for (array::element ele : subarr) { std::cout << "array element: " << to_json(ele.get_value()) << std::endl; } break; } default: std::cout << "We messed up!" << std::endl; } // usually we don't need to actually use a switch statement, because we can also // get a variant 'value' that can hold any BSON type. types::value ele_val{ele.get_value()}; // if we need to print an arbitrary value, we can use to_json, which provides // a suitable overload. std::cout << "the value is " << to_json(ele_val) << std::endl;; } // If we want to search for an element we can use operator[] // (we also provide a find() method that returns an iterator) // Note, this does a linear search so it is O(n) in the length of the BSON document. document::element ele{view["team"]}; if (ele) { // this block will execute if ele was actually found std::cout << "as expected, we have a team of " << to_json(ele.get_value()) << std::endl; } // Because view implements begin(), end(), we can also use standard STL algorithms. // i.e. if we want to find the number of keys in a document we can use std::distance using std::begin; using std::end; auto num_keys = std::distance(begin(view), end(view)); std::cout << "document has " << num_keys << " keys." << std::endl; // i.e. if we want a vector of all the keys in a document, we can use std::transform std::vector<std::string> doc_keys; std::transform(begin(view), end(view), std::back_inserter(doc_keys), [](document::element ele) { // note that key() returns a string_view return ele.key().to_string(); }); std::cout << "document keys are: " << std::endl; for (auto key : doc_keys) { std::cout << key << " " << std::endl; } std::cout << std::endl; }
fix examples
minor: fix examples
C++
apache-2.0
xdg/mongo-cxx-driver,acmorrow/mongo-cxx-driver,mongodb/mongo-cxx-driver,acmorrow/mongo-cxx-driver,acmorrow/mongo-cxx-driver,mongodb/mongo-cxx-driver,xdg/mongo-cxx-driver,xdg/mongo-cxx-driver,mongodb/mongo-cxx-driver,mongodb/mongo-cxx-driver,acmorrow/mongo-cxx-driver,xdg/mongo-cxx-driver
7005d4c4e39ba858e2d92071cd68e20705e9acf4
examples/complete/Conway/Conway.cpp
examples/complete/Conway/Conway.cpp
/* * Conway's Game of Life implementation with less than 1KB code. * Prototype is developed first with Arduino then ported to ATtiny84A. * * Description: * - cells are displayed on an 8x8 LED matrix * - initial setup is set through 2 pots (X and Y) and one button to select/unselect a cell * - starting/suspending the game is done by a second push button * - when the game has started, the Y pot allows speed tuning * - the end of game is detected when: * - no cells are alive: in this case a smiley is blinking * - the last generation is stable (still life): in this case the last generation is blinking * * Circuit: * - MCU is connected to 2 chained 74HC595 SIPO * - First SIPO is connected to matrix columns through 8 330Ohm resistors * - Second SIPO is connected to matrix rows * * Wiring: * - on Arduino UNO: * - D2 is an output connected to both SIPO clock pins * - D3 is an output connected to both SIPO latch pins * - D4 is an output connected to first SIPO serial data input * - D0 is an input connected to the START/STOP button (connected itself to GND) * - D7 is an input connected to the SELECT button (connected itself to GND) * - A0 is an analog input connected to the ROW potentiometer * - A1 is an analog input connected to the COLUMN potentiometer * - on ATtinyX4 based boards: * - PA2 is an output connected to both SIPO clock pins * - PA1 is an output connected to both SIPO latch pins * - PA0 is an output connected to first SIPO serial data input * - PA5 is an input connected to the START/STOP button (connected itself to GND) * - PA4 is an input connected to the SELECT button (connected itself to GND) * - A7 is an analog input connected to the ROW potentiometer * - A6 is an analog input connected to the COLUMN potentiometer */ #include <avr/interrupt.h> #include <util/delay.h> #include <fastarduino/time.hh> #include <fastarduino/AnalogInput.hh> #include "Multiplexer.hh" #include "Button.hh" #include "Game.hh" #if defined(ARDUINO_UNO) static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D2; static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D3; static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D4; static constexpr const Board::AnalogPin ROW = Board::AnalogPin::A0; static constexpr const Board::AnalogPin COLUMN = Board::AnalogPin::A1; static constexpr const Board::AnalogPin SPEED = Board::AnalogPin::A0; static constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D5; static constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D6; #define HAS_TRACE 1 #elif defined (BREADBOARD_ATTINYX4) static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D2; static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D1; static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D0; static constexpr const Board::AnalogPin ROW = Board::AnalogPin::A6; static constexpr const Board::AnalogPin COLUMN = Board::AnalogPin::A7; static constexpr const Board::AnalogPin SPEED = Board::AnalogPin::A7; static constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D4; static constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D5; #else #error "Current target is not yet supported!" #endif // Trace is used only for Arduino UNO if needed #if HAS_TRACE #include <fastarduino/uart.hh> USE_UATX0(); // Buffers for UART static const uint8_t OUTPUT_BUFFER_SIZE = 128; static char output_buffer[OUTPUT_BUFFER_SIZE]; static UATX<Board::USART::USART0> uatx{output_buffer}; FormattedOutput<OutputBuffer> trace = uatx.fout(); #endif // Uncomment these lines if you want to quickly generate a program for a 16x16 LED matrix (default is 8x8)) //#define ROW_COUNT 16 //#define COLUMN_COUNT 16 // Those defines can be overridden in command line to support bigger LED matrices (eg 16x16) #ifndef ROW_COUNT #define ROW_COUNT 8 #endif #ifndef COLUMN_COUNT #define COLUMN_COUNT 8 #endif // Single port used by this circuit static constexpr const Board::Port PORT = FastPinType<CLOCK>::PORT; // Check at compile time that all pins are on the same port static_assert(FastPinType<LATCH>::PORT == PORT, "LATCH must be on same port as CLOCK"); static_assert(FastPinType<DATA>::PORT == PORT, "DATA must be on same port as CLOCK"); static_assert(FastPinType<SELECT>::PORT == PORT, "SELECT must be on same port as CLOCK"); static_assert(FastPinType<START_STOP>::PORT == PORT, "START_STOP must be on same port as CLOCK"); // Utility function to find the exponent of the nearest power of 2 for an integer constexpr uint16_t LOG2(uint16_t n) { return (n < 2) ? 0 : 1 + LOG2(n / 2); } // Timing constants // Multiplexing is done one row every 1ms, ie 8 rows in 8ms static constexpr const uint16_t REFRESH_PERIOD_MS = 1; static constexpr const uint16_t REFRESH_PERIOD_US = 1000 * REFRESH_PERIOD_MS; // Blinking LEDs are toggled every 20 times the display is fully refreshed (ie 20 x 8 x 2ms = 320ms) static constexpr const uint16_t BLINKING_HALF_TIME_MS = 250; static constexpr const uint16_t BLINKING_COUNTER = BLINKING_HALF_TIME_MS / REFRESH_PERIOD_MS; // Buttons debouncing is done on a duration of 20ms static constexpr const uint16_t DEBOUNCE_TIME_MS = 20; static constexpr const uint8_t DEBOUNCE_COUNTER = DEBOUNCE_TIME_MS / REFRESH_PERIOD_MS; // Minimum delay between 2 generations during phase 2 (must be a power of 2) static constexpr const uint16_t MIN_PROGRESS_PERIOD_MS = 256; // Delay between phase 2 (game) and phase 3 (end of game) static constexpr const uint16_t DELAY_BEFORE_END_GAME_MS = 1000; // Useful constants and types static constexpr const uint8_t ROWS = ROW_COUNT; static constexpr const uint8_t COLUMNS = COLUMN_COUNT; using MULTIPLEXER = MatrixMultiplexer<CLOCK, LATCH, DATA, BLINKING_COUNTER, ROWS, COLUMNS>; using ROW_TYPE = MULTIPLEXER::ROW_TYPE; using GAME = GameOfLife<ROWS, ROW_TYPE>; // Calculate direction of pins (3 output, 2 input with pullups) static constexpr const uint8_t ALL_DDR = MULTIPLEXER::DDR_MASK; static constexpr const uint8_t BUTTONS_MASK = FastPinType<SELECT>::MASK | FastPinType<START_STOP>::MASK; static constexpr const uint8_t ALL_PORT = MULTIPLEXER::PORT_MASK | BUTTONS_MASK; //NOTE: on the stripboards-based circuit, rows and columns are inverted //FIXME make it size-agnostic (how??) static constexpr const ROW_TYPE SMILEY[] = { 0B01110000, 0B10001000, 0B10000100, 0B01000010, 0B01000010, 0B10000100, 0B10001000, 0B01110000 }; static uint16_t game_period() { AnalogInput<SPEED, Board::AnalogReference::AVCC, uint8_t> speed_input; uint8_t period = speed_input.sample() >> 4; return (MIN_PROGRESS_PERIOD_MS * (period + 1)) >> LOG2(REFRESH_PERIOD_MS); } int main() __attribute__((OS_main)); int main() { // Enable interrupts at startup time sei(); #if HAS_TRACE // Setup traces (Arduino only) uatx.begin(57600); trace.width(0); #endif // Initialize all pins (only one port) FastPort<PORT>{ALL_DDR, ALL_PORT}; // Initialize Multiplexer MULTIPLEXER mux; // STOP button is used during both phase 1 and 2, hence declare it in global main() scope Button<START_STOP, DEBOUNCE_COUNTER> stop; // Step #1: Initialize board with 1st generation //=============================================== { Button<SELECT, DEBOUNCE_COUNTER> select; AnalogInput<ROW, Board::AnalogReference::AVCC, uint8_t> row_input; AnalogInput<COLUMN, Board::AnalogReference::AVCC, uint8_t> column_input; uint8_t row = 0; uint8_t col = 0; mux.blinks()[0] = _BV(0); while (true) { // Update selected cell mux.blinks()[row] = 0; row = ROWS - 1 - (row_input.sample() >> (8 - LOG2(ROWS))); col = COLUMNS - 1 - (column_input.sample() >> (8 - LOG2(COLUMNS))); mux.blinks()[row] = _BV(col); // Check button states if (stop.unique_press()) break; if (select.unique_press()) mux.data()[row] ^= _BV(col); mux.refresh(BlinkMode::BLINK_ALL_BLINKS); Time::delay_us(REFRESH_PERIOD_US); } } // Step #2: Start game //===================== { // Initialize game board GAME game{mux.data()}; // Loop to refresh LED matrix and progress game to next generation uint16_t progress_counter = 0; bool pause = false; while (true) { mux.refresh(BlinkMode::NO_BLINK); Time::delay_us(REFRESH_PERIOD_US); if (stop.unique_press()) pause = !pause; if (!pause && ++progress_counter >= game_period()) { game.progress_game(); progress_counter = 0; // Check if game is finished (ie no more live cell, or still life) if (game.is_empty()) { // Load a smiley into the game for (uint8_t i = 0; i < sizeof(SMILEY)/sizeof(SMILEY[0]); ++i) mux.data()[i] = SMILEY[i]; break; } if (game.is_still()) break; } } } // Step #3: End game //=================== // Here we just need to refresh content and blink it until reset // First we clear multiplexer display, then we wait for one second mux.clear(); Time::delay_ms(DELAY_BEFORE_END_GAME_MS); while (true) { Time::delay_us(REFRESH_PERIOD_US); mux.refresh(BlinkMode::BLINK_ALL_DATA); } return 0; } #if defined (BREADBOARD_ATTINYX4) // Since we use -nostartfiles option we must manually set the startup code (at address 0x00) void __jumpMain() __attribute__((naked)) __attribute__((section (".init9"))); // Startup code just clears R1 (this is expected by GCC) and calls main() void __jumpMain() { asm volatile ( ".set __stack, %0" :: "i" (RAMEND) ); asm volatile ( "clr __zero_reg__" ); // r1 set to 0 asm volatile ( "rjmp main"); // jump to main() } #endif
/* * Conway's Game of Life implementation with less than 1KB code. * Prototype is developed first with Arduino then ported to ATtiny84A. * * Description: * - cells are displayed on an 8x8 LED matrix * - initial setup is set through 2 pots (X and Y) and one button to select/unselect a cell * - starting/suspending the game is done by a second push button * - when the game has started, the Y pot allows speed tuning * - the end of game is detected when: * - no cells are alive: in this case a smiley is blinking * - the last generation is stable (still life): in this case the last generation is blinking * * Circuit: * - MCU is connected to 2 chained 74HC595 SIPO * - First SIPO is connected to matrix columns through 8 330Ohm resistors * - Second SIPO is connected to matrix rows * * Wiring: * - on Arduino UNO: * - D2 is an output connected to both SIPO clock pins * - D3 is an output connected to both SIPO latch pins * - D4 is an output connected to first SIPO serial data input * - D0 is an input connected to the START/STOP button (connected itself to GND) * - D7 is an input connected to the SELECT button (connected itself to GND) * - A0 is an analog input connected to the ROW potentiometer * - A1 is an analog input connected to the COLUMN potentiometer * - on ATtinyX4 based boards: * - PA2 is an output connected to both SIPO clock pins * - PA1 is an output connected to both SIPO latch pins * - PA0 is an output connected to first SIPO serial data input * - PA5 is an input connected to the START/STOP button (connected itself to GND) * - PA4 is an input connected to the SELECT button (connected itself to GND) * - A7 is an analog input connected to the ROW potentiometer * - A6 is an analog input connected to the COLUMN potentiometer */ #include <avr/interrupt.h> #include <util/delay.h> #include <fastarduino/time.hh> #include <fastarduino/AnalogInput.hh> #include "Multiplexer.hh" #include "Button.hh" #include "Game.hh" #if defined(ARDUINO_UNO) static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D2; static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D3; static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D4; static constexpr const Board::AnalogPin ROW = Board::AnalogPin::A0; static constexpr const Board::AnalogPin COLUMN = Board::AnalogPin::A1; static constexpr const Board::AnalogPin SPEED = Board::AnalogPin::A0; static constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D5; static constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D6; #define HAS_TRACE 1 #elif defined (BREADBOARD_ATTINYX4) static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D2; static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D1; static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D0; static constexpr const Board::AnalogPin ROW = Board::AnalogPin::A6; static constexpr const Board::AnalogPin COLUMN = Board::AnalogPin::A7; static constexpr const Board::AnalogPin SPEED = Board::AnalogPin::A7; static constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D4; static constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D5; #else #error "Current target is not yet supported!" #endif // Trace is used only for Arduino UNO if needed #if HAS_TRACE #include <fastarduino/uart.hh> USE_UATX0(); // Buffers for UART static const uint8_t OUTPUT_BUFFER_SIZE = 128; static char output_buffer[OUTPUT_BUFFER_SIZE]; static UATX<Board::USART::USART0> uatx{output_buffer}; FormattedOutput<OutputBuffer> trace = uatx.fout(); #endif // Uncomment these lines if you want to quickly generate a program for a 16x16 LED matrix (default is 8x8)) //#define ROW_COUNT 16 //#define COLUMN_COUNT 16 // Those defines can be overridden in command line to support bigger LED matrices (eg 16x16) #ifndef ROW_COUNT #define ROW_COUNT 8 #endif #ifndef COLUMN_COUNT #define COLUMN_COUNT 8 #endif // Single port used by this circuit static constexpr const Board::Port PORT = FastPinType<CLOCK>::PORT; // Check at compile time that all pins are on the same port static_assert(FastPinType<LATCH>::PORT == PORT, "LATCH must be on same port as CLOCK"); static_assert(FastPinType<DATA>::PORT == PORT, "DATA must be on same port as CLOCK"); static_assert(FastPinType<SELECT>::PORT == PORT, "SELECT must be on same port as CLOCK"); static_assert(FastPinType<START_STOP>::PORT == PORT, "START_STOP must be on same port as CLOCK"); // Utility function to find the exponent of the nearest power of 2 for an integer constexpr uint16_t LOG2(uint16_t n) { return (n < 2) ? 0 : 1 + LOG2(n / 2); } // Timing constants // Multiplexing is done one row every 1ms, ie 8 rows in 8ms static constexpr const uint16_t REFRESH_PERIOD_MS = 1; static constexpr const uint16_t REFRESH_PERIOD_US = 1000 * REFRESH_PERIOD_MS; // Blinking LEDs are toggled every 250ms static constexpr const uint16_t BLINKING_HALF_TIME_MS = 250; static constexpr const uint16_t BLINKING_COUNTER = BLINKING_HALF_TIME_MS / REFRESH_PERIOD_MS; // Buttons debouncing is done on a duration of 20ms static constexpr const uint16_t DEBOUNCE_TIME_MS = 20; static constexpr const uint8_t DEBOUNCE_COUNTER = DEBOUNCE_TIME_MS / REFRESH_PERIOD_MS; // Minimum delay between 2 generations during phase 2 (must be a power of 2) static constexpr const uint16_t MIN_PROGRESS_PERIOD_MS = 256; // Delay between phase 2 (game) and phase 3 (end of game) static constexpr const uint16_t DELAY_BEFORE_END_GAME_MS = 1000; // Useful constants and types static constexpr const uint8_t ROWS = ROW_COUNT; static constexpr const uint8_t COLUMNS = COLUMN_COUNT; using MULTIPLEXER = MatrixMultiplexer<CLOCK, LATCH, DATA, BLINKING_COUNTER, ROWS, COLUMNS>; using ROW_TYPE = MULTIPLEXER::ROW_TYPE; using GAME = GameOfLife<ROWS, ROW_TYPE>; // Calculate direction of pins (3 output, 2 input with pullups) static constexpr const uint8_t ALL_DDR = MULTIPLEXER::DDR_MASK; static constexpr const uint8_t BUTTONS_MASK = FastPinType<SELECT>::MASK | FastPinType<START_STOP>::MASK; static constexpr const uint8_t ALL_PORT = MULTIPLEXER::PORT_MASK | BUTTONS_MASK; //NOTE: on the stripboards-based circuit, rows and columns are inverted //FIXME make it size-agnostic (how??) static constexpr const ROW_TYPE SMILEY[] = { 0B01110000, 0B10001000, 0B10000100, 0B01000010, 0B01000010, 0B10000100, 0B10001000, 0B01110000 }; static uint16_t game_period() { AnalogInput<SPEED, Board::AnalogReference::AVCC, uint8_t> speed_input; uint8_t period = speed_input.sample() >> 4; return (MIN_PROGRESS_PERIOD_MS * (period + 1)) >> LOG2(REFRESH_PERIOD_MS); } int main() __attribute__((OS_main)); int main() { // Enable interrupts at startup time sei(); #if HAS_TRACE // Setup traces (Arduino only) uatx.begin(57600); trace.width(0); #endif // Initialize all pins (only one port) FastPort<PORT>{ALL_DDR, ALL_PORT}; // Initialize Multiplexer MULTIPLEXER mux; // STOP button is used during both phase 1 and 2, hence declare it in global main() scope Button<START_STOP, DEBOUNCE_COUNTER> stop; // Step #1: Initialize board with 1st generation //=============================================== { Button<SELECT, DEBOUNCE_COUNTER> select; AnalogInput<ROW, Board::AnalogReference::AVCC, uint8_t> row_input; AnalogInput<COLUMN, Board::AnalogReference::AVCC, uint8_t> column_input; uint8_t row = 0; uint8_t col = 0; mux.blinks()[0] = _BV(0); while (true) { // Update selected cell mux.blinks()[row] = 0; row = ROWS - 1 - (row_input.sample() >> (8 - LOG2(ROWS))); col = COLUMNS - 1 - (column_input.sample() >> (8 - LOG2(COLUMNS))); mux.blinks()[row] = _BV(col); // Check button states if (stop.unique_press()) break; if (select.unique_press()) mux.data()[row] ^= _BV(col); mux.refresh(BlinkMode::BLINK_ALL_BLINKS); Time::delay_us(REFRESH_PERIOD_US); } } // Step #2: Start game //===================== { // Initialize game board GAME game{mux.data()}; // Loop to refresh LED matrix and progress game to next generation uint16_t progress_counter = 0; bool pause = false; while (true) { mux.refresh(BlinkMode::NO_BLINK); Time::delay_us(REFRESH_PERIOD_US); if (stop.unique_press()) pause = !pause; if (!pause && ++progress_counter >= game_period()) { game.progress_game(); progress_counter = 0; // Check if game is finished (ie no more live cell, or still life) if (game.is_empty()) { // Load a smiley into the game for (uint8_t i = 0; i < sizeof(SMILEY)/sizeof(SMILEY[0]); ++i) mux.data()[i] = SMILEY[i]; break; } if (game.is_still()) break; } } } // Step #3: End game //=================== // Here we just need to refresh content and blink it until reset // First we clear multiplexer display, then we wait for one second mux.clear(); Time::delay_ms(DELAY_BEFORE_END_GAME_MS); while (true) { Time::delay_us(REFRESH_PERIOD_US); mux.refresh(BlinkMode::BLINK_ALL_DATA); } return 0; } #if defined (BREADBOARD_ATTINYX4) // Since we use -nostartfiles option we must manually set the startup code (at address 0x00) void __jumpMain() __attribute__((naked)) __attribute__((section (".init9"))); // Startup code just clears R1 (this is expected by GCC) and calls main() void __jumpMain() { asm volatile ( ".set __stack, %0" :: "i" (RAMEND) ); asm volatile ( "clr __zero_reg__" ); // r1 set to 0 asm volatile ( "rjmp main"); // jump to main() } #endif
Fix comments in Conway.
Fix comments in Conway.
C++
lgpl-2.1
jfpoilpret/fast-arduino-lib,jfpoilpret/fast-arduino-lib,jfpoilpret/fast-arduino-lib,jfpoilpret/fast-arduino-lib
319c29a70991ec6d8a506f5705b5a55ef349bc7e
src/nix-prefetch-url/nix-prefetch-url.cc
src/nix-prefetch-url/nix-prefetch-url.cc
#include "hash.hh" #include "shared.hh" #include "download.hh" #include "store-api.hh" #include "eval.hh" #include "eval-inline.hh" #include "common-eval-args.hh" #include "attr-path.hh" #include "legacy.hh" #include "finally.hh" #include "progress-bar.hh" #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> using namespace nix; /* If ‘uri’ starts with ‘mirror://’, then resolve it using the list of mirrors defined in Nixpkgs. */ string resolveMirrorUri(EvalState & state, string uri) { if (string(uri, 0, 9) != "mirror://") return uri; string s(uri, 9); auto p = s.find('/'); if (p == string::npos) throw Error("invalid mirror URI"); string mirrorName(s, 0, p); Value vMirrors; state.eval(state.parseExprFromString("import <nixpkgs/pkgs/build-support/fetchurl/mirrors.nix>", "."), vMirrors); state.forceAttrs(vMirrors); auto mirrorList = vMirrors.attrs->find(state.symbols.create(mirrorName)); if (mirrorList == vMirrors.attrs->end()) throw Error(format("unknown mirror name '%1%'") % mirrorName); state.forceList(*mirrorList->value); if (mirrorList->value->listSize() < 1) throw Error(format("mirror URI '%1%' did not expand to anything") % uri); string mirror = state.forceString(*mirrorList->value->listElems()[0]); return mirror + (hasSuffix(mirror, "/") ? "" : "/") + string(s, p + 1); } static int _main(int argc, char * * argv) { { HashType ht = htSHA256; std::vector<string> args; bool printPath = getEnv("PRINT_PATH") == "1"; bool fromExpr = false; string attrPath; bool unpack = false; string name; struct MyArgs : LegacyArgs, MixEvalArgs { using LegacyArgs::LegacyArgs; }; MyArgs myArgs(baseNameOf(argv[0]), [&](Strings::iterator & arg, const Strings::iterator & end) { if (*arg == "--help") showManPage("nix-prefetch-url"); else if (*arg == "--version") printVersion("nix-prefetch-url"); else if (*arg == "--type") { string s = getArg(*arg, arg, end); ht = parseHashType(s); if (ht == htUnknown) throw UsageError(format("unknown hash type '%1%'") % s); } else if (*arg == "--print-path") printPath = true; else if (*arg == "--attr" || *arg == "-A") { fromExpr = true; attrPath = getArg(*arg, arg, end); } else if (*arg == "--unpack") unpack = true; else if (*arg == "--name") name = getArg(*arg, arg, end); else if (*arg != "" && arg->at(0) == '-') return false; else args.push_back(*arg); return true; }); myArgs.parseCmdline(argvToStrings(argc, argv)); initPlugins(); if (args.size() > 2) throw UsageError("too many arguments"); Finally f([]() { stopProgressBar(); }); if (isatty(STDERR_FILENO)) startProgressBar(); auto store = openStore(); auto state = std::make_unique<EvalState>(myArgs.searchPath, store); Bindings & autoArgs = *myArgs.getAutoArgs(*state); /* If -A is given, get the URI from the specified Nix expression. */ string uri; if (!fromExpr) { if (args.empty()) throw UsageError("you must specify a URI"); uri = args[0]; } else { Path path = resolveExprPath(lookupFileArg(*state, args.empty() ? "." : args[0])); Value vRoot; state->evalFile(path, vRoot); Value & v(*findAlongAttrPath(*state, attrPath, autoArgs, vRoot)); state->forceAttrs(v); /* Extract the URI. */ auto attr = v.attrs->find(state->symbols.create("urls")); if (attr == v.attrs->end()) throw Error("attribute set does not contain a 'urls' attribute"); state->forceList(*attr->value); if (attr->value->listSize() < 1) throw Error("'urls' list is empty"); uri = state->forceString(*attr->value->listElems()[0]); /* Extract the hash mode. */ attr = v.attrs->find(state->symbols.create("outputHashMode")); if (attr == v.attrs->end()) printInfo("warning: this does not look like a fetchurl call"); else unpack = state->forceString(*attr->value) == "recursive"; /* Extract the name. */ if (name.empty()) { attr = v.attrs->find(state->symbols.create("name")); if (attr != v.attrs->end()) name = state->forceString(*attr->value); } } /* Figure out a name in the Nix store. */ if (name.empty()) name = baseNameOf(uri); if (name.empty()) throw Error(format("cannot figure out file name for '%1%'") % uri); /* If an expected hash is given, the file may already exist in the store. */ Hash hash, expectedHash(ht); Path storePath; if (args.size() == 2) { expectedHash = Hash(args[1], ht); storePath = store->makeFixedOutputPath(unpack, expectedHash, name); if (store->isValidPath(storePath)) hash = expectedHash; else storePath.clear(); } if (storePath.empty()) { auto actualUri = resolveMirrorUri(*state, uri); AutoDelete tmpDir(createTempDir(), true); Path tmpFile = (Path) tmpDir + "/tmp"; /* Download the file. */ { AutoCloseFD fd = open(tmpFile.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0600); if (!fd) throw SysError("creating temporary file '%s'", tmpFile); FdSink sink(fd.get()); DownloadRequest req(actualUri); req.decompress = false; getDownloader()->download(std::move(req), sink); } /* Optionally unpack the file. */ if (unpack) { printInfo("unpacking..."); Path unpacked = (Path) tmpDir + "/unpacked"; createDirs(unpacked); if (hasSuffix(baseNameOf(uri), ".zip")) runProgram("unzip", true, {"-qq", tmpFile, "-d", unpacked}); else // FIXME: this requires GNU tar for decompression. runProgram("tar", true, {"xf", tmpFile, "-C", unpacked}); /* If the archive unpacks to a single file/directory, then use that as the top-level. */ auto entries = readDirectory(unpacked); if (entries.size() == 1) tmpFile = unpacked + "/" + entries[0].name; else tmpFile = unpacked; } /* FIXME: inefficient; addToStore() will also hash this. */ hash = unpack ? hashPath(ht, tmpFile).first : hashFile(ht, tmpFile); if (expectedHash != Hash(ht) && expectedHash != hash) throw Error(format("hash mismatch for '%1%'") % uri); /* Copy the file to the Nix store. FIXME: if RemoteStore implemented addToStoreFromDump() and downloadFile() supported a sink, we could stream the download directly into the Nix store. */ storePath = store->addToStore(name, tmpFile, unpack, ht); assert(storePath == store->makeFixedOutputPath(unpack, hash, name)); } stopProgressBar(); if (!printPath) printInfo(format("path is '%1%'") % storePath); std::cout << printHash16or32(hash) << std::endl; if (printPath) std::cout << storePath << std::endl; return 0; } } static RegisterLegacyCommand s1("nix-prefetch-url", _main);
#include "hash.hh" #include "shared.hh" #include "download.hh" #include "store-api.hh" #include "eval.hh" #include "eval-inline.hh" #include "common-eval-args.hh" #include "attr-path.hh" #include "legacy.hh" #include "finally.hh" #include "progress-bar.hh" #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> using namespace nix; /* If ‘uri’ starts with ‘mirror://’, then resolve it using the list of mirrors defined in Nixpkgs. */ string resolveMirrorUri(EvalState & state, string uri) { if (string(uri, 0, 9) != "mirror://") return uri; string s(uri, 9); auto p = s.find('/'); if (p == string::npos) throw Error("invalid mirror URI"); string mirrorName(s, 0, p); Value vMirrors; state.eval(state.parseExprFromString("import <nixpkgs/pkgs/build-support/fetchurl/mirrors.nix>", "."), vMirrors); state.forceAttrs(vMirrors); auto mirrorList = vMirrors.attrs->find(state.symbols.create(mirrorName)); if (mirrorList == vMirrors.attrs->end()) throw Error(format("unknown mirror name '%1%'") % mirrorName); state.forceList(*mirrorList->value); if (mirrorList->value->listSize() < 1) throw Error(format("mirror URI '%1%' did not expand to anything") % uri); string mirror = state.forceString(*mirrorList->value->listElems()[0]); return mirror + (hasSuffix(mirror, "/") ? "" : "/") + string(s, p + 1); } static int _main(int argc, char * * argv) { { HashType ht = htSHA256; std::vector<string> args; bool printPath = getEnv("PRINT_PATH") == "1"; bool fromExpr = false; string attrPath; bool unpack = false; string name; struct MyArgs : LegacyArgs, MixEvalArgs { using LegacyArgs::LegacyArgs; }; MyArgs myArgs(baseNameOf(argv[0]), [&](Strings::iterator & arg, const Strings::iterator & end) { if (*arg == "--help") showManPage("nix-prefetch-url"); else if (*arg == "--version") printVersion("nix-prefetch-url"); else if (*arg == "--type") { string s = getArg(*arg, arg, end); ht = parseHashType(s); if (ht == htUnknown) throw UsageError(format("unknown hash type '%1%'") % s); } else if (*arg == "--print-path") printPath = true; else if (*arg == "--attr" || *arg == "-A") { fromExpr = true; attrPath = getArg(*arg, arg, end); } else if (*arg == "--unpack") unpack = true; else if (*arg == "--name") name = getArg(*arg, arg, end); else if (*arg != "" && arg->at(0) == '-') return false; else args.push_back(*arg); return true; }); myArgs.parseCmdline(argvToStrings(argc, argv)); initPlugins(); if (args.size() > 2) throw UsageError("too many arguments"); Finally f([]() { stopProgressBar(); }); if (isatty(STDERR_FILENO)) startProgressBar(); auto store = openStore(); auto state = std::make_unique<EvalState>(myArgs.searchPath, store); Bindings & autoArgs = *myArgs.getAutoArgs(*state); /* If -A is given, get the URI from the specified Nix expression. */ string uri; if (!fromExpr) { if (args.empty()) throw UsageError("you must specify a URI"); uri = args[0]; } else { Path path = resolveExprPath(lookupFileArg(*state, args.empty() ? "." : args[0])); Value vRoot; state->evalFile(path, vRoot); Value & v(*findAlongAttrPath(*state, attrPath, autoArgs, vRoot)); state->forceAttrs(v); /* Extract the URI. */ auto attr = v.attrs->find(state->symbols.create("urls")); if (attr == v.attrs->end()) throw Error("attribute set does not contain a 'urls' attribute"); state->forceList(*attr->value); if (attr->value->listSize() < 1) throw Error("'urls' list is empty"); uri = state->forceString(*attr->value->listElems()[0]); /* Extract the hash mode. */ attr = v.attrs->find(state->symbols.create("outputHashMode")); if (attr == v.attrs->end()) printInfo("warning: this does not look like a fetchurl call"); else unpack |= state->forceString(*attr->value) == "recursive"; /* Extract the name. */ if (name.empty()) { attr = v.attrs->find(state->symbols.create("name")); if (attr != v.attrs->end()) name = state->forceString(*attr->value); } } /* Figure out a name in the Nix store. */ if (name.empty()) name = baseNameOf(uri); if (name.empty()) throw Error(format("cannot figure out file name for '%1%'") % uri); /* If an expected hash is given, the file may already exist in the store. */ Hash hash, expectedHash(ht); Path storePath; if (args.size() == 2) { expectedHash = Hash(args[1], ht); storePath = store->makeFixedOutputPath(unpack, expectedHash, name); if (store->isValidPath(storePath)) hash = expectedHash; else storePath.clear(); } if (storePath.empty()) { auto actualUri = resolveMirrorUri(*state, uri); AutoDelete tmpDir(createTempDir(), true); Path tmpFile = (Path) tmpDir + "/tmp"; /* Download the file. */ { AutoCloseFD fd = open(tmpFile.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0600); if (!fd) throw SysError("creating temporary file '%s'", tmpFile); FdSink sink(fd.get()); DownloadRequest req(actualUri); req.decompress = false; getDownloader()->download(std::move(req), sink); } /* Optionally unpack the file. */ if (unpack) { printInfo("unpacking..."); Path unpacked = (Path) tmpDir + "/unpacked"; createDirs(unpacked); if (hasSuffix(baseNameOf(uri), ".zip")) runProgram("unzip", true, {"-qq", tmpFile, "-d", unpacked}); else // FIXME: this requires GNU tar for decompression. runProgram("tar", true, {"xf", tmpFile, "-C", unpacked}); /* If the archive unpacks to a single file/directory, then use that as the top-level. */ auto entries = readDirectory(unpacked); if (entries.size() == 1) tmpFile = unpacked + "/" + entries[0].name; else tmpFile = unpacked; } /* FIXME: inefficient; addToStore() will also hash this. */ hash = unpack ? hashPath(ht, tmpFile).first : hashFile(ht, tmpFile); if (expectedHash != Hash(ht) && expectedHash != hash) throw Error(format("hash mismatch for '%1%'") % uri); /* Copy the file to the Nix store. FIXME: if RemoteStore implemented addToStoreFromDump() and downloadFile() supported a sink, we could stream the download directly into the Nix store. */ storePath = store->addToStore(name, tmpFile, unpack, ht); assert(storePath == store->makeFixedOutputPath(unpack, hash, name)); } stopProgressBar(); if (!printPath) printInfo(format("path is '%1%'") % storePath); std::cout << printHash16or32(hash) << std::endl; if (printPath) std::cout << storePath << std::endl; return 0; } } static RegisterLegacyCommand s1("nix-prefetch-url", _main);
support --unpack w/ -A?
nix-prefetch-url: support --unpack w/ -A?
C++
lgpl-2.1
dtzWill/nix,dtzWill/nix,dtzWill/nix,dtzWill/nix,dtzWill/nix
4f1ac7d72a5102259188aff4961dad954d7efbcd
examples/libxml2/libxml2_example.cc
examples/libxml2/libxml2_example.cc
// Copyright 2017 Google Inc. 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 "libxml/parser.h" #include "port/protobuf.h" #include "src/xml/xml_mutator.h" namespace { protobuf_mutator::protobuf::LogSilencer log_silincer; void ignore(void* ctx, const char* msg, ...) {} } extern "C" size_t LLVMFuzzerCustomMutator(uint8_t* data, size_t size, size_t max_size, unsigned int seed) { return protobuf_mutator::xml::MutateTextMessage(data, size, max_size, seed); } extern "C" size_t LLVMFuzzerCustomCrossOver(const uint8_t* data1, size_t size1, const uint8_t* data2, size_t size2, uint8_t* out, size_t max_out_size, unsigned int seed) { return protobuf_mutator::xml::CrossOverTextMessages( data1, size1, data2, size2, out, max_out_size, seed); } extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { int options = 0; std::string xml; protobuf_mutator::xml::ParseTextMessage(data, size, &xml, &options); // Network requests are too slow. options |= XML_PARSE_NONET; // These flags can cause network or file access and hangs. options &= ~(XML_PARSE_NOENT | XML_PARSE_HUGE | XML_PARSE_DTDVALID | XML_PARSE_DTDLOAD | XML_PARSE_DTDATTR); xmlSetGenericErrorFunc(nullptr, &ignore); if (auto doc = xmlReadMemory(xml.c_str(), static_cast<int>(xml.size()), "", nullptr, options)) { xmlFreeDoc(doc); } return 0; }
// Copyright 2017 Google Inc. 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 "libxml/parser.h" #include "libxml/xmlsave.h" #include "port/protobuf.h" #include "src/xml/xml_mutator.h" namespace { protobuf_mutator::protobuf::LogSilencer log_silincer; void ignore(void* ctx, const char* msg, ...) {} template <class T, class D> std::unique_ptr<T, D> MakeUnique(T* obj, D del) { return {obj, del}; } } extern "C" size_t LLVMFuzzerCustomMutator(uint8_t* data, size_t size, size_t max_size, unsigned int seed) { return protobuf_mutator::xml::MutateTextMessage(data, size, max_size, seed); } extern "C" size_t LLVMFuzzerCustomCrossOver(const uint8_t* data1, size_t size1, const uint8_t* data2, size_t size2, uint8_t* out, size_t max_out_size, unsigned int seed) { return protobuf_mutator::xml::CrossOverTextMessages( data1, size1, data2, size2, out, max_out_size, seed); } extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { int options = 0; std::string xml; protobuf_mutator::xml::ParseTextMessage(data, size, &xml, &options); // Network requests are too slow. options |= XML_PARSE_NONET; // These flags can cause network or file access and hangs. options &= ~(XML_PARSE_NOENT | XML_PARSE_HUGE | XML_PARSE_DTDVALID | XML_PARSE_DTDLOAD | XML_PARSE_DTDATTR); xmlSetGenericErrorFunc(nullptr, &ignore); if (auto doc = MakeUnique(xmlReadMemory(xml.c_str(), static_cast<int>(xml.size()), "", nullptr, options), &xmlFreeDoc)) { auto buf = MakeUnique(xmlBufferCreate(), &xmlBufferFree); auto ctxt = MakeUnique(xmlSaveToBuffer(buf.get(), nullptr, 0), &xmlSaveClose); xmlSaveDoc(ctxt.get(), doc.get()); } return 0; }
Add xmlSaveToBuffer to libxml fuzzer.
Add xmlSaveToBuffer to libxml fuzzer.
C++
apache-2.0
vitalybuka/libprotobuf-mutator,google/libprotobuf-mutator,vitalybuka/libprotobuf-mutator,google/libprotobuf-mutator
d805accad513c4d8c2e9c0aa84a18d5c96ccd98a
src/controller/CHIPDeviceControllerFactory.cpp
src/controller/CHIPDeviceControllerFactory.cpp
/* * * Copyright (c) 2021 Project CHIP 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. */ /** * @file * Implementation of CHIP Device Controller Factory, a utility/manager class * that vends Controller objects */ #include <controller/CHIPDeviceControllerFactory.h> #include <app/OperationalDeviceProxy.h> #include <app/util/DataModelHandler.h> #include <lib/support/ErrorStr.h> #include <messaging/ReliableMessageProtocolConfig.h> #if CONFIG_DEVICE_LAYER #include <platform/CHIPDeviceLayer.h> #include <platform/ConfigurationManager.h> #endif #include <app/server/Dnssd.h> #include <protocols/secure_channel/CASEServer.h> #include <protocols/secure_channel/SimpleSessionResumptionStorage.h> using namespace chip::Inet; using namespace chip::System; using namespace chip::Credentials; namespace chip { namespace Controller { CHIP_ERROR DeviceControllerFactory::Init(FactoryInitParams params) { // SystemState is only set the first time init is called, after that it is managed // internally. If SystemState is set then init has already completed. if (mSystemState != nullptr) { ChipLogError(Controller, "Device Controller Factory already initialized..."); return CHIP_NO_ERROR; } // Save our initialization state that we can't recover later from a // created-but-shut-down system state. mListenPort = params.listenPort; mFabricIndependentStorage = params.fabricIndependentStorage; mEnableServerInteractions = params.enableServerInteractions; CHIP_ERROR err = InitSystemState(params); return err; } CHIP_ERROR DeviceControllerFactory::InitSystemState() { FactoryInitParams params; if (mSystemState != nullptr) { params.systemLayer = mSystemState->SystemLayer(); params.tcpEndPointManager = mSystemState->TCPEndPointManager(); params.udpEndPointManager = mSystemState->UDPEndPointManager(); #if CONFIG_NETWORK_LAYER_BLE params.bleLayer = mSystemState->BleLayer(); #endif params.listenPort = mListenPort; params.fabricIndependentStorage = mFabricIndependentStorage; params.enableServerInteractions = mEnableServerInteractions; params.groupDataProvider = mSystemState->GetGroupDataProvider(); } return InitSystemState(params); } CHIP_ERROR DeviceControllerFactory::InitSystemState(FactoryInitParams params) { if (mSystemState != nullptr && mSystemState->IsInitialized()) { return CHIP_NO_ERROR; } if (mSystemState != nullptr) { mSystemState->Release(); chip::Platform::Delete(mSystemState); mSystemState = nullptr; } DeviceControllerSystemStateParams stateParams; #if CONFIG_DEVICE_LAYER ReturnErrorOnFailure(DeviceLayer::PlatformMgr().InitChipStack()); stateParams.systemLayer = &DeviceLayer::SystemLayer(); stateParams.tcpEndPointManager = DeviceLayer::TCPEndPointManager(); stateParams.udpEndPointManager = DeviceLayer::UDPEndPointManager(); #else stateParams.systemLayer = params.systemLayer; stateParams.tcpEndPointManager = params.tcpEndPointManager; stateParams.udpEndPointManager = params.udpEndPointManager; ChipLogError(Controller, "Warning: Device Controller Factory should be with a CHIP Device Layer..."); #endif // CONFIG_DEVICE_LAYER VerifyOrReturnError(stateParams.systemLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(stateParams.udpEndPointManager != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #if CONFIG_NETWORK_LAYER_BLE #if CONFIG_DEVICE_LAYER stateParams.bleLayer = DeviceLayer::ConnectivityMgr().GetBleLayer(); #else stateParams.bleLayer = params.bleLayer; #endif // CONFIG_DEVICE_LAYER VerifyOrReturnError(stateParams.bleLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #endif stateParams.transportMgr = chip::Platform::New<DeviceTransportMgr>(); // // The logic below expects IPv6 to be at index 0 of this tuple. Please do not alter that. // ReturnErrorOnFailure(stateParams.transportMgr->Init(Transport::UdpListenParameters(stateParams.udpEndPointManager) .SetAddressType(Inet::IPAddressType::kIPv6) .SetListenPort(params.listenPort) #if INET_CONFIG_ENABLE_IPV4 , Transport::UdpListenParameters(stateParams.udpEndPointManager) .SetAddressType(Inet::IPAddressType::kIPv4) .SetListenPort(params.listenPort) #endif #if CONFIG_NETWORK_LAYER_BLE , Transport::BleListenParameters(stateParams.bleLayer) #endif )); stateParams.fabricTable = chip::Platform::New<FabricTable>(); stateParams.sessionMgr = chip::Platform::New<SessionManager>(); SimpleSessionResumptionStorage * sessionResumptionStorage = chip::Platform::New<SimpleSessionResumptionStorage>(); stateParams.sessionResumptionStorage = sessionResumptionStorage; stateParams.exchangeMgr = chip::Platform::New<Messaging::ExchangeManager>(); stateParams.messageCounterManager = chip::Platform::New<secure_channel::MessageCounterManager>(); stateParams.groupDataProvider = params.groupDataProvider; ReturnErrorOnFailure(stateParams.fabricTable->Init(params.fabricIndependentStorage)); ReturnErrorOnFailure(sessionResumptionStorage->Init(params.fabricIndependentStorage)); auto delegate = chip::Platform::MakeUnique<ControllerFabricDelegate>(); ReturnErrorOnFailure(delegate->Init(stateParams.sessionMgr, stateParams.groupDataProvider)); ReturnErrorOnFailure(stateParams.fabricTable->AddFabricDelegate(delegate.get())); delegate.release(); ReturnErrorOnFailure(stateParams.sessionMgr->Init(stateParams.systemLayer, stateParams.transportMgr, stateParams.messageCounterManager, params.fabricIndependentStorage, stateParams.fabricTable)); ReturnErrorOnFailure(stateParams.exchangeMgr->Init(stateParams.sessionMgr)); ReturnErrorOnFailure(stateParams.messageCounterManager->Init(stateParams.exchangeMgr)); InitDataModelHandler(stateParams.exchangeMgr); ReturnErrorOnFailure(chip::app::InteractionModelEngine::GetInstance()->Init(stateParams.exchangeMgr)); ReturnErrorOnFailure(Dnssd::Resolver::Instance().Init(stateParams.udpEndPointManager)); if (params.enableServerInteractions) { stateParams.caseServer = chip::Platform::New<CASEServer>(); // // Enable listening for session establishment messages. // // We pass in a nullptr for the BLELayer since we're not permitting usage of BLE in this server modality for the controller, // especially since it will interrupt other potential usages of BLE by the controller acting in a commissioning capacity. // ReturnErrorOnFailure(stateParams.caseServer->ListenForSessionEstablishment( stateParams.exchangeMgr, stateParams.transportMgr, stateParams.sessionMgr, stateParams.fabricTable, stateParams.sessionResumptionStorage, stateParams.groupDataProvider)); // // We need to advertise the port that we're listening to for unsolicited messages over UDP. However, we have both a IPv4 // and IPv6 endpoint to pick from. Given that the listen port passed in may be set to 0 (which then has the kernel select // a valid port at bind time), that will result in two possible ports being provided back from the resultant endpoint // initializations. Since IPv6 is POR for Matter, let's go ahead and pick that port. // app::DnssdServer::Instance().SetSecuredPort(stateParams.transportMgr->GetTransport().GetImplAtIndex<0>().GetBoundPort()); // // TODO: This is a hack to workaround the fact that we have a bi-polar stack that has controller and server modalities that // are mutually exclusive in terms of initialization of key stack singletons. Consequently, DnssdServer accesses // Server::GetInstance().GetFabricTable() to access the fabric table, but we don't want to do that when we're initializing // the controller logic since the factory here has its own fabric table. // // Consequently, reach in set the fabric table pointer to point to the right version. // app::DnssdServer::Instance().SetFabricTable(stateParams.fabricTable); // // Start up the DNS-SD server. We are not giving it a // CommissioningModeProvider, so it will not claim we are in // commissioning mode. // chip::app::DnssdServer::Instance().StartServer(); } stateParams.operationalDevicePool = Platform::New<DeviceControllerSystemStateParams::OperationalDevicePool>(); stateParams.caseClientPool = Platform::New<DeviceControllerSystemStateParams::CASEClientPool>(); DeviceProxyInitParams deviceInitParams = { .sessionManager = stateParams.sessionMgr, .sessionResumptionStorage = stateParams.sessionResumptionStorage, .exchangeMgr = stateParams.exchangeMgr, .fabricTable = stateParams.fabricTable, .clientPool = stateParams.caseClientPool, .groupDataProvider = stateParams.groupDataProvider, .mrpLocalConfig = Optional<ReliableMessageProtocolConfig>::Value(GetLocalMRPConfig()), }; CASESessionManagerConfig sessionManagerConfig = { .sessionInitParams = deviceInitParams, .devicePool = stateParams.operationalDevicePool, }; // TODO: Need to be able to create a CASESessionManagerConfig here! stateParams.caseSessionManager = Platform::New<CASESessionManager>(); ReturnErrorOnFailure(stateParams.caseSessionManager->Init(stateParams.systemLayer, sessionManagerConfig)); // store the system state mSystemState = chip::Platform::New<DeviceControllerSystemState>(stateParams); ChipLogDetail(Controller, "System State Initialized..."); return CHIP_NO_ERROR; } void DeviceControllerFactory::PopulateInitParams(ControllerInitParams & controllerParams, const SetupParams & params) { controllerParams.operationalCredentialsDelegate = params.operationalCredentialsDelegate; controllerParams.operationalKeypair = params.operationalKeypair; controllerParams.controllerNOC = params.controllerNOC; controllerParams.controllerICAC = params.controllerICAC; controllerParams.controllerRCAC = params.controllerRCAC; controllerParams.systemState = mSystemState; controllerParams.controllerVendorId = params.controllerVendorId; controllerParams.enableServerInteractions = params.enableServerInteractions; } CHIP_ERROR DeviceControllerFactory::SetupController(SetupParams params, DeviceController & controller) { VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); ReturnErrorOnFailure(InitSystemState()); ControllerInitParams controllerParams; PopulateInitParams(controllerParams, params); CHIP_ERROR err = controller.Init(controllerParams); return err; } CHIP_ERROR DeviceControllerFactory::SetupCommissioner(SetupParams params, DeviceCommissioner & commissioner) { VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); ReturnErrorOnFailure(InitSystemState()); CommissionerInitParams commissionerParams; // PopulateInitParams works against ControllerInitParams base class of CommissionerInitParams only PopulateInitParams(commissionerParams, params); // Set commissioner-specific fields not in ControllerInitParams commissionerParams.pairingDelegate = params.pairingDelegate; commissionerParams.defaultCommissioner = params.defaultCommissioner; CHIP_ERROR err = commissioner.Init(commissionerParams); return err; } CHIP_ERROR DeviceControllerFactory::ServiceEvents() { VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); #if CONFIG_DEVICE_LAYER ReturnErrorOnFailure(DeviceLayer::PlatformMgr().StartEventLoopTask()); #endif // CONFIG_DEVICE_LAYER return CHIP_NO_ERROR; } DeviceControllerFactory::~DeviceControllerFactory() { Shutdown(); } void DeviceControllerFactory::Shutdown() { if (mSystemState != nullptr) { mSystemState->Release(); chip::Platform::Delete(mSystemState); mSystemState = nullptr; } mFabricIndependentStorage = nullptr; } CHIP_ERROR DeviceControllerSystemState::Shutdown() { VerifyOrReturnError(mRefCount == 1, CHIP_ERROR_INCORRECT_STATE); ChipLogDetail(Controller, "Shutting down the System State, this will teardown the CHIP Stack"); if (mCASEServer != nullptr) { chip::Platform::Delete(mCASEServer); mCASEServer = nullptr; } if (mCASESessionManager != nullptr) { mCASESessionManager->Shutdown(); Platform::Delete(mCASESessionManager); mCASESessionManager = nullptr; } // mCASEClientPool and mDevicePool must be deallocated // after mCASESessionManager, which uses them. if (mOperationalDevicePool != nullptr) { Platform::Delete(mOperationalDevicePool); mOperationalDevicePool = nullptr; } if (mCASEClientPool != nullptr) { Platform::Delete(mCASEClientPool); mCASEClientPool = nullptr; } Dnssd::Resolver::Instance().Shutdown(); // Shut down the interaction model app::InteractionModelEngine::GetInstance()->Shutdown(); // Shut down the TransportMgr. This holds Inet::UDPEndPoints so it must be shut down // before PlatformMgr().Shutdown() shuts down Inet. if (mTransportMgr != nullptr) { mTransportMgr->Close(); chip::Platform::Delete(mTransportMgr); mTransportMgr = nullptr; } #if CONFIG_DEVICE_LAYER // // We can safely call PlatformMgr().Shutdown(), which like DeviceController::Shutdown(), // expects to be called with external thread synchronization and will not try to acquire the // stack lock. // // Actually stopping the event queue is a separable call that applications will have to sequence. // Consumers are expected to call PlaformMgr().StopEventLoopTask() before calling // DeviceController::Shutdown() in the CONFIG_DEVICE_LAYER configuration // ReturnErrorOnFailure(DeviceLayer::PlatformMgr().Shutdown()); #endif if (mExchangeMgr != nullptr) { mExchangeMgr->Shutdown(); } if (mSessionMgr != nullptr) { mSessionMgr->Shutdown(); } mSystemLayer = nullptr; mTCPEndPointManager = nullptr; mUDPEndPointManager = nullptr; #if CONFIG_NETWORK_LAYER_BLE mBleLayer = nullptr; #endif // CONFIG_NETWORK_LAYER_BLE if (mMessageCounterManager != nullptr) { chip::Platform::Delete(mMessageCounterManager); mMessageCounterManager = nullptr; } if (mExchangeMgr != nullptr) { chip::Platform::Delete(mExchangeMgr); mExchangeMgr = nullptr; } if (mSessionMgr != nullptr) { chip::Platform::Delete(mSessionMgr); mSessionMgr = nullptr; } if (mFabrics != nullptr) { chip::Platform::Delete(mFabrics); mFabrics = nullptr; } return CHIP_NO_ERROR; } } // namespace Controller } // namespace chip
/* * * Copyright (c) 2021 Project CHIP 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. */ /** * @file * Implementation of CHIP Device Controller Factory, a utility/manager class * that vends Controller objects */ #include <controller/CHIPDeviceControllerFactory.h> #include <app/OperationalDeviceProxy.h> #include <app/util/DataModelHandler.h> #include <lib/support/ErrorStr.h> #include <messaging/ReliableMessageProtocolConfig.h> #if CONFIG_DEVICE_LAYER #include <platform/CHIPDeviceLayer.h> #include <platform/ConfigurationManager.h> #endif #include <app/server/Dnssd.h> #include <protocols/secure_channel/CASEServer.h> #include <protocols/secure_channel/SimpleSessionResumptionStorage.h> using namespace chip::Inet; using namespace chip::System; using namespace chip::Credentials; namespace chip { namespace Controller { CHIP_ERROR DeviceControllerFactory::Init(FactoryInitParams params) { // SystemState is only set the first time init is called, after that it is managed // internally. If SystemState is set then init has already completed. if (mSystemState != nullptr) { ChipLogError(Controller, "Device Controller Factory already initialized..."); return CHIP_NO_ERROR; } // Save our initialization state that we can't recover later from a // created-but-shut-down system state. mListenPort = params.listenPort; mFabricIndependentStorage = params.fabricIndependentStorage; mEnableServerInteractions = params.enableServerInteractions; CHIP_ERROR err = InitSystemState(params); return err; } CHIP_ERROR DeviceControllerFactory::InitSystemState() { FactoryInitParams params; if (mSystemState != nullptr) { params.systemLayer = mSystemState->SystemLayer(); params.tcpEndPointManager = mSystemState->TCPEndPointManager(); params.udpEndPointManager = mSystemState->UDPEndPointManager(); #if CONFIG_NETWORK_LAYER_BLE params.bleLayer = mSystemState->BleLayer(); #endif params.listenPort = mListenPort; params.fabricIndependentStorage = mFabricIndependentStorage; params.enableServerInteractions = mEnableServerInteractions; params.groupDataProvider = mSystemState->GetGroupDataProvider(); } return InitSystemState(params); } CHIP_ERROR DeviceControllerFactory::InitSystemState(FactoryInitParams params) { if (mSystemState != nullptr && mSystemState->IsInitialized()) { return CHIP_NO_ERROR; } if (mSystemState != nullptr) { mSystemState->Release(); chip::Platform::Delete(mSystemState); mSystemState = nullptr; } DeviceControllerSystemStateParams stateParams; #if CONFIG_DEVICE_LAYER ReturnErrorOnFailure(DeviceLayer::PlatformMgr().InitChipStack()); stateParams.systemLayer = &DeviceLayer::SystemLayer(); stateParams.tcpEndPointManager = DeviceLayer::TCPEndPointManager(); stateParams.udpEndPointManager = DeviceLayer::UDPEndPointManager(); #else stateParams.systemLayer = params.systemLayer; stateParams.tcpEndPointManager = params.tcpEndPointManager; stateParams.udpEndPointManager = params.udpEndPointManager; ChipLogError(Controller, "Warning: Device Controller Factory should be with a CHIP Device Layer..."); #endif // CONFIG_DEVICE_LAYER VerifyOrReturnError(stateParams.systemLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(stateParams.udpEndPointManager != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #if CONFIG_NETWORK_LAYER_BLE #if CONFIG_DEVICE_LAYER stateParams.bleLayer = DeviceLayer::ConnectivityMgr().GetBleLayer(); #else stateParams.bleLayer = params.bleLayer; #endif // CONFIG_DEVICE_LAYER VerifyOrReturnError(stateParams.bleLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #endif stateParams.transportMgr = chip::Platform::New<DeviceTransportMgr>(); // // The logic below expects IPv6 to be at index 0 of this tuple. Please do not alter that. // ReturnErrorOnFailure(stateParams.transportMgr->Init(Transport::UdpListenParameters(stateParams.udpEndPointManager) .SetAddressType(Inet::IPAddressType::kIPv6) .SetListenPort(params.listenPort) #if INET_CONFIG_ENABLE_IPV4 , Transport::UdpListenParameters(stateParams.udpEndPointManager) .SetAddressType(Inet::IPAddressType::kIPv4) .SetListenPort(params.listenPort) #endif #if CONFIG_NETWORK_LAYER_BLE , Transport::BleListenParameters(stateParams.bleLayer) #endif )); stateParams.fabricTable = chip::Platform::New<FabricTable>(); stateParams.sessionMgr = chip::Platform::New<SessionManager>(); SimpleSessionResumptionStorage * sessionResumptionStorage = chip::Platform::New<SimpleSessionResumptionStorage>(); stateParams.sessionResumptionStorage = sessionResumptionStorage; stateParams.exchangeMgr = chip::Platform::New<Messaging::ExchangeManager>(); stateParams.messageCounterManager = chip::Platform::New<secure_channel::MessageCounterManager>(); stateParams.groupDataProvider = params.groupDataProvider; ReturnErrorOnFailure(stateParams.fabricTable->Init(params.fabricIndependentStorage)); ReturnErrorOnFailure(sessionResumptionStorage->Init(params.fabricIndependentStorage)); auto delegate = chip::Platform::MakeUnique<ControllerFabricDelegate>(); ReturnErrorOnFailure(delegate->Init(stateParams.sessionMgr, stateParams.groupDataProvider)); ReturnErrorOnFailure(stateParams.fabricTable->AddFabricDelegate(delegate.get())); delegate.release(); ReturnErrorOnFailure(stateParams.sessionMgr->Init(stateParams.systemLayer, stateParams.transportMgr, stateParams.messageCounterManager, params.fabricIndependentStorage, stateParams.fabricTable)); ReturnErrorOnFailure(stateParams.exchangeMgr->Init(stateParams.sessionMgr)); ReturnErrorOnFailure(stateParams.messageCounterManager->Init(stateParams.exchangeMgr)); InitDataModelHandler(stateParams.exchangeMgr); ReturnErrorOnFailure(chip::app::InteractionModelEngine::GetInstance()->Init(stateParams.exchangeMgr)); ReturnErrorOnFailure(Dnssd::Resolver::Instance().Init(stateParams.udpEndPointManager)); if (params.enableServerInteractions) { stateParams.caseServer = chip::Platform::New<CASEServer>(); // Enable listening for session establishment messages. ReturnErrorOnFailure(stateParams.caseServer->ListenForSessionEstablishment( stateParams.exchangeMgr, stateParams.transportMgr, stateParams.sessionMgr, stateParams.fabricTable, stateParams.sessionResumptionStorage, stateParams.groupDataProvider)); // // We need to advertise the port that we're listening to for unsolicited messages over UDP. However, we have both a IPv4 // and IPv6 endpoint to pick from. Given that the listen port passed in may be set to 0 (which then has the kernel select // a valid port at bind time), that will result in two possible ports being provided back from the resultant endpoint // initializations. Since IPv6 is POR for Matter, let's go ahead and pick that port. // app::DnssdServer::Instance().SetSecuredPort(stateParams.transportMgr->GetTransport().GetImplAtIndex<0>().GetBoundPort()); // // TODO: This is a hack to workaround the fact that we have a bi-polar stack that has controller and server modalities that // are mutually exclusive in terms of initialization of key stack singletons. Consequently, DnssdServer accesses // Server::GetInstance().GetFabricTable() to access the fabric table, but we don't want to do that when we're initializing // the controller logic since the factory here has its own fabric table. // // Consequently, reach in set the fabric table pointer to point to the right version. // app::DnssdServer::Instance().SetFabricTable(stateParams.fabricTable); // // Start up the DNS-SD server. We are not giving it a // CommissioningModeProvider, so it will not claim we are in // commissioning mode. // chip::app::DnssdServer::Instance().StartServer(); } stateParams.operationalDevicePool = Platform::New<DeviceControllerSystemStateParams::OperationalDevicePool>(); stateParams.caseClientPool = Platform::New<DeviceControllerSystemStateParams::CASEClientPool>(); DeviceProxyInitParams deviceInitParams = { .sessionManager = stateParams.sessionMgr, .sessionResumptionStorage = stateParams.sessionResumptionStorage, .exchangeMgr = stateParams.exchangeMgr, .fabricTable = stateParams.fabricTable, .clientPool = stateParams.caseClientPool, .groupDataProvider = stateParams.groupDataProvider, .mrpLocalConfig = Optional<ReliableMessageProtocolConfig>::Value(GetLocalMRPConfig()), }; CASESessionManagerConfig sessionManagerConfig = { .sessionInitParams = deviceInitParams, .devicePool = stateParams.operationalDevicePool, }; // TODO: Need to be able to create a CASESessionManagerConfig here! stateParams.caseSessionManager = Platform::New<CASESessionManager>(); ReturnErrorOnFailure(stateParams.caseSessionManager->Init(stateParams.systemLayer, sessionManagerConfig)); // store the system state mSystemState = chip::Platform::New<DeviceControllerSystemState>(stateParams); ChipLogDetail(Controller, "System State Initialized..."); return CHIP_NO_ERROR; } void DeviceControllerFactory::PopulateInitParams(ControllerInitParams & controllerParams, const SetupParams & params) { controllerParams.operationalCredentialsDelegate = params.operationalCredentialsDelegate; controllerParams.operationalKeypair = params.operationalKeypair; controllerParams.controllerNOC = params.controllerNOC; controllerParams.controllerICAC = params.controllerICAC; controllerParams.controllerRCAC = params.controllerRCAC; controllerParams.systemState = mSystemState; controllerParams.controllerVendorId = params.controllerVendorId; controllerParams.enableServerInteractions = params.enableServerInteractions; } CHIP_ERROR DeviceControllerFactory::SetupController(SetupParams params, DeviceController & controller) { VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); ReturnErrorOnFailure(InitSystemState()); ControllerInitParams controllerParams; PopulateInitParams(controllerParams, params); CHIP_ERROR err = controller.Init(controllerParams); return err; } CHIP_ERROR DeviceControllerFactory::SetupCommissioner(SetupParams params, DeviceCommissioner & commissioner) { VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); ReturnErrorOnFailure(InitSystemState()); CommissionerInitParams commissionerParams; // PopulateInitParams works against ControllerInitParams base class of CommissionerInitParams only PopulateInitParams(commissionerParams, params); // Set commissioner-specific fields not in ControllerInitParams commissionerParams.pairingDelegate = params.pairingDelegate; commissionerParams.defaultCommissioner = params.defaultCommissioner; CHIP_ERROR err = commissioner.Init(commissionerParams); return err; } CHIP_ERROR DeviceControllerFactory::ServiceEvents() { VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); #if CONFIG_DEVICE_LAYER ReturnErrorOnFailure(DeviceLayer::PlatformMgr().StartEventLoopTask()); #endif // CONFIG_DEVICE_LAYER return CHIP_NO_ERROR; } DeviceControllerFactory::~DeviceControllerFactory() { Shutdown(); } void DeviceControllerFactory::Shutdown() { if (mSystemState != nullptr) { mSystemState->Release(); chip::Platform::Delete(mSystemState); mSystemState = nullptr; } mFabricIndependentStorage = nullptr; } CHIP_ERROR DeviceControllerSystemState::Shutdown() { VerifyOrReturnError(mRefCount == 1, CHIP_ERROR_INCORRECT_STATE); ChipLogDetail(Controller, "Shutting down the System State, this will teardown the CHIP Stack"); if (mCASEServer != nullptr) { chip::Platform::Delete(mCASEServer); mCASEServer = nullptr; } if (mCASESessionManager != nullptr) { mCASESessionManager->Shutdown(); Platform::Delete(mCASESessionManager); mCASESessionManager = nullptr; } // mCASEClientPool and mDevicePool must be deallocated // after mCASESessionManager, which uses them. if (mOperationalDevicePool != nullptr) { Platform::Delete(mOperationalDevicePool); mOperationalDevicePool = nullptr; } if (mCASEClientPool != nullptr) { Platform::Delete(mCASEClientPool); mCASEClientPool = nullptr; } Dnssd::Resolver::Instance().Shutdown(); // Shut down the interaction model app::InteractionModelEngine::GetInstance()->Shutdown(); // Shut down the TransportMgr. This holds Inet::UDPEndPoints so it must be shut down // before PlatformMgr().Shutdown() shuts down Inet. if (mTransportMgr != nullptr) { mTransportMgr->Close(); chip::Platform::Delete(mTransportMgr); mTransportMgr = nullptr; } #if CONFIG_DEVICE_LAYER // // We can safely call PlatformMgr().Shutdown(), which like DeviceController::Shutdown(), // expects to be called with external thread synchronization and will not try to acquire the // stack lock. // // Actually stopping the event queue is a separable call that applications will have to sequence. // Consumers are expected to call PlaformMgr().StopEventLoopTask() before calling // DeviceController::Shutdown() in the CONFIG_DEVICE_LAYER configuration // ReturnErrorOnFailure(DeviceLayer::PlatformMgr().Shutdown()); #endif if (mExchangeMgr != nullptr) { mExchangeMgr->Shutdown(); } if (mSessionMgr != nullptr) { mSessionMgr->Shutdown(); } mSystemLayer = nullptr; mTCPEndPointManager = nullptr; mUDPEndPointManager = nullptr; #if CONFIG_NETWORK_LAYER_BLE mBleLayer = nullptr; #endif // CONFIG_NETWORK_LAYER_BLE if (mMessageCounterManager != nullptr) { chip::Platform::Delete(mMessageCounterManager); mMessageCounterManager = nullptr; } if (mExchangeMgr != nullptr) { chip::Platform::Delete(mExchangeMgr); mExchangeMgr = nullptr; } if (mSessionMgr != nullptr) { chip::Platform::Delete(mSessionMgr); mSessionMgr = nullptr; } if (mFabrics != nullptr) { chip::Platform::Delete(mFabrics); mFabrics = nullptr; } return CHIP_NO_ERROR; } } // namespace Controller } // namespace chip
Remove meaningless comment (#17582)
Remove meaningless comment (#17582)
C++
apache-2.0
project-chip/connectedhomeip,nestlabs/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,nestlabs/connectedhomeip
549553254c3e3736a72db23e74a32b897e2db18e
src/plugins/winrt/src/winrt_platform.cpp
src/plugins/winrt/src/winrt_platform.cpp
#include "winrt_system.h" #ifdef WINDOWS_STORE #include "winrt_platform.h" #include "winrt_http.h" #include "xbl_manager.h" using namespace Halley; WinRTPlatform::WinRTPlatform(WinRTSystem* system) : system(system) { } void WinRTPlatform::init() { xbl = std::make_shared<XBLManager>(); xbl->init(); } void WinRTPlatform::deInit() { xbl.reset(); } void WinRTPlatform::update() {} std::unique_ptr<HTTPRequest> WinRTPlatform::makeHTTPRequest(const String& method, const String& url) { return std::make_unique<WinRTHTTPRequest>(method, url); } bool WinRTPlatform::canProvideAuthToken() const { return true; } Future<std::unique_ptr<AuthorisationToken>> WinRTPlatform::getAuthToken() { return xbl->getAuthToken(); } bool WinRTPlatform::canProvideCloudSave() const { return true; } std::shared_ptr<ISaveData> WinRTPlatform::getCloudSaveContainer(const String& containerName) { return xbl->getSaveContainer(containerName); } #endif
#include "winrt_system.h" #ifdef WINDOWS_STORE #include "winrt_platform.h" #include "winrt_http.h" #include "xbl_manager.h" using namespace Halley; WinRTPlatform::WinRTPlatform(WinRTSystem* system) : system(system) { } void WinRTPlatform::init() { xbl = std::make_shared<XBLManager>(); xbl->init(); } void WinRTPlatform::deInit() { xbl.reset(); } void WinRTPlatform::update() {} std::unique_ptr<HTTPRequest> WinRTPlatform::makeHTTPRequest(const String& method, const String& url) { return std::make_unique<WinRTHTTPRequest>(method, url); } bool WinRTPlatform::canProvideAuthToken() const { return true; } Future<std::unique_ptr<AuthorisationToken>> WinRTPlatform::getAuthToken() { return xbl->getAuthToken(); } bool WinRTPlatform::canProvideCloudSave() const { return false; } std::shared_ptr<ISaveData> WinRTPlatform::getCloudSaveContainer(const String& containerName) { return xbl->getSaveContainer(containerName); } #endif
Disable UWP cloud save
Disable UWP cloud save
C++
apache-2.0
amzeratul/halley,amzeratul/halley,amzeratul/halley
996ad5b8b64faf63192d3e661b448f1cb5842470
src/examples/box_cxx_example_02.cc
src/examples/box_cxx_example_02.cc
//Compile with: //gcc -g box_example_02.c -o box_example_02 `pkg-config --cflags --libs elementary` #ifdef HAVE_CONFIG_H # include <elementary_config.h> #endif #define ELM_INTERNAL_API_ARGESFSDFEFC #define ELM_INTERFACE_ATSPI_ACCESSIBLE_PROTECTED #define ELM_INTERFACE_ATSPI_COMPONENT_PROTECTED #define ELM_INTERFACE_ATSPI_ACTION_PROTECTED #define ELM_INTERFACE_ATSPI_VALUE_PROTECTED #define ELM_INTERFACE_ATSPI_EDITABLE_TEXT_PROTECTED #define ELM_INTERFACE_ATSPI_TEXT_PROTECTED #define ELM_INTERFACE_ATSPI_SELECTION_PROTECTED #define ELM_INTERFACE_ATSPI_IMAGE_PROTECTED #define ELM_INTERFACE_ATSPI_WIDGET_ACTION_PROTECTED #include <iostream> #include <Elementary.h> #include <Eo.h> #include <Evas.h> #include <Elementary.h> #include <elm_widget.h> #include "elm_interface_atspi_accessible.h" #include "elm_interface_atspi_accessible.eo.h" #include "elm_interface_atspi_widget_action.h" #include "elm_interface_atspi_widget_action.eo.h" #include <elm_win.eo.hh> #include <elm_box.eo.hh> #include <elm_button.eo.hh> #include <Eina.hh> #include <deque> struct Transitions_Data { efl::eo::wref<elm_box> box; std::deque<Evas_Object_Box_Layout> transitions; Evas_Object_Box_Layout last_layout; }; static void _test_box_transition_change(void *data) { Transitions_Data *tdata = static_cast<Transitions_Data*>(data); Elm_Box_Transition *layout_data; Evas_Object_Box_Layout next_layout; assert (!!data); assert (!tdata->transitions.empty()); if(efl::eina::optional<elm_box> box = tdata->box.lock()) { next_layout = tdata->transitions.front(); layout_data = elm_box_transition_new(2.0, tdata->transitions.back(), nullptr, nullptr, next_layout, nullptr, nullptr, _test_box_transition_change, tdata); box->layout_set(elm_box_layout_transition, layout_data, elm_box_transition_free); tdata->last_layout = next_layout; tdata->transitions.push_back(tdata->transitions[0]); tdata->transitions.pop_front(); } } struct clean_ref { clean_ref(efl::eo::base base) : _ref(base._eo_ptr()) {} template <typename T> void operator()(T const&, Eo_Event_Description const&, void*) const { if(_ref) eo_unref(_ref); } Eo* _ref; }; EAPI_MAIN int elm_main(int argc, char *argv[]) { elm_policy_set(ELM_POLICY_QUIT, ELM_POLICY_QUIT_LAST_WINDOW_CLOSED); Transitions_Data tdata; Eo* test; { ::elm_win win (elm_win_util_standard_add("box-transition", "Box Transition")); win.autodel_set(true); elm_box bigbox ( efl::eo::parent = win ); bigbox.size_hint_weight_set(EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); win.resize_object_add(bigbox); bigbox.visibility_set(true); win.callback_del_add(clean_ref(bigbox)); elm_box buttons ( efl::eo::parent = win ); buttons.horizontal_set(EINA_TRUE); bigbox.pack_end(buttons); buttons.visibility_set(true); win.callback_del_add(clean_ref(buttons)); elm_button add ( efl::eo::parent = win ); add.text_set("elm.text", "Add"); buttons.pack_end(add); add.visibility_set(true); add.callback_clicked_add (std::bind([&tdata] { if(efl::eina::optional<elm_box> box = tdata.box.lock()) { elm_button btn ( efl::eo::parent = *box ); btn.text_set("elm.text", "I do nothing"); efl::eina::list<evas::object> childrens = box->children_get(); if (!childrens.empty()) { box->pack_after(btn, childrens.front()); } else box->pack_end(btn); btn.visibility_set(true); } })); win.callback_del_add(clean_ref(add)); elm_button clear ( efl::eo::parent = win ); clear.text_set("elm.text", "Clear"); buttons.pack_end(clear); clear.visibility_set(true); clear.callback_clicked_add(std::bind([&tdata] { tdata.box.lock()->clear(); })); win.callback_del_add(clean_ref(clear)); elm_box dynamic ( efl::eo::parent = win ); dynamic.size_hint_weight_set(EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); dynamic.size_hint_align_set(EVAS_HINT_FILL, EVAS_HINT_FILL); bigbox.pack_end(dynamic); dynamic.visibility_set(true); win.callback_del_add(clean_ref(dynamic)); auto unpack = std::bind([&tdata] (evas::clickable_interface obj) { elm_button btn = efl::eo::downcast<elm_button>(obj); tdata.box.lock()->unpack(btn); btn.position_set(0, 50); btn.color_set(128, 64, 0, 128); }, std::placeholders::_1) ; elm_button bt1 ( efl::eo::parent = win ); bt1.text_set("elm.text", "Button 1"); bt1.callback_clicked_add(unpack); bt1.size_hint_weight_set(EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); bt1.size_hint_align_set(EVAS_HINT_FILL, EVAS_HINT_FILL); dynamic.pack_end(bt1); bt1.visibility_set(true); win.callback_del_add(clean_ref(bt1)); elm_button bt2 ( efl::eo::parent = win ); bt2.text_set("elm.text", "Button 2"); bt2.size_hint_weight_set(EVAS_HINT_EXPAND, 0.0); bt2.size_hint_align_set(1.0, 0.5); bt2.callback_clicked_add(unpack); dynamic.pack_end(bt2); bt2.visibility_set(true); win.callback_del_add(clean_ref(bt2)); elm_button bt3 ( efl::eo::parent = win ); bt3.text_set("elm.text", "Button 3"); bt3.callback_clicked_add(unpack); dynamic.pack_end(bt3); bt3.visibility_set(true); win.callback_del_add(clean_ref(bt3)); tdata.box = dynamic; tdata.last_layout = evas_object_box_layout_horizontal; tdata.transitions.push_back(evas_object_box_layout_vertical); tdata.transitions.push_back(evas_object_box_layout_horizontal); tdata.transitions.push_back(evas_object_box_layout_stack); tdata.transitions.push_back(evas_object_box_layout_homogeneous_vertical); tdata.transitions.push_back(evas_object_box_layout_homogeneous_horizontal); tdata.transitions.push_back(evas_object_box_layout_flow_vertical); tdata.transitions.push_back(evas_object_box_layout_flow_horizontal); tdata.transitions.push_back(evas_object_box_layout_stack); dynamic.layout_set(evas_object_box_layout_horizontal, nullptr, nullptr); _test_box_transition_change(&tdata); win.size_set(300, 320); win.visibility_set(true); std::cout << "references to win " << win.ref_get() << std::endl; test = win._eo_ptr(); win._release(); } std::cout << "references to win " << ::eo_ref_get(test) << std::endl; elm_run(); elm_shutdown(); return 0; } ELM_MAIN()
//Compile with: //gcc -g box_example_02.c -o box_example_02 `pkg-config --cflags --libs elementary` extern "C" { #ifdef HAVE_CONFIG_H # include <elementary_config.h> #endif #define ELM_INTERNAL_API_ARGESFSDFEFC #define ELM_INTERFACE_ATSPI_ACCESSIBLE_PROTECTED #define ELM_INTERFACE_ATSPI_COMPONENT_PROTECTED #define ELM_INTERFACE_ATSPI_ACTION_PROTECTED #define ELM_INTERFACE_ATSPI_VALUE_PROTECTED #define ELM_INTERFACE_ATSPI_EDITABLE_TEXT_PROTECTED #define ELM_INTERFACE_ATSPI_TEXT_PROTECTED #define ELM_INTERFACE_ATSPI_SELECTION_PROTECTED #define ELM_INTERFACE_ATSPI_IMAGE_PROTECTED #define ELM_INTERFACE_ATSPI_WIDGET_ACTION_PROTECTED #include <Elementary.h> #include <Eo.h> #include <Evas.h> #include <Elementary.h> #include <elm_widget.h> #include "elm_interface_atspi_accessible.h" #include "elm_interface_atspi_accessible.eo.h" #include "elm_interface_atspi_widget_action.h" #include "elm_interface_atspi_widget_action.eo.h" } #include <iostream> #include <elm_win.eo.hh> #include <elm_box.eo.hh> #include <elm_button.eo.hh> #include <Eina.hh> #include <deque> struct Transitions_Data { efl::eo::wref<elm_box> box; std::deque<Evas_Object_Box_Layout> transitions; Evas_Object_Box_Layout last_layout; }; static void _test_box_transition_change(void *data) { Transitions_Data *tdata = static_cast<Transitions_Data*>(data); Elm_Box_Transition *layout_data; Evas_Object_Box_Layout next_layout; assert (!!data); assert (!tdata->transitions.empty()); if(efl::eina::optional<elm_box> box = tdata->box.lock()) { next_layout = tdata->transitions.front(); layout_data = elm_box_transition_new(2.0, tdata->transitions.back(), nullptr, nullptr, next_layout, nullptr, nullptr, _test_box_transition_change, tdata); box->layout_set(elm_box_layout_transition, layout_data, elm_box_transition_free); tdata->last_layout = next_layout; tdata->transitions.push_back(tdata->transitions[0]); tdata->transitions.pop_front(); } } struct clean_ref { clean_ref(efl::eo::base base) : _ref(base._eo_ptr()) {} template <typename T> void operator()(T const&, Eo_Event_Description const&, void*) const { if(_ref) eo_unref(_ref); } Eo* _ref; }; EAPI_MAIN int elm_main(int argc, char *argv[]) { elm_policy_set(ELM_POLICY_QUIT, ELM_POLICY_QUIT_LAST_WINDOW_CLOSED); Transitions_Data tdata; Eo* test; { ::elm_win win (elm_win_util_standard_add("box-transition", "Box Transition")); win.autodel_set(true); elm_box bigbox ( efl::eo::parent = win ); bigbox.size_hint_weight_set(EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); win.resize_object_add(bigbox); bigbox.visibility_set(true); win.callback_del_add(clean_ref(bigbox)); elm_box buttons ( efl::eo::parent = win ); buttons.horizontal_set(EINA_TRUE); bigbox.pack_end(buttons); buttons.visibility_set(true); win.callback_del_add(clean_ref(buttons)); elm_button add ( efl::eo::parent = win ); add.text_set("elm.text", "Add"); buttons.pack_end(add); add.visibility_set(true); add.callback_clicked_add (std::bind([&tdata] { if(efl::eina::optional<elm_box> box = tdata.box.lock()) { elm_button btn ( efl::eo::parent = *box ); btn.text_set("elm.text", "I do nothing"); efl::eina::list<evas::object> childrens(box->children_get()); if (!childrens.empty()) { box->pack_after(btn, childrens.front()); } else box->pack_end(btn); btn.visibility_set(true); } })); win.callback_del_add(clean_ref(add)); elm_button clear ( efl::eo::parent = win ); clear.text_set("elm.text", "Clear"); buttons.pack_end(clear); clear.visibility_set(true); clear.callback_clicked_add(std::bind([&tdata] { tdata.box.lock()->clear(); })); win.callback_del_add(clean_ref(clear)); elm_box dynamic ( efl::eo::parent = win ); dynamic.size_hint_weight_set(EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); dynamic.size_hint_align_set(EVAS_HINT_FILL, EVAS_HINT_FILL); bigbox.pack_end(dynamic); dynamic.visibility_set(true); win.callback_del_add(clean_ref(dynamic)); auto unpack = std::bind([&tdata] (evas::clickable_interface obj) { elm_button btn = efl::eo::downcast<elm_button>(obj); tdata.box.lock()->unpack(btn); btn.position_set(0, 50); btn.color_set(128, 64, 0, 128); }, std::placeholders::_1) ; elm_button bt1 ( efl::eo::parent = win ); bt1.text_set("elm.text", "Button 1"); bt1.callback_clicked_add(unpack); bt1.size_hint_weight_set(EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); bt1.size_hint_align_set(EVAS_HINT_FILL, EVAS_HINT_FILL); dynamic.pack_end(bt1); bt1.visibility_set(true); win.callback_del_add(clean_ref(bt1)); elm_button bt2 ( efl::eo::parent = win ); bt2.text_set("elm.text", "Button 2"); bt2.size_hint_weight_set(EVAS_HINT_EXPAND, 0.0); bt2.size_hint_align_set(1.0, 0.5); bt2.callback_clicked_add(unpack); dynamic.pack_end(bt2); bt2.visibility_set(true); win.callback_del_add(clean_ref(bt2)); elm_button bt3 ( efl::eo::parent = win ); bt3.text_set("elm.text", "Button 3"); bt3.callback_clicked_add(unpack); dynamic.pack_end(bt3); bt3.visibility_set(true); win.callback_del_add(clean_ref(bt3)); tdata.box = dynamic; tdata.last_layout = evas_object_box_layout_horizontal; tdata.transitions.push_back(evas_object_box_layout_vertical); tdata.transitions.push_back(evas_object_box_layout_horizontal); tdata.transitions.push_back(evas_object_box_layout_stack); tdata.transitions.push_back(evas_object_box_layout_homogeneous_vertical); tdata.transitions.push_back(evas_object_box_layout_homogeneous_horizontal); tdata.transitions.push_back(evas_object_box_layout_flow_vertical); tdata.transitions.push_back(evas_object_box_layout_flow_horizontal); tdata.transitions.push_back(evas_object_box_layout_stack); dynamic.layout_set(evas_object_box_layout_horizontal, nullptr, nullptr); _test_box_transition_change(&tdata); win.size_set(300, 320); win.visibility_set(true); std::cout << "references to win " << win.ref_get() << std::endl; test = win._eo_ptr(); win._release(); } std::cout << "references to win " << ::eo_ref_get(test) << std::endl; elm_run(); elm_shutdown(); return 0; } ELM_MAIN()
Add extern "C" guards to C++ example.
examples: Add extern "C" guards to C++ example.
C++
lgpl-2.1
tasn/elementary,rvandegrift/elementary,FlorentRevest/Elementary,FlorentRevest/Elementary,tasn/elementary,FlorentRevest/Elementary,rvandegrift/elementary,tasn/elementary,rvandegrift/elementary,rvandegrift/elementary,tasn/elementary,FlorentRevest/Elementary,tasn/elementary
05f2f5bcc38eb3f5d83b71a86c7e5bb172247d4e
src/cpp/session/modules/clang/SessionClang.cpp
src/cpp/session/modules/clang/SessionClang.cpp
/* * SessionClang.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionClang.hpp" #include <core/Exec.hpp> #include <core/json/JsonRpc.hpp> #include <core/system/System.hpp> #include <core/system/Process.hpp> #include <r/RSexp.hpp> #include <r/RRoutines.hpp> #include <session/SessionModuleContext.hpp> #include <session/IncrementalFileChangeHandler.hpp> #include "libclang/LibClang.hpp" #include "libclang/UnsavedFiles.hpp" #include "libclang/SourceIndex.hpp" #include "libclang/CompilationDatabase.hpp" #include "CodeCompletion.hpp" using namespace core ; namespace session { namespace modules { namespace clang { using namespace libclang; namespace { bool isCppSourceDoc(const FilePath& filePath) { std::string ex = filePath.extensionLowerCase(); return (ex == ".c" || ex == ".cc" || ex == ".cpp" || ex == ".m" || ex == ".mm"); } bool isMakefile(const FilePath& filePath, const std::string& pkgSrcDir) { if (filePath.parent().absolutePath() == pkgSrcDir) { std::string filename = filePath.filename(); return filename == "Makevars" || filename == "Makevars.win" || filename == "Makefile"; } else { return false; } } bool isPackageBuildFile(const FilePath& filePath) { using namespace projects; FilePath buildTargetPath = projectContext().buildTargetPath(); FilePath descPath = buildTargetPath.childPath("DESCRIPTION"); FilePath srcPath = buildTargetPath.childPath("src"); if (filePath == descPath) { return true; } else if (isMakefile(filePath, srcPath.absolutePath())) { return true; } else { return false; } } bool packageCppFileFilter(const std::string& pkgSrcDir, const std::string& pkgDescFile, const FileInfo& fileInfo) { // create file path FilePath filePath(fileInfo.absolutePath()); // DESCRIPTION file if (filePath.absolutePath() == pkgDescFile) { return true; } // otherwise must be an appropriate file type within the src directory else if (filePath.parent().absolutePath() == pkgSrcDir) { FilePath filePath(fileInfo.absolutePath()); if (isCppSourceDoc(filePath)) { return true; } else if (isMakefile(filePath, pkgSrcDir)) { return true; } else { return false; } } else { return false; } } void fileChangeHandler(const core::system::FileChangeEvent& event) { using namespace core::system; FilePath filePath(event.fileInfo().absolutePath()); // is this a source file? if so updated the source index if (isCppSourceDoc(filePath)) { if (event.type() == FileChangeEvent::FileAdded || event.type() == FileChangeEvent::FileModified) { sourceIndex().updateTranslationUnit(filePath.absolutePath()); } else if (event.type() == FileChangeEvent::FileRemoved) { sourceIndex().removeTranslationUnit(filePath.absolutePath()); } } // is this a build related file? if so update the compilation database else if (isPackageBuildFile(filePath)) { compilationDatabase().updateForCurrentPackage(); } } void onSourceDocUpdated(boost::shared_ptr<source_database::SourceDocument> pDoc) { // ignore if the file doesn't have a path if (pDoc->path().empty()) return; // resolve to a full path FilePath docPath = module_context::resolveAliasedPath(pDoc->path()); // verify that it's an indexable C/C++ file (we allow any and all // files into the database here since these files are open within // the source editor) if (!isCppSourceDoc(docPath)) return; // update unsaved files (we do this even if the document is dirty // as even in this case it will need to be removed from the list // of unsaved files) unsavedFiles().update(pDoc); // if the file isn't dirty of if we've never seen it before then // update the compilation database and/or source index std::string path = docPath.absolutePath(); if (!pDoc->dirty() || !sourceIndex().hasTranslationUnit(path)) { // if this is a standalone c++ file outside of a project then // we need to update it's compilation database projects::ProjectContext& projectContext = projects::projectContext(); if ((projectContext.config().buildType != r_util::kBuildTypePackage) || !docPath.isWithin(projectContext.buildTargetPath().childPath("src"))) { compilationDatabase().updateForStandaloneCpp(docPath); } // update the source index for this file sourceIndex().updateTranslationUnit(path); } } // diagnostic function to assist in determine whether/where // libclang was loaded from (and any errors which occurred // that prevented loading, e.g. inadequate version, missing // symbols, etc.) SEXP rs_isLibClangAvailable() { // check availability std::string diagnostics; bool isAvailable = isLibClangAvailable(&diagnostics); // print diagnostics module_context::consoleWriteOutput(diagnostics); // return status r::sexp::Protect rProtect; return r::sexp::create(isAvailable, &rProtect); } // incremental file change handler boost::scoped_ptr<IncrementalFileChangeHandler> pFileChangeHandler; } // anonymous namespace bool isAvailable() { return clang().isLoaded(); } Error initialize() { // if we don't have a recent version of Rcpp (that can do dryRun with // sourceCpp) then forget it if (!module_context::isPackageVersionInstalled("Rcpp", "0.11.2.7")) return Success(); // attempt to load clang interface loadLibClang(); // register diagnostics function R_CallMethodDef methodDef ; methodDef.name = "rs_isLibClangAvailable" ; methodDef.fun = (DL_FUNC)rs_isLibClangAvailable; methodDef.numArgs = 0; r::routines::addCallMethod(methodDef); // subscribe to onSourceDocUpdated (used for maintaining both the // main source index and the unsaved files list) source_database::events().onDocUpdated.connect(onSourceDocUpdated); // connect source doc removed events to unsaved files list source_database::events().onDocRemoved.connect( boost::bind(&UnsavedFiles::remove, &unsavedFiles(), _1)); source_database::events().onRemoveAll.connect( boost::bind(&UnsavedFiles::removeAll, &unsavedFiles())); // if this is a pakcage with a src directory then initialize various // things related to maintaining the package src index using namespace projects; if ((projectContext().config().buildType == r_util::kBuildTypePackage) && projectContext().buildTargetPath().childPath("src").exists()) { FilePath buildTargetPath = projectContext().buildTargetPath(); FilePath descPath = buildTargetPath.childPath("DESCRIPTION"); FilePath srcPath = projectContext().buildTargetPath().childPath("src"); // update the compilation database for this package compilationDatabase().updateForCurrentPackage(); // filter file change notifications to files of interest IncrementalFileChangeHandler::Filter filter = boost::bind(packageCppFileFilter, srcPath.absolutePath(), descPath.absolutePath(), _1); // create incremental file change handler (this is used for updating // the main source index) pFileChangeHandler.reset(new IncrementalFileChangeHandler( filter, fileChangeHandler, boost::posix_time::milliseconds(200), boost::posix_time::milliseconds(20), false)); /* allow indexing during idle time */ // subscribe to the file monitor pFileChangeHandler->subscribeToFileMonitor("C++ Code Completion"); } ExecBlock initBlock ; using boost::bind; using namespace module_context; initBlock.addFunctions() (bind(registerRpcMethod, "print_cpp_completions", printCppCompletions)); return initBlock.execute(); // return success return Success(); } } // namespace clang } // namespace modules } // namesapce session
/* * SessionClang.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionClang.hpp" #include <core/Exec.hpp> #include <core/json/JsonRpc.hpp> #include <core/system/System.hpp> #include <core/system/Process.hpp> #include <r/RSexp.hpp> #include <r/RRoutines.hpp> #include <session/SessionModuleContext.hpp> #include <session/IncrementalFileChangeHandler.hpp> #include "libclang/LibClang.hpp" #include "libclang/UnsavedFiles.hpp" #include "libclang/SourceIndex.hpp" #include "libclang/CompilationDatabase.hpp" #include "CodeCompletion.hpp" using namespace core ; namespace session { namespace modules { namespace clang { using namespace libclang; namespace { bool isCppSourceDoc(const FilePath& filePath) { std::string ex = filePath.extensionLowerCase(); return (ex == ".c" || ex == ".cc" || ex == ".cpp" || ex == ".m" || ex == ".mm"); } bool isMakefile(const FilePath& filePath, const std::string& pkgSrcDir) { if (filePath.parent().absolutePath() == pkgSrcDir) { std::string filename = filePath.filename(); return filename == "Makevars" || filename == "Makevars.win" || filename == "Makefile"; } else { return false; } } bool isPackageBuildFile(const FilePath& filePath) { using namespace projects; FilePath buildTargetPath = projectContext().buildTargetPath(); FilePath descPath = buildTargetPath.childPath("DESCRIPTION"); FilePath srcPath = buildTargetPath.childPath("src"); if (filePath == descPath) { return true; } else if (isMakefile(filePath, srcPath.absolutePath())) { return true; } else { return false; } } bool packageCppFileFilter(const std::string& pkgSrcDir, const std::string& pkgDescFile, const FileInfo& fileInfo) { // create file path FilePath filePath(fileInfo.absolutePath()); if (!filePath.exists()) return false; // DESCRIPTION file if (filePath.absolutePath() == pkgDescFile) { return true; } // otherwise must be an appropriate file type within the src directory else if (filePath.parent().absolutePath() == pkgSrcDir) { if (isCppSourceDoc(filePath)) { return true; } else if (isMakefile(filePath, pkgSrcDir)) { return true; } else { return false; } } else { return false; } } void fileChangeHandler(const core::system::FileChangeEvent& event) { using namespace core::system; FilePath filePath(event.fileInfo().absolutePath()); // is this a source file? if so updated the source index if (isCppSourceDoc(filePath)) { if (event.type() == FileChangeEvent::FileAdded || event.type() == FileChangeEvent::FileModified) { sourceIndex().updateTranslationUnit(filePath.absolutePath()); } else if (event.type() == FileChangeEvent::FileRemoved) { sourceIndex().removeTranslationUnit(filePath.absolutePath()); } } // is this a build related file? if so update the compilation database else if (isPackageBuildFile(filePath)) { compilationDatabase().updateForCurrentPackage(); } } void onSourceDocUpdated(boost::shared_ptr<source_database::SourceDocument> pDoc) { // ignore if the file doesn't have a path if (pDoc->path().empty()) return; // resolve to a full path FilePath docPath = module_context::resolveAliasedPath(pDoc->path()); // verify that it's an indexable C/C++ file (we allow any and all // files into the database here since these files are open within // the source editor) if (!isCppSourceDoc(docPath)) return; // update unsaved files (we do this even if the document is dirty // as even in this case it will need to be removed from the list // of unsaved files) unsavedFiles().update(pDoc); // if the file isn't dirty of if we've never seen it before then // update the compilation database and/or source index std::string path = docPath.absolutePath(); if (!pDoc->dirty() || !sourceIndex().hasTranslationUnit(path)) { // if this is a standalone c++ file outside of a project then // we need to update it's compilation database projects::ProjectContext& projectContext = projects::projectContext(); if ((projectContext.config().buildType != r_util::kBuildTypePackage) || !docPath.isWithin(projectContext.buildTargetPath().childPath("src"))) { compilationDatabase().updateForStandaloneCpp(docPath); } // update the source index for this file sourceIndex().updateTranslationUnit(path); } } // diagnostic function to assist in determine whether/where // libclang was loaded from (and any errors which occurred // that prevented loading, e.g. inadequate version, missing // symbols, etc.) SEXP rs_isLibClangAvailable() { // check availability std::string diagnostics; bool isAvailable = isLibClangAvailable(&diagnostics); // print diagnostics module_context::consoleWriteOutput(diagnostics); // return status r::sexp::Protect rProtect; return r::sexp::create(isAvailable, &rProtect); } // incremental file change handler boost::scoped_ptr<IncrementalFileChangeHandler> pFileChangeHandler; } // anonymous namespace bool isAvailable() { return clang().isLoaded(); } Error initialize() { // if we don't have a recent version of Rcpp (that can do dryRun with // sourceCpp) then forget it if (!module_context::isPackageVersionInstalled("Rcpp", "0.11.2.7")) return Success(); // attempt to load clang interface loadLibClang(); // register diagnostics function R_CallMethodDef methodDef ; methodDef.name = "rs_isLibClangAvailable" ; methodDef.fun = (DL_FUNC)rs_isLibClangAvailable; methodDef.numArgs = 0; r::routines::addCallMethod(methodDef); // subscribe to onSourceDocUpdated (used for maintaining both the // main source index and the unsaved files list) source_database::events().onDocUpdated.connect(onSourceDocUpdated); // connect source doc removed events to unsaved files list source_database::events().onDocRemoved.connect( boost::bind(&UnsavedFiles::remove, &unsavedFiles(), _1)); source_database::events().onRemoveAll.connect( boost::bind(&UnsavedFiles::removeAll, &unsavedFiles())); // if this is a pakcage with a src directory then initialize various // things related to maintaining the package src index using namespace projects; if ((projectContext().config().buildType == r_util::kBuildTypePackage) && projectContext().buildTargetPath().childPath("src").exists()) { FilePath buildTargetPath = projectContext().buildTargetPath(); FilePath descPath = buildTargetPath.childPath("DESCRIPTION"); FilePath srcPath = projectContext().buildTargetPath().childPath("src"); // update the compilation database for this package compilationDatabase().updateForCurrentPackage(); // filter file change notifications to files of interest IncrementalFileChangeHandler::Filter filter = boost::bind(packageCppFileFilter, srcPath.absolutePath(), descPath.absolutePath(), _1); // create incremental file change handler (this is used for updating // the main source index) pFileChangeHandler.reset(new IncrementalFileChangeHandler( filter, fileChangeHandler, boost::posix_time::milliseconds(200), boost::posix_time::milliseconds(20), false)); /* allow indexing during idle time */ // subscribe to the file monitor pFileChangeHandler->subscribeToFileMonitor("C++ Code Completion"); } ExecBlock initBlock ; using boost::bind; using namespace module_context; initBlock.addFunctions() (bind(registerRpcMethod, "print_cpp_completions", printCppCompletions)); return initBlock.execute(); // return success return Success(); } } // namespace clang } // namespace modules } // namesapce session
remove redundant FilePath creation
remove redundant FilePath creation
C++
agpl-3.0
tbarrongh/rstudio,jzhu8803/rstudio,thklaus/rstudio,githubfun/rstudio,pssguy/rstudio,vbelakov/rstudio,jar1karp/rstudio,edrogers/rstudio,JanMarvin/rstudio,john-r-mcpherson/rstudio,sfloresm/rstudio,tbarrongh/rstudio,edrogers/rstudio,piersharding/rstudio,more1/rstudio,more1/rstudio,jrnold/rstudio,more1/rstudio,jzhu8803/rstudio,suribes/rstudio,piersharding/rstudio,brsimioni/rstudio,john-r-mcpherson/rstudio,thklaus/rstudio,maligulzar/Rstudio-instrumented,brsimioni/rstudio,tbarrongh/rstudio,jrnold/rstudio,maligulzar/Rstudio-instrumented,john-r-mcpherson/rstudio,nvoron23/rstudio,JanMarvin/rstudio,githubfun/rstudio,pssguy/rstudio,more1/rstudio,tbarrongh/rstudio,edrogers/rstudio,vbelakov/rstudio,piersharding/rstudio,jrnold/rstudio,suribes/rstudio,pssguy/rstudio,thklaus/rstudio,more1/rstudio,jzhu8803/rstudio,piersharding/rstudio,jzhu8803/rstudio,sfloresm/rstudio,maligulzar/Rstudio-instrumented,vbelakov/rstudio,pssguy/rstudio,JanMarvin/rstudio,githubfun/rstudio,suribes/rstudio,john-r-mcpherson/rstudio,jar1karp/rstudio,edrogers/rstudio,JanMarvin/rstudio,edrogers/rstudio,suribes/rstudio,suribes/rstudio,pssguy/rstudio,tbarrongh/rstudio,jrnold/rstudio,jzhu8803/rstudio,jar1karp/rstudio,john-r-mcpherson/rstudio,vbelakov/rstudio,maligulzar/Rstudio-instrumented,jar1karp/rstudio,sfloresm/rstudio,jrnold/rstudio,pssguy/rstudio,maligulzar/Rstudio-instrumented,nvoron23/rstudio,jzhu8803/rstudio,piersharding/rstudio,piersharding/rstudio,sfloresm/rstudio,piersharding/rstudio,jar1karp/rstudio,maligulzar/Rstudio-instrumented,sfloresm/rstudio,JanMarvin/rstudio,nvoron23/rstudio,piersharding/rstudio,edrogers/rstudio,vbelakov/rstudio,more1/rstudio,suribes/rstudio,jrnold/rstudio,jzhu8803/rstudio,githubfun/rstudio,john-r-mcpherson/rstudio,brsimioni/rstudio,jzhu8803/rstudio,suribes/rstudio,john-r-mcpherson/rstudio,edrogers/rstudio,tbarrongh/rstudio,JanMarvin/rstudio,brsimioni/rstudio,edrogers/rstudio,jar1karp/rstudio,JanMarvin/rstudio,sfloresm/rstudio,thklaus/rstudio,sfloresm/rstudio,nvoron23/rstudio,vbelakov/rstudio,JanMarvin/rstudio,maligulzar/Rstudio-instrumented,githubfun/rstudio,john-r-mcpherson/rstudio,maligulzar/Rstudio-instrumented,pssguy/rstudio,sfloresm/rstudio,brsimioni/rstudio,nvoron23/rstudio,jar1karp/rstudio,maligulzar/Rstudio-instrumented,tbarrongh/rstudio,thklaus/rstudio,brsimioni/rstudio,suribes/rstudio,thklaus/rstudio,thklaus/rstudio,githubfun/rstudio,vbelakov/rstudio,jar1karp/rstudio,githubfun/rstudio,JanMarvin/rstudio,brsimioni/rstudio,nvoron23/rstudio,jrnold/rstudio,tbarrongh/rstudio,jrnold/rstudio,thklaus/rstudio,more1/rstudio,brsimioni/rstudio,jar1karp/rstudio,pssguy/rstudio,jrnold/rstudio,more1/rstudio,piersharding/rstudio,githubfun/rstudio,nvoron23/rstudio,vbelakov/rstudio
5b9a2f5edf82518014682e8025c257df516fd3f9
kaddressbook/nameeditdialog.cpp
kaddressbook/nameeditdialog.cpp
/* This file is part of KAddressBook. Copyright (c) 2002 Mike Pilone <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 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 <qlayout.h> #include <qlabel.h> #include <qlistbox.h> #include <qlistview.h> #include <qtooltip.h> #include <qpushbutton.h> #include <qcheckbox.h> #include <qstring.h> #include <qwhatsthis.h> #include <kaccelmanager.h> #include <kapplication.h> #include <kbuttonbox.h> #include <kconfig.h> #include <klineedit.h> #include <klistview.h> #include <kcombobox.h> #include <klocale.h> #include <kdebug.h> #include <kiconloader.h> #include <kmessagebox.h> #include "nameeditdialog.h" NameEditDialog::NameEditDialog( const KABC::Addressee &addr, int type, bool readOnly, QWidget *parent, const char *name ) : KDialogBase( Plain, i18n( "Edit Contact Name" ), Help | Ok | Cancel, Ok, parent, name, true ), mAddressee( addr ) { QWidget *page = plainPage(); QGridLayout *layout = new QGridLayout( page ); layout->setSpacing( spacingHint() ); layout->addColSpacing( 2, 100 ); QLabel *label; label = new QLabel( i18n( "Honorific prefixes:" ), page ); layout->addWidget( label, 0, 0 ); mPrefixCombo = new KComboBox( page ); mPrefixCombo->setDuplicatesEnabled( false ); mPrefixCombo->setEditable( true ); mPrefixCombo->setEnabled( !readOnly ); label->setBuddy( mPrefixCombo ); layout->addMultiCellWidget( mPrefixCombo, 0, 0, 1, 2 ); QWhatsThis::add( mPrefixCombo, i18n( "The predefined honorific prefixes can be extended in the settings dialog." ) ); label = new QLabel( i18n( "Given name:" ), page ); layout->addWidget( label, 1, 0 ); mGivenNameEdit = new KLineEdit( page ); mGivenNameEdit->setReadOnly( readOnly ); label->setBuddy( mGivenNameEdit ); layout->addMultiCellWidget( mGivenNameEdit, 1, 1, 1, 2 ); label = new QLabel( i18n( "Additional names:" ), page ); layout->addWidget( label, 2, 0 ); mAdditionalNameEdit = new KLineEdit( page ); mAdditionalNameEdit->setReadOnly( readOnly ); label->setBuddy( mAdditionalNameEdit ); layout->addMultiCellWidget( mAdditionalNameEdit, 2, 2, 1, 2 ); label = new QLabel( i18n( "Family names:" ), page ); layout->addWidget( label, 3, 0 ); mFamilyNameEdit = new KLineEdit( page ); mFamilyNameEdit->setReadOnly( readOnly ); label->setBuddy( mFamilyNameEdit ); layout->addMultiCellWidget( mFamilyNameEdit, 3, 3, 1, 2 ); label = new QLabel( i18n( "Honorific suffixes:" ), page ); layout->addWidget( label, 4, 0 ); mSuffixCombo = new KComboBox( page ); mSuffixCombo->setDuplicatesEnabled( false ); mSuffixCombo->setEditable( true ); mSuffixCombo->setEnabled( !readOnly ); label->setBuddy( mSuffixCombo ); layout->addMultiCellWidget( mSuffixCombo, 4, 4, 1, 2 ); QWhatsThis::add( mSuffixCombo, i18n( "The predefined honorific suffixes can be extended in the settings dialog." ) ); label = new QLabel( i18n( "Formatted name:" ), page ); layout->addWidget( label, 5, 0 ); mFormattedNameCombo = new KComboBox( page ); mFormattedNameCombo->setEnabled( !readOnly ); layout->addWidget( mFormattedNameCombo, 5, 1 ); connect( mFormattedNameCombo, SIGNAL( activated( int ) ), SLOT( typeChanged( int ) ) ); mFormattedNameEdit = new KLineEdit( page ); mFormattedNameEdit->setEnabled( type == CustomName && !readOnly ); layout->addWidget( mFormattedNameEdit, 5, 2 ); mParseBox = new QCheckBox( i18n( "Parse name automatically" ), page ); mParseBox->setEnabled( !readOnly ); connect( mParseBox, SIGNAL( toggled(bool) ), SLOT( parseBoxChanged(bool) ) ); connect( mParseBox, SIGNAL( toggled(bool) ), SLOT( modified() ) ); layout->addMultiCellWidget( mParseBox, 6, 6, 0, 1 ); // Fill in the values mFamilyNameEdit->setText( addr.familyName() ); mGivenNameEdit->setText( addr.givenName() ); mAdditionalNameEdit->setText( addr.additionalName() ); mFormattedNameEdit->setText( addr.formattedName() ); // Prefix and suffix combos KConfig config( "kabcrc" ); config.setGroup( "General" ); QStringList sTitle; sTitle += i18n( "Dr." ); sTitle += i18n( "Miss" ); sTitle += i18n( "Mr." ); sTitle += i18n( "Mrs." ); sTitle += i18n( "Ms." ); sTitle += i18n( "Prof." ); sTitle += config.readListEntry( "Prefixes" ); sTitle.sort(); QStringList sSuffix; sSuffix += i18n( "I" ); sSuffix += i18n( "II" ); sSuffix += i18n( "III" ); sSuffix += i18n( "Jr." ); sSuffix += i18n( "Sr." ); sSuffix += config.readListEntry( "Suffixes" ); sSuffix.sort(); mPrefixCombo->insertStringList( sTitle ); mSuffixCombo->insertStringList( sSuffix ); mPrefixCombo->setCurrentText( addr.prefix() ); mSuffixCombo->setCurrentText( addr.suffix() ); mAddresseeConfig.setAddressee( addr ); mParseBox->setChecked( mAddresseeConfig.automaticNameParsing() ); KAcceleratorManager::manage( this ); connect( mPrefixCombo, SIGNAL( textChanged( const QString& ) ), this, SLOT( modified() ) ); connect( mGivenNameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( modified() ) ); connect( mAdditionalNameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( modified() ) ); connect( mFamilyNameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( modified() ) ); connect( mSuffixCombo, SIGNAL( textChanged( const QString& ) ), this, SLOT( modified() ) ); connect( mFormattedNameCombo, SIGNAL( activated( int ) ), this, SLOT( modified() ) ); connect( mFormattedNameCombo, SIGNAL( activated( int ) ), this, SLOT( formattedNameTypeChanged() ) ); connect( mFormattedNameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( modified() ) ); connect( mFormattedNameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( formattedNameChanged( const QString& ) ) ); initTypeCombo(); mFormattedNameCombo->setCurrentItem( type ); mPrefixCombo->lineEdit()->setFocus(); mChanged = false; } NameEditDialog::~NameEditDialog() { } QString NameEditDialog::familyName() const { return mFamilyNameEdit->text(); } QString NameEditDialog::givenName() const { return mGivenNameEdit->text(); } QString NameEditDialog::prefix() const { return mPrefixCombo->currentText(); } QString NameEditDialog::suffix() const { return mSuffixCombo->currentText(); } QString NameEditDialog::additionalName() const { return mAdditionalNameEdit->text(); } QString NameEditDialog::customFormattedName() const { return mFormattedNameEdit->text(); } int NameEditDialog::formattedNameType() const { return mFormattedNameCombo->currentItem(); } bool NameEditDialog::changed() const { return mChanged; } void NameEditDialog::formattedNameTypeChanged() { QString name; if ( formattedNameType() == CustomName ) name = mCustomFormattedName; else { KABC::Addressee addr; addr.setPrefix( prefix() ); addr.setFamilyName( familyName() ); addr.setAdditionalName( additionalName() ); addr.setGivenName( givenName() ); addr.setSuffix( suffix() ); addr.setOrganization( mAddressee.organization() ); name = formattedName( addr, formattedNameType() ); } mFormattedNameEdit->setText( name ); } QString NameEditDialog::formattedName( const KABC::Addressee &addr, int type ) { QString name; switch ( type ) { case SimpleName: name = addr.givenName() + " " + addr.familyName(); break; case FullName: name = addr.assembledName(); break; case ReverseNameWithComma: name = addr.familyName() + ", " + addr.givenName(); break; case ReverseName: name = addr.familyName() + " " + addr.givenName(); break; case Organization: name = addr.organization(); break; default: name = ""; break; } return name.simplifyWhiteSpace(); } void NameEditDialog::parseBoxChanged( bool value ) { mAddresseeConfig.setAutomaticNameParsing( value ); } void NameEditDialog::typeChanged( int pos ) { mFormattedNameEdit->setEnabled( pos == 0 ); } void NameEditDialog::formattedNameChanged( const QString &name ) { if ( formattedNameType() == CustomName ) mCustomFormattedName = name; } void NameEditDialog::modified() { mChanged = true; } void NameEditDialog::initTypeCombo() { int pos = mFormattedNameCombo->currentItem(); mFormattedNameCombo->clear(); mFormattedNameCombo->insertItem( i18n( "Custom" ) ); mFormattedNameCombo->insertItem( i18n( "Simple Name" ) ); mFormattedNameCombo->insertItem( i18n( "Full Name" ) ); mFormattedNameCombo->insertItem( i18n( "Reverse Name with Comma" ) ); mFormattedNameCombo->insertItem( i18n( "Reverse Name" ) ); mFormattedNameCombo->insertItem( i18n( "Organization" ) ); mFormattedNameCombo->setCurrentItem( pos ); } void NameEditDialog::slotHelp() { kapp->invokeHelp( "managing-contacts-automatic-nameparsing" ); } #include "nameeditdialog.moc"
/* This file is part of KAddressBook. Copyright (c) 2002 Mike Pilone <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 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 <qlayout.h> #include <qlabel.h> #include <qlistbox.h> #include <qlistview.h> #include <qtooltip.h> #include <qpushbutton.h> #include <qcheckbox.h> #include <qstring.h> #include <qwhatsthis.h> #include <kaccelmanager.h> #include <kapplication.h> #include <kbuttonbox.h> #include <kconfig.h> #include <klineedit.h> #include <klistview.h> #include <kcombobox.h> #include <klocale.h> #include <kdebug.h> #include <kiconloader.h> #include <kmessagebox.h> #include "nameeditdialog.h" NameEditDialog::NameEditDialog( const KABC::Addressee &addr, int type, bool readOnly, QWidget *parent, const char *name ) : KDialogBase( Plain, i18n( "Edit Contact Name" ), Help | Ok | Cancel, Ok, parent, name, true ), mAddressee( addr ) { QWidget *page = plainPage(); QGridLayout *layout = new QGridLayout( page ); layout->setSpacing( spacingHint() ); layout->addColSpacing( 2, 100 ); QLabel *label; label = new QLabel( i18n( "Honorific prefixes:" ), page ); layout->addWidget( label, 0, 0 ); mPrefixCombo = new KComboBox( page ); mPrefixCombo->setDuplicatesEnabled( false ); mPrefixCombo->setEditable( true ); mPrefixCombo->setEnabled( !readOnly ); label->setBuddy( mPrefixCombo ); layout->addMultiCellWidget( mPrefixCombo, 0, 0, 1, 2 ); QWhatsThis::add( mPrefixCombo, i18n( "The predefined honorific prefixes can be extended in the settings dialog." ) ); label = new QLabel( i18n( "Given name:" ), page ); layout->addWidget( label, 1, 0 ); mGivenNameEdit = new KLineEdit( page ); mGivenNameEdit->setReadOnly( readOnly ); label->setBuddy( mGivenNameEdit ); layout->addMultiCellWidget( mGivenNameEdit, 1, 1, 1, 2 ); label = new QLabel( i18n( "Additional names:" ), page ); layout->addWidget( label, 2, 0 ); mAdditionalNameEdit = new KLineEdit( page ); mAdditionalNameEdit->setReadOnly( readOnly ); label->setBuddy( mAdditionalNameEdit ); layout->addMultiCellWidget( mAdditionalNameEdit, 2, 2, 1, 2 ); label = new QLabel( i18n( "Family names:" ), page ); layout->addWidget( label, 3, 0 ); mFamilyNameEdit = new KLineEdit( page ); mFamilyNameEdit->setReadOnly( readOnly ); label->setBuddy( mFamilyNameEdit ); layout->addMultiCellWidget( mFamilyNameEdit, 3, 3, 1, 2 ); label = new QLabel( i18n( "Honorific suffixes:" ), page ); layout->addWidget( label, 4, 0 ); mSuffixCombo = new KComboBox( page ); mSuffixCombo->setDuplicatesEnabled( false ); mSuffixCombo->setEditable( true ); mSuffixCombo->setEnabled( !readOnly ); label->setBuddy( mSuffixCombo ); layout->addMultiCellWidget( mSuffixCombo, 4, 4, 1, 2 ); QWhatsThis::add( mSuffixCombo, i18n( "The predefined honorific suffixes can be extended in the settings dialog." ) ); label = new QLabel( i18n( "Formatted name:" ), page ); layout->addWidget( label, 5, 0 ); mFormattedNameCombo = new KComboBox( page ); mFormattedNameCombo->setEnabled( !readOnly ); layout->addWidget( mFormattedNameCombo, 5, 1 ); connect( mFormattedNameCombo, SIGNAL( activated( int ) ), SLOT( typeChanged( int ) ) ); mFormattedNameEdit = new KLineEdit( page ); mFormattedNameEdit->setEnabled( type == CustomName && !readOnly ); layout->addWidget( mFormattedNameEdit, 5, 2 ); mParseBox = new QCheckBox( i18n( "Parse name automatically" ), page ); mParseBox->setEnabled( !readOnly ); connect( mParseBox, SIGNAL( toggled(bool) ), SLOT( parseBoxChanged(bool) ) ); connect( mParseBox, SIGNAL( toggled(bool) ), SLOT( modified() ) ); layout->addMultiCellWidget( mParseBox, 6, 6, 0, 1 ); // Fill in the values mFamilyNameEdit->setText( addr.familyName() ); mGivenNameEdit->setText( addr.givenName() ); mAdditionalNameEdit->setText( addr.additionalName() ); mFormattedNameEdit->setText( addr.formattedName() ); // Prefix and suffix combos KConfig config( "kabcrc" ); config.setGroup( "General" ); QStringList sTitle; sTitle += ""; sTitle += i18n( "Dr." ); sTitle += i18n( "Miss" ); sTitle += i18n( "Mr." ); sTitle += i18n( "Mrs." ); sTitle += i18n( "Ms." ); sTitle += i18n( "Prof." ); sTitle += config.readListEntry( "Prefixes" ); sTitle.sort(); QStringList sSuffix; sSuffix += ""; sSuffix += i18n( "I" ); sSuffix += i18n( "II" ); sSuffix += i18n( "III" ); sSuffix += i18n( "Jr." ); sSuffix += i18n( "Sr." ); sSuffix += config.readListEntry( "Suffixes" ); sSuffix.sort(); mPrefixCombo->insertStringList( sTitle ); mSuffixCombo->insertStringList( sSuffix ); mPrefixCombo->setCurrentText( addr.prefix() ); mSuffixCombo->setCurrentText( addr.suffix() ); mAddresseeConfig.setAddressee( addr ); mParseBox->setChecked( mAddresseeConfig.automaticNameParsing() ); KAcceleratorManager::manage( this ); connect( mPrefixCombo, SIGNAL( textChanged( const QString& ) ), this, SLOT( modified() ) ); connect( mGivenNameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( modified() ) ); connect( mAdditionalNameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( modified() ) ); connect( mFamilyNameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( modified() ) ); connect( mSuffixCombo, SIGNAL( textChanged( const QString& ) ), this, SLOT( modified() ) ); connect( mFormattedNameCombo, SIGNAL( activated( int ) ), this, SLOT( modified() ) ); connect( mFormattedNameCombo, SIGNAL( activated( int ) ), this, SLOT( formattedNameTypeChanged() ) ); connect( mFormattedNameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( modified() ) ); connect( mFormattedNameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( formattedNameChanged( const QString& ) ) ); initTypeCombo(); mFormattedNameCombo->setCurrentItem( type ); mPrefixCombo->lineEdit()->setFocus(); mChanged = false; } NameEditDialog::~NameEditDialog() { } QString NameEditDialog::familyName() const { return mFamilyNameEdit->text(); } QString NameEditDialog::givenName() const { return mGivenNameEdit->text(); } QString NameEditDialog::prefix() const { return mPrefixCombo->currentText(); } QString NameEditDialog::suffix() const { return mSuffixCombo->currentText(); } QString NameEditDialog::additionalName() const { return mAdditionalNameEdit->text(); } QString NameEditDialog::customFormattedName() const { return mFormattedNameEdit->text(); } int NameEditDialog::formattedNameType() const { return mFormattedNameCombo->currentItem(); } bool NameEditDialog::changed() const { return mChanged; } void NameEditDialog::formattedNameTypeChanged() { QString name; if ( formattedNameType() == CustomName ) name = mCustomFormattedName; else { KABC::Addressee addr; addr.setPrefix( prefix() ); addr.setFamilyName( familyName() ); addr.setAdditionalName( additionalName() ); addr.setGivenName( givenName() ); addr.setSuffix( suffix() ); addr.setOrganization( mAddressee.organization() ); name = formattedName( addr, formattedNameType() ); } mFormattedNameEdit->setText( name ); } QString NameEditDialog::formattedName( const KABC::Addressee &addr, int type ) { QString name; switch ( type ) { case SimpleName: name = addr.givenName() + " " + addr.familyName(); break; case FullName: name = addr.assembledName(); break; case ReverseNameWithComma: name = addr.familyName() + ", " + addr.givenName(); break; case ReverseName: name = addr.familyName() + " " + addr.givenName(); break; case Organization: name = addr.organization(); break; default: name = ""; break; } return name.simplifyWhiteSpace(); } void NameEditDialog::parseBoxChanged( bool value ) { mAddresseeConfig.setAutomaticNameParsing( value ); } void NameEditDialog::typeChanged( int pos ) { mFormattedNameEdit->setEnabled( pos == 0 ); } void NameEditDialog::formattedNameChanged( const QString &name ) { if ( formattedNameType() == CustomName ) mCustomFormattedName = name; } void NameEditDialog::modified() { mChanged = true; } void NameEditDialog::initTypeCombo() { int pos = mFormattedNameCombo->currentItem(); mFormattedNameCombo->clear(); mFormattedNameCombo->insertItem( i18n( "Custom" ) ); mFormattedNameCombo->insertItem( i18n( "Simple Name" ) ); mFormattedNameCombo->insertItem( i18n( "Full Name" ) ); mFormattedNameCombo->insertItem( i18n( "Reverse Name with Comma" ) ); mFormattedNameCombo->insertItem( i18n( "Reverse Name" ) ); mFormattedNameCombo->insertItem( i18n( "Organization" ) ); mFormattedNameCombo->setCurrentItem( pos ); } void NameEditDialog::slotHelp() { kapp->invokeHelp( "managing-contacts-automatic-nameparsing" ); } #include "nameeditdialog.moc"
Add blank entry to readwrite comboboxes to allow proper mouse wheel using
Add blank entry to readwrite comboboxes to allow proper mouse wheel using BUG:113695 svn path=/branches/KDE/3.5/kdepim/; revision=466353
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
1e0329465a4aaa3416ec434eb554207aa5859535
src/sc2laddercore/LegacyLadderConfig.cpp
src/sc2laddercore/LegacyLadderConfig.cpp
#include "LegacyLadderConfig.h" #include <string> #include <map> #include <iostream> #include <sstream> #include <fstream> LegacyLadderConfig::LegacyLadderConfig(const std::string &InConfigFile) :ConfigFileLocation(InConfigFile) { } bool LegacyLadderConfig::ParseConfig() { std::ifstream ifs(ConfigFileLocation, std::ifstream::binary); if (!ifs) { return false; } std::string line; while (std::getline(ifs, line)) { std::istringstream is_line(line); std::string key; if (std::getline(is_line, key, '=')) { std::string value; if (std::getline(is_line, value)) { TrimString(key); TrimString(value); options.insert(std::make_pair(key, value)); } } } return true; } bool LegacyLadderConfig::WriteConfig() { std::ofstream outfile(ConfigFileLocation, std::ofstream::binary); for (const auto& setting : options) { outfile << setting.first << "=" << setting.second << std::endl; } outfile.close(); return true; } std::string LegacyLadderConfig::GetValue(std::string RequestedValue) { auto search = options.find(RequestedValue); if (search != options.end()) { return search->second; } return std::string(); } void LegacyLadderConfig::TrimString(std::string &Str) { size_t p = Str.find_first_not_of(" \t"); Str.erase(0, p); p = Str.find_last_not_of(" \t\r\n"); if (std::string::npos != p) { Str.erase(p + 1); } } void LegacyLadderConfig::AddValue(const std::string &Index, const std::string &Value) { options.insert(std::make_pair(Index, Value)); }
#include "LegacyLadderConfig.h" #include <iostream> #include <sstream> #include <fstream> LegacyLadderConfig::LegacyLadderConfig(const std::string &InConfigFile) :ConfigFileLocation(InConfigFile) { } bool LegacyLadderConfig::ParseConfig() { std::ifstream ifs(ConfigFileLocation, std::ifstream::binary); if (!ifs) { return false; } std::string line; while (std::getline(ifs, line)) { std::istringstream is_line(line); std::string key; if (std::getline(is_line, key, '=')) { std::string value; if (std::getline(is_line, value)) { TrimString(key); TrimString(value); options.insert(std::make_pair(key, value)); } } } return true; } bool LegacyLadderConfig::WriteConfig() { std::ofstream outfile(ConfigFileLocation, std::ofstream::binary); for (const auto& setting : options) { outfile << setting.first << "=" << setting.second << std::endl; } outfile.close(); return true; } std::string LegacyLadderConfig::GetValue(std::string RequestedValue) { auto search = options.find(RequestedValue); if (search != options.end()) { return search->second; } return std::string(); } void LegacyLadderConfig::TrimString(std::string &Str) { size_t p = Str.find_first_not_of(" \t"); Str.erase(0, p); p = Str.find_last_not_of(" \t\r\n"); if (std::string::npos != p) { Str.erase(p + 1); } } void LegacyLadderConfig::AddValue(const std::string &Index, const std::string &Value) { options.insert(std::make_pair(Index, Value)); }
Remove now unrequired header includes for legacy config
Remove now unrequired header includes for legacy config
C++
mit
Cryptyc/Sc2LadderServer,Cryptyc/Sc2LadderServer,Cryptyc/Sc2LadderServer
4726b4af8b13e201a3d3e98c151bbf52f4fc4370
pyQuantuccia/src/pyQuantuccia.cpp
pyQuantuccia/src/pyQuantuccia.cpp
#include <Python.h> #include "Quantuccia/ql/time/calendars/unitedstates.hpp"
#include <Python.h> #include "Quantuccia/ql/time/calendars/unitedstates.hpp" PyObject* PyInit_pyQuantuccia(void){ return NULL; }
Add a stub function to init the module.
Add a stub function to init the module.
C++
bsd-3-clause
jwg4/pyQuantuccia,jwg4/pyQuantuccia
8a2aeabf3238b4ba648a8440cb10d806eaafcce2
korganizer/filtereditdialog.cpp
korganizer/filtereditdialog.cpp
/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <[email protected]> Copyright (C) 2004 Reinhold Kainhofer <[email protected]> Copyright (C) 2005 Thomas Zander <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 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 <qpushbutton.h> #include <qcheckbox.h> #include <qbuttongroup.h> #include <qlineedit.h> #include <qradiobutton.h> #include <qlistbox.h> #include <qwhatsthis.h> #include <kdebug.h> #include <klocale.h> #include <kmessagebox.h> #include <knuminput.h> #include <libkcal/calfilter.h> #include <libkdepim/categoryselectdialog.h> #include "koprefs.h" #include "filteredit_base.h" #include "filtereditdialog.h" #include "filtereditdialog.moc" FilterEditDialog::FilterEditDialog( QPtrList<CalFilter> *filters, QWidget *parent, const char *name) : KDialogBase( parent, name, false, i18n("Edit Calendar Filters"), Ok | Apply | Cancel ) { setMainWidget( mFilterEdit = new FilterEdit(filters, this)); connect(mFilterEdit, SIGNAL(dataConsistent(bool)), SLOT(setDialogConsistent(bool))); updateFilterList(); connect( mFilterEdit, SIGNAL( editCategories() ), SIGNAL( editCategories() ) ); connect( mFilterEdit, SIGNAL( filterChanged() ), SIGNAL( filterChanged() ) ); } FilterEditDialog::~FilterEditDialog() { delete mFilterEdit; mFilterEdit = 0L; } void FilterEditDialog::updateFilterList() { mFilterEdit->updateFilterList(); } void FilterEditDialog::updateCategoryConfig() { mFilterEdit->updateCategoryConfig(); } void FilterEditDialog::slotApply() { mFilterEdit->saveChanges(); } void FilterEditDialog::slotOk() { slotApply(); accept(); } void FilterEditDialog::setDialogConsistent(bool consistent) { enableButtonOK( consistent ); enableButtonApply( consistent ); } FilterEdit::FilterEdit(QPtrList<CalFilter> *filters, QWidget *parent) : FilterEdit_base( parent), current(0), mCategorySelectDialog( 0 ) { mFilters = filters; QWhatsThis::add( mNewButton, i18n( "Press this button to define a new filter." ) ); QWhatsThis::add( mDeleteButton, i18n( "Press this button to remove the currently active filter." ) ); connect(mRulesList, SIGNAL(selectionChanged()), this, SLOT(filterSelected())); connect( mNewButton, SIGNAL( clicked() ), SLOT( bNewPressed() ) ); connect( mDeleteButton, SIGNAL( clicked() ), SLOT( bDeletePressed() ) ); connect( mNameLineEdit, SIGNAL( textChanged(const QString &) ), SLOT( updateSelectedName(const QString &) ) ); connect( mCatEditButton, SIGNAL( clicked() ), SLOT( editCategorySelection() ) ); } FilterEdit::~FilterEdit() { } void FilterEdit::updateFilterList() { mRulesList->clear(); CalFilter *filter = mFilters->first(); if ( !filter ) emit(dataConsistent(false)); else { while( filter ) { mRulesList->insertItem( filter->name() ); filter = mFilters->next(); } CalFilter *f = mFilters->at( mRulesList->currentItem() ); if ( f ) filterSelected( f ); emit(dataConsistent(true)); } if(current == 0L && mFilters->count() > 0) filterSelected(mFilters->at(0)); mDeleteButton->setEnabled( mFilters->count() > 1 ); } void FilterEdit::saveChanges() { if(current != 0L) filterSelected(current); } void FilterEdit::filterSelected() { filterSelected(mFilters->at(mRulesList->currentItem())); } void FilterEdit::filterSelected(CalFilter *filter) { if(filter == current) return; kdDebug(5850) << "Selected filter " << filter->name() << endl; if(current != 0L) { // save the old values first. current->setName(mNameLineEdit->text()); int criteria = 0; if ( mCompletedCheck->isChecked() ) criteria |= CalFilter::HideCompleted; if ( mRecurringCheck->isChecked() ) criteria |= CalFilter::HideRecurring; if ( mCatShowCheck->isChecked() ) criteria |= CalFilter::ShowCategories; if ( mHideInactiveTodosCheck->isChecked() ) criteria |= CalFilter::HideInactiveTodos; current->setCriteria( criteria ); current->setCompletedTimeSpan( mCompletedTimeSpan->value() ); QStringList categoryList; for( uint i = 0; i < mCatList->count(); ++i ) categoryList.append( mCatList->text( i ) ); current->setCategoryList( categoryList ); emit filterChanged(); } current = filter; mNameLineEdit->blockSignals(true); mNameLineEdit->setText(current->name()); mNameLineEdit->blockSignals(false); mDetailsFrame->setEnabled(current != 0L); mCompletedCheck->setChecked( current->criteria() & CalFilter::HideCompleted ); mCompletedTimeSpan->setValue( current->completedTimeSpan() ); mRecurringCheck->setChecked( current->criteria() & CalFilter::HideRecurring ); mHideInactiveTodosCheck->setChecked( current->criteria() & CalFilter::HideInactiveTodos ); mCategoriesButtonGroup->setButton( (current->criteria() & CalFilter::ShowCategories)?0:1 ); mCatList->clear(); mCatList->insertStringList( current->categoryList() ); } void FilterEdit::bNewPressed() { CalFilter *newFilter = new CalFilter( i18n("New Filter %1").arg(mFilters->count()) ); mFilters->append( newFilter ); updateFilterList(); mRulesList->setSelected(mRulesList->count()-1, true); emit filterChanged(); } void FilterEdit::bDeletePressed() { if ( mRulesList->currentItem() < 0 ) return; // nothing selected if ( mFilters->count() <= 1 ) return; // We need at least a default filter object. int result = KMessageBox::warningContinueCancel( this, i18n("This item will be permanently deleted."), i18n("Delete Confirmation"), KGuiItem(i18n("Delete"),"editdelete") ); if ( result != KMessageBox::Continue ) return; unsigned int selected = mRulesList->currentItem(); mFilters->remove( selected ); current = 0L; updateFilterList(); mRulesList->setSelected(QMIN(mRulesList->count()-1, selected), true); emit filterChanged(); } void FilterEdit::updateSelectedName(const QString &newText) { mRulesList->changeItem(newText, mRulesList->currentItem()); bool allOk = true; CalFilter *filter = mFilters->first(); while( allOk && filter ) { if(filter->name().isEmpty()) allOk = false; filter = mFilters->next(); } emit dataConsistent(allOk); } void FilterEdit::editCategorySelection() { if( !current ) return; if ( !mCategorySelectDialog ) { mCategorySelectDialog = new KPIM::CategorySelectDialog( KOPrefs::instance(), this, "filterCatSelect" ); connect( mCategorySelectDialog, SIGNAL( categoriesSelected( const QStringList & ) ), SLOT( updateCategorySelection( const QStringList & ) ) ); connect( mCategorySelectDialog, SIGNAL( editCategories() ), SIGNAL( editCategories() ) ); } mCategorySelectDialog->setSelected( current->categoryList() ); mCategorySelectDialog->show(); } void FilterEdit::updateCategorySelection( const QStringList &categories ) { mCatList->clear(); mCatList->insertStringList(categories); current->setCategoryList(categories); } void FilterEdit::updateCategoryConfig() { if ( mCategorySelectDialog ) mCategorySelectDialog->updateCategoryConfig(); }
/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <[email protected]> Copyright (C) 2004 Reinhold Kainhofer <[email protected]> Copyright (C) 2005 Thomas Zander <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 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 <qpushbutton.h> #include <qcheckbox.h> #include <qbuttongroup.h> #include <qlineedit.h> #include <qradiobutton.h> #include <qlistbox.h> #include <qwhatsthis.h> #include <kdebug.h> #include <klocale.h> #include <kmessagebox.h> #include <knuminput.h> #include <libkcal/calfilter.h> #include <libkdepim/categoryselectdialog.h> #include "koprefs.h" #include "filteredit_base.h" #include "filtereditdialog.h" #include "filtereditdialog.moc" FilterEditDialog::FilterEditDialog( QPtrList<CalFilter> *filters, QWidget *parent, const char *name) : KDialogBase( parent, name, false, i18n("Edit Calendar Filters"), Ok | Apply | Cancel ) { setMainWidget( mFilterEdit = new FilterEdit(filters, this)); connect(mFilterEdit, SIGNAL(dataConsistent(bool)), SLOT(setDialogConsistent(bool))); updateFilterList(); connect( mFilterEdit, SIGNAL( editCategories() ), SIGNAL( editCategories() ) ); connect( mFilterEdit, SIGNAL( filterChanged() ), SIGNAL( filterChanged() ) ); } FilterEditDialog::~FilterEditDialog() { delete mFilterEdit; mFilterEdit = 0L; } void FilterEditDialog::updateFilterList() { mFilterEdit->updateFilterList(); } void FilterEditDialog::updateCategoryConfig() { mFilterEdit->updateCategoryConfig(); } void FilterEditDialog::slotApply() { mFilterEdit->saveChanges(); } void FilterEditDialog::slotOk() { slotApply(); accept(); } void FilterEditDialog::setDialogConsistent(bool consistent) { enableButtonOK( consistent ); enableButtonApply( consistent ); } FilterEdit::FilterEdit(QPtrList<CalFilter> *filters, QWidget *parent) : FilterEdit_base( parent), current(0), mCategorySelectDialog( 0 ) { mFilters = filters; QWhatsThis::add( mNewButton, i18n( "Press this button to define a new filter." ) ); QWhatsThis::add( mDeleteButton, i18n( "Press this button to remove the currently active filter." ) ); connect(mRulesList, SIGNAL(selectionChanged()), this, SLOT(filterSelected())); connect( mNewButton, SIGNAL( clicked() ), SLOT( bNewPressed() ) ); connect( mDeleteButton, SIGNAL( clicked() ), SLOT( bDeletePressed() ) ); connect( mNameLineEdit, SIGNAL( textChanged(const QString &) ), SLOT( updateSelectedName(const QString &) ) ); connect( mCatEditButton, SIGNAL( clicked() ), SLOT( editCategorySelection() ) ); } FilterEdit::~FilterEdit() { } void FilterEdit::updateFilterList() { mRulesList->clear(); CalFilter *filter = mFilters->first(); if ( !filter ) emit(dataConsistent(false)); else { while( filter ) { mRulesList->insertItem( filter->name() ); filter = mFilters->next(); } CalFilter *f = mFilters->at( mRulesList->currentItem() ); if ( f ) filterSelected( f ); emit(dataConsistent(true)); } if(current == 0L && mFilters->count() > 0) filterSelected(mFilters->at(0)); mDeleteButton->setEnabled( mFilters->count() > 1 ); } void FilterEdit::saveChanges() { if(current != 0L) filterSelected(current); } void FilterEdit::filterSelected() { filterSelected(mFilters->at(mRulesList->currentItem())); } void FilterEdit::filterSelected(CalFilter *filter) { if(filter == current) return; kdDebug(5850) << "Selected filter " << (filter!=0?filter->name():"") << endl; if(current != 0L) { // save the old values first. current->setName(mNameLineEdit->text()); int criteria = 0; if ( mCompletedCheck->isChecked() ) criteria |= CalFilter::HideCompleted; if ( mRecurringCheck->isChecked() ) criteria |= CalFilter::HideRecurring; if ( mCatShowCheck->isChecked() ) criteria |= CalFilter::ShowCategories; if ( mHideInactiveTodosCheck->isChecked() ) criteria |= CalFilter::HideInactiveTodos; current->setCriteria( criteria ); current->setCompletedTimeSpan( mCompletedTimeSpan->value() ); QStringList categoryList; for( uint i = 0; i < mCatList->count(); ++i ) categoryList.append( mCatList->text( i ) ); current->setCategoryList( categoryList ); emit filterChanged(); } current = filter; mNameLineEdit->blockSignals(true); mNameLineEdit->setText(current->name()); mNameLineEdit->blockSignals(false); mDetailsFrame->setEnabled(current != 0L); mCompletedCheck->setChecked( current->criteria() & CalFilter::HideCompleted ); mCompletedTimeSpan->setValue( current->completedTimeSpan() ); mRecurringCheck->setChecked( current->criteria() & CalFilter::HideRecurring ); mHideInactiveTodosCheck->setChecked( current->criteria() & CalFilter::HideInactiveTodos ); mCategoriesButtonGroup->setButton( (current->criteria() & CalFilter::ShowCategories)?0:1 ); mCatList->clear(); mCatList->insertStringList( current->categoryList() ); } void FilterEdit::bNewPressed() { CalFilter *newFilter = new CalFilter( i18n("New Filter %1").arg(mFilters->count()) ); mFilters->append( newFilter ); updateFilterList(); mRulesList->setSelected(mRulesList->count()-1, true); emit filterChanged(); } void FilterEdit::bDeletePressed() { if ( mRulesList->currentItem() < 0 ) return; // nothing selected if ( mFilters->count() <= 1 ) return; // We need at least a default filter object. int result = KMessageBox::warningContinueCancel( this, i18n("This item will be permanently deleted."), i18n("Delete Confirmation"), KGuiItem(i18n("Delete"),"editdelete") ); if ( result != KMessageBox::Continue ) return; unsigned int selected = mRulesList->currentItem(); mFilters->remove( selected ); current = 0L; updateFilterList(); mRulesList->setSelected(QMIN(mRulesList->count()-1, selected), true); emit filterChanged(); } void FilterEdit::updateSelectedName(const QString &newText) { mRulesList->changeItem(newText, mRulesList->currentItem()); bool allOk = true; CalFilter *filter = mFilters->first(); while( allOk && filter ) { if(filter->name().isEmpty()) allOk = false; filter = mFilters->next(); } emit dataConsistent(allOk); } void FilterEdit::editCategorySelection() { if( !current ) return; if ( !mCategorySelectDialog ) { mCategorySelectDialog = new KPIM::CategorySelectDialog( KOPrefs::instance(), this, "filterCatSelect" ); connect( mCategorySelectDialog, SIGNAL( categoriesSelected( const QStringList & ) ), SLOT( updateCategorySelection( const QStringList & ) ) ); connect( mCategorySelectDialog, SIGNAL( editCategories() ), SIGNAL( editCategories() ) ); } mCategorySelectDialog->setSelected( current->categoryList() ); mCategorySelectDialog->show(); } void FilterEdit::updateCategorySelection( const QStringList &categories ) { mCatList->clear(); mCatList->insertStringList(categories); current->setCategoryList(categories); } void FilterEdit::updateCategoryConfig() { if ( mCategorySelectDialog ) mCategorySelectDialog->updateCategoryConfig(); }
Fix possible crash; don't blindly print filter->name() in a _debug_ statement, filter might be null.
Fix possible crash; don't blindly print filter->name() in a _debug_ statement, filter might be null. svn path=/trunk/KDE/kdepim/; revision=423475
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
caa3e7e27ab3f81cef0869ed72abf26f996f1651
korganizer/korgac/alarmdialog.cpp
korganizer/korgac/alarmdialog.cpp
/* This file is part of the KOrganizer alarm daemon. Copyright (c) 2000,2003 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 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 <qhbox.h> #include <qvbox.h> #include <qlabel.h> #include <qfile.h> #include <qspinbox.h> #include <qlayout.h> #include <qpushbutton.h> #include <qcstring.h> #include <qdatastream.h> #include <kapplication.h> #include <dcopclient.h> #include <klocale.h> #include <kprocess.h> #include <kaudioplayer.h> #include <kdebug.h> #include <kmessagebox.h> #include <knotifyclient.h> #include <kcombobox.h> #include <kwin.h> #include <klockfile.h> #include <libkcal/event.h> #include "koeventviewer.h" #include "alarmdialog.h" #include "alarmdialog.moc" AlarmDialog::AlarmDialog( QWidget *parent, const char *name ) : KDialogBase( Plain, WType_TopLevel | WStyle_Customize | WStyle_StaysOnTop | WStyle_DialogBorder, parent, name, false, i18n("Reminder"), Ok | User1 | User2/* | User3*/, User1/*3*/, false, i18n("Suspend"), i18n("Edit...") ), mSuspendTimer(this) { QWidget *topBox = plainPage(); QBoxLayout *topLayout = new QVBoxLayout( topBox ); topLayout->setSpacing( spacingHint() ); QLabel *label = new QLabel( i18n("The following events triggered reminders:"), topBox ); topLayout->addWidget( label ); mEventViewer = new KOEventViewer( topBox ); topLayout->addWidget( mEventViewer ); QHBox *suspendBox = new QHBox( topBox ); suspendBox->setSpacing( spacingHint() ); topLayout->addWidget( suspendBox ); new QLabel( i18n("Suspend duration:"), suspendBox ); mSuspendSpin = new QSpinBox( 1, 9999, 1, suspendBox ); mSuspendSpin->setValue( 5 ); // default suspend duration mSuspendUnit = new KComboBox( suspendBox ); mSuspendUnit->insertItem( i18n("minute(s)") ); mSuspendUnit->insertItem( i18n("hour(s)") ); mSuspendUnit->insertItem( i18n("day(s)") ); mSuspendUnit->insertItem( i18n("week(s)") ); connect( mSuspendSpin, SIGNAL( valueChanged(int) ), actionButton(User1), SLOT( setFocus() ) ); connect( mSuspendUnit, SIGNAL( activated(int) ), actionButton(User1), SLOT( setFocus() ) ); connect( mSuspendUnit, SIGNAL( activated(int) ), actionButton(User2), SLOT( setFocus() ) ); // showButton( User2/*3*/, false ); setMinimumSize( 300, 200 ); } AlarmDialog::~AlarmDialog() { delete mIncidence; } void AlarmDialog::setIncidence( Incidence *incidence ) { mIncidence = incidence->clone(); mEventViewer->appendIncidence( mIncidence ); } void AlarmDialog::setRemindAt( QDateTime dt ) { mRemindAt = dt; } void AlarmDialog::slotOk() { accept(); emit finishedSignal( this ); } void AlarmDialog::slotUser1() { if ( !isVisible() ) return; int unit=1; switch (mSuspendUnit->currentItem()) { case 3: // weeks unit *= 7; case 2: // days unit *= 24; case 1: // hours unit *= 60; case 0: // minutes unit *= 60; default: break; } setTimer( unit * mSuspendSpin->value() ); accept(); } void AlarmDialog::setTimer( int seconds ) { connect( &mSuspendTimer, SIGNAL( timeout() ), SLOT( show() ) ); mSuspendTimer.start( 1000 * seconds, true ); mRemindAt = QDateTime::currentDateTime(); mRemindAt = mRemindAt.addSecs( seconds ); } void AlarmDialog::slotUser2() { if ( !kapp->dcopClient()->isApplicationRegistered( "korganizer" ) ) { if ( kapp->startServiceByDesktopName( "korganizer", QString::null ) ) KMessageBox::error( 0, i18n("Could not start KOrganizer.") ); } kapp->dcopClient()->send( "korganizer", "KOrganizerIface", "editIncidence(QString)", mIncidence->uid() ); // get desktop # where korganizer (or kontact) runs QByteArray replyData; QCString object, replyType; object = kapp->dcopClient()->isApplicationRegistered( "kontact" ) ? "kontact-mainwindow#1" : "KOrganizer MainWindow"; if (!kapp->dcopClient()->call( "korganizer", object, "getWinID()", 0, replyType, replyData, true, -1 ) ) { } if ( replyType == "int" ) { int desktop, window; QDataStream ds( replyData, IO_ReadOnly ); ds >> window; desktop = KWin::windowInfo( window ).desktop(); if ( KWin::currentDesktop() == desktop ) { KWin::iconifyWindow( winId(), false ); } else KWin::setCurrentDesktop( desktop ); KWin::activateWindow( KWin::transientFor( window ) ); } } void AlarmDialog::show() { KDialogBase::show(); KWin::setState( winId(), NET::KeepAbove ); KWin::setOnAllDesktops( winId(), true ); eventNotification(); } void AlarmDialog::eventNotification() { bool beeped = false; Alarm::List alarms = mIncidence->alarms(); Alarm::List::ConstIterator it; for ( it = alarms.begin(); it != alarms.end(); ++it ) { Alarm *alarm = *it; // FIXME: Check whether this should be done for all multiple alarms if (alarm->type() == Alarm::Procedure) { // FIXME: Add a message box asking whether the procedure should really be executed kdDebug(5890) << "Starting program: '" << alarm->programFile() << "'" << endl; KProcess proc; proc << QFile::encodeName(alarm->programFile()); proc.start(KProcess::DontCare); } else if (alarm->type() == Alarm::Audio) { beeped = true; KAudioPlayer::play(QFile::encodeName(alarm->audioFile())); } } if ( !beeped ) { KNotifyClient::beep(); } } void AlarmDialog::wakeUp() { if ( mRemindAt <= QDateTime::currentDateTime() ) show(); else setTimer( QDateTime::currentDateTime().secsTo( mRemindAt ) ); } void AlarmDialog::slotSave() { KConfig *config = kapp->config(); KLockFile::Ptr lock = config->lockFile(); if ( lock.data()->lock() != KLockFile::LockOK ) return; config->setGroup( "General" ); int numReminders = config->readNumEntry("Reminders", 0); config->writeEntry( "Reminders", ++numReminders ); config->setGroup( QString("Incidence-%1").arg(numReminders) ); config->writeEntry( "UID", mIncidence->uid() ); config->writeEntry( "RemindAt", mRemindAt ); config->sync(); lock.data()->unlock(); }
/* This file is part of the KOrganizer alarm daemon. Copyright (c) 2000,2003 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 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 <qhbox.h> #include <qvbox.h> #include <qlabel.h> #include <qfile.h> #include <qspinbox.h> #include <qlayout.h> #include <qpushbutton.h> #include <qcstring.h> #include <qdatastream.h> #include <kapplication.h> #include <dcopclient.h> #include <klocale.h> #include <kprocess.h> #include <kaudioplayer.h> #include <kdebug.h> #include <kmessagebox.h> #include <knotifyclient.h> #include <kcombobox.h> #include <kwin.h> #include <klockfile.h> #include <libkcal/event.h> #include "koeventviewer.h" #include "alarmdialog.h" #include "alarmdialog.moc" AlarmDialog::AlarmDialog( QWidget *parent, const char *name ) : KDialogBase( Plain, WType_TopLevel | WStyle_Customize | WStyle_StaysOnTop | WStyle_DialogBorder, parent, name, false, i18n("Reminder"), Ok | User1 | User2/* | User3*/, User1/*3*/, false, i18n("Suspend"), i18n("Edit...") ), mSuspendTimer(this) { QWidget *topBox = plainPage(); QBoxLayout *topLayout = new QVBoxLayout( topBox ); topLayout->setSpacing( spacingHint() ); QLabel *label = new QLabel( i18n("The following events triggered reminders:"), topBox ); topLayout->addWidget( label ); mEventViewer = new KOEventViewer( topBox ); topLayout->addWidget( mEventViewer ); QHBox *suspendBox = new QHBox( topBox ); suspendBox->setSpacing( spacingHint() ); topLayout->addWidget( suspendBox ); QLabel *l = new QLabel( i18n("Suspend &duration:"), suspendBox ); mSuspendSpin = new QSpinBox( 1, 9999, 1, suspendBox ); mSuspendSpin->setValue( 5 ); // default suspend duration l->setBuddy( mSuspendSpin ); mSuspendUnit = new KComboBox( suspendBox ); mSuspendUnit->insertItem( i18n("minute(s)") ); mSuspendUnit->insertItem( i18n("hour(s)") ); mSuspendUnit->insertItem( i18n("day(s)") ); mSuspendUnit->insertItem( i18n("week(s)") ); // showButton( User2/*3*/, false ); setMinimumSize( 300, 200 ); } AlarmDialog::~AlarmDialog() { delete mIncidence; } void AlarmDialog::setIncidence( Incidence *incidence ) { mIncidence = incidence->clone(); mEventViewer->appendIncidence( mIncidence ); } void AlarmDialog::setRemindAt( QDateTime dt ) { mRemindAt = dt; } void AlarmDialog::slotOk() { accept(); emit finishedSignal( this ); } void AlarmDialog::slotUser1() { if ( !isVisible() ) return; int unit=1; switch (mSuspendUnit->currentItem()) { case 3: // weeks unit *= 7; case 2: // days unit *= 24; case 1: // hours unit *= 60; case 0: // minutes unit *= 60; default: break; } setTimer( unit * mSuspendSpin->value() ); accept(); } void AlarmDialog::setTimer( int seconds ) { connect( &mSuspendTimer, SIGNAL( timeout() ), SLOT( show() ) ); mSuspendTimer.start( 1000 * seconds, true ); mRemindAt = QDateTime::currentDateTime(); mRemindAt = mRemindAt.addSecs( seconds ); } void AlarmDialog::slotUser2() { if ( !kapp->dcopClient()->isApplicationRegistered( "korganizer" ) ) { if ( kapp->startServiceByDesktopName( "korganizer", QString::null ) ) KMessageBox::error( 0, i18n("Could not start KOrganizer.") ); } kapp->dcopClient()->send( "korganizer", "KOrganizerIface", "editIncidence(QString)", mIncidence->uid() ); // get desktop # where korganizer (or kontact) runs QByteArray replyData; QCString object, replyType; object = kapp->dcopClient()->isApplicationRegistered( "kontact" ) ? "kontact-mainwindow#1" : "KOrganizer MainWindow"; if (!kapp->dcopClient()->call( "korganizer", object, "getWinID()", 0, replyType, replyData, true, -1 ) ) { } if ( replyType == "int" ) { int desktop, window; QDataStream ds( replyData, IO_ReadOnly ); ds >> window; desktop = KWin::windowInfo( window ).desktop(); if ( KWin::currentDesktop() == desktop ) { KWin::iconifyWindow( winId(), false ); } else KWin::setCurrentDesktop( desktop ); KWin::activateWindow( KWin::transientFor( window ) ); } } void AlarmDialog::show() { KDialogBase::show(); KWin::setState( winId(), NET::KeepAbove ); KWin::setOnAllDesktops( winId(), true ); eventNotification(); } void AlarmDialog::eventNotification() { bool beeped = false; Alarm::List alarms = mIncidence->alarms(); Alarm::List::ConstIterator it; for ( it = alarms.begin(); it != alarms.end(); ++it ) { Alarm *alarm = *it; // FIXME: Check whether this should be done for all multiple alarms if (alarm->type() == Alarm::Procedure) { // FIXME: Add a message box asking whether the procedure should really be executed kdDebug(5890) << "Starting program: '" << alarm->programFile() << "'" << endl; KProcess proc; proc << QFile::encodeName(alarm->programFile()); proc.start(KProcess::DontCare); } else if (alarm->type() == Alarm::Audio) { beeped = true; KAudioPlayer::play(QFile::encodeName(alarm->audioFile())); } } if ( !beeped ) { KNotifyClient::beep(); } } void AlarmDialog::wakeUp() { if ( mRemindAt <= QDateTime::currentDateTime() ) show(); else setTimer( QDateTime::currentDateTime().secsTo( mRemindAt ) ); } void AlarmDialog::slotSave() { KConfig *config = kapp->config(); KLockFile::Ptr lock = config->lockFile(); if ( lock.data()->lock() != KLockFile::LockOK ) return; config->setGroup( "General" ); int numReminders = config->readNumEntry("Reminders", 0); config->writeEntry( "Reminders", ++numReminders ); config->setGroup( QString("Incidence-%1").arg(numReminders) ); config->writeEntry( "UID", mIncidence->uid() ); config->writeEntry( "RemindAt", mRemindAt ); config->sync(); lock.data()->unlock(); }
Make the reminder dialog somewhat more usable when working with they keyboard. No strange focus switching with up-down arrows in the spin box for example. And added an accelerator for the interval spin box.
Make the reminder dialog somewhat more usable when working with they keyboard. No strange focus switching with up-down arrows in the spin box for example. And added an accelerator for the interval spin box. BUG:137177 svn path=/branches/KDE/3.5/kdepim/; revision=604038
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
89f429867071cacdaee16bcab3b13048b22077c6
cdc/cdc_extension.hh
cdc/cdc_extension.hh
/* * Copyright 2020 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Affero General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "serializer.hh" #include "db/extensions.hh" #include "cdc/cdc_options.hh" #include "schema.hh" namespace cdc { class cdc_extension : public schema_extension { cdc::options _cdc_options; public: static constexpr auto NAME = "cdc"; cdc_extension() = default; cdc_extension(const options& opts) : _cdc_options(opts) {} explicit cdc_extension(std::map<sstring, sstring> tags) : _cdc_options(std::move(tags)) {} explicit cdc_extension(const bytes& b) : _cdc_options(cdc_extension::deserialize(b)) {} explicit cdc_extension(const sstring& s) { throw std::logic_error("Cannot create cdc info from string"); } bytes serialize() const override { return ser::serialize_to_buffer<bytes>(_cdc_options.to_map()); } static std::map<sstring, sstring> deserialize(const bytes_view& buffer) { return ser::deserialize_from_buffer(buffer, boost::type<std::map<sstring, sstring>>()); } const options& get_options() const { return _cdc_options; } }; }
/* * Copyright 2020 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Affero General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <map> #include <seastar/core/sstring.hh> #include "bytes.hh" #include "serializer.hh" #include "db/extensions.hh" #include "cdc/cdc_options.hh" #include "schema.hh" #include "serializer_impl.hh" namespace cdc { class cdc_extension : public schema_extension { cdc::options _cdc_options; public: static constexpr auto NAME = "cdc"; cdc_extension() = default; cdc_extension(const options& opts) : _cdc_options(opts) {} explicit cdc_extension(std::map<sstring, sstring> tags) : _cdc_options(std::move(tags)) {} explicit cdc_extension(const bytes& b) : _cdc_options(cdc_extension::deserialize(b)) {} explicit cdc_extension(const sstring& s) { throw std::logic_error("Cannot create cdc info from string"); } bytes serialize() const override { return ser::serialize_to_buffer<bytes>(_cdc_options.to_map()); } static std::map<sstring, sstring> deserialize(const bytes_view& buffer) { return ser::deserialize_from_buffer(buffer, boost::type<std::map<sstring, sstring>>()); } const options& get_options() const { return _cdc_options; } }; }
Add missing includes to cdc_extension.hh
cdc: Add missing includes to cdc_extension.hh Without those additional includes, a .cc file that includes cdc_extension.hh won't compile. Signed-off-by: Piotr Jastrzebski <[email protected]>
C++
agpl-3.0
scylladb/scylla,scylladb/scylla,scylladb/scylla,scylladb/scylla
5f7d6f697b022908dd21ea29626a30c43ba4d78f
Programs/dicomfind.cxx
Programs/dicomfind.cxx
/*========================================================================= Program: DICOM for VTK Copyright (c) 2012-2014 David Gobbi All rights reserved. See Copyright.txt or http://dgobbi.github.io/bsd3.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 notice for more information. =========================================================================*/ #include "vtkDICOMDirectory.h" #include "vtkDICOMMetaData.h" #include "vtkDICOMItem.h" #include "vtkDICOMDataElement.h" #include "vtkDICOMParser.h" #include "vtkDICOMMetaData.h" // from dicomcli #include "readquery.h" #include <vtkStringArray.h> #include <vtkSmartPointer.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> // print the version void dicomfind_version(FILE *file, const char *cp) { fprintf(file, "%s %s\n", cp, DICOM_VERSION); fprintf(file, "\n" "Copyright (c) 2012-2014, David Gobbi.\n\n" "This software is distributed under an open-source license. See the\n" "Copyright.txt file that comes with the vtk-dicom source distribution.\n"); } // print the usage void dicomfind_usage(FILE *file, const char *cp) { fprintf(file, "usage:\n" " %s -q <query.txt> -o <data.csv> <directory>\n\n", cp); fprintf(file, "options:\n" " -q <query.txt> Provide a file to describe the find query.\n" " -o <data.csv> Provide a file for the query results.\n" " --help Print a brief help message.\n" " --version Print the software version.\n"); } // print the help void dicomfind_help(FILE *file, const char *cp) { dicomfind_usage(file, cp); fprintf(file, "\n" "Dump the metadata from a DICOM series as text.\n"); } // remove path portion of filename const char *dicomfind_basename(const char *filename) { const char *cp = filename + strlen(filename); while (cp != filename && cp[-1] != '\\' && cp[-1] != '/') { --cp; } return cp; } typedef vtkDICOMVR VR; // Write the header void dicomfind_writeheader( const vtkDICOMItem& query, const QueryTagList *ql, std::ostream& os) { // print human-readable names for each tag for (size_t i = 0; i < ql->size(); i++) { if (i != 0) { os << ","; } const vtkDICOMItem *pitem = &query; vtkDICOMTagPath tagPath = ql->at(i); for (;;) { vtkDICOMTag tag = tagPath.GetHead(); vtkDICOMDictEntry e = pitem->FindDictEntry(tag); if (e.IsValid()) { os << e.GetName(); } if (!tagPath.HasTail()) { break; } pitem = pitem->GetAttributeValue(tag).GetSequenceData(); tagPath = tagPath.GetTail(); os << "\\"; } } os << "\r\n"; // print the private creator for (size_t i = 0; i < ql->size(); i++) { if (i != 0) { os << ","; } const vtkDICOMItem *pitem = &query; vtkDICOMTagPath tagPath = ql->at(i); for (;;) { vtkDICOMTag tag = tagPath.GetHead(); std::string creator = "DICOM"; if ((tag.GetGroup() & 0x0001) == 1) { vtkDICOMTag ctag(tag.GetGroup(), tag.GetElement() >> 8); creator = pitem->GetAttributeValue(ctag).AsString(); } os << creator.c_str(); if (!tagPath.HasTail()) { break; } pitem = pitem->GetAttributeValue(tag).GetSequenceData(); tagPath = tagPath.GetTail(); os << "\\"; } } os << "\r\n"; // print the tag as a hexadecimal number for (size_t i = 0; i < ql->size(); i++) { if (i != 0) { os << ","; } const vtkDICOMItem *pitem = &query; vtkDICOMTagPath tagPath = ql->at(i); for (;;) { vtkDICOMTag tag = tagPath.GetHead(); unsigned short g = tag.GetGroup(); unsigned short e = tag.GetElement(); std::string creator; if ((tag.GetGroup() & 0x0001) == 1) { vtkDICOMTag ctag(tag.GetGroup(), tag.GetElement() >> 8); creator = pitem->GetAttributeValue(ctag).AsString(); if (creator.length() > 0) { // remove the creator portion of the element number e &= 0x00FF; } } char tagtext[16]; sprintf(tagtext, "%04X%04X", g, e); os << tagtext; if (!tagPath.HasTail()) { break; } pitem = pitem->GetAttributeValue(tag).GetSequenceData(); tagPath = tagPath.GetTail(); os << "\\"; } } os << "\r\n"; // print the VR for (size_t i = 0; i < ql->size(); i++) { if (i != 0) { os << ","; } const vtkDICOMItem *pitem = &query; vtkDICOMTagPath tagPath = ql->at(i); vtkDICOMValue v = query.GetAttributeValue(tagPath); if (v.IsValid()) { os << v.GetVR().GetText(); } else { for (;;) { vtkDICOMTag tag = tagPath.GetHead(); if (!tagPath.HasTail()) { vtkDICOMDictEntry e = pitem->FindDictEntry(tag); if (e.IsValid()) { os << e.GetVR().GetText(); } break; } pitem = pitem->GetAttributeValue(tag).GetSequenceData(); tagPath = tagPath.GetTail(); } } } os << "\r\n"; } // Convert date to format YYYY-MM-DD HH:MM:SS std::string dicomfind_date(const std::string& dt, vtkDICOMVR vr) { if (vr == VR::TM && dt.length() >= 6) { return dt.substr(0,2) + ":" + dt.substr(2,2) + ":" + dt.substr(4,2); } else if (vr == VR::DA && dt.length() >= 8) { return dt.substr(0,4) + "-" + dt.substr(4,2) + "-" + dt.substr(6,2); } else if (vr == VR::DT && dt.length() >= 14) { return dt.substr(0,4) + "-" + dt.substr(4,2) + "-" + dt.substr(6,2) + " " + dt.substr(8,2) + ":" + dt.substr(10,2) + ":" + dt.substr(12,2); } return ""; } // Quote a string by doubling any double-quotes that are found // (this follows RFC 4180) std::string dicomfind_quote(const std::string& s) { size_t i = 0; std::string r; for (;;) { size_t j = s.find('\"', i); if (j < s.length()) { r += s.substr(i, j-i+1); r += "\""; i = j+1; } else { r += s.substr(i); break; } } return r; } // Write out the results void dicomfind_write(vtkDICOMDirectory *finder, const vtkDICOMItem& query, const QueryTagList *ql, std::ostream& os) { for (int j = 0; j < finder->GetNumberOfStudies(); j++) { int k0 = finder->GetFirstSeriesForStudy(j); int k1 = finder->GetLastSeriesForStudy(j); for (int k = k0; k <= k1; k++) { vtkStringArray *a = finder->GetFileNamesForSeries(k); vtkSmartPointer<vtkDICOMMetaData> meta = vtkSmartPointer<vtkDICOMMetaData>::New(); vtkSmartPointer<vtkDICOMParser> parser = vtkSmartPointer<vtkDICOMParser>::New(); parser->SetFileName(a->GetValue(0)); parser->SetMetaData(meta); parser->Update(); vtkDICOMItem result = meta->Query(query); vtkDICOMDataElementIterator iter; // print the value of each tag for (size_t i = 0; i < ql->size(); i++) { if (i != 0) { os << ","; } const vtkDICOMItem *qitem = &query; const vtkDICOMItem *mitem = 0; const vtkDICOMValue *vp = 0; vtkDICOMTagPath tagPath = ql->at(i); for (;;) { vtkDICOMTag tag = tagPath.GetHead(); std::string creator; if ((tag.GetGroup() & 0x0001) == 1) { vtkDICOMTag ctag(tag.GetGroup(), tag.GetElement() >> 8); creator = qitem->GetAttributeValue(ctag).AsString(); if (mitem) { tag = meta->ResolvePrivateTag(tag, creator); } else { tag = mitem->ResolvePrivateTag(tag, creator); } } if (mitem) { vp = &mitem->GetAttributeValue(tag); } else { vp = &meta->GetAttributeValue(tag); } if (vp == 0 || !tagPath.HasTail()) { break; } qitem = qitem->GetAttributeValue( tagPath.GetHead()).GetSequenceData(); tagPath = tagPath.GetTail(); mitem = vp->GetSequenceData(); if (mitem == 0 || vp->GetNumberOfValues() == 0) { break; } } if (vp != 0) { const vtkDICOMValue& v = *vp; if (v.GetNumberOfValues() == 1 && (v.GetVR() == VR::SS || v.GetVR() == VR::US || v.GetVR() == VR::SL || v.GetVR() == VR::UL || v.GetVR() == VR::FL || v.GetVR() == VR::FD)) { os << v; } else if (v.GetVR() == VR::DA || v.GetVR() == VR::TM || v.GetVR() == VR::DT) { os << "\"" << dicomfind_date(v.AsString(), v.GetVR()) << "\""; } else if (v.GetVR() == VR::SQ) { // how should a sequence be printed out to the csv file? } else if (v.GetVL() != 0 && v.GetVL() != 0xFFFFFFFF) { os << "\"" << dicomfind_quote(v.AsUTF8String()) << "\""; } } } os << "\r\n"; } } } // This program will dump all the metadata in the given file int main(int argc, char *argv[]) { int rval = 0; vtkSmartPointer<vtkStringArray> a = vtkSmartPointer<vtkStringArray>::New(); const char *ofile = 0; const char *qfile = 0; if (argc < 2) { dicomfind_usage(stdout, dicomfind_basename(argv[0])); return rval; } else if (argc == 2 && strcmp(argv[1], "--help") == 0) { dicomfind_help(stdout, dicomfind_basename(argv[0])); return rval; } else if (argc == 2 && strcmp(argv[1], "--version") == 0) { dicomfind_version(stdout, dicomfind_basename(argv[0])); return rval; } for (int argi = 1; argi < argc; argi++) { const char *arg = argv[argi]; if (strcmp(arg, "-q") == 0 || strcmp(arg, "-o") == 0) { if (argi + 1 == argc || argv[argi+1][0] == '-') { fprintf(stderr, "%s must be followed by a file.\n\n", arg); dicomfind_usage(stderr, dicomfind_basename(argv[0])); return 1; } if (arg[1] == 'q') { qfile = argv[++argi]; } else if (arg[1] == 'o') { ofile = argv[++argi]; } } else if (arg[0] == '-') { fprintf(stderr, "unrecognized option %s.\n\n", arg); dicomfind_usage(stderr, dicomfind_basename(argv[0])); return 1; } else { a->InsertNextValue(arg); } } if (qfile == 0) { fprintf(stderr, "No query file.\n\n"); dicomfind_usage(stderr, dicomfind_basename(argv[0])); return 1; } std::ostream *osp = &std::cout; std::ofstream ofs; if (ofile) { ofs.open(ofile, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc); if (ofs.bad()) { fprintf(stderr, "Unable to open output file %s.\n", ofile); return 1; } osp = &ofs; } // read the query file, create a query QueryTagList qtlist; vtkDICOMItem query = dicomcli_readquery(qfile, &qtlist); // Write the header dicomfind_writeheader(query, &qtlist, *osp); osp->flush(); // Write data for every input directory for (vtkIdType i = 0; i < a->GetNumberOfTuples(); i++) { vtkSmartPointer<vtkDICOMDirectory> finder = vtkSmartPointer<vtkDICOMDirectory>::New(); finder->SetDirectoryName(a->GetValue(i)); finder->SetScanDepth(8); finder->SetFindQuery(query); finder->Update(); dicomfind_write(finder, query, &qtlist, *osp); osp->flush(); } return rval; }
/*========================================================================= Program: DICOM for VTK Copyright (c) 2012-2014 David Gobbi All rights reserved. See Copyright.txt or http://dgobbi.github.io/bsd3.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 notice for more information. =========================================================================*/ #include "vtkDICOMDirectory.h" #include "vtkDICOMMetaData.h" #include "vtkDICOMItem.h" #include "vtkDICOMDataElement.h" #include "vtkDICOMParser.h" #include "vtkDICOMMetaData.h" // from dicomcli #include "readquery.h" #include <vtkStringArray.h> #include <vtkSmartPointer.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> // print the version void dicomfind_version(FILE *file, const char *cp) { fprintf(file, "%s %s\n", cp, DICOM_VERSION); fprintf(file, "\n" "Copyright (c) 2012-2014, David Gobbi.\n\n" "This software is distributed under an open-source license. See the\n" "Copyright.txt file that comes with the vtk-dicom source distribution.\n"); } // print the usage void dicomfind_usage(FILE *file, const char *cp) { fprintf(file, "usage:\n" " %s -q <query.txt> -o <data.csv> <directory>\n\n", cp); fprintf(file, "options:\n" " -q <query.txt> Provide a file to describe the find query.\n" " -o <data.csv> Provide a file for the query results.\n" " --help Print a brief help message.\n" " --version Print the software version.\n"); } // print the help void dicomfind_help(FILE *file, const char *cp) { dicomfind_usage(file, cp); fprintf(file, "\n" "Dump the metadata from a DICOM series as text.\n"); } // remove path portion of filename const char *dicomfind_basename(const char *filename) { const char *cp = filename + strlen(filename); while (cp != filename && cp[-1] != '\\' && cp[-1] != '/') { --cp; } return cp; } typedef vtkDICOMVR VR; // Write the header void dicomfind_writeheader( const vtkDICOMItem& query, const QueryTagList *ql, std::ostream& os) { // print human-readable names for each tag for (size_t i = 0; i < ql->size(); i++) { if (i != 0) { os << ","; } const vtkDICOMItem *pitem = &query; vtkDICOMTagPath tagPath = ql->at(i); for (;;) { vtkDICOMTag tag = tagPath.GetHead(); vtkDICOMDictEntry e = pitem->FindDictEntry(tag); if (e.IsValid()) { os << e.GetName(); } if (!tagPath.HasTail()) { break; } pitem = pitem->GetAttributeValue(tag).GetSequenceData(); tagPath = tagPath.GetTail(); os << "\\"; } } os << "\r\n"; // print the private creator for (size_t i = 0; i < ql->size(); i++) { if (i != 0) { os << ","; } const vtkDICOMItem *pitem = &query; vtkDICOMTagPath tagPath = ql->at(i); for (;;) { vtkDICOMTag tag = tagPath.GetHead(); std::string creator = "DICOM"; if ((tag.GetGroup() & 0x0001) == 1) { vtkDICOMTag ctag(tag.GetGroup(), tag.GetElement() >> 8); creator = pitem->GetAttributeValue(ctag).AsString(); } os << creator.c_str(); if (!tagPath.HasTail()) { break; } pitem = pitem->GetAttributeValue(tag).GetSequenceData(); tagPath = tagPath.GetTail(); os << "\\"; } } os << "\r\n"; // print the tag as a hexadecimal number for (size_t i = 0; i < ql->size(); i++) { if (i != 0) { os << ","; } const vtkDICOMItem *pitem = &query; vtkDICOMTagPath tagPath = ql->at(i); for (;;) { vtkDICOMTag tag = tagPath.GetHead(); unsigned short g = tag.GetGroup(); unsigned short e = tag.GetElement(); std::string creator; if ((tag.GetGroup() & 0x0001) == 1) { vtkDICOMTag ctag(tag.GetGroup(), tag.GetElement() >> 8); creator = pitem->GetAttributeValue(ctag).AsString(); if (creator.length() > 0) { // remove the creator portion of the element number e &= 0x00FF; } } char tagtext[16]; sprintf(tagtext, "%04X%04X", g, e); os << tagtext; if (!tagPath.HasTail()) { break; } pitem = pitem->GetAttributeValue(tag).GetSequenceData(); tagPath = tagPath.GetTail(); os << "\\"; } } os << "\r\n"; // print the VR for (size_t i = 0; i < ql->size(); i++) { if (i != 0) { os << ","; } const vtkDICOMItem *pitem = &query; vtkDICOMTagPath tagPath = ql->at(i); vtkDICOMValue v = query.GetAttributeValue(tagPath); if (v.IsValid()) { os << v.GetVR().GetText(); } else { for (;;) { vtkDICOMTag tag = tagPath.GetHead(); if (!tagPath.HasTail()) { vtkDICOMDictEntry e = pitem->FindDictEntry(tag); if (e.IsValid()) { os << e.GetVR().GetText(); } break; } pitem = pitem->GetAttributeValue(tag).GetSequenceData(); tagPath = tagPath.GetTail(); } } } os << "\r\n"; } // Convert date to format YYYY-MM-DD HH:MM:SS std::string dicomfind_date(const std::string& dt, vtkDICOMVR vr) { if (vr == VR::TM && dt.length() >= 6) { return dt.substr(0,2) + ":" + dt.substr(2,2) + ":" + dt.substr(4,2); } else if (vr == VR::DA && dt.length() >= 8) { return dt.substr(0,4) + "-" + dt.substr(4,2) + "-" + dt.substr(6,2); } else if (vr == VR::DT && dt.length() >= 14) { return dt.substr(0,4) + "-" + dt.substr(4,2) + "-" + dt.substr(6,2) + " " + dt.substr(8,2) + ":" + dt.substr(10,2) + ":" + dt.substr(12,2); } return ""; } // Quote a string by doubling any double-quotes that are found // (this follows RFC 4180) std::string dicomfind_quote(const std::string& s) { size_t i = 0; std::string r; for (;;) { size_t j = s.find('\"', i); if (j < s.length()) { r += s.substr(i, j-i+1); r += "\""; i = j+1; } else { r += s.substr(i); break; } } return r; } // Write out the results void dicomfind_write(vtkDICOMDirectory *finder, const vtkDICOMItem& query, const QueryTagList *ql, std::ostream& os) { for (int j = 0; j < finder->GetNumberOfStudies(); j++) { int k0 = finder->GetFirstSeriesForStudy(j); int k1 = finder->GetLastSeriesForStudy(j); for (int k = k0; k <= k1; k++) { vtkStringArray *a = finder->GetFileNamesForSeries(k); vtkSmartPointer<vtkDICOMMetaData> meta = vtkSmartPointer<vtkDICOMMetaData>::New(); vtkSmartPointer<vtkDICOMParser> parser = vtkSmartPointer<vtkDICOMParser>::New(); parser->SetFileName(a->GetValue(0)); parser->SetMetaData(meta); parser->SetQueryItem(query); parser->Update(); vtkDICOMDataElementIterator iter; // print the value of each tag for (size_t i = 0; i < ql->size(); i++) { if (i != 0) { os << ","; } const vtkDICOMItem *qitem = &query; const vtkDICOMItem *mitem = 0; const vtkDICOMValue *vp = 0; vtkDICOMTagPath tagPath = ql->at(i); for (;;) { vtkDICOMTag tag = tagPath.GetHead(); std::string creator; if ((tag.GetGroup() & 0x0001) == 1) { vtkDICOMTag ctag(tag.GetGroup(), tag.GetElement() >> 8); creator = qitem->GetAttributeValue(ctag).AsString(); if (mitem) { tag = meta->ResolvePrivateTag(tag, creator); } else { tag = mitem->ResolvePrivateTag(tag, creator); } } if (mitem) { vp = &mitem->GetAttributeValue(tag); } else { vp = &meta->GetAttributeValue(tag); } if (vp == 0 || !tagPath.HasTail()) { break; } qitem = qitem->GetAttributeValue( tagPath.GetHead()).GetSequenceData(); tagPath = tagPath.GetTail(); mitem = vp->GetSequenceData(); if (mitem == 0 || vp->GetNumberOfValues() == 0) { break; } } if (vp != 0) { const vtkDICOMValue& v = *vp; if (v.GetNumberOfValues() == 1 && (v.GetVR() == VR::SS || v.GetVR() == VR::US || v.GetVR() == VR::SL || v.GetVR() == VR::UL || v.GetVR() == VR::FL || v.GetVR() == VR::FD)) { os << v; } else if (v.GetVR() == VR::DA || v.GetVR() == VR::TM || v.GetVR() == VR::DT) { os << "\"" << dicomfind_date(v.AsString(), v.GetVR()) << "\""; } else if (v.GetVR() == VR::SQ) { // how should a sequence be printed out to the csv file? } else if (v.GetVL() != 0 && v.GetVL() != 0xFFFFFFFF) { os << "\"" << dicomfind_quote(v.AsUTF8String()) << "\""; } } } os << "\r\n"; } } } // This program will dump all the metadata in the given file int main(int argc, char *argv[]) { int rval = 0; vtkSmartPointer<vtkStringArray> a = vtkSmartPointer<vtkStringArray>::New(); const char *ofile = 0; const char *qfile = 0; if (argc < 2) { dicomfind_usage(stdout, dicomfind_basename(argv[0])); return rval; } else if (argc == 2 && strcmp(argv[1], "--help") == 0) { dicomfind_help(stdout, dicomfind_basename(argv[0])); return rval; } else if (argc == 2 && strcmp(argv[1], "--version") == 0) { dicomfind_version(stdout, dicomfind_basename(argv[0])); return rval; } for (int argi = 1; argi < argc; argi++) { const char *arg = argv[argi]; if (strcmp(arg, "-q") == 0 || strcmp(arg, "-o") == 0) { if (argi + 1 == argc || argv[argi+1][0] == '-') { fprintf(stderr, "%s must be followed by a file.\n\n", arg); dicomfind_usage(stderr, dicomfind_basename(argv[0])); return 1; } if (arg[1] == 'q') { qfile = argv[++argi]; } else if (arg[1] == 'o') { ofile = argv[++argi]; } } else if (arg[0] == '-') { fprintf(stderr, "unrecognized option %s.\n\n", arg); dicomfind_usage(stderr, dicomfind_basename(argv[0])); return 1; } else { a->InsertNextValue(arg); } } if (qfile == 0) { fprintf(stderr, "No query file.\n\n"); dicomfind_usage(stderr, dicomfind_basename(argv[0])); return 1; } std::ostream *osp = &std::cout; std::ofstream ofs; if (ofile) { ofs.open(ofile, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc); if (ofs.bad()) { fprintf(stderr, "Unable to open output file %s.\n", ofile); return 1; } osp = &ofs; } // read the query file, create a query QueryTagList qtlist; vtkDICOMItem query = dicomcli_readquery(qfile, &qtlist); // Write the header dicomfind_writeheader(query, &qtlist, *osp); osp->flush(); // Write data for every input directory for (vtkIdType i = 0; i < a->GetNumberOfTuples(); i++) { vtkSmartPointer<vtkDICOMDirectory> finder = vtkSmartPointer<vtkDICOMDirectory>::New(); finder->SetDirectoryName(a->GetValue(i)); finder->SetScanDepth(8); finder->SetFindQuery(query); finder->Update(); dicomfind_write(finder, query, &qtlist, *osp); osp->flush(); } return rval; }
Use query to filter parser results in dicomfind.
Use query to filter parser results in dicomfind.
C++
bsd-3-clause
hendradarwin/vtk-dicom,hendradarwin/vtk-dicom,dgobbi/vtk-dicom,dgobbi/vtk-dicom,dgobbi/vtk-dicom,hendradarwin/vtk-dicom
3a11066d67c28572d3489654500e68c535817d14
main.cpp
main.cpp
dd67cdd7-ad5c-11e7-b10b-ac87a332f658
ddbff091-ad5c-11e7-8d6d-ac87a332f658
Put the thingie in the thingie
Put the thingie in the thingie
C++
mit
justinhyou/GestureRecognition-CNN,justinhyou/GestureRecognition-CNN
c42de42ed7f8d0039849eabc4a79d3cfeb76ecf1
main.cpp
main.cpp
/*[email protected]*/ #include <QtWidgets/QApplication> #include "ignsdk.h" #include <QtWebKitWidgets/QWebView> #include <QFileDialog> #include <iostream> #include "version.h" #include <QCommandLineParser> using namespace std; int main(int argc, char *argv[]) { QApplication a(argc, argv); ign w; QString url = NULL; bool file = false; QString optional; QCommandLineParser cmd_parser; cmd_parser.setApplicationDescription("IGOS Nusantara Software Development Kit"); QCommandLineOption cmd_project(QStringList() << "p" << "project", "Specify project directory", "directory"); cmd_parser.addOption(cmd_project); QCommandLineOption cmd_file(QStringList() << "f" << "file", "Load specific HTML file instead of index.html", "file"); cmd_parser.addOption(cmd_file); QCommandLineOption cmd_dev(QStringList() << "d" << "development", "Activate development mode"); cmd_parser.addOption(cmd_dev); QCommandLineOption cmd_remote(QStringList() << "r" << "remote", "Activate remote debugging", "port"); cmd_parser.addOption(cmd_remote); QCommandLineOption cmd_version(QStringList() << "v" << "version", "Show version"); cmd_parser.addOption(cmd_version); cmd_parser.addHelpOption(); cmd_parser.process(a); if (cmd_parser.isSet(cmd_version)){ printf("IGNSDK version %s (%s). Compiled on %s %s. Maintained by %s.\n", IGNSDK_VERSION, IGNSDK_CODENAME, __DATE__, __TIME__, IGNSDK_MAINTAINER); exit(0); } url = cmd_parser.value(cmd_project); if (cmd_parser.isSet(cmd_remote)){ w.setDevRemote(cmd_parser.value(cmd_remote).toInt()); } if (cmd_parser.isSet(cmd_file)){ if (cmd_parser.isSet(cmd_project)){ file = true; optional = cmd_parser.value(cmd_file); } else { qDebug() << "Error: Project directory must be specified."; exit(1); } } QString opt = url; QString path = url; if (!opt.isEmpty()){ w.pathApp = opt; /*icon set*/ a.setWindowIcon(QIcon(path+"icons/app.png")); if(file){ opt += "/"; opt += optional; } else { opt += "/index.html"; } if (QFile::exists(opt)){ w.render(opt); w.config(url); w.show(); } else { qDebug() << "Error:" << opt << "is not exist."; exit(1); } } else { QFileDialog *fd = new QFileDialog; #ifdef Linux QTreeView *tree = fd->findChild <QTreeView*>(); tree->setRootIsDecorated(true); tree->setItemsExpandable(true); #endif fd->setFileMode(QFileDialog::Directory); fd->setOption(QFileDialog::ShowDirsOnly); fd->setViewMode(QFileDialog::Detail); int result = fd->exec(); QString directory; if (result){ directory = fd->selectedFiles()[0]; if (QFile::exists(directory + "/index.html")) { w.config(directory); w.render(directory+"/index.html"); w.show(); } else { qDebug() << "Error:" << (directory + "/index.html") << "is not exist."; exit(1); } } else { exit(1); } } return a.exec(); }
/*[email protected]*/ #include <QtWidgets/QApplication> #include "ignsdk.h" #include <QtWebKitWidgets/QWebView> #include <QFileDialog> #include <iostream> #include "version.h" #include <QCommandLineParser> using namespace std; int main(int argc, char *argv[]) { QApplication app(argc, argv); ign ignsdk; QString url = NULL; bool file = false; QString optional; QCommandLineParser cmd_parser; cmd_parser.setApplicationDescription("IGOS Nusantara Software Development Kit"); QCommandLineOption cmd_project(QStringList() << "p" << "project", "Specify project directory", "directory"); cmd_parser.addOption(cmd_project); QCommandLineOption cmd_file(QStringList() << "f" << "file", "Load specific HTML file instead of index.html", "file"); cmd_parser.addOption(cmd_file); QCommandLineOption cmd_dev(QStringList() << "d" << "development", "Activate development mode"); cmd_parser.addOption(cmd_dev); QCommandLineOption cmd_remote(QStringList() << "r" << "remote", "Activate remote debugging", "port"); cmd_parser.addOption(cmd_remote); QCommandLineOption cmd_version(QStringList() << "v" << "version", "Show version"); cmd_parser.addOption(cmd_version); cmd_parser.addHelpOption(); cmd_parser.process(app); if (cmd_parser.isSet(cmd_version)){ printf("IGNSDK version %s (%s). Compiled on %s %s. Maintained by %s.\n", IGNSDK_VERSION, IGNSDK_CODENAME, __DATE__, __TIME__, IGNSDK_MAINTAINER); exit(0); } url = cmd_parser.value(cmd_project); if (cmd_parser.isSet(cmd_remote)){ ignsdk.setDevRemote(cmd_parser.value(cmd_remote).toInt()); } if (cmd_parser.isSet(cmd_file)){ if (cmd_parser.isSet(cmd_project)){ file = true; optional = cmd_parser.value(cmd_file); } else { qDebug() << "Error: Project directory must be specified."; exit(1); } } QString opt = url; QString path = url; if (!opt.isEmpty()){ ignsdk.pathApp = opt; app.setWindowIcon(QIcon(path+"icons/app.png")); if(file){ opt += "/"; opt += optional; } else { opt += "/index.html"; } if (QFile::exists(opt)){ ignsdk.render(opt); ignsdk.config(url); ignsdk.show(); } else { qDebug() << "Error:" << opt << "is not exist."; exit(1); } } else { QFileDialog *fileDialog = new QFileDialog; #ifdef Linux QTreeView *tree = fileDialog->findChild <QTreeView*>(); tree->setRootIsDecorated(true); tree->setItemsExpandable(true); #endif fileDialog->setFileMode(QFileDialog::Directory); fileDialog->setOption(QFileDialog::ShowDirsOnly); fileDialog->setViewMode(QFileDialog::Detail); int result = fileDialog->exec(); QString directory; if (result){ directory = fileDialog->selectedFiles()[0]; if (QFile::exists(directory + "/index.html")) { ignsdk.config(directory); ignsdk.render(directory + "/index.html"); ignsdk.show(); } else { qDebug() << "Error:" << (directory + "/index.html") << "is not exist."; exit(1); } } else { exit(1); } } return app.exec(); }
Improve code readability and consistency
main.cpp: Improve code readability and consistency
C++
bsd-3-clause
ubunteroz/ignsdk,ubunteroz/ignsdk,ubunteroz/ignsdk,ubunteroz/ignsdk-debian,ubunteroz/ignsdk-debian,ubunteroz/ignsdk-debian
e36c10fca24a194d1c6134a1c885c461186455cc
main.cpp
main.cpp
#include <iostream> #include "type_name_rt.hpp" #include "type_name_pt.hpp" // std::array<char> output operator, for type_name_pt output template <size_t N> std::ostream& operator<<(std::ostream& o, std::array<char,N> const& a) { for (char c : a) o.put(c); return o; } constexpr char c{}; int main() { std::cout << "AUTO_NAME &c : " << auto_name_pt<&c> << '\n'; std::cout << "AUTO_NAME char{} : " << auto_name_pt<char{}> << '\n'; std::cout << '\n'; std::cout << "TYPE_NAME char _PT : " << type_name_pt<char> << '\n'; std::cout << " _RT : " << type_name_rt<char> << '\n'; std::cout << "TYPE_NAME int& _PT : " << type_name_pt<int&> << '\n'; std::cout << " _RT : " << type_name_rt<int&> << '\n'; std::cout << "TYPE_NAME bool&& _PT : " << type_name_pt<bool&&> << '\n'; std::cout << " _RT : " << type_name_rt<bool&&> << '\n'; std::cout << "TYPE_NAME int const& _PT : " << type_name_pt<int const&> << '\n'; std::cout << " _RT : " << type_name_rt<int const&> << '\n'; std::cout << '\n'; const volatile char abc[1][2][3]{}; using ABC = decltype(abc); std::cout << "TYPE_NAME const volatile char[1][2][3] _PT: " << type_name_pt<ABC> << '\n'; std::cout << " _RT: " << type_name_rt<ABC> << '\n'; std::cout << '\n'; std::cout << "TYPE_NAME std::string : _PT " << type_name_pt<std::string> << '\n'; std::cout << " : _RT " << type_name_rt<std::string> << '\n'; }
#include <iostream> #include "type_name_rt.hpp" #include "type_name_pt.hpp" // std::array<char> output operator, for type_name_pt output template <size_t N> std::ostream& operator<<(std::ostream& o, std::array<char,N> const& a) { for (char c : a) o.put(c); return o; } constexpr char static_var{}; int main() { std::cout << "AUTO_NAME &static_var : " << auto_name_pt<&static_var> << '\n'; std::cout << "AUTO_NAME char{} : " << auto_name_pt<char{}> << '\n'; std::cout << '\n'; std::cout << "TYPE_NAME char _PT : " << type_name_pt<char> << '\n'; std::cout << " _RT : " << type_name_rt<char> << '\n'; std::cout << "TYPE_NAME int& _PT : " << type_name_pt<int&> << '\n'; std::cout << " _RT : " << type_name_rt<int&> << '\n'; std::cout << "TYPE_NAME bool&& _PT : " << type_name_pt<bool&&> << '\n'; std::cout << " _RT : " << type_name_rt<bool&&> << '\n'; std::cout << "TYPE_NAME int const& _PT : " << type_name_pt<int const&> << '\n'; std::cout << " _RT : " << type_name_rt<int const&> << '\n'; std::cout << '\n'; const volatile char abc[1][2][3]{}; using ABC = decltype(abc); std::cout << "TYPE_NAME const volatile char[1][2][3] _PT: " << type_name_pt<ABC> << '\n'; std::cout << " _RT: " << type_name_rt<ABC> << '\n'; std::cout << '\n'; std::cout << "TYPE_NAME std::string : _PT " << type_name_pt<std::string> << '\n'; std::cout << " : _RT " << type_name_rt<std::string> << '\n'; }
rename global var to longer descriptive name - single char was shadowing
rename global var to longer descriptive name - single char was shadowing
C++
cc0-1.0
willwray/type_name
ce560141ba66353e43f3e740e369f7dcee7babbc
main.cpp
main.cpp
/* **** **** **** **** **** **** **** **** * * * _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * _/ _/ _/ _/ _/ _/ * _/ _/ _/ _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * * bit by bit * main.cpp * * author: ISHII 2bit * mail: [email protected] * * **** **** **** **** **** **** **** **** */ #include "bit_by_bit.hpp" void reusable_array_test(); void byte_array_test(); void multithread_test(size_t num); void range_test(); int main(int argc, char *argv[]) { reusable_array_test(); byte_array_test(); multithread_test(4); range_test(); } #pragma mark reusable_array_test #include <cassert> #include <iostream> struct particle { int life_time; int age; int name; particle() {} particle(int life_time, int name) : life_time(life_time) , name(name) , age(0) {} void init(int life_time, int name) { this->life_time = life_time; this->name = name; this->age = 0; } bool update() { return ++age < life_time; } void print() const { std::cout << name << ", " << (life_time - age) << std::endl; } }; constexpr int loop_num(1); constexpr int elem_num(10); void reusable_array_test() { bbb::random::set_seed_mt(0); auto a = bbb::random::mt(); bbb::random::set_seed_mt(0); auto b = bbb::random::mt(); bbb::random::set_seed_mt(1); auto c = bbb::random::mt(); assert(a == b); assert(a != c); bbb::stop_watch watch; watch.start(); { bbb::random::set_seed_mt(0); bbb::reusable_array<particle, elem_num> f; watch.rap(); for(int k = 0; k++ < loop_num;) { do f.init(bbb::random::mt() % 100, f.current_size()); while(f.has_space()); while(f.current_size()) { f.update(); } } watch.rap(); std::cout << "time: " << watch.getLastRapNanoseconds() << std::endl; } { bbb::random::set_seed_mt(0); bbb::shared_vector<particle> f; watch.rap(); for(int k = 0; k++ < loop_num;) { for(; f.size() < elem_num; f.push_back(std::shared_ptr<particle>(new particle(rand() % 100, f.size())))); auto wrapper = bbb::make_reverse(f); while(f.size()) for(auto e : wrapper) if(!e->update()) { e = f.back(); f.pop_back(); } } watch.rap(); std::cout << "time: " << watch.getLastRapNanoseconds() << std::endl; } } void byte_array_test() { bbb::byte_array<int> barr{0x7FFFFFFF}; for(auto i = 0; i < barr.size(); i++) { std::cout << (int)barr[i] << std::endl; } }; void multithread_test(size_t num) { size_t sum = 0; bool is_run = true; bbb::stop_watch watch; watch.start(); bbb::multithread::manager manager(num, [&sum, &is_run](size_t index, std::mutex &mutex) { while(is_run) { if(mutex.try_lock()) { sum++; mutex.unlock(); } bbb::sleep_nanoseconds(50); } }); while(is_run) { bbb::sleep_milliseconds(10); auto lock(manager.lock_guard()); if(100000 < sum) { is_run = false; manager.join(); } } watch.rap(); std::cout << "time: " << watch.getLastRapMilliseconds() << std::endl; } void range_test() { { std::vector<int> vec; bbb::for_each(bbb::range(10, 2), [&vec](int x) { vec.push_back(x); }); bbb::for_each(vec, [](int &x) { x *= 2; }); for(auto v : bbb::enumerate(vec)) { std::cout << v.index << ", " << v.value << std::endl; v.value *= 2; } for(auto v : bbb::enumerate(vec)) { std::cout << v.index << ", " << v.value << std::endl; } } { const std::vector<int> cvec{1, 2, 3}; for(auto v : bbb::enumerate(cvec)) { std::cout << v.index << ", " << v.value << std::endl; } } std::cout << std::endl; std::vector<std::string> svec{"a", "hoge", "foo"}; for(auto &v : bbb::enumerate(svec)) { std::cout << v.index << ", " << v.value << std::endl; } for(const auto &v : bbb::enumerate(svec)) { std::cout << v.index << ", " << v.value << std::endl; } }
/* **** **** **** **** **** **** **** **** * * * _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * _/ _/ _/ _/ _/ _/ * _/ _/ _/ _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * * bit by bit * main.cpp * * author: ISHII 2bit * mail: [email protected] * * **** **** **** **** **** **** **** **** */ #include "bit_by_bit.hpp" void reusable_array_test(); void byte_array_test(); void multithread_test(size_t num); void range_test(); void iterator_test(); int main(int argc, char *argv[]) { reusable_array_test(); byte_array_test(); multithread_test(4); range_test(); iterator_test(); } #pragma mark reusable_array_test #include <cassert> #include <iostream> struct particle { int life_time; int age; int name; particle() {} particle(int life_time, int name) : life_time(life_time) , name(name) , age(0) {} void init(int life_time, int name) { this->life_time = life_time; this->name = name; this->age = 0; } bool update() { return ++age < life_time; } void print() const { std::cout << name << ", " << (life_time - age) << std::endl; } }; constexpr int loop_num(1); constexpr int elem_num(10); void reusable_array_test() { bbb::random::set_seed_mt(0); auto a = bbb::random::mt(); bbb::random::set_seed_mt(0); auto b = bbb::random::mt(); bbb::random::set_seed_mt(1); auto c = bbb::random::mt(); assert(a == b); assert(a != c); bbb::stop_watch watch; watch.start(); { bbb::random::set_seed_mt(0); bbb::reusable_array<particle, elem_num> f; watch.rap(); for(int k = 0; k++ < loop_num;) { do f.init(bbb::random::mt() % 100, f.current_size()); while(f.has_space()); while(f.current_size()) { f.update(); } } watch.rap(); std::cout << "time: " << watch.getLastRapNanoseconds() << std::endl; } { bbb::random::set_seed_mt(0); bbb::shared_vector<particle> f; watch.rap(); for(int k = 0; k++ < loop_num;) { for(; f.size() < elem_num; f.push_back(std::shared_ptr<particle>(new particle(rand() % 100, f.size())))); auto wrapper = bbb::make_reverse(f); while(f.size()) for(auto e : wrapper) if(!e->update()) { e = f.back(); f.pop_back(); } } watch.rap(); std::cout << "time: " << watch.getLastRapNanoseconds() << std::endl; } } void byte_array_test() { bbb::byte_array<int> barr{0x7FFFFFFF}; for(auto i = 0; i < barr.size(); i++) { std::cout << (int)barr[i] << std::endl; } for(auto &b : barr) { std::cout << (int)b << std::endl; } }; void multithread_test(size_t num) { size_t sum = 0; bool is_run = true; bbb::stop_watch watch; watch.start(); bbb::multithread::manager manager(num, [&sum, &is_run](size_t index, std::mutex &mutex) { while(is_run) { if(mutex.try_lock()) { sum++; mutex.unlock(); } bbb::sleep_nanoseconds(50); } }); while(is_run) { bbb::sleep_milliseconds(10); auto lock(manager.lock_guard()); if(100000 < sum) { is_run = false; manager.join(); } } watch.rap(); std::cout << "time: " << watch.getLastRapMilliseconds() << std::endl; } void range_test() { { std::vector<int> vec; bbb::for_each(bbb::range(10, 2), [&vec](int x) { vec.push_back(x); }); bbb::for_each(vec, [](int &x) { x *= 2; }); for(auto v : bbb::enumerate(vec)) { std::cout << v.index << ", " << v.value << std::endl; v.value *= 2; } for(auto v : bbb::enumerate(vec)) { std::cout << v.index << ", " << v.value << std::endl; } } { const std::vector<int> cvec{1, 2, 3}; for(auto v : bbb::enumerate(cvec)) { std::cout << v.index << ", " << v.value << std::endl; } } std::cout << std::endl; std::vector<std::string> svec{"a", "hoge", "foo"}; for(auto &v : bbb::enumerate(svec)) { std::cout << v.index << ", " << v.value << std::endl; } for(const auto &v : bbb::enumerate(svec)) { std::cout << v.index << ", " << v.value << std::endl; } } #include <iostream> #include <vector> #include <deque> #include <queue> #include <list> #include <map> #include <string> struct vectroid : bbb::iterator_delegation<std::vector<int>> { std::vector<int> body; vectroid() : delegation(body) {}; }; struct mappoid : bbb::iterator_delegation<std::map<int, int>> { std::map<int, int> body; mappoid() : delegation(body) {}; }; struct introid : bbb::iterator_delegation<int> { int body; introid() : delegation(body) {}; }; void iterator_test() { static_assert(bbb::iteratable_class_traits<std::vector<int>>::has_iterator, "vector<int> has iterator"); static_assert(bbb::iteratable_class_traits<std::vector<int>>::has_reverse_iterator, "vector<int> has reverse_iterator"); std::cout << "std::map<int, int>::iterator " << bbb::iteratable_class_traits<std::map<int, int>>::has_iterator << std::endl; std::cout << "std::string::iterator " << bbb::iteratable_class_traits<std::string>::has_iterator << std::endl; std::cout << "int::iterator " << bbb::iteratable_class_traits<int>::has_iterator << std::endl; std::cout << "bbb::iterator_delegation<std::vector<int>>::iterator " << bbb::iteratable_class_traits<bbb::iterator_delegation<std::vector<int>>>::has_iterator << std::endl; std::cout << std::endl; std::cout << "vector has_insert " << bbb::iteratable_class_traits<std::vector<int>>::has_insert << std::endl; std::cout << "vector has_push_back " << bbb::iteratable_class_traits<std::vector<int>>::has_push_back << std::endl; std::cout << "vector has_push_front " << bbb::iteratable_class_traits<std::vector<int>>::has_push_front << std::endl; std::cout << "deque has_insert " << bbb::iteratable_class_traits<std::deque<int>>::has_insert << std::endl; std::cout << "deque has_push_back " << bbb::iteratable_class_traits<std::deque<int>>::has_push_back << std::endl; std::cout << "deque has_push_front " << bbb::iteratable_class_traits<std::deque<int>>::has_push_front << std::endl; std::cout << "list has_insert " << bbb::iteratable_class_traits<std::list<int>>::has_insert << std::endl; std::cout << "list has_push_back " << bbb::iteratable_class_traits<std::list<int>>::has_push_back << std::endl; std::cout << "list has_push_front " << bbb::iteratable_class_traits<std::list<int>>::has_push_front << std::endl; std::cout << "queue has_insert " << bbb::iteratable_class_traits<std::queue<int>>::has_insert << std::endl; std::cout << "queue has_push_back " << bbb::iteratable_class_traits<std::queue<int>>::has_push_back << std::endl; std::cout << "queue has_push_front " << bbb::iteratable_class_traits<std::queue<int>>::has_push_front << std::endl; std::cout << "int has_insert " << bbb::iteratable_class_traits<int>::has_insert << std::endl; std::cout << "int has_push_back " << bbb::iteratable_class_traits<int>::has_push_back << std::endl; std::cout << "int has_push_front " << bbb::iteratable_class_traits<int>::has_push_front << std::endl; vectroid v; v.body.push_back(-1); v.body.push_back(-2); v.body.push_back(-3); std::vector<int> src{1, 2, 3, 4}; std::copy(src.begin(), src.end(), std::back_inserter(v)); std::copy(src.begin(), src.end(), std::inserter(v, v.begin())); for(const auto &i : v) { std::cout << i << std::endl; } mappoid m; m.body.insert(std::make_pair(2, 3)); m.body.insert(std::make_pair(6, 7)); m.body.insert(std::make_pair(4, 5)); m.body.insert(std::make_pair(8, 9)); for(const auto &p : m) { std::cout << p.first << ", " << p.second << std::endl; } introid i; // for(auto &it : i) {} // Error: delegated type doesn't provide iterator }
add iterator_test
add iterator_test
C++
mit
2bbb/bit_by_bit
ea40295d2dd1d0c7aa5ac27950561032a3bf58db
main.cpp
main.cpp
9dd12780-4b02-11e5-847b-28cfe9171a43
9ddf3c11-4b02-11e5-b584-28cfe9171a43
add file
add file
C++
apache-2.0
haosdent/jcgroup,haosdent/jcgroup
61fdc47b8220716b81518036751368aac2e67f8c
src/components/score.cpp
src/components/score.cpp
// Copyright 2015 Google Inc. 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 "components/score.h" #include "event_system/event_manager.h" #include "event_system/event_payload.h" #include "events/event_ids.h" #include "events/hit_patron.h" #include "events/hit_patron_body.h" #include "events/hit_patron_mouth.h" #include "events/projectile_fired_event.h" #include "fplbase/utilities.h" namespace fpl { namespace fpl_project { void ScoreData::OnEvent(int event_id, const event::EventPayload& event_payload) { (void)event_payload; switch (event_id) { case kEventIdProjectileFired: { LogInfo("Fired projectile"); ++projectiles_fired; break; } case kEventIdHitPatronMouth: { LogInfo("Hit patron mouth"); ++patrons_fed; break; } case kEventIdHitPatronBody: { LogInfo("Hit patron body"); ++patrons_hit; break; } case kEventIdHitPatron: { LogInfo("Hit patron"); // Do nothing here right now... break; } default: { assert(0); } } } void ScoreComponent::Initialize(event::EventManager* event_manager) { event_manager->RegisterListener(kEventIdProjectileFired, this); event_manager->RegisterListener(kEventIdHitPatronMouth, this); event_manager->RegisterListener(kEventIdHitPatronBody, this); event_manager->RegisterListener(kEventIdHitPatron, this); } void ScoreComponent::OnEvent(int event_id, const event::EventPayload& event_payload) { const EntityEventPayload* entity_event; switch (event_id) { case kEventIdProjectileFired: { entity_event = event_payload.ToData<ProjectileFiredEventPayload>(); break; } case kEventIdHitPatronMouth: { entity_event = event_payload.ToData<HitPatronMouthEventPayload>(); break; } case kEventIdHitPatronBody: { entity_event = event_payload.ToData<HitPatronBodyEventPayload>(); break; } case kEventIdHitPatron: { entity_event = event_payload.ToData<HitPatronEventPayload>(); break; } default: { assert(0); } } if (entity_event) { ScoreData* score_data = Data<ScoreData>(entity_event->target); if (score_data) { score_data->OnEvent(event_id, event_payload); } } } void ScoreComponent::AddFromRawData(entity::EntityRef& entity, const void* raw_data) { auto component_data = static_cast<const ComponentDefInstance*>(raw_data); assert(component_data->data_type() == ComponentDataUnion_ScoreDef); AddEntity(entity); } } // fpl_project } // fpl
// Copyright 2015 Google Inc. 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 "components/score.h" #include "event_system/event_manager.h" #include "event_system/event_payload.h" #include "events/event_ids.h" #include "events/hit_patron.h" #include "events/hit_patron_body.h" #include "events/hit_patron_mouth.h" #include "events/projectile_fired_event.h" #include "fplbase/utilities.h" namespace fpl { namespace fpl_project { void ScoreData::OnEvent(int event_id, const event::EventPayload& event_payload) { (void)event_payload; switch (event_id) { case kEventIdProjectileFired: { LogInfo("Fired projectile"); ++projectiles_fired; break; } case kEventIdHitPatronMouth: { LogInfo("Hit patron mouth"); ++patrons_fed; break; } case kEventIdHitPatronBody: { LogInfo("Hit patron body"); ++patrons_hit; break; } case kEventIdHitPatron: { LogInfo("Hit patron"); // Do nothing here right now... break; } default: { assert(0); } } } void ScoreComponent::Initialize(event::EventManager* event_manager) { event_manager->RegisterListener(kEventIdProjectileFired, this); event_manager->RegisterListener(kEventIdHitPatronMouth, this); event_manager->RegisterListener(kEventIdHitPatronBody, this); event_manager->RegisterListener(kEventIdHitPatron, this); } void ScoreComponent::OnEvent(int event_id, const event::EventPayload& event_payload) { const EntityEventPayload* entity_event = nullptr; switch (event_id) { case kEventIdProjectileFired: { entity_event = event_payload.ToData<ProjectileFiredEventPayload>(); break; } case kEventIdHitPatronMouth: { entity_event = event_payload.ToData<HitPatronMouthEventPayload>(); break; } case kEventIdHitPatronBody: { entity_event = event_payload.ToData<HitPatronBodyEventPayload>(); break; } case kEventIdHitPatron: { entity_event = event_payload.ToData<HitPatronEventPayload>(); break; } default: { assert(0); } } if (entity_event) { ScoreData* score_data = Data<ScoreData>(entity_event->target); if (score_data) { score_data->OnEvent(event_id, event_payload); } } } void ScoreComponent::AddFromRawData(entity::EntityRef& entity, const void* raw_data) { auto component_data = static_cast<const ComponentDefInstance*>(raw_data); (void)component_data; assert(component_data->data_type() == ComponentDataUnion_ScoreDef); AddEntity(entity); } } // fpl_project } // fpl
Fix android build.
Fix android build. Tested: Android builds and runs now. Change-Id: I6e52c65c5aac9bc01c25bd7563ce49fd191eff19
C++
apache-2.0
google/zooshi,google/zooshi,google/zooshi,google/zooshi,google/zooshi
be7189de13981cd8b02f1fde49b54b651754df32
main.cpp
main.cpp
#include <iostream> #include <time.h> #include <string> #include <unistd.h> #include <fcntl.h> #include <fstream> int main(){ // get current time time_t epoch_time; struct tm *tm_p; epoch_time = time( NULL ); tm_p = localtime( &epoch_time ); // get date items int day = tm_p->tm_mday; int month = tm_p->tm_mon+1; int year = tm_p->tm_year-100; int hour = tm_p->tm_hour; int minute = tm_p->tm_min; int second = tm_p->tm_sec; // convert to std::string std::string s_day = std::to_string(day); std::string s_month = std::to_string(month); std::string s_year = std::to_string(year); std::string s_hour = std::to_string(hour); std::string s_minute = std::to_string(minute); std::string s_second = std::to_string(second); // add leading zeros if(day < 10){ s_day = "0" + s_day; } if(month < 10){ s_month = "0" + s_month; } if(year < 10){ s_year = "0" + s_year; } if(hour < 10){ s_hour = "0" + s_hour; } if(minute < 10){ s_minute = "0" + s_minute; } if(second < 10){ s_second = "0" + s_second; } // construct commands std::string datestring = ":SC" + s_month + "/" + s_day + "/" + s_year + "#"; std::string timestring = "#:SL" + s_hour + ":" + s_minute + ":" + s_second + "#"; // open port std::fstream port("/dev/ttyUSB0"); if(!port){ std::cout << "Port cannot be opened!" << std::endl; return 1; } std::cout << "Port opened..." << std::endl; std::cout << "Setting date..." << std::endl; // write date port << datestring; std::cout << "Setting time..." << std::endl; // write time port << timestring; port.close(); return 0; }
#include <iostream> #include <time.h> #include <string> #include <unistd.h> #include <fcntl.h> #include <fstream> int main(){ // get current time time_t epoch_time; struct tm *tm_p; epoch_time = time( NULL ); tm_p = localtime( &epoch_time ); // get date items int day = tm_p->tm_mday; int month = tm_p->tm_mon+1; int year = tm_p->tm_year-100; int hour = tm_p->tm_hour; int minute = tm_p->tm_min; int second = tm_p->tm_sec; // convert to std::string std::string s_day = std::to_string(day); std::string s_month = std::to_string(month); std::string s_year = std::to_string(year); std::string s_hour = std::to_string(hour); std::string s_minute = std::to_string(minute); std::string s_second = std::to_string(second); // add leading zeros if(day < 10){ s_day = "0" + s_day; } if(month < 10){ s_month = "0" + s_month; } if(year < 10){ s_year = "0" + s_year; } if(hour < 10){ s_hour = "0" + s_hour; } if(minute < 10){ s_minute = "0" + s_minute; } if(second < 10){ s_second = "0" + s_second; } // construct commands std::string datestring = ":SC" + s_month + "/" + s_day + "/" + s_year + "#"; std::string timestring = "#:SL" + s_hour + ":" + s_minute + ":" + s_second + "#"; // open port std::fstream port("/dev/ttyUSB0"); if(!port){ std::cout << "Port cannot be opened!" << std::endl; return 1; } std::cout << "Port opened..." << std::endl; std::cout << "Setting date..." << std::endl; // write date port << datestring; std::cout << "Setting time..." << std::endl; // write time port << timestring; port.close(); return 0; }
Revert "fixed tabs"
Revert "fixed tabs" This reverts commit d4533c500db3c6fdabc57023e700be38093669a5.
C++
mit
joushx/telescope-time
8bc22dc36269b946ce5dbbc4729e2d8370827fdf
main.cpp
main.cpp
#include <functional> #include <map> #include <stdio.h> #include <time.h> #include <vector> unsigned char s_array[8][64] = { {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}, {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}, {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}, {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}, {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}, {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}, {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}, {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}}; unsigned char p_box_data[32] = {16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25}; unsigned long p_box_array[256][4]; unsigned char extend_data[48] = {0}; unsigned long long extend_array[4][256]; namespace no_use { template <size_t N> class TYPE {}; template <> class TYPE<32> { typedef unsigned long type; }; template <> class TYPE<64> { typedef unsigned long long type; }; template <> class TYPE<48> { typedef unsigned long long type; }; template <size_t N> using len_type = typename TYPE<N>::type; template <size_t count, size_t block_size, typename in_type, typename out_type, size_t count_ = 0> struct tran { static inline out_type f(in_type in, out_type (*array)[count]) { return array[in & ((0x1 << block_size) - 1)][count_] | tran<count, block_size, in_type, out_type, count_ + 1>::f( in >> block_size, array); }; }; template <size_t count, size_t block_size, typename in_type, typename out_type> struct tran<count, block_size, in_type, out_type, count> { static inline out_type f(in_type in, out_type (*array)[count]) { return 0; }; }; } template <size_t block_size = 8, typename in_type = no_use::len_type<block_size << 3>, size_t count, typename out_type> static inline out_type map(in_type in, out_type (*array)[count]) { return no_use::tran<count, block_size, in_type, out_type>::f(in, array); } // init map by data template <size_t block_size = 8, size_t count, typename out_type> static inline void init(std::vector<unsigned char> source, out_type (*map)[count]) { std::multimap<unsigned char, unsigned> cache; out_type i_; for (unsigned i = 0; i < source.size(); i++) { cache.insert(std::make_pair(source[i], i - source[i])); } for (out_type i = 0; i < 256; i++) for (unsigned n = 0; n < count; n++) for (unsigned j = 0; j < block_size; j++) { i_ = i << n * block_size; auto pair = cache.equal_range(n * block_size + j); for (auto it = pair.first; it != pair.second; it++) map[i][n] |= it->second > 0 ? (i_ & 0x1ll << j) << it->second : (i_ & 0x1ll << j) >> -it->second; } } int main() { unsigned long n; unsigned long m; unsigned long array[256][4] = {{0}}; std::vector<unsigned char> qwe; init(qwe, array); clock_t a = clock(); for (unsigned long n = 0; n < 0xfffffff; n++) m += map(n, array); clock_t b = clock(); printf("%u", b - a, m); }
#include <algorithm> #include <functional> #include <map> #include <stdio.h> #include <time.h> #include <vector> unsigned char s_array[8][64] = { {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}, {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}, {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}, {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}, {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}, {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}, {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}, {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}}; unsigned long (*s_box_array)[8]; std::vector<unsigned char> p_box_data = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25}; unsigned long p_box_array[256][4]; std::vector<unsigned char> extend_data = { 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1}; unsigned long long extend_array[256][4]; unsigned char key_shift[16] = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1}; namespace no_use { template <size_t count, size_t block_size, typename in_type, typename out_type, size_t count_ = 0> struct tran { static inline out_type f(in_type in, out_type (*&array)[count]) { return array[in & ((0x1 << block_size) - 1)][count_] | tran<count, block_size, in_type, out_type, count_ + 1>::f( in >> block_size, array); }; }; template <size_t count, size_t block_size, typename in_type, typename out_type> struct tran<count, block_size, in_type, out_type, count> { static inline out_type f(in_type in, out_type (*&array)[count]) { return 0; }; }; } template <size_t block_size = 8, typename in_type, size_t count, typename out_type> static inline out_type map(in_type in, out_type (*array)[count]) { return no_use::tran<count, block_size, in_type, out_type>::f(in, array); } // init map by data template <size_t block_size = 8, size_t count, typename out_type> static inline void init(std::vector<unsigned char> source, out_type (*map)[count]) { std::multimap<unsigned char, unsigned> cache; out_type i_; for (unsigned i = 0; i < source.size(); i++) { cache.insert(std::make_pair(source[i], i - source[i])); } for (out_type i = 0; i < 256; i++) for (unsigned n = 0; n < count; n++) for (unsigned j = 0; j < block_size; j++) { i_ = i << n * block_size; auto pair = cache.equal_range(n * block_size + j); for (auto it = pair.first; it != pair.second; it++) map[i][n] |= it->second > 0 ? (i_ & 0x1ll << j) << it->second : (i_ & 0x1ll << j) >> -it->second; } } void init_s() { s_box_array = (unsigned long(*)[8])malloc(sizeof(unsigned long) * 64 * 8); for (unsigned i = 1; i < 8; i++) { for (unsigned j = 0; j < 64; j++) { s_box_array[j][i] = s_array[i][j] << 4 * i; } } } void init() { init_s(); std::for_each( p_box_data.begin(), p_box_data.end(), std::bind(std::minus<unsigned char>(), std::placeholders::_1, 1)); std::for_each( extend_data.begin(), extend_data.end(), std::bind(std::minus<unsigned char>(), std::placeholders::_1, 1)); init(p_box_data, p_box_array); init(extend_data, extend_array); } unsigned long f(unsigned long value, unsigned long long key) { return map(map<6>(map(value, extend_array) ^ key, s_box_array), p_box_array); } unsigned long long des(unsigned long long value, unsigned long long key) { unsigned long left = value; unsigned long right = value >> 32; unsigned long tmp; tmp = left; left = right; right = tmp ^ f(right, key); } void gen_sub_key(unsigned long long key, unsigned long long keys[16]) { unsigned long long left = key << 32; left |= left >> 32; unsigned long long right = key >> 32; right |= right << 32; for (unsigned i = 0; i < 16; i++) { } } int main() { unsigned long m; init(); clock_t a = clock(); for (unsigned long n = 0; n < 0xfffffff; n++) m += f(n, 0x1); clock_t b = clock(); printf("%u", b - a, m); }
add f()
add f()
C++
mit
cjwddtc/des
9a6dfa2500bc410aab9ce9b82bf30e38050aca4b
main.cpp
main.cpp
#include <algorithm> // for std::accumulate() #include <cstring> // for std::strcpy #include <iostream> // for std::cout #include <map> // for std::map #include <math.h> // for pow() #include <set> // for std::set #include <stdio.h> // for printf, scanf, fscanf #include <stdlib.h> #include <string.h> // for strlen(), strcpy() const char* infile_name = "data/test_data_primers_10000_25.txt"; const int max_number_of_primers = 10000; const int primer_len = 25; const int number_of_bases = 4; const int min_tail_len = 5; const int max_tail_len = 10; const int hash_base = 4; const int hash_table_size = pow(hash_base, max_tail_len); typedef struct node { int primer_index; node* next; } node_t; std::vector<char> bases = {'A', 'T', 'C', 'G'}; std::map<char, char> complement_map = {{'A', 'T'}, {'T', 'A'}, {'C', 'G'}, {'G', 'C'}}; std::map<char, char> next_base = {{'A', 'T'}, {'T', 'C'}, {'C', 'G'}, {'G', 'A'}}; std::map<char, int> base_map = {{'A', 0}, {'T', 1}, {'C', 2}, {'G', 3}}; int hash(char* str) { int val = 0; for (int i = 0; str[i] != '\0'; ++i) val += pow(hash_base, i) * base_map[str[i]]; if (val >= hash_table_size) printf("hashing error, val >= hash_table_size"); return val; } void ReverseComplement(char* dst, char* src) { int len = strlen(src); dst[len] = '\0'; for (int i = 0; src[i] != '\0'; ++i) dst[len - 1 - i] = complement_map[src[i]]; } std::set<std::set<int>> kSubsets(int n, int k) { /* returns all k-subsets of {0, 1, ..., n-1} */ if (k < 1) printf("ERROR: in kSubsets k must be >= 1"); if (k > n) printf("ERROR: in kSubsets k must be < n"); std::set<std::set<int>> ret_set; std::set<int> tmp_set; std::vector<int> include_indexes; for (int i = 0; i < k; ++i) include_indexes.push_back(i); while(1) { tmp_set.clear(); for (int i: include_indexes) tmp_set.insert(i); ret_set.insert(tmp_set); if (include_indexes[0] == (n-1)-(k-1)) break; // update include_indexes for (auto i = include_indexes.size() - 1; i >= 0; --i) { if (i == include_indexes.size() - 1 && include_indexes[i] < n-1) { ++include_indexes[i]; break; } else if (i < include_indexes.size() - 1 && include_indexes[i] < include_indexes[i+1] - 1) { ++include_indexes[i]; for (auto j = i + 1; j < include_indexes.size(); ++j) { include_indexes[j] = include_indexes[j-1]+1; } break; } } } return ret_set; } std::set<std::string> kMismatch(char* input_string, int max_mismatches) { std::set<std::string> ret_set; std::string stdstr; if (max_mismatches < 0) { printf("ERROR: in kMismatch, max_mismatches must be nonnegative."); exit(EXIT_FAILURE); } else if (max_mismatches == 0) { stdstr = input_string; ret_set.insert(stdstr); } else { int len = strlen(input_string); if (max_mismatches > len) max_mismatches = len; std::set<std::set<int>> s = kSubsets(len, max_mismatches); std::vector<int> include_indexes_sorted; char tmp[max_tail_len + 1]; for (std::set<int> include_indexes: s) { strcpy(tmp, input_string); include_indexes_sorted.clear(); for (int i: include_indexes) include_indexes_sorted.push_back(i); std::sort(include_indexes_sorted.begin(), include_indexes_sorted.end()); for (int i: include_indexes_sorted) tmp[i] = 'A'; for (int j = 0; j < pow(number_of_bases, max_mismatches); j++) { stdstr = tmp; ret_set.insert(stdstr); for (auto i = 0u; i < include_indexes_sorted.size(); ++i) { if (tmp[include_indexes_sorted[i]] != 'G') { tmp[include_indexes_sorted[i]] = next_base[tmp[include_indexes_sorted[i]]]; for (auto u = 0u; u < i; ++u) tmp[include_indexes_sorted[u]] = 'A'; break; } } } } } return ret_set; } void PrintHashTableStatistics(node** hash_table, int hash_table_size) { int count, max_count = 0, total_count = 0; node_t* tmp_node_ptr; for (auto i = 0; i < hash_table_size; ++i) { count = 0; tmp_node_ptr = hash_table[i]; while (tmp_node_ptr != NULL) { ++count; tmp_node_ptr = tmp_node_ptr->next; } if (count > max_count) max_count = count; total_count += count; } //printf("There are %i total entries in the hash table\n", total_count); //printf("The most entries in one index is %i\n", max_count); printf(" %-10i|", total_count); } void LoadHashTable(node_t** hash_table, char** primers, int number_of_primers, int tail_len, int max_mismatches) { char tail_rc[max_tail_len + 1]; // reverse complement of the tail int hash_val; std::set<std::string> similar_sequences; for (int i = 0; i < number_of_primers; ++i) { ReverseComplement(tail_rc, primers[i] + strlen(primers[i]) - tail_len); similar_sequences = kMismatch(tail_rc, max_mismatches); for (std::string sequence: similar_sequences) { char * tmp = new char [sequence.length()+1]; std::strcpy (tmp, sequence.c_str()); hash_val = hash(tmp); node_t* tmp_node_ptr = (node_t*) malloc(sizeof(node_t)); tmp_node_ptr->primer_index = i; if (hash_table[hash_val] == NULL) { tmp_node_ptr->next = NULL; } else { tmp_node_ptr->next = hash_table[hash_val]; } hash_table[hash_val] = tmp_node_ptr; delete tmp; } } } void ClearHashTable(node** hash_table, int hash_table_size) { node_t* node_ptr_1; node_t* node_ptr_2; for (auto i = 0; i < hash_table_size; ++i) { node_ptr_1 = hash_table[i]; while (node_ptr_1 != NULL) { node_ptr_2 = node_ptr_1; node_ptr_1 = node_ptr_1->next; free(node_ptr_2); node_ptr_2 = NULL; } hash_table[i] = NULL; } } void PrintHitStatistics(std::vector<std::vector<int>> hit, int number_of_primers) { int hits, max_hits = 0, max_hits_index; std::vector<int> all_hits; for (int i = 0; i < number_of_primers; ++i) { hits = 0; for (int j = 0; j < number_of_primers; ++j) { if (hit[i][j]) ++hits; } if (hits > max_hits) { max_hits = hits; max_hits_index = i; } all_hits.push_back(hits); } double avg_hits = std::accumulate(all_hits.begin(), all_hits.end(), 0ULL) / (double)all_hits.size(); //printf("the max_hits for any primer = %i, for primer %i\n", max_hits, max_hits_index); //printf("the avg_hits for each primer = %f\n", avg_hits); //printf("the avg percentage hits for each primer = %f%%\n", 100*avg_hits/number_of_primers); printf(" %-12f|", avg_hits/number_of_primers); } std::vector<std::vector<int>> SlideWindow(char** primers, int number_of_primers, node_t** hash_table, int tail_len) { // initialise hit vector std::vector<std::vector<int>> hit; std::vector<int> zero_vect(number_of_primers, 0); for (int i = 0; i < number_of_primers; ++i) hit.push_back(zero_vect); char tmp_primer[primer_len + 1]; node_t* tmp_node_ptr; for (int i = 0; i < number_of_primers; ++i) { strcpy(tmp_primer, primers[i]); char* window; window = tmp_primer + strlen(tmp_primer) - tail_len; //printf("%s\n", window); for (; window != tmp_primer; --window) { if (window == tmp_primer) break; //printf("%s\n", window); tmp_node_ptr = hash_table[hash(window)]; while(tmp_node_ptr != NULL) { hit[i][tmp_node_ptr->primer_index] = hit[tmp_node_ptr->primer_index][i] = 1; tmp_node_ptr = tmp_node_ptr->next; } tmp_primer[strlen(tmp_primer) - 1] = '\0'; } } return hit; } double P_substring(int substring_len, int target_len) { return (target_len - substring_len + 1) * pow(1.0/number_of_bases, substring_len); } int main(int argc, char* argv[]) { // open file FILE* infile = fopen(infile_name, "r"); // check if file exists if (infile == NULL) { printf("can't open infile\n"); exit(EXIT_FAILURE); } // read input file int number_of_primers; char **primers = (char**) malloc(max_number_of_primers * sizeof(char*)); fscanf(infile, "%d\n", &number_of_primers); char *tmp; for (int i = 0; i < number_of_primers; ++i) { tmp = (char*) malloc(1 + primer_len * sizeof(char)); fgets(tmp, primer_len+2, infile); if (tmp[strlen(tmp) - 1] == '\n') tmp[strlen(tmp) - 1] = '\0'; primers[i] = tmp; } printf("primer_len = %i\n", primer_len); printf("number_of_primers = %i\n", number_of_primers); // close infile fclose(infile); // create hash table node_t** hash_table = (node_t**) malloc(hash_table_size * sizeof(node_t*)); for (auto i = 0; i < hash_table_size; ++i) hash_table[i] = NULL; // test probabilies for different tail_len and max_mismatches printf("+------------+--------+-----------+-------------+-------------+\n"); printf("| max | tail | total | actual | expected |\n"); printf("| mismatches | length | entries | hit | hit |\n"); printf("| | | in | probability | probability |\n"); printf("| | | hashtable | | |\n"); printf("+------------+--------+-----------+-------------+-------------+\n"); std::vector<std::vector<int>> hit; for (auto tail_len = min_tail_len; tail_len <= max_tail_len; ++tail_len) { for (auto max_mismatches = 0; max_mismatches <= 3; ++max_mismatches) { printf("| %-11i| %-7i|", max_mismatches, tail_len); LoadHashTable(hash_table, primers, number_of_primers, tail_len, max_mismatches); PrintHashTableStatistics(hash_table, hash_table_size); hit.clear(); hit = SlideWindow(primers, number_of_primers, hash_table, tail_len); PrintHitStatistics(hit, number_of_primers); ClearHashTable(hash_table, hash_table_size); if (max_mismatches == 0) printf(" %-12f|", P_substring(tail_len, primer_len)); printf("\n"); printf("+------------+--------+-----------+-------------+-------------+\n"); } } // free hash table free(hash_table); // free memory from input for (int i = 0; i < number_of_primers; ++i) free(primers[i]); free(primers); return 0; }
#include <algorithm> // for std::accumulate() #include <cstring> // for std::strcpy #include <iostream> // for std::cout #include <map> // for std::map #include <math.h> // for pow() #include <set> // for std::set #include <stdio.h> // for printf, scanf, fscanf #include <stdlib.h> #include <string.h> // for strlen(), strcpy() const char* infile_name = "data/test_data_primers_4000_25.txt"; const int max_number_of_primers = 4000; const int primer_len = 25; const int number_of_bases = 4; const int min_tail_len = 5; const int max_tail_len = 7; const int hash_base = 4; const int hash_table_size = pow(hash_base, max_tail_len); typedef struct node { int primer_index; node* next; } node_t; std::vector<char> bases = {'A', 'T', 'C', 'G'}; std::map<char, char> complement_map = {{'A', 'T'}, {'T', 'A'}, {'C', 'G'}, {'G', 'C'}}; std::map<char, char> next_base = {{'A', 'T'}, {'T', 'C'}, {'C', 'G'}, {'G', 'A'}}; std::map<char, int> base_map = {{'A', 0}, {'T', 1}, {'C', 2}, {'G', 3}}; int hash(std::string str) { int ret_val = 0; for (auto i = 0u; i < str.size(); ++i) ret_val += pow(hash_base, i) * base_map[str[i]]; if (ret_val >= hash_table_size) printf("hashing error, ret_val >= hash_table_size"); return ret_val; } void ReverseComplement(char* dst, char* src) { int len = strlen(src); dst[len] = '\0'; for (int i = 0; src[i] != '\0'; ++i) dst[len - 1 - i] = complement_map[src[i]]; } std::set<std::set<int>> kSubsets(int n, int k) { /* returns all k-subsets of {0, 1, ..., n-1} */ if (k < 1) printf("ERROR: in kSubsets k must be >= 1"); if (k > n) printf("ERROR: in kSubsets k must be < n"); std::set<std::set<int>> ret_set; std::set<int> tmp_set; std::vector<int> include_indexes; for (int i = 0; i < k; ++i) include_indexes.push_back(i); while(1) { tmp_set.clear(); for (int i: include_indexes) tmp_set.insert(i); ret_set.insert(tmp_set); if (include_indexes[0] == (n-1)-(k-1)) break; // update include_indexes for (auto i = include_indexes.size() - 1; i >= 0; --i) { if (i == include_indexes.size() - 1 && include_indexes[i] < n-1) { ++include_indexes[i]; break; } else if (i < include_indexes.size() - 1 && include_indexes[i] < include_indexes[i+1] - 1) { ++include_indexes[i]; for (auto j = i + 1; j < include_indexes.size(); ++j) { include_indexes[j] = include_indexes[j-1]+1; } break; } } } return ret_set; } std::set<std::string> kMismatch(char* input_string, int max_mismatches) { std::set<std::string> ret_set; std::string stdstr; if (max_mismatches < 0) { printf("ERROR: in kMismatch, max_mismatches must be nonnegative."); exit(EXIT_FAILURE); } else if (max_mismatches == 0) { stdstr = input_string; ret_set.insert(stdstr); } else { int len = strlen(input_string); if (max_mismatches > len) max_mismatches = len; std::set<std::set<int>> s = kSubsets(len, max_mismatches); std::vector<int> include_indexes_sorted; char tmp[max_tail_len + 1]; for (std::set<int> include_indexes: s) { strcpy(tmp, input_string); include_indexes_sorted.clear(); for (int i: include_indexes) include_indexes_sorted.push_back(i); std::sort(include_indexes_sorted.begin(), include_indexes_sorted.end()); for (int i: include_indexes_sorted) tmp[i] = 'A'; for (int j = 0; j < pow(number_of_bases, max_mismatches); j++) { stdstr = tmp; ret_set.insert(stdstr); for (auto i = 0u; i < include_indexes_sorted.size(); ++i) { if (tmp[include_indexes_sorted[i]] != 'G') { tmp[include_indexes_sorted[i]] = next_base[tmp[include_indexes_sorted[i]]]; for (auto u = 0u; u < i; ++u) tmp[include_indexes_sorted[u]] = 'A'; break; } } } } } return ret_set; } void PrintHashTableStatistics(node** hash_table, int hash_table_size) { int count, max_count = 0, total_count = 0; node_t* tmp_node_ptr; for (auto i = 0; i < hash_table_size; ++i) { count = 0; tmp_node_ptr = hash_table[i]; while (tmp_node_ptr != NULL) { ++count; tmp_node_ptr = tmp_node_ptr->next; } if (count > max_count) max_count = count; total_count += count; } //printf("There are %i total entries in the hash table\n", total_count); //printf("The most entries in one index is %i\n", max_count); printf(" %-10i|", total_count); } void LoadHashTable(node_t** hash_table, char** primers, int number_of_primers, int tail_len, int max_mismatches) { char tail_rc[max_tail_len + 1]; // reverse complement of the tail int hash_val; std::set<std::string> similar_sequences; for (int i = 0; i < number_of_primers; ++i) { ReverseComplement(tail_rc, primers[i] + strlen(primers[i]) - tail_len); similar_sequences = kMismatch(tail_rc, max_mismatches); for (std::string sequence: similar_sequences) { hash_val = hash(sequence); node_t* tmp_node_ptr = (node_t*) malloc(sizeof(node_t)); tmp_node_ptr->primer_index = i; if (hash_table[hash_val] == NULL) { tmp_node_ptr->next = NULL; } else { tmp_node_ptr->next = hash_table[hash_val]; } hash_table[hash_val] = tmp_node_ptr; } } } void ClearHashTable(node** hash_table, int hash_table_size) { node_t* node_ptr_1; node_t* node_ptr_2; for (auto i = 0; i < hash_table_size; ++i) { node_ptr_1 = hash_table[i]; while (node_ptr_1 != NULL) { node_ptr_2 = node_ptr_1; node_ptr_1 = node_ptr_1->next; free(node_ptr_2); node_ptr_2 = NULL; } hash_table[i] = NULL; } } void PrintHitStatistics(std::vector<std::vector<int>> hit, int number_of_primers) { int hits, max_hits = 0, max_hits_index; std::vector<int> all_hits; for (int i = 0; i < number_of_primers; ++i) { hits = 0; for (int j = 0; j < number_of_primers; ++j) { if (hit[i][j]) ++hits; } if (hits > max_hits) { max_hits = hits; max_hits_index = i; } all_hits.push_back(hits); } double avg_hits = std::accumulate(all_hits.begin(), all_hits.end(), 0ull) / (double)all_hits.size(); //printf("the max_hits for any primer = %i, for primer %i\n", max_hits, max_hits_index); //printf("the avg_hits for each primer = %f\n", avg_hits); //printf("the avg percentage hits for each primer = %f%%\n", 100*avg_hits/number_of_primers); printf(" %-12f|", avg_hits/number_of_primers); } std::vector<std::vector<int>> SlideWindow(char** primers, int number_of_primers, node_t** hash_table, int tail_len) { // initialise hit vector std::vector<std::vector<int>> hit; std::vector<int> zero_vect(number_of_primers, 0); for (int i = 0; i < number_of_primers; ++i) hit.push_back(zero_vect); char tmp_primer[primer_len + 1]; node_t* tmp_node_ptr; for (int i = 0; i < number_of_primers; ++i) { strcpy(tmp_primer, primers[i]); char* window; window = tmp_primer + strlen(tmp_primer) - tail_len; //printf("%s\n", window); for (; window != tmp_primer; --window) { if (window == tmp_primer) break; //printf("%s\n", window); tmp_node_ptr = hash_table[hash(window)]; while(tmp_node_ptr != NULL) { hit[i][tmp_node_ptr->primer_index] = hit[tmp_node_ptr->primer_index][i] = 1; tmp_node_ptr = tmp_node_ptr->next; } tmp_primer[strlen(tmp_primer) - 1] = '\0'; } } return hit; } double P_substring(int substring_len, int target_len) { return (target_len - substring_len + 1) * pow(1.0/number_of_bases, substring_len); } int main(int argc, char* argv[]) { // open file FILE* infile = fopen(infile_name, "r"); // check if file exists if (infile == NULL) { printf("can't open infile\n"); exit(EXIT_FAILURE); } // read input file int number_of_primers; char **primers = (char**) malloc(max_number_of_primers * sizeof(char*)); fscanf(infile, "%d\n", &number_of_primers); char *tmp; for (int i = 0; i < number_of_primers; ++i) { tmp = (char*) malloc(1 + primer_len * sizeof(char)); fgets(tmp, primer_len+2, infile); if (tmp[strlen(tmp) - 1] == '\n') tmp[strlen(tmp) - 1] = '\0'; primers[i] = tmp; } printf("primer_len = %i\n", primer_len); printf("number_of_primers = %i\n", number_of_primers); // close infile fclose(infile); // create hash table node_t** hash_table = (node_t**) malloc(hash_table_size * sizeof(node_t*)); for (auto i = 0; i < hash_table_size; ++i) hash_table[i] = NULL; // test probabilies for different tail_len and max_mismatches printf("+------------+--------+-----------+-------------+-------------+\n"); printf("| max | tail | total | actual | expected |\n"); printf("| mismatches | length | entries | hit | hit |\n"); printf("| | | in | probability | probability |\n"); printf("| | | hashtable | | |\n"); printf("+------------+--------+-----------+-------------+-------------+\n"); std::vector<std::vector<int>> hit; for (auto tail_len = min_tail_len; tail_len <= max_tail_len; ++tail_len) { for (auto max_mismatches = 0; max_mismatches <= 3; ++max_mismatches) { printf("| %-11i| %-7i|", max_mismatches, tail_len); LoadHashTable(hash_table, primers, number_of_primers, tail_len, max_mismatches); PrintHashTableStatistics(hash_table, hash_table_size); hit.clear(); hit = SlideWindow(primers, number_of_primers, hash_table, tail_len); PrintHitStatistics(hit, number_of_primers); ClearHashTable(hash_table, hash_table_size); if (max_mismatches == 0) printf(" %-12f|", P_substring(tail_len, primer_len)); printf("\n"); printf("+------------+--------+-----------+-------------+-------------+\n"); } } // free hash table free(hash_table); // free memory from input for (int i = 0; i < number_of_primers; ++i) free(primers[i]); free(primers); return 0; }
change hash() to take a std::string instead of a C-style string
change hash() to take a std::string instead of a C-style string
C++
mit
jamesc0/primer-dimers,jamesc0/primer-dimers
d682968d08172647644333be379880737f943865
main.cpp
main.cpp
/** * This is free and unencumbered software released into the public domain. **/ #include "Sha256.h" #include "JsonRpc.h" #include "Settings.h" #include "Util.h" #include "Transaction.h" #include "Radix.h" #include "Block.h" #include "Miner.h" #include <cassert> #include <algorithm> #include <cstdio> #include <iostream> #include <string> #include <ctype.h> #include <climits> #include <chrono> #include <thread> #include <atomic> #include <sstream> using namespace std; std::unique_ptr<Block> createBlockTemplate() { JsonRpc rpc( Settings::RpcHost(), Settings::RpcPort(), Settings::RpcUser(), Settings::RpcPassword() ); // Get block template Json::Value params; params[0u]["capabilities"] = Json::arrayValue; auto blockTemplate = rpc.call( "getblocktemplate", params ); if( blockTemplate.isMember("coinbasetxn") ) throw std::runtime_error( "Coinbase txn already exists" ); // Get coinbase destination params.clear(); params[0u] = "Mining Coinbase"; auto coinbaseAddress = rpc.call( "getaccountaddress", params ).asString(); // Convert address to pubkey hash auto coinbasePubKeyHash = Radix::base58DecodeCheck( coinbaseAddress ); // Remove leading version byte coinbasePubKeyHash.erase( coinbasePubKeyHash.begin() ); auto coinbaseValue = blockTemplate["coinbasevalue"].asInt64(); // Create coinbase transaction auto coinbaseTxn = Transaction::createCoinbase( blockTemplate["height"].asInt(), coinbaseValue, coinbasePubKeyHash ); // Create block std::unique_ptr<Block> block( new Block ); block->header.version = blockTemplate["version"].asInt(); block->header.time = blockTemplate["curtime"].asInt(); block->header.bits = stoi( blockTemplate["bits"].asString(), nullptr, 16 ); auto prevBlockHash = hexStringToBinary( blockTemplate["previousblockhash"].asString() ); std::reverse( prevBlockHash.begin(), prevBlockHash.end() ); block->setPrevBlockHash( prevBlockHash ); // Add all the transactions block->appendTransaction( std::move(coinbaseTxn) ); auto txnArray = blockTemplate["transactions"]; assert( txnArray.isArray() ); for( unsigned i = 0; i < txnArray.size(); ++i ) { auto txnData = txnArray[i]["data"].asString(); auto txn = Transaction::deserialize( txnData ); block->appendTransaction( std::move(txn) ); } block->updateHeader(); return block; } int main( int argc, char** argv ) { try { Settings::init( argc, argv ); auto miner = Miner::createInstance( Settings::minerType() ); if( miner == nullptr ) { throw runtime_error( "Miner implementation doesn't exist" ); } auto block = createBlockTemplate(); if( miner->mine(*block) == Miner::SolutionFound ) { std::cout << "Solution found: " << std::endl << "\tHeader: " << block->headerData() << std::endl << "\tHash: " << Sha256::doubleHash( &block->header, sizeof(block->header) ) << std::endl; } else { std::cout << "No solution found" << std::endl; } return EXIT_SUCCESS; } catch( std::exception& e ) { cerr << "ERROR: " << e.what() << endl; return EXIT_FAILURE; } }
/** * This is free and unencumbered software released into the public domain. **/ #include "Sha256.h" #include "JsonRpc.h" #include "Settings.h" #include "Util.h" #include "Transaction.h" #include "Radix.h" #include "Block.h" #include "Miner.h" #include <cassert> #include <algorithm> #include <cstdio> #include <iostream> #include <string> #include <ctype.h> #include <climits> #include <chrono> #include <thread> #include <atomic> #include <sstream> using namespace std; std::unique_ptr<Block> createBlockTemplate( JsonRpc& rpc ) { // Get block template Json::Value params; params[0u]["capabilities"] = Json::arrayValue; auto blockTemplate = rpc.call( "getblocktemplate", params ); if( blockTemplate.isMember("coinbasetxn") ) throw std::runtime_error( "Coinbase txn already exists" ); // Get coinbase destination params.clear(); params[0u] = "Mining Coinbase"; auto coinbaseAddress = rpc.call( "getaccountaddress", params ).asString(); // Convert address to pubkey hash auto coinbasePubKeyHash = Radix::base58DecodeCheck( coinbaseAddress ); // Remove leading version byte coinbasePubKeyHash.erase( coinbasePubKeyHash.begin() ); auto coinbaseValue = blockTemplate["coinbasevalue"].asInt64(); // Create coinbase transaction auto coinbaseTxn = Transaction::createCoinbase( blockTemplate["height"].asInt(), coinbaseValue, coinbasePubKeyHash ); // Create block std::unique_ptr<Block> block( new Block ); block->header.version = blockTemplate["version"].asInt(); block->header.time = blockTemplate["curtime"].asInt(); block->header.bits = stoi( blockTemplate["bits"].asString(), nullptr, 16 ); auto prevBlockHash = hexStringToBinary( blockTemplate["previousblockhash"].asString() ); std::reverse( prevBlockHash.begin(), prevBlockHash.end() ); block->setPrevBlockHash( prevBlockHash ); // Add all the transactions block->appendTransaction( std::move(coinbaseTxn) ); auto txnArray = blockTemplate["transactions"]; assert( txnArray.isArray() ); for( unsigned i = 0; i < txnArray.size(); ++i ) { auto txnData = txnArray[i]["data"].asString(); auto txn = Transaction::deserialize( txnData ); block->appendTransaction( std::move(txn) ); } block->updateHeader(); return block; } Json::Value submitBlock( JsonRpc& rpc, const Block& block ) { std::ostringstream stream; block.serialize( stream ); Json::Value params; params[0] = stream.str(); return rpc.call( "submitblock", params ); } int main( int argc, char** argv ) { try { Settings::init( argc, argv ); JsonRpc rpc( Settings::RpcHost(), Settings::RpcPort(), Settings::RpcUser(), Settings::RpcPassword() ); auto miner = Miner::createInstance( Settings::minerType() ); if( miner == nullptr ) { throw runtime_error( "Miner implementation doesn't exist" ); } auto block = createBlockTemplate( rpc ); if( miner->mine(*block) == Miner::SolutionFound ) { std::cout << "Solution found: " << std::endl << "\tHeader: " << block->headerData() << std::endl << "\tHash: " << Sha256::doubleHash( &block->header, sizeof(block->header) ) << std::endl; auto result = submitBlock( rpc, *block ); if( !result.isNull() ) { std::cout << "Solution rejected! (" << result.asString() << ")" << std::endl; } else { std::cout << "Solution accepted!" << std::endl; } } else { std::cout << "No solution found" << std::endl; } return EXIT_SUCCESS; } catch( std::exception& e ) { cerr << "ERROR: " << e.what() << endl; return EXIT_FAILURE; } }
Add submitblock function
Add submitblock function - Works on regtest!
C++
unlicense
jrmrjnck/jrmrmine
3159819ed71a2e814175a593147f7637a423ba56
lib/Rewrite/InclusionRewriter.cpp
lib/Rewrite/InclusionRewriter.cpp
//===--- InclusionRewriter.cpp - Rewrite includes into their expansions ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This code rewrites include invocations into their expansions. This gives you // a file with all included files merged into it. // //===----------------------------------------------------------------------===// #include "clang/Rewrite/Rewriters.h" #include "clang/Lex/Preprocessor.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/PreprocessorOutputOptions.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace llvm; namespace { class InclusionRewriter : public PPCallbacks { /// Information about which #includes were actually performed, /// created by preprocessor callbacks. struct FileChange { SourceLocation From; FileID Id; SrcMgr::CharacteristicKind FileType; FileChange(SourceLocation From) : From(From) { } }; Preprocessor &PP; ///< Used to find inclusion directives. SourceManager &SM; ///< Used to read and manage source files. raw_ostream &OS; ///< The destination stream for rewritten contents. bool ShowLineMarkers; ///< Show #line markers. bool UseLineDirective; ///< Use of line directives or line markers. typedef std::map<unsigned, FileChange> FileChangeMap; FileChangeMap FileChanges; /// Tracks which files were included where. /// Used transitively for building up the FileChanges mapping over the /// various \c PPCallbacks callbacks. FileChangeMap::iterator LastInsertedFileChange; public: InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers); bool Process(FileID FileId, SrcMgr::CharacteristicKind FileType); private: virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID); virtual void FileSkipped(const FileEntry &ParentFile, const Token &FilenameTok, SrcMgr::CharacteristicKind FileType); virtual void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName, bool IsAngled, const FileEntry *File, SourceLocation EndLoc, StringRef SearchPath, StringRef RelativePath); void WriteLineInfo(const char *Filename, int Line, SrcMgr::CharacteristicKind FileType, StringRef EOL, StringRef Extra = StringRef()); void OutputContentUpTo(const MemoryBuffer &FromFile, unsigned &WriteFrom, unsigned WriteTo, StringRef EOL, int &lines, bool EnsureNewline = false); void CommentOutDirective(Lexer &DirectivesLex, const Token &StartToken, const MemoryBuffer &FromFile, StringRef EOL, unsigned &NextToWrite, int &Lines); const FileChange *FindFileChangeLocation(SourceLocation Loc) const; StringRef NextIdentifierName(Lexer &RawLex, Token &RawToken); }; } // end anonymous namespace /// Initializes an InclusionRewriter with a \p PP source and \p OS destination. InclusionRewriter::InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers) : PP(PP), SM(PP.getSourceManager()), OS(OS), ShowLineMarkers(ShowLineMarkers), LastInsertedFileChange(FileChanges.end()) { // If we're in microsoft mode, use normal #line instead of line markers. UseLineDirective = PP.getLangOpts().MicrosoftExt; } /// Write appropriate line information as either #line directives or GNU line /// markers depending on what mode we're in, including the \p Filename and /// \p Line we are located at, using the specified \p EOL line separator, and /// any \p Extra context specifiers in GNU line directives. void InclusionRewriter::WriteLineInfo(const char *Filename, int Line, SrcMgr::CharacteristicKind FileType, StringRef EOL, StringRef Extra) { if (!ShowLineMarkers) return; if (UseLineDirective) { OS << "#line" << ' ' << Line << ' ' << '"' << Filename << '"'; } else { // Use GNU linemarkers as described here: // http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html OS << '#' << ' ' << Line << ' ' << '"' << Filename << '"'; if (!Extra.empty()) OS << Extra; if (FileType == SrcMgr::C_System) // "`3' This indicates that the following text comes from a system header // file, so certain warnings should be suppressed." OS << " 3"; else if (FileType == SrcMgr::C_ExternCSystem) // as above for `3', plus "`4' This indicates that the following text // should be treated as being wrapped in an implicit extern "C" block." OS << " 3 4"; } OS << EOL; } /// FileChanged - Whenever the preprocessor enters or exits a #include file /// it invokes this handler. void InclusionRewriter::FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind NewFileType, FileID) { if (Reason != EnterFile) return; if (LastInsertedFileChange == FileChanges.end()) // we didn't reach this file (eg: the main file) via an inclusion directive return; LastInsertedFileChange->second.Id = FullSourceLoc(Loc, SM).getFileID(); LastInsertedFileChange->second.FileType = NewFileType; LastInsertedFileChange = FileChanges.end(); } /// Called whenever an inclusion is skipped due to canonical header protection /// macros. void InclusionRewriter::FileSkipped(const FileEntry &/*ParentFile*/, const Token &/*FilenameTok*/, SrcMgr::CharacteristicKind /*FileType*/) { assert(LastInsertedFileChange != FileChanges.end() && "A file, that wasn't " "found via an inclusion directive, was skipped"); FileChanges.erase(LastInsertedFileChange); LastInsertedFileChange = FileChanges.end(); } /// This should be called whenever the preprocessor encounters include /// directives. It does not say whether the file has been included, but it /// provides more information about the directive (hash location instead /// of location inside the included file). It is assumed that the matching /// FileChanged() or FileSkipped() is called after this. void InclusionRewriter::InclusionDirective(SourceLocation HashLoc, const Token &/*IncludeTok*/, StringRef /*FileName*/, bool /*IsAngled*/, const FileEntry * /*File*/, SourceLocation /*EndLoc*/, StringRef /*SearchPath*/, StringRef /*RelativePath*/) { assert(LastInsertedFileChange == FileChanges.end() && "Another inclusion " "directive was found before the previous one was processed"); std::pair<FileChangeMap::iterator, bool> p = FileChanges.insert( std::make_pair(HashLoc.getRawEncoding(), FileChange(HashLoc))); assert(p.second && "Unexpected revisitation of the same include directive"); LastInsertedFileChange = p.first; } /// Simple lookup for a SourceLocation (specifically one denoting the hash in /// an inclusion directive) in the map of inclusion information, FileChanges. const InclusionRewriter::FileChange * InclusionRewriter::FindFileChangeLocation(SourceLocation Loc) const { FileChangeMap::const_iterator I = FileChanges.find(Loc.getRawEncoding()); if (I != FileChanges.end()) return &I->second; return NULL; } /// Count the raw \\n characters in the \p Len characters from \p Pos. inline unsigned CountNewLines(const char *Pos, int Len) { const char *End = Pos + Len; unsigned Lines = 0; --Pos; while ((Pos = static_cast<const char*>(memchr(Pos + 1, '\n', End - Pos - 1)))) ++Lines; return Lines; } /// Detect the likely line ending style of \p FromFile by examining the first /// newline found within it. static StringRef DetectEOL(const MemoryBuffer &FromFile) { // detect what line endings the file uses, so that added content does not mix // the style const char *Pos = strchr(FromFile.getBufferStart(), '\n'); if (Pos == NULL) return "\n"; if (Pos + 1 < FromFile.getBufferEnd() && Pos[1] == '\r') return "\n\r"; if (Pos - 1 >= FromFile.getBufferStart() && Pos[-1] == '\r') return "\r\n"; return "\n"; } /// Writes out bytes from \p FromFile, starting at \p NextToWrite and ending at /// \p WriteTo - 1. void InclusionRewriter::OutputContentUpTo(const MemoryBuffer &FromFile, unsigned &WriteFrom, unsigned WriteTo, StringRef EOL, int &Line, bool EnsureNewline) { if (WriteTo <= WriteFrom) return; OS.write(FromFile.getBufferStart() + WriteFrom, WriteTo - WriteFrom); // count lines manually, it's faster than getPresumedLoc() Line += CountNewLines(FromFile.getBufferStart() + WriteFrom, WriteTo - WriteFrom); if (EnsureNewline) { char LastChar = FromFile.getBufferStart()[WriteTo - 1]; if (LastChar != '\n' && LastChar != '\r') OS << EOL; } WriteFrom = WriteTo; } /// Print characters from \p FromFile starting at \p NextToWrite up until the /// inclusion directive at \p StartToken, then print out the inclusion /// inclusion directive disabled by a #if directive, updating \p NextToWrite /// and \p Line to track the number of source lines visited and the progress /// through the \p FromFile buffer. void InclusionRewriter::CommentOutDirective(Lexer &DirectiveLex, const Token &StartToken, const MemoryBuffer &FromFile, StringRef EOL, unsigned &NextToWrite, int &Line) { OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(StartToken.getLocation()), EOL, Line); Token DirectiveToken; do { DirectiveLex.LexFromRawLexer(DirectiveToken); } while (!DirectiveToken.is(tok::eod) && DirectiveToken.isNot(tok::eof)); OS << "#if 0 /* expanded by -rewrite-includes */" << EOL; OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(DirectiveToken.getLocation()) + DirectiveToken.getLength(), EOL, Line); OS << "#endif /* expanded by -rewrite-includes */" << EOL; } /// Find the next identifier in the pragma directive specified by \p RawToken. StringRef InclusionRewriter::NextIdentifierName(Lexer &RawLex, Token &RawToken) { RawLex.LexFromRawLexer(RawToken); if (RawToken.is(tok::raw_identifier)) PP.LookUpIdentifierInfo(RawToken); if (RawToken.is(tok::identifier)) return RawToken.getIdentifierInfo()->getName(); return StringRef(); } /// Use a raw lexer to analyze \p FileId, inccrementally copying parts of it /// and including content of included files recursively. bool InclusionRewriter::Process(FileID FileId, SrcMgr::CharacteristicKind FileType) { bool Invalid; const MemoryBuffer &FromFile = *SM.getBuffer(FileId, &Invalid); assert(!Invalid && "Invalid FileID while trying to rewrite includes"); const char *FileName = FromFile.getBufferIdentifier(); Lexer RawLex(FileId, &FromFile, PP.getSourceManager(), PP.getLangOpts()); RawLex.SetCommentRetentionState(false); StringRef EOL = DetectEOL(FromFile); // Per the GNU docs: "1" indicates the start of a new file. WriteLineInfo(FileName, 1, FileType, EOL, " 1"); if (SM.getFileIDSize(FileId) == 0) return true; // The next byte to be copied from the source file unsigned NextToWrite = 0; int Line = 1; // The current input file line number. Token RawToken; RawLex.LexFromRawLexer(RawToken); // TODO: Consider adding a switch that strips possibly unimportant content, // such as comments, to reduce the size of repro files. while (RawToken.isNot(tok::eof)) { if (RawToken.is(tok::hash) && RawToken.isAtStartOfLine()) { RawLex.setParsingPreprocessorDirective(true); Token HashToken = RawToken; RawLex.LexFromRawLexer(RawToken); if (RawToken.is(tok::raw_identifier)) PP.LookUpIdentifierInfo(RawToken); if (RawToken.is(tok::identifier)) { switch (RawToken.getIdentifierInfo()->getPPKeywordID()) { case tok::pp_include: case tok::pp_include_next: case tok::pp_import: { CommentOutDirective(RawLex, HashToken, FromFile, EOL, NextToWrite, Line); if (const FileChange *Change = FindFileChangeLocation( HashToken.getLocation())) { // now include and recursively process the file if (Process(Change->Id, Change->FileType)) // and set lineinfo back to this file, if the nested one was // actually included // `2' indicates returning to a file (after having included // another file. WriteLineInfo(FileName, Line, FileType, EOL, " 2"); } else // fix up lineinfo (since commented out directive changed line // numbers) for inclusions that were skipped due to header guards WriteLineInfo(FileName, Line, FileType, EOL); break; } case tok::pp_pragma: { StringRef Identifier = NextIdentifierName(RawLex, RawToken); if (Identifier == "clang" || Identifier == "GCC") { if (NextIdentifierName(RawLex, RawToken) == "system_header") { // keep the directive in, commented out CommentOutDirective(RawLex, HashToken, FromFile, EOL, NextToWrite, Line); // update our own type FileType = SM.getFileCharacteristic(RawToken.getLocation()); WriteLineInfo(FileName, Line, FileType, EOL); } } else if (Identifier == "once") { // keep the directive in, commented out CommentOutDirective(RawLex, HashToken, FromFile, EOL, NextToWrite, Line); WriteLineInfo(FileName, Line, FileType, EOL); } break; } default: break; } } RawLex.setParsingPreprocessorDirective(false); } RawLex.LexFromRawLexer(RawToken); } OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(SM.getLocForEndOfFile(FileId)) + 1, EOL, Line, /*EnsureNewline*/true); return true; } /// InclusionRewriterInInput - Implement -rewrite-includes mode. void clang::RewriteIncludesInInput(Preprocessor &PP, raw_ostream *OS, const PreprocessorOutputOptions &Opts) { SourceManager &SM = PP.getSourceManager(); InclusionRewriter *Rewrite = new InclusionRewriter(PP, *OS, Opts.ShowLineMarkers); PP.addPPCallbacks(Rewrite); // First let the preprocessor process the entire file and call callbacks. // Callbacks will record which #include's were actually performed. PP.EnterMainSourceFile(); Token Tok; // Only preprocessor directives matter here, so disable macro expansion // everywhere else as an optimization. // TODO: It would be even faster if the preprocessor could be switched // to a mode where it would parse only preprocessor directives and comments, // nothing else matters for parsing or processing. PP.SetMacroExpansionOnlyInDirectives(); do { PP.Lex(Tok); } while (Tok.isNot(tok::eof)); Rewrite->Process(SM.getMainFileID(), SrcMgr::C_User); OS->flush(); }
//===--- InclusionRewriter.cpp - Rewrite includes into their expansions ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This code rewrites include invocations into their expansions. This gives you // a file with all included files merged into it. // //===----------------------------------------------------------------------===// #include "clang/Rewrite/Rewriters.h" #include "clang/Lex/Preprocessor.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/PreprocessorOutputOptions.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace llvm; namespace { class InclusionRewriter : public PPCallbacks { /// Information about which #includes were actually performed, /// created by preprocessor callbacks. struct FileChange { SourceLocation From; FileID Id; SrcMgr::CharacteristicKind FileType; FileChange(SourceLocation From) : From(From) { } }; Preprocessor &PP; ///< Used to find inclusion directives. SourceManager &SM; ///< Used to read and manage source files. raw_ostream &OS; ///< The destination stream for rewritten contents. bool ShowLineMarkers; ///< Show #line markers. bool UseLineDirective; ///< Use of line directives or line markers. typedef std::map<unsigned, FileChange> FileChangeMap; FileChangeMap FileChanges; /// Tracks which files were included where. /// Used transitively for building up the FileChanges mapping over the /// various \c PPCallbacks callbacks. FileChangeMap::iterator LastInsertedFileChange; public: InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers); bool Process(FileID FileId, SrcMgr::CharacteristicKind FileType); private: virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID); virtual void FileSkipped(const FileEntry &ParentFile, const Token &FilenameTok, SrcMgr::CharacteristicKind FileType); virtual void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName, bool IsAngled, const FileEntry *File, SourceLocation EndLoc, StringRef SearchPath, StringRef RelativePath); void WriteLineInfo(const char *Filename, int Line, SrcMgr::CharacteristicKind FileType, StringRef EOL, StringRef Extra = StringRef()); void OutputContentUpTo(const MemoryBuffer &FromFile, unsigned &WriteFrom, unsigned WriteTo, StringRef EOL, int &lines, bool EnsureNewline = false); void CommentOutDirective(Lexer &DirectivesLex, const Token &StartToken, const MemoryBuffer &FromFile, StringRef EOL, unsigned &NextToWrite, int &Lines); const FileChange *FindFileChangeLocation(SourceLocation Loc) const; StringRef NextIdentifierName(Lexer &RawLex, Token &RawToken); }; } // end anonymous namespace /// Initializes an InclusionRewriter with a \p PP source and \p OS destination. InclusionRewriter::InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers) : PP(PP), SM(PP.getSourceManager()), OS(OS), ShowLineMarkers(ShowLineMarkers), LastInsertedFileChange(FileChanges.end()) { // If we're in microsoft mode, use normal #line instead of line markers. UseLineDirective = PP.getLangOpts().MicrosoftExt; } /// Write appropriate line information as either #line directives or GNU line /// markers depending on what mode we're in, including the \p Filename and /// \p Line we are located at, using the specified \p EOL line separator, and /// any \p Extra context specifiers in GNU line directives. void InclusionRewriter::WriteLineInfo(const char *Filename, int Line, SrcMgr::CharacteristicKind FileType, StringRef EOL, StringRef Extra) { if (!ShowLineMarkers) return; if (UseLineDirective) { OS << "#line" << ' ' << Line << ' ' << '"' << Filename << '"'; } else { // Use GNU linemarkers as described here: // http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html OS << '#' << ' ' << Line << ' ' << '"' << Filename << '"'; if (!Extra.empty()) OS << Extra; if (FileType == SrcMgr::C_System) // "`3' This indicates that the following text comes from a system header // file, so certain warnings should be suppressed." OS << " 3"; else if (FileType == SrcMgr::C_ExternCSystem) // as above for `3', plus "`4' This indicates that the following text // should be treated as being wrapped in an implicit extern "C" block." OS << " 3 4"; } OS << EOL; } /// FileChanged - Whenever the preprocessor enters or exits a #include file /// it invokes this handler. void InclusionRewriter::FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind NewFileType, FileID) { if (Reason != EnterFile) return; if (LastInsertedFileChange == FileChanges.end()) // we didn't reach this file (eg: the main file) via an inclusion directive return; LastInsertedFileChange->second.Id = FullSourceLoc(Loc, SM).getFileID(); LastInsertedFileChange->second.FileType = NewFileType; LastInsertedFileChange = FileChanges.end(); } /// Called whenever an inclusion is skipped due to canonical header protection /// macros. void InclusionRewriter::FileSkipped(const FileEntry &/*ParentFile*/, const Token &/*FilenameTok*/, SrcMgr::CharacteristicKind /*FileType*/) { assert(LastInsertedFileChange != FileChanges.end() && "A file, that wasn't " "found via an inclusion directive, was skipped"); FileChanges.erase(LastInsertedFileChange); LastInsertedFileChange = FileChanges.end(); } /// This should be called whenever the preprocessor encounters include /// directives. It does not say whether the file has been included, but it /// provides more information about the directive (hash location instead /// of location inside the included file). It is assumed that the matching /// FileChanged() or FileSkipped() is called after this. void InclusionRewriter::InclusionDirective(SourceLocation HashLoc, const Token &/*IncludeTok*/, StringRef /*FileName*/, bool /*IsAngled*/, const FileEntry * /*File*/, SourceLocation /*EndLoc*/, StringRef /*SearchPath*/, StringRef /*RelativePath*/) { assert(LastInsertedFileChange == FileChanges.end() && "Another inclusion " "directive was found before the previous one was processed"); std::pair<FileChangeMap::iterator, bool> p = FileChanges.insert( std::make_pair(HashLoc.getRawEncoding(), FileChange(HashLoc))); assert(p.second && "Unexpected revisitation of the same include directive"); LastInsertedFileChange = p.first; } /// Simple lookup for a SourceLocation (specifically one denoting the hash in /// an inclusion directive) in the map of inclusion information, FileChanges. const InclusionRewriter::FileChange * InclusionRewriter::FindFileChangeLocation(SourceLocation Loc) const { FileChangeMap::const_iterator I = FileChanges.find(Loc.getRawEncoding()); if (I != FileChanges.end()) return &I->second; return NULL; } /// Detect the likely line ending style of \p FromFile by examining the first /// newline found within it. static StringRef DetectEOL(const MemoryBuffer &FromFile) { // detect what line endings the file uses, so that added content does not mix // the style const char *Pos = strchr(FromFile.getBufferStart(), '\n'); if (Pos == NULL) return "\n"; if (Pos + 1 < FromFile.getBufferEnd() && Pos[1] == '\r') return "\n\r"; if (Pos - 1 >= FromFile.getBufferStart() && Pos[-1] == '\r') return "\r\n"; return "\n"; } /// Writes out bytes from \p FromFile, starting at \p NextToWrite and ending at /// \p WriteTo - 1. void InclusionRewriter::OutputContentUpTo(const MemoryBuffer &FromFile, unsigned &WriteFrom, unsigned WriteTo, StringRef EOL, int &Line, bool EnsureNewline) { if (WriteTo <= WriteFrom) return; OS.write(FromFile.getBufferStart() + WriteFrom, WriteTo - WriteFrom); // count lines manually, it's faster than getPresumedLoc() Line += std::count(FromFile.getBufferStart() + WriteFrom, FromFile.getBufferStart() + WriteTo, '\n'); if (EnsureNewline) { char LastChar = FromFile.getBufferStart()[WriteTo - 1]; if (LastChar != '\n' && LastChar != '\r') OS << EOL; } WriteFrom = WriteTo; } /// Print characters from \p FromFile starting at \p NextToWrite up until the /// inclusion directive at \p StartToken, then print out the inclusion /// inclusion directive disabled by a #if directive, updating \p NextToWrite /// and \p Line to track the number of source lines visited and the progress /// through the \p FromFile buffer. void InclusionRewriter::CommentOutDirective(Lexer &DirectiveLex, const Token &StartToken, const MemoryBuffer &FromFile, StringRef EOL, unsigned &NextToWrite, int &Line) { OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(StartToken.getLocation()), EOL, Line); Token DirectiveToken; do { DirectiveLex.LexFromRawLexer(DirectiveToken); } while (!DirectiveToken.is(tok::eod) && DirectiveToken.isNot(tok::eof)); OS << "#if 0 /* expanded by -rewrite-includes */" << EOL; OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(DirectiveToken.getLocation()) + DirectiveToken.getLength(), EOL, Line); OS << "#endif /* expanded by -rewrite-includes */" << EOL; } /// Find the next identifier in the pragma directive specified by \p RawToken. StringRef InclusionRewriter::NextIdentifierName(Lexer &RawLex, Token &RawToken) { RawLex.LexFromRawLexer(RawToken); if (RawToken.is(tok::raw_identifier)) PP.LookUpIdentifierInfo(RawToken); if (RawToken.is(tok::identifier)) return RawToken.getIdentifierInfo()->getName(); return StringRef(); } /// Use a raw lexer to analyze \p FileId, inccrementally copying parts of it /// and including content of included files recursively. bool InclusionRewriter::Process(FileID FileId, SrcMgr::CharacteristicKind FileType) { bool Invalid; const MemoryBuffer &FromFile = *SM.getBuffer(FileId, &Invalid); assert(!Invalid && "Invalid FileID while trying to rewrite includes"); const char *FileName = FromFile.getBufferIdentifier(); Lexer RawLex(FileId, &FromFile, PP.getSourceManager(), PP.getLangOpts()); RawLex.SetCommentRetentionState(false); StringRef EOL = DetectEOL(FromFile); // Per the GNU docs: "1" indicates the start of a new file. WriteLineInfo(FileName, 1, FileType, EOL, " 1"); if (SM.getFileIDSize(FileId) == 0) return true; // The next byte to be copied from the source file unsigned NextToWrite = 0; int Line = 1; // The current input file line number. Token RawToken; RawLex.LexFromRawLexer(RawToken); // TODO: Consider adding a switch that strips possibly unimportant content, // such as comments, to reduce the size of repro files. while (RawToken.isNot(tok::eof)) { if (RawToken.is(tok::hash) && RawToken.isAtStartOfLine()) { RawLex.setParsingPreprocessorDirective(true); Token HashToken = RawToken; RawLex.LexFromRawLexer(RawToken); if (RawToken.is(tok::raw_identifier)) PP.LookUpIdentifierInfo(RawToken); if (RawToken.is(tok::identifier)) { switch (RawToken.getIdentifierInfo()->getPPKeywordID()) { case tok::pp_include: case tok::pp_include_next: case tok::pp_import: { CommentOutDirective(RawLex, HashToken, FromFile, EOL, NextToWrite, Line); if (const FileChange *Change = FindFileChangeLocation( HashToken.getLocation())) { // now include and recursively process the file if (Process(Change->Id, Change->FileType)) // and set lineinfo back to this file, if the nested one was // actually included // `2' indicates returning to a file (after having included // another file. WriteLineInfo(FileName, Line, FileType, EOL, " 2"); } else // fix up lineinfo (since commented out directive changed line // numbers) for inclusions that were skipped due to header guards WriteLineInfo(FileName, Line, FileType, EOL); break; } case tok::pp_pragma: { StringRef Identifier = NextIdentifierName(RawLex, RawToken); if (Identifier == "clang" || Identifier == "GCC") { if (NextIdentifierName(RawLex, RawToken) == "system_header") { // keep the directive in, commented out CommentOutDirective(RawLex, HashToken, FromFile, EOL, NextToWrite, Line); // update our own type FileType = SM.getFileCharacteristic(RawToken.getLocation()); WriteLineInfo(FileName, Line, FileType, EOL); } } else if (Identifier == "once") { // keep the directive in, commented out CommentOutDirective(RawLex, HashToken, FromFile, EOL, NextToWrite, Line); WriteLineInfo(FileName, Line, FileType, EOL); } break; } default: break; } } RawLex.setParsingPreprocessorDirective(false); } RawLex.LexFromRawLexer(RawToken); } OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(SM.getLocForEndOfFile(FileId)) + 1, EOL, Line, /*EnsureNewline*/true); return true; } /// InclusionRewriterInInput - Implement -rewrite-includes mode. void clang::RewriteIncludesInInput(Preprocessor &PP, raw_ostream *OS, const PreprocessorOutputOptions &Opts) { SourceManager &SM = PP.getSourceManager(); InclusionRewriter *Rewrite = new InclusionRewriter(PP, *OS, Opts.ShowLineMarkers); PP.addPPCallbacks(Rewrite); // First let the preprocessor process the entire file and call callbacks. // Callbacks will record which #include's were actually performed. PP.EnterMainSourceFile(); Token Tok; // Only preprocessor directives matter here, so disable macro expansion // everywhere else as an optimization. // TODO: It would be even faster if the preprocessor could be switched // to a mode where it would parse only preprocessor directives and comments, // nothing else matters for parsing or processing. PP.SetMacroExpansionOnlyInDirectives(); do { PP.Lex(Tok); } while (Tok.isNot(tok::eof)); Rewrite->Process(SM.getMainFileID(), SrcMgr::C_User); OS->flush(); }
Replace a char counting helper function with std::count.
Replace a char counting helper function with std::count. No functionality change. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@158272 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang
73278080c8078002beb4706d5b1592e9b9c5f9b3
lib/Target/PowerPC/PPCJITInfo.cpp
lib/Target/PowerPC/PPCJITInfo.cpp
//===-- PPC32JITInfo.cpp - Implement the JIT interfaces for the PowerPC ---===// // // 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 JIT interfaces for the 32-bit PowerPC target. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "jit" #include "PPC32JITInfo.h" #include "PPC32Relocations.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/Config/alloca.h" using namespace llvm; static TargetJITInfo::JITCompilerFn JITCompilerFunction; #define BUILD_ADDIS(RD,RS,IMM16) \ ((15 << 26) | ((RD) << 21) | ((RS) << 16) | ((IMM16) & 65535)) #define BUILD_ORI(RD,RS,UIMM16) \ ((24 << 26) | ((RS) << 21) | ((RD) << 16) | ((UIMM16) & 65535)) #define BUILD_MTSPR(RS,SPR) \ ((31 << 26) | ((RS) << 21) | ((SPR) << 16) | (467 << 1)) #define BUILD_BCCTRx(BO,BI,LINK) \ ((19 << 26) | ((BO) << 21) | ((BI) << 16) | (528 << 1) | ((LINK) & 1)) // Pseudo-ops #define BUILD_LIS(RD,IMM16) BUILD_ADDIS(RD,0,IMM16) #define BUILD_MTCTR(RS) BUILD_MTSPR(RS,9) #define BUILD_BCTR(LINK) BUILD_BCCTRx(20,0,LINK) static void EmitBranchToAt(void *At, void *To, bool isCall) { intptr_t Addr = (intptr_t)To; // FIXME: should special case the short branch case. unsigned *AtI = (unsigned*)At; AtI[0] = BUILD_LIS(12, Addr >> 16); // lis r12, hi16(address) AtI[1] = BUILD_ORI(12, 12, Addr); // ori r12, r12, low16(address) AtI[2] = BUILD_MTCTR(12); // mtctr r12 AtI[3] = BUILD_BCTR(isCall); // bctr/bctrl } static void CompilationCallback() { // Save R3-R31, since we want to restore arguments and nonvolatile regs used // by the compiler. We also save and restore the FP regs, although this is // probably just paranoia (gcc is unlikely to emit code that uses them for // for this function. #if defined(__POWERPC__) || defined (__ppc__) || defined(_POWER) unsigned IntRegs[29]; double FPRegs[13]; __asm__ __volatile__ ( "stmw r3, 0(%0)\n" "stfd f1, 0(%1)\n" "stfd f2, 8(%1)\n" "stfd f3, 16(%1)\n" "stfd f4, 24(%1)\n" "stfd f5, 32(%1)\n" "stfd f6, 40(%1)\n" "stfd f7, 48(%1)\n" "stfd f8, 56(%1)\n" "stfd f9, 64(%1)\n" "stfd f10, 72(%1)\n" "stfd f11, 80(%1)\n" "stfd f12, 88(%1)\n" "stfd f13, 96(%1)\n" :: "b" (IntRegs), "b" (FPRegs) ); /// FIXME: Need to safe and restore the rest of the FP regs! #endif unsigned *CameFromStub = (unsigned*)__builtin_return_address(0); unsigned *CameFromOrig = (unsigned*)__builtin_return_address(1); unsigned *CCStackPtr = (unsigned*)__builtin_frame_address(0); //unsigned *StubStackPtr = (unsigned*)__builtin_frame_address(1); unsigned *OrigStackPtr = (unsigned*)__builtin_frame_address(2); // Adjust pointer to the branch, not the return address. --CameFromStub; void *Target = JITCompilerFunction(CameFromStub); // Check to see if CameFromOrig[-1] is a 'bl' instruction, and if we can // rewrite it to branch directly to the destination. If so, rewrite it so it // does not need to go through the stub anymore. unsigned CameFromOrigInst = CameFromOrig[-1]; if ((CameFromOrigInst >> 26) == 18) { // Direct call. intptr_t Offset = ((intptr_t)Target-(intptr_t)CameFromOrig+4) >> 2; if (Offset >= -(1 << 23) && Offset < (1 << 23)) { // In range? // Clear the original target out. CameFromOrigInst &= (63 << 26) | 3; // Fill in the new target. CameFromOrigInst |= (Offset & ((1 << 24)-1)) << 2; // Replace the call. CameFromOrig[-1] = CameFromOrigInst; } } // Locate the start of the stub. If this is a short call, adjust backwards // the short amount, otherwise the full amount. bool isShortStub = (*CameFromStub >> 26) == 18; CameFromStub -= isShortStub ? 2 : 6; // Rewrite the stub with an unconditional branch to the target, for any users // who took the address of the stub. EmitBranchToAt(CameFromStub, Target, false); // Change the SP so that we pop two stack frames off when we return. *CCStackPtr = (intptr_t)OrigStackPtr; // Put the address of the stub and the LR value that originally came into the // stub in a place that is easy to get on the stack after we restore all regs. CCStackPtr[2] = (intptr_t)Target; CCStackPtr[1] = (intptr_t)CameFromOrig; // Note, this is not a standard epilog! #if defined(__POWERPC__) || defined (__ppc__) || defined(_POWER) register unsigned *IRR asm ("r2") = IntRegs; register double *FRR asm ("r3") = FPRegs; __asm__ __volatile__ ( "lfd f1, 0(%0)\n" "lfd f2, 8(%0)\n" "lfd f3, 16(%0)\n" "lfd f4, 24(%0)\n" "lfd f5, 32(%0)\n" "lfd f6, 40(%0)\n" "lfd f7, 48(%0)\n" "lfd f8, 56(%0)\n" "lfd f9, 64(%0)\n" "lfd f10, 72(%0)\n" "lfd f11, 80(%0)\n" "lfd f12, 88(%0)\n" "lfd f13, 96(%0)\n" "lmw r3, 0(%1)\n" // Load all integer regs "lwz r0,4(r1)\n" // Get CameFromOrig (LR into stub) "mtlr r0\n" // Put it in the LR register "lwz r0,8(r1)\n" // Get target function pointer "mtctr r0\n" // Put it into the CTR register "lwz r1,0(r1)\n" // Pop two frames off "bctr\n" :: // Return to stub! "b" (FRR), "b" (IRR)); #endif } TargetJITInfo::LazyResolverFn PPC32JITInfo::getLazyResolverFunction(JITCompilerFn Fn) { JITCompilerFunction = Fn; return CompilationCallback; } void *PPC32JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) { // If this is just a call to an external function, emit a branch instead of a // call. The code is the same except for one bit of the last instruction. if (Fn != CompilationCallback) { MCE.startFunctionStub(4*4); void *Addr = (void*)(intptr_t)MCE.getCurrentPCValue(); MCE.emitWord(0); MCE.emitWord(0); MCE.emitWord(0); MCE.emitWord(0); EmitBranchToAt(Addr, Fn, false); return MCE.finishFunctionStub(0); } MCE.startFunctionStub(4*7); MCE.emitWord(0x9421ffe0); // stwu r1,-32(r1) MCE.emitWord(0x7d6802a6); // mflr r11 MCE.emitWord(0x91610028); // stw r11, 40(r1) void *Addr = (void*)(intptr_t)MCE.getCurrentPCValue(); MCE.emitWord(0); MCE.emitWord(0); MCE.emitWord(0); MCE.emitWord(0); EmitBranchToAt(Addr, Fn, true/*is call*/); return MCE.finishFunctionStub(0); } void PPC32JITInfo::relocate(void *Function, MachineRelocation *MR, unsigned NumRelocs) { for (unsigned i = 0; i != NumRelocs; ++i, ++MR) { unsigned *RelocPos = (unsigned*)Function + MR->getMachineCodeOffset()/4; intptr_t ResultPtr = (intptr_t)MR->getResultPointer(); switch ((PPC::RelocationType)MR->getRelocationType()) { default: assert(0 && "Unknown relocation type!"); case PPC::reloc_pcrel_bx: // PC-relative relocation for b and bl instructions. ResultPtr = (ResultPtr-(intptr_t)RelocPos) >> 2; assert(ResultPtr >= -(1 << 23) && ResultPtr < (1 << 23) && "Relocation out of range!"); *RelocPos |= (ResultPtr & ((1 << 24)-1)) << 2; break; case PPC::reloc_absolute_loadhi: // Relocate high bits into addis case PPC::reloc_absolute_la: // Relocate low bits into addi ResultPtr += MR->getConstantVal(); if (MR->getRelocationType() == PPC::reloc_absolute_loadhi) { // If the low part will have a carry (really a borrow) from the low // 16-bits into the high 16, add a bit to borrow from. if (((int)ResultPtr << 16) < 0) ResultPtr += 1 << 16; ResultPtr >>= 16; } // Do the addition then mask, so the addition does not overflow the 16-bit // immediate section of the instruction. unsigned LowBits = (*RelocPos + ResultPtr) & 65535; unsigned HighBits = *RelocPos & ~65535; *RelocPos = LowBits | HighBits; // Slam into low 16-bits break; } } } void PPC32JITInfo::replaceMachineCodeForFunction(void *Old, void *New) { EmitBranchToAt(Old, New, false); }
//===-- PPC32JITInfo.cpp - Implement the JIT interfaces for the PowerPC ---===// // // 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 JIT interfaces for the 32-bit PowerPC target. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "jit" #include "PPC32JITInfo.h" #include "PPC32Relocations.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/Config/alloca.h" using namespace llvm; static TargetJITInfo::JITCompilerFn JITCompilerFunction; #define BUILD_ADDIS(RD,RS,IMM16) \ ((15 << 26) | ((RD) << 21) | ((RS) << 16) | ((IMM16) & 65535)) #define BUILD_ORI(RD,RS,UIMM16) \ ((24 << 26) | ((RS) << 21) | ((RD) << 16) | ((UIMM16) & 65535)) #define BUILD_MTSPR(RS,SPR) \ ((31 << 26) | ((RS) << 21) | ((SPR) << 16) | (467 << 1)) #define BUILD_BCCTRx(BO,BI,LINK) \ ((19 << 26) | ((BO) << 21) | ((BI) << 16) | (528 << 1) | ((LINK) & 1)) // Pseudo-ops #define BUILD_LIS(RD,IMM16) BUILD_ADDIS(RD,0,IMM16) #define BUILD_MTCTR(RS) BUILD_MTSPR(RS,9) #define BUILD_BCTR(LINK) BUILD_BCCTRx(20,0,LINK) static void EmitBranchToAt(void *At, void *To, bool isCall) { intptr_t Addr = (intptr_t)To; // FIXME: should special case the short branch case. unsigned *AtI = (unsigned*)At; AtI[0] = BUILD_LIS(12, Addr >> 16); // lis r12, hi16(address) AtI[1] = BUILD_ORI(12, 12, Addr); // ori r12, r12, low16(address) AtI[2] = BUILD_MTCTR(12); // mtctr r12 AtI[3] = BUILD_BCTR(isCall); // bctr/bctrl } extern "C" void PPC32CompilationCallback(); #if defined(__POWERPC__) || defined (__ppc__) || defined(_POWER) // CompilationCallback stub - We can't use a C function with inline assembly in // it, because we the prolog/epilog inserted by GCC won't work for us. Instead, // write our own wrapper, which does things our way, so we have complete control // over register saving and restoring. asm( ".text\n" ".align 2\n" ".globl _PPC32CompilationCallback\n" "_PPC32CompilationCallback:\n" // Make space for 29 ints r[3-31] and 14 doubles f[0-13] "stwu r1, -272(r1)\n" "mflr r11\n" "stw r11, 280(r1)\n" // Set up a proper stack frame "stmw r3, 156(r1)\n" // Save all of the integer registers // Save all call-clobbered FP regs. "stfd f1, 44(r1)\n" "stfd f2, 52(r1)\n" "stfd f3, 60(r1)\n" "stfd f4, 68(r1)\n" "stfd f5, 76(r1)\n" "stfd f6, 84(r1)\n" "stfd f7, 92(r1)\n" "stfd f8, 100(r1)\n" "stfd f9, 108(r1)\n" "stfd f10, 116(r1)\n" "stfd f11, 124(r1)\n" "stfd f12, 132(r1)\n" "stfd f13, 140(r1)\n" // Now that everything is saved, go to the C compilation callback function, // passing the address of the intregs and fpregs. "addi r3, r1, 156\n" // &IntRegs[0] "addi r4, r1, 44\n" // &FPRegs[0] "bl _PPC32CompilationCallbackC\n" ); #endif extern "C" void PPC32CompilationCallbackC(unsigned *IntRegs, double *FPRegs) { unsigned *CameFromStub = (unsigned*)__builtin_return_address(0+1); unsigned *CameFromOrig = (unsigned*)__builtin_return_address(1+1); unsigned *CCStackPtr = (unsigned*)__builtin_frame_address(0); //unsigned *StubStackPtr = (unsigned*)__builtin_frame_address(1); unsigned *OrigStackPtr = (unsigned*)__builtin_frame_address(2+1); // Adjust pointer to the branch, not the return address. --CameFromStub; void *Target = JITCompilerFunction(CameFromStub); // Check to see if CameFromOrig[-1] is a 'bl' instruction, and if we can // rewrite it to branch directly to the destination. If so, rewrite it so it // does not need to go through the stub anymore. unsigned CameFromOrigInst = CameFromOrig[-1]; if ((CameFromOrigInst >> 26) == 18) { // Direct call. intptr_t Offset = ((intptr_t)Target-(intptr_t)CameFromOrig+4) >> 2; if (Offset >= -(1 << 23) && Offset < (1 << 23)) { // In range? // Clear the original target out. CameFromOrigInst &= (63 << 26) | 3; // Fill in the new target. CameFromOrigInst |= (Offset & ((1 << 24)-1)) << 2; // Replace the call. CameFromOrig[-1] = CameFromOrigInst; } } // Locate the start of the stub. If this is a short call, adjust backwards // the short amount, otherwise the full amount. bool isShortStub = (*CameFromStub >> 26) == 18; CameFromStub -= isShortStub ? 2 : 6; // Rewrite the stub with an unconditional branch to the target, for any users // who took the address of the stub. EmitBranchToAt(CameFromStub, Target, false); // Change the SP so that we pop two stack frames off when we return. *CCStackPtr = (intptr_t)OrigStackPtr; // Put the address of the stub and the LR value that originally came into the // stub in a place that is easy to get on the stack after we restore all regs. CCStackPtr[2] = (intptr_t)Target; CCStackPtr[1] = (intptr_t)CameFromOrig; // Note, this is not a standard epilog! #if defined(__POWERPC__) || defined (__ppc__) || defined(_POWER) register unsigned *IRR asm ("r2") = IntRegs; register double *FRR asm ("r3") = FPRegs; __asm__ __volatile__ ( "lfd f1, 0(%0)\n" "lfd f2, 8(%0)\n" "lfd f3, 16(%0)\n" "lfd f4, 24(%0)\n" "lfd f5, 32(%0)\n" "lfd f6, 40(%0)\n" "lfd f7, 48(%0)\n" "lfd f8, 56(%0)\n" "lfd f9, 64(%0)\n" "lfd f10, 72(%0)\n" "lfd f11, 80(%0)\n" "lfd f12, 88(%0)\n" "lfd f13, 96(%0)\n" "lmw r3, 0(%1)\n" // Load all integer regs "lwz r0,4(r1)\n" // Get CameFromOrig (LR into stub) "mtlr r0\n" // Put it in the LR register "lwz r0,8(r1)\n" // Get target function pointer "mtctr r0\n" // Put it into the CTR register "lwz r1,0(r1)\n" // Pop two frames off "bctr\n" :: // Return to stub! "b" (FRR), "b" (IRR)); #endif } TargetJITInfo::LazyResolverFn PPC32JITInfo::getLazyResolverFunction(JITCompilerFn Fn) { JITCompilerFunction = Fn; return PPC32CompilationCallback; } void *PPC32JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) { // If this is just a call to an external function, emit a branch instead of a // call. The code is the same except for one bit of the last instruction. if (Fn != PPC32CompilationCallback) { MCE.startFunctionStub(4*4); void *Addr = (void*)(intptr_t)MCE.getCurrentPCValue(); MCE.emitWord(0); MCE.emitWord(0); MCE.emitWord(0); MCE.emitWord(0); EmitBranchToAt(Addr, Fn, false); return MCE.finishFunctionStub(0); } MCE.startFunctionStub(4*7); MCE.emitWord(0x9421ffe0); // stwu r1,-32(r1) MCE.emitWord(0x7d6802a6); // mflr r11 MCE.emitWord(0x91610028); // stw r11, 40(r1) void *Addr = (void*)(intptr_t)MCE.getCurrentPCValue(); MCE.emitWord(0); MCE.emitWord(0); MCE.emitWord(0); MCE.emitWord(0); EmitBranchToAt(Addr, Fn, true/*is call*/); return MCE.finishFunctionStub(0); } void PPC32JITInfo::relocate(void *Function, MachineRelocation *MR, unsigned NumRelocs) { for (unsigned i = 0; i != NumRelocs; ++i, ++MR) { unsigned *RelocPos = (unsigned*)Function + MR->getMachineCodeOffset()/4; intptr_t ResultPtr = (intptr_t)MR->getResultPointer(); switch ((PPC::RelocationType)MR->getRelocationType()) { default: assert(0 && "Unknown relocation type!"); case PPC::reloc_pcrel_bx: // PC-relative relocation for b and bl instructions. ResultPtr = (ResultPtr-(intptr_t)RelocPos) >> 2; assert(ResultPtr >= -(1 << 23) && ResultPtr < (1 << 23) && "Relocation out of range!"); *RelocPos |= (ResultPtr & ((1 << 24)-1)) << 2; break; case PPC::reloc_absolute_loadhi: // Relocate high bits into addis case PPC::reloc_absolute_la: // Relocate low bits into addi ResultPtr += MR->getConstantVal(); if (MR->getRelocationType() == PPC::reloc_absolute_loadhi) { // If the low part will have a carry (really a borrow) from the low // 16-bits into the high 16, add a bit to borrow from. if (((int)ResultPtr << 16) < 0) ResultPtr += 1 << 16; ResultPtr >>= 16; } // Do the addition then mask, so the addition does not overflow the 16-bit // immediate section of the instruction. unsigned LowBits = (*RelocPos + ResultPtr) & 65535; unsigned HighBits = *RelocPos & ~65535; *RelocPos = LowBits | HighBits; // Slam into low 16-bits break; } } } void PPC32JITInfo::replaceMachineCodeForFunction(void *Old, void *New) { EmitBranchToAt(Old, New, false); }
Write CompilationCallback as an explicit assembly stub to avoid getting GCC's prolog.
Write CompilationCallback as an explicit assembly stub to avoid getting GCC's prolog. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@18220 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm
b5b11bdf30a8a143b810eaa1e8173f2dfac70686
main.cpp
main.cpp
#include <opencv2/highgui.hpp> #include <opencv2/opencv.hpp> #include <iostream> #ifdef HAVE_OPENCV_CONTRIB #include <opencv2/bgsegm.hpp> #endif #include "bgsubcnt.h" using namespace cv; using namespace std; const string keys = "{help h usage ? || print this message}" "{file || use file (default is system camera)}" "{type |CNT| bg subtraction type from - CNT/MOG2/KNN" #ifdef HAVE_OPENCV_CONTRIB "GMG/MOG" #endif "}" "{bg || calculate also the background}" "{nogui || run without GUI to measure times}"; int main( int argc, char** argv ) { VideoCapture cap; CommandLineParser parser(argc, argv, keys); parser.about("BackgroundSubtractorCNT demo/benchmark/comparison"); if (parser.has("help")) { parser.printMessage(); return 0; } bool hasFile = parser.has("file"); bool hasGui = ! parser.has("nogui"); bool bgImage = parser.has("bg"); string type = parser.get<string>("type"); string filePath; if (hasFile) { filePath = parser.get<string>("file"); if (filePath == "true") { cout << "You must supply a file path argument with -file=filePath\n"; return 1; } cap.open(filePath); } else { cap.open(0); } if (! parser.check()) { parser.printErrors(); return 1; } if( !cap.isOpened() ) { cout << "Could not initialize capturing...\n"; return 0; } Ptr<BackgroundSubtractor> pBgSub; if (type == "CNT") { int fps = 30; if (hasFile) { fps = cap.get(CAP_PROP_FPS); } pBgSub = createBackgroundSubtractorCNT(fps, true, fps*60); } else if (type == "MOG2") { Ptr<BackgroundSubtractorMOG2> pBgSubMOG2 = createBackgroundSubtractorMOG2(); pBgSubMOG2->setDetectShadows(false); pBgSub = pBgSubMOG2; } else if (type == "KNN") { pBgSub = createBackgroundSubtractorKNN(); } #ifdef HAVE_OPENCV_CONTRIB else if (type == "GMG") { pBgSub = cv::bgsegm::createBackgroundSubtractorGMG(); } else if (type == "MOG") { pBgSub = cv::bgsegm::createBackgroundSubtractorMOG(); } #endif else { parser.printMessage(); cout << "\nWrong type - please see above\n"; return 1; } bool showFG=true; if (hasGui) { namedWindow("Orig", 1); namedWindow("FG", 1); if (bgImage) { namedWindow("BG", 1); } } double startTime = getTickCount(); for(;;) { Mat frame; cap >> frame; if( frame.empty() ) { break; } Mat gray; cvtColor(frame, gray, COLOR_BGR2GRAY); Mat fgMask; pBgSub->apply(gray, fgMask); if (hasGui) { imshow("Orig", frame); if (showFG) { Mat fg; frame.copyTo(fg, fgMask); imshow("FG", fg); } } if (bgImage) { Mat bg; pBgSub->getBackgroundImage(bg); if (hasGui) { imshow("BG", bg); } } if (hasGui) { char c = (char)waitKey(1); if (c == 27) { break; } } } double tfreq = getTickFrequency(); double secs = ((double) getTickCount() - startTime)/tfreq; cout << "Execution took " << fixed << secs << " seconds." << endl; }
#include <opencv2/opencv.hpp> #include <iostream> #ifdef HAVE_OPENCV_CONTRIB #include <opencv2/bgsegm.hpp> #endif #include "bgsubcnt.h" using namespace cv; using namespace std; const string keys = "{help h usage ? || print this message}" "{file || use file (default is system camera)}" "{type |CNT| bg subtraction type from - CNT/MOG2/KNN" #ifdef HAVE_OPENCV_CONTRIB "GMG/MOG" #endif "}" "{bg || calculate also the background}" "{nogui || run without GUI to measure times}"; int main( int argc, char** argv ) { VideoCapture cap; CommandLineParser parser(argc, argv, keys); parser.about("BackgroundSubtractorCNT demo/benchmark/comparison"); if (parser.has("help")) { parser.printMessage(); return 0; } bool hasFile = parser.has("file"); bool hasGui = ! parser.has("nogui"); bool bgImage = parser.has("bg"); string type = parser.get<string>("type"); string filePath; if (hasFile) { filePath = parser.get<string>("file"); if (filePath == "true") { cout << "You must supply a file path argument with -file=filePath\n"; return 1; } cap.open(filePath); } else { cap.open(0); } if (! parser.check()) { parser.printErrors(); return 1; } if( !cap.isOpened() ) { cout << "Could not initialize capturing...\n"; return 0; } Ptr<BackgroundSubtractor> pBgSub; if (type == "CNT") { int fps = 30; if (hasFile) { fps = cap.get(CAP_PROP_FPS); } pBgSub = createBackgroundSubtractorCNT(fps, true, fps*60); } else if (type == "MOG2") { Ptr<BackgroundSubtractorMOG2> pBgSubMOG2 = createBackgroundSubtractorMOG2(); pBgSubMOG2->setDetectShadows(false); pBgSub = pBgSubMOG2; } else if (type == "KNN") { pBgSub = createBackgroundSubtractorKNN(); } #ifdef HAVE_OPENCV_CONTRIB else if (type == "GMG") { pBgSub = cv::bgsegm::createBackgroundSubtractorGMG(); } else if (type == "MOG") { pBgSub = cv::bgsegm::createBackgroundSubtractorMOG(); } #endif else { parser.printMessage(); cout << "\nWrong type - please see above\n"; return 1; } bool showFG=true; if (hasGui) { namedWindow("Orig", 1); namedWindow("FG", 1); if (bgImage) { namedWindow("BG", 1); } cout << "Press 's' to save a frame to the current directory.\n" "Use ESC to quit.\n" << endl; } double startTime = getTickCount(); for(;;) { Mat frame, fgMask, fg, bg; cap >> frame; if( frame.empty() ) { break; } Mat gray; cvtColor(frame, gray, COLOR_BGR2GRAY); pBgSub->apply(gray, fgMask); if (hasGui) { imshow("Orig", frame); if (showFG) { frame.copyTo(fg, fgMask); imshow("FG", fg); } } if (bgImage) { pBgSub->getBackgroundImage(bg); if (hasGui) { imshow("BG", bg); } } if (hasGui) { char c = (char)waitKey(1); if (c == 27) { break; } else if (c == 's') { cv::imwrite("frame.jpg", frame); cv::imwrite("fg.jpg", fg); if (bgImage) { cv::imwrite("bg.jpg", bg); } } } } double tfreq = getTickFrequency(); double secs = ((double) getTickCount() - startTime)/tfreq; cout << "Execution took " << fixed << secs << " seconds." << endl; }
save frame feature
save frame feature
C++
bsd-3-clause
sagi-z/BackgroundSubtractorCNT,sagi-z/BackgroundSubtractorCNT,sagi-z/BackgroundSubtractorCNT
4e1da11af4ccff45bccd4dde3ffa9e394b8b50d2
main.cpp
main.cpp
c4555f66-4b02-11e5-9556-28cfe9171a43
c4620414-4b02-11e5-9e9a-28cfe9171a43
fix for the previous fix
fix for the previous fix
C++
apache-2.0
haosdent/jcgroup,haosdent/jcgroup
e4cfa76d8c7c81f5e8673c8216a65ef7960dc867
main.cpp
main.cpp
#include <iostream> #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QRunnable> #include <QThreadPool> #include "SMU.h" #include "utils/backtracing.h" #include "utils/fileio.h" int main(int argc, char *argv[]) { QCoreApplication::addLibraryPath("./"); // Prevent config being written to ~/.config/Unknown Organization/pixelpulse2.conf QCoreApplication::setOrganizationName("Analog Devices, Inc."); QCoreApplication::setApplicationName("Pixelpulse2"); init_signal_handlers(argv[0]); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; registerTypes(); FileIO fileIO; SessionItem smu_session; smu_session.openAllDevices(); engine.rootContext()->setContextProperty("session", &smu_session); QVariantMap versions; versions.insert("build_date", BUILD_DATE); versions.insert("git_version", GIT_VERSION); engine.rootContext()->setContextProperty("versions", versions); engine.rootContext()->setContextProperty("fileio", &fileIO); if (argc > 1) { if (strcmp(argv[1], "-v") || strcmp(argv[1], "--version")) { std::cout << GIT_VERSION << ": Built on " << BUILD_DATE << std::endl; return 0; } engine.load(argv[1]); } else { engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); } int r = app.exec(); smu_session.closeAllDevices(); return r; }
#include <iostream> #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QRunnable> #include <QThreadPool> #include "SMU.h" #include "utils/backtracing.h" #include "utils/fileio.h" int main(int argc, char *argv[]) { QCoreApplication::addLibraryPath("./"); // Prevent config being written to ~/.config/Unknown Organization/pixelpulse2.conf QCoreApplication::setOrganizationName("Pixelpulse2"); QCoreApplication::setApplicationName("Pixelpulse2"); init_signal_handlers(argv[0]); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; registerTypes(); FileIO fileIO; SessionItem smu_session; smu_session.openAllDevices(); engine.rootContext()->setContextProperty("session", &smu_session); QVariantMap versions; versions.insert("build_date", BUILD_DATE); versions.insert("git_version", GIT_VERSION); engine.rootContext()->setContextProperty("versions", versions); engine.rootContext()->setContextProperty("fileio", &fileIO); if (argc > 1) { if (strcmp(argv[1], "-v") || strcmp(argv[1], "--version")) { std::cout << GIT_VERSION << ": Built on " << BUILD_DATE << std::endl; return 0; } engine.load(argv[1]); } else { engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); } int r = app.exec(); smu_session.closeAllDevices(); return r; }
fix spaces in org name - revert 0c7a1b78
fix spaces in org name - revert 0c7a1b78
C++
mpl-2.0
analogdevicesinc/Pixelpulse2,analogdevicesinc/Pixelpulse2,analogdevicesinc/Pixelpulse2
95bf47c534737019f956fbcca2c622c98dacc266
src/usr/pore/poreve/porevesrc/pib2cfam.C
src/usr/pore/poreve/porevesrc/pib2cfam.C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/pore/poreve/porevesrc/pib2cfam.C $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* COPYRIGHT International Business Machines Corp. 2012,2013 */ /* */ /* p1 */ /* */ /* Object Code Only (OCO) source materials */ /* Licensed Internal Code Source Materials */ /* IBM HostBoot Licensed Internal Code */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* Origin: 30 */ /* */ /* IBM_PROLOG_END_TAG */ // -*- mode: C++; c-file-style: "linux"; -*- // $Id: pib2cfam.C,v 1.15 2013/06/24 14:51:53 jeshua Exp $ /// \file pib2cfam.C /// \brief A simple PibSlave that maps a small range of PIB addresses to CFAM /// addresses. #include "pib2cfam.H" using namespace vsbe; ////////////////////////////// Creators ////////////////////////////// Pib2Cfam::Pib2Cfam() { } Pib2Cfam::~Pib2Cfam() { } //////////////////////////// Manipulators //////////////////////////// static uint32_t translateAddress(uint32_t address, fapi::Target* i_target) { uint8_t fsi_gpreg_scom_access = 0; fapi::ReturnCode frc; frc = FAPI_ATTR_GET( ATTR_FSI_GP_REG_SCOM_ACCESS, i_target, fsi_gpreg_scom_access ); if(!frc.ok()) { FAPI_ERR( "Unable to get ATTR_FSI_GP_REG_SCOM_ACCESS for target\n" ); //JDS TODO - create an actual fapi error // FAPI_SET_HWP_ERROR( frc, "Unable to get ATTR_FSI_GP_REG_SCOM_ACCESS for target\n" ); } if( fsi_gpreg_scom_access ) { return (address - 0x00050000) + 0x2800; } else { return (address - 0x00050000) + 0x1000; } } fapi::ReturnCode Pib2Cfam::operation(Transaction& io_transaction) { fapi::ReturnCode rc; ModelError me; switch (io_transaction.iv_mode) { case ACCESS_MODE_READ: switch (io_transaction.iv_address) { case 0x00050006: case 0x00050007: case 0x00050012: case 0x00050013: case 0x00050014: case 0x00050015: case 0x00050016: case 0x00050017: case 0x00050018: case 0x00050019: case 0x0005001A: case 0x0005001B: rc = fapiGetCfamRegister(*iv_target, translateAddress(io_transaction.iv_address, iv_target), *iv_dataBuffer); if (rc.ok()) { io_transaction.iv_data = ((uint64_t)iv_dataBuffer->getWord(0)) << 32; me = ME_SUCCESS; } else { me = ME_FAILURE; } break; default: me = ME_NOT_MAPPED_IN_MEMORY; } break; case ACCESS_MODE_WRITE: switch (io_transaction.iv_address) { case 0x00050006: case 0x00050007: case 0x00050012: case 0x00050013: case 0x00050014: case 0x00050015: case 0x00050016: case 0x00050017: case 0x00050018: case 0x0005001B: iv_dataBuffer->setWordLength(1); iv_dataBuffer->setWord(0, io_transaction.iv_data >> 32); rc = fapiPutCfamRegister(*iv_target, translateAddress(io_transaction.iv_address, iv_target), *iv_dataBuffer); if (rc.ok()) { me = ME_SUCCESS; } else { me = ME_FAILURE; } break; case 0x00050019: case 0x0005001A: FAPI_SET_HWP_ERROR(rc, RC_POREVE_PIB2CFAM_ERROR); me = ME_BUS_SLAVE_PERMISSION_DENIED; break; default: FAPI_SET_HWP_ERROR(rc, RC_POREVE_PIB2CFAM_ERROR); me = ME_NOT_MAPPED_IN_MEMORY; } break; default: FAPI_SET_HWP_ERROR(rc, RC_POREVE_PIB2CFAM_ERROR); me = ME_BUS_SLAVE_PERMISSION_DENIED; break; } io_transaction.busError(me); return rc; } /* Local Variables: */ /* c-basic-offset: 4 */ /* End: */
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/pore/poreve/porevesrc/pib2cfam.C $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* COPYRIGHT International Business Machines Corp. 2012,2013 */ /* */ /* p1 */ /* */ /* Object Code Only (OCO) source materials */ /* Licensed Internal Code Source Materials */ /* IBM HostBoot Licensed Internal Code */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* Origin: 30 */ /* */ /* IBM_PROLOG_END_TAG */ // -*- mode: C++; c-file-style: "linux"; -*- // $Id: pib2cfam.C,v 1.16 2013/08/29 14:54:56 jeshua Exp $ /// \file pib2cfam.C /// \brief A simple PibSlave that maps a small range of PIB addresses to CFAM /// addresses. #include "pib2cfam.H" using namespace vsbe; ////////////////////////////// Creators ////////////////////////////// Pib2Cfam::Pib2Cfam() { } Pib2Cfam::~Pib2Cfam() { } //////////////////////////// Manipulators //////////////////////////// static uint32_t translateAddress(uint32_t address, fapi::Target* i_target) { uint8_t fsi_gpreg_scom_access = 0; fapi::ReturnCode frc; frc = FAPI_ATTR_GET( ATTR_FSI_GP_REG_SCOM_ACCESS, i_target, fsi_gpreg_scom_access ); if(!frc.ok()) { FAPI_ERR( "Unable to get ATTR_FSI_GP_REG_SCOM_ACCESS for target\n" ); //JDS TODO - create an actual fapi error // FAPI_SET_HWP_ERROR( frc, "Unable to get ATTR_FSI_GP_REG_SCOM_ACCESS for target\n" ); } if( fsi_gpreg_scom_access ) { return (address - 0x00050000) + 0x2800; } else { return (address - 0x00050000) + 0x1000; } } fapi::ReturnCode Pib2Cfam::operation(Transaction& io_transaction) { fapi::ReturnCode rc; ModelError me; switch (io_transaction.iv_mode) { case ACCESS_MODE_READ: switch (io_transaction.iv_address) { case 0x00050006: case 0x00050007: case 0x0005000A: case 0x00050012: case 0x00050013: case 0x00050014: case 0x00050015: case 0x00050016: case 0x00050017: case 0x00050018: case 0x00050019: case 0x0005001A: case 0x0005001B: rc = fapiGetCfamRegister(*iv_target, translateAddress(io_transaction.iv_address, iv_target), *iv_dataBuffer); if (rc.ok()) { io_transaction.iv_data = ((uint64_t)iv_dataBuffer->getWord(0)) << 32; me = ME_SUCCESS; } else { me = ME_FAILURE; } break; default: me = ME_NOT_MAPPED_IN_MEMORY; } break; case ACCESS_MODE_WRITE: switch (io_transaction.iv_address) { case 0x00050006: case 0x00050007: case 0x00050012: case 0x00050013: case 0x00050014: case 0x00050015: case 0x00050016: case 0x00050017: case 0x00050018: case 0x0005001B: iv_dataBuffer->setWordLength(1); iv_dataBuffer->setWord(0, io_transaction.iv_data >> 32); rc = fapiPutCfamRegister(*iv_target, translateAddress(io_transaction.iv_address, iv_target), *iv_dataBuffer); if (rc.ok()) { me = ME_SUCCESS; } else { me = ME_FAILURE; } break; case 0x00050019: case 0x0005001A: FAPI_SET_HWP_ERROR(rc, RC_POREVE_PIB2CFAM_ERROR); me = ME_BUS_SLAVE_PERMISSION_DENIED; break; default: FAPI_SET_HWP_ERROR(rc, RC_POREVE_PIB2CFAM_ERROR); me = ME_NOT_MAPPED_IN_MEMORY; } break; default: FAPI_SET_HWP_ERROR(rc, RC_POREVE_PIB2CFAM_ERROR); me = ME_BUS_SLAVE_PERMISSION_DENIED; break; } io_transaction.busError(me); return rc; } /* Local Variables: */ /* c-basic-offset: 4 */ /* End: */
Update vSBE to support latest centaur SBE image
Update vSBE to support latest centaur SBE image Change-Id: I6fb263f2203a3e2d07c6151d3a4355c4646cea97 Reviewed-on: http://gfw160.austin.ibm.com:8080/gerrit/6617 Reviewed-by: Thi N. Tran <[email protected]> Tested-by: Jenkins Server Reviewed-by: A. Patrick Williams III <[email protected]>
C++
apache-2.0
alvintpwang/hostboot,csmart/hostboot,open-power/hostboot,Over-enthusiastic/hostboot,csmart/hostboot,open-power/hostboot,open-power/hostboot,Over-enthusiastic/hostboot,csmart/hostboot,Over-enthusiastic/hostboot,csmart/hostboot,alvintpwang/hostboot,open-power/hostboot,Over-enthusiastic/hostboot,csmart/hostboot,Over-enthusiastic/hostboot,alvintpwang/hostboot,alvintpwang/hostboot,open-power/hostboot,alvintpwang/hostboot
700ab095928923a6db42f9873dd86ddacceb6441
src/DBase3File.cpp
src/DBase3File.cpp
#include "DBase3File.h" #include "utf8.h" #ifndef _WIN32 #include "../system/IConv.h" #endif #include <cstring> #include <cassert> #include <shapefil.h> #include <iostream> using namespace std; using namespace table; class table::DBase3Handle { public: DBase3Handle() { } ~DBase3Handle() { if (h) { DBFClose(h); } } void open(const std::string & fn) { h = DBFOpen(fn.c_str(), "rb"); if (!h) { cerr << "failed to open DBF " << fn << endl; } } int readIntegerAttribute(int rec, int field) { return DBFReadIntegerAttribute(h, rec, field); } double readDoubleAttribute(int rec, int field) { return DBFReadDoubleAttribute(h, rec, field); } std::string readStringAttribute(int rec, int field) { const char * tmp = DBFReadStringAttribute(h, rec, field); if (tmp) { #ifdef _WIN32 string output; while (!tmp) { utf8::append((unsigned char)*tmp, back_inserter(output)); tmp++; } return output; #else IConv iconv("ISO8859-1", "UTF-8"); string tmp2; if (iconv.convert(tmp, tmp2)) { return tmp2; } #endif } return ""; } bool readBoolAttribute(int rec, int field) { return DBFReadLogicalAttribute(h, rec, field); } bool isNull(int rec, int field) { return DBFIsAttributeNULL(h, rec, field); } unsigned int getRecordCount() { return h ? DBFGetRecordCount(h) : 0; } unsigned int getFieldCount() { return h ? DBFGetFieldCount(h) : 0; } string getFieldName(int field) { char fieldname[255]; DBFFieldType type = DBFGetFieldInfo(h, field, fieldname, 0, 0); return fieldname; } private: DBFHandle h = 0; }; DBase3File::DBase3File(const string & filename) { record_count = 0; openDBF(filename); } bool DBase3File::openDBF(const string & filename) { dbf = std::make_shared<DBase3Handle>(); dbf->open(filename); record_count = dbf->getRecordCount(); unsigned int field_count = dbf->getFieldCount(); for (unsigned int i = 0; i < field_count; i++) { string name = dbf->getFieldName(i); columns.push_back(std::make_shared<DBase3Column>(dbf, i, record_count, name)); } return true; } DBase3Column::DBase3Column(const std::shared_ptr<DBase3Handle> _dbf, int _column_index, int _num_rows, const std::string & _name) : Column(_name), dbf(_dbf), column_index(_column_index), num_rows(_num_rows) { } long long DBase3Column::getInt64(int i) const { if (i >= 0 && i < num_rows) { return dbf->readIntegerAttribute(i, column_index); } else { return 0; } } std::string DBase3Column::getText(int i) const { if (i >= 0 && i < num_rows) { return dbf->readStringAttribute(i, column_index); } else { return ""; } } double DBase3Column::getDouble(int i) const { if (i >= 0 && i < num_rows) { return dbf->readIntegerAttribute(i, column_index); } else { return 0; } } int DBase3Column::getInt(int i) const { if (i >= 0 && i < num_rows) { return dbf->readIntegerAttribute(i, column_index); } else { return 0; } }
#include "DBase3File.h" #include "utf8.h" #include <cstring> #include <cassert> #include <shapefil.h> #include <iostream> using namespace std; using namespace table; class table::DBase3Handle { public: DBase3Handle() { } ~DBase3Handle() { if (h) { DBFClose(h); } } void open(const std::string & fn) { h = DBFOpen(fn.c_str(), "rb"); if (!h) { cerr << "failed to open DBF " << fn << endl; } } int readIntegerAttribute(int rec, int field) { return DBFReadIntegerAttribute(h, rec, field); } double readDoubleAttribute(int rec, int field) { return DBFReadDoubleAttribute(h, rec, field); } std::string readStringAttribute(int rec, int field) { const char * tmp = DBFReadStringAttribute(h, rec, field); if (tmp) { string output; while (!tmp) { utf8::append((unsigned char)*tmp, back_inserter(output)); tmp++; } return output; } return ""; } bool readBoolAttribute(int rec, int field) { return DBFReadLogicalAttribute(h, rec, field); } bool isNull(int rec, int field) { return DBFIsAttributeNULL(h, rec, field); } unsigned int getRecordCount() { return h ? DBFGetRecordCount(h) : 0; } unsigned int getFieldCount() { return h ? DBFGetFieldCount(h) : 0; } string getFieldName(int field) { char fieldname[255]; DBFFieldType type = DBFGetFieldInfo(h, field, fieldname, 0, 0); return fieldname; } private: DBFHandle h = 0; }; DBase3File::DBase3File(const string & filename) { record_count = 0; openDBF(filename); } bool DBase3File::openDBF(const string & filename) { dbf = std::make_shared<DBase3Handle>(); dbf->open(filename); record_count = dbf->getRecordCount(); unsigned int field_count = dbf->getFieldCount(); for (unsigned int i = 0; i < field_count; i++) { string name = dbf->getFieldName(i); columns.push_back(std::make_shared<DBase3Column>(dbf, i, record_count, name)); } return true; } DBase3Column::DBase3Column(const std::shared_ptr<DBase3Handle> _dbf, int _column_index, int _num_rows, const std::string & _name) : Column(_name), dbf(_dbf), column_index(_column_index), num_rows(_num_rows) { } long long DBase3Column::getInt64(int i) const { if (i >= 0 && i < num_rows) { return dbf->readIntegerAttribute(i, column_index); } else { return 0; } } std::string DBase3Column::getText(int i) const { if (i >= 0 && i < num_rows) { return dbf->readStringAttribute(i, column_index); } else { return ""; } } double DBase3Column::getDouble(int i) const { if (i >= 0 && i < num_rows) { return dbf->readIntegerAttribute(i, column_index); } else { return 0; } } int DBase3Column::getInt(int i) const { if (i >= 0 && i < num_rows) { return dbf->readIntegerAttribute(i, column_index); } else { return 0; } }
remove dependency for IConv
remove dependency for IConv
C++
mit
Sometrik/graphlib,Sometrik/graphlib
7b8fd157b942b0feeccd99ac8ddf57466a10e984
main.cpp
main.cpp
#include <SDL.h> #include <GL/glcorearb.h> #include "imgui/imgui.h" #include "imgui_impl_sdl_gl3.h" #include "opengl.h" #include "renderer.h" #include "scene.h" #include "mysdl_dpi.h" #include <cstdio> #include <functional> extern "C" int main(int argc, char *argv[]) { MySDL_SetDPIAwareness_MustBeFirstWSICallInProgram(); if (SDL_Init(SDL_INIT_EVERYTHING)) { fprintf(stderr, "SDL_Init: %s\n", SDL_GetError()); exit(1); } // GL 4.1 for OS X support SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); #ifdef _DEBUG SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); #endif SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // Enable multisampling SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); // Enable SRGB SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1); // Don't need depth, it's done manually through the FBO. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0); // Scale window accoridng to DPI zoom int windowDpiScaledWidth, windowDpiScaledHeight; { int windowDpiUnscaledWidth = 1280, windowDpiUnscaledHeight = 720; float hdpi, vdpi, defaultDpi; MySDL_GetDisplayDPI(0, &hdpi, &vdpi, &defaultDpi); windowDpiScaledWidth = int(windowDpiUnscaledWidth * hdpi / defaultDpi); windowDpiScaledHeight = int(windowDpiUnscaledHeight * vdpi / defaultDpi); } Uint32 windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; #ifdef _WIN32 // highdpi doesn't work on Mac yet because we have to set the NSHighResolutionCapable Info.plist property windowFlags |= SDL_WINDOW_ALLOW_HIGHDPI; #endif SDL_Window* window = SDL_CreateWindow( "fictional-doodle", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowDpiScaledWidth, windowDpiScaledHeight, windowFlags); if (!window) { fprintf(stderr, "SDL_CreateWindow: %s\n", SDL_GetError()); exit(1); } SDL_GLContext glctx = SDL_GL_CreateContext(window); if (!glctx) { fprintf(stderr, "SDL_GL_CreateContext: %s\n", SDL_GetError()); exit(1); } InitGL(); Renderer renderer{}; InitRenderer(&renderer); ImGui_ImplSdlGL3_Init(window); // Initial resize to create framebuffers { int drawableWidth, drawableHeight; SDL_GL_GetDrawableSize(window, &drawableWidth, &drawableHeight); int windowWidth, windowHeight; SDL_GetWindowSize(window, &windowWidth, &windowHeight); int numSamples; SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &numSamples); ResizeRenderer(&renderer,windowWidth, windowHeight, drawableWidth, drawableHeight, numSamples); } Scene scene{}; InitScene(&scene); bool guiFocusEnabled = true; auto updateGuiFocus = [&] { if (guiFocusEnabled) { SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "0"); SDL_SetRelativeMouseMode(SDL_FALSE); scene.EnableCamera = false; } else { // Warping mouse seems necessary to acquire mouse focus for OS X track pad. SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "1"); SDL_SetRelativeMouseMode(SDL_TRUE); // Prevent initial mouse warp state change from reorienting the camera. SDL_GetRelativeMouseState(NULL, NULL); scene.EnableCamera = true; } }; updateGuiFocus(); Uint32 lastTicks = SDL_GetTicks(); // main loop for (;;) { SDL_Event ev; while (SDL_PollEvent(&ev)) { if (guiFocusEnabled) { ImGui_ImplSdlGL3_ProcessEvent(&ev); } if (ev.type == SDL_QUIT) { goto endmainloop; } else if (ev.type == SDL_WINDOWEVENT) { if (ev.window.event == SDL_WINDOWEVENT_RESIZED) { int drawableWidth, drawableHeight; SDL_GL_GetDrawableSize(window, &drawableWidth, &drawableHeight); int windowWidth, windowHeight; SDL_GetWindowSize(window, &windowWidth, &windowHeight); int numSamples; SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &numSamples); ResizeRenderer(&renderer, windowWidth, windowHeight, drawableWidth, drawableHeight, numSamples); } } else if (ev.type == SDL_KEYDOWN) { if (ev.key.keysym.sym == SDLK_ESCAPE) { guiFocusEnabled = !guiFocusEnabled; updateGuiFocus(); } else if (ev.key.keysym.sym == SDLK_RETURN) { if (ev.key.keysym.mod & KMOD_ALT) { Uint32 wflags = SDL_GetWindowFlags(window); if (wflags & SDL_WINDOW_FULLSCREEN_DESKTOP) { SDL_SetWindowFullscreen(window, 0); } else { SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP); } } } } } ImGui_ImplSdlGL3_NewFrame(guiFocusEnabled); Uint32 currTicks = SDL_GetTicks(); Uint32 deltaTicks = currTicks - lastTicks; UpdateScene(&scene, window, deltaTicks); PaintRenderer(&renderer, window, &scene); // Bind 0 to the draw framebuffer before swapping the window, because otherwise in Mac OS X nothing will happen. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); SDL_GL_SwapWindow(window); lastTicks = currTicks; } endmainloop: ImGui_ImplSdlGL3_Shutdown(); SDL_GL_DeleteContext(glctx); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
#include <SDL.h> #include <GL/glcorearb.h> #include "imgui/imgui.h" #include "imgui_impl_sdl_gl3.h" #include "opengl.h" #include "renderer.h" #include "scene.h" #include "mysdl_dpi.h" #include <cstdio> #include <functional> extern "C" int main(int argc, char *argv[]) { MySDL_SetDPIAwareness_MustBeFirstWSICallInProgram(); if (SDL_Init(SDL_INIT_EVERYTHING)) { fprintf(stderr, "SDL_Init: %s\n", SDL_GetError()); exit(1); } // GL 4.1 for OS X support SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); #ifdef _DEBUG SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); #endif SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // Enable multisampling SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); // Enable SRGB SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1); // Don't need depth, it's done manually through the FBO. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0); // Scale window accoridng to DPI zoom int windowDpiScaledWidth, windowDpiScaledHeight; { int windowDpiUnscaledWidth = 1280, windowDpiUnscaledHeight = 720; float hdpi, vdpi, defaultDpi; MySDL_GetDisplayDPI(0, &hdpi, &vdpi, &defaultDpi); windowDpiScaledWidth = int(windowDpiUnscaledWidth * hdpi / defaultDpi); windowDpiScaledHeight = int(windowDpiUnscaledHeight * vdpi / defaultDpi); } Uint32 windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; #ifdef _WIN32 // highdpi doesn't work on Mac yet because we have to set the NSHighResolutionCapable Info.plist property windowFlags |= SDL_WINDOW_ALLOW_HIGHDPI; #endif SDL_Window* window = SDL_CreateWindow( "fictional-doodle", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowDpiScaledWidth, windowDpiScaledHeight, windowFlags); if (!window) { fprintf(stderr, "SDL_CreateWindow: %s\n", SDL_GetError()); exit(1); } SDL_GLContext glctx = SDL_GL_CreateContext(window); if (!glctx) { fprintf(stderr, "SDL_GL_CreateContext: %s\n", SDL_GetError()); exit(1); } InitGL(); Renderer renderer{}; InitRenderer(&renderer); ImGui_ImplSdlGL3_Init(window); // Initial resize to create framebuffers { int drawableWidth, drawableHeight; SDL_GL_GetDrawableSize(window, &drawableWidth, &drawableHeight); int windowWidth, windowHeight; SDL_GetWindowSize(window, &windowWidth, &windowHeight); int numSamples; SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &numSamples); ResizeRenderer(&renderer,windowWidth, windowHeight, drawableWidth, drawableHeight, numSamples); } Scene scene{}; InitScene(&scene); bool guiFocusEnabled = true; auto updateGuiFocus = [&] { if (guiFocusEnabled) { //SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "0"); SDL_SetRelativeMouseMode(SDL_FALSE); scene.EnableCamera = false; } else { // Warping mouse seems necessary to acquire mouse focus for OS X track pad. //SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "1"); SDL_SetRelativeMouseMode(SDL_TRUE); // Prevent initial mouse warp state change from reorienting the camera. SDL_GetRelativeMouseState(NULL, NULL); scene.EnableCamera = true; } }; updateGuiFocus(); Uint32 lastTicks = SDL_GetTicks(); // main loop for (;;) { SDL_Event ev; while (SDL_PollEvent(&ev)) { if (guiFocusEnabled) { ImGui_ImplSdlGL3_ProcessEvent(&ev); } if (ev.type == SDL_QUIT) { goto endmainloop; } else if (ev.type == SDL_WINDOWEVENT) { if (ev.window.event == SDL_WINDOWEVENT_RESIZED) { int drawableWidth, drawableHeight; SDL_GL_GetDrawableSize(window, &drawableWidth, &drawableHeight); int windowWidth, windowHeight; SDL_GetWindowSize(window, &windowWidth, &windowHeight); int numSamples; SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &numSamples); ResizeRenderer(&renderer, windowWidth, windowHeight, drawableWidth, drawableHeight, numSamples); } } else if (ev.type == SDL_KEYDOWN) { if (ev.key.keysym.sym == SDLK_ESCAPE) { guiFocusEnabled = !guiFocusEnabled; updateGuiFocus(); } else if (ev.key.keysym.sym == SDLK_RETURN) { if (ev.key.keysym.mod & KMOD_ALT) { Uint32 wflags = SDL_GetWindowFlags(window); if (wflags & SDL_WINDOW_FULLSCREEN_DESKTOP) { SDL_SetWindowFullscreen(window, 0); } else { SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP); } } } } } ImGui_ImplSdlGL3_NewFrame(guiFocusEnabled); Uint32 currTicks = SDL_GetTicks(); Uint32 deltaTicks = currTicks - lastTicks; UpdateScene(&scene, window, deltaTicks); PaintRenderer(&renderer, window, &scene); // Bind 0 to the draw framebuffer before swapping the window, because otherwise in Mac OS X nothing will happen. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); SDL_GL_SwapWindow(window); lastTicks = currTicks; } endmainloop: ImGui_ImplSdlGL3_Shutdown(); SDL_GL_DeleteContext(glctx); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
remove mouse warping to smooth camera rotation
remove mouse warping to smooth camera rotation While technically still necessary for OS X if the application were to launch in relative mouse mode, because we start with the GUI focused, the transition into relative mouse mode works without warping.
C++
mit
nlguillemot/fictional-doodle,nlguillemot/fictional-doodle
43a722e52d469561f4d93b21b03ba2d47a5c4101
lib/XRay/InstrumentationMap.cpp
lib/XRay/InstrumentationMap.cpp
//===- InstrumentationMap.cpp - XRay Instrumentation Map ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implementation of the InstrumentationMap type for XRay sleds. // //===----------------------------------------------------------------------===// #include "llvm/XRay/InstrumentationMap.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/None.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Triple.h" #include "llvm/ADT/Twine.h" #include "llvm/Object/Binary.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/DataExtractor.h" #include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/YAMLTraits.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <system_error> #include <vector> using namespace llvm; using namespace xray; Optional<int32_t> InstrumentationMap::getFunctionId(uint64_t Addr) const { auto I = FunctionIds.find(Addr); if (I != FunctionIds.end()) return I->second; return None; } Optional<uint64_t> InstrumentationMap::getFunctionAddr(int32_t FuncId) const { auto I = FunctionAddresses.find(FuncId); if (I != FunctionAddresses.end()) return I->second; return None; } using RelocMap = DenseMap<uint64_t, uint64_t>; static Error loadObj(StringRef Filename, object::OwningBinary<object::ObjectFile> &ObjFile, InstrumentationMap::SledContainer &Sleds, InstrumentationMap::FunctionAddressMap &FunctionAddresses, InstrumentationMap::FunctionAddressReverseMap &FunctionIds) { InstrumentationMap Map; // Find the section named "xray_instr_map". if ((!ObjFile.getBinary()->isELF() && !ObjFile.getBinary()->isMachO()) || !(ObjFile.getBinary()->getArch() == Triple::x86_64 || ObjFile.getBinary()->getArch() == Triple::ppc64le)) return make_error<StringError>( "File format not supported (only does ELF and Mach-O little endian 64-bit).", std::make_error_code(std::errc::not_supported)); StringRef Contents = ""; const auto &Sections = ObjFile.getBinary()->sections(); auto I = llvm::find_if(Sections, [&](object::SectionRef Section) { StringRef Name = ""; if (Section.getName(Name)) return false; return Name == "xray_instr_map"; }); if (I == Sections.end()) return make_error<StringError>( "Failed to find XRay instrumentation map.", std::make_error_code(std::errc::executable_format_error)); if (I->getContents(Contents)) return errorCodeToError( std::make_error_code(std::errc::executable_format_error)); RelocMap Relocs; if (ObjFile.getBinary()->isELF()) { uint32_t RelrRelocationType = [](object::ObjectFile *ObjFile) { if (const auto *ELFObj = dyn_cast<object::ELF32LEObjectFile>(ObjFile)) return ELFObj->getELFFile()->getRelrRelocationType(); else if (const auto *ELFObj = dyn_cast<object::ELF32BEObjectFile>(ObjFile)) return ELFObj->getELFFile()->getRelrRelocationType(); else if (const auto *ELFObj = dyn_cast<object::ELF64LEObjectFile>(ObjFile)) return ELFObj->getELFFile()->getRelrRelocationType(); else if (const auto *ELFObj = dyn_cast<object::ELF64BEObjectFile>(ObjFile)) return ELFObj->getELFFile()->getRelrRelocationType(); else return static_cast<uint32_t>(0); }(ObjFile.getBinary()); for (const object::SectionRef &Section : Sections) { for (const object::RelocationRef &Reloc : Section.relocations()) { if (Reloc.getType() != RelrRelocationType) continue; if (auto AddendOrErr = object::ELFRelocationRef(Reloc).getAddend()) Relocs.insert({Reloc.getOffset(), *AddendOrErr}); } } } // Copy the instrumentation map data into the Sleds data structure. auto C = Contents.bytes_begin(); static constexpr size_t ELF64SledEntrySize = 32; if ((C - Contents.bytes_end()) % ELF64SledEntrySize != 0) return make_error<StringError>( Twine("Instrumentation map entries not evenly divisible by size of " "an XRay sled entry in ELF64."), std::make_error_code(std::errc::executable_format_error)); auto RelocateOrElse = [&](uint32_t Offset, uint64_t Address) { if (!Address) { uint64_t A = I->getAddress() + C - Contents.bytes_begin() + Offset; RelocMap::const_iterator R = Relocs.find(A); if (R != Relocs.end()) return R->second; } return Address; }; int32_t FuncId = 1; uint64_t CurFn = 0; for (; C != Contents.bytes_end(); C += ELF64SledEntrySize) { DataExtractor Extractor( StringRef(reinterpret_cast<const char *>(C), ELF64SledEntrySize), true, 8); Sleds.push_back({}); auto &Entry = Sleds.back(); uint32_t OffsetPtr = 0; Entry.Address = RelocateOrElse(OffsetPtr, Extractor.getU64(&OffsetPtr)); Entry.Function = RelocateOrElse(OffsetPtr, Extractor.getU64(&OffsetPtr)); auto Kind = Extractor.getU8(&OffsetPtr); static constexpr SledEntry::FunctionKinds Kinds[] = { SledEntry::FunctionKinds::ENTRY, SledEntry::FunctionKinds::EXIT, SledEntry::FunctionKinds::TAIL, SledEntry::FunctionKinds::LOG_ARGS_ENTER, SledEntry::FunctionKinds::CUSTOM_EVENT}; if (Kind >= sizeof(Kinds)) return errorCodeToError( std::make_error_code(std::errc::executable_format_error)); Entry.Kind = Kinds[Kind]; Entry.AlwaysInstrument = Extractor.getU8(&OffsetPtr) != 0; // We do replicate the function id generation scheme implemented in the // XRay runtime. // FIXME: Figure out how to keep this consistent with the XRay runtime. if (CurFn == 0) { CurFn = Entry.Function; FunctionAddresses[FuncId] = Entry.Function; FunctionIds[Entry.Function] = FuncId; } if (Entry.Function != CurFn) { ++FuncId; CurFn = Entry.Function; FunctionAddresses[FuncId] = Entry.Function; FunctionIds[Entry.Function] = FuncId; } } return Error::success(); } static Error loadYAML(int Fd, size_t FileSize, StringRef Filename, InstrumentationMap::SledContainer &Sleds, InstrumentationMap::FunctionAddressMap &FunctionAddresses, InstrumentationMap::FunctionAddressReverseMap &FunctionIds) { std::error_code EC; sys::fs::mapped_file_region MappedFile( Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC); if (EC) return make_error<StringError>( Twine("Failed memory-mapping file '") + Filename + "'.", EC); std::vector<YAMLXRaySledEntry> YAMLSleds; yaml::Input In(StringRef(MappedFile.data(), MappedFile.size())); In >> YAMLSleds; if (In.error()) return make_error<StringError>( Twine("Failed loading YAML document from '") + Filename + "'.", In.error()); Sleds.reserve(YAMLSleds.size()); for (const auto &Y : YAMLSleds) { FunctionAddresses[Y.FuncId] = Y.Function; FunctionIds[Y.Function] = Y.FuncId; Sleds.push_back( SledEntry{Y.Address, Y.Function, Y.Kind, Y.AlwaysInstrument}); } return Error::success(); } // FIXME: Create error types that encapsulate a bit more information than what // StringError instances contain. Expected<InstrumentationMap> llvm::xray::loadInstrumentationMap(StringRef Filename) { // At this point we assume the file is an object file -- and if that doesn't // work, we treat it as YAML. // FIXME: Extend to support non-ELF and non-x86_64 binaries. InstrumentationMap Map; auto ObjectFileOrError = object::ObjectFile::createObjectFile(Filename); if (!ObjectFileOrError) { auto E = ObjectFileOrError.takeError(); // We try to load it as YAML if the ELF load didn't work. int Fd; if (sys::fs::openFileForRead(Filename, Fd)) return std::move(E); uint64_t FileSize; if (sys::fs::file_size(Filename, FileSize)) return std::move(E); // If the file is empty, we return the original error. if (FileSize == 0) return std::move(E); // From this point on the errors will be only for the YAML parts, so we // consume the errors at this point. consumeError(std::move(E)); if (auto E = loadYAML(Fd, FileSize, Filename, Map.Sleds, Map.FunctionAddresses, Map.FunctionIds)) return std::move(E); } else if (auto E = loadObj(Filename, *ObjectFileOrError, Map.Sleds, Map.FunctionAddresses, Map.FunctionIds)) { return std::move(E); } return Map; }
//===- InstrumentationMap.cpp - XRay Instrumentation Map ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implementation of the InstrumentationMap type for XRay sleds. // //===----------------------------------------------------------------------===// #include "llvm/XRay/InstrumentationMap.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/None.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Triple.h" #include "llvm/ADT/Twine.h" #include "llvm/Object/Binary.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/DataExtractor.h" #include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/YAMLTraits.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <system_error> #include <vector> using namespace llvm; using namespace xray; Optional<int32_t> InstrumentationMap::getFunctionId(uint64_t Addr) const { auto I = FunctionIds.find(Addr); if (I != FunctionIds.end()) return I->second; return None; } Optional<uint64_t> InstrumentationMap::getFunctionAddr(int32_t FuncId) const { auto I = FunctionAddresses.find(FuncId); if (I != FunctionAddresses.end()) return I->second; return None; } using RelocMap = DenseMap<uint64_t, uint64_t>; static Error loadObj(StringRef Filename, object::OwningBinary<object::ObjectFile> &ObjFile, InstrumentationMap::SledContainer &Sleds, InstrumentationMap::FunctionAddressMap &FunctionAddresses, InstrumentationMap::FunctionAddressReverseMap &FunctionIds) { InstrumentationMap Map; // Find the section named "xray_instr_map". if ((!ObjFile.getBinary()->isELF() && !ObjFile.getBinary()->isMachO()) || !(ObjFile.getBinary()->getArch() == Triple::x86_64 || ObjFile.getBinary()->getArch() == Triple::ppc64le)) return make_error<StringError>( "File format not supported (only does ELF and Mach-O little endian 64-bit).", std::make_error_code(std::errc::not_supported)); StringRef Contents = ""; const auto &Sections = ObjFile.getBinary()->sections(); auto I = llvm::find_if(Sections, [&](object::SectionRef Section) { StringRef Name = ""; if (Section.getName(Name)) return false; return Name == "xray_instr_map"; }); if (I == Sections.end()) return make_error<StringError>( "Failed to find XRay instrumentation map.", std::make_error_code(std::errc::executable_format_error)); if (I->getContents(Contents)) return errorCodeToError( std::make_error_code(std::errc::executable_format_error)); RelocMap Relocs; if (ObjFile.getBinary()->isELF()) { uint32_t RelrRelocationType = [](object::ObjectFile *ObjFile) { if (const auto *ELFObj = dyn_cast<object::ELF32LEObjectFile>(ObjFile)) return ELFObj->getELFFile()->getRelrRelocationType(); else if (const auto *ELFObj = dyn_cast<object::ELF32BEObjectFile>(ObjFile)) return ELFObj->getELFFile()->getRelrRelocationType(); else if (const auto *ELFObj = dyn_cast<object::ELF64LEObjectFile>(ObjFile)) return ELFObj->getELFFile()->getRelrRelocationType(); else if (const auto *ELFObj = dyn_cast<object::ELF64BEObjectFile>(ObjFile)) return ELFObj->getELFFile()->getRelrRelocationType(); else return static_cast<uint32_t>(0); }(ObjFile.getBinary()); for (const object::SectionRef &Section : Sections) { for (const object::RelocationRef &Reloc : Section.relocations()) { if (Reloc.getType() != RelrRelocationType) continue; if (auto AddendOrErr = object::ELFRelocationRef(Reloc).getAddend()) Relocs.insert({Reloc.getOffset(), *AddendOrErr}); } } } // Copy the instrumentation map data into the Sleds data structure. auto C = Contents.bytes_begin(); static constexpr size_t ELF64SledEntrySize = 32; if ((C - Contents.bytes_end()) % ELF64SledEntrySize != 0) return make_error<StringError>( Twine("Instrumentation map entries not evenly divisible by size of " "an XRay sled entry in ELF64."), std::make_error_code(std::errc::executable_format_error)); auto RelocateOrElse = [&](uint32_t Offset, uint64_t Address) { if (!Address) { uint64_t A = I->getAddress() + C - Contents.bytes_begin() + Offset; RelocMap::const_iterator R = Relocs.find(A); if (R != Relocs.end()) return R->second; } return Address; }; int32_t FuncId = 1; uint64_t CurFn = 0; for (; C != Contents.bytes_end(); C += ELF64SledEntrySize) { DataExtractor Extractor( StringRef(reinterpret_cast<const char *>(C), ELF64SledEntrySize), true, 8); Sleds.push_back({}); auto &Entry = Sleds.back(); uint32_t OffsetPtr = 0; uint32_t AddrPtr = OffsetPtr; Entry.Address = RelocateOrElse(AddrOff, Extractor.getU64(&OffsetPtr)); uint32_t FuncPtr = OffsetPtr; Entry.Function = RelocateOrElse(FuncOff, Extractor.getU64(&OffsetPtr)); auto Kind = Extractor.getU8(&OffsetPtr); static constexpr SledEntry::FunctionKinds Kinds[] = { SledEntry::FunctionKinds::ENTRY, SledEntry::FunctionKinds::EXIT, SledEntry::FunctionKinds::TAIL, SledEntry::FunctionKinds::LOG_ARGS_ENTER, SledEntry::FunctionKinds::CUSTOM_EVENT}; if (Kind >= sizeof(Kinds)) return errorCodeToError( std::make_error_code(std::errc::executable_format_error)); Entry.Kind = Kinds[Kind]; Entry.AlwaysInstrument = Extractor.getU8(&OffsetPtr) != 0; // We do replicate the function id generation scheme implemented in the // XRay runtime. // FIXME: Figure out how to keep this consistent with the XRay runtime. if (CurFn == 0) { CurFn = Entry.Function; FunctionAddresses[FuncId] = Entry.Function; FunctionIds[Entry.Function] = FuncId; } if (Entry.Function != CurFn) { ++FuncId; CurFn = Entry.Function; FunctionAddresses[FuncId] = Entry.Function; FunctionIds[Entry.Function] = FuncId; } } return Error::success(); } static Error loadYAML(int Fd, size_t FileSize, StringRef Filename, InstrumentationMap::SledContainer &Sleds, InstrumentationMap::FunctionAddressMap &FunctionAddresses, InstrumentationMap::FunctionAddressReverseMap &FunctionIds) { std::error_code EC; sys::fs::mapped_file_region MappedFile( Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC); if (EC) return make_error<StringError>( Twine("Failed memory-mapping file '") + Filename + "'.", EC); std::vector<YAMLXRaySledEntry> YAMLSleds; yaml::Input In(StringRef(MappedFile.data(), MappedFile.size())); In >> YAMLSleds; if (In.error()) return make_error<StringError>( Twine("Failed loading YAML document from '") + Filename + "'.", In.error()); Sleds.reserve(YAMLSleds.size()); for (const auto &Y : YAMLSleds) { FunctionAddresses[Y.FuncId] = Y.Function; FunctionIds[Y.Function] = Y.FuncId; Sleds.push_back( SledEntry{Y.Address, Y.Function, Y.Kind, Y.AlwaysInstrument}); } return Error::success(); } // FIXME: Create error types that encapsulate a bit more information than what // StringError instances contain. Expected<InstrumentationMap> llvm::xray::loadInstrumentationMap(StringRef Filename) { // At this point we assume the file is an object file -- and if that doesn't // work, we treat it as YAML. // FIXME: Extend to support non-ELF and non-x86_64 binaries. InstrumentationMap Map; auto ObjectFileOrError = object::ObjectFile::createObjectFile(Filename); if (!ObjectFileOrError) { auto E = ObjectFileOrError.takeError(); // We try to load it as YAML if the ELF load didn't work. int Fd; if (sys::fs::openFileForRead(Filename, Fd)) return std::move(E); uint64_t FileSize; if (sys::fs::file_size(Filename, FileSize)) return std::move(E); // If the file is empty, we return the original error. if (FileSize == 0) return std::move(E); // From this point on the errors will be only for the YAML parts, so we // consume the errors at this point. consumeError(std::move(E)); if (auto E = loadYAML(Fd, FileSize, Filename, Map.Sleds, Map.FunctionAddresses, Map.FunctionIds)) return std::move(E); } else if (auto E = loadObj(Filename, *ObjectFileOrError, Map.Sleds, Map.FunctionAddresses, Map.FunctionIds)) { return std::move(E); } return Map; }
Store offset pointers in temporaries
[llvm-xray] Store offset pointers in temporaries DataExtractor::getU64 modifies the OffsetPtr which also pass to RelocateOrElse which breaks on Windows. This addresses the issue introduced in r349120. Differential Revision: https://reviews.llvm.org/D55689 git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@349129 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm
0d4471f522a802efb32c76f15145f68a5cd47628
src/GUIManager.cpp
src/GUIManager.cpp
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <cstdlib> #include <iostream> #include <cmath> #include <cstring> #include <string> #include <sstream> #include <ctime> #include <vector> #include <set> #include "GUIManager.hpp" // Public Functions GUIManager::GUIManager() { } void GUIManager::init() { cv::namedWindow("FRC Team 3341 Targeting", 0); } void GUIManager::setImage(cv::Mat inputImage) { image = inputImage; } void GUIManager::setImageText(std::string imageText) { cv::putText(image, imageText, cv::Point(0, image.rows - 5), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0.0, 0.0, 255.0, 0.0), 1); } void GUIManager::show(bool isFile) { //isFile determines if image should be shown indefinitely //in File Mode, the main loop only runs once rather than continuously cv::imshow("FRC Team 3341 Targeting", image); if(isFile) cv::waitKey(0); else cv::waitKey(10); }
Update GuiManager.cpp
Update GuiManager.cpp
C++
mit
sarthak171/cv-2017,sarthak171/cv-2017,Nohpyr/cv-2017,compvision/cv-2017,gastaunda/cv-2017,gastaunda/cv-2017,sarthak171/cv-2017,Nohpyr/cv-2017,gastaunda/cv-2017,compvision/cv-2017,compvision/cv-2017,Nohpyr/cv-2017
44c34fb55a2952c183ee9703455b90b9cbd9c67e
src/Game/Clock.cpp
src/Game/Clock.cpp
#include "Game/Clock.h" #include <array> #include <chrono> using namespace std::chrono_literals; #include <cassert> #include <limits> #include <sstream> #include "Game/Board.h" #include "Game/Game_Result.h" Clock::Clock(seconds duration_seconds, size_t moves_to_reset, seconds increment_seconds, Time_Reset_Method reset_method, Piece_Color starting_turn, std::chrono::system_clock::time_point previous_start_time) noexcept : timers({duration_seconds, duration_seconds}), initial_start_time(duration_seconds), increment_time({increment_seconds, increment_seconds}), move_count_reset(moves_to_reset), method_of_reset(reset_method), whose_turn(starting_turn), game_start_date_time(previous_start_time) { } Game_Result Clock::punch(const Board& board) noexcept { if( ! is_in_use() || ! is_running()) { return {}; } auto time_this_punch = std::chrono::steady_clock::now(); auto player_index = static_cast<int>(whose_turn); timers[player_index] -= (time_this_punch - time_previous_punch); time_previous_punch = time_this_punch; whose_turn = opposite(whose_turn); if(time_left(opposite(whose_turn)) < 0.0s) { if(board.enough_material_to_checkmate(whose_turn)) { return Game_Result(whose_turn, Game_Result_Type::TIME_FORFEIT); } else { return Game_Result(Winner_Color::NONE, Game_Result_Type::TIME_EXPIRED_WITH_INSUFFICIENT_MATERIAL); } } else { if(++moves_since_clock_reset[player_index] == move_count_reset) { if(method_of_reset == Time_Reset_Method::ADDITION) { timers[player_index] += initial_start_time; } else { timers[player_index] = initial_start_time; } moves_since_clock_reset[player_index] = 0; } timers[player_index] += increment_time[player_index]; return {}; } } void Clock::unpunch() noexcept { moves_since_clock_reset[static_cast<int>(whose_turn)] -= 1; moves_since_clock_reset[static_cast<int>(opposite(whose_turn))] -= 1; punch({}); } void Clock::stop() noexcept { auto time_stop = std::chrono::steady_clock::now(); timers[static_cast<int>(whose_turn)] -= (time_stop - time_previous_punch); clocks_running = false; } void Clock::start() noexcept { static const auto default_game_start_date_time = std::chrono::system_clock::time_point{}; time_previous_punch = std::chrono::steady_clock::now(); if(game_start_date_time == default_game_start_date_time) { game_start_date_time = std::chrono::system_clock::now(); } clocks_running = true; } Clock::seconds Clock::time_left(Piece_Color color) const noexcept { if( ! is_in_use()) { return 0.0s; } if(whose_turn != color || ! clocks_running) { return timers[static_cast<int>(color)]; } else { auto now = std::chrono::steady_clock::now(); return timers[static_cast<int>(color)] - (now - time_previous_punch); } } size_t Clock::moves_until_reset(Piece_Color color) const noexcept { if(move_count_reset > 0) { return move_count_reset - moves_since_clock_reset[static_cast<int>(color)]; } else { return std::numeric_limits<int>::max(); } } Piece_Color Clock::running_for() const noexcept { return whose_turn; } void Clock::set_time(Piece_Color player, seconds new_time_seconds) noexcept { timers[static_cast<int>(player)] = new_time_seconds; time_previous_punch = std::chrono::steady_clock::now(); } void Clock::set_increment(Piece_Color player, seconds new_increment_time_seconds) noexcept { increment_time[static_cast<int>(player)] = new_increment_time_seconds; } void Clock::set_next_time_reset(Piece_Color player, size_t moves_to_reset) noexcept { if(moves_to_reset == 0) { move_count_reset = 0; } else { move_count_reset = moves_since_clock_reset[static_cast<int>(player)] + moves_to_reset; } } Clock::seconds Clock::running_time_left() const noexcept { return time_left(running_for()); } bool Clock::is_running() const noexcept { return clocks_running; } std::chrono::system_clock::time_point Clock::game_start_date_and_time() const noexcept { return game_start_date_time; } size_t Clock::moves_per_time_period() const noexcept { return move_count_reset; } Time_Reset_Method Clock::reset_mode() const noexcept { return method_of_reset; } Clock::seconds Clock::initial_time() const noexcept { return initial_start_time; } Clock::seconds Clock::increment(Piece_Color color) const noexcept { return increment_time[static_cast<int>(color)]; } bool Clock::is_in_use() const noexcept { return initial_time() > 0.0s || increment(Piece_Color::WHITE) > 0.0s || increment(Piece_Color::BLACK) > 0.0s; } std::string Clock::time_control_string() const noexcept { std::ostringstream time_control_spec; if(moves_per_time_period() > 0) { time_control_spec << moves_per_time_period() << '/'; } time_control_spec << initial_time().count(); if(increment(Piece_Color::WHITE) > 0.0s) { time_control_spec << '+' << increment(Piece_Color::WHITE).count(); } return time_control_spec.str(); }
#include "Game/Clock.h" #include <array> #include <chrono> using namespace std::chrono_literals; #include <cassert> #include <limits> #include <sstream> #include "Game/Board.h" #include "Game/Game_Result.h" Clock::Clock(seconds duration_seconds, size_t moves_to_reset, seconds increment_seconds, Time_Reset_Method reset_method, Piece_Color starting_turn, std::chrono::system_clock::time_point previous_start_time) noexcept : timers({duration_seconds, duration_seconds}), initial_start_time(duration_seconds), increment_time({increment_seconds, increment_seconds}), move_count_reset(moves_to_reset), method_of_reset(reset_method), whose_turn(starting_turn), game_start_date_time(previous_start_time) { } Game_Result Clock::punch(const Board& board) noexcept { if( ! is_in_use() || ! is_running()) { return {}; } auto time_this_punch = std::chrono::steady_clock::now(); auto player_index = static_cast<int>(whose_turn); timers[player_index] -= (time_this_punch - time_previous_punch); time_previous_punch = time_this_punch; whose_turn = opposite(whose_turn); auto punch_result = Game_Result{}; if(time_left(opposite(whose_turn)) < 0.0s) { if(board.enough_material_to_checkmate(whose_turn)) { punch_result = Game_Result(whose_turn, Game_Result_Type::TIME_FORFEIT); } else { punch_result = Game_Result(Winner_Color::NONE, Game_Result_Type::TIME_EXPIRED_WITH_INSUFFICIENT_MATERIAL); } } if(++moves_since_clock_reset[player_index] == move_count_reset) { if(method_of_reset == Time_Reset_Method::ADDITION) { timers[player_index] += initial_start_time; } else { timers[player_index] = initial_start_time; } moves_since_clock_reset[player_index] = 0; } timers[player_index] += increment_time[player_index]; return punch_result; } void Clock::unpunch() noexcept { moves_since_clock_reset[static_cast<int>(whose_turn)] -= 1; moves_since_clock_reset[static_cast<int>(opposite(whose_turn))] -= 1; punch({}); } void Clock::stop() noexcept { auto time_stop = std::chrono::steady_clock::now(); timers[static_cast<int>(whose_turn)] -= (time_stop - time_previous_punch); clocks_running = false; } void Clock::start() noexcept { static const auto default_game_start_date_time = std::chrono::system_clock::time_point{}; time_previous_punch = std::chrono::steady_clock::now(); if(game_start_date_time == default_game_start_date_time) { game_start_date_time = std::chrono::system_clock::now(); } clocks_running = true; } Clock::seconds Clock::time_left(Piece_Color color) const noexcept { if( ! is_in_use()) { return 0.0s; } if(whose_turn != color || ! clocks_running) { return timers[static_cast<int>(color)]; } else { auto now = std::chrono::steady_clock::now(); return timers[static_cast<int>(color)] - (now - time_previous_punch); } } size_t Clock::moves_until_reset(Piece_Color color) const noexcept { if(move_count_reset > 0) { return move_count_reset - moves_since_clock_reset[static_cast<int>(color)]; } else { return std::numeric_limits<int>::max(); } } Piece_Color Clock::running_for() const noexcept { return whose_turn; } void Clock::set_time(Piece_Color player, seconds new_time_seconds) noexcept { timers[static_cast<int>(player)] = new_time_seconds; time_previous_punch = std::chrono::steady_clock::now(); } void Clock::set_increment(Piece_Color player, seconds new_increment_time_seconds) noexcept { increment_time[static_cast<int>(player)] = new_increment_time_seconds; } void Clock::set_next_time_reset(Piece_Color player, size_t moves_to_reset) noexcept { if(moves_to_reset == 0) { move_count_reset = 0; } else { move_count_reset = moves_since_clock_reset[static_cast<int>(player)] + moves_to_reset; } } Clock::seconds Clock::running_time_left() const noexcept { return time_left(running_for()); } bool Clock::is_running() const noexcept { return clocks_running; } std::chrono::system_clock::time_point Clock::game_start_date_and_time() const noexcept { return game_start_date_time; } size_t Clock::moves_per_time_period() const noexcept { return move_count_reset; } Time_Reset_Method Clock::reset_mode() const noexcept { return method_of_reset; } Clock::seconds Clock::initial_time() const noexcept { return initial_start_time; } Clock::seconds Clock::increment(Piece_Color color) const noexcept { return increment_time[static_cast<int>(color)]; } bool Clock::is_in_use() const noexcept { return initial_time() > 0.0s || increment(Piece_Color::WHITE) > 0.0s || increment(Piece_Color::BLACK) > 0.0s; } std::string Clock::time_control_string() const noexcept { std::ostringstream time_control_spec; if(moves_per_time_period() > 0) { time_control_spec << moves_per_time_period() << '/'; } time_control_spec << initial_time().count(); if(increment(Piece_Color::WHITE) > 0.0s) { time_control_spec << '+' << increment(Piece_Color::WHITE).count(); } return time_control_spec.str(); }
Adjust clocks after punch even if time expired
Adjust clocks after punch even if time expired Add increments or reset time due enough moves made even if the result returned by punch will be a game-ending Game_Result. Games with GUIs and games over the internet ignore clock.punch() results.
C++
mit
MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess
f344732386f5740518511fb34a0a9656ef5063f6
main.cpp
main.cpp
/* * This file is part of Playslave-C++. * Playslave-C++ is licenced under MIT License. See LICENSE.txt for more details. */ #include <thread> #include <chrono> #include <iostream> #include "cmd.h" #include "io.hpp" #include "constants.h" /* LOOP_NSECS */ #include "messages.h" /* MSG_xyz */ #include "player.h" static void ListOutputDevices(); static std::string DeviceId(int argc, char *argv[]); static void MainLoop(Player &player); static void RegisterListeners(Player &p); const static std::unordered_map<State, std::string> STATES = { { State::EJECTED, "Ejected" }, { State::STOPPED, "Stopped" }, { State::PLAYING, "Playing" }, { State::QUITTING, "Quitting" } }; /** * Lists on stdout all sound devices to which the audio output may connect. * This is mainly for the benefit of the end user. */ static void ListOutputDevices() { for (auto device : AudioOutput::ListDevices()) { std::cout << device.first << ": " << device.second << std::endl; } } /** * Tries to get the output device ID from stdin. * If there is no stdin, the program prints up the available devices and dies. * @param argc The program argument count (from main()). * @param argv The program argument vector (from main()). * @return The device ID, as a string. */ static std::string DeviceId(int argc, char *argv[]) { std::string device = ""; // TODO: Perhaps make this section more robust. if (argc < 2) { ListOutputDevices(); throw Error(ErrorCode::BAD_CONFIG, MSG_DEV_NOID); } else { device = std::string(argv[1]); } return device; } /** * Registers various listeners with the Player. * This is so time and state changes can be sent out on stdout. * @param player The player to which the listeners will subscribe. */ static void RegisterListeners(Player &player) { player.RegisterPositionListener([](uint64_t position) { Respond(Response::TIME, position); }, TIME_USECS); player.RegisterStateListener([](State old_state, State new_state) { Respond(Response::STAT, STATES.at(old_state), STATES.at(new_state)); }); } /** * The main entry point. * @param argc Program argument count. * @param argv Program argument vector. */ int main(int argc, char *argv[]) { int exit_code = EXIT_SUCCESS; try { AudioOutput::InitialiseLibraries(); // Don't roll this into the constructor: it'll go out of scope! std::string device_id = DeviceId(argc, argv); Player p(device_id); RegisterListeners(p); MainLoop(p); } catch (Error &error) { error.ToResponse(); Debug("Unhandled exception caught, going away now."); exit_code = EXIT_FAILURE; } AudioOutput::CleanupLibraries(); return exit_code; } /** * Performs the playslave main loop. * This involves listening for commands and asking the player to do some work. * @todo Make the command check asynchronous/event based. * @todo Possibly separate command check and player updating into separate threads? */ static void MainLoop(Player &p) { /* Set of commands that can be performed on the player. */ command_set PLAYER_CMDS = { /* Nullary commands */ { "play", [&](const cmd_words &) { return p.Play(); } }, { "stop", [&](const cmd_words &) { return p.Stop(); } }, { "ejct", [&](const cmd_words &) { return p.Eject(); } }, { "quit", [&](const cmd_words &) { return p.Quit(); } }, /* Unary commands */ { "load", [&](const cmd_words &words) { return p.Load(words[1]); } }, { "seek", [&](const cmd_words &words) { return p.Seek(words[1]); } } }; Respond(Response::OHAI, MSG_OHAI); // Say hello while (p.CurrentState() != State::QUITTING) { /* * Possible Improvement: separate command checking and player * updating into two threads. Player updating is quite * intensive and thus impairs the command checking latency. * Do this if it doesn't make the code too complex. */ check_commands(PLAYER_CMDS); /* TODO: Check to see if err was fatal */ p.Update(); std::this_thread::sleep_for(std::chrono::nanoseconds(LOOP_NSECS)); } Respond(Response::TTFN, MSG_TTFN); // Wave goodbye }
/* * This file is part of Playslave-C++. * Playslave-C++ is licenced under MIT License. See LICENSE.txt for more details. */ #include <thread> #include <chrono> #include <iostream> #include "cmd.h" #include "io.hpp" #include "constants.h" /* LOOP_NSECS */ #include "messages.h" /* MSG_xyz */ #include "player.h" static void ListOutputDevices(); static std::string DeviceId(int argc, char *argv[]); static void MainLoop(Player &player); static void RegisterListeners(Player &player); const static std::unordered_map<State, std::string> STATES = { { State::EJECTED, "Ejected" }, { State::STOPPED, "Stopped" }, { State::PLAYING, "Playing" }, { State::QUITTING, "Quitting" } }; /** * Lists on stdout all sound devices to which the audio output may connect. * This is mainly for the benefit of the end user. */ static void ListOutputDevices() { for (auto device : AudioOutput::ListDevices()) { std::cout << device.first << ": " << device.second << std::endl; } } /** * Tries to get the output device ID from stdin. * If there is no stdin, the program prints up the available devices and dies. * @param argc The program argument count (from main()). * @param argv The program argument vector (from main()). * @return The device ID, as a string. */ static std::string DeviceId(int argc, char *argv[]) { std::string device = ""; // TODO: Perhaps make this section more robust. if (argc < 2) { ListOutputDevices(); throw Error(ErrorCode::BAD_CONFIG, MSG_DEV_NOID); } else { device = std::string(argv[1]); } return device; } /** * Registers various listeners with the Player. * This is so time and state changes can be sent out on stdout. * @param player The player to which the listeners will subscribe. */ static void RegisterListeners(Player &player) { player.RegisterPositionListener([](uint64_t position) { Respond(Response::TIME, position); }, TIME_USECS); player.RegisterStateListener([](State old_state, State new_state) { Respond(Response::STAT, STATES.at(old_state), STATES.at(new_state)); }); } /** * The main entry point. * @param argc Program argument count. * @param argv Program argument vector. */ int main(int argc, char *argv[]) { int exit_code = EXIT_SUCCESS; try { AudioOutput::InitialiseLibraries(); // Don't roll this into the constructor: it'll go out of scope! std::string device_id = DeviceId(argc, argv); Player player(device_id); RegisterListeners(player); MainLoop(player); } catch (Error &error) { error.ToResponse(); Debug("Unhandled exception caught, going away now."); exit_code = EXIT_FAILURE; } AudioOutput::CleanupLibraries(); return exit_code; } /** * Performs the playslave main loop. * This involves listening for commands and asking the player to do some work. * @todo Make the command check asynchronous/event based. * @todo Possibly separate command check and player updating into separate threads? */ static void MainLoop(Player &player) { /* Set of commands that can be performed on the player. */ command_set PLAYER_CMDS = { /* Nullary commands */ { "play", [&](const cmd_words &) { return player.Play(); } }, { "stop", [&](const cmd_words &) { return player.Stop(); } }, { "ejct", [&](const cmd_words &) { return player.Eject(); } }, { "quit", [&](const cmd_words &) { return player.Quit(); } }, /* Unary commands */ { "load", [&](const cmd_words &words) { return player.Load(words[1]); } }, { "seek", [&](const cmd_words &words) { return player.Seek(words[1]); } } }; Respond(Response::OHAI, MSG_OHAI); // Say hello while (player.CurrentState() != State::QUITTING) { /* * Possible Improvement: separate command checking and player * updating into two threads. Player updating is quite * intensive and thus impairs the command checking latency. * Do this if it doesn't make the code too complex. */ check_commands(PLAYER_CMDS); player.Update(); std::this_thread::sleep_for(std::chrono::nanoseconds(LOOP_NSECS)); } Respond(Response::TTFN, MSG_TTFN); // Wave goodbye }
Expand out name of player variable.
Expand out name of player variable.
C++
mit
LordAro/ury-playd,LordAro/ury-playd,LordAro/ury-playd
ecba87e720be60ed771e13a84d128a0cc7411453
main.cpp
main.cpp
/* --------------------------------------------------------------------------- This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org> --------------------------------------------------------------------------- */ /* Made By: Patrick J. Rye Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases. Current Revision: 3.1b Change Log--------------------------------------------------------------------------------------------------------------------------------------------------- Date Revision Changed By Changes ------ --------- ------------ --------------------------------------------------------------------------------------------------------------------- ============================================================================================================================================================= ------------------------------------------------------------------------------------------------------------------------------------------------------------- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM ALPHA TO BETA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ------------------------------------------------------------------------------------------------------------------------------------------------------------- ============================================================================================================================================================= 2015/02/24 1.0b Patrick Rye -Moved from V5.0-alpha to V1.0-beta -Fixed level up so it happens when you get to a new level. -Allowed exit on map. -Fixed opening text to reflect recent changes in the game. -Grammar and spelling fixes (yay, made it several revisions without having to do this. :) ). ============================================================================================================================================================= 2015/02/24 1.1b Patrick Rye -Attempted to allow movement on map through arrow keys. -Could not get this to work and broke everything. Rolling back to previous version. -Keeping this attempt in the record and will try to implement it again later. ============================================================================================================================================================= 2015/02/25 1.2b Patrick Rye -Grammar and spelling fixes. ((╯°□°)╯︵ ┻━┻) -Cleaned up code some more. -Changed some if statements to case switches. -Added breaks to case switches. ============================================================================================================================================================= 2015/02/26 1.3b Patrick Rye -Moved player movement to the room.h ============================================================================================================================================================= 2015/02/27 2.0b Patrick Rye -Added a save function, for testing purposes. -Added load function. -Added function to see if file exists. ============================================================================================================================================================= 2015/02/27 2.1b Patrick Rye -Moved save checker to basic.h -Renamed casechecker.h to basic.h -Added more comments explaining parts of the code. -Changed some names of functions to better reflect what they do. -Health is now carried between battles. -Moved healing to be able to happen between battles. -Added fail check for load function. ============================================================================================================================================================= 2015/03/02 2.2b Patrick Rye -Improved code a bit. -Added version number tracker. -Prompt for loading save. -Prompt for incorrect save version. -Moved saving and loading functions to its own header. ============================================================================================================================================================= 2015/03/02 2.2.1b Patrick Rye -Quick fix for version not being applied properly. ============================================================================================================================================================= 2015/03/03 2.3b Patrick Rye -Added more comments. -Changed some wording to better explain stuff. -Added a debug mode to game, detects if source code exists. -Grammar & spelling fixes. ============================================================================================================================================================= 2015/03/04 2.4b Patrick Rye -Debug mode can be set by loading a debug save. -Grammar & spelling fixes. -Improved map menu. -Changed save to 'V' rather than 'P'. ============================================================================================================================================================= 2015/03/06 2.5ß Patrick Rye -Changed some debug commands. -Changed change log date format from MM/DD/YY to YYYY/MM/DD because I like it better. -Added better opening message. -Replaced all system("pause") with getchar(); ============================================================================================================================================================= 2015/03/06 3.0b Patrick Rye -Redid some calculations in battle.h -Added better winning message. -Added spells.h does nothing currently just for testing. ============================================================================================================================================================= 2015/03/09 3.1b Patrick Rye -Edits to spells.h, more testing on adding spells. -Sets debug mode in spells.h -Win / opening messages moved to basic.h ============================================================================================================================================================= */ /*********************************************************************************************************/ #include <iostream> #include <fstream> #include <string> #include <math.h> #include <cstdlib> #include <cmath> #include <locale> #include <cstdio> #include <ctime> /*********************************************************************************************************/ #include "basic.h" //Functions that are simple and won't need to be changed very often. #include "battle.h" //Functions that deal with battling, levelling up and making a player. #include "rooms.h" //Functions that deal with generating a dungeon. #include "spells.h" //Functions that deal with spells and magic, a possible future addition. /*********************************************************************************************************/ using namespace std; Dungeon d; //Define the dungeon class as 'd' so I can use functions in there anywhere later in the code. /*********************************************************************************************************/ //Make all the global variables that I need. int intMainLevel; //The level of the dungeon. int intLevelStart = 1; //The level that the game starts at. Will be 1 unless loading from a save. bool blDebugMode = false; //If game is in debug mode or not, effects if player has access to debug commands. const string CurrentVerison = "3.1b"; //The current version of this program, stored in a save file later on. /*********************************************************************************************************/ //These functions have to be up here as functions in save.h use them. //These values are used to pass values to the save header so that they may be saved. //Or to set values from a load. int getmainvalue(int intvalue) { if(intvalue == 0 ) {return intMainLevel;} else if (intvalue == 1) {return intLevelStart;} else {return 1;} } void setmainvalue(int intlocation, int intvalue) {if (intlocation == 0) {intLevelStart = intvalue;}} void setdebugmode(bool blsetdebugmode) {blDebugMode = blsetdebugmode;} #include "save.h" //A header to hold functions related to saving and loading. /*********************************************************************************************************/ int main() { PassProgramVerison(CurrentVerison); //Pass current program version into the save header. cout << string(48, '\n'); char charPlayerDirection; bool blBattleEnding = false; char charExitFind; bool blOldSave = false; char chrPlayerMade = 'F'; char chrSaveSuccess = 'N'; //N means that save has not been run. //If game is not already in debug mode, checks if source code exists then put it in debug mode if it does. if (!(blDebugMode)) {blDebugMode = fileexists("main.cpp"); } if (blDebugMode) {SetBattleDebugMode(true); SetRoomDebugMode(true); SetSpellDebugMode(true);} //Sets debug mode for both rooms.h, battle.h, & spells.h ShowOpeningMessage(); getchar(); cout<<string(50,'\n'); if (fileexists("save.bif")) //Check if there is a save present. { blOldSave = LoadOldSave(); if (blOldSave) {chrPlayerMade = 'T';} //End of if save exists. } else {cout<<string(50, '\n');} if(!blOldSave) //If it is not an old save show welcome message. { cout<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl; cout<<"You are looking for the stairs down ( > ). While you are represented by † ."<<endl; cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl; cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl; cout<<"Good luck!"<<endl<<endl<<endl<<endl; while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made. } for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++) { //Do level up if new level. if (intMainLevel > intLevelStart) {LevelUpFunction();} charExitFind = 'F'; cout<<endl; if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon. else {Dungeon d;/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon. do { cout << string(50, '\n'); d.showDungeon(); cout<<"Level "<<intMainLevel<<" of 10."<<endl; cout<<"Please enter a direction you would like to go: "<<endl; cout<<"[N]orth, [E]ast, [S]outh, [W]est "<<endl; cout<<"E[X]it, [C]heck your health, [H]eal, Sa[V]e "<<endl; if (blDebugMode) {cout<<"[L]evel up, or [M]onster."<<endl;} cout<<"> "; cin>>charPlayerDirection; charPlayerDirection = CharConvertToUpper(charPlayerDirection); charExitFind = d.PlayerMovement(charPlayerDirection); if (charExitFind == 'E') {return 0;} //If we get an error exit program. if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game. switch (chrSaveSuccess) { case 'T' : cout<<endl<<"Save succeeded."<<endl; getchar(); chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message. break; case 'F' : cout<<endl<<"Save failed!"<<endl; getchar(); chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message. break; } if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster. { if(rand() % 101 <= 10 || charExitFind == 'M') //Random chance to encounter monster, or debug code to force monster encounter. { cout << string(50, '\n'); blBattleEnding = startbattle(intMainLevel); //Starts battle. if(!blBattleEnding) {return 0;} //Player lost battle. } } }while (charExitFind != 'T'); //Repeat until player finds exit. //End of FOR levels. } cout << string(50, '\n'); ShowWinningMessage(); getchar(); return 0; //End of main }
/* --------------------------------------------------------------------------- This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org> --------------------------------------------------------------------------- */ /* Made By: Patrick J. Rye Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases. Current Revision: 4.0b-dev2 Change Log--------------------------------------------------------------------------------------------------------------------------------------------------- Date Revision Changed By Changes ------ --------- ------------ --------------------------------------------------------------------------------------------------------------------- ============================================================================================================================================================= ------------------------------------------------------------------------------------------------------------------------------------------------------------- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM ALPHA TO BETA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ------------------------------------------------------------------------------------------------------------------------------------------------------------- ============================================================================================================================================================= 2015/02/24 1.0b Patrick Rye -Moved from V5.0-alpha to V1.0-beta -Fixed level up so it happens when you get to a new level. -Allowed exit on map. -Fixed opening text to reflect recent changes in the game. -Grammar and spelling fixes (yay, made it several revisions without having to do this. :) ). ============================================================================================================================================================= 2015/02/24 1.1b Patrick Rye -Attempted to allow movement on map through arrow keys. -Could not get this to work and broke everything. Rolling back to previous version. -Keeping this attempt in the record and will try to implement it again later. ============================================================================================================================================================= 2015/02/25 1.2b Patrick Rye -Grammar and spelling fixes. ((╯°□°)╯︵ ┻━┻) -Cleaned up code some more. -Changed some if statements to case switches. -Added breaks to case switches. ============================================================================================================================================================= 2015/02/26 1.3b Patrick Rye -Moved player movement to the room.h ============================================================================================================================================================= 2015/02/27 2.0b Patrick Rye -Added a save function, for testing purposes. -Added load function. -Added function to see if file exists. ============================================================================================================================================================= 2015/02/27 2.1b Patrick Rye -Moved save checker to basic.h -Renamed casechecker.h to basic.h -Added more comments explaining parts of the code. -Changed some names of functions to better reflect what they do. -Health is now carried between battles. -Moved healing to be able to happen between battles. -Added fail check for load function. ============================================================================================================================================================= 2015/03/02 2.2b Patrick Rye -Improved code a bit. -Added version number tracker. -Prompt for loading save. -Prompt for incorrect save version. -Moved saving and loading functions to its own header. ============================================================================================================================================================= 2015/03/02 2.2.1b Patrick Rye -Quick fix for version not being applied properly. ============================================================================================================================================================= 2015/03/03 2.3b Patrick Rye -Added more comments. -Changed some wording to better explain stuff. -Added a debug mode to game, detects if source code exists. -Grammar & spelling fixes. ============================================================================================================================================================= 2015/03/04 2.4b Patrick Rye -Debug mode can be set by loading a debug save. -Grammar & spelling fixes. -Improved map menu. -Changed save to 'V' rather than 'P'. ============================================================================================================================================================= 2015/03/06 2.5ß Patrick Rye -Changed some debug commands. -Changed change log date format from MM/DD/YY to YYYY/MM/DD because I like it better. -Added better opening message. -Replaced all system("pause") with getchar(); ============================================================================================================================================================= 2015/03/06 3.0b Patrick Rye -Redid some calculations in battle.h -Added better winning message. -Added spells.h does nothing currently just for testing. ============================================================================================================================================================= 2015/03/09 3.1b Patrick Rye -Edits to spells.h, more testing on adding spells. -Sets debug mode in spells.h -Win / opening messages moved to basic.h ============================================================================================================================================================= 2015/03/10 4.0b Patrick Rye -Implemented status effects. ============================================================================================================================================================= */ /*********************************************************************************************************/ #include <iostream> #include <fstream> #include <string> #include <math.h> #include <cstdlib> #include <cmath> #include <locale> #include <cstdio> #include <ctime> /*********************************************************************************************************/ #include "basic.h" //Functions that are simple and won't need to be changed very often. #include "battle.h" //Functions that deal with battling, levelling up and making a player. #include "rooms.h" //Functions that deal with generating a dungeon. #include "spells.h" //Functions that deal with spells and magic, a possible future addition. /*********************************************************************************************************/ using namespace std; Dungeon d; //Define the dungeon class as 'd' so I can use functions in there anywhere later in the code. /*********************************************************************************************************/ //Make all the global variables that I need. int intMainLevel; //The level of the dungeon. int intLevelStart = 1; //The level that the game starts at. Will be 1 unless loading from a save. bool blDebugMode = false; //If game is in debug mode or not, effects if player has access to debug commands. const string CurrentVerison = "4.0b-dev2"; //The current version of this program, stored in a save file later on. /*********************************************************************************************************/ //These functions have to be up here as functions in save.h use them. //These values are used to pass values to the save header so that they may be saved. //Or to set values from a load. int getmainvalue(int intvalue) { if(intvalue == 0 ) {return intMainLevel;} else if (intvalue == 1) {return intLevelStart;} else {return 1;} } void setmainvalue(int intlocation, int intvalue) {if (intlocation == 0) {intLevelStart = intvalue;}} void setdebugmode(bool blsetdebugmode) {blDebugMode = blsetdebugmode;} #include "save.h" //A header to hold functions related to saving and loading. /*********************************************************************************************************/ int main() { PassProgramVerison(CurrentVerison); //Pass current program version into the save header. cout << string(48, '\n'); char charPlayerDirection; bool blBattleEnding = false; char charExitFind; bool blOldSave = false; char chrPlayerMade = 'F'; char chrSaveSuccess = 'N'; //N means that save has not been run. //If game is not already in debug mode, checks if source code exists then put it in debug mode if it does. if (!(blDebugMode)) {blDebugMode = fileexists("main.cpp"); } if (blDebugMode) {SetBattleDebugMode(true); SetRoomDebugMode(true); SetSpellDebugMode(true);} //Sets debug mode for both rooms.h, battle.h, & spells.h ShowOpeningMessage(); getchar(); cout<<string(50,'\n'); if (fileexists("save.bif")) //Check if there is a save present. { blOldSave = LoadOldSave(); if (blOldSave) {chrPlayerMade = 'T';} //End of if save exists. } else {cout<<string(50, '\n');} if(!blOldSave) //If it is not an old save show welcome message. { cout<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl; cout<<"You are looking for the stairs down ( > ). While you are represented by † ."<<endl; cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl; cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl; cout<<"Good luck!"<<endl<<endl<<endl<<endl; while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made. } for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++) { //Do level up if new level. if (intMainLevel > intLevelStart) {LevelUpFunction();} charExitFind = 'F'; cout<<endl; if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon. else {Dungeon d;/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon. do { cout << string(50, '\n'); d.showDungeon(); cout<<"Level "<<intMainLevel<<" of 10."<<endl; cout<<"Please enter a direction you would like to go: "<<endl; cout<<"[N]orth, [E]ast, [S]outh, [W]est "<<endl; cout<<"E[X]it, [C]heck your health, [H]eal, Sa[V]e "<<endl; if (blDebugMode) {cout<<"[L]evel up, or [M]onster."<<endl;} cout<<"> "; cin>>charPlayerDirection; charPlayerDirection = CharConvertToUpper(charPlayerDirection); charExitFind = d.PlayerMovement(charPlayerDirection); if (charExitFind == 'E') {return 0;} //If we get an error exit program. if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game. switch (chrSaveSuccess) { case 'T' : cout<<endl<<"Save succeeded."<<endl; getchar(); chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message. break; case 'F' : cout<<endl<<"Save failed!"<<endl; getchar(); chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message. break; } if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster. { if(rand() % 101 <= 10 || charExitFind == 'M') //Random chance to encounter monster, or debug code to force monster encounter. { cout << string(50, '\n'); blBattleEnding = startbattle(intMainLevel); //Starts battle. if(!blBattleEnding) {return 0;} //Player lost battle. } } }while (charExitFind != 'T'); //Repeat until player finds exit. //End of FOR levels. } cout << string(50, '\n'); ShowWinningMessage(); getchar(); return 0; //End of main }
Update main to V4.0b-dev2
Update main to V4.0b-dev2 -Implemented status effects.
C++
unlicense
GamerMan7799/Attacker-The-Game
7777e5cbb723ba2dd9c0697eac14f30f77971be9
maybe.hh
maybe.hh
#ifndef MAYBE_HH #define MAYBE_HH #include <cassert> #include <cstring> #include <new> #include <memory> template<typename T> struct maybe { maybe() : is_init(false) {} maybe(const T &other) : is_init(false) { new (&memory) T(other); is_init = true; } maybe(maybe &&other) { is_init = other.is_init; memcpy(reinterpret_cast<char *>(&memory), reinterpret_cast<char *>(&other.memory), sizeof(T)); other.is_init = false; } ~maybe() { if (is_init) { this->operator*().~T(); } } explicit operator bool() const { return is_init; } T &operator*() { assert(is_init); return *reinterpret_cast<T *>(&memory); } const T &operator*() const { assert(is_init); return *reinterpret_cast<T *>(&memory); } T *operator->() { assert(is_init); return reinterpret_cast<T *>(&memory); } const T *operator->() const { assert(is_init); return reinterpret_cast<T *>(&memory); } T *get() { return is_init ? reinterpret_cast<T *>(&memory) : nullptr; } const T *get() const { return is_init ? reinterpret_cast<T *>(&memory) : nullptr; } private: typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type memory; bool is_init; }; #endif
#ifndef MAYBE_HH #define MAYBE_HH #include <cassert> #include <cstring> #include <new> #include <memory> template<typename T> struct maybe { maybe() : is_init(false) {} maybe(const T &other) : is_init(false) { new (&memory) T(other); is_init = true; } maybe(const maybe &other) : is_init(false) { new (&memory) T(*reinterpret_cast<const T *>(&other.memory)); is_init = other.is_init; } maybe(maybe &&other) { is_init = other.is_init; memcpy(reinterpret_cast<char *>(&memory), reinterpret_cast<char *>(&other.memory), sizeof(T)); other.is_init = false; } ~maybe() { if (is_init) { this->operator*().~T(); } } explicit operator bool() const { return is_init; } T &operator*() { assert(is_init); return *reinterpret_cast<T *>(&memory); } const T &operator*() const { assert(is_init); return *reinterpret_cast<T *>(&memory); } T *operator->() { assert(is_init); return reinterpret_cast<T *>(&memory); } const T *operator->() const { assert(is_init); return reinterpret_cast<T *>(&memory); } T *get() { return is_init ? reinterpret_cast<T *>(&memory) : nullptr; } const T *get() const { return is_init ? reinterpret_cast<T *>(&memory) : nullptr; } private: typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type memory; bool is_init; }; #endif
add copy-constructor from maybe<T>
maybe.hh: add copy-constructor from maybe<T>
C++
mit
thestinger/util,thestinger/util
18c6454ad19d5d323af7b3318f18c409b84c7a12
src/gallium/auxiliary/gallivm/lp_bld_debug.cpp
src/gallium/auxiliary/gallivm/lp_bld_debug.cpp
/************************************************************************** * * Copyright 2009-2011 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS 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 <stddef.h> #include <llvm-c/Core.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Target/TargetInstrInfo.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/Format.h> #include <llvm/Support/MemoryObject.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/MC/MCSubtargetInfo.h> #include <llvm/Support/Host.h> #include <llvm/MC/MCDisassembler.h> #include <llvm/MC/MCAsmInfo.h> #include <llvm/MC/MCInst.h> #include <llvm/MC/MCInstPrinter.h> #include <llvm/MC/MCRegisterInfo.h> #if HAVE_LLVM >= 0x0303 #include <llvm/ADT/OwningPtr.h> #endif #if HAVE_LLVM >= 0x0305 #include <llvm/MC/MCContext.h> #endif #include "util/u_math.h" #include "util/u_debug.h" #include "lp_bld_debug.h" #ifdef __linux__ #include <sys/stat.h> #include <fcntl.h> #endif /** * Check alignment. * * It is important that this check is not implemented as a macro or inlined * function, as the compiler assumptions in respect to alignment of global * and stack variables would often make the check a no op, defeating the * whole purpose of the exercise. */ extern "C" boolean lp_check_alignment(const void *ptr, unsigned alignment) { assert(util_is_power_of_two(alignment)); return ((uintptr_t)ptr & (alignment - 1)) == 0; } class raw_debug_ostream : public llvm::raw_ostream { private: uint64_t pos; public: raw_debug_ostream() : pos(0) { } void write_impl(const char *Ptr, size_t Size); uint64_t current_pos() const { return pos; } size_t preferred_buffer_size() const { return 512; } }; void raw_debug_ostream::write_impl(const char *Ptr, size_t Size) { if (Size > 0) { char *lastPtr = (char *)&Ptr[Size]; char last = *lastPtr; *lastPtr = 0; _debug_printf("%*s", Size, Ptr); *lastPtr = last; pos += Size; } } /** * Same as LLVMDumpValue, but through our debugging channels. */ extern "C" void lp_debug_dump_value(LLVMValueRef value) { #if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED) raw_debug_ostream os; llvm::unwrap(value)->print(os); os.flush(); #else LLVMDumpValue(value); #endif } /* * MemoryObject wrapper around a buffer of memory, to be used by MC * disassembler. */ class BufferMemoryObject: public llvm::MemoryObject { private: const uint8_t *Bytes; uint64_t Length; public: BufferMemoryObject(const uint8_t *bytes, uint64_t length) : Bytes(bytes), Length(length) { } uint64_t getBase() const { return 0; } uint64_t getExtent() const { return Length; } int readByte(uint64_t addr, uint8_t *byte) const { if (addr > getExtent()) return -1; *byte = Bytes[addr]; return 0; } }; /* * Disassemble a function, using the LLVM MC disassembler. * * See also: * - http://blog.llvm.org/2010/01/x86-disassembler.html * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html */ static size_t disassemble(const void* func, llvm::raw_ostream & Out) { using namespace llvm; const uint8_t *bytes = (const uint8_t *)func; /* * Limit disassembly to this extent */ const uint64_t extent = 96 * 1024; uint64_t max_pc = 0; /* * Initialize all used objects. */ std::string Triple = sys::getDefaultTargetTriple(); std::string Error; const Target *T = TargetRegistry::lookupTarget(Triple, Error); #if HAVE_LLVM >= 0x0304 OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(*T->createMCRegInfo(Triple), Triple)); #else OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple)); #endif if (!AsmInfo) { Out << "error: no assembly info for target " << Triple << "\n"; return 0; } unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); OwningPtr<const MCRegisterInfo> MRI(T->createMCRegInfo(Triple)); if (!MRI) { Out << "error: no register info for target " << Triple.c_str() << "\n"; return 0; } OwningPtr<const MCInstrInfo> MII(T->createMCInstrInfo()); if (!MII) { Out << "error: no instruction info for target " << Triple.c_str() << "\n"; return 0; } #if HAVE_LLVM >= 0x0305 OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), "")); OwningPtr<MCContext> MCCtx(new MCContext(AsmInfo.get(), MRI.get(), 0)); OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI, *MCCtx)); #else OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), "")); OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI)); #endif if (!DisAsm) { Out << "error: no disassembler for target " << Triple << "\n"; return 0; } OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI)); if (!Printer) { Out << "error: no instruction printer for target " << Triple.c_str() << "\n"; return 0; } TargetOptions options; #if defined(DEBUG) options.JITEmitDebugInfo = true; #endif #if defined(PIPE_ARCH_X86) options.StackAlignmentOverride = 4; #endif #if defined(DEBUG) || defined(PROFILE) options.NoFramePointerElim = true; #endif OwningPtr<TargetMachine> TM(T->createTargetMachine(Triple, sys::getHostCPUName(), "", options)); const TargetInstrInfo *TII = TM->getInstrInfo(); /* * Wrap the data in a MemoryObject */ BufferMemoryObject memoryObject((const uint8_t *)bytes, extent); uint64_t pc; pc = 0; while (true) { MCInst Inst; uint64_t Size; /* * Print address. We use addresses relative to the start of the function, * so that between runs. */ Out << llvm::format("%6lu:\t", (unsigned long)pc); if (!DisAsm->getInstruction(Inst, Size, memoryObject, pc, nulls(), nulls())) { Out << "invalid"; pc += 1; } /* * Output the bytes in hexidecimal format. */ if (0) { unsigned i; for (i = 0; i < Size; ++i) { Out << llvm::format("%02x ", ((const uint8_t*)bytes)[pc + i]); } for (; i < 16; ++i) { Out << " "; } } /* * Print the instruction. */ Printer->printInst(&Inst, Out, ""); /* * Advance. */ pc += Size; const MCInstrDesc &TID = TII->get(Inst.getOpcode()); /* * Keep track of forward jumps to a nearby address. */ if (TID.isBranch()) { for (unsigned i = 0; i < Inst.getNumOperands(); ++i) { const MCOperand &operand = Inst.getOperand(i); if (operand.isImm()) { uint64_t jump; /* * FIXME: Handle both relative and absolute addresses correctly. * EDInstInfo actually has this info, but operandTypes and * operandFlags enums are not exposed in the public interface. */ if (1) { /* * PC relative addr. */ jump = pc + operand.getImm(); } else { /* * Absolute addr. */ jump = (uint64_t)operand.getImm(); } /* * Output the address relative to the function start, given * that MC will print the addresses relative the current pc. */ Out << "\t\t; " << jump; /* * Ignore far jumps given it could be actually a tail return to * a random address. */ if (jump > max_pc && jump < extent) { max_pc = jump; } } } } Out << "\n"; /* * Stop disassembling on return statements, if there is no record of a * jump to a successive address. */ if (TID.isReturn()) { if (pc > max_pc) { break; } } } /* * Print GDB command, useful to verify output. */ if (0) { _debug_printf("disassemble %p %p\n", bytes, bytes + pc); } Out << "\n"; Out.flush(); return pc; } extern "C" void lp_disassemble(LLVMValueRef func, const void *code) { raw_debug_ostream Out; disassemble(code, Out); } /* * Linux perf profiler integration. * * See also: * - http://penberg.blogspot.co.uk/2009/06/jato-has-profiler.html * - https://github.com/penberg/jato/commit/73ad86847329d99d51b386f5aba692580d1f8fdc * - http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=commitdiff;h=80d496be89ed7dede5abee5c057634e80a31c82d */ extern "C" void lp_profile(LLVMValueRef func, const void *code) { #if defined(__linux__) && (defined(DEBUG) || defined(PROFILE)) static boolean first_time = TRUE; static FILE *perf_map_file = NULL; static int perf_asm_fd = -1; if (first_time) { /* * We rely on the disassembler for determining a function's size, but * the disassembly is a leaky and slow operation, so avoid running * this except when running inside linux perf, which can be inferred * by the PERF_BUILDID_DIR environment variable. */ if (getenv("PERF_BUILDID_DIR")) { pid_t pid = getpid(); char filename[256]; util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map", (unsigned long long)pid); perf_map_file = fopen(filename, "wt"); util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map.asm", (unsigned long long)pid); mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; perf_asm_fd = open(filename, O_WRONLY | O_CREAT, mode); } first_time = FALSE; } if (perf_map_file) { const char *symbol = LLVMGetValueName(func); unsigned long addr = (uintptr_t)code; llvm::raw_fd_ostream Out(perf_asm_fd, false); Out << symbol << ":\n"; unsigned long size = disassemble(code, Out); fprintf(perf_map_file, "%lx %lx %s\n", addr, size, symbol); fflush(perf_map_file); } #else (void)func; (void)code; #endif }
/************************************************************************** * * Copyright 2009-2011 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS 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 <stddef.h> #include <llvm-c/Core.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Target/TargetInstrInfo.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/Format.h> #include <llvm/Support/MemoryObject.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/MC/MCSubtargetInfo.h> #include <llvm/Support/Host.h> #include <llvm/MC/MCDisassembler.h> #include <llvm/MC/MCAsmInfo.h> #include <llvm/MC/MCInst.h> #include <llvm/MC/MCInstPrinter.h> #include <llvm/MC/MCRegisterInfo.h> #if HAVE_LLVM >= 0x0303 #include <llvm/ADT/OwningPtr.h> #endif #if HAVE_LLVM >= 0x0305 #include <llvm/MC/MCContext.h> #endif #include "util/u_math.h" #include "util/u_debug.h" #include "lp_bld_debug.h" #ifdef __linux__ #include <sys/stat.h> #include <fcntl.h> #endif /** * Check alignment. * * It is important that this check is not implemented as a macro or inlined * function, as the compiler assumptions in respect to alignment of global * and stack variables would often make the check a no op, defeating the * whole purpose of the exercise. */ extern "C" boolean lp_check_alignment(const void *ptr, unsigned alignment) { assert(util_is_power_of_two(alignment)); return ((uintptr_t)ptr & (alignment - 1)) == 0; } class raw_debug_ostream : public llvm::raw_ostream { private: uint64_t pos; public: raw_debug_ostream() : pos(0) { } void write_impl(const char *Ptr, size_t Size); uint64_t current_pos() const { return pos; } size_t preferred_buffer_size() const { return 512; } }; void raw_debug_ostream::write_impl(const char *Ptr, size_t Size) { if (Size > 0) { char *lastPtr = (char *)&Ptr[Size]; char last = *lastPtr; *lastPtr = 0; _debug_printf("%*s", Size, Ptr); *lastPtr = last; pos += Size; } } /** * Same as LLVMDumpValue, but through our debugging channels. */ extern "C" void lp_debug_dump_value(LLVMValueRef value) { #if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED) raw_debug_ostream os; llvm::unwrap(value)->print(os); os.flush(); #else LLVMDumpValue(value); #endif } /* * MemoryObject wrapper around a buffer of memory, to be used by MC * disassembler. */ class BufferMemoryObject: public llvm::MemoryObject { private: const uint8_t *Bytes; uint64_t Length; public: BufferMemoryObject(const uint8_t *bytes, uint64_t length) : Bytes(bytes), Length(length) { } uint64_t getBase() const { return 0; } uint64_t getExtent() const { return Length; } int readByte(uint64_t addr, uint8_t *byte) const { if (addr > getExtent()) return -1; *byte = Bytes[addr]; return 0; } }; /* * Disassemble a function, using the LLVM MC disassembler. * * See also: * - http://blog.llvm.org/2010/01/x86-disassembler.html * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html */ static size_t disassemble(const void* func, llvm::raw_ostream & Out) { using namespace llvm; const uint8_t *bytes = (const uint8_t *)func; /* * Limit disassembly to this extent */ const uint64_t extent = 96 * 1024; uint64_t max_pc = 0; /* * Initialize all used objects. */ std::string Triple = sys::getDefaultTargetTriple(); std::string Error; const Target *T = TargetRegistry::lookupTarget(Triple, Error); #if HAVE_LLVM >= 0x0304 OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(*T->createMCRegInfo(Triple), Triple)); #else OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple)); #endif if (!AsmInfo) { Out << "error: no assembly info for target " << Triple << "\n"; Out.flush(); return 0; } unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); OwningPtr<const MCRegisterInfo> MRI(T->createMCRegInfo(Triple)); if (!MRI) { Out << "error: no register info for target " << Triple.c_str() << "\n"; Out.flush(); return 0; } OwningPtr<const MCInstrInfo> MII(T->createMCInstrInfo()); if (!MII) { Out << "error: no instruction info for target " << Triple.c_str() << "\n"; Out.flush(); return 0; } #if HAVE_LLVM >= 0x0305 OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), "")); OwningPtr<MCContext> MCCtx(new MCContext(AsmInfo.get(), MRI.get(), 0)); OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI, *MCCtx)); #else OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), "")); OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI)); #endif if (!DisAsm) { Out << "error: no disassembler for target " << Triple << "\n"; Out.flush(); return 0; } OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI)); if (!Printer) { Out << "error: no instruction printer for target " << Triple.c_str() << "\n"; Out.flush(); return 0; } TargetOptions options; #if defined(DEBUG) options.JITEmitDebugInfo = true; #endif #if defined(PIPE_ARCH_X86) options.StackAlignmentOverride = 4; #endif #if defined(DEBUG) || defined(PROFILE) options.NoFramePointerElim = true; #endif OwningPtr<TargetMachine> TM(T->createTargetMachine(Triple, sys::getHostCPUName(), "", options)); const TargetInstrInfo *TII = TM->getInstrInfo(); /* * Wrap the data in a MemoryObject */ BufferMemoryObject memoryObject((const uint8_t *)bytes, extent); uint64_t pc; pc = 0; while (true) { MCInst Inst; uint64_t Size; /* * Print address. We use addresses relative to the start of the function, * so that between runs. */ Out << llvm::format("%6lu:\t", (unsigned long)pc); if (!DisAsm->getInstruction(Inst, Size, memoryObject, pc, nulls(), nulls())) { Out << "invalid"; pc += 1; } /* * Output the bytes in hexidecimal format. */ if (0) { unsigned i; for (i = 0; i < Size; ++i) { Out << llvm::format("%02x ", ((const uint8_t*)bytes)[pc + i]); } for (; i < 16; ++i) { Out << " "; } } /* * Print the instruction. */ Printer->printInst(&Inst, Out, ""); /* * Advance. */ pc += Size; const MCInstrDesc &TID = TII->get(Inst.getOpcode()); /* * Keep track of forward jumps to a nearby address. */ if (TID.isBranch()) { for (unsigned i = 0; i < Inst.getNumOperands(); ++i) { const MCOperand &operand = Inst.getOperand(i); if (operand.isImm()) { uint64_t jump; /* * FIXME: Handle both relative and absolute addresses correctly. * EDInstInfo actually has this info, but operandTypes and * operandFlags enums are not exposed in the public interface. */ if (1) { /* * PC relative addr. */ jump = pc + operand.getImm(); } else { /* * Absolute addr. */ jump = (uint64_t)operand.getImm(); } /* * Output the address relative to the function start, given * that MC will print the addresses relative the current pc. */ Out << "\t\t; " << jump; /* * Ignore far jumps given it could be actually a tail return to * a random address. */ if (jump > max_pc && jump < extent) { max_pc = jump; } } } } Out << "\n"; /* * Stop disassembling on return statements, if there is no record of a * jump to a successive address. */ if (TID.isReturn()) { if (pc > max_pc) { break; } } } /* * Print GDB command, useful to verify output. */ if (0) { _debug_printf("disassemble %p %p\n", bytes, bytes + pc); } Out << "\n"; Out.flush(); return pc; } extern "C" void lp_disassemble(LLVMValueRef func, const void *code) { raw_debug_ostream Out; disassemble(code, Out); } /* * Linux perf profiler integration. * * See also: * - http://penberg.blogspot.co.uk/2009/06/jato-has-profiler.html * - https://github.com/penberg/jato/commit/73ad86847329d99d51b386f5aba692580d1f8fdc * - http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=commitdiff;h=80d496be89ed7dede5abee5c057634e80a31c82d */ extern "C" void lp_profile(LLVMValueRef func, const void *code) { #if defined(__linux__) && (defined(DEBUG) || defined(PROFILE)) static boolean first_time = TRUE; static FILE *perf_map_file = NULL; static int perf_asm_fd = -1; if (first_time) { /* * We rely on the disassembler for determining a function's size, but * the disassembly is a leaky and slow operation, so avoid running * this except when running inside linux perf, which can be inferred * by the PERF_BUILDID_DIR environment variable. */ if (getenv("PERF_BUILDID_DIR")) { pid_t pid = getpid(); char filename[256]; util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map", (unsigned long long)pid); perf_map_file = fopen(filename, "wt"); util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map.asm", (unsigned long long)pid); mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; perf_asm_fd = open(filename, O_WRONLY | O_CREAT, mode); } first_time = FALSE; } if (perf_map_file) { const char *symbol = LLVMGetValueName(func); unsigned long addr = (uintptr_t)code; llvm::raw_fd_ostream Out(perf_asm_fd, false); Out << symbol << ":\n"; unsigned long size = disassemble(code, Out); fprintf(perf_map_file, "%lx %lx %s\n", addr, size, symbol); fflush(perf_map_file); } #else (void)func; (void)code; #endif }
fix output stream flushing in error case for disassembly.
gallivm: fix output stream flushing in error case for disassembly. When there's an error, also need to flush the stream, otherwise an assertion is hit (meaning you don't actually see the error neither).
C++
mit
tokyovigilante/glsl-optimizer,zz85/glsl-optimizer,dellis1972/glsl-optimizer,mcanthony/glsl-optimizer,djreep81/glsl-optimizer,tokyovigilante/glsl-optimizer,wolf96/glsl-optimizer,jbarczak/glsl-optimizer,wolf96/glsl-optimizer,benaadams/glsl-optimizer,zeux/glsl-optimizer,wolf96/glsl-optimizer,mcanthony/glsl-optimizer,mcanthony/glsl-optimizer,zz85/glsl-optimizer,jbarczak/glsl-optimizer,zz85/glsl-optimizer,mcanthony/glsl-optimizer,djreep81/glsl-optimizer,mcanthony/glsl-optimizer,dellis1972/glsl-optimizer,benaadams/glsl-optimizer,djreep81/glsl-optimizer,zz85/glsl-optimizer,metora/MesaGLSLCompiler,zeux/glsl-optimizer,bkaradzic/glsl-optimizer,tokyovigilante/glsl-optimizer,dellis1972/glsl-optimizer,bkaradzic/glsl-optimizer,zeux/glsl-optimizer,jbarczak/glsl-optimizer,tokyovigilante/glsl-optimizer,bkaradzic/glsl-optimizer,zeux/glsl-optimizer,benaadams/glsl-optimizer,bkaradzic/glsl-optimizer,djreep81/glsl-optimizer,wolf96/glsl-optimizer,jbarczak/glsl-optimizer,zeux/glsl-optimizer,zz85/glsl-optimizer,zz85/glsl-optimizer,jbarczak/glsl-optimizer,dellis1972/glsl-optimizer,tokyovigilante/glsl-optimizer,djreep81/glsl-optimizer,bkaradzic/glsl-optimizer,benaadams/glsl-optimizer,benaadams/glsl-optimizer,metora/MesaGLSLCompiler,wolf96/glsl-optimizer,benaadams/glsl-optimizer,dellis1972/glsl-optimizer,metora/MesaGLSLCompiler
063ae8e0bdc3e623bb759d2f2057789065522781
src/NodePoppler.cc
src/NodePoppler.cc
#include <nan.h> #include <iostream> #include <string> #include <sstream> #include <map> #include <stdlib.h> #include <stdio.h> #include <poppler/qt4/poppler-form.h> #include <poppler/qt4/poppler-qt4.h> #include <cairo/cairo.h> #include <cairo/cairo-pdf.h> #include <QtCore/QBuffer> #include <QtCore/QFile> #include <QtGui/QImage> #include "NodePoppler.h" // NOLINT(build/include) using namespace std; using v8::Number; using v8::String; using v8::Object; using v8::Local; using v8::Array; using v8::Value; using v8::Boolean; inline bool fileExists (const std::string& name) { if (FILE *file = fopen(name.c_str(), "r")) { fclose(file); return true; } else { return false; } } // Cairo write and read functions (to QBuffer) static cairo_status_t readPngFromBuffer(void *closure, unsigned char *data, unsigned int length) { QBuffer *myBuffer = (QBuffer *)closure; size_t bytes_read; bytes_read = myBuffer->read((char *)data, length); if (bytes_read != length) return CAIRO_STATUS_READ_ERROR; return CAIRO_STATUS_SUCCESS; } static cairo_status_t writePngToBuffer(void *closure, const unsigned char *data, unsigned int length) { QBuffer *myBuffer = (QBuffer *)closure; size_t bytes_wrote; bytes_wrote = myBuffer->write((char *)data, length); if (bytes_wrote != length) return CAIRO_STATUS_READ_ERROR; return CAIRO_STATUS_SUCCESS; } void createPdf(QBuffer *buffer, Poppler::Document *document) { ostringstream ss; Poppler::PDFConverter *converter = document->pdfConverter(); converter->setPDFOptions(converter->pdfOptions() | Poppler::PDFConverter::WithChanges); converter->setOutputDevice(buffer); if (!converter->convert()) { // enum Error // { // NoError, // FileLockedError, // OpenOutputError, // NotSupportedInputFileError // }; ss << "Error occurred when converting PDF: " << converter->lastError(); throw ss.str(); } } void createImgPdf(QBuffer *buffer, Poppler::Document *document) { // Initialize Cairo writing surface, and since we have images at 360 DPI, we'll set scaling. Width and Height are set for A4 dimensions. cairo_surface_t *surface = cairo_pdf_surface_create_for_stream(writePngToBuffer, buffer, 595.00, 842.00); cairo_t *cr = cairo_create(surface); cairo_scale(cr, 0.2, 0.2); int n = document->numPages(); for (int i = 0; i < n; i += 1) { Poppler::Page *page = document->page(i); // Save the page as PNG image to buffer. (We could use QFile if we want to save images to files) QBuffer *pageImage = new QBuffer(); pageImage->open(QIODevice::ReadWrite); QImage img = page->renderToImage(360, 360); img.save(pageImage, "png"); pageImage->seek(0); // Reading does not work if we don't reset the pointer // Ookay, let's try to make new page out of the image cairo_surface_t *drawImageSurface = cairo_image_surface_create_from_png_stream(readPngFromBuffer, pageImage); cairo_set_source_surface(cr, drawImageSurface, 0, 0); cairo_paint(cr); // Create new page if multipage document if (n > 0) { cairo_surface_show_page(surface); cr = cairo_create(surface); cairo_scale(cr, 0.2, 0.2); } pageImage->close(); } // Close Cairo cairo_destroy(cr); cairo_surface_finish(surface); cairo_surface_destroy (surface); } WriteFieldsParams v8ParamsToCpp(const v8::FunctionCallbackInfo<Value>& args) { Local<Object> parameters; string saveFormat = "imgpdf"; map<string, string> fields; string sourcePdfFileName = *NanAsciiString(args[0]); Local<Object> changeFields = args[1]->ToObject(); // Check if any configuration parameters if (args.Length() > 2) { parameters = args[2]->ToObject(); Local<Value> saveParam = parameters->Get(NanNew<String>("save")); if (!saveParam->IsUndefined()) { saveFormat = *NanAsciiString(parameters->Get(NanNew<String>("save"))); } } // Convert form fields to c++ map Local<Array> fieldArray = changeFields->GetPropertyNames(); for (uint32_t i = 0; i < fieldArray->Length(); i += 1) { Local<Value> name = fieldArray->Get(i); Local<Value> value = changeFields->Get(name); fields[std::string(*v8::String::Utf8Value(name))] = std::string(*v8::String::Utf8Value(value)); } // Create and return PDF struct WriteFieldsParams params(sourcePdfFileName, saveFormat, fields); return params; } // Pdf creator that is not dependent on V8 internals (safe at async?) QBuffer *writePdfFields(struct WriteFieldsParams params) { ostringstream ss; // If source file does not exist, throw error and return false if (!fileExists(params.sourcePdfFileName)) { ss << "File \"" << params.sourcePdfFileName << "\" does not exist"; throw ss.str(); } // Open document and return false and throw error if something goes wrong Poppler::Document *document = Poppler::Document::load(QString::fromStdString(params.sourcePdfFileName)); if (document == NULL) { ss << "Error occurred when reading \"" << params.sourcePdfFileName << "\""; throw ss.str(); } // Fill form int n = document->numPages(); for (int i = 0; i < n; i += 1) { Poppler::Page *page = document->page(i); foreach (Poppler::FormField *field, page->formFields()) { string fieldName = field->fullyQualifiedName().toStdString(); if (!field->isReadOnly() && field->isVisible() && params.fields.count(fieldName)) { // Text if (field->type() == Poppler::FormField::FormText) { Poppler::FormFieldText *textField = (Poppler::FormFieldText *) field; textField->setText(QString::fromUtf8(params.fields[fieldName].c_str())); } // Button if (field->type() == Poppler::FormField::FormButton) { Poppler::FormFieldButton *buttonField = (Poppler::FormFieldButton *) field; // Checkbox !TODO! - enable also other types. Note. Poppler doesn't support checkboxes with hashtag names (aka using exportValue). if (buttonField->buttonType() == Poppler::FormFieldButton::CheckBox) { if (params.fields[fieldName].compare("true") == 0) { buttonField->setState(true); } else { buttonField->setState(false); } } } } } } // Now save and return the document QBuffer *bufferDevice = new QBuffer(); bufferDevice->open(QIODevice::ReadWrite); // Get save parameters if (params.saveFormat == "imgpdf") { createImgPdf(bufferDevice, document); } else { createPdf(bufferDevice, document); } return bufferDevice; } //*********************************** // // Node.js methods // //*********************************** // Read PDF form fields NAN_METHOD(ReadSync) { NanScope(); // expect a number as the first argument NanUtf8String *fileName = new NanUtf8String(args[0]); ostringstream ss; int n = 0; // If file does not exist, throw error and return false if (!fileExists(**fileName)) { ss << "File \"" << **fileName << "\" does not exist"; NanThrowError(NanNew<String>(ss.str())); NanReturnValue(NanFalse()); } // Open document and return false and throw error if something goes wrong Poppler::Document *document = Poppler::Document::load(**fileName); if (document != NULL) { // Get field list n = document->numPages(); } else { ss << "Error occurred when reading \"" << **fileName << "\""; NanThrowError(NanNew<String>(ss.str())); NanReturnValue(NanFalse()); } // Store field value objects to v8 array Local<Array> fieldArray = NanNew<Array>(); int fieldNum = 0; for (int i = 0; i < n; i += 1) { Poppler::Page *page = document->page(i); foreach (Poppler::FormField *field, page->formFields()) { if (!field->isReadOnly() && field->isVisible()) { // Make JavaScript object out of the fieldnames Local<Object> obj = NanNew<Object>(); obj->Set(NanNew<String>("name"), NanNew<String>(field->fullyQualifiedName().toStdString())); obj->Set(NanNew<String>("page"), NanNew<Number>(i)); // ! TODO ! Now supports values only for "checkbox" and "text". Note. Poppler doesn't support checkboxes with hashtag names (aka using exportValue). string fieldType; // Set default value undefined obj->Set(NanNew<String>("value"), NanUndefined()); Poppler::FormFieldButton *myButton; Poppler::FormFieldChoice *myChoice; switch (field->type()) { // FormButton case Poppler::FormField::FormButton: myButton = (Poppler::FormFieldButton *)field; switch (myButton->buttonType()) { // Push case Poppler::FormFieldButton::Push: fieldType = "push_button"; break; case Poppler::FormFieldButton::CheckBox: fieldType = "checkbox"; obj->Set(NanNew<String>("value"), NanNew<Boolean>(myButton->state())); break; case Poppler::FormFieldButton::Radio: fieldType = "radio"; break; } break; // FormText case Poppler::FormField::FormText: obj->Set(NanNew<String>("value"), NanNew<String>(((Poppler::FormFieldText *)field)->text().toStdString())); fieldType = "text"; break; // FormChoice case Poppler::FormField::FormChoice: myChoice = (Poppler::FormFieldChoice *)field; switch (myChoice->choiceType()) { case Poppler::FormFieldChoice::ComboBox: fieldType = "combobox"; break; case Poppler::FormFieldChoice::ListBox: fieldType = "listbox"; break; } break; // FormSignature case Poppler::FormField::FormSignature: fieldType = "formsignature"; break; default: fieldType = "undefined"; break; } obj->Set(NanNew<String>("type"), NanNew<String>(fieldType.c_str())); fieldArray->Set(fieldNum, obj); fieldNum++; } } } NanReturnValue(fieldArray); } // Write PDF form fields NAN_METHOD(WriteSync) { NanScope(); // Check and return parameters given at JavaScript function call WriteFieldsParams params = v8ParamsToCpp(args); // Create and return pdf try { QBuffer *buffer = writePdfFields(params); Local<Object> returnPdf = NanNewBufferHandle(buffer->data().data(), buffer->size()); buffer->close(); delete buffer; NanReturnValue(returnPdf); } catch (string error) { NanThrowError(NanNew<String>(error)); NanReturnValue(NanNull()); } }
#include <nan.h> #include <iostream> #include <string> #include <sstream> #include <map> #include <stdlib.h> #include <stdio.h> #include <poppler/qt4/poppler-form.h> #include <poppler/qt4/poppler-qt4.h> #include <cairo/cairo.h> #include <cairo/cairo-pdf.h> #include <QtCore/QBuffer> #include <QtCore/QFile> #include <QtGui/QImage> #include "NodePoppler.h" // NOLINT(build/include) using namespace std; using v8::Number; using v8::String; using v8::Object; using v8::Local; using v8::Array; using v8::Value; using v8::Boolean; inline bool fileExists (const std::string& name) { if (FILE *file = fopen(name.c_str(), "r")) { fclose(file); return true; } else { return false; } } // Cairo write and read functions (to QBuffer) static cairo_status_t readPngFromBuffer(void *closure, unsigned char *data, unsigned int length) { QBuffer *myBuffer = (QBuffer *)closure; size_t bytes_read; bytes_read = myBuffer->read((char *)data, length); if (bytes_read != length) return CAIRO_STATUS_READ_ERROR; return CAIRO_STATUS_SUCCESS; } static cairo_status_t writePngToBuffer(void *closure, const unsigned char *data, unsigned int length) { QBuffer *myBuffer = (QBuffer *)closure; size_t bytes_wrote; bytes_wrote = myBuffer->write((char *)data, length); if (bytes_wrote != length) return CAIRO_STATUS_READ_ERROR; return CAIRO_STATUS_SUCCESS; } void createPdf(QBuffer *buffer, Poppler::Document *document) { ostringstream ss; Poppler::PDFConverter *converter = document->pdfConverter(); converter->setPDFOptions(converter->pdfOptions() | Poppler::PDFConverter::WithChanges); converter->setOutputDevice(buffer); if (!converter->convert()) { // enum Error // { // NoError, // FileLockedError, // OpenOutputError, // NotSupportedInputFileError // }; ss << "Error occurred when converting PDF: " << converter->lastError(); throw ss.str(); } } void createImgPdf(QBuffer *buffer, Poppler::Document *document) { // Initialize Cairo writing surface, and since we have images at 360 DPI, we'll set scaling. Width and Height are set for A4 dimensions. cairo_surface_t *surface = cairo_pdf_surface_create_for_stream(writePngToBuffer, buffer, 595.00, 842.00); cairo_t *cr = cairo_create(surface); cairo_scale(cr, 0.2, 0.2); int n = document->numPages(); for (int i = 0; i < n; i += 1) { Poppler::Page *page = document->page(i); // Save the page as PNG image to buffer. (We could use QFile if we want to save images to files) QBuffer *pageImage = new QBuffer(); pageImage->open(QIODevice::ReadWrite); QImage img = page->renderToImage(360, 360); img.save(pageImage, "png"); pageImage->seek(0); // Reading does not work if we don't reset the pointer // Ookay, let's try to make new page out of the image cairo_surface_t *drawImageSurface = cairo_image_surface_create_from_png_stream(readPngFromBuffer, pageImage); cairo_set_source_surface(cr, drawImageSurface, 0, 0); cairo_paint(cr); // Create new page if multipage document if (n > 0) { cairo_surface_show_page(surface); cr = cairo_create(surface); cairo_scale(cr, 0.2, 0.2); } pageImage->close(); } // Close Cairo cairo_destroy(cr); cairo_surface_finish(surface); cairo_surface_destroy (surface); } WriteFieldsParams v8ParamsToCpp(const v8::FunctionCallbackInfo<Value>& args) { Local<Object> parameters; string saveFormat = "imgpdf"; map<string, string> fields; string sourcePdfFileName = *NanAsciiString(args[0]); Local<Object> changeFields = args[1]->ToObject(); // Check if any configuration parameters if (args.Length() > 2) { parameters = args[2]->ToObject(); Local<Value> saveParam = parameters->Get(NanNew<String>("save")); if (!saveParam->IsUndefined()) { saveFormat = *NanAsciiString(parameters->Get(NanNew<String>("save"))); } } // Convert form fields to c++ map Local<Array> fieldArray = changeFields->GetPropertyNames(); for (uint32_t i = 0; i < fieldArray->Length(); i += 1) { Local<Value> name = fieldArray->Get(i); Local<Value> value = changeFields->Get(name); fields[std::string(*v8::String::Utf8Value(name))] = std::string(*v8::String::Utf8Value(value)); } // Create and return PDF struct WriteFieldsParams params(sourcePdfFileName, saveFormat, fields); return params; } // Pdf creator that is not dependent on V8 internals (safe at async?) QBuffer *writePdfFields(struct WriteFieldsParams params) { ostringstream ss; // If source file does not exist, throw error and return false if (!fileExists(params.sourcePdfFileName)) { ss << "File \"" << params.sourcePdfFileName << "\" does not exist"; throw ss.str(); } // Open document and return false and throw error if something goes wrong Poppler::Document *document = Poppler::Document::load(QString::fromStdString(params.sourcePdfFileName)); if (document == NULL) { ss << "Error occurred when reading \"" << params.sourcePdfFileName << "\""; throw ss.str(); } // Fill form int n = document->numPages(); for (int i = 0; i < n; i += 1) { Poppler::Page *page = document->page(i); foreach (Poppler::FormField *field, page->formFields()) { string fieldName = field->fullyQualifiedName().toStdString(); if (!field->isReadOnly() && field->isVisible() && params.fields.count(fieldName)) { // Text if (field->type() == Poppler::FormField::FormText) { Poppler::FormFieldText *textField = (Poppler::FormFieldText *) field; textField->setText(QString::fromUtf8(params.fields[fieldName].c_str())); } // Choice if (field->type() == Poppler::FormField::FormChoice) { Poppler::FormFieldChoice *choiceField = (Poppler::FormFieldChoice *) field; if (choiceField->isEditable()) { choiceField->setEditChoice(QString::fromUtf8(params.fields[fieldName].c_str())); } else { QStringList possibleChoices = choiceField->choices(); QString proposedChoice = QString::fromUtf8(params.fields[fieldName].c_str()); int index = possibleChoices.indexOf(proposedChoice); if (index >= 0) { QList<int> choiceList; choiceList << index; choiceField->setCurrentChoices(choiceList); } } } // Button if (field->type() == Poppler::FormField::FormButton) { Poppler::FormFieldButton *buttonField = (Poppler::FormFieldButton *) field; if (params.fields[fieldName].compare("true") == 0) { buttonField->setState(true); } else { buttonField->setState(false); } } } } } // Now save and return the document QBuffer *bufferDevice = new QBuffer(); bufferDevice->open(QIODevice::ReadWrite); // Get save parameters if (params.saveFormat == "imgpdf") { createImgPdf(bufferDevice, document); } else { createPdf(bufferDevice, document); } return bufferDevice; } //*********************************** // // Node.js methods // //*********************************** // Read PDF form fields NAN_METHOD(ReadSync) { NanScope(); // expect a number as the first argument NanUtf8String *fileName = new NanUtf8String(args[0]); ostringstream ss; int n = 0; // If file does not exist, throw error and return false if (!fileExists(**fileName)) { ss << "File \"" << **fileName << "\" does not exist"; NanThrowError(NanNew<String>(ss.str())); NanReturnValue(NanFalse()); } // Open document and return false and throw error if something goes wrong Poppler::Document *document = Poppler::Document::load(**fileName); if (document != NULL) { // Get field list n = document->numPages(); } else { ss << "Error occurred when reading \"" << **fileName << "\""; NanThrowError(NanNew<String>(ss.str())); NanReturnValue(NanFalse()); } // Store field value objects to v8 array Local<Array> fieldArray = NanNew<Array>(); int fieldNum = 0; for (int i = 0; i < n; i += 1) { Poppler::Page *page = document->page(i); foreach (Poppler::FormField *field, page->formFields()) { if (!field->isReadOnly() && field->isVisible()) { // Make JavaScript object out of the fieldnames Local<Object> obj = NanNew<Object>(); obj->Set(NanNew<String>("name"), NanNew<String>(field->fullyQualifiedName().toStdString())); obj->Set(NanNew<String>("page"), NanNew<Number>(i)); // ! TODO ! Now supports values only for "checkbox" and "text". Note. Poppler doesn't support checkboxes with hashtag names (aka using exportValue). string fieldType; Local<Array> choiceArray = NanNew<Array>(); // Set default value undefined obj->Set(NanNew<String>("value"), NanUndefined()); Poppler::FormFieldButton *myButton; Poppler::FormFieldChoice *myChoice; switch (field->type()) { // FormButton case Poppler::FormField::FormButton: myButton = (Poppler::FormFieldButton *)field; switch (myButton->buttonType()) { // Push case Poppler::FormFieldButton::Push: fieldType = "push_button"; break; case Poppler::FormFieldButton::CheckBox: fieldType = "checkbox"; obj->Set(NanNew<String>("value"), NanNew<Boolean>(myButton->state())); break; case Poppler::FormFieldButton::Radio: fieldType = "radio"; break; } break; // FormText case Poppler::FormField::FormText: obj->Set(NanNew<String>("value"), NanNew<String>(((Poppler::FormFieldText *)field)->text().toStdString())); fieldType = "text"; break; // FormChoice case Poppler::FormField::FormChoice: { myChoice = (Poppler::FormFieldChoice *)field; QStringList possibleChoices = myChoice->choices(); for (int i = 0; i < possibleChoices.size(); i++) { choiceArray->Set(i, NanNew<String>(possibleChoices.at(i).toStdString())); } obj->Set(NanNew<String>("choices"), choiceArray); switch (myChoice->choiceType()) { case Poppler::FormFieldChoice::ComboBox: fieldType = "combobox"; break; case Poppler::FormFieldChoice::ListBox: fieldType = "listbox"; break; } break; } // FormSignature case Poppler::FormField::FormSignature: fieldType = "formsignature"; break; default: fieldType = "undefined"; break; } obj->Set(NanNew<String>("type"), NanNew<String>(fieldType.c_str())); fieldArray->Set(fieldNum, obj); fieldNum++; } } } NanReturnValue(fieldArray); } // Write PDF form fields NAN_METHOD(WriteSync) { NanScope(); // Check and return parameters given at JavaScript function call WriteFieldsParams params = v8ParamsToCpp(args); // Create and return pdf try { QBuffer *buffer = writePdfFields(params); Local<Object> returnPdf = NanNewBufferHandle(buffer->data().data(), buffer->size()); buffer->close(); delete buffer; NanReturnValue(returnPdf); } catch (string error) { NanThrowError(NanNew<String>(error)); NanReturnValue(NanNull()); } }
Add read and write support for ChoiceType fields
Add read and write support for ChoiceType fields
C++
mit
tpisto/pdf-fill-form,tpisto/pdf-fill-form,zepspaiva/pdf-fill-form-latin1,zepspaiva/pdf-fill-form-latin1,zepspaiva/pdf-fill-form-latin1,tpisto/pdf-fill-form,zepspaiva/pdf-fill-form-latin1,tpisto/pdf-fill-form
7f5c8c3e9fa5880b9a783486bf239302852616ce
src/PrimeTower.cpp
src/PrimeTower.cpp
#include "PrimeTower.h" #include <limits> #include "ExtruderTrain.h" #include "sliceDataStorage.h" #include "gcodeExport.h" #include "LayerPlan.h" #include "infill.h" #include "PrintFeature.h" namespace cura { PrimeTower::PrimeTower(const SliceDataStorage& storage) : is_hollow(false) , wipe_from_middle(false) { enabled = storage.getSettingBoolean("prime_tower_enable") && storage.getSettingInMicrons("prime_tower_wall_thickness") > 10 && storage.getSettingInMicrons("prime_tower_size") > 10; if (enabled) { generateGroundpoly(storage); } } void PrimeTower::generateGroundpoly(const SliceDataStorage& storage) { extruder_count = storage.meshgroup->getExtruderCount(); int64_t prime_tower_wall_thickness = storage.getSettingInMicrons("prime_tower_wall_thickness"); int64_t tower_size = storage.getSettingInMicrons("prime_tower_size"); if (prime_tower_wall_thickness * 2 < tower_size) { is_hollow = true; } PolygonRef p = ground_poly.newPoly(); int tower_distance = 0; int x = storage.getSettingInMicrons("prime_tower_position_x"); // storage.model_max.x int y = storage.getSettingInMicrons("prime_tower_position_y"); // storage.model_max.y p.add(Point(x + tower_distance, y + tower_distance)); p.add(Point(x + tower_distance, y + tower_distance + tower_size)); p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size)); p.add(Point(x + tower_distance - tower_size, y + tower_distance)); middle = Point(x - tower_size / 2, y + tower_size / 2); if (is_hollow) { ground_poly = ground_poly.difference(ground_poly.offset(-prime_tower_wall_thickness)); } post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2); } void PrimeTower::generatePaths(const SliceDataStorage& storage) { enabled &= storage.max_print_height_second_to_last_extruder >= 0; //Maybe it turns out that we don't need a prime tower after all because there are no layer switches. if (enabled) { generatePaths_denseInfill(storage); generateWipeLocations(storage); } } void PrimeTower::generatePaths_denseInfill(const SliceDataStorage& storage) { int n_patterns = 2; // alternating patterns between layers int infill_overlap = 60; // so that it can't be zero; EDIT: wtf? int extra_infill_shift = 0; int64_t z = 0; // (TODO) because the prime tower stores the paths for each extruder for once instead of generating each layer, we don't know the z position for (int extruder = 0; extruder < extruder_count; extruder++) { int line_width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("prime_tower_line_width"); patterns_per_extruder.emplace_back(n_patterns); std::vector<ExtrusionMoves>& patterns = patterns_per_extruder.back(); patterns.resize(n_patterns); for (int pattern_idx = 0; pattern_idx < n_patterns; pattern_idx++) { patterns[pattern_idx].polygons = ground_poly.offset(-line_width / 2); Polygons& result_lines = patterns[pattern_idx].lines; int outline_offset = -line_width; int line_distance = line_width; double fill_angle = 45 + pattern_idx * 90; Polygons result_polygons; // should remain empty, since we generate lines pattern! Infill infill_comp(EFillMethod::LINES, ground_poly, outline_offset, line_width, line_distance, infill_overlap, fill_angle, z, extra_infill_shift); infill_comp.generate(result_polygons, result_lines); } } } void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcodeLayer, const GCodeExport& gcode, const int layer_nr, const int prev_extruder, const int new_extruder) const { if (!enabled) { return; } if (gcodeLayer.getPrimeTowerIsPlanned()) { // don't print the prime tower if it has been printed already return; } if (layer_nr > storage.max_print_height_second_to_last_extruder + 1) { return; } bool pre_wipe = storage.meshgroup->getExtruderTrain(new_extruder)->getSettingBoolean("dual_pre_wipe"); bool post_wipe = storage.meshgroup->getExtruderTrain(prev_extruder)->getSettingBoolean("prime_tower_wipe_enabled"); if (prev_extruder == new_extruder) { pre_wipe = false; post_wipe = false; } // pre-wipe: if (pre_wipe) { preWipe(storage, gcodeLayer, layer_nr, new_extruder); } addToGcode_denseInfill(gcodeLayer, layer_nr, new_extruder); // post-wipe: if (post_wipe) { //Make sure we wipe the old extruder on the prime tower. gcodeLayer.addTravel(post_wipe_point - gcode.getExtruderOffset(prev_extruder) + gcode.getExtruderOffset(new_extruder)); } gcodeLayer.setPrimeTowerIsPlanned(); } void PrimeTower::addToGcode_denseInfill(LayerPlan& gcode_layer, const int layer_nr, const int extruder_nr) const { const ExtrusionMoves& pattern = patterns_per_extruder[extruder_nr][((layer_nr % 2) + 2) % 2]; // +2) %2 to handle negative layer numbers const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr]; gcode_layer.addPolygonsByOptimizer(pattern.polygons, &config); gcode_layer.addLinesByOptimizer(pattern.lines, &config, SpaceFillType::Lines); } Point PrimeTower::getLocationBeforePrimeTower(const SliceDataStorage& storage) const { Point ret(0, 0); int absolute_starting_points = 0; for (int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++) { ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(0); if (train.getSettingBoolean("machine_extruder_start_pos_abs")) { ret += Point(train.getSettingInMicrons("machine_extruder_start_pos_x"), train.getSettingInMicrons("machine_extruder_start_pos_y")); absolute_starting_points++; } } if (absolute_starting_points > 0) { // take the average over all absolute starting positions ret /= absolute_starting_points; } else { // use the middle of the bed if (!storage.getSettingBoolean("machine_center_is_zero")) { ret = Point(storage.getSettingInMicrons("machine_width"), storage.getSettingInMicrons("machine_depth")) / 2; } // otherwise keep (0, 0) } return ret; } void PrimeTower::generateWipeLocations(const SliceDataStorage& storage) { wipe_from_middle = is_hollow; // only wipe from the middle of the prime tower if we have a z hop already on the first move after the layer switch for (int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++) { const ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(extruder_nr); wipe_from_middle &= train.getSettingBoolean("retraction_hop_enabled") && (!train.getSettingBoolean("retraction_hop_only_when_collides") || train.getSettingBoolean("retraction_hop_after_extruder_switch")); } PolygonsPointIndex segment_start; // from where to start the sequence of wipe points PolygonsPointIndex segment_end; // where to end the sequence of wipe points if (wipe_from_middle) { // take the same start as end point so that the whole poly os covered. // find the inner polygon. segment_start = segment_end = PolygonUtils::findNearestVert(middle, ground_poly); } else { // take the closer corner of the wipe tower and generate wipe locations on that side only: // // | // | // +----- // . // ^ nozzle switch location Point from = getLocationBeforePrimeTower(storage); // find the single line segment closest to [from] pointing most toward [from] PolygonsPointIndex closest_vert = PolygonUtils::findNearestVert(from, ground_poly); PolygonsPointIndex prev = closest_vert.prev(); PolygonsPointIndex next = closest_vert.next(); int64_t prev_dot_score = dot(from - closest_vert.p(), turn90CCW(prev.p() - closest_vert.p())); int64_t next_dot_score = dot(from - closest_vert.p(), turn90CCW(closest_vert.p() - next.p())); if (prev_dot_score > next_dot_score) { segment_start = prev; segment_end = closest_vert; } else { segment_start = closest_vert; segment_end = next; } } PolygonUtils::spreadDots(segment_start, segment_end, number_of_pre_wipe_locations, pre_wipe_locations); } void PrimeTower::preWipe(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int layer_nr, const int extruder_nr) const { int current_pre_wipe_location_idx = (pre_wipe_location_skip * layer_nr) % number_of_pre_wipe_locations; const ClosestPolygonPoint wipe_location = pre_wipe_locations[current_pre_wipe_location_idx]; ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(extruder_nr); const int inward_dist = train.getSettingInMicrons("machine_nozzle_size") * 3 / 2 ; const int start_dist = train.getSettingInMicrons("machine_nozzle_size") * 2; const Point prime_end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist); const Point outward_dir = wipe_location.location - prime_end; const Point prime_start = wipe_location.location + normal(outward_dir, start_dist); const double purge_volume = train.getSettingInCubicMillimeters("prime_tower_purge_volume"); // Volume to be primed if (wipe_from_middle) { // for hollow wipe tower: // start from above // go to wipe start // go to the Z height of the previous/current layer // wipe // go to normal layer height (automatically on the next extrusion move)... GCodePath& toward_middle = gcode_layer.addTravel(middle); toward_middle.perform_z_hop = true; gcode_layer.forceNewPathStart(); if (purge_volume > 0) { // Find out how much purging needs to be done. const coord_t purge_move_length = vSize(middle - prime_start); const unsigned int line_width = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr].getLineWidth(); const double layer_height_mm = (layer_nr == 0) ? train.getSettingInMillimeters("layer_height_0") : train.getSettingInMillimeters("layer_height"); const double normal_volume = INT2MM(INT2MM(purge_move_length * line_width)) * layer_height_mm; // Volume extruded on the "normal" move float purge_flow = purge_volume / normal_volume; // As we need a plan, which can't have a stationary extrusion, we use an extrusion move to prime. // This has the added benefit that it will evenly spread the primed material inside the tower. gcode_layer.addExtrusionMove(prime_start, &gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr], SpaceFillType::None, purge_flow); } else { // Normal move behavior to wipe start location. GCodePath& toward_wipe_start = gcode_layer.addTravel_simple(prime_start); toward_wipe_start.perform_z_hop = false; toward_wipe_start.retract = true; } } else { if (purge_volume > 0) { // Find location to start purge (we're purging right outside of the tower) const Point purge_start = prime_start + normal(outward_dir, start_dist); gcode_layer.addTravel(purge_start); // Calculate how much we need to purge int purge_move_length = vSize(purge_start - prime_start); const unsigned int line_width = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr].getLineWidth(); const double layer_height_mm = (layer_nr == 0)? train.getSettingInMillimeters("layer_height_0") : train.getSettingInMillimeters("layer_height"); const double normal_volume = INT2MM(INT2MM(purge_move_length * line_width)) * layer_height_mm; // Volume extruded on the "normal" move float purge_flow = purge_volume / normal_volume; // As we need a plan, which can't have a stationary extrusion, we use an extrusion move to prime. gcode_layer.addExtrusionMove(prime_start, &gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr], SpaceFillType::None, purge_flow); } gcode_layer.addTravel(prime_start); } float flow = 0.0001; // Force this path being interpreted as an extrusion path, so that no Z hop will occur (TODO: really separately handle travel and extrusion moves) gcode_layer.addExtrusionMove(prime_end, &gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr], SpaceFillType::None, flow); } void PrimeTower::subtractFromSupport(SliceDataStorage& storage) { const Polygons outside_polygon = ground_poly.getOutsidePolygons(); for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++) { storage.support.supportLayers[layer].supportAreas = storage.support.supportLayers[layer].supportAreas.difference(outside_polygon); } } }//namespace cura
#include "PrimeTower.h" #include <limits> #include "ExtruderTrain.h" #include "sliceDataStorage.h" #include "gcodeExport.h" #include "LayerPlan.h" #include "infill.h" #include "PrintFeature.h" namespace cura { PrimeTower::PrimeTower(const SliceDataStorage& storage) : is_hollow(false) , wipe_from_middle(false) { enabled = storage.getSettingBoolean("prime_tower_enable") && storage.getSettingInMicrons("prime_tower_wall_thickness") > 10 && storage.getSettingInMicrons("prime_tower_size") > 10; if (enabled) { generateGroundpoly(storage); } } void PrimeTower::generateGroundpoly(const SliceDataStorage& storage) { extruder_count = storage.meshgroup->getExtruderCount(); int64_t prime_tower_wall_thickness = storage.getSettingInMicrons("prime_tower_wall_thickness"); int64_t tower_size = storage.getSettingInMicrons("prime_tower_size"); if (prime_tower_wall_thickness * 2 < tower_size) { is_hollow = true; } PolygonRef p = ground_poly.newPoly(); int tower_distance = 0; int x = storage.getSettingInMicrons("prime_tower_position_x"); // storage.model_max.x int y = storage.getSettingInMicrons("prime_tower_position_y"); // storage.model_max.y p.add(Point(x + tower_distance, y + tower_distance)); p.add(Point(x + tower_distance, y + tower_distance + tower_size)); p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size)); p.add(Point(x + tower_distance - tower_size, y + tower_distance)); middle = Point(x - tower_size / 2, y + tower_size / 2); if (is_hollow) { ground_poly = ground_poly.difference(ground_poly.offset(-prime_tower_wall_thickness)); } post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2); } void PrimeTower::generatePaths(const SliceDataStorage& storage) { enabled &= storage.max_print_height_second_to_last_extruder >= 0; //Maybe it turns out that we don't need a prime tower after all because there are no layer switches. if (enabled) { generatePaths_denseInfill(storage); generateWipeLocations(storage); } } void PrimeTower::generatePaths_denseInfill(const SliceDataStorage& storage) { int n_patterns = 2; // alternating patterns between layers int infill_overlap = 60; // so that it can't be zero; EDIT: wtf? int extra_infill_shift = 0; int64_t z = 0; // (TODO) because the prime tower stores the paths for each extruder for once instead of generating each layer, we don't know the z position for (int extruder = 0; extruder < extruder_count; extruder++) { int line_width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("prime_tower_line_width"); patterns_per_extruder.emplace_back(n_patterns); std::vector<ExtrusionMoves>& patterns = patterns_per_extruder.back(); patterns.resize(n_patterns); for (int pattern_idx = 0; pattern_idx < n_patterns; pattern_idx++) { patterns[pattern_idx].polygons = ground_poly.offset(-line_width / 2); Polygons& result_lines = patterns[pattern_idx].lines; int outline_offset = -line_width; int line_distance = line_width; double fill_angle = 45 + pattern_idx * 90; Polygons result_polygons; // should remain empty, since we generate lines pattern! Infill infill_comp(EFillMethod::LINES, ground_poly, outline_offset, line_width, line_distance, infill_overlap, fill_angle, z, extra_infill_shift); infill_comp.generate(result_polygons, result_lines); } } } void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcodeLayer, const GCodeExport& gcode, const int layer_nr, const int prev_extruder, const int new_extruder) const { if (!enabled) { return; } if (gcodeLayer.getPrimeTowerIsPlanned()) { // don't print the prime tower if it has been printed already return; } if (layer_nr > storage.max_print_height_second_to_last_extruder + 1) { return; } bool pre_wipe = storage.meshgroup->getExtruderTrain(new_extruder)->getSettingBoolean("dual_pre_wipe"); bool post_wipe = storage.meshgroup->getExtruderTrain(prev_extruder)->getSettingBoolean("prime_tower_wipe_enabled"); if (prev_extruder == new_extruder) { pre_wipe = false; post_wipe = false; } // pre-wipe: if (pre_wipe) { preWipe(storage, gcodeLayer, layer_nr, new_extruder); } addToGcode_denseInfill(gcodeLayer, layer_nr, new_extruder); // post-wipe: if (post_wipe) { //Make sure we wipe the old extruder on the prime tower. gcodeLayer.addTravel(post_wipe_point - gcode.getExtruderOffset(prev_extruder) + gcode.getExtruderOffset(new_extruder)); } gcodeLayer.setPrimeTowerIsPlanned(); } void PrimeTower::addToGcode_denseInfill(LayerPlan& gcode_layer, const int layer_nr, const int extruder_nr) const { const ExtrusionMoves& pattern = patterns_per_extruder[extruder_nr][((layer_nr % 2) + 2) % 2]; // +2) %2 to handle negative layer numbers const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr]; gcode_layer.addPolygonsByOptimizer(pattern.polygons, &config); gcode_layer.addLinesByOptimizer(pattern.lines, &config, SpaceFillType::Lines); } Point PrimeTower::getLocationBeforePrimeTower(const SliceDataStorage& storage) const { Point ret(0, 0); int absolute_starting_points = 0; for (int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++) { ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(0); if (train.getSettingBoolean("machine_extruder_start_pos_abs")) { ret += Point(train.getSettingInMicrons("machine_extruder_start_pos_x"), train.getSettingInMicrons("machine_extruder_start_pos_y")); absolute_starting_points++; } } if (absolute_starting_points > 0) { // take the average over all absolute starting positions ret /= absolute_starting_points; } else { // use the middle of the bed if (!storage.getSettingBoolean("machine_center_is_zero")) { ret = Point(storage.getSettingInMicrons("machine_width"), storage.getSettingInMicrons("machine_depth")) / 2; } // otherwise keep (0, 0) } return ret; } void PrimeTower::generateWipeLocations(const SliceDataStorage& storage) { wipe_from_middle = is_hollow; // only wipe from the middle of the prime tower if we have a z hop already on the first move after the layer switch for (int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++) { const ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(extruder_nr); wipe_from_middle &= train.getSettingBoolean("retraction_hop_enabled") && (!train.getSettingBoolean("retraction_hop_only_when_collides") || train.getSettingBoolean("retraction_hop_after_extruder_switch")); } PolygonsPointIndex segment_start; // from where to start the sequence of wipe points PolygonsPointIndex segment_end; // where to end the sequence of wipe points if (wipe_from_middle) { // take the same start as end point so that the whole poly os covered. // find the inner polygon. segment_start = segment_end = PolygonUtils::findNearestVert(middle, ground_poly); } else { // take the closer corner of the wipe tower and generate wipe locations on that side only: // // | // | // +----- // . // ^ nozzle switch location Point from = getLocationBeforePrimeTower(storage); // find the single line segment closest to [from] pointing most toward [from] PolygonsPointIndex closest_vert = PolygonUtils::findNearestVert(from, ground_poly); PolygonsPointIndex prev = closest_vert.prev(); PolygonsPointIndex next = closest_vert.next(); int64_t prev_dot_score = dot(from - closest_vert.p(), turn90CCW(prev.p() - closest_vert.p())); int64_t next_dot_score = dot(from - closest_vert.p(), turn90CCW(closest_vert.p() - next.p())); if (prev_dot_score > next_dot_score) { segment_start = prev; segment_end = closest_vert; } else { segment_start = closest_vert; segment_end = next; } } PolygonUtils::spreadDots(segment_start, segment_end, number_of_pre_wipe_locations, pre_wipe_locations); } void PrimeTower::preWipe(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int layer_nr, const int extruder_nr) const { int current_pre_wipe_location_idx = (pre_wipe_location_skip * layer_nr) % number_of_pre_wipe_locations; const ClosestPolygonPoint wipe_location = pre_wipe_locations[current_pre_wipe_location_idx]; ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(extruder_nr); const int inward_dist = train.getSettingInMicrons("machine_nozzle_size") * 3 / 2 ; const int start_dist = train.getSettingInMicrons("machine_nozzle_size") * 2; const Point prime_end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist); const Point outward_dir = wipe_location.location - prime_end; const Point prime_start = wipe_location.location + normal(outward_dir, start_dist); const double purge_volume = train.getSettingInCubicMillimeters("prime_tower_purge_volume"); // Volume to be primed if (wipe_from_middle) { // for hollow wipe tower: // start from above // go to wipe start // go to the Z height of the previous/current layer // wipe // go to normal layer height (automatically on the next extrusion move)... GCodePath& toward_middle = gcode_layer.addTravel(middle); toward_middle.perform_z_hop = true; gcode_layer.forceNewPathStart(); if (purge_volume > 0) { // Find out how much purging needs to be done. const coord_t purge_move_length = vSize(middle - prime_start); const unsigned int line_width = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr].getLineWidth(); const double layer_height_mm = (layer_nr == 0) ? train.getSettingInMillimeters("layer_height_0") : train.getSettingInMillimeters("layer_height"); const double normal_volume = INT2MM(INT2MM(purge_move_length * line_width)) * layer_height_mm; // Volume extruded on the "normal" move float purge_flow = purge_volume / normal_volume; // As we need a plan, which can't have a stationary extrusion, we use an extrusion move to prime. // This has the added benefit that it will evenly spread the primed material inside the tower. gcode_layer.addExtrusionMove(prime_start, &gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr], SpaceFillType::None, purge_flow); } else { // Normal move behavior to wipe start location. GCodePath& toward_wipe_start = gcode_layer.addTravel_simple(prime_start); toward_wipe_start.perform_z_hop = false; toward_wipe_start.retract = true; } } else { if (purge_volume > 0) { // Find location to start purge (we're purging right outside of the tower) const Point purge_start = prime_start + normal(outward_dir, start_dist); gcode_layer.addTravel(purge_start); // Calculate how much we need to purge const coord_t purge_move_length = vSize(purge_start - prime_start); const unsigned int line_width = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr].getLineWidth(); const double layer_height_mm = (layer_nr == 0)? train.getSettingInMillimeters("layer_height_0") : train.getSettingInMillimeters("layer_height"); const double normal_volume = INT2MM(INT2MM(purge_move_length * line_width)) * layer_height_mm; // Volume extruded on the "normal" move float purge_flow = purge_volume / normal_volume; // As we need a plan, which can't have a stationary extrusion, we use an extrusion move to prime. gcode_layer.addExtrusionMove(prime_start, &gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr], SpaceFillType::None, purge_flow); } gcode_layer.addTravel(prime_start); } float flow = 0.0001; // Force this path being interpreted as an extrusion path, so that no Z hop will occur (TODO: really separately handle travel and extrusion moves) gcode_layer.addExtrusionMove(prime_end, &gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr], SpaceFillType::None, flow); } void PrimeTower::subtractFromSupport(SliceDataStorage& storage) { const Polygons outside_polygon = ground_poly.getOutsidePolygons(); for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++) { storage.support.supportLayers[layer].supportAreas = storage.support.supportLayers[layer].supportAreas.difference(outside_polygon); } } }//namespace cura
Use coord_t for wipe distance
Use coord_t for wipe distance CURA-3094 coord_t can handle larger numbers than int.
C++
agpl-3.0
alephobjects/CuraEngine,ROBO3D/CuraEngine,alephobjects/CuraEngine,ROBO3D/CuraEngine,alephobjects/CuraEngine,Ultimaker/CuraEngine,Ultimaker/CuraEngine,ROBO3D/CuraEngine
5a7c3553d5eb44cf037ecbd66492092753369deb
flash-graph/libgraph-algs/wcc.cpp
flash-graph/libgraph-algs/wcc.cpp
/** * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng ([email protected]) * * This file is part of FlashGraph. * * 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. */ #ifdef PROFILER #include <google/profiler.h> #endif #include <vector> #include <unordered_map> #include "thread.h" #include "io_interface.h" #include "container.h" #include "concurrency.h" #include "vertex_index.h" #include "graph_engine.h" #include "graph_config.h" #include "FG_vector.h" #include "FGlib.h" atomic_number<long> num_visits; enum wcc_stage_t { REMOVE_EMPTY, FIND_COMPONENTS, } wcc_stage; class component_message: public vertex_message { int id; public: component_message(vertex_id_t id): vertex_message( sizeof(component_message), true) { this->id = id; } vertex_id_t get_id() const { return id; } }; class wcc_vertex: public compute_vertex { bool updated; bool empty; vertex_id_t component_id; public: wcc_vertex(vertex_id_t id): compute_vertex(id) { component_id = id; updated = true; // TODO assert(0); empty = false; } bool is_empty(graph_engine &graph) const { return empty; } bool belong2component() const { return component_id != UINT_MAX; } vertex_id_t get_component_id() const { return component_id; } void run(vertex_program &prog) { if (updated) { vertex_id_t id = get_id(); request_vertices(&id, 1); updated = false; } } void run(vertex_program &prog, const page_vertex &vertex); void run_on_message(vertex_program &, const vertex_message &msg1) { component_message &msg = (component_message &) msg1; if (msg.get_id() < component_id) { updated = true; component_id = msg.get_id(); } } }; void wcc_vertex::run(vertex_program &prog, const page_vertex &vertex) { // We need to add the neighbors of the vertex to the queue of // the next level. int num_dests = vertex.get_num_edges(BOTH_EDGES); edge_seq_iterator it = vertex.get_neigh_seq_it(BOTH_EDGES, 0, num_dests); component_message msg(component_id); prog.multicast_msg(it, msg); } /** * This query is to save the component IDs to a FG vector. */ class save_cid_query: public vertex_query { FG_vector<vertex_id_t>::ptr vec; public: save_cid_query(FG_vector<vertex_id_t>::ptr vec) { this->vec = vec; } virtual void run(graph_engine &graph, compute_vertex &v) { wcc_vertex &wcc_v = (wcc_vertex &) v; if (!wcc_v.is_empty(graph)) vec->set(wcc_v.get_id(), wcc_v.get_component_id()); else vec->set(wcc_v.get_id(), INVALID_VERTEX_ID); } virtual void merge(graph_engine &graph, vertex_query::ptr q) { } virtual ptr clone() { return vertex_query::ptr(new save_cid_query(vec)); } }; FG_vector<vertex_id_t>::ptr compute_wcc(FG_graph::ptr fg) { graph_index::ptr index = NUMA_graph_index<wcc_vertex>::create( fg->get_index_file()); graph_engine::ptr graph = graph_engine::create(fg->get_graph_file(), index, fg->get_configs()); printf("weakly connected components starts\n"); #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStart(graph_conf.get_prof_file().c_str()); #endif struct timeval start, end; gettimeofday(&start, NULL); graph->start_all(); graph->wait4complete(); gettimeofday(&end, NULL); printf("WCC takes %f seconds\n", time_diff(start, end)); #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStop(); #endif FG_vector<vertex_id_t>::ptr vec = FG_vector<vertex_id_t>::create(graph); graph->query_on_all(vertex_query::ptr(new save_cid_query(vec))); return vec; }
/** * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng ([email protected]) * * This file is part of FlashGraph. * * 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. */ #ifdef PROFILER #include <google/profiler.h> #endif #include <vector> #include <unordered_map> #include "thread.h" #include "io_interface.h" #include "container.h" #include "concurrency.h" #include "vertex_index.h" #include "graph_engine.h" #include "graph_config.h" #include "FG_vector.h" #include "FGlib.h" atomic_number<long> num_visits; enum wcc_stage_t { FIND_COMPONENTS, REMOVE_EMPTY, } wcc_stage; class component_message: public vertex_message { int id; public: component_message(vertex_id_t id): vertex_message( sizeof(component_message), true) { this->id = id; } vertex_id_t get_id() const { return id; } }; class wcc_vertex: public compute_vertex { bool updated; bool empty; vertex_id_t component_id; public: wcc_vertex(vertex_id_t id): compute_vertex(id) { component_id = id; updated = true; empty = false; } bool is_empty(graph_engine &graph) const { return empty; } bool belong2component() const { return component_id != UINT_MAX; } vertex_id_t get_component_id() const { return component_id; } void run(vertex_program &prog) { vertex_id_t id = get_id(); if (wcc_stage == wcc_stage_t::FIND_COMPONENTS) { if (updated) { request_vertices(&id, 1); updated = false; } } else { request_num_edges(&id, 1); } } void run(vertex_program &prog, const page_vertex &vertex); void run_on_message(vertex_program &, const vertex_message &msg1) { component_message &msg = (component_message &) msg1; if (msg.get_id() < component_id) { updated = true; component_id = msg.get_id(); } } void run_on_num_edges(vertex_id_t id, vsize_t num_edges) { assert(get_id() == id); empty = (num_edges == 0); } }; void wcc_vertex::run(vertex_program &prog, const page_vertex &vertex) { // We need to add the neighbors of the vertex to the queue of // the next level. int num_dests = vertex.get_num_edges(BOTH_EDGES); edge_seq_iterator it = vertex.get_neigh_seq_it(BOTH_EDGES, 0, num_dests); component_message msg(component_id); prog.multicast_msg(it, msg); } /** * This query is to save the component IDs to a FG vector. */ class save_cid_query: public vertex_query { FG_vector<vertex_id_t>::ptr vec; public: save_cid_query(FG_vector<vertex_id_t>::ptr vec) { this->vec = vec; } virtual void run(graph_engine &graph, compute_vertex &v) { wcc_vertex &wcc_v = (wcc_vertex &) v; if (!wcc_v.is_empty(graph)) vec->set(wcc_v.get_id(), wcc_v.get_component_id()); else vec->set(wcc_v.get_id(), INVALID_VERTEX_ID); } virtual void merge(graph_engine &graph, vertex_query::ptr q) { } virtual ptr clone() { return vertex_query::ptr(new save_cid_query(vec)); } }; FG_vector<vertex_id_t>::ptr compute_wcc(FG_graph::ptr fg) { graph_index::ptr index = NUMA_graph_index<wcc_vertex>::create( fg->get_index_file()); graph_engine::ptr graph = graph_engine::create(fg->get_graph_file(), index, fg->get_configs()); printf("weakly connected components starts\n"); #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStart(graph_conf.get_prof_file().c_str()); #endif struct timeval start, end; gettimeofday(&start, NULL); wcc_stage = wcc_stage_t::FIND_COMPONENTS; graph->start_all(); graph->wait4complete(); gettimeofday(&end, NULL); printf("WCC takes %f seconds\n", time_diff(start, end)); #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStop(); #endif wcc_stage = wcc_stage_t::REMOVE_EMPTY; graph->start_all(); graph->wait4complete(); FG_vector<vertex_id_t>::ptr vec = FG_vector<vertex_id_t>::create(graph); graph->query_on_all(vertex_query::ptr(new save_cid_query(vec))); return vec; }
fix wcc for the new graph engine.
[Graph]: fix wcc for the new graph engine.
C++
apache-2.0
silky/FlashGraph,icoming/FlashX,silky/FlashGraph,flashxio/FlashX,flashxio/FlashX,icoming/FlashGraph,flashxio/FlashX,icoming/FlashX,silky/FlashGraph,icoming/FlashX,icoming/FlashGraph,icoming/FlashX,silky/FlashGraph,zheng-da/FlashX,zheng-da/FlashX,icoming/FlashX,silky/FlashGraph,zheng-da/FlashX,zheng-da/FlashX,icoming/FlashGraph,flashxio/FlashX,flashxio/FlashX,zheng-da/FlashX,flashxio/FlashX,icoming/FlashGraph,icoming/FlashGraph
d4b2d6ebaa377e5a66c4c5e8632073217bda5ef0
src/lib/process_splitters/AlignmentOffsets.hpp
src/lib/process_splitters/AlignmentOffsets.hpp
#pragma once #include "Utility.hpp" #include "Parse.hpp" #include <sam.h> #include <boost/format.hpp> #include <stdint.h> #include <string.h> #include <stdexcept> using boost::format; struct AlignmentOffsets { uint32_t raLen; uint32_t qaLen; uint32_t sclip; uint32_t eclip; bool first; AlignmentOffsets(char const* cigar) : raLen(0) , qaLen(0) , sclip(0) , eclip(0) , first(true) { char const* beg = cigar; std::size_t len = strlen(beg); char const* end = beg + len; for(; *beg != '\0'; ++beg) { uint32_t oplen = 0; if (!auto_parse(beg, end, oplen) || !cigar::valid_cigar_len(oplen)) { throw std::runtime_error(str(format( "Error parsing cigar string %1%: expected number at position %2%" ) % cigar % (beg - cigar))); } int op = cigar::opcode_for_char(*beg); if (op < 0) { throw std::runtime_error(str(format( "Error parsing cigar string %1%: invalid cigar op char at position %2%" ) % cigar % (beg - cigar))); } update_offset(op, oplen); } } AlignmentOffsets(uint32_t const* cigar, uint32_t const& n_cigar) : raLen(0) , qaLen(0) , sclip(0) , eclip(0) , first(true) { for (uint32_t i = 0; i < n_cigar; ++i) { update_offset(bam_cigar_op(cigar[i]), bam_cigar_oplen(cigar[i])); } } inline void update_offset(int32_t const& opcode, uint32_t const& oplen); };
#pragma once #include "Utility.hpp" #include "Parse.hpp" #include <sam.h> #include <boost/format.hpp> #include <stdint.h> #include <string.h> #include <stdexcept> using boost::format; struct AlignmentOffsets { uint32_t raLen; uint32_t qaLen; uint32_t sclip; uint32_t eclip; bool first; AlignmentOffsets() : raLen(0) , qaLen(0) , sclip(0) , eclip(0) , first(true) {} AlignmentOffsets(char const* cigar) : raLen(0) , qaLen(0) , sclip(0) , eclip(0) , first(true) { char const* beg = cigar; std::size_t len = strlen(beg); char const* end = beg + len; for(; *beg != '\0'; ++beg) { uint32_t oplen = 0; if (!auto_parse(beg, end, oplen) || !cigar::valid_cigar_len(oplen)) { throw std::runtime_error(str(format( "Error parsing cigar string %1%: expected number at position %2%" ) % cigar % (beg - cigar))); } int op = cigar::opcode_for_char(*beg); if (op < 0) { throw std::runtime_error(str(format( "Error parsing cigar string %1%: invalid cigar op char at position %2%" ) % cigar % (beg - cigar))); } update_offset(op, oplen); } } AlignmentOffsets(uint32_t const* cigar, uint32_t const& n_cigar) : raLen(0) , qaLen(0) , sclip(0) , eclip(0) , first(true) { for (uint32_t i = 0; i < n_cigar; ++i) { update_offset(bam_cigar_op(cigar[i]), bam_cigar_oplen(cigar[i])); } } inline void update_offset(int32_t const& opcode, uint32_t const& oplen); };
add default constructor
add default constructor
C++
mit
hall-lab/extract_sv_reads,hall-lab/extract_sv_reads,hall-lab/extract_sv_reads
005a1964eebe4a6ebc787bce3745b1689bca61fc
renderdoc/driver/gl/cgl_hooks.cpp
renderdoc/driver/gl/cgl_hooks.cpp
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2018-2019 Baldur Karlsson * * 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 <dlfcn.h> #include "hooks/hooks.h" #include "cgl_dispatch_table.h" #include "gl_driver.h" class CGLHook : LibraryHook { public: CGLHook() : driver(GetGLPlatform()) {} void RegisterHooks(); // default to RTLD_NEXT for CGL lookups if we haven't gotten a more specific library handle void *handle = RTLD_NEXT; WrappedOpenGL driver; std::set<CGLContextObj> contexts; volatile int32_t suppressed = 0; } cglhook; CGLError GL_EXPORT_NAME(CGLCreateContext)(CGLPixelFormatObj pix, CGLContextObj share, CGLContextObj *ctx) { if(RenderDoc::Inst().IsReplayApp()) { if(!CGL.CGLCreateContext) CGL.PopulateForReplay(); return CGL.CGLCreateContext(pix, share, ctx); } CGLError ret = CGL.CGLCreateContext(pix, share, ctx); if(ret != kCGLNoError) return ret; GLInitParams init = {}; init.width = 0; init.height = 0; GLint value = 0; CGLError err = kCGLNoError; CGL.CGLDescribePixelFormat(pix, 0, kCGLPFAColorSize, &value); init.colorBits = (uint32_t)value; CGL.CGLDescribePixelFormat(pix, 0, kCGLPFADepthSize, &value); init.depthBits = (uint32_t)value; CGL.CGLDescribePixelFormat(pix, 0, kCGLPFAStencilSize, &value); init.stencilBits = (uint32_t)value; // TODO: is macOS sRGB? init.isSRGB = 1; CGL.CGLDescribePixelFormat(pix, 0, kCGLPFASamples, &value); init.multiSamples = RDCMAX(1, value); GLWindowingData data; data.wnd = NULL; data.ctx = *ctx; data.pix = pix; { SCOPED_LOCK(glLock); cglhook.driver.CreateContext(data, share, init, true, true); } return ret; } CGLError GL_EXPORT_NAME(CGLSetCurrentContext)(CGLContextObj ctx) { if(RenderDoc::Inst().IsReplayApp()) { if(!CGL.CGLSetCurrentContext) CGL.PopulateForReplay(); return CGL.CGLSetCurrentContext(ctx); } CGLError ret = CGL.CGLSetCurrentContext(ctx); if(Atomic::CmpExch32(&cglhook.suppressed, 0, 0) != 0) return ret; if(ret == kCGLNoError) { SCOPED_LOCK(glLock); SetDriverForHooks(&cglhook.driver); if(ctx && cglhook.contexts.find(ctx) == cglhook.contexts.end()) { cglhook.contexts.insert(ctx); FetchEnabledExtensions(); // see gl_emulated.cpp GL.EmulateUnsupportedFunctions(); GL.EmulateRequiredExtensions(); GL.DriverForEmulation(&cglhook.driver); } CGRect rect = {}; GLWindowingData data; data.wnd = NULL; data.ctx = ctx; data.pix = CGLGetPixelFormat(ctx); if(data.ctx) { CGSConnectionID conn = 0; CGSWindowID window = 0; CGSSurfaceID surface = 0; CGL.CGLGetSurface(ctx, &conn, &window, &surface); data.wnd = (void *)(uintptr_t)window; CGL.CGSGetSurfaceBounds(conn, window, surface, &rect); } cglhook.driver.ActivateContext(data); if(data.ctx) { GLInitParams &params = cglhook.driver.GetInitParams(data); params.width = (uint32_t)rect.size.width; params.height = (uint32_t)rect.size.height; } } return ret; } CGLError GL_EXPORT_NAME(CGLFlushDrawable)(CGLContextObj ctx) { if(RenderDoc::Inst().IsReplayApp()) { if(!CGL.CGLFlushDrawable) CGL.PopulateForReplay(); return CGL.CGLFlushDrawable(ctx); } { SCOPED_LOCK(glLock); CGSConnectionID conn = 0; CGSWindowID window = 0; CGSSurfaceID surface = 0; CGL.CGLGetSurface(ctx, &conn, &window, &surface); cglhook.driver.SwapBuffers((void *)(uintptr_t)window); } CGLError ret; { DisableGLHooks(); Atomic::Inc32(&cglhook.suppressed); ret = CGL.CGLFlushDrawable(ctx); Atomic::Dec32(&cglhook.suppressed); EnableGLHooks(); } return ret; } DECL_HOOK_EXPORT(CGLCreateContext); DECL_HOOK_EXPORT(CGLSetCurrentContext); DECL_HOOK_EXPORT(CGLFlushDrawable); static void CGLHooked(void *handle) { RDCDEBUG("CGL library hooked"); // store the handle for any pass-through implementations that need to look up their onward // pointers cglhook.handle = handle; // enable hooks immediately, we'll suppress them when calling into CGL EnableGLHooks(); // as a hook callback this is only called while capturing RDCASSERT(!RenderDoc::Inst().IsReplayApp()); // fetch non-hooked functions into our dispatch table #define CGL_FETCH(func) CGL.func = &func; CGL_NONHOOKED_SYMBOLS(CGL_FETCH) #undef CGL_FETCH } void CGLHook::RegisterHooks() { RDCLOG("Registering CGL hooks"); // register library hooks LibraryHooks::RegisterLibraryHook( "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", &CGLHooked); LibraryHooks::RegisterLibraryHook("libGL.dylib", NULL); // register CGL hooks #define CGL_REGISTER(func) \ LibraryHooks::RegisterFunctionHook( \ "OpenGL", FunctionHook(STRINGIZE(func), (void **)&CGL.func, (void *)&GL_EXPORT_NAME(func))); CGL_HOOKED_SYMBOLS(CGL_REGISTER) #undef CGL_REGISTER }
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2018-2019 Baldur Karlsson * * 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 <dlfcn.h> #include "hooks/hooks.h" #include "cgl_dispatch_table.h" #include "gl_driver.h" class CGLHook : LibraryHook { public: CGLHook() : driver(GetGLPlatform()) {} void RegisterHooks(); // default to RTLD_NEXT for CGL lookups if we haven't gotten a more specific library handle void *handle = RTLD_NEXT; WrappedOpenGL driver; std::set<CGLContextObj> contexts; volatile int32_t suppressed = 0; } cglhook; CGLError GL_EXPORT_NAME(CGLCreateContext)(CGLPixelFormatObj pix, CGLContextObj share, CGLContextObj *ctx) { if(RenderDoc::Inst().IsReplayApp()) { if(!CGL.CGLCreateContext) CGL.PopulateForReplay(); return CGL.CGLCreateContext(pix, share, ctx); } CGLError ret = CGL.CGLCreateContext(pix, share, ctx); if(ret != kCGLNoError) return ret; GLInitParams init = {}; init.width = 0; init.height = 0; GLint value = 0; CGLError err = kCGLNoError; CGL.CGLDescribePixelFormat(pix, 0, kCGLPFAColorSize, &value); init.colorBits = (uint32_t)value; CGL.CGLDescribePixelFormat(pix, 0, kCGLPFADepthSize, &value); init.depthBits = (uint32_t)value; CGL.CGLDescribePixelFormat(pix, 0, kCGLPFAStencilSize, &value); init.stencilBits = (uint32_t)value; // TODO: is macOS sRGB? init.isSRGB = 1; CGL.CGLDescribePixelFormat(pix, 0, kCGLPFASamples, &value); init.multiSamples = RDCMAX(1, value); CGL.CGLDescribePixelFormat(pix, 0, kCGLPFAOpenGLProfile, &value); bool isCore = (value >= kCGLOGLPVersion_3_2_Core); GLWindowingData data; data.wnd = NULL; data.ctx = *ctx; data.pix = pix; { SCOPED_LOCK(glLock); cglhook.driver.CreateContext(data, share, init, isCore, isCore); } return ret; } CGLError GL_EXPORT_NAME(CGLSetCurrentContext)(CGLContextObj ctx) { if(RenderDoc::Inst().IsReplayApp()) { if(!CGL.CGLSetCurrentContext) CGL.PopulateForReplay(); return CGL.CGLSetCurrentContext(ctx); } CGLError ret = CGL.CGLSetCurrentContext(ctx); if(Atomic::CmpExch32(&cglhook.suppressed, 0, 0) != 0) return ret; if(ret == kCGLNoError) { SCOPED_LOCK(glLock); SetDriverForHooks(&cglhook.driver); if(ctx && cglhook.contexts.find(ctx) == cglhook.contexts.end()) { cglhook.contexts.insert(ctx); FetchEnabledExtensions(); // see gl_emulated.cpp GL.EmulateUnsupportedFunctions(); GL.EmulateRequiredExtensions(); GL.DriverForEmulation(&cglhook.driver); } CGRect rect = {}; GLWindowingData data; data.wnd = NULL; data.ctx = ctx; data.pix = CGLGetPixelFormat(ctx); if(data.ctx) { CGSConnectionID conn = 0; CGSWindowID window = 0; CGSSurfaceID surface = 0; CGL.CGLGetSurface(ctx, &conn, &window, &surface); data.wnd = (void *)(uintptr_t)window; CGL.CGSGetSurfaceBounds(conn, window, surface, &rect); } cglhook.driver.ActivateContext(data); if(data.ctx) { GLInitParams &params = cglhook.driver.GetInitParams(data); params.width = (uint32_t)rect.size.width; params.height = (uint32_t)rect.size.height; } } return ret; } CGLError GL_EXPORT_NAME(CGLFlushDrawable)(CGLContextObj ctx) { if(RenderDoc::Inst().IsReplayApp()) { if(!CGL.CGLFlushDrawable) CGL.PopulateForReplay(); return CGL.CGLFlushDrawable(ctx); } { SCOPED_LOCK(glLock); CGSConnectionID conn = 0; CGSWindowID window = 0; CGSSurfaceID surface = 0; CGL.CGLGetSurface(ctx, &conn, &window, &surface); cglhook.driver.SwapBuffers((void *)(uintptr_t)window); } CGLError ret; { DisableGLHooks(); Atomic::Inc32(&cglhook.suppressed); ret = CGL.CGLFlushDrawable(ctx); Atomic::Dec32(&cglhook.suppressed); EnableGLHooks(); } return ret; } DECL_HOOK_EXPORT(CGLCreateContext); DECL_HOOK_EXPORT(CGLSetCurrentContext); DECL_HOOK_EXPORT(CGLFlushDrawable); static void CGLHooked(void *handle) { RDCDEBUG("CGL library hooked"); // store the handle for any pass-through implementations that need to look up their onward // pointers cglhook.handle = handle; // enable hooks immediately, we'll suppress them when calling into CGL EnableGLHooks(); // as a hook callback this is only called while capturing RDCASSERT(!RenderDoc::Inst().IsReplayApp()); // fetch non-hooked functions into our dispatch table #define CGL_FETCH(func) CGL.func = &func; CGL_NONHOOKED_SYMBOLS(CGL_FETCH) #undef CGL_FETCH } void CGLHook::RegisterHooks() { RDCLOG("Registering CGL hooks"); // register library hooks LibraryHooks::RegisterLibraryHook( "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", &CGLHooked); LibraryHooks::RegisterLibraryHook("libGL.dylib", NULL); // register CGL hooks #define CGL_REGISTER(func) \ LibraryHooks::RegisterFunctionHook( \ "OpenGL", FunctionHook(STRINGIZE(func), (void **)&CGL.func, (void *)&GL_EXPORT_NAME(func))); CGL_HOOKED_SYMBOLS(CGL_REGISTER) #undef CGL_REGISTER }
Check for GL profile on macos to determine if context is core or compat
Check for GL profile on macos to determine if context is core or compat
C++
mit
Zorro666/renderdoc,baldurk/renderdoc,Zorro666/renderdoc,TurtleRockStudios/renderdoc_public,baldurk/renderdoc,baldurk/renderdoc,Zorro666/renderdoc,TurtleRockStudios/renderdoc_public,Zorro666/renderdoc,TurtleRockStudios/renderdoc_public,baldurk/renderdoc,TurtleRockStudios/renderdoc_public,TurtleRockStudios/renderdoc_public,baldurk/renderdoc,baldurk/renderdoc,TurtleRockStudios/renderdoc_public,Zorro666/renderdoc,Zorro666/renderdoc
1f8ed5af25717d4f03abb8bd505894d71a8561d8
Runtime/RetroTypes.hpp
Runtime/RetroTypes.hpp
#pragma once #include <vector> #include <utility> #include <string> #include <functional> #include "GCNTypes.hpp" #include "rstl.hpp" #include "IOStreams.hpp" #include "hecl/hecl.hpp" #include "zeus/CVector3f.hpp" #include "zeus/CVector2f.hpp" #include "zeus/CMatrix3f.hpp" #include "zeus/CMatrix4f.hpp" #include "zeus/CTransform.hpp" #undef min #undef max using namespace std::literals; namespace urde { using FourCC = hecl::FourCC; class CAssetId { u64 id = UINT64_MAX; public: CAssetId() = default; CAssetId(u64 v) { Assign(v); } explicit CAssetId(CInputStream& in); bool IsValid() const { return id != UINT64_MAX; } u64 Value() const { return id; } void Assign(u64 v) { id = (v == UINT32_MAX ? UINT64_MAX : (v == 0 ? UINT64_MAX : v)); } void Reset() { id = UINT64_MAX; } void PutTo(COutputStream& out); bool operator==(const CAssetId& other) const { return id == other.id; } bool operator!=(const CAssetId& other) const { return id != other.id; } bool operator<(const CAssetId& other) const { return id < other.id; } }; //#define kInvalidAssetId CAssetId() struct SObjectTag { FourCC type; CAssetId id; operator bool() const { return id.IsValid(); } bool operator!=(const SObjectTag& other) const { return id != other.id; } bool operator==(const SObjectTag& other) const { return id == other.id; } bool operator<(const SObjectTag& other) const { return id < other.id; } SObjectTag() = default; SObjectTag(FourCC tp, CAssetId rid) : type(tp), id(rid) {} SObjectTag(CInputStream& in) { in.readBytesToBuf(&type, 4); id = CAssetId(in); } void readMLVL(CInputStream& in) { id = CAssetId(in); in.readBytesToBuf(&type, 4); } }; struct TEditorId { TEditorId() = default; TEditorId(u32 idin) : id(idin) {} u32 id = u32(-1); u8 LayerNum() const { return u8((id >> 26) & 0x3f); } u16 AreaNum() const { return u16((id >> 16) & 0x3ff); } u16 Id() const { return u16(id & 0xffff); } bool operator<(const TEditorId& other) const { return (id & 0x3ffffff) < (other.id & 0x3ffffff); } bool operator!=(const TEditorId& other) const { return (id & 0x3ffffff) != (other.id & 0x3ffffff); } bool operator==(const TEditorId& other) const { return (id & 0x3ffffff) == (other.id & 0x3ffffff); } }; #define kInvalidEditorId TEditorId() struct TUniqueId { TUniqueId() = default; TUniqueId(u16 value, u16 version) : id(value | (version << 10)) {} u16 id = u16(-1); u16 Version() const { return u16((id >> 10) & 0x3f); } u16 Value() const { return u16(id & 0x3ff); } bool operator<(const TUniqueId& other) const { return (id < other.id); } bool operator!=(const TUniqueId& other) const { return (id != other.id); } bool operator==(const TUniqueId& other) const { return (id == other.id); } }; #define kInvalidUniqueId TUniqueId() using TAreaId = s32; #define kInvalidAreaId TAreaId(-1) #if 0 template <class T, size_t N> class TRoundRobin { rstl::reserved_vector<T, N> vals; public: TRoundRobin(const T& val) : vals(N, val) {} void PushBack(const T& val) { vals.push_back(val); } size_t Size() const { return vals.size(); } const T& GetLastValue() const { return vals.back(); } void Clear() { vals.clear(); } const T& GetValue(s32) const {} }; #endif template <class T> T GetAverage(const T* v, s32 count) { T r = v[0]; for (s32 i = 1; i < count; ++i) r += v[i]; return r / count; } template <class T, size_t N> class TReservedAverage : rstl::reserved_vector<T, N> { public: TReservedAverage() = default; TReservedAverage(const T& t) { rstl::reserved_vector<T, N>::resize(N, t); } void AddValue(const T& t) { if (this->size() < N) { this->insert(this->begin(), t); } else { this->pop_back(); this->insert(this->begin(), t); } } std::optional<T> GetAverage() const { if (this->empty()) return {}; return {urde::GetAverage<T>(this->data(), this->size())}; } std::optional<T> GetEntry(int i) const { if (i >= this->size()) return {}; return this->operator[](i); } void Clear() { this->clear(); } size_t Size() const { return this->size(); } }; } // namespace urde namespace std { template <> struct hash<urde::SObjectTag> { size_t operator()(const urde::SObjectTag& tag) const noexcept { return tag.id.Value(); } }; template <> struct hash<urde::CAssetId> { size_t operator()(const urde::CAssetId& id) const noexcept { return id.Value(); } }; } // namespace std FMT_CUSTOM_FORMATTER(urde::CAssetId, "{:08X}", obj.Value()) FMT_CUSTOM_FORMATTER(urde::TEditorId, "{:08X}", obj.id) FMT_CUSTOM_FORMATTER(urde::TUniqueId, "{:04X}", obj.id) FMT_CUSTOM_FORMATTER(urde::SObjectTag, "{} {}", obj.type, obj.id) FMT_CUSTOM_FORMATTER(zeus::CVector3f, "({} {} {})", float(obj.x()), float(obj.y()), float(obj.z())) FMT_CUSTOM_FORMATTER(zeus::CVector2f, "({} {})", float(obj.x()), float(obj.y())) FMT_CUSTOM_FORMATTER(zeus::CMatrix3f, "\n({} {} {})" "\n({} {} {})" "\n({} {} {})", float(obj[0][0]), float(obj[1][0]), float(obj[2][0]), float(obj[0][1]), float(obj[1][1]), float(obj[2][1]), float(obj[0][2]), float(obj[1][2]), float(obj[2][2])) FMT_CUSTOM_FORMATTER(zeus::CMatrix4f, "\n({} {} {} {})" "\n({} {} {} {})" "\n({} {} {} {})" "\n({} {} {} {})", float(obj[0][0]), float(obj[1][0]), float(obj[2][0]), float(obj[3][0]), float(obj[0][1]), float(obj[1][1]), float(obj[2][1]), float(obj[3][1]), float(obj[0][2]), float(obj[1][2]), float(obj[2][2]), float(obj[3][2]), float(obj[0][3]), float(obj[1][3]), float(obj[2][3]), float(obj[3][3])) FMT_CUSTOM_FORMATTER(zeus::CTransform, "\n({} {} {} {})" "\n({} {} {} {})" "\n({} {} {} {})", float(obj.basis[0][0]), float(obj.basis[1][0]), float(obj.basis[2][0]), float(obj.origin[0]), float(obj.basis[0][1]), float(obj.basis[1][1]), float(obj.basis[2][1]), float(obj.origin[1]), float(obj.basis[0][2]), float(obj.basis[1][2]), float(obj.basis[2][2]), float(obj.origin[2])) #if defined(__has_feature) #if __has_feature(memory_sanitizer) #define URDE_MSAN 1 #endif #endif
#pragma once #include <vector> #include <utility> #include <string> #include <functional> #include "GCNTypes.hpp" #include "rstl.hpp" #include "IOStreams.hpp" #include "hecl/hecl.hpp" #include "zeus/CVector3f.hpp" #include "zeus/CVector2f.hpp" #include "zeus/CMatrix3f.hpp" #include "zeus/CMatrix4f.hpp" #include "zeus/CTransform.hpp" #undef min #undef max using namespace std::literals; namespace urde { using FourCC = hecl::FourCC; class CAssetId { u64 id = UINT64_MAX; public: constexpr CAssetId() = default; constexpr CAssetId(u64 v) { Assign(v); } explicit CAssetId(CInputStream& in); constexpr bool IsValid() const { return id != UINT64_MAX; } constexpr u64 Value() const { return id; } constexpr void Assign(u64 v) { id = (v == UINT32_MAX ? UINT64_MAX : (v == 0 ? UINT64_MAX : v)); } constexpr void Reset() { id = UINT64_MAX; } void PutTo(COutputStream& out); constexpr bool operator==(const CAssetId& other) const { return id == other.id; } constexpr bool operator!=(const CAssetId& other) const { return !operator==(other); } constexpr bool operator<(const CAssetId& other) const { return id < other.id; } }; //#define kInvalidAssetId CAssetId() struct SObjectTag { FourCC type; CAssetId id; constexpr operator bool() const { return id.IsValid(); } constexpr bool operator==(const SObjectTag& other) const { return id == other.id; } constexpr bool operator!=(const SObjectTag& other) const { return !operator==(other); } constexpr bool operator<(const SObjectTag& other) const { return id < other.id; } constexpr SObjectTag() = default; constexpr SObjectTag(FourCC tp, CAssetId rid) : type(tp), id(rid) {} SObjectTag(CInputStream& in) { in.readBytesToBuf(&type, 4); id = CAssetId(in); } void readMLVL(CInputStream& in) { id = CAssetId(in); in.readBytesToBuf(&type, 4); } }; struct TEditorId { u32 id = u32(-1); constexpr TEditorId() = default; constexpr TEditorId(u32 idin) : id(idin) {} constexpr u8 LayerNum() const { return u8((id >> 26) & 0x3f); } constexpr u16 AreaNum() const { return u16((id >> 16) & 0x3ff); } constexpr u16 Id() const { return u16(id & 0xffff); } constexpr bool operator<(const TEditorId& other) const { return (id & 0x3ffffff) < (other.id & 0x3ffffff); } constexpr bool operator==(const TEditorId& other) const { return (id & 0x3ffffff) == (other.id & 0x3ffffff); } constexpr bool operator!=(const TEditorId& other) const { return !operator==(other); } }; #define kInvalidEditorId TEditorId() struct TUniqueId { u16 id = u16(-1); constexpr TUniqueId() = default; constexpr TUniqueId(u16 value, u16 version) : id(value | (version << 10)) {} constexpr u16 Version() const { return u16((id >> 10) & 0x3f); } constexpr u16 Value() const { return u16(id & 0x3ff); } constexpr bool operator<(const TUniqueId& other) const { return id < other.id; } constexpr bool operator==(const TUniqueId& other) const { return id == other.id; } constexpr bool operator!=(const TUniqueId& other) const { return !operator==(other); } }; #define kInvalidUniqueId TUniqueId() using TAreaId = s32; #define kInvalidAreaId TAreaId(-1) #if 0 template <class T, size_t N> class TRoundRobin { rstl::reserved_vector<T, N> vals; public: TRoundRobin(const T& val) : vals(N, val) {} void PushBack(const T& val) { vals.push_back(val); } size_t Size() const { return vals.size(); } const T& GetLastValue() const { return vals.back(); } void Clear() { vals.clear(); } const T& GetValue(s32) const {} }; #endif template <class T> T GetAverage(const T* v, s32 count) { T r = v[0]; for (s32 i = 1; i < count; ++i) r += v[i]; return r / count; } template <class T, size_t N> class TReservedAverage : rstl::reserved_vector<T, N> { public: TReservedAverage() = default; TReservedAverage(const T& t) { rstl::reserved_vector<T, N>::resize(N, t); } void AddValue(const T& t) { if (this->size() < N) { this->insert(this->begin(), t); } else { this->pop_back(); this->insert(this->begin(), t); } } std::optional<T> GetAverage() const { if (this->empty()) return {}; return {urde::GetAverage<T>(this->data(), this->size())}; } std::optional<T> GetEntry(int i) const { if (i >= this->size()) return {}; return this->operator[](i); } void Clear() { this->clear(); } size_t Size() const { return this->size(); } }; } // namespace urde namespace std { template <> struct hash<urde::SObjectTag> { size_t operator()(const urde::SObjectTag& tag) const noexcept { return tag.id.Value(); } }; template <> struct hash<urde::CAssetId> { size_t operator()(const urde::CAssetId& id) const noexcept { return id.Value(); } }; } // namespace std FMT_CUSTOM_FORMATTER(urde::CAssetId, "{:08X}", obj.Value()) FMT_CUSTOM_FORMATTER(urde::TEditorId, "{:08X}", obj.id) FMT_CUSTOM_FORMATTER(urde::TUniqueId, "{:04X}", obj.id) FMT_CUSTOM_FORMATTER(urde::SObjectTag, "{} {}", obj.type, obj.id) FMT_CUSTOM_FORMATTER(zeus::CVector3f, "({} {} {})", float(obj.x()), float(obj.y()), float(obj.z())) FMT_CUSTOM_FORMATTER(zeus::CVector2f, "({} {})", float(obj.x()), float(obj.y())) FMT_CUSTOM_FORMATTER(zeus::CMatrix3f, "\n({} {} {})" "\n({} {} {})" "\n({} {} {})", float(obj[0][0]), float(obj[1][0]), float(obj[2][0]), float(obj[0][1]), float(obj[1][1]), float(obj[2][1]), float(obj[0][2]), float(obj[1][2]), float(obj[2][2])) FMT_CUSTOM_FORMATTER(zeus::CMatrix4f, "\n({} {} {} {})" "\n({} {} {} {})" "\n({} {} {} {})" "\n({} {} {} {})", float(obj[0][0]), float(obj[1][0]), float(obj[2][0]), float(obj[3][0]), float(obj[0][1]), float(obj[1][1]), float(obj[2][1]), float(obj[3][1]), float(obj[0][2]), float(obj[1][2]), float(obj[2][2]), float(obj[3][2]), float(obj[0][3]), float(obj[1][3]), float(obj[2][3]), float(obj[3][3])) FMT_CUSTOM_FORMATTER(zeus::CTransform, "\n({} {} {} {})" "\n({} {} {} {})" "\n({} {} {} {})", float(obj.basis[0][0]), float(obj.basis[1][0]), float(obj.basis[2][0]), float(obj.origin[0]), float(obj.basis[0][1]), float(obj.basis[1][1]), float(obj.basis[2][1]), float(obj.origin[1]), float(obj.basis[0][2]), float(obj.basis[1][2]), float(obj.basis[2][2]), float(obj.origin[2])) #if defined(__has_feature) #if __has_feature(memory_sanitizer) #define URDE_MSAN 1 #endif #endif
Make types constexpr where applicable
RetroTypes: Make types constexpr where applicable These are generally used as basic tags and ID types, so these can have a constexpr interface. This is particularly beneficial, given some of these types are used in file-static lookup tables. Without being constexpr, these type's constructors in that case are technically runtime static constructors. While most compilers will initialize the type at compile-time, this would be dependent on the optimizer. By marking them constexpr, we allow it outright. It also allows those arrays to be made constexpr as well.
C++
mit
RetroView/PathShagged,AxioDL/PathShagged,AxioDL/PathShagged,AxioDL/PathShagged,RetroView/PathShagged,RetroView/PathShagged
3f898e6785875c97e3a6cdf33d6ffe42ba526b41
lib/Analysis/LibCallSemantics.cpp
lib/Analysis/LibCallSemantics.cpp
//===- LibCallSemantics.cpp - Describe library semantics ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements interfaces that can be used to describe language // specific runtime library interfaces (e.g. libc, libm, etc) to LLVM // optimizers. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/LibCallSemantics.h" #include "llvm/ADT/StringMap.h" #include "llvm/IR/Function.h" using namespace llvm; /// getMap - This impl pointer in ~LibCallInfo is actually a StringMap. This /// helper does the cast. static StringMap<const LibCallFunctionInfo*> *getMap(void *Ptr) { return static_cast<StringMap<const LibCallFunctionInfo*> *>(Ptr); } LibCallInfo::~LibCallInfo() { delete getMap(Impl); } const LibCallLocationInfo &LibCallInfo::getLocationInfo(unsigned LocID) const { // Get location info on the first call. if (NumLocations == 0) NumLocations = getLocationInfo(Locations); assert(LocID < NumLocations && "Invalid location ID!"); return Locations[LocID]; } /// getFunctionInfo - Return the LibCallFunctionInfo object corresponding to /// the specified function if we have it. If not, return null. const LibCallFunctionInfo * LibCallInfo::getFunctionInfo(const Function *F) const { StringMap<const LibCallFunctionInfo*> *Map = getMap(Impl); /// If this is the first time we are querying for this info, lazily construct /// the StringMap to index it. if (!Map) { Impl = Map = new StringMap<const LibCallFunctionInfo*>(); const LibCallFunctionInfo *Array = getFunctionInfoArray(); if (!Array) return nullptr; // We now have the array of entries. Populate the StringMap. for (unsigned i = 0; Array[i].Name; ++i) (*Map)[Array[i].Name] = Array+i; } // Look up this function in the string map. return Map->lookup(F->getName()); }
//===- LibCallSemantics.cpp - Describe library semantics ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements interfaces that can be used to describe language // specific runtime library interfaces (e.g. libc, libm, etc) to LLVM // optimizers. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/LibCallSemantics.h" #include "llvm/ADT/StringMap.h" #include "llvm/IR/Function.h" using namespace llvm; /// This impl pointer in ~LibCallInfo is actually a StringMap. This /// helper does the cast. static StringMap<const LibCallFunctionInfo*> *getMap(void *Ptr) { return static_cast<StringMap<const LibCallFunctionInfo*> *>(Ptr); } LibCallInfo::~LibCallInfo() { delete getMap(Impl); } const LibCallLocationInfo &LibCallInfo::getLocationInfo(unsigned LocID) const { // Get location info on the first call. if (NumLocations == 0) NumLocations = getLocationInfo(Locations); assert(LocID < NumLocations && "Invalid location ID!"); return Locations[LocID]; } /// Return the LibCallFunctionInfo object corresponding to /// the specified function if we have it. If not, return null. const LibCallFunctionInfo * LibCallInfo::getFunctionInfo(const Function *F) const { StringMap<const LibCallFunctionInfo*> *Map = getMap(Impl); /// If this is the first time we are querying for this info, lazily construct /// the StringMap to index it. if (!Map) { Impl = Map = new StringMap<const LibCallFunctionInfo*>(); const LibCallFunctionInfo *Array = getFunctionInfoArray(); if (!Array) return nullptr; // We now have the array of entries. Populate the StringMap. for (unsigned i = 0; Array[i].Name; ++i) (*Map)[Array[i].Name] = Array+i; } // Look up this function in the string map. return Map->lookup(F->getName()); }
remove function names from comments; NFC
remove function names from comments; NFC git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@220309 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm
24f29638cd880cc5a64b5e7ff6beedfee47b380d
cue.cpp
cue.cpp
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Flacon - audio File Encoder * https://github.com/flacon/flacon * * Copyright: 2012-2015 * Alexander Sokoloff <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "cue.h" #include "cuedata.h" #include "types.h" #include "tags.h" #include <QFile> #include <QFileInfo> #include <QObject> #include <QDebug> /************************************************ * ************************************************/ static void splitTitle(Track *track, char separator) { QByteArray b = track->tagData(TagId::Title); int pos = b.indexOf(separator); track->setTag(TagId::Artist, b.left(pos).trimmed()); track->setTag(TagId::Title, b.right(b.length() - pos - 1).trimmed()); } /************************************************ * ************************************************/ CueDisc::CueDisc() : Tracks() { } /************************************************ * ************************************************/ CueDisc::CueDisc(const QString &fileName) { CueData data(fileName); if (data.isEmpty()) { throw CueReaderError(QObject::tr("<b>%1</b> is not a valid CUE file. The CUE sheet has no FILE tag.").arg(fileName)); } QFileInfo cueFileInfo(fileName); QString fullPath = QFileInfo(fileName).absoluteFilePath(); //CueDisc res; mFileName = fullPath; mDiscCount = 1; mDiscNum = 1; setUri(fullPath); QByteArray albumPerformer = getAlbumPerformer(data); const CueData::Tags &global = data.globalTags(); for (const CueData::Tags &t : data.tracks()) { Track track; track.setTag(TagId::File, t.value(CueData::FILE_TAG)); track.setTag(TagId::Album, global.value(CueData::TITLE_TAG)); track.setCueIndex(0, CueIndex(t.value("INDEX 00"))); track.setCueIndex(1, CueIndex(t.value("INDEX 01"))); track.setTag(TagId::Catalog, global.value("CATALOG")); track.setTag(TagId::CDTextfile, global.value("CDTEXTFILE")); track.setTag(TagId::Comment, global.value("COMMENT")); track.setTag(TagId::Flags, t.value("FLAGS")); track.setTag(TagId::Genre, global.value("GENRE")); track.setTag(TagId::ISRC, t.value("ISRC")); track.setTag(TagId::Title, t.value("TITLE")); track.setTag(TagId::Artist, t.value("PERFORMER", global.value("PERFORMER"))); track.setTag(TagId::SongWriter, t.value("SONGWRITER", global.value("SONGWRITER"))); track.setTag(TagId::DiscId, global.value("DISCID")); track.setTag(TagId::Date, global.value("DATE")); track.setTag(TagId::AlbumArtist, albumPerformer); track.setTrackNum(TrackNum(t.value(CueData::TRACK_TAG).toUInt())); track.setTrackCount(TrackNum(data.tracks().count())); track.setTag(TagId::DiscNum, global.value("DISCNUMBER", "1")); track.setTag(TagId::DiscCount, global.value("TOTALDISCS", "1")); track.setCueFileName(fullPath); this->append(track); } splitTitleTag(data); setCodecName(data); } /************************************************ * ************************************************/ bool CueDisc::isMutiplyAudio() const { if (isEmpty()) return false; QByteArray file = last().tagData(TagId::File); for (const Track &track : *this) { if (track.tagData(TagId::File) != file) return true; } return false; } /************************************************ * ************************************************/ QByteArray CueDisc::getAlbumPerformer(const CueData &data) { QByteArray res = data.globalTags().value(CueData::PERFORMER_TAG); if (!res.isEmpty()) return res; res = data.tracks().first().value(CueData::PERFORMER_TAG); for (const CueData::Tags &t : data.tracks()) { if (t.value(CueData::PERFORMER_TAG) != res) return ""; } return res; } /************************************************ * ************************************************/ void CueDisc::splitTitleTag(const CueData &data) { bool splitByDash = true; bool splitBySlash = true; bool splitByBackSlash = true; for (const CueData::Tags &track : data.tracks()) { if (track.contains("PERFORMER")) { return; } QByteArray value = track.value("TITLE"); splitByDash = splitByDash && value.contains('-'); splitBySlash = splitBySlash && value.contains('/'); splitByBackSlash = splitByBackSlash && value.contains('\\'); } // clang-format off for (Track &track : *this) { if (splitByBackSlash) splitTitle(&track, '\\'); else if (splitBySlash) splitTitle(&track, '/'); else if (splitByDash) splitTitle(&track, '-'); } // clang-format off } /************************************************ * Auto detect codepage ************************************************/ void CueDisc::setCodecName(const CueData &data) { QString codecName = data.codecName(); if (codecName.isEmpty()) { UcharDet charDet; foreach (const Track &track, *this) { charDet << track; } codecName = charDet.textCodecName(); } for (Track &track : *this) { track.setCodecName(codecName); } } /************************************************ * ************************************************/ CueReader::CueReader() { } /************************************************ Complete CUE sheet syntax documentation https://github.com/flacon/flacon/blob/master/cuesheet_syntax.md ************************************************/ /*CueDisc CueReader::load(const QString &fileName) { CueData data(fileName); if (data.isEmpty()) { throw CueReaderError(QObject::tr("<b>%1</b> is not a valid CUE file. The CUE sheet has no FILE tag.").arg(fileName)); } QFileInfo cueFileInfo(fileName); QString fullPath = QFileInfo(fileName).absoluteFilePath(); CueDisc res; res.mFileName = fullPath; res.mDiscCount = 1; res.mDiscNum = 1; res.setUri(fullPath); QByteArray albumPerformer = getAlbumPerformer(data); const CueData::Tags &global = data.globalTags(); for (const CueData::Tags &t: data.tracks()) { Track track; track.setTag(TagId::File, t.value(CueData::FILE_TAG)); track.setTag(TagId::Album, global.value(CueData::TITLE_TAG)); track.setCueIndex(0, CueIndex(t.value("INDEX 00"))); track.setCueIndex(1, CueIndex(t.value("INDEX 01"))); track.setTag(TagId::Catalog, global.value("CATALOG")); track.setTag(TagId::CDTextfile, global.value("CDTEXTFILE")); track.setTag(TagId::Comment, global.value("COMMENT")); track.setTag(TagId::Flags, t.value("FLAGS")); track.setTag(TagId::Genre, global.value("GENRE")); track.setTag(TagId::ISRC, t.value("ISRC")); track.setTag(TagId::Title, t.value("TITLE")); track.setTag(TagId::Artist, t.value("PERFORMER", global.value("PERFORMER"))); track.setTag(TagId::SongWriter, t.value("SONGWRITER", global.value("SONGWRITER"))); track.setTag(TagId::DiscId, global.value("DISCID")); track.setTag(TagId::Date, global.value("DATE")); track.setTag(TagId::AlbumArtist, albumPerformer); track.setTrackNum(TrackNum(t.value(CueData::TRACK_TAG).toUInt())); track.setTrackCount(TrackNum(data.tracks().count())); track.setTag(TagId::DiscNum, global.value("DISCNUMBER", "1")); track.setTag(TagId::DiscCount, global.value("TOTALDISCS", "1")); track.setCueFileName(fullPath); res << track; } splitTitleTag(data, res); setCodecName(data, res); return res; }*/ QVector<CueDisc> CueReader::load(const QString &fileName) { return QVector<CueDisc>(); }
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Flacon - audio File Encoder * https://github.com/flacon/flacon * * Copyright: 2012-2015 * Alexander Sokoloff <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "cue.h" #include "cuedata.h" #include "types.h" #include "tags.h" #include <QFile> #include <QFileInfo> #include <QObject> #include <QDebug> /************************************************ * ************************************************/ static void splitTitle(Track *track, char separator) { QByteArray b = track->tagData(TagId::Title); int pos = b.indexOf(separator); track->setTag(TagId::Artist, b.left(pos).trimmed()); track->setTag(TagId::Title, b.right(b.length() - pos - 1).trimmed()); } /************************************************ * ************************************************/ CueDisc::CueDisc() : Tracks() { } /************************************************ * ************************************************/ CueDisc::CueDisc(const QString &fileName) { CueData data(fileName); if (data.isEmpty()) { throw CueReaderError(QObject::tr("<b>%1</b> is not a valid CUE file. The CUE sheet has no FILE tag.").arg(fileName)); } QFileInfo cueFileInfo(fileName); QString fullPath = QFileInfo(fileName).absoluteFilePath(); //CueDisc res; mFileName = fullPath; mDiscCount = 1; mDiscNum = 1; setUri(fullPath); QByteArray albumPerformer = getAlbumPerformer(data); const CueData::Tags &global = data.globalTags(); for (const CueData::Tags &t : data.tracks()) { Track track; track.setTag(TagId::File, t.value(CueData::FILE_TAG)); track.setTag(TagId::Album, global.value(CueData::TITLE_TAG)); track.setCueIndex(0, CueIndex(t.value("INDEX 00"))); track.setCueIndex(1, CueIndex(t.value("INDEX 01"))); track.setTag(TagId::Catalog, global.value("CATALOG")); track.setTag(TagId::CDTextfile, global.value("CDTEXTFILE")); track.setTag(TagId::Comment, global.value("COMMENT")); track.setTag(TagId::Flags, t.value("FLAGS")); track.setTag(TagId::Genre, global.value("GENRE")); track.setTag(TagId::ISRC, t.value("ISRC")); track.setTag(TagId::Title, t.value("TITLE")); track.setTag(TagId::Artist, t.value("PERFORMER", global.value("PERFORMER"))); track.setTag(TagId::SongWriter, t.value("SONGWRITER", global.value("SONGWRITER"))); track.setTag(TagId::DiscId, global.value("DISCID")); track.setTag(TagId::Date, global.value("DATE")); track.setTag(TagId::AlbumArtist, albumPerformer); track.setTrackNum(TrackNum(t.value(CueData::TRACK_TAG).toUInt())); track.setTrackCount(TrackNum(data.tracks().count())); track.setTag(TagId::DiscNum, global.value("DISCNUMBER", "1")); track.setTag(TagId::DiscCount, global.value("TOTALDISCS", "1")); track.setCueFileName(fullPath); this->append(track); } splitTitleTag(data); setCodecName(data); } /************************************************ * ************************************************/ bool CueDisc::isMutiplyAudio() const { if (isEmpty()) return false; QByteArray file = last().tagData(TagId::File); for (const Track &track : *this) { if (track.tagData(TagId::File) != file) return true; } return false; } /************************************************ * ************************************************/ QByteArray CueDisc::getAlbumPerformer(const CueData &data) { QByteArray res = data.globalTags().value(CueData::PERFORMER_TAG); if (!res.isEmpty()) return res; res = data.tracks().first().value(CueData::PERFORMER_TAG); for (const CueData::Tags &t : data.tracks()) { if (t.value(CueData::PERFORMER_TAG) != res) return ""; } return res; } /************************************************ * ************************************************/ void CueDisc::splitTitleTag(const CueData &data) { bool splitByDash = true; bool splitBySlash = true; bool splitByBackSlash = true; for (const CueData::Tags &track : data.tracks()) { if (track.contains("PERFORMER")) { return; } QByteArray value = track.value("TITLE"); splitByDash = splitByDash && value.contains('-'); splitBySlash = splitBySlash && value.contains('/'); splitByBackSlash = splitByBackSlash && value.contains('\\'); } // clang-format off for (Track &track : *this) { if (splitByBackSlash) splitTitle(&track, '\\'); else if (splitBySlash) splitTitle(&track, '/'); else if (splitByDash) splitTitle(&track, '-'); } // clang-format off } /************************************************ * Auto detect codepage ************************************************/ void CueDisc::setCodecName(const CueData &data) { QString codecName = data.codecName(); if (codecName.isEmpty()) { UcharDet charDet; foreach (const Track &track, *this) { charDet << track; } codecName = charDet.textCodecName(); } for (Track &track : *this) { track.setCodecName(codecName); } } /************************************************ * ************************************************/ CueReader::CueReader() { } QVector<CueDisc> CueReader::load(const QString &fileName) { return QVector<CueDisc>(); }
Remove old CueReader::load method
Remove old CueReader::load method
C++
lgpl-2.1
flacon/flacon,flacon/flacon,flacon/flacon,flacon/flacon
59affc672aeb1e397153dedeb6316747eb6dbdbc
lib/DebugInfo/PDB/Raw/PDBFile.cpp
lib/DebugInfo/PDB/Raw/PDBFile.cpp
//===- PDBFile.cpp - Low level interface to a PDB file ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/Raw/PDBFile.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/DebugInfo/PDB/Raw/DbiStream.h" #include "llvm/DebugInfo/PDB/Raw/InfoStream.h" #include "llvm/Support/Endian.h" #include "llvm/Support/MemoryBuffer.h" using namespace llvm; using namespace llvm::pdb; namespace { static const char Magic[] = {'M', 'i', 'c', 'r', 'o', 's', 'o', 'f', 't', ' ', 'C', '/', 'C', '+', '+', ' ', 'M', 'S', 'F', ' ', '7', '.', '0', '0', '\r', '\n', '\x1a', 'D', 'S', '\0', '\0', '\0'}; // The superblock is overlaid at the beginning of the file (offset 0). // It starts with a magic header and is followed by information which describes // the layout of the file system. struct SuperBlock { char MagicBytes[sizeof(Magic)]; // The file system is split into a variable number of fixed size elements. // These elements are referred to as blocks. The size of a block may vary // from system to system. support::ulittle32_t BlockSize; // This field's purpose is not yet known. support::ulittle32_t Unknown0; // This contains the number of blocks resident in the file system. In // practice, NumBlocks * BlockSize is equivalent to the size of the PDB file. support::ulittle32_t NumBlocks; // This contains the number of bytes which make up the directory. support::ulittle32_t NumDirectoryBytes; // This field's purpose is not yet known. support::ulittle32_t Unknown1; // This contains the block # of the block map. support::ulittle32_t BlockMapAddr; }; } struct llvm::pdb::PDBFileContext { std::unique_ptr<MemoryBuffer> Buffer; const SuperBlock *SB; std::vector<uint32_t> StreamSizes; DenseMap<uint32_t, std::vector<uint32_t>> StreamMap; }; static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr, const uint64_t Size) { if (Addr + Size < Addr || Addr + Size < Size || Addr + Size > uintptr_t(M.getBufferEnd()) || Addr < uintptr_t(M.getBufferStart())) { return std::make_error_code(std::errc::bad_address); } return std::error_code(); } template <typename T> static std::error_code checkOffset(MemoryBufferRef M, ArrayRef<T> AR) { return checkOffset(M, uintptr_t(AR.data()), (uint64_t)AR.size() * sizeof(T)); } PDBFile::PDBFile(std::unique_ptr<MemoryBuffer> MemBuffer) { Context.reset(new PDBFileContext()); Context->Buffer = std::move(MemBuffer); } PDBFile::~PDBFile() {} uint32_t PDBFile::getBlockSize() const { return Context->SB->BlockSize; } uint32_t PDBFile::getUnknown0() const { return Context->SB->Unknown0; } uint32_t PDBFile::getBlockCount() const { return Context->SB->NumBlocks; } uint32_t PDBFile::getNumDirectoryBytes() const { return Context->SB->NumDirectoryBytes; } uint32_t PDBFile::getBlockMapIndex() const { return Context->SB->BlockMapAddr; } uint32_t PDBFile::getUnknown1() const { return Context->SB->Unknown1; } uint32_t PDBFile::getNumDirectoryBlocks() const { return bytesToBlocks(Context->SB->NumDirectoryBytes, Context->SB->BlockSize); } uint64_t PDBFile::getBlockMapOffset() const { return (uint64_t)Context->SB->BlockMapAddr * Context->SB->BlockSize; } uint32_t PDBFile::getNumStreams() const { return Context->StreamSizes.size(); } uint32_t PDBFile::getStreamByteSize(uint32_t StreamIndex) const { return Context->StreamSizes[StreamIndex]; } llvm::ArrayRef<uint32_t> PDBFile::getStreamBlockList(uint32_t StreamIndex) const { auto &Data = Context->StreamMap[StreamIndex]; return llvm::ArrayRef<uint32_t>(Data); } StringRef PDBFile::getBlockData(uint32_t BlockIndex, uint32_t NumBytes) const { uint64_t StreamBlockOffset = blockToOffset(BlockIndex, getBlockSize()); return StringRef(Context->Buffer->getBufferStart() + StreamBlockOffset, NumBytes); } std::error_code PDBFile::parseFileHeaders() { std::error_code EC; MemoryBufferRef BufferRef = *Context->Buffer; Context->SB = reinterpret_cast<const SuperBlock *>(BufferRef.getBufferStart()); const SuperBlock *SB = Context->SB; switch (SB->BlockSize) { case 512: case 1024: case 2048: case 4096: break; default: // An invalid block size suggests a corrupt PDB file. return std::make_error_code(std::errc::illegal_byte_sequence); } // Make sure the file is sufficiently large to hold a super block. if (BufferRef.getBufferSize() < sizeof(SuperBlock)) return std::make_error_code(std::errc::illegal_byte_sequence); // Check the magic bytes. if (memcmp(SB->MagicBytes, Magic, sizeof(Magic)) != 0) return std::make_error_code(std::errc::illegal_byte_sequence); // We don't support blocksizes which aren't a multiple of four bytes. if (SB->BlockSize == 0 || SB->BlockSize % sizeof(support::ulittle32_t) != 0) return std::make_error_code(std::errc::not_supported); // We don't support directories whose sizes aren't a multiple of four bytes. if (SB->NumDirectoryBytes % sizeof(support::ulittle32_t) != 0) return std::make_error_code(std::errc::not_supported); // The number of blocks which comprise the directory is a simple function of // the number of bytes it contains. uint64_t NumDirectoryBlocks = getNumDirectoryBlocks(); // The block map, as we understand it, is a block which consists of a list of // block numbers. // It is unclear what would happen if the number of blocks couldn't fit on a // single block. if (NumDirectoryBlocks > SB->BlockSize / sizeof(support::ulittle32_t)) return std::make_error_code(std::errc::illegal_byte_sequence); return std::error_code(); } std::error_code PDBFile::parseStreamData() { assert(Context && Context->SB); bool SeenNumStreams = false; uint32_t NumStreams = 0; uint32_t StreamIdx = 0; uint64_t DirectoryBytesRead = 0; MemoryBufferRef M = *Context->Buffer; const SuperBlock *SB = Context->SB; auto DirectoryBlocks = getDirectoryBlockArray(); // The structure of the directory is as follows: // struct PDBDirectory { // uint32_t NumStreams; // uint32_t StreamSizes[NumStreams]; // uint32_t StreamMap[NumStreams][]; // }; // // Empty streams don't consume entries in the StreamMap. for (uint32_t DirectoryBlockAddr : DirectoryBlocks) { uint64_t DirectoryBlockOffset = blockToOffset(DirectoryBlockAddr, SB->BlockSize); auto DirectoryBlock = makeArrayRef(reinterpret_cast<const support::ulittle32_t *>( M.getBufferStart() + DirectoryBlockOffset), SB->BlockSize / sizeof(support::ulittle32_t)); if (auto EC = checkOffset(M, DirectoryBlock)) return EC; // We read data out of the directory four bytes at a time. Depending on // where we are in the directory, the contents may be: the number of streams // in the directory, a stream's size, or a block in the stream map. for (uint32_t Data : DirectoryBlock) { // Don't read beyond the end of the directory. if (DirectoryBytesRead == SB->NumDirectoryBytes) break; DirectoryBytesRead += sizeof(Data); // This data must be the number of streams if we haven't seen it yet. if (!SeenNumStreams) { NumStreams = Data; SeenNumStreams = true; continue; } // This data must be a stream size if we have not seen them all yet. if (Context->StreamSizes.size() < NumStreams) { // It seems like some streams have their set to -1 when their contents // are not present. Treat them like empty streams for now. if (Data == UINT32_MAX) Context->StreamSizes.push_back(0); else Context->StreamSizes.push_back(Data); continue; } // This data must be a stream block number if we have seen all of the // stream sizes. std::vector<uint32_t> *StreamBlocks = nullptr; // Figure out which stream this block number belongs to. while (StreamIdx < NumStreams) { uint64_t NumExpectedStreamBlocks = bytesToBlocks(Context->StreamSizes[StreamIdx], SB->BlockSize); StreamBlocks = &Context->StreamMap[StreamIdx]; if (NumExpectedStreamBlocks > StreamBlocks->size()) break; ++StreamIdx; } // It seems this block doesn't belong to any stream? The stream is either // corrupt or something more mysterious is going on. if (StreamIdx == NumStreams) return std::make_error_code(std::errc::illegal_byte_sequence); StreamBlocks->push_back(Data); } } // We should have read exactly SB->NumDirectoryBytes bytes. assert(DirectoryBytesRead == SB->NumDirectoryBytes); return std::error_code(); } llvm::ArrayRef<support::ulittle32_t> PDBFile::getDirectoryBlockArray() { return makeArrayRef( reinterpret_cast<const support::ulittle32_t *>( Context->Buffer->getBufferStart() + getBlockMapOffset()), getNumDirectoryBlocks()); } InfoStream &PDBFile::getPDBInfoStream() { if (!Info) { Info.reset(new InfoStream(*this)); Info->reload(); } return *Info; } DbiStream &PDBFile::getPDBDbiStream() { if (!Dbi) { Dbi.reset(new DbiStream(*this)); Dbi->reload(); } return *Dbi; }
//===- PDBFile.cpp - Low level interface to a PDB file ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/Raw/PDBFile.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/DebugInfo/PDB/Raw/DbiStream.h" #include "llvm/DebugInfo/PDB/Raw/InfoStream.h" #include "llvm/Support/Endian.h" #include "llvm/Support/MemoryBuffer.h" using namespace llvm; using namespace llvm::pdb; namespace { static const char Magic[] = {'M', 'i', 'c', 'r', 'o', 's', 'o', 'f', 't', ' ', 'C', '/', 'C', '+', '+', ' ', 'M', 'S', 'F', ' ', '7', '.', '0', '0', '\r', '\n', '\x1a', 'D', 'S', '\0', '\0', '\0'}; // The superblock is overlaid at the beginning of the file (offset 0). // It starts with a magic header and is followed by information which describes // the layout of the file system. struct SuperBlock { char MagicBytes[sizeof(Magic)]; // The file system is split into a variable number of fixed size elements. // These elements are referred to as blocks. The size of a block may vary // from system to system. support::ulittle32_t BlockSize; // This field's purpose is not yet known. support::ulittle32_t Unknown0; // This contains the number of blocks resident in the file system. In // practice, NumBlocks * BlockSize is equivalent to the size of the PDB file. support::ulittle32_t NumBlocks; // This contains the number of bytes which make up the directory. support::ulittle32_t NumDirectoryBytes; // This field's purpose is not yet known. support::ulittle32_t Unknown1; // This contains the block # of the block map. support::ulittle32_t BlockMapAddr; }; } struct llvm::pdb::PDBFileContext { std::unique_ptr<MemoryBuffer> Buffer; const SuperBlock *SB; std::vector<uint32_t> StreamSizes; DenseMap<uint32_t, std::vector<uint32_t>> StreamMap; }; static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr, const uint64_t Size) { if (Addr + Size < Addr || Addr + Size < Size || Addr + Size > uintptr_t(M.getBufferEnd()) || Addr < uintptr_t(M.getBufferStart())) { return std::make_error_code(std::errc::bad_address); } return std::error_code(); } template <typename T> static std::error_code checkOffset(MemoryBufferRef M, ArrayRef<T> AR) { return checkOffset(M, uintptr_t(AR.data()), (uint64_t)AR.size() * sizeof(T)); } PDBFile::PDBFile(std::unique_ptr<MemoryBuffer> MemBuffer) { Context.reset(new PDBFileContext()); Context->Buffer = std::move(MemBuffer); } PDBFile::~PDBFile() {} uint32_t PDBFile::getBlockSize() const { return Context->SB->BlockSize; } uint32_t PDBFile::getUnknown0() const { return Context->SB->Unknown0; } uint32_t PDBFile::getBlockCount() const { return Context->SB->NumBlocks; } uint32_t PDBFile::getNumDirectoryBytes() const { return Context->SB->NumDirectoryBytes; } uint32_t PDBFile::getBlockMapIndex() const { return Context->SB->BlockMapAddr; } uint32_t PDBFile::getUnknown1() const { return Context->SB->Unknown1; } uint32_t PDBFile::getNumDirectoryBlocks() const { return bytesToBlocks(Context->SB->NumDirectoryBytes, Context->SB->BlockSize); } uint64_t PDBFile::getBlockMapOffset() const { return (uint64_t)Context->SB->BlockMapAddr * Context->SB->BlockSize; } uint32_t PDBFile::getNumStreams() const { return Context->StreamSizes.size(); } uint32_t PDBFile::getStreamByteSize(uint32_t StreamIndex) const { return Context->StreamSizes[StreamIndex]; } llvm::ArrayRef<uint32_t> PDBFile::getStreamBlockList(uint32_t StreamIndex) const { auto &Data = Context->StreamMap[StreamIndex]; return llvm::ArrayRef<uint32_t>(Data); } StringRef PDBFile::getBlockData(uint32_t BlockIndex, uint32_t NumBytes) const { uint64_t StreamBlockOffset = blockToOffset(BlockIndex, getBlockSize()); return StringRef(Context->Buffer->getBufferStart() + StreamBlockOffset, NumBytes); } std::error_code PDBFile::parseFileHeaders() { std::error_code EC; MemoryBufferRef BufferRef = *Context->Buffer; if (BufferRef.getBufferSize() < sizeof(SuperBlock)) return std::make_error_code(std::errc::illegal_byte_sequence); Context->SB = reinterpret_cast<const SuperBlock *>(BufferRef.getBufferStart()); const SuperBlock *SB = Context->SB; switch (SB->BlockSize) { case 512: case 1024: case 2048: case 4096: break; default: // An invalid block size suggests a corrupt PDB file. return std::make_error_code(std::errc::illegal_byte_sequence); } if (BufferRef.getBufferSize() % SB->BlockSize != 0) return std::make_error_code(std::errc::illegal_byte_sequence); // Make sure the file is sufficiently large to hold a super block. if (BufferRef.getBufferSize() < sizeof(SuperBlock)) return std::make_error_code(std::errc::illegal_byte_sequence); // Check the magic bytes. if (memcmp(SB->MagicBytes, Magic, sizeof(Magic)) != 0) return std::make_error_code(std::errc::illegal_byte_sequence); // We don't support blocksizes which aren't a multiple of four bytes. if (SB->BlockSize == 0 || SB->BlockSize % sizeof(support::ulittle32_t) != 0) return std::make_error_code(std::errc::not_supported); // We don't support directories whose sizes aren't a multiple of four bytes. if (SB->NumDirectoryBytes % sizeof(support::ulittle32_t) != 0) return std::make_error_code(std::errc::not_supported); // The number of blocks which comprise the directory is a simple function of // the number of bytes it contains. uint64_t NumDirectoryBlocks = getNumDirectoryBlocks(); // The block map, as we understand it, is a block which consists of a list of // block numbers. // It is unclear what would happen if the number of blocks couldn't fit on a // single block. if (NumDirectoryBlocks > SB->BlockSize / sizeof(support::ulittle32_t)) return std::make_error_code(std::errc::illegal_byte_sequence); return std::error_code(); } std::error_code PDBFile::parseStreamData() { assert(Context && Context->SB); bool SeenNumStreams = false; uint32_t NumStreams = 0; uint32_t StreamIdx = 0; uint64_t DirectoryBytesRead = 0; MemoryBufferRef M = *Context->Buffer; const SuperBlock *SB = Context->SB; auto DirectoryBlocks = getDirectoryBlockArray(); // The structure of the directory is as follows: // struct PDBDirectory { // uint32_t NumStreams; // uint32_t StreamSizes[NumStreams]; // uint32_t StreamMap[NumStreams][]; // }; // // Empty streams don't consume entries in the StreamMap. for (uint32_t DirectoryBlockAddr : DirectoryBlocks) { uint64_t DirectoryBlockOffset = blockToOffset(DirectoryBlockAddr, SB->BlockSize); auto DirectoryBlock = makeArrayRef(reinterpret_cast<const support::ulittle32_t *>( M.getBufferStart() + DirectoryBlockOffset), SB->BlockSize / sizeof(support::ulittle32_t)); if (auto EC = checkOffset(M, DirectoryBlock)) return EC; // We read data out of the directory four bytes at a time. Depending on // where we are in the directory, the contents may be: the number of streams // in the directory, a stream's size, or a block in the stream map. for (uint32_t Data : DirectoryBlock) { // Don't read beyond the end of the directory. if (DirectoryBytesRead == SB->NumDirectoryBytes) break; DirectoryBytesRead += sizeof(Data); // This data must be the number of streams if we haven't seen it yet. if (!SeenNumStreams) { NumStreams = Data; SeenNumStreams = true; continue; } // This data must be a stream size if we have not seen them all yet. if (Context->StreamSizes.size() < NumStreams) { // It seems like some streams have their set to -1 when their contents // are not present. Treat them like empty streams for now. if (Data == UINT32_MAX) Context->StreamSizes.push_back(0); else Context->StreamSizes.push_back(Data); continue; } // This data must be a stream block number if we have seen all of the // stream sizes. std::vector<uint32_t> *StreamBlocks = nullptr; // Figure out which stream this block number belongs to. while (StreamIdx < NumStreams) { uint64_t NumExpectedStreamBlocks = bytesToBlocks(Context->StreamSizes[StreamIdx], SB->BlockSize); StreamBlocks = &Context->StreamMap[StreamIdx]; if (NumExpectedStreamBlocks > StreamBlocks->size()) break; ++StreamIdx; } // It seems this block doesn't belong to any stream? The stream is either // corrupt or something more mysterious is going on. if (StreamIdx == NumStreams) return std::make_error_code(std::errc::illegal_byte_sequence); StreamBlocks->push_back(Data); } } // We should have read exactly SB->NumDirectoryBytes bytes. assert(DirectoryBytesRead == SB->NumDirectoryBytes); return std::error_code(); } llvm::ArrayRef<support::ulittle32_t> PDBFile::getDirectoryBlockArray() { return makeArrayRef( reinterpret_cast<const support::ulittle32_t *>( Context->Buffer->getBufferStart() + getBlockMapOffset()), getNumDirectoryBlocks()); } InfoStream &PDBFile::getPDBInfoStream() { if (!Info) { Info.reset(new InfoStream(*this)); Info->reload(); } return *Info; } DbiStream &PDBFile::getPDBDbiStream() { if (!Dbi) { Dbi.reset(new DbiStream(*this)); Dbi->reload(); } return *Dbi; }
Fix read past EOF when file is too small.
[llvm-pdbdump] Fix read past EOF when file is too small. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@268316 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm
d41726b381bcd3a0dd64a623af9dc06a5bd41bd7
src/plugin_winamp3/cnv_flacpcm.cpp
src/plugin_winamp3/cnv_flacpcm.cpp
/* FLAC input plugin for Winamp3 * Copyright (C) 2000,2001,2002 Josh Coalson * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * NOTE: this code is derived from the 'rawpcm' example by * Nullsoft; the original license for the 'rawpcm' example follows. */ /* Nullsoft WASABI Source File License Copyright 1999-2001 Nullsoft, Inc. 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. Brennan Underwood [email protected] */ #include "cnv_flacpcm.h" #include "flacpcm.h" static WACNAME wac; WAComponentClient *the = &wac; #include "studio/services/servicei.h" // {683FA153-4055-467c-ABEE-5E35FA03C51E} static const GUID guid = { 0x683fa153, 0x4055, 0x467c, { 0xab, 0xee, 0x5e, 0x35, 0xfa, 0x3, 0xc5, 0x1e } }; _int nch("# of channels", 2); _int samplerate("Sample rate", 44100); _int bps("Bits per second", 16); WACNAME::WACNAME() : WAComponentClient("RAW files support") { registerService(new waServiceT<svc_mediaConverter, FlacPcm>); } WACNAME::~WACNAME() { } GUID WACNAME::getGUID() { return guid; } void WACNAME::onRegisterServices() { api->core_registerExtension("*.flac","FLAC Files"); registerAttribute(&nch); registerAttribute(&samplerate); registerAttribute(&bps); }
/* FLAC input plugin for Winamp3 * Copyright (C) 2000,2001,2002 Josh Coalson * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * NOTE: this code is derived from the 'rawpcm' example by * Nullsoft; the original license for the 'rawpcm' example follows. */ /* Nullsoft WASABI Source File License Copyright 1999-2001 Nullsoft, Inc. 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. Brennan Underwood [email protected] */ #include "cnv_flacpcm.h" #include "flacpcm.h" static WACNAME wac; WAComponentClient *the = &wac; #include "studio/services/servicei.h" // {683FA153-4055-467c-ABEE-5E35FA03C51E} static const GUID guid = { 0x683fa153, 0x4055, 0x467c, { 0xab, 0xee, 0x5e, 0x35, 0xfa, 0x3, 0xc5, 0x1e } }; _int nch("# of channels", 2); _int samplerate("Sample rate", 44100); _int bps("Bits per second", 16); WACNAME::WACNAME() : WAComponentClient("FLAC file support") { registerService(new waServiceT<svc_mediaConverter, FlacPcm>); } WACNAME::~WACNAME() { } GUID WACNAME::getGUID() { return guid; } void WACNAME::onRegisterServices() { api->core_registerExtension("*.flac","FLAC Files"); registerAttribute(&nch); registerAttribute(&samplerate); registerAttribute(&bps); }
fix WACNAME
fix WACNAME
C++
bsd-3-clause
Distrotech/flac,Distrotech/flac,waitman/flac,waitman/flac,Distrotech/flac,waitman/flac,fredericgermain/flac,LordJZ/libflac,Distrotech/flac,fredericgermain/flac,kode54/flac,LordJZ/libflac,fredericgermain/flac,LordJZ/libflac,kode54/flac,fredericgermain/flac,waitman/flac,kode54/flac,kode54/flac,LordJZ/libflac,waitman/flac
ab0e8d918f69d30841d8aa20441400c72e25e1b8
src/aur/request.cc
src/aur/request.cc
#include "request.hh" #include <cstring> #include <memory> #include <string_view> #include <curl/curl.h> namespace aur { namespace { std::string UrlEscape(const std::string_view sv) { char* ptr = curl_easy_escape(nullptr, sv.data(), sv.size()); std::string escaped(ptr); curl_free(ptr); return escaped; } char* AppendUnsafe(char* to, std::string_view from) { auto ptr = mempcpy(to, from.data(), from.size()); return static_cast<char*>(ptr); } template <typename... Pieces> void StrAppend(std::string* out, const Pieces&... args) { std::vector<std::string_view> v{args...}; std::string::size_type append_sz = 0; for (const auto& piece : v) { append_sz += piece.size(); } auto original_sz = out->size(); out->resize(original_sz + append_sz); char* ptr = out->data() + original_sz; for (const auto& piece : v) { ptr = AppendUnsafe(ptr, piece); } } template <typename... Pieces> std::string StrCat(const Pieces&... args) { std::string out; StrAppend(&out, args...); return out; } void QueryParamFormatter(std::string* out, const HttpRequest::QueryParam& kv) { StrAppend(out, kv.first, "=", UrlEscape(kv.second)); } template <typename Iterator, typename Formatter> std::string StrJoin(Iterator begin, Iterator end, std::string_view s, Formatter&& f) { std::string result; std::string_view sep(""); for (Iterator it = begin; it != end; ++it) { result.append(sep.data(), sep.size()); f(&result, *it); sep = s; } return result; } } // namespace void RpcRequest::AddArg(std::string_view key, std::string_view value) { args_.emplace_back(key, value); } std::vector<std::string> RpcRequest::Build(std::string_view baseurl) const { const auto next_span = [&](std::string_view s) -> std::string_view { // No chopping needed. if (s.size() <= approx_max_length_) { return s; } // Try to chop at the final ampersand before the cutoff length. auto n = s.substr(0, approx_max_length_).rfind('&'); if (n != std::string_view::npos) { return s.substr(0, n); } // We found a single arg which is Too Damn Long. Look for the ampersand just // after the length limit and use all of it. n = s.substr(approx_max_length_).find('&'); if (n != std::string_view::npos) { return s.substr(0, n + approx_max_length_); } // We're at the end of the querystring and have no place to chop. return s; }; const auto qs = StrJoin(args_.begin(), args_.end(), "&", &QueryParamFormatter); std::string_view sv(qs); std::vector<std::string> requests; while (!sv.empty()) { const auto span = next_span(sv); requests.push_back(StrCat(baseurl, "/rpc?", base_querystring_, "&", span)); sv.remove_prefix(std::min(sv.length(), span.length() + 1)); } return requests; } RpcRequest::RpcRequest(const HttpRequest::QueryParams& base_params, long unsigned approx_max_length) : base_querystring_(StrJoin(base_params.begin(), base_params.end(), "&", &QueryParamFormatter)), approx_max_length_(approx_max_length) {} // static RawRequest RawRequest::ForTarball(const Package& package) { return RawRequest(package.aur_urlpath); } // static RawRequest RawRequest::ForSourceFile(const Package& package, std::string_view filename) { return RawRequest(StrCat("/cgit/aur.git/plain/", filename, "?h=", UrlEscape(package.pkgbase))); } std::vector<std::string> RawRequest::Build(std::string_view baseurl) const { return {StrCat(baseurl, urlpath_)}; } std::vector<std::string> CloneRequest::Build(std::string_view baseurl) const { return {StrCat(baseurl, "/", reponame_)}; } } // namespace aur
#include "request.hh" #include <cstring> #include <memory> #include <string_view> #include <curl/curl.h> namespace aur { namespace { std::string UrlEscape(const std::string_view sv) { char* ptr = curl_easy_escape(nullptr, sv.data(), sv.size()); std::string escaped(ptr); curl_free(ptr); return escaped; } char* AppendUnsafe(char* to, std::string_view from) { auto ptr = mempcpy(to, from.data(), from.size()); return static_cast<char*>(ptr); } template <typename... Pieces> void StrAppend(std::string* out, const Pieces&... args) { std::vector<std::string_view> v{args...}; std::string_view::size_type append_sz = 0; for (const auto& piece : v) { append_sz += piece.size(); } auto original_sz = out->size(); out->resize(original_sz + append_sz); char* ptr = out->data() + original_sz; for (const auto& piece : v) { ptr = AppendUnsafe(ptr, piece); } } template <typename... Pieces> std::string StrCat(const Pieces&... args) { std::string out; StrAppend(&out, args...); return out; } void QueryParamFormatter(std::string* out, const HttpRequest::QueryParam& kv) { StrAppend(out, kv.first, "=", UrlEscape(kv.second)); } template <typename Iterator, typename Formatter> std::string StrJoin(Iterator begin, Iterator end, std::string_view s, Formatter&& f) { std::string result; std::string_view sep(""); for (Iterator it = begin; it != end; ++it) { result.append(sep.data(), sep.size()); f(&result, *it); sep = s; } return result; } } // namespace void RpcRequest::AddArg(std::string_view key, std::string_view value) { args_.emplace_back(key, value); } std::vector<std::string> RpcRequest::Build(std::string_view baseurl) const { const auto next_span = [&](std::string_view s) -> std::string_view { // No chopping needed. if (s.size() <= approx_max_length_) { return s; } // Try to chop at the final ampersand before the cutoff length. auto n = s.substr(0, approx_max_length_).rfind('&'); if (n != std::string_view::npos) { return s.substr(0, n); } // We found a single arg which is Too Damn Long. Look for the ampersand just // after the length limit and use all of it. n = s.substr(approx_max_length_).find('&'); if (n != std::string_view::npos) { return s.substr(0, n + approx_max_length_); } // We're at the end of the querystring and have no place to chop. return s; }; const auto qs = StrJoin(args_.begin(), args_.end(), "&", &QueryParamFormatter); std::string_view sv(qs); std::vector<std::string> requests; while (!sv.empty()) { const auto span = next_span(sv); requests.push_back(StrCat(baseurl, "/rpc?", base_querystring_, "&", span)); sv.remove_prefix(std::min(sv.length(), span.length() + 1)); } return requests; } RpcRequest::RpcRequest(const HttpRequest::QueryParams& base_params, long unsigned approx_max_length) : base_querystring_(StrJoin(base_params.begin(), base_params.end(), "&", &QueryParamFormatter)), approx_max_length_(approx_max_length) {} // static RawRequest RawRequest::ForTarball(const Package& package) { return RawRequest(package.aur_urlpath); } // static RawRequest RawRequest::ForSourceFile(const Package& package, std::string_view filename) { return RawRequest(StrCat("/cgit/aur.git/plain/", filename, "?h=", UrlEscape(package.pkgbase))); } std::vector<std::string> RawRequest::Build(std::string_view baseurl) const { return {StrCat(baseurl, urlpath_)}; } std::vector<std::string> CloneRequest::Build(std::string_view baseurl) const { return {StrCat(baseurl, "/", reponame_)}; } } // namespace aur
Fix type in append size calculation
Fix type in append size calculation
C++
mit
falconindy/auracle,falconindy/auracle,falconindy/auracle
85ce6e18e1968c2480563b528b2c3ac1daad273c
src/pubkey/gost_3410/gost_3410.cpp
src/pubkey/gost_3410/gost_3410.cpp
/* * GOST 34.10-2001 implemenation * (C) 2007 Falko Strenzke, FlexSecure GmbH * Manuel Hartl, FlexSecure GmbH * (C) 2008-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/gost_3410.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <iostream> #include <stdio.h> namespace Botan { MemoryVector<byte> GOST_3410_PublicKey::x509_subject_public_key() const { // Trust CryptoPro to come up with something obnoxious const BigInt& x = public_point().get_affine_x(); const BigInt& y = public_point().get_affine_y(); u32bit part_size = std::max(x.bytes(), y.bytes()); MemoryVector<byte> bits(2*part_size); x.binary_encode(bits + (part_size - x.bytes())); y.binary_encode(bits + (2*part_size - y.bytes())); // Keys are stored in little endian format (WTF) for(u32bit i = 0; i != part_size / 2; ++i) { std::swap(bits[i], bits[part_size-1-i]); std::swap(bits[part_size+i], bits[2*part_size-1-i]); } return DER_Encoder().encode(bits, OCTET_STRING).get_contents(); } AlgorithmIdentifier GOST_3410_PublicKey::algorithm_identifier() const { MemoryVector<byte> params = DER_Encoder().start_cons(SEQUENCE) .encode(OID(domain().get_oid())) .end_cons() .get_contents(); return AlgorithmIdentifier(get_oid(), params); } GOST_3410_PublicKey::GOST_3410_PublicKey(const AlgorithmIdentifier& alg_id, const MemoryRegion<byte>& key_bits) { OID ecc_param_id; // Also includes hash and cipher OIDs... brilliant design guys BER_Decoder(alg_id.parameters).start_cons(SEQUENCE).decode(ecc_param_id); domain_params = EC_Domain_Params(ecc_param_id); SecureVector<byte> bits; BER_Decoder(key_bits).decode(bits, OCTET_STRING); const u32bit part_size = bits.size() / 2; // Keys are stored in little endian format (WTF) for(u32bit i = 0; i != part_size / 2; ++i) { std::swap(bits[i], bits[part_size-1-i]); std::swap(bits[part_size+i], bits[2*part_size-1-i]); } BigInt x(bits, part_size); BigInt y(bits + part_size, part_size); public_key = PointGFp(domain().get_curve(), x, y); try { public_key.check_invariants(); } catch(Illegal_Point) { throw Internal_Error("Loaded GOST 34.10 public key failed self test"); } } GOST_3410_Signature_Operation::GOST_3410_Signature_Operation( const GOST_3410_PrivateKey& gost_3410) : base_point(gost_3410.domain().get_base_point()), order(gost_3410.domain().get_order()), x(gost_3410.private_value()) { } SecureVector<byte> GOST_3410_Signature_Operation::sign(const byte msg[], u32bit msg_len, RandomNumberGenerator& rng) { BigInt k; do k.randomize(rng, order.bits()-1); while(k >= order); BigInt e(msg, msg_len); e %= order; if(e == 0) e = 1; PointGFp k_times_P = base_point * k; k_times_P.check_invariants(); BigInt r = k_times_P.get_affine_x() % order; BigInt s = (r*x + k*e) % order; if(r == 0 || s == 0) throw Invalid_State("GOST 34.10: r == 0 || s == 0"); SecureVector<byte> output(2*order.bytes()); r.binary_encode(output + (output.size() / 2 - r.bytes())); s.binary_encode(output + (output.size() - s.bytes())); return output; } GOST_3410_Verification_Operation::GOST_3410_Verification_Operation(const GOST_3410_PublicKey& gost) : base_point(gost.domain().get_base_point()), public_point(gost.public_point()), order(gost.domain().get_order()) { } bool GOST_3410_Verification_Operation::verify(const byte msg[], u32bit msg_len, const byte sig[], u32bit sig_len) { if(sig_len != order.bytes()*2) return false; BigInt e(msg, msg_len); BigInt r(sig, sig_len / 2); BigInt s(sig + sig_len / 2, sig_len / 2); if(r < 0 || r >= order || s < 0 || s >= order) return false; e %= order; if(e == 0) e = 1; BigInt v = inverse_mod(e, order); BigInt z1 = (s*v) % order; BigInt z2 = (-r*v) % order; PointGFp R = (z1 * base_point + z2 * public_point); return (R.get_affine_x() == r); } }
/* * GOST 34.10-2001 implemenation * (C) 2007 Falko Strenzke, FlexSecure GmbH * Manuel Hartl, FlexSecure GmbH * (C) 2008-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/gost_3410.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> namespace Botan { MemoryVector<byte> GOST_3410_PublicKey::x509_subject_public_key() const { // Trust CryptoPro to come up with something obnoxious const BigInt& x = public_point().get_affine_x(); const BigInt& y = public_point().get_affine_y(); u32bit part_size = std::max(x.bytes(), y.bytes()); MemoryVector<byte> bits(2*part_size); x.binary_encode(bits + (part_size - x.bytes())); y.binary_encode(bits + (2*part_size - y.bytes())); // Keys are stored in little endian format (WTF) for(u32bit i = 0; i != part_size / 2; ++i) { std::swap(bits[i], bits[part_size-1-i]); std::swap(bits[part_size+i], bits[2*part_size-1-i]); } return DER_Encoder().encode(bits, OCTET_STRING).get_contents(); } AlgorithmIdentifier GOST_3410_PublicKey::algorithm_identifier() const { MemoryVector<byte> params = DER_Encoder().start_cons(SEQUENCE) .encode(OID(domain().get_oid())) .end_cons() .get_contents(); return AlgorithmIdentifier(get_oid(), params); } GOST_3410_PublicKey::GOST_3410_PublicKey(const AlgorithmIdentifier& alg_id, const MemoryRegion<byte>& key_bits) { OID ecc_param_id; // Also includes hash and cipher OIDs... brilliant design guys BER_Decoder(alg_id.parameters).start_cons(SEQUENCE).decode(ecc_param_id); domain_params = EC_Domain_Params(ecc_param_id); SecureVector<byte> bits; BER_Decoder(key_bits).decode(bits, OCTET_STRING); const u32bit part_size = bits.size() / 2; // Keys are stored in little endian format (WTF) for(u32bit i = 0; i != part_size / 2; ++i) { std::swap(bits[i], bits[part_size-1-i]); std::swap(bits[part_size+i], bits[2*part_size-1-i]); } BigInt x(bits, part_size); BigInt y(bits + part_size, part_size); public_key = PointGFp(domain().get_curve(), x, y); try { public_key.check_invariants(); } catch(Illegal_Point) { throw Internal_Error("Loaded GOST 34.10 public key failed self test"); } } GOST_3410_Signature_Operation::GOST_3410_Signature_Operation( const GOST_3410_PrivateKey& gost_3410) : base_point(gost_3410.domain().get_base_point()), order(gost_3410.domain().get_order()), x(gost_3410.private_value()) { } SecureVector<byte> GOST_3410_Signature_Operation::sign(const byte msg[], u32bit msg_len, RandomNumberGenerator& rng) { BigInt k; do k.randomize(rng, order.bits()-1); while(k >= order); BigInt e(msg, msg_len); e %= order; if(e == 0) e = 1; PointGFp k_times_P = base_point * k; k_times_P.check_invariants(); BigInt r = k_times_P.get_affine_x() % order; BigInt s = (r*x + k*e) % order; if(r == 0 || s == 0) throw Invalid_State("GOST 34.10: r == 0 || s == 0"); SecureVector<byte> output(2*order.bytes()); r.binary_encode(output + (output.size() / 2 - r.bytes())); s.binary_encode(output + (output.size() - s.bytes())); return output; } GOST_3410_Verification_Operation::GOST_3410_Verification_Operation(const GOST_3410_PublicKey& gost) : base_point(gost.domain().get_base_point()), public_point(gost.public_point()), order(gost.domain().get_order()) { } bool GOST_3410_Verification_Operation::verify(const byte msg[], u32bit msg_len, const byte sig[], u32bit sig_len) { if(sig_len != order.bytes()*2) return false; BigInt e(msg, msg_len); BigInt r(sig, sig_len / 2); BigInt s(sig + sig_len / 2, sig_len / 2); if(r < 0 || r >= order || s < 0 || s >= order) return false; e %= order; if(e == 0) e = 1; BigInt v = inverse_mod(e, order); BigInt z1 = (s*v) % order; BigInt z2 = (-r*v) % order; PointGFp R = (z1 * base_point + z2 * public_point); return (R.get_affine_x() == r); } }
Remove iostream/stdio includes
Remove iostream/stdio includes
C++
bsd-2-clause
Rohde-Schwarz-Cybersecurity/botan,randombit/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,webmaster128/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,webmaster128/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan
63ddad54a9901450c09c136d19d68dd0357b72b8
libcaf_net/src/network_socket.cpp
libcaf_net/src/network_socket.cpp
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/net/network_socket.hpp" #include <cstdint> #include "caf/config.hpp" #include "caf/detail/net_syscall.hpp" #include "caf/detail/socket_sys_aliases.hpp" #include "caf/detail/socket_sys_includes.hpp" #include "caf/error.hpp" #include "caf/expected.hpp" #include "caf/io/network/protocol.hpp" #include "caf/logger.hpp" #include "caf/sec.hpp" #include "caf/variant.hpp" namespace { uint16_t port_of(sockaddr_in& what) { return what.sin_port; } uint16_t port_of(sockaddr_in6& what) { return what.sin6_port; } uint16_t port_of(sockaddr& what) { switch (what.sa_family) { case AF_INET: return port_of(reinterpret_cast<sockaddr_in&>(what)); case AF_INET6: return port_of(reinterpret_cast<sockaddr_in6&>(what)); default: break; } CAF_CRITICAL("invalid protocol family"); } } // namespace namespace caf { namespace net { #if defined(CAF_MACOS) || defined(CAF_IOS) || defined(CAF_BSD) # define CAF_HAS_NOSIGPIPE_SOCKET_FLAG #endif #ifdef CAF_WINDOWS error allow_sigpipe(network_socket x, bool) { if (x == invalid_socket) return make_error(sec::network_syscall_failed, "setsockopt", "invalid socket"); return none; } error allow_udp_connreset(network_socket x, bool new_value) { DWORD bytes_returned = 0; CAF_NET_SYSCALL("WSAIoctl", res, !=, 0, WSAIoctl(x.id, _WSAIOW(IOC_VENDOR, 12), &new_value, sizeof(new_value), NULL, 0, &bytes_returned, NULL, NULL)); return none; } #else // CAF_WINDOWS error allow_sigpipe(network_socket x, bool new_value) { # ifdef CAF_HAS_NOSIGPIPE_SOCKET_FLAG int value = new_value ? 0 : 1; CAF_NET_SYSCALL("setsockopt", res, !=, 0, setsockopt(x.id, SOL_SOCKET, SO_NOSIGPIPE, &value, static_cast<unsigned>(sizeof(value)))); # else // CAF_HAS_NO_SIGPIPE_SOCKET_FLAG if (x == invalid_socket) return make_error(sec::network_syscall_failed, "setsockopt", "invalid socket"); # endif // CAF_HAS_NO_SIGPIPE_SOCKET_FLAG return none; } error allow_udp_connreset(network_socket x, bool) { // SIO_UDP_CONNRESET only exists on Windows if (x == invalid_socket) return make_error(sec::network_syscall_failed, "WSAIoctl", "invalid socket"); return none; } #endif // CAF_WINDOWS expected<size_t> send_buffer_size(network_socket x) { int size = 0; socket_size_type ret_size = sizeof(size); CAF_NET_SYSCALL("getsockopt", res, !=, 0, getsockopt(x.id, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<getsockopt_ptr>(&size), &ret_size)); return static_cast<size_t>(size); } error send_buffer_size(network_socket x, size_t capacity) { auto new_value = static_cast<int>(capacity); CAF_NET_SYSCALL("setsockopt", res, !=, 0, setsockopt(x.id, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<setsockopt_ptr>(&new_value), static_cast<socket_size_type>(sizeof(int)))); return none; } expected<std::string> local_addr(network_socket x) { sockaddr_storage st; socket_size_type st_len = sizeof(st); sockaddr* sa = reinterpret_cast<sockaddr*>(&st); CAF_NET_SYSCALL("getsockname", tmp1, !=, 0, getsockname(x.id, sa, &st_len)); char addr[INET6_ADDRSTRLEN]{0}; switch (sa->sa_family) { case AF_INET: return inet_ntop(AF_INET, &reinterpret_cast<sockaddr_in*>(sa)->sin_addr, addr, sizeof(addr)); case AF_INET6: return inet_ntop(AF_INET6, &reinterpret_cast<sockaddr_in6*>(sa)->sin6_addr, addr, sizeof(addr)); default: break; } return make_error(sec::invalid_protocol_family, "local_addr", sa->sa_family); } expected<uint16_t> local_port(network_socket x) { sockaddr_storage st; auto st_len = static_cast<socket_size_type>(sizeof(st)); CAF_NET_SYSCALL("getsockname", tmp, !=, 0, getsockname(x.id, reinterpret_cast<sockaddr*>(&st), &st_len)); return ntohs(port_of(reinterpret_cast<sockaddr&>(st))); } expected<std::string> remote_addr(network_socket x) { sockaddr_storage st; socket_size_type st_len = sizeof(st); sockaddr* sa = reinterpret_cast<sockaddr*>(&st); CAF_NET_SYSCALL("getpeername", tmp, !=, 0, getpeername(x.id, sa, &st_len)); char addr[INET6_ADDRSTRLEN]{0}; switch (sa->sa_family) { case AF_INET: return inet_ntop(AF_INET, &reinterpret_cast<sockaddr_in*>(sa)->sin_addr, addr, sizeof(addr)); case AF_INET6: return inet_ntop(AF_INET6, &reinterpret_cast<sockaddr_in6*>(sa)->sin6_addr, addr, sizeof(addr)); default: break; } return make_error(sec::invalid_protocol_family, "remote_addr", sa->sa_family); } expected<uint16_t> remote_port(network_socket x) { sockaddr_storage st; socket_size_type st_len = sizeof(st); CAF_NET_SYSCALL("getpeername", tmp, !=, 0, getpeername(x.id, reinterpret_cast<sockaddr*>(&st), &st_len)); return ntohs(port_of(reinterpret_cast<sockaddr&>(st))); } void shutdown_read(network_socket x) { ::shutdown(x.id, 0); } void shutdown_write(network_socket x) { ::shutdown(x.id, 1); } void shutdown(network_socket x) { ::shutdown(x.id, 2); } } // namespace net } // namespace caf
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/net/network_socket.hpp" #include <cstdint> #include "caf/config.hpp" #include "caf/detail/net_syscall.hpp" #include "caf/detail/socket_sys_aliases.hpp" #include "caf/detail/socket_sys_includes.hpp" #include "caf/error.hpp" #include "caf/expected.hpp" #include "caf/logger.hpp" #include "caf/sec.hpp" #include "caf/variant.hpp" namespace { uint16_t port_of(sockaddr_in& what) { return what.sin_port; } uint16_t port_of(sockaddr_in6& what) { return what.sin6_port; } uint16_t port_of(sockaddr& what) { switch (what.sa_family) { case AF_INET: return port_of(reinterpret_cast<sockaddr_in&>(what)); case AF_INET6: return port_of(reinterpret_cast<sockaddr_in6&>(what)); default: break; } CAF_CRITICAL("invalid protocol family"); } } // namespace namespace caf { namespace net { #if defined(CAF_MACOS) || defined(CAF_IOS) || defined(CAF_BSD) # define CAF_HAS_NOSIGPIPE_SOCKET_FLAG #endif #ifdef CAF_WINDOWS error allow_sigpipe(network_socket x, bool) { if (x == invalid_socket) return make_error(sec::network_syscall_failed, "setsockopt", "invalid socket"); return none; } error allow_udp_connreset(network_socket x, bool new_value) { DWORD bytes_returned = 0; CAF_NET_SYSCALL("WSAIoctl", res, !=, 0, WSAIoctl(x.id, _WSAIOW(IOC_VENDOR, 12), &new_value, sizeof(new_value), NULL, 0, &bytes_returned, NULL, NULL)); return none; } #else // CAF_WINDOWS error allow_sigpipe(network_socket x, bool new_value) { # ifdef CAF_HAS_NOSIGPIPE_SOCKET_FLAG int value = new_value ? 0 : 1; CAF_NET_SYSCALL("setsockopt", res, !=, 0, setsockopt(x.id, SOL_SOCKET, SO_NOSIGPIPE, &value, static_cast<unsigned>(sizeof(value)))); # else // CAF_HAS_NO_SIGPIPE_SOCKET_FLAG if (x == invalid_socket) return make_error(sec::network_syscall_failed, "setsockopt", "invalid socket"); # endif // CAF_HAS_NO_SIGPIPE_SOCKET_FLAG return none; } error allow_udp_connreset(network_socket x, bool) { // SIO_UDP_CONNRESET only exists on Windows if (x == invalid_socket) return make_error(sec::network_syscall_failed, "WSAIoctl", "invalid socket"); return none; } #endif // CAF_WINDOWS expected<size_t> send_buffer_size(network_socket x) { int size = 0; socket_size_type ret_size = sizeof(size); CAF_NET_SYSCALL("getsockopt", res, !=, 0, getsockopt(x.id, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<getsockopt_ptr>(&size), &ret_size)); return static_cast<size_t>(size); } error send_buffer_size(network_socket x, size_t capacity) { auto new_value = static_cast<int>(capacity); CAF_NET_SYSCALL("setsockopt", res, !=, 0, setsockopt(x.id, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<setsockopt_ptr>(&new_value), static_cast<socket_size_type>(sizeof(int)))); return none; } expected<std::string> local_addr(network_socket x) { sockaddr_storage st; socket_size_type st_len = sizeof(st); sockaddr* sa = reinterpret_cast<sockaddr*>(&st); CAF_NET_SYSCALL("getsockname", tmp1, !=, 0, getsockname(x.id, sa, &st_len)); char addr[INET6_ADDRSTRLEN]{0}; switch (sa->sa_family) { case AF_INET: return inet_ntop(AF_INET, &reinterpret_cast<sockaddr_in*>(sa)->sin_addr, addr, sizeof(addr)); case AF_INET6: return inet_ntop(AF_INET6, &reinterpret_cast<sockaddr_in6*>(sa)->sin6_addr, addr, sizeof(addr)); default: break; } return make_error(sec::invalid_protocol_family, "local_addr", sa->sa_family); } expected<uint16_t> local_port(network_socket x) { sockaddr_storage st; auto st_len = static_cast<socket_size_type>(sizeof(st)); CAF_NET_SYSCALL("getsockname", tmp, !=, 0, getsockname(x.id, reinterpret_cast<sockaddr*>(&st), &st_len)); return ntohs(port_of(reinterpret_cast<sockaddr&>(st))); } expected<std::string> remote_addr(network_socket x) { sockaddr_storage st; socket_size_type st_len = sizeof(st); sockaddr* sa = reinterpret_cast<sockaddr*>(&st); CAF_NET_SYSCALL("getpeername", tmp, !=, 0, getpeername(x.id, sa, &st_len)); char addr[INET6_ADDRSTRLEN]{0}; switch (sa->sa_family) { case AF_INET: return inet_ntop(AF_INET, &reinterpret_cast<sockaddr_in*>(sa)->sin_addr, addr, sizeof(addr)); case AF_INET6: return inet_ntop(AF_INET6, &reinterpret_cast<sockaddr_in6*>(sa)->sin6_addr, addr, sizeof(addr)); default: break; } return make_error(sec::invalid_protocol_family, "remote_addr", sa->sa_family); } expected<uint16_t> remote_port(network_socket x) { sockaddr_storage st; socket_size_type st_len = sizeof(st); CAF_NET_SYSCALL("getpeername", tmp, !=, 0, getpeername(x.id, reinterpret_cast<sockaddr*>(&st), &st_len)); return ntohs(port_of(reinterpret_cast<sockaddr&>(st))); } void shutdown_read(network_socket x) { ::shutdown(x.id, 0); } void shutdown_write(network_socket x) { ::shutdown(x.id, 1); } void shutdown(network_socket x) { ::shutdown(x.id, 2); } } // namespace net } // namespace caf
Remove unnecessary include
Remove unnecessary include
C++
bsd-3-clause
DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework
2ee2ed5ddfa4987cfeae5042f1eb4c89df63d818
lib/smurff-cpp/MatricesData.cpp
lib/smurff-cpp/MatricesData.cpp
#include "MatricesData.h" #include "UnusedNoise.h" using namespace smurff; MatricesData::MatricesData() : total_dim(2) { name = "MatricesData"; noise_ptr = std::unique_ptr<INoiseModel>(new UnusedNoise(this)); } void MatricesData::init_pre() { mode_dim.resize(nmode()); for(int n = 0; n<nmode(); ++n) { std::vector<int> S(blocks.size()); int max_pos = -1; for(auto &blk : blocks) { int pos = blk.pos(n); int size = blk.dim(n); assert(size > 0); assert(S.at(pos) == 0 || S.at(pos) == size); S.at(pos) = size; max_pos = std::max(max_pos, pos); } int off = 0; auto &O = mode_dim.at(n); O.resize(max_pos+1); for(int pos=0; pos<=max_pos; ++pos) { O.at(pos) = off; off += S[pos]; } total_dim.at(n) = off; for(auto &blk : blocks) { int pos = blk.pos(n); blk._start.at(n) = O[pos]; } } cwise_mean = sum() / (double)(size() - nna()); // init sub-matrices for(auto &p : blocks) { p.data().init_pre(); p.data().compute_mode_mean(); } } void MatricesData::init_post() { Data::init_post(); // init sub-matrices for(auto &p : blocks) { p.data().init_post(); } } void MatricesData::setCenterMode(std::string mode) { Data::setCenterMode(mode); for(auto &p : blocks) p.data().setCenterMode(mode); } void MatricesData::center(double global_mean) { // center sub-matrices assert(global_mean == cwise_mean); this->global_mean = global_mean; for(auto &p : blocks) p.data().center(cwise_mean); } double MatricesData::compute_mode_mean(int mode, int pos) { double sum = .0; int N = 0; int count = 0; apply(mode, pos, [&](const Block &b) { double local_mean = b.data().mean(mode, pos - b.start(mode)); sum += local_mean * b.dim(mode); N += b.dim(mode); count++; }); assert(N>0); return sum / N; } double MatricesData::offset_to_mean(const PVec& pos) const { const Block &b = find(pos); return b.data().offset_to_mean(pos - b.start()); } MatrixData& MatricesData::add(const PVec& p, std::unique_ptr<MatrixData> data) { blocks.push_back(Block(p, std::move(data))); return blocks.back().data(); } double MatricesData::sumsq(const SubModel& model) const { assert(false); return NAN; } double MatricesData::var_total() const { return NAN; } double MatricesData::train_rmse(const SubModel& model) const { double sum = .0; int N = 0; int count = 0; for(auto &p : blocks) { auto &mtx = p.data(); double local_rmse = mtx.train_rmse(p.submodel(model)); sum += (local_rmse * local_rmse) * (mtx.size() - mtx.nna()); N += (mtx.size() - mtx.nna()); count++; } assert(N>0); return sqrt(sum / N); } void MatricesData::update(const SubModel &model) { for(auto &b : blocks) { b.data().noise().update(b.submodel(model)); } } void MatricesData::get_pnm(const SubModel& model, int mode, int d, Eigen::VectorXd& rr, Eigen::MatrixXd& MM) { int count = 0; apply(mode, pos, [&model, mode, pos, &rr, &MM, &count](const Block &b) { b.data().get_pnm(b.submodel(model), mode, pos - b.start(mode), rr, MM); count++; }); assert(count>0); } void MatricesData::update_pnm(const SubModel& model, int m) { for(auto &b : blocks) { b.data().update_pnm(b.submodel(model), m); } } std::ostream& MatricesData::info(std::ostream& os, std::string indent) { MatrixData::info(os, indent); os << indent << "Sub-Matrices:\n"; for(auto &p : blocks) { os << indent; p.pos().info(os); os << ":\n"; p.data().info(os, indent + " "); os << std::endl; } return os; } std::ostream& MatricesData::status(std::ostream& os, std::string indent) const { os << indent << "Sub-Matrices:\n"; for(auto &p : blocks) { os << indent << " "; p.pos().info(os); os << ": " << p.data().noise().getStatus() << "\n"; } return os; } int MatricesData::nnz() const { return accumulate(0, &MatrixData::nnz); } int MatricesData::nna() const { return accumulate(0, &MatrixData::nna); } double MatricesData::sum() const { return accumulate(.0, &MatrixData::sum); } PVec MatricesData::dim() const { return total_dim; } MatricesData::Block::Block(PVec p, std::unique_ptr<MatrixData> c) : _pos(p) , _start(2) , m(std::move(c)) { } const PVec MatricesData::Block::start() const { return _start; } const PVec MatricesData::Block::end() const { return start() + dim(); } const PVec MatricesData::Block::dim() const { return data().dim(); } const PVec MatricesData::Block::pos() const { return _pos; } int MatricesData::Block::start(int mode) const { return start().at(mode); } int MatricesData::Block::end(int mode) const { return end().at(mode); } int MatricesData::Block::dim(int mode) const { return dim().at(mode); } int MatricesData::Block::pos(int mode) const { return pos().at(mode); } MatrixData& MatricesData::Block::data() const { return *m; } bool MatricesData::Block::in(const PVec &p) const { return p.in(start(), end()); } bool MatricesData::Block::in(int mode, int p) const { return p >= start(mode) && p < end(mode); } SubModel MatricesData::Block::submodel(const SubModel& model) const { return SubModel(model, start(), dim()); } const MatricesData::Block& MatricesData::find(const PVec& p) const { return *std::find_if(blocks.begin(), blocks.end(), [p](const Block &b) -> bool { return b.in(p); }); } int MatricesData::nview(int mode) const { return mode_dim.at(mode).size(); } int MatricesData::view(int mode, int pos) const { assert(pos < MatrixData::dim(mode)); const auto &v = mode_dim.at(mode); int off = 0; for(int i=0; i<nview(mode); ++i) { off += v.at(i); if (pos < off) return i; } assert(false); return -1; }
#include "MatricesData.h" #include "UnusedNoise.h" using namespace smurff; MatricesData::MatricesData() : total_dim(2) { name = "MatricesData"; noise_ptr = std::unique_ptr<INoiseModel>(new UnusedNoise(this)); } void MatricesData::init_pre() { mode_dim.resize(nmode()); for(int n = 0; n<nmode(); ++n) { std::vector<int> S(blocks.size()); int max_pos = -1; for(auto &blk : blocks) { int pos = blk.pos(n); int size = blk.dim(n); assert(size > 0); assert(S.at(pos) == 0 || S.at(pos) == size); S.at(pos) = size; max_pos = std::max(max_pos, pos); } int off = 0; auto &O = mode_dim.at(n); O.resize(max_pos+1); for(int pos=0; pos<=max_pos; ++pos) { O.at(pos) = off; off += S[pos]; } total_dim.at(n) = off; for(auto &blk : blocks) { int pos = blk.pos(n); blk._start.at(n) = O[pos]; } } cwise_mean = sum() / (double)(size() - nna()); // init sub-matrices for(auto &p : blocks) { p.data().init_pre(); p.data().compute_mode_mean(); } } void MatricesData::init_post() { Data::init_post(); // init sub-matrices for(auto &p : blocks) { p.data().init_post(); } } void MatricesData::setCenterMode(std::string mode) { Data::setCenterMode(mode); for(auto &p : blocks) p.data().setCenterMode(mode); } void MatricesData::center(double global_mean) { // center sub-matrices assert(global_mean == cwise_mean); this->global_mean = global_mean; for(auto &p : blocks) p.data().center(cwise_mean); } double MatricesData::compute_mode_mean(int mode, int pos) { double sum = .0; int N = 0; int count = 0; apply(mode, pos, [&](const Block &b) { double local_mean = b.data().mean(mode, pos - b.start(mode)); sum += local_mean * b.dim(mode); N += b.dim(mode); count++; }); assert(N>0); return sum / N; } double MatricesData::offset_to_mean(const PVec& pos) const { const Block &b = find(pos); return b.data().offset_to_mean(pos - b.start()); } MatrixData& MatricesData::add(const PVec& p, std::unique_ptr<MatrixData> data) { blocks.push_back(Block(p, std::move(data))); return blocks.back().data(); } double MatricesData::sumsq(const SubModel& model) const { assert(false); return NAN; } double MatricesData::var_total() const { return NAN; } double MatricesData::train_rmse(const SubModel& model) const { double sum = .0; int N = 0; int count = 0; for(auto &p : blocks) { auto &mtx = p.data(); double local_rmse = mtx.train_rmse(p.submodel(model)); sum += (local_rmse * local_rmse) * (mtx.size() - mtx.nna()); N += (mtx.size() - mtx.nna()); count++; } assert(N>0); return sqrt(sum / N); } void MatricesData::update(const SubModel &model) { for(auto &b : blocks) { b.data().noise().update(b.submodel(model)); } } void MatricesData::get_pnm(const SubModel& model, int mode, int pos, Eigen::VectorXd& rr, Eigen::MatrixXd& MM) { int count = 0; apply(mode, pos, [&model, mode, pos, &rr, &MM, &count](const Block &b) { b.data().get_pnm(b.submodel(model), mode, pos - b.start(mode), rr, MM); count++; }); assert(count>0); } void MatricesData::update_pnm(const SubModel& model, int m) { for(auto &b : blocks) { b.data().update_pnm(b.submodel(model), m); } } std::ostream& MatricesData::info(std::ostream& os, std::string indent) { MatrixData::info(os, indent); os << indent << "Sub-Matrices:\n"; for(auto &p : blocks) { os << indent; p.pos().info(os); os << ":\n"; p.data().info(os, indent + " "); os << std::endl; } return os; } std::ostream& MatricesData::status(std::ostream& os, std::string indent) const { os << indent << "Sub-Matrices:\n"; for(auto &p : blocks) { os << indent << " "; p.pos().info(os); os << ": " << p.data().noise().getStatus() << "\n"; } return os; } int MatricesData::nnz() const { return accumulate(0, &MatrixData::nnz); } int MatricesData::nna() const { return accumulate(0, &MatrixData::nna); } double MatricesData::sum() const { return accumulate(.0, &MatrixData::sum); } PVec MatricesData::dim() const { return total_dim; } MatricesData::Block::Block(PVec p, std::unique_ptr<MatrixData> c) : _pos(p) , _start(2) , m(std::move(c)) { } const PVec MatricesData::Block::start() const { return _start; } const PVec MatricesData::Block::end() const { return start() + dim(); } const PVec MatricesData::Block::dim() const { return data().dim(); } const PVec MatricesData::Block::pos() const { return _pos; } int MatricesData::Block::start(int mode) const { return start().at(mode); } int MatricesData::Block::end(int mode) const { return end().at(mode); } int MatricesData::Block::dim(int mode) const { return dim().at(mode); } int MatricesData::Block::pos(int mode) const { return pos().at(mode); } MatrixData& MatricesData::Block::data() const { return *m; } bool MatricesData::Block::in(const PVec &p) const { return p.in(start(), end()); } bool MatricesData::Block::in(int mode, int p) const { return p >= start(mode) && p < end(mode); } SubModel MatricesData::Block::submodel(const SubModel& model) const { return SubModel(model, start(), dim()); } const MatricesData::Block& MatricesData::find(const PVec& p) const { return *std::find_if(blocks.begin(), blocks.end(), [p](const Block &b) -> bool { return b.in(p); }); } int MatricesData::nview(int mode) const { return mode_dim.at(mode).size(); } int MatricesData::view(int mode, int pos) const { assert(pos < MatrixData::dim(mode)); const auto &v = mode_dim.at(mode); int off = 0; for(int i=0; i<nview(mode); ++i) { off += v.at(i); if (pos < off) return i; } assert(false); return -1; }
Fix compilation issue
Fix compilation issue
C++
mit
ExaScience/smurff,ExaScience/smurff,ExaScience/smurff,ExaScience/smurff,ExaScience/smurff,ExaScience/smurff
ae40630a7b6c1932bf5a3c0a66265afb52a402dc
lib/Target/ARM/ARMMacroFusion.cpp
lib/Target/ARM/ARMMacroFusion.cpp
//===- ARMMacroFusion.cpp - ARM Macro Fusion ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file This file contains the ARM implementation of the DAG scheduling /// mutation to pair instructions back to back. // //===----------------------------------------------------------------------===// #include "ARMMacroFusion.h" #include "ARMSubtarget.h" #include "llvm/CodeGen/MacroFusion.h" #include "llvm/CodeGen/TargetInstrInfo.h" namespace llvm { // Fuse AES crypto encoding or decoding. static bool isAESPair(const MachineInstr *FirstMI, const MachineInstr &SecondMI) { // Assume the 1st instr to be a wildcard if it is unspecified. unsigned FirstOpcode = FirstMI ? FirstMI->getOpcode() : static_cast<unsigned>(ARM::INSTRUCTION_LIST_END); unsigned SecondOpcode = SecondMI.getOpcode(); switch(SecondOpcode) { // AES encode. case ARM::AESMC : return FirstOpcode == ARM::AESE || FirstOpcode == ARM::INSTRUCTION_LIST_END; // AES decode. case ARM::AESIMC: return FirstOpcode == ARM::AESD || FirstOpcode == ARM::INSTRUCTION_LIST_END; } return false; } // Fuse literal generation. static bool isLiteralsPair(const MachineInstr *FirstMI, const MachineInstr &SecondMI) { // Assume the 1st instr to be a wildcard if it is unspecified. unsigned FirstOpcode = FirstMI ? FirstMI->getOpcode() : static_cast<unsigned>(ARM::INSTRUCTION_LIST_END); unsigned SecondOpcode = SecondMI.getOpcode(); // 32 bit immediate. if ((FirstOpcode == ARM::INSTRUCTION_LIST_END || FirstOpcode == ARM::MOVi16) && SecondOpcode == ARM::MOVTi16) return true; return false; } /// Check if the instr pair, FirstMI and SecondMI, should be fused /// together. Given SecondMI, when FirstMI is unspecified, then check if /// SecondMI may be part of a fused pair at all. static bool shouldScheduleAdjacent(const TargetInstrInfo &TII, const TargetSubtargetInfo &TSI, const MachineInstr *FirstMI, const MachineInstr &SecondMI) { const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(TSI); if (ST.hasFuseAES() && isAESPair(FirstMI, SecondMI)) return true; if (ST.hasFuseLiterals() && isLiteralsPair(FirstMI, SecondMI)) return true; return false; } std::unique_ptr<ScheduleDAGMutation> createARMMacroFusionDAGMutation () { return createMacroFusionDAGMutation(shouldScheduleAdjacent); } } // end namespace llvm
//===- ARMMacroFusion.cpp - ARM Macro Fusion ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file This file contains the ARM implementation of the DAG scheduling /// mutation to pair instructions back to back. // //===----------------------------------------------------------------------===// #include "ARMMacroFusion.h" #include "ARMSubtarget.h" #include "llvm/CodeGen/MacroFusion.h" #include "llvm/CodeGen/TargetInstrInfo.h" namespace llvm { // Fuse AES crypto encoding or decoding. static bool isAESPair(const MachineInstr *FirstMI, const MachineInstr &SecondMI) { // Assume the 1st instr to be a wildcard if it is unspecified. switch(SecondMI.getOpcode()) { // AES encode. case ARM::AESMC : return FirstMI == nullptr || FirstMI->getOpcode() == ARM::AESE; // AES decode. case ARM::AESIMC: return FirstMI == nullptr || FirstMI->getOpcode() == ARM::AESD; } return false; } // Fuse literal generation. static bool isLiteralsPair(const MachineInstr *FirstMI, const MachineInstr &SecondMI) { // Assume the 1st instr to be a wildcard if it is unspecified. if ((FirstMI == nullptr || FirstMI->getOpcode() == ARM::MOVi16) && SecondMI.getOpcode() == ARM::MOVTi16) return true; return false; } /// Check if the instr pair, FirstMI and SecondMI, should be fused /// together. Given SecondMI, when FirstMI is unspecified, then check if /// SecondMI may be part of a fused pair at all. static bool shouldScheduleAdjacent(const TargetInstrInfo &TII, const TargetSubtargetInfo &TSI, const MachineInstr *FirstMI, const MachineInstr &SecondMI) { const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(TSI); if (ST.hasFuseAES() && isAESPair(FirstMI, SecondMI)) return true; if (ST.hasFuseLiterals() && isLiteralsPair(FirstMI, SecondMI)) return true; return false; } std::unique_ptr<ScheduleDAGMutation> createARMMacroFusionDAGMutation () { return createMacroFusionDAGMutation(shouldScheduleAdjacent); } } // end namespace llvm
Refactor macro fusion
[NFC][ARM] Refactor macro fusion Simplify code for wildcards. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@344625 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm
6fd02f44810754ae7481838b6a67c5df7f909ca3
tensorflow/core/kernels/sparse_add_op.cc
tensorflow/core/kernels/sparse_add_op.cc
/* 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/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_util.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/util/sparse/sparse_tensor.h" namespace tensorflow { template <typename T, typename Treal> class SparseAddOp : public OpKernel { public: explicit SparseAddOp(OpKernelConstruction *ctx) : OpKernel(ctx) {} void Compute(OpKernelContext *ctx) override { // (0) validations const Tensor *a_indices, *b_indices, *a_values_t, *b_values_t, *a_shape, *b_shape, *thresh_t; OP_REQUIRES_OK(ctx, ctx->input("a_indices", &a_indices)); OP_REQUIRES_OK(ctx, ctx->input("b_indices", &b_indices)); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a_indices->shape()) && TensorShapeUtils::IsMatrix(b_indices->shape()), errors::InvalidArgument( "Input indices should be matrices but received shapes: ", a_indices->shape().DebugString(), " and ", b_indices->shape().DebugString())); const int64 a_nnz = a_indices->dim_size(0); const int64 b_nnz = b_indices->dim_size(0); OP_REQUIRES_OK(ctx, ctx->input("a_values", &a_values_t)); OP_REQUIRES_OK(ctx, ctx->input("b_values", &b_values_t)); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(a_values_t->shape()) && TensorShapeUtils::IsVector(b_values_t->shape()), errors::InvalidArgument( "Input values should be vectors but received shapes: ", a_values_t->shape().DebugString(), " and ", b_values_t->shape().DebugString())); auto a_values = ctx->input(1).vec<T>(); auto b_values = ctx->input(4).vec<T>(); OP_REQUIRES( ctx, a_values.size() == a_nnz && b_values.size() == b_nnz, errors::InvalidArgument("Expected ", a_nnz, " and ", b_nnz, " non-empty input values, got ", a_values.size(), " and ", b_values.size())); OP_REQUIRES_OK(ctx, ctx->input("a_shape", &a_shape)); OP_REQUIRES_OK(ctx, ctx->input("b_shape", &b_shape)); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(a_shape->shape()) && TensorShapeUtils::IsVector(b_shape->shape()), errors::InvalidArgument( "Input shapes should be a vector but received shapes ", a_shape->shape().DebugString(), " and ", b_shape->shape().DebugString())); OP_REQUIRES( ctx, a_shape->IsSameSize(*b_shape), errors::InvalidArgument( "Operands do not have the same ranks; got shapes: ", a_shape->SummarizeValue(10), " and ", b_shape->SummarizeValue(10))); const auto a_shape_flat = a_shape->flat<int64>(); const auto b_shape_flat = b_shape->flat<int64>(); for (int i = 0; i < a_shape->NumElements(); ++i) { OP_REQUIRES(ctx, a_shape_flat(i) == b_shape_flat(i), errors::InvalidArgument( "Operands' shapes do not match: got ", a_shape_flat(i), " and ", b_shape_flat(i), " for dimension ", i)); } OP_REQUIRES_OK(ctx, ctx->input("thresh", &thresh_t)); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(thresh_t->shape()), errors::InvalidArgument( "The magnitude threshold must be a scalar: got shape ", thresh_t->shape().DebugString())); // std::abs() so that it works for complex{64,128} values as well const Treal thresh = thresh_t->scalar<Treal>()(); // (1) do a pass over inputs, and append values and indices to vectors auto a_indices_mat = a_indices->matrix<int64>(); auto b_indices_mat = b_indices->matrix<int64>(); std::vector<std::pair<bool, int64>> entries_to_copy; // from_a?, idx entries_to_copy.reserve(a_nnz + b_nnz); std::vector<T> out_values; const int num_dims = a_shape->dim_size(0); // The input and output sparse tensors are assumed to be ordered along // increasing dimension number. int64 i = 0, j = 0; T s; while (i < a_nnz && j < b_nnz) { switch (sparse::DimComparator::cmp(a_indices_mat, b_indices_mat, i, j, num_dims)) { case -1: entries_to_copy.emplace_back(true, i); out_values.push_back(a_values(i)); ++i; break; case 0: s = a_values(i) + b_values(j); if (thresh <= std::abs(s)) { entries_to_copy.emplace_back(true, i); out_values.push_back(s); } ++i; ++j; break; case 1: entries_to_copy.emplace_back(false, j); out_values.push_back(b_values(j)); ++j; break; } } #define HANDLE_LEFTOVERS(A_OR_B, IDX, IS_A) \ while (IDX < A_OR_B##_nnz) { \ entries_to_copy.emplace_back(IS_A, IDX); \ out_values.push_back(A_OR_B##_values(IDX)); \ ++IDX; \ } // at most one of these calls appends new values HANDLE_LEFTOVERS(a, i, true); HANDLE_LEFTOVERS(b, j, false); #undef HANDLE_LEFTOVERS // (2) allocate and fill output tensors const int64 sum_nnz = out_values.size(); Tensor *out_indices_t, *out_values_t; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}), &out_indices_t)); OP_REQUIRES_OK( ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &out_values_t)); auto out_indices_mat = out_indices_t->matrix<int64>(); auto out_values_flat = out_values_t->vec<T>(); for (i = 0; i < sum_nnz; ++i) { const bool from_a = entries_to_copy[i].first; const int64 idx = entries_to_copy[i].second; out_indices_mat.chip<0>(i) = from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx); } if (sum_nnz > 0) { std::copy_n(out_values.begin(), sum_nnz, &out_values_flat(0)); } ctx->set_output(2, *a_shape); } }; #define REGISTER_KERNELS(type, thresh_type) \ REGISTER_KERNEL_BUILDER( \ Name("SparseAdd").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ SparseAddOp<type, thresh_type>) // The list below is equivalent to TF_CALL_REAL_NUMBER_TYPES, minus uint8. This // is because std::abs() on uint8 does not compile. REGISTER_KERNELS(float, float); REGISTER_KERNELS(double, double); REGISTER_KERNELS(int64, int64); REGISTER_KERNELS(int32, int32); REGISTER_KERNELS(int16, int16); REGISTER_KERNELS(int8, int8); REGISTER_KERNELS(complex64, float); REGISTER_KERNELS(complex128, double); #undef REGISTER_KERNELS } // namespace tensorflow
/* 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/core/framework/op_kernel.h" #include "tensorflow/core/framework/op_requires.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_util.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/util/sparse/sparse_tensor.h" namespace tensorflow { template <typename T, typename Treal> class SparseAddOp : public OpKernel { public: explicit SparseAddOp(OpKernelConstruction *ctx) : OpKernel(ctx) {} void Compute(OpKernelContext *ctx) override { // (0) validations const Tensor *a_indices, *b_indices, *a_values_t, *b_values_t, *a_shape, *b_shape, *thresh_t; OP_REQUIRES_OK(ctx, ctx->input("a_indices", &a_indices)); OP_REQUIRES_OK(ctx, ctx->input("b_indices", &b_indices)); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a_indices->shape()) && TensorShapeUtils::IsMatrix(b_indices->shape()), errors::InvalidArgument( "Input indices should be matrices but received shapes: ", a_indices->shape().DebugString(), " and ", b_indices->shape().DebugString())); const int64 a_nnz = a_indices->dim_size(0); const int64 b_nnz = b_indices->dim_size(0); OP_REQUIRES_OK(ctx, ctx->input("a_values", &a_values_t)); OP_REQUIRES_OK(ctx, ctx->input("b_values", &b_values_t)); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(a_values_t->shape()) && TensorShapeUtils::IsVector(b_values_t->shape()), errors::InvalidArgument( "Input values should be vectors but received shapes: ", a_values_t->shape().DebugString(), " and ", b_values_t->shape().DebugString())); auto a_values = ctx->input(1).vec<T>(); auto b_values = ctx->input(4).vec<T>(); OP_REQUIRES( ctx, a_values.size() == a_nnz && b_values.size() == b_nnz, errors::InvalidArgument("Expected ", a_nnz, " and ", b_nnz, " non-empty input values, got ", a_values.size(), " and ", b_values.size())); OP_REQUIRES_OK(ctx, ctx->input("a_shape", &a_shape)); OP_REQUIRES_OK(ctx, ctx->input("b_shape", &b_shape)); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(a_shape->shape()) && TensorShapeUtils::IsVector(b_shape->shape()), errors::InvalidArgument( "Input shapes should be a vector but received shapes ", a_shape->shape().DebugString(), " and ", b_shape->shape().DebugString())); OP_REQUIRES( ctx, a_shape->IsSameSize(*b_shape), errors::InvalidArgument( "Operands do not have the same ranks; got shapes: ", a_shape->SummarizeValue(10), " and ", b_shape->SummarizeValue(10))); const auto a_shape_flat = a_shape->flat<int64>(); const auto b_shape_flat = b_shape->flat<int64>(); for (int i = 0; i < a_shape->NumElements(); ++i) { OP_REQUIRES(ctx, a_shape_flat(i) == b_shape_flat(i), errors::InvalidArgument( "Operands' shapes do not match: got ", a_shape_flat(i), " and ", b_shape_flat(i), " for dimension ", i)); } OP_REQUIRES_OK(ctx, ctx->input("thresh", &thresh_t)); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(thresh_t->shape()), errors::InvalidArgument( "The magnitude threshold must be a scalar: got shape ", thresh_t->shape().DebugString())); // std::abs() so that it works for complex{64,128} values as well const Treal thresh = thresh_t->scalar<Treal>()(); // (1) do a pass over inputs, and append values and indices to vectors auto a_indices_mat = a_indices->matrix<int64>(); auto b_indices_mat = b_indices->matrix<int64>(); std::vector<std::pair<bool, int64>> entries_to_copy; // from_a?, idx entries_to_copy.reserve(a_nnz + b_nnz); std::vector<T> out_values; const int num_dims = a_shape->dim_size(0); OP_REQUIRES(ctx, num_dims > 0, errors::InvalidArgument("Invalid input_a shape. Received: ", a_shape->DebugString())); // The input and output sparse tensors are assumed to be ordered along // increasing dimension number. int64 i = 0, j = 0; T s; while (i < a_nnz && j < b_nnz) { switch (sparse::DimComparator::cmp(a_indices_mat, b_indices_mat, i, j, num_dims)) { case -1: entries_to_copy.emplace_back(true, i); out_values.push_back(a_values(i)); ++i; break; case 0: s = a_values(i) + b_values(j); if (thresh <= std::abs(s)) { entries_to_copy.emplace_back(true, i); out_values.push_back(s); } ++i; ++j; break; case 1: entries_to_copy.emplace_back(false, j); out_values.push_back(b_values(j)); ++j; break; } } #define HANDLE_LEFTOVERS(A_OR_B, IDX, IS_A) \ while (IDX < A_OR_B##_nnz) { \ entries_to_copy.emplace_back(IS_A, IDX); \ out_values.push_back(A_OR_B##_values(IDX)); \ ++IDX; \ } // at most one of these calls appends new values HANDLE_LEFTOVERS(a, i, true); HANDLE_LEFTOVERS(b, j, false); #undef HANDLE_LEFTOVERS // (2) allocate and fill output tensors const int64 sum_nnz = out_values.size(); Tensor *out_indices_t, *out_values_t; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}), &out_indices_t)); OP_REQUIRES_OK( ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &out_values_t)); auto out_indices_mat = out_indices_t->matrix<int64>(); auto out_values_flat = out_values_t->vec<T>(); for (i = 0; i < sum_nnz; ++i) { const bool from_a = entries_to_copy[i].first; const int64 idx = entries_to_copy[i].second; out_indices_mat.chip<0>(i) = from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx); } if (sum_nnz > 0) { std::copy_n(out_values.begin(), sum_nnz, &out_values_flat(0)); } ctx->set_output(2, *a_shape); } }; #define REGISTER_KERNELS(type, thresh_type) \ REGISTER_KERNEL_BUILDER( \ Name("SparseAdd").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ SparseAddOp<type, thresh_type>) // The list below is equivalent to TF_CALL_REAL_NUMBER_TYPES, minus uint8. This // is because std::abs() on uint8 does not compile. REGISTER_KERNELS(float, float); REGISTER_KERNELS(double, double); REGISTER_KERNELS(int64, int64); REGISTER_KERNELS(int32, int32); REGISTER_KERNELS(int16, int16); REGISTER_KERNELS(int8, int8); REGISTER_KERNELS(complex64, float); REGISTER_KERNELS(complex128, double); #undef REGISTER_KERNELS } // namespace tensorflow
Fix `tf.raw_ops.SparseAdd ` invalid memory access failure.
Fix `tf.raw_ops.SparseAdd ` invalid memory access failure. PiperOrigin-RevId: 370568774 Change-Id: I5f73b31c865f2948a1c8dfb7ebd22b3cfb6405bf
C++
apache-2.0
tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,gautam1858/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,sarvex/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,yongtang/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,sarvex/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,sarvex/tensorflow,karllessard/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,karllessard/tensorflow,gautam1858/tensorflow,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow
a937f5ef10ebc81f1d9d68e6c0bbf2173bd5583e
libkopete/private/kopeteprefs.cpp
libkopete/private/kopeteprefs.cpp
/* kopeteprefs.cpp - Kopete Preferences Container-Class Copyright (c) 2002 by Stefan Gehn <[email protected]> Kopete (c) 2002-2003 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "kopeteprefs.h" #include <qfile.h> #include <kapplication.h> #include <kglobalsettings.h> #include <kconfig.h> #include <kdebug.h> #include <kstandarddirs.h> KopetePrefs *KopetePrefs::s_prefs = 0L; KopetePrefs *KopetePrefs::prefs() { if( !s_prefs ) s_prefs = new KopetePrefs; return s_prefs; } KopetePrefs::KopetePrefs() : QObject( kapp, "KopetePrefs" ) { config = KGlobal::config(); load(); } void KopetePrefs::load() { // kdDebug(14010) << "KopetePrefs::load()" << endl; config->setGroup("Appearance"); mWindowAppearanceChanged = false; mIconTheme = config->readEntry("EmoticonTheme", defaultTheme()); mUseEmoticons = config->readBoolEntry("Use Emoticons", true); mShowOffline = config->readBoolEntry("ShowOfflineUsers", true); mGreyIdle = config->readBoolEntry("GreyIdleMetaContacts", true); mSortByGroup = config->readBoolEntry("SortByGroup" , true); mTreeView = config->readBoolEntry("TreeView", true); mStartDocked = config->readBoolEntry("StartDocked", false); mUseQueue = config->readBoolEntry("Use Queue", true); mRaiseMsgWindow = config->readBoolEntry("Raise Msg Window", false); mShowEvents = config->readBoolEntry("Show Events in Chat Window", true); mTrayflashNotify = config->readBoolEntry("Trayflash Notification", true); mBalloonNotify = config->readBoolEntry("Balloon Notification", true); mSoundIfAway = config->readBoolEntry("Sound Notification If Away", false); mChatWindowPolicy = config->readNumEntry("Chatwindow Policy", 0); mTransparencyEnabled = config->readBoolEntry("ChatView Transparency Enabled", false); mTransparencyValue = config->readNumEntry("ChatView Transparency Value", 50); mNotifyAway = config->readBoolEntry("Notification Away", false); mTransparencyColor = config->readColorEntry("ChatView Transparency Tint Color", &Qt::white); mChatViewBufferSize = config->readNumEntry("ChatView BufferSize", 250); QColor tmpColor = KGlobalSettings::highlightColor(); mHighlightBackground = config->readColorEntry("Highlight Background Color", &tmpColor); tmpColor = KGlobalSettings::highlightedTextColor(); mHighlightForeground = config->readColorEntry("Highlight Foreground Color", &tmpColor); mHighlightEnabled = config->readBoolEntry("Highlighting Enabled", true); mBgOverride = config->readBoolEntry("ChatView Override Background", true); mInterfacePreference = config->readNumEntry("Interface Preference", 1); tmpColor = KGlobalSettings::textColor(); mTextColor = config->readColorEntry("Text Color", &tmpColor ); tmpColor = KGlobalSettings::baseColor(); mBgColor = config->readColorEntry("Bg Color", &tmpColor ); tmpColor = KGlobalSettings::linkColor(); mLinkColor = config->readColorEntry("Link Color", &tmpColor ); mFontFace = config->readFontEntry("Font Face"); tmpColor = darkGray; mIdleContactColor = config->readColorEntry("Idle Contact Color", &tmpColor); mShowTray = config->readBoolEntry( "Show Systemtray", true); mStyleSheet = config->readEntry("Stylesheet", locate("appdata",QString::fromLatin1("styles/Kopete.xsl") ) ); mStyleContents = fileContents( mStyleSheet ); config->setGroup("Appearance"); // FIXME, Why setgroup again? [mETz] mWindowAppearanceChanged = false; mTransparencyChanged = false; } void KopetePrefs::save() { // kdDebug(14010) << "KopetePrefs::save()" << endl; config->setGroup("Appearance"); config->writeEntry("EmoticonTheme", mIconTheme); config->writeEntry("Use Emoticons", mUseEmoticons); config->writeEntry("ShowOfflineUsers", mShowOffline); config->writeEntry("GreyIdleMetaContacts", mGreyIdle); config->writeEntry("TreeView", mTreeView); config->writeEntry("SortByGroup", mSortByGroup); config->writeEntry("StartDocked", mStartDocked); config->writeEntry("Use Queue", mUseQueue); config->writeEntry("Raise Msg Window", mRaiseMsgWindow); config->writeEntry("Show Events in Chat Window", mShowEvents); config->writeEntry("Trayflash Notification", mTrayflashNotify); config->writeEntry("Balloon Notification", mBalloonNotify); config->writeEntry("Sound Notification If Away", mSoundIfAway); config->writeEntry("Notification Away", mNotifyAway); config->writeEntry("Chatwindow Policy", mChatWindowPolicy); config->writeEntry("ChatView Transparency Enabled", mTransparencyEnabled); config->writeEntry("ChatView Transparency Value", mTransparencyValue); config->writeEntry("ChatView Transparency Tint Color", mTransparencyColor); config->writeEntry("ChatView Override Background", mBgOverride); config->writeEntry("ChatView BufferSize", mChatViewBufferSize); config->writeEntry("Highlight Background Color", mHighlightBackground); config->writeEntry("Highlight Foreground Color", mHighlightForeground); config->writeEntry("Highlighting Enabled", mHighlightEnabled ); config->writeEntry("Font Face", mFontFace); config->writeEntry("Text Color",mTextColor); config->writeEntry("Bg Color", mBgColor); config->writeEntry("Link Color", mLinkColor); config->writeEntry("Idle Contact Color", mIdleContactColor); config->writeEntry("Interface Preference", mInterfacePreference); config->writeEntry("Show Systemtray", mShowTray); config->writeEntry("Stylesheet", mStyleSheet); config->sync(); emit saved(); if(mTransparencyChanged) emit(transparencyChanged()); if(mWindowAppearanceChanged) emit(windowAppearanceChanged()); mWindowAppearanceChanged = false; mTransparencyChanged = false; } void KopetePrefs::setIconTheme(const QString &value) { mIconTheme = value; } void KopetePrefs::setUseEmoticons(bool value) { mUseEmoticons = value; } void KopetePrefs::setShowOffline(bool value) { mShowOffline = value; } void KopetePrefs::setTreeView(bool value) { mTreeView = value; } void KopetePrefs::setSortByGroup(bool value) { mSortByGroup = value; } void KopetePrefs::setGreyIdleMetaContacts(bool value) { mGreyIdle = value; } void KopetePrefs::setStartDocked(bool value) { mStartDocked = value; } void KopetePrefs::setUseQueue(bool value) { mUseQueue = value; } void KopetePrefs::setRaiseMsgWindow(bool value) { mRaiseMsgWindow = value; } void KopetePrefs::setShowEvents(bool value) { mShowEvents = value; } void KopetePrefs::setTrayflashNotify(bool value) { mTrayflashNotify = value; } void KopetePrefs::setBalloonNotify(bool value) { mBalloonNotify = value; } void KopetePrefs::setSoundIfAway(bool value) { mSoundIfAway = value; } void KopetePrefs::setStyleSheet(const QString &value) { if( mStyleSheet != value ) { mStyleSheet = value; mStyleContents = fileContents( mStyleSheet ); emit( messageAppearanceChanged() ); } } void KopetePrefs::setFontFace( const QFont &value ) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mFontFace); mFontFace = value; } void KopetePrefs::setTextColor( const QColor &value ) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mTextColor); mTextColor = value; } void KopetePrefs::setBgColor( const QColor &value ) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mBgColor); mBgColor = value; } void KopetePrefs::setLinkColor( const QColor &value ) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mLinkColor); mLinkColor = value; } void KopetePrefs::setChatWindowPolicy(int value) { mChatWindowPolicy = value; } void KopetePrefs::setInterfacePreference(int value) { mInterfacePreference = value; } void KopetePrefs::setTransparencyEnabled(bool value) { mTransparencyChanged = mTransparencyChanged || !(value == mTransparencyEnabled); mTransparencyEnabled = value; } void KopetePrefs::setTransparencyColor(const QColor &value) { mTransparencyChanged = mTransparencyChanged || !(value == mTransparencyColor); mTransparencyColor = value; } void KopetePrefs::setChatViewBufferSize(const int value) { mChatViewBufferSize = value; } void KopetePrefs::setHighlightBackground(const QColor &value) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mHighlightBackground); mHighlightBackground = value; } void KopetePrefs::setHighlightForeground(const QColor &value) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mHighlightForeground); mHighlightForeground = value; } void KopetePrefs::setHighlightEnabled(bool value) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mHighlightEnabled); mHighlightEnabled = value; } void KopetePrefs::setTransparencyValue(int value) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mTransparencyValue); mTransparencyValue = value; } void KopetePrefs::setBgOverride(bool value) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mBgOverride); mBgOverride = value; } void KopetePrefs::setShowTray(bool value) { mShowTray = value; } void KopetePrefs::setNotifyAway(bool value) { mNotifyAway=value; } QString KopetePrefs::fileContents( const QString &path ) { QString contents; QFile file( path ); if ( file.open( IO_ReadOnly ) ) { QTextStream stream( &file ); contents = stream.read(); file.close(); } return contents; } void KopetePrefs::setIdleContactColor(const QColor &value) { mIdleContactColor = value; } #include "kopeteprefs.moc" // vim: set noet ts=4 sts=4 sw=4:
/* kopeteprefs.cpp - Kopete Preferences Container-Class Copyright (c) 2002 by Stefan Gehn <[email protected]> Kopete (c) 2002-2003 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "kopeteprefs.h" #include <qfile.h> #include <kapplication.h> #include <kglobalsettings.h> #include <kconfig.h> #include <kdebug.h> #include <kstandarddirs.h> KopetePrefs *KopetePrefs::s_prefs = 0L; KopetePrefs *KopetePrefs::prefs() { if( !s_prefs ) s_prefs = new KopetePrefs; return s_prefs; } KopetePrefs::KopetePrefs() : QObject( kapp, "KopetePrefs" ) { config = KGlobal::config(); load(); } void KopetePrefs::load() { // kdDebug(14010) << "KopetePrefs::load()" << endl; config->setGroup("Appearance"); mWindowAppearanceChanged = false; mIconTheme = config->readEntry("EmoticonTheme", defaultTheme()); mUseEmoticons = config->readBoolEntry("Use Emoticons", true); mShowOffline = config->readBoolEntry("ShowOfflineUsers", true); mGreyIdle = config->readBoolEntry("GreyIdleMetaContacts", true); mSortByGroup = config->readBoolEntry("SortByGroup" , true); mTreeView = config->readBoolEntry("TreeView", true); mStartDocked = config->readBoolEntry("StartDocked", false); mUseQueue = config->readBoolEntry("Use Queue", true); mRaiseMsgWindow = config->readBoolEntry("Raise Msg Window", false); mShowEvents = config->readBoolEntry("Show Events in Chat Window", true); mTrayflashNotify = config->readBoolEntry("Trayflash Notification", true); mBalloonNotify = config->readBoolEntry("Balloon Notification", true); mSoundIfAway = config->readBoolEntry("Sound Notification If Away", false); mChatWindowPolicy = config->readNumEntry("Chatwindow Policy", 0); mTransparencyEnabled = config->readBoolEntry("ChatView Transparency Enabled", false); mTransparencyValue = config->readNumEntry("ChatView Transparency Value", 50); mNotifyAway = config->readBoolEntry("Notification Away", false); mTransparencyColor = config->readColorEntry("ChatView Transparency Tint Color", &Qt::white); mChatViewBufferSize = config->readNumEntry("ChatView BufferSize", 250); QColor tmpColor = KGlobalSettings::highlightColor(); mHighlightBackground = config->readColorEntry("Highlight Background Color", &tmpColor); tmpColor = KGlobalSettings::highlightedTextColor(); mHighlightForeground = config->readColorEntry("Highlight Foreground Color", &tmpColor); mHighlightEnabled = config->readBoolEntry("Highlighting Enabled", true); mBgOverride = config->readBoolEntry("ChatView Override Background", true); mInterfacePreference = config->readNumEntry("Interface Preference", 1); tmpColor = KGlobalSettings::textColor(); mTextColor = config->readColorEntry("Text Color", &tmpColor ); tmpColor = KGlobalSettings::baseColor(); mBgColor = config->readColorEntry("Bg Color", &tmpColor ); tmpColor = KGlobalSettings::linkColor(); mLinkColor = config->readColorEntry("Link Color", &tmpColor ); mFontFace = config->readFontEntry("Font Face"); tmpColor = darkGray; mIdleContactColor = config->readColorEntry("Idle Contact Color", &tmpColor); mShowTray = config->readBoolEntry( "Show Systemtray", true); mStyleSheet = config->readEntry("Stylesheet", locate("appdata",QString::fromLatin1("styles/Kopete.xsl") ) ); mStyleContents = fileContents( mStyleSheet ); config->setGroup("Appearance"); // FIXME, Why setgroup again? [mETz] mWindowAppearanceChanged = false; mTransparencyChanged = false; } void KopetePrefs::save() { // kdDebug(14010) << "KopetePrefs::save()" << endl; config->setGroup("Appearance"); config->writeEntry("EmoticonTheme", mIconTheme); config->writeEntry("Use Emoticons", mUseEmoticons); config->writeEntry("ShowOfflineUsers", mShowOffline); config->writeEntry("GreyIdleMetaContacts", mGreyIdle); config->writeEntry("TreeView", mTreeView); config->writeEntry("SortByGroup", mSortByGroup); config->writeEntry("StartDocked", mStartDocked); config->writeEntry("Use Queue", mUseQueue); config->writeEntry("Raise Msg Window", mRaiseMsgWindow); config->writeEntry("Show Events in Chat Window", mShowEvents); config->writeEntry("Trayflash Notification", mTrayflashNotify); config->writeEntry("Balloon Notification", mBalloonNotify); config->writeEntry("Sound Notification If Away", mSoundIfAway); config->writeEntry("Notification Away", mNotifyAway); config->writeEntry("Chatwindow Policy", mChatWindowPolicy); config->writeEntry("ChatView Transparency Enabled", mTransparencyEnabled); config->writeEntry("ChatView Transparency Value", mTransparencyValue); config->writeEntry("ChatView Transparency Tint Color", mTransparencyColor); config->writeEntry("ChatView Override Background", mBgOverride); config->writeEntry("ChatView BufferSize", mChatViewBufferSize); config->writeEntry("Highlight Background Color", mHighlightBackground); config->writeEntry("Highlight Foreground Color", mHighlightForeground); config->writeEntry("Highlighting Enabled", mHighlightEnabled ); config->writeEntry("Font Face", mFontFace); config->writeEntry("Text Color",mTextColor); config->writeEntry("Bg Color", mBgColor); config->writeEntry("Link Color", mLinkColor); config->writeEntry("Idle Contact Color", mIdleContactColor); config->writeEntry("Interface Preference", mInterfacePreference); config->writeEntry("Show Systemtray", mShowTray); config->writeEntry("Stylesheet", mStyleSheet); config->sync(); emit saved(); if(mTransparencyChanged) emit(transparencyChanged()); if(mWindowAppearanceChanged) emit(windowAppearanceChanged()); mWindowAppearanceChanged = false; mTransparencyChanged = false; } void KopetePrefs::setIconTheme(const QString &value) { mIconTheme = value; } void KopetePrefs::setUseEmoticons(bool value) { mUseEmoticons = value; } void KopetePrefs::setShowOffline(bool value) { mShowOffline = value; } void KopetePrefs::setTreeView(bool value) { mTreeView = value; } void KopetePrefs::setSortByGroup(bool value) { mSortByGroup = value; } void KopetePrefs::setGreyIdleMetaContacts(bool value) { mGreyIdle = value; } void KopetePrefs::setStartDocked(bool value) { mStartDocked = value; } void KopetePrefs::setUseQueue(bool value) { mUseQueue = value; } void KopetePrefs::setRaiseMsgWindow(bool value) { mRaiseMsgWindow = value; } void KopetePrefs::setShowEvents(bool value) { mShowEvents = value; } void KopetePrefs::setTrayflashNotify(bool value) { mTrayflashNotify = value; } void KopetePrefs::setBalloonNotify(bool value) { mBalloonNotify = value; } void KopetePrefs::setSoundIfAway(bool value) { mSoundIfAway = value; } void KopetePrefs::setStyleSheet(const QString &value) { if( mStyleSheet != value ) { mStyleSheet = value; mStyleContents = fileContents( mStyleSheet ); emit( messageAppearanceChanged() ); } } void KopetePrefs::setFontFace( const QFont &value ) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mFontFace); mFontFace = value; } void KopetePrefs::setTextColor( const QColor &value ) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mTextColor); mTextColor = value; } void KopetePrefs::setBgColor( const QColor &value ) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mBgColor); mBgColor = value; } void KopetePrefs::setLinkColor( const QColor &value ) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mLinkColor); mLinkColor = value; } void KopetePrefs::setChatWindowPolicy(int value) { mChatWindowPolicy = value; } void KopetePrefs::setInterfacePreference(int value) { mInterfacePreference = value; } void KopetePrefs::setTransparencyEnabled(bool value) { mTransparencyChanged = mTransparencyChanged || !(value == mTransparencyEnabled); mTransparencyEnabled = value; } void KopetePrefs::setTransparencyColor(const QColor &value) { mTransparencyChanged = mTransparencyChanged || !(value == mTransparencyColor); mTransparencyColor = value; } void KopetePrefs::setChatViewBufferSize(const int value) { mChatViewBufferSize = value; } void KopetePrefs::setHighlightBackground(const QColor &value) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mHighlightBackground); mHighlightBackground = value; } void KopetePrefs::setHighlightForeground(const QColor &value) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mHighlightForeground); mHighlightForeground = value; } void KopetePrefs::setHighlightEnabled(bool value) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mHighlightEnabled); mHighlightEnabled = value; } void KopetePrefs::setTransparencyValue(int value) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mTransparencyValue); mTransparencyValue = value; } void KopetePrefs::setBgOverride(bool value) { mWindowAppearanceChanged = mWindowAppearanceChanged || !(value == mBgOverride); mBgOverride = value; } void KopetePrefs::setShowTray(bool value) { mShowTray = value; } void KopetePrefs::setNotifyAway(bool value) { mNotifyAway=value; } QString KopetePrefs::fileContents( const QString &path ) { QString contents; QFile file( path ); if ( file.open( IO_ReadOnly ) ) { QTextStream stream( &file ); contents = stream.read(); file.close(); } return contents; } void KopetePrefs::setIdleContactColor(const QColor &value) { mIdleContactColor = value; } #include "kopeteprefs.moc" // vim: set noet ts=4 sts=4 sw=4:
Fix warning
Fix warning svn path=/trunk/kdenetwork/kopete/; revision=231963
C++
lgpl-2.1
josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136
3c38aab8bbcb8dbc80081616e74f64b9a47edd25
test/SemaCXX/constructor-initializer.cpp
test/SemaCXX/constructor-initializer.cpp
// RUN: clang-cc -Wreorder -fsyntax-only -verify %s class A { int m; A() : A::m(17) { } // expected-error {{member initializer 'm' does not name a non-static data member or base class}} A(int); }; class B : public A { public: B() : A(), m(1), n(3.14) { } private: int m; float n; }; class C : public virtual B { public: C() : B() { } }; class D : public C { public: D() : B(), C() { } }; class E : public D, public B { public: E() : B(), D() { } // expected-error{{base class initializer 'B' names both a direct base class and an inherited virtual base class}} }; typedef int INT; class F : public B { public: int B; F() : B(17), m(17), // expected-error{{member initializer 'm' does not name a non-static data member or base class}} INT(17) // expected-error{{constructor initializer 'INT' (aka 'int') does not name a class}} { } }; class G : A { G() : A(10); // expected-error{{expected '{'}} }; void f() : a(242) { } // expected-error{{only constructors take base initializers}} class H : A { H(); }; H::H() : A(10) { } class X {}; class Y {}; struct S : Y, virtual X { S (); }; struct Z : S { Z() : X(), S(), E() {} // expected-error {{type 'class E' is not a direct or virtual base of 'Z'}} }; class U { union { int a; char* p; }; union { int b; double d; }; U() : a(1), p(0), d(1.0) {} // expected-error {{multiple initializations given for non-static member 'p'}} \ // expected-note {{previous initialization is here}} }; struct V {}; struct Base {}; struct Base1 {}; struct Derived : Base, Base1, virtual V { Derived (); }; struct Current : Derived { int Derived; Current() : Derived(1), ::Derived(), // expected-warning {{member 'Derived' will be initialized after}} \ // expected-note {{base '::Derived'}} \ // expected-warning {{base class '::Derived' will be initialized after}} ::Derived::Base(), // expected-error {{type '::Derived::Base' is not a direct or virtual base of 'Current'}} Derived::Base1(), // expected-error {{type 'Derived::Base1' is not a direct or virtual base of 'Current'}} Derived::V(), // expected-note {{base 'Derived::V'}} ::NonExisting(), // expected-error {{member initializer 'NonExisting' does not name a non-static data member or}} INT::NonExisting() {} // expected-error {{expected a class or namespace}} \ // expected-error {{member initializer 'NonExisting' does not name a non-static data member or}} }; // FIXME. This is bad message! struct M { // expected-note {{candidate function}} \ // expected-note {{candidate function}} M(int i, int j); // expected-note {{candidate function}} \ // // expected-note {{candidate function}} }; struct N : M { N() : M(1), // expected-error {{no matching constructor for initialization of 'M'}} m1(100) { } // expected-error {{no matching constructor for initialization of 'm1'}} M m1; }; struct P : M { // expected-error {{default constructor for 'struct M' is missing in initialization of base class}} P() { } M m; // expected-error {{default constructor for 'struct M' is missing in initialization of mamber}} }; struct Q { Q() : f1(1,2), // expected-error {{Too many arguments for member initializer 'f1'}} pf(0.0) { } // expected-error {{incompatible type passing 'double', expected 'float *'}} float f1; float *pf; };
// RUN: clang-cc -Wreorder -fsyntax-only -verify %s class A { int m; A() : A::m(17) { } // expected-error {{member initializer 'm' does not name a non-static data member or base class}} A(int); }; class B : public A { public: B() : A(), m(1), n(3.14) { } private: int m; float n; }; class C : public virtual B { public: C() : B() { } }; class D : public C { public: D() : B(), C() { } }; class E : public D, public B { public: E() : B(), D() { } // expected-error{{base class initializer 'B' names both a direct base class and an inherited virtual base class}} }; typedef int INT; class F : public B { public: int B; F() : B(17), m(17), // expected-error{{member initializer 'm' does not name a non-static data member or base class}} INT(17) // expected-error{{constructor initializer 'INT' (aka 'int') does not name a class}} { } }; class G : A { G() : A(10); // expected-error{{expected '{'}} }; void f() : a(242) { } // expected-error{{only constructors take base initializers}} class H : A { H(); }; H::H() : A(10) { } class X {}; class Y {}; struct S : Y, virtual X { S (); }; struct Z : S { Z() : X(), S(), E() {} // expected-error {{type 'class E' is not a direct or virtual base of 'Z'}} }; class U { union { int a; char* p; }; union { int b; double d; }; U() : a(1), p(0), d(1.0) {} // expected-error {{multiple initializations given for non-static member 'p'}} \ // expected-note {{previous initialization is here}} }; struct V {}; struct Base {}; struct Base1 {}; struct Derived : Base, Base1, virtual V { Derived (); }; struct Current : Derived { int Derived; Current() : Derived(1), ::Derived(), // expected-warning {{member 'Derived' will be initialized after}} \ // expected-note {{base '::Derived'}} \ // expected-warning {{base class '::Derived' will be initialized after}} ::Derived::Base(), // expected-error {{type '::Derived::Base' is not a direct or virtual base of 'Current'}} Derived::Base1(), // expected-error {{type 'Derived::Base1' is not a direct or virtual base of 'Current'}} Derived::V(), // expected-note {{base 'Derived::V'}} ::NonExisting(), // expected-error {{member initializer 'NonExisting' does not name a non-static data member or}} INT::NonExisting() {} // expected-error {{expected a class or namespace}} \ // expected-error {{member initializer 'NonExisting' does not name a non-static data member or}} }; // FIXME. This is bad message! struct M { // expected-note {{candidate function}} \ // expected-note {{candidate function}} M(int i, int j); // expected-note {{candidate function}} \ // // expected-note {{candidate function}} }; struct N : M { N() : M(1), // expected-error {{no matching constructor for initialization of 'M'}} m1(100) { } // expected-error {{no matching constructor for initialization of 'm1'}} M m1; }; struct P : M { // expected-error {{default constructor for 'struct M' is missing in initialization of base class}} P() { } M m; // expected-error {{default constructor for 'struct M' is missing in initialization of member}} }; struct Q { Q() : f1(1,2), // expected-error {{Too many arguments for member initializer 'f1'}} pf(0.0) { } // expected-error {{incompatible type passing 'double', expected 'float *'}} float f1; float *pf; };
fix test (broken in r77224)
fix test (broken in r77224) git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@77241 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang
1c55c7be31ad845038b5c3f999299e20185f9cf9
wowfoot-cpp/handlers/skillShared/skillShared.cpp
wowfoot-cpp/handlers/skillShared/skillShared.cpp
#include "skillShared.h" #include "lockEnums.h" #include <string.h> #include <stdio.h> #include "win32.h" // returns NULL on parse error. const SkillLine* parseSkillId(ostream& os, const char* urlPart) { // format: <category>.<skill> int categoryId, skillId; uint len; int res = sscanf(urlPart, "%i.%i%n", &categoryId, &skillId, &len); EASSERT(res == 2); //printf("category: %i. skill: %i. len: %i\n", categoryId, skillId, len); EASSERT(len == strlen(urlPart)); const SkillLine* sl = gSkillLines.find(skillId); if(!sl) { os << "Skill not found.\n"; return NULL; } if(sl->category != categoryId) { os << "Skill not found in category.\n"; return NULL; } return sl; } // returns 0 if no lock type. int lockTypeFromSkill(int skillId) { switch(skillId) { case 633: return LOCKTYPE_PICKLOCK; case 182: return LOCKTYPE_HERBALISM; case 186: return LOCKTYPE_MINING; case 356: return LOCKTYPE_FISHING; default: return 0; //default: FAIL("skill is not associated with locks."); } }
#include "skillShared.h" #include "lockEnums.h" #include <string.h> #include <stdio.h> #include "win32.h" // returns NULL on parse error. const SkillLine* parseSkillId(ostream& os, const char* urlPart) { // format: <category>.<skill> int categoryId, skillId; uint len; int res = sscanf(urlPart, "%i.%i%n", &categoryId, &skillId, &len); if(res != 2) { res = sscanf(urlPart, "%i%n", &skillId, &len); EASSERT(res == 1); categoryId = -1; } //printf("category: %i. skill: %i. len: %i\n", categoryId, skillId, len); EASSERT(len == strlen(urlPart)); const SkillLine* sl = gSkillLines.find(skillId); if(!sl) { os << "Skill not found.\n"; return NULL; } if(sl->category != categoryId && categoryId != -1) { os << "Skill not found in category.\n"; return NULL; } return sl; } // returns 0 if no lock type. int lockTypeFromSkill(int skillId) { switch(skillId) { case 633: return LOCKTYPE_PICKLOCK; case 182: return LOCKTYPE_HERBALISM; case 186: return LOCKTYPE_MINING; case 356: return LOCKTYPE_FISHING; default: return 0; //default: FAIL("skill is not associated with locks."); } }
allow skillId without categoryId.
parseSkillId: allow skillId without categoryId.
C++
agpl-3.0
Masken3/wowfoot,Masken3/wowfoot,Masken3/wowfoot,Masken3/wowfoot,Masken3/wowfoot,Masken3/wowfoot
bc496094806d37b2d3a79ae38880f1e079a97631
libcaf_core/caf/span.hpp
libcaf_core/caf/span.hpp
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2019 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <array> #include <type_traits> #include "caf/byte.hpp" #include "caf/detail/type_traits.hpp" namespace caf { /// A C++11/14 drop-in replacement for C++20's `std::span` without support for /// static extents. template <class T> class span { public: // -- member types ----------------------------------------------------------- using element_type = T; using value_type = typename std::remove_cv<T>::type; using index_type = size_t; using difference_type = ptrdiff_t; using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = T&; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; // -- constructors, destructors, and assignment operators -------------------- constexpr span() noexcept : begin_(nullptr), size_(0) { // nop } constexpr span(pointer ptr, size_t size) : begin_(ptr), size_(size) { // nop } constexpr span(pointer first, pointer last) : begin_(first), size_(static_cast<size_t>(last - first)) { // nop } template <size_t Size> constexpr span(element_type (&arr)[Size]) noexcept : begin_(arr), size_(Size) { // nop } template <class C, class E = detail::enable_if_t<detail::has_data_member<C>::value>> span(C& xs) noexcept : begin_(xs.data()), size_(xs.size()) { // nop } constexpr span(const span&) noexcept = default; span& operator=(const span&) noexcept = default; // -- iterators -------------------------------------------------------------- constexpr iterator begin() const noexcept { return begin_; } constexpr const_iterator cbegin() const noexcept { return begin_; } constexpr iterator end() const noexcept { return begin() + size_; } constexpr const_iterator cend() const noexcept { return cbegin() + size_; } constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; } constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator{end()}; } constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; } constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator{begin()}; } // -- element access --------------------------------------------------------- constexpr reference operator[](size_t index) const noexcept { return begin_[index]; } constexpr reference front() const noexcept { return *begin_; } constexpr reference back() const noexcept { return (*this)[size_ - 1]; } // -- properties ------------------------------------------------------------- constexpr size_t size() const noexcept { return size_; } constexpr size_t size_bytes() const noexcept { return size_ * sizeof(element_type); } constexpr bool empty() const noexcept { return size_ == 0; } constexpr pointer data() const noexcept { return begin_; } // -- subviews --------------------------------------------------------------- constexpr span subspan(size_t offset, size_t num_bytes) const { return {begin_ + offset, num_bytes}; } constexpr span first(size_t num_bytes) const { return {begin_, num_bytes}; } constexpr span last(size_t num_bytes) const { return subspan(size_ - num_bytes, num_bytes); } private: // -- member variables ------------------------------------------------------- /// Points to the first element in the contiguous memory block. pointer begin_; /// Stores the number of elements in the contiguous memory block. size_t size_; }; template <class T> auto begin(const span<T>& xs) -> decltype(xs.begin()) { return xs.begin(); } template <class T> auto cbegin(const span<T>& xs) -> decltype(xs.cbegin()) { return xs.cbegin(); } template <class T> auto end(const span<T>& xs) -> decltype(xs.end()) { return xs.end(); } template <class T> auto cend(const span<T>& xs) -> decltype(xs.cend()) { return xs.cend(); } template <class T> span<const byte> as_bytes(span<T> xs) { return {reinterpret_cast<const byte*>(xs.data()), xs.size_bytes()}; } template <class T> span<byte> as_writable_bytes(span<T> xs) { return {reinterpret_cast<byte*>(xs.data()), xs.size_bytes()}; } /// Convenience function to make using `caf::span` more convenient without the /// deduction guides. template <class T> auto make_span(T& xs) -> span<detail::remove_reference_t<decltype(xs[0])>> { return {xs.data(), xs.size()}; } /// Convenience function to make using `caf::span` more convenient without the /// deduction guides. template <class T> span<T> make_span(T* first, size_t size) { return {first, size}; } /// Convenience function to make using `caf::span` more convenient without the /// deduction guides. template <class T> span<T> make_span(T* first, T* last) { return {first, last}; } } // namespace caf
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2019 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <array> #include <type_traits> #include "caf/byte.hpp" #include "caf/detail/type_traits.hpp" namespace caf { /// A C++11/14 drop-in replacement for C++20's `std::span` without support for /// static extents. template <class T> class span { public: // -- member types ----------------------------------------------------------- using element_type = T; using value_type = typename std::remove_cv<T>::type; using index_type = size_t; using difference_type = ptrdiff_t; using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = T&; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; // -- constructors, destructors, and assignment operators -------------------- constexpr span() noexcept : begin_(nullptr), size_(0) { // nop } constexpr span(pointer ptr, size_t size) : begin_(ptr), size_(size) { // nop } constexpr span(pointer first, pointer last) : begin_(first), size_(static_cast<size_t>(last - first)) { // nop } template <size_t Size> constexpr span(element_type (&arr)[Size]) noexcept : begin_(arr), size_(Size) { // nop } template <class C, class E = detail::enable_if_t<detail::has_data_member<C>::value>> span(C& xs) noexcept : begin_(xs.data()), size_(xs.size()) { // nop } template <class C, class E = detail::enable_if_t<detail::has_data_member<C>::value>> span(const C& xs) noexcept : begin_(xs.data()), size_(xs.size()) { // nop } constexpr span(const span&) noexcept = default; span& operator=(const span&) noexcept = default; // -- iterators -------------------------------------------------------------- constexpr iterator begin() const noexcept { return begin_; } constexpr const_iterator cbegin() const noexcept { return begin_; } constexpr iterator end() const noexcept { return begin() + size_; } constexpr const_iterator cend() const noexcept { return cbegin() + size_; } constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; } constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator{end()}; } constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; } constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator{begin()}; } // -- element access --------------------------------------------------------- constexpr reference operator[](size_t index) const noexcept { return begin_[index]; } constexpr reference front() const noexcept { return *begin_; } constexpr reference back() const noexcept { return (*this)[size_ - 1]; } // -- properties ------------------------------------------------------------- constexpr size_t size() const noexcept { return size_; } constexpr size_t size_bytes() const noexcept { return size_ * sizeof(element_type); } constexpr bool empty() const noexcept { return size_ == 0; } constexpr pointer data() const noexcept { return begin_; } // -- subviews --------------------------------------------------------------- constexpr span subspan(size_t offset, size_t num_bytes) const { return {begin_ + offset, num_bytes}; } constexpr span first(size_t num_bytes) const { return {begin_, num_bytes}; } constexpr span last(size_t num_bytes) const { return subspan(size_ - num_bytes, num_bytes); } private: // -- member variables ------------------------------------------------------- /// Points to the first element in the contiguous memory block. pointer begin_; /// Stores the number of elements in the contiguous memory block. size_t size_; }; template <class T> auto begin(const span<T>& xs) -> decltype(xs.begin()) { return xs.begin(); } template <class T> auto cbegin(const span<T>& xs) -> decltype(xs.cbegin()) { return xs.cbegin(); } template <class T> auto end(const span<T>& xs) -> decltype(xs.end()) { return xs.end(); } template <class T> auto cend(const span<T>& xs) -> decltype(xs.cend()) { return xs.cend(); } template <class T> span<const byte> as_bytes(span<T> xs) { return {reinterpret_cast<const byte*>(xs.data()), xs.size_bytes()}; } template <class T> span<byte> as_writable_bytes(span<T> xs) { return {reinterpret_cast<byte*>(xs.data()), xs.size_bytes()}; } /// Convenience function to make using `caf::span` more convenient without the /// deduction guides. template <class T> auto make_span(T& xs) -> span<detail::remove_reference_t<decltype(xs[0])>> { return {xs.data(), xs.size()}; } /// Convenience function to make using `caf::span` more convenient without the /// deduction guides. template <class T> span<T> make_span(T* first, size_t size) { return {first, size}; } /// Convenience function to make using `caf::span` more convenient without the /// deduction guides. template <class T> span<T> make_span(T* first, T* last) { return {first, last}; } } // namespace caf
Add missing constructor
Add missing constructor
C++
bsd-3-clause
DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework
597cc27a50f7b59a9ce63c910e45a234d55cff85
src/bp_control.cxx
src/bp_control.cxx
/* * Handler for control messages. * * author: Max Kellermann <[email protected]> */ #include "bp_control.hxx" #include "bp_stats.hxx" #include "control_server.hxx" #include "control_local.hxx" #include "udp-distribute.h" #include "bp_instance.hxx" #include "tcache.hxx" #include "translate_request.hxx" #include "tpool.h" #include "beng-proxy/translation.h" #include "pool.hxx" #include "net/SocketAddress.hxx" #include "util/ConstBuffer.hxx" #include <daemon/log.h> #include <glib.h> #include <assert.h> #include <arpa/inet.h> #include <string.h> static bool apply_translation_packet(TranslateRequest *request, enum beng_translation_command command, const char *payload, size_t payload_length) { switch (command) { case TRANSLATE_URI: request->uri = payload; break; case TRANSLATE_SESSION: request->session = { payload, payload_length }; break; /* XXX case TRANSLATE_LOCAL_ADDRESS: request->local_address = payload; break; */ case TRANSLATE_REMOTE_HOST: request->remote_host = payload; break; case TRANSLATE_HOST: request->host = payload; break; case TRANSLATE_LANGUAGE: request->accept_language = payload; break; case TRANSLATE_USER_AGENT: request->user_agent = payload; break; case TRANSLATE_UA_CLASS: request->ua_class = payload; break; case TRANSLATE_QUERY_STRING: request->query_string = payload; break; default: /* unsupported */ return false; } return true; } static unsigned decode_translation_packets(struct pool *pool, TranslateRequest *request, uint16_t *cmds, unsigned max_cmds, const void *data, size_t length, const char **site_r) { *site_r = NULL; unsigned num_cmds = 0; if (length % 4 != 0) /* must be padded */ return 0; while (length > 0) { const beng_translation_header *header = (const beng_translation_header *)data; if (length < sizeof(*header)) return 0; size_t payload_length = GUINT16_FROM_BE(header->length); beng_translation_command command = beng_translation_command(GUINT16_FROM_BE(header->command)); data = header + 1; length -= sizeof(*header); if (length < payload_length) return 0; char *payload = payload_length > 0 ? p_strndup(pool, (const char *)data, payload_length) : NULL; if (command == TRANSLATE_SITE) *site_r = payload; else if (apply_translation_packet(request, command, payload, payload_length)) { if (num_cmds >= max_cmds) return 0; cmds[num_cmds++] = (uint16_t)command; } else return 0; payload_length = ((payload_length + 3) | 3) - 3; /* apply padding */ data = (const char *)data + payload_length; length -= payload_length; } return num_cmds; } static void control_tcache_invalidate(struct instance *instance, const void *payload, size_t payload_length) { (void)instance; const AutoRewindPool auto_rewind(*tpool); TranslateRequest request; memset(&request, 0, sizeof(request)); const char *site; uint16_t cmds[32]; unsigned num_cmds = decode_translation_packets(tpool, &request, cmds, G_N_ELEMENTS(cmds), payload, payload_length, &site); if (num_cmds == 0 && site == NULL) { daemon_log(2, "malformed TCACHE_INVALIDATE control packet\n"); return; } translate_cache_invalidate(*instance->translate_cache, request, ConstBuffer<uint16_t>(cmds, num_cmds), site); } static void query_stats(struct instance *instance, struct control_server *server, SocketAddress address) { if (address.GetSize() == 0) /* TODO: this packet was forwarded by the master process, and has no source address; however, the master process must get statistics from all worker processes (even those that have exited already) */ return; struct beng_control_stats stats; bp_get_stats(instance, &stats); const AutoRewindPool auto_rewind(*tpool); GError *error = NULL; if (!control_server_reply(server, tpool, address, CONTROL_STATS, &stats, sizeof(stats), &error)) { daemon_log(3, "%s\n", error->message); g_error_free(error); } } static void handle_control_packet(struct instance *instance, struct control_server *server, enum beng_control_command command, const void *payload, size_t payload_length, SocketAddress address) { daemon_log(5, "control command=%d payload_length=%zu\n", command, payload_length); switch (command) { case CONTROL_NOP: /* duh! */ break; case CONTROL_TCACHE_INVALIDATE: control_tcache_invalidate(instance, payload, payload_length); break; case CONTROL_DUMP_POOLS: pool_dump_tree(instance->pool); break; case CONTROL_ENABLE_NODE: case CONTROL_FADE_NODE: case CONTROL_NODE_STATUS: /* only for beng-lb */ break; case CONTROL_STATS: query_stats(instance, server, address); break; case CONTROL_VERBOSE: if (payload_length == 1) daemon_log_config.verbose = *(const uint8_t *)payload; break; case CONTROL_FADE_CHILDREN: instance->FadeChildren(); break; } } static void global_control_packet(enum beng_control_command command, const void *payload, size_t payload_length, SocketAddress address, void *ctx) { struct instance *instance = (struct instance *)ctx; handle_control_packet(instance, instance->control_server, command, payload, payload_length, address); } static void global_control_error(GError *error, gcc_unused void *ctx) { daemon_log(2, "%s\n", error->message); g_error_free(error); } static struct udp_distribute *global_udp_distribute; static bool global_control_raw(const void *data, size_t length, gcc_unused SocketAddress address, gcc_unused int uid, gcc_unused void *ctx) { /* forward the packet to all worker processes */ udp_distribute_packet(global_udp_distribute, data, length); return true; } static const struct control_handler global_control_handler = { .raw = global_control_raw, .packet = global_control_packet, .error = global_control_error, }; bool global_control_handler_init(struct pool *pool, struct instance *instance) { if (instance->config.control_listen == NULL) return true; struct in_addr group_buffer; const struct in_addr *group = NULL; if (instance->config.multicast_group != NULL) { group_buffer.s_addr = inet_addr(instance->config.multicast_group); group = &group_buffer; } GError *error = NULL; instance->control_server = control_server_new_port(instance->config.control_listen, 5478, group, &global_control_handler, instance, &error); if (instance->control_server == NULL) { daemon_log(1, "%s\n", error->message); g_error_free(error); return false; } global_udp_distribute = udp_distribute_new(pool); return true; } void global_control_handler_deinit(struct instance *instance) { if (global_udp_distribute != NULL) udp_distribute_free(global_udp_distribute); if (instance->control_server != NULL) control_server_free(instance->control_server); } void global_control_handler_enable(struct instance &instance) { if (instance.control_server != nullptr) control_server_enable(instance.control_server); } void global_control_handler_disable(struct instance &instance) { if (instance.control_server != nullptr) control_server_disable(instance.control_server); } int global_control_handler_add_fd(gcc_unused struct instance *instance) { assert(instance->control_server != NULL); assert(global_udp_distribute != NULL); return udp_distribute_add(global_udp_distribute); } void global_control_handler_set_fd(struct instance *instance, int fd) { assert(instance->control_server != NULL); assert(global_udp_distribute != NULL); udp_distribute_clear(global_udp_distribute); control_server_set_fd(instance->control_server, fd); } /* * local (implicit) control channel */ static void local_control_packet(enum beng_control_command command, const void *payload, size_t payload_length, SocketAddress address, void *ctx) { struct instance *instance = (struct instance *)ctx; handle_control_packet(instance, control_local_get(instance->local_control_server), command, payload, payload_length, address); } static const struct control_handler local_control_handler = { nullptr, .packet = local_control_packet, .error = global_control_error, }; void local_control_handler_init(struct instance *instance) { instance->local_control_server = control_local_new("beng_control:pid=", &local_control_handler, instance); } void local_control_handler_deinit(struct instance *instance) { control_local_free(instance->local_control_server); } bool local_control_handler_open(struct instance *instance) { GError *error = NULL; if (!control_local_open(instance->local_control_server, &error)) { daemon_log(1, "%s\n", error->message); g_error_free(error); return false; } return true; }
/* * Handler for control messages. * * author: Max Kellermann <[email protected]> */ #include "bp_control.hxx" #include "bp_stats.hxx" #include "control_server.hxx" #include "control_local.hxx" #include "udp-distribute.h" #include "bp_instance.hxx" #include "tcache.hxx" #include "translate_request.hxx" #include "tpool.h" #include "beng-proxy/translation.h" #include "pool.hxx" #include "net/SocketAddress.hxx" #include "util/ConstBuffer.hxx" #include <daemon/log.h> #include <glib.h> #include <assert.h> #include <arpa/inet.h> #include <string.h> static bool apply_translation_packet(TranslateRequest *request, enum beng_translation_command command, const char *payload, size_t payload_length) { switch (command) { case TRANSLATE_URI: request->uri = payload; break; case TRANSLATE_SESSION: request->session = { payload, payload_length }; break; /* XXX case TRANSLATE_LOCAL_ADDRESS: request->local_address = payload; break; */ case TRANSLATE_REMOTE_HOST: request->remote_host = payload; break; case TRANSLATE_HOST: request->host = payload; break; case TRANSLATE_LANGUAGE: request->accept_language = payload; break; case TRANSLATE_USER_AGENT: request->user_agent = payload; break; case TRANSLATE_UA_CLASS: request->ua_class = payload; break; case TRANSLATE_QUERY_STRING: request->query_string = payload; break; default: /* unsupported */ return false; } return true; } static unsigned decode_translation_packets(struct pool *pool, TranslateRequest *request, uint16_t *cmds, unsigned max_cmds, const void *data, size_t length, const char **site_r) { *site_r = NULL; unsigned num_cmds = 0; if (length % 4 != 0) /* must be padded */ return 0; while (length > 0) { const beng_translation_header *header = (const beng_translation_header *)data; if (length < sizeof(*header)) return 0; size_t payload_length = GUINT16_FROM_BE(header->length); beng_translation_command command = beng_translation_command(GUINT16_FROM_BE(header->command)); data = header + 1; length -= sizeof(*header); if (length < payload_length) return 0; char *payload = payload_length > 0 ? p_strndup(pool, (const char *)data, payload_length) : NULL; if (command == TRANSLATE_SITE) *site_r = payload; else if (apply_translation_packet(request, command, payload, payload_length)) { if (num_cmds >= max_cmds) return 0; cmds[num_cmds++] = (uint16_t)command; } else return 0; payload_length = ((payload_length + 3) | 3) - 3; /* apply padding */ data = (const char *)data + payload_length; length -= payload_length; } return num_cmds; } static void control_tcache_invalidate(struct instance *instance, const void *payload, size_t payload_length) { (void)instance; const AutoRewindPool auto_rewind(*tpool); TranslateRequest request; request.Clear(); const char *site; uint16_t cmds[32]; unsigned num_cmds = decode_translation_packets(tpool, &request, cmds, G_N_ELEMENTS(cmds), payload, payload_length, &site); if (num_cmds == 0 && site == NULL) { daemon_log(2, "malformed TCACHE_INVALIDATE control packet\n"); return; } translate_cache_invalidate(*instance->translate_cache, request, ConstBuffer<uint16_t>(cmds, num_cmds), site); } static void query_stats(struct instance *instance, struct control_server *server, SocketAddress address) { if (address.GetSize() == 0) /* TODO: this packet was forwarded by the master process, and has no source address; however, the master process must get statistics from all worker processes (even those that have exited already) */ return; struct beng_control_stats stats; bp_get_stats(instance, &stats); const AutoRewindPool auto_rewind(*tpool); GError *error = NULL; if (!control_server_reply(server, tpool, address, CONTROL_STATS, &stats, sizeof(stats), &error)) { daemon_log(3, "%s\n", error->message); g_error_free(error); } } static void handle_control_packet(struct instance *instance, struct control_server *server, enum beng_control_command command, const void *payload, size_t payload_length, SocketAddress address) { daemon_log(5, "control command=%d payload_length=%zu\n", command, payload_length); switch (command) { case CONTROL_NOP: /* duh! */ break; case CONTROL_TCACHE_INVALIDATE: control_tcache_invalidate(instance, payload, payload_length); break; case CONTROL_DUMP_POOLS: pool_dump_tree(instance->pool); break; case CONTROL_ENABLE_NODE: case CONTROL_FADE_NODE: case CONTROL_NODE_STATUS: /* only for beng-lb */ break; case CONTROL_STATS: query_stats(instance, server, address); break; case CONTROL_VERBOSE: if (payload_length == 1) daemon_log_config.verbose = *(const uint8_t *)payload; break; case CONTROL_FADE_CHILDREN: instance->FadeChildren(); break; } } static void global_control_packet(enum beng_control_command command, const void *payload, size_t payload_length, SocketAddress address, void *ctx) { struct instance *instance = (struct instance *)ctx; handle_control_packet(instance, instance->control_server, command, payload, payload_length, address); } static void global_control_error(GError *error, gcc_unused void *ctx) { daemon_log(2, "%s\n", error->message); g_error_free(error); } static struct udp_distribute *global_udp_distribute; static bool global_control_raw(const void *data, size_t length, gcc_unused SocketAddress address, gcc_unused int uid, gcc_unused void *ctx) { /* forward the packet to all worker processes */ udp_distribute_packet(global_udp_distribute, data, length); return true; } static const struct control_handler global_control_handler = { .raw = global_control_raw, .packet = global_control_packet, .error = global_control_error, }; bool global_control_handler_init(struct pool *pool, struct instance *instance) { if (instance->config.control_listen == NULL) return true; struct in_addr group_buffer; const struct in_addr *group = NULL; if (instance->config.multicast_group != NULL) { group_buffer.s_addr = inet_addr(instance->config.multicast_group); group = &group_buffer; } GError *error = NULL; instance->control_server = control_server_new_port(instance->config.control_listen, 5478, group, &global_control_handler, instance, &error); if (instance->control_server == NULL) { daemon_log(1, "%s\n", error->message); g_error_free(error); return false; } global_udp_distribute = udp_distribute_new(pool); return true; } void global_control_handler_deinit(struct instance *instance) { if (global_udp_distribute != NULL) udp_distribute_free(global_udp_distribute); if (instance->control_server != NULL) control_server_free(instance->control_server); } void global_control_handler_enable(struct instance &instance) { if (instance.control_server != nullptr) control_server_enable(instance.control_server); } void global_control_handler_disable(struct instance &instance) { if (instance.control_server != nullptr) control_server_disable(instance.control_server); } int global_control_handler_add_fd(gcc_unused struct instance *instance) { assert(instance->control_server != NULL); assert(global_udp_distribute != NULL); return udp_distribute_add(global_udp_distribute); } void global_control_handler_set_fd(struct instance *instance, int fd) { assert(instance->control_server != NULL); assert(global_udp_distribute != NULL); udp_distribute_clear(global_udp_distribute); control_server_set_fd(instance->control_server, fd); } /* * local (implicit) control channel */ static void local_control_packet(enum beng_control_command command, const void *payload, size_t payload_length, SocketAddress address, void *ctx) { struct instance *instance = (struct instance *)ctx; handle_control_packet(instance, control_local_get(instance->local_control_server), command, payload, payload_length, address); } static const struct control_handler local_control_handler = { nullptr, .packet = local_control_packet, .error = global_control_error, }; void local_control_handler_init(struct instance *instance) { instance->local_control_server = control_local_new("beng_control:pid=", &local_control_handler, instance); } void local_control_handler_deinit(struct instance *instance) { control_local_free(instance->local_control_server); } bool local_control_handler_open(struct instance *instance) { GError *error = NULL; if (!control_local_open(instance->local_control_server, &error)) { daemon_log(1, "%s\n", error->message); g_error_free(error); return false; } return true; }
use TranslateRequest::Clear() instead of memset()
bp_control: use TranslateRequest::Clear() instead of memset()
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
a85464242f3501c80f5e1a200969e539b6f528c3
ds9/backend.cpp
ds9/backend.cpp
/* This file is part of the KDE project. Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include "backend.h" #include "backendnode.h" #include "audiooutput.h" #include "effect.h" #include "mediaobject.h" #include "videowidget.h" #include "volumeeffect.h" //windows specific (DirectX Media Object) #include <dmo.h> #include <QtCore/QSettings> #include <QtCore/QSet> #include <QtCore/QVariant> #include <QtCore/QtPlugin> QT_BEGIN_NAMESPACE Q_EXPORT_PLUGIN2(phonon_ds9, Phonon::DS9::Backend); namespace Phonon { namespace DS9 { bool Backend::AudioMoniker::operator==(const AudioMoniker &other) { return other->IsEqual(*this) == S_OK; } Backend::Backend(QObject *parent, const QVariantList &) : QObject(parent) { ::CoInitialize(0); //registering meta types qRegisterMetaType<HRESULT>("HRESULT"); qRegisterMetaType<QSet<Filter> >("QSet<Filter>"); qRegisterMetaType<Graph>("Graph"); } Backend::~Backend() { m_audioOutputs.clear(); m_audioEffects.clear(); ::CoUninitialize(); } QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args) { switch (c) { case MediaObjectClass: return new MediaObject(parent); case AudioOutputClass: return new AudioOutput(this, parent); #ifndef QT_NO_PHONON_EFFECT case EffectClass: return new Effect(m_audioEffects[ args[0].toInt() ], parent); #endif //QT_NO_PHONON_EFFECT #ifndef QT_NO_PHONON_VIDEO case VideoWidgetClass: return new VideoWidget(qobject_cast<QWidget *>(parent)); #endif //QT_NO_PHONON_VIDEO #ifndef QT_NO_PHONON_VOLUMEFADEREFFECT case VolumeFaderEffectClass: return new VolumeEffect(parent); #endif //QT_NO_PHONON_VOLUMEFADEREFFECT default: return 0; } } bool Backend::supportsVideo() const { #ifndef QT_NO_PHONON_VIDEO return true; #else return false; #endif //QT_NO_PHONON_VIDEO } QStringList Backend::availableMimeTypes() const { QSet<QString> ret; const QStringList locations = QStringList() << QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\mplayer2\\mime types") << QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\wmplayer\\mime types"); Q_FOREACH(QString s, locations) { QSettings settings(s, QSettings::NativeFormat); ret += settings.childGroups().replaceInStrings("\\", "/").toSet(); } QStringList list = ret.toList(); qSort(list); return list; } Filter Backend::getAudioOutputFilter(int index) const { Filter ret; if (index >= 0 && index < m_audioOutputs.count()) { m_audioOutputs.at(index)->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast<void**>(&ret)); } else { //just return the default audio renderer (not directsound) ret = Filter(CLSID_AudioRender, IID_IBaseFilter); } return ret; } QList<int> Backend::objectDescriptionIndexes(Phonon::ObjectDescriptionType type) const { QList<int> ret; switch(type) { case Phonon::AudioOutputDeviceType: { #ifdef Q_OS_WINCE ret << 0; // only one audio device with index 0 #else ComPointer<ICreateDevEnum> devEnum(CLSID_SystemDeviceEnum, IID_ICreateDevEnum); if (!devEnum) { return ret; //it is impossible to enumerate the devices } ComPointer<IEnumMoniker> enumMon; HRESULT hr = devEnum->CreateClassEnumerator(CLSID_AudioRendererCategory, enumMon.pparam(), 0); if (FAILED(hr)) { break; } AudioMoniker mon; //let's reorder the devices so that directshound appears first int nbds = 0; //number of directsound devices while (S_OK == enumMon->Next(1, mon.pparam(), 0)) { LPOLESTR str = 0; mon->GetDisplayName(0,0,&str); const QString name = QString::fromUtf16((unsigned short*)str); ComPointer<IMalloc> alloc; ::CoGetMalloc(1, alloc.pparam()); alloc->Free(str); int insert_pos = 0; if (!m_audioOutputs.contains(mon)) { insert_pos = m_audioOutputs.count(); m_audioOutputs.append(mon); } else { insert_pos = m_audioOutputs.indexOf(mon); } if (name.contains(QLatin1String("DirectSound"))) { ret.insert(nbds++, insert_pos); } else { ret.append(insert_pos); } } #endif break; } #ifndef QT_NO_PHONON_EFFECT case Phonon::EffectType: { m_audioEffects.clear(); ComPointer<IEnumDMO> enumDMO; HRESULT hr = ::DMOEnum(DMOCATEGORY_AUDIO_EFFECT, DMO_ENUMF_INCLUDE_KEYED, 0, 0, 0, 0, enumDMO.pparam()); if (SUCCEEDED(hr)) { CLSID clsid; while (S_OK == enumDMO->Next(1, &clsid, 0, 0)) { ret += m_audioEffects.count(); m_audioEffects.append(clsid); } } break; } break; #endif //QT_NO_PHONON_EFFECT default: break; } return ret; } QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(Phonon::ObjectDescriptionType type, int index) const { QHash<QByteArray, QVariant> ret; switch (type) { case Phonon::AudioOutputDeviceType: { #ifdef Q_OS_WINCE ret["name"] = QLatin1String("default audio device"); #else const AudioMoniker &mon = m_audioOutputs[index]; LPOLESTR str = 0; HRESULT hr = mon->GetDisplayName(0,0, &str); if (SUCCEEDED(hr)) { QString name = QString::fromUtf16((unsigned short*)str); ComPointer<IMalloc> alloc; ::CoGetMalloc(1, alloc.pparam()); alloc->Free(str); ret["name"] = name.mid(name.indexOf('\\') + 1); } #endif } break; #ifndef QT_NO_PHONON_EFFECT case Phonon::EffectType: { WCHAR name[80]; // 80 is clearly stated in the MSDN doc HRESULT hr = ::DMOGetName(m_audioEffects[index], name); if (SUCCEEDED(hr)) { ret["name"] = QString::fromUtf16((unsigned short*)name); } } break; #endif //QT_NO_PHONON_EFFECT default: break; } return ret; } bool Backend::endConnectionChange(QSet<QObject *> objects) { //end of a transaction HRESULT hr = E_FAIL; if (!objects.isEmpty()) { Q_FOREACH(QObject *o, objects) { if (BackendNode *node = qobject_cast<BackendNode*>(o)) { MediaObject *mo = node->mediaObject(); if (mo && m_graphState.contains(mo)) { switch(m_graphState[mo]) { case Phonon::ErrorState: case Phonon::StoppedState: case Phonon::LoadingState: //nothing to do break; case Phonon::PausedState: mo->pause(); break; default: mo->play(); break; } if (mo->state() != Phonon::ErrorState) { hr = S_OK; } m_graphState.remove(mo); } } } } return SUCCEEDED(hr); } bool Backend::startConnectionChange(QSet<QObject *> objects) { //start a transaction QSet<MediaObject*> mediaObjects; //let's save the state of the graph (before we stop it) Q_FOREACH(QObject *o, objects) { if (BackendNode *node = qobject_cast<BackendNode*>(o)) { if (MediaObject *mo = node->mediaObject()) { mediaObjects << mo; } } } Q_FOREACH(MediaObject *mo, mediaObjects) { m_graphState[mo] = mo->state(); mo->ensureStopped(); //we have to stop the graph.. } return !mediaObjects.isEmpty(); } bool Backend::connectNodes(QObject *_source, QObject *_sink) { BackendNode *source = qobject_cast<BackendNode*>(_source); if (!source) { return false; } BackendNode *sink = qobject_cast<BackendNode*>(_sink); if (!sink) { return false; } //setting the graph if needed if (source->mediaObject() == 0 && sink->mediaObject() == 0) { //error: no graph selected return false; } else if (source->mediaObject() && source->mediaObject() != sink->mediaObject()) { //this' graph becomes the common one source->mediaObject()->grabNode(sink); } else if (source->mediaObject() == 0) { //sink's graph becomes the common one sink->mediaObject()->grabNode(source); } return source->mediaObject()->connectNodes(source, sink); } bool Backend::disconnectNodes(QObject *_source, QObject *_sink) { BackendNode *source = qobject_cast<BackendNode*>(_source); if (!source) { return false; } BackendNode *sink = qobject_cast<BackendNode*>(_sink); if (!sink) { return false; } return source->mediaObject() == 0 || source->mediaObject()->disconnectNodes(source, sink); } } } QT_END_NAMESPACE #include "moc_backend.cpp"
/* This file is part of the KDE project. Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include "backend.h" #include "backendnode.h" #include "audiooutput.h" #include "effect.h" #include "mediaobject.h" #include "videowidget.h" #include "volumeeffect.h" //windows specific (DirectX Media Object) #include <dmo.h> #include <QtCore/QSettings> #include <QtCore/QSet> #include <QtCore/QVariant> #include <QtCore/QtPlugin> QT_BEGIN_NAMESPACE Q_EXPORT_PLUGIN2(phonon_ds9, Phonon::DS9::Backend); namespace Phonon { namespace DS9 { bool Backend::AudioMoniker::operator==(const AudioMoniker &other) { return other->IsEqual(*this) == S_OK; } Backend::Backend(QObject *parent, const QVariantList &) : QObject(parent) { ::CoInitialize(0); //registering meta types qRegisterMetaType<HRESULT>("HRESULT"); qRegisterMetaType<QSet<Filter> >("QSet<Filter>"); qRegisterMetaType<Graph>("Graph"); } Backend::~Backend() { m_audioOutputs.clear(); m_audioEffects.clear(); ::CoUninitialize(); } QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args) { switch (c) { case MediaObjectClass: return new MediaObject(parent); case AudioOutputClass: return new AudioOutput(this, parent); #ifndef QT_NO_PHONON_EFFECT case EffectClass: return new Effect(m_audioEffects[ args[0].toInt() ], parent); #endif //QT_NO_PHONON_EFFECT #ifndef QT_NO_PHONON_VIDEO case VideoWidgetClass: return new VideoWidget(qobject_cast<QWidget *>(parent)); #endif //QT_NO_PHONON_VIDEO #ifndef QT_NO_PHONON_VOLUMEFADEREFFECT case VolumeFaderEffectClass: return new VolumeEffect(parent); #endif //QT_NO_PHONON_VOLUMEFADEREFFECT default: return 0; } } bool Backend::supportsVideo() const { #ifndef QT_NO_PHONON_VIDEO return true; #else return false; #endif //QT_NO_PHONON_VIDEO } QStringList Backend::availableMimeTypes() const { QSet<QString> ret; const QStringList locations = QStringList() << QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\mplayer2\\mime types") << QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\wmplayer\\mime types"); Q_FOREACH(QString s, locations) { QSettings settings(s, QSettings::NativeFormat); ret += settings.childGroups().replaceInStrings("\\", "/").toSet(); } QStringList list = ret.toList(); qSort(list); return list; } Filter Backend::getAudioOutputFilter(int index) const { Filter ret; if (index >= 0 && index < m_audioOutputs.count()) { m_audioOutputs.at(index)->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast<void**>(&ret)); } else { //just return the default audio renderer (not directsound) ret = Filter(CLSID_AudioRender, IID_IBaseFilter); } return ret; } QList<int> Backend::objectDescriptionIndexes(Phonon::ObjectDescriptionType type) const { QList<int> ret; switch(type) { case Phonon::AudioOutputDeviceType: { #ifdef Q_OS_WINCE ret << 0; // only one audio device with index 0 #else ComPointer<ICreateDevEnum> devEnum(CLSID_SystemDeviceEnum, IID_ICreateDevEnum); if (!devEnum) { return ret; //it is impossible to enumerate the devices } ComPointer<IEnumMoniker> enumMon; HRESULT hr = devEnum->CreateClassEnumerator(CLSID_AudioRendererCategory, enumMon.pparam(), 0); if (FAILED(hr)) { break; } AudioMoniker mon; //let's reorder the devices so that directshound appears first int nbds = 0; //number of directsound devices while (S_OK == enumMon->Next(1, mon.pparam(), 0)) { LPOLESTR str = 0; mon->GetDisplayName(0,0,&str); const QString name = QString::fromUtf16((unsigned short*)str); ComPointer<IMalloc> alloc; ::CoGetMalloc(1, alloc.pparam()); alloc->Free(str); int insert_pos = 0; if (!m_audioOutputs.contains(mon)) { insert_pos = m_audioOutputs.count(); m_audioOutputs.append(mon); } else { insert_pos = m_audioOutputs.indexOf(mon); } if (name.contains(QLatin1String("DirectSound"))) { ret.insert(nbds++, insert_pos); } else { ret.append(insert_pos); } } #endif break; } #ifndef QT_NO_PHONON_EFFECT case Phonon::EffectType: { m_audioEffects.clear(); ComPointer<IEnumDMO> enumDMO; HRESULT hr = ::DMOEnum(DMOCATEGORY_AUDIO_EFFECT, DMO_ENUMF_INCLUDE_KEYED, 0, 0, 0, 0, enumDMO.pparam()); if (SUCCEEDED(hr)) { CLSID clsid; while (S_OK == enumDMO->Next(1, &clsid, 0, 0)) { ret += m_audioEffects.count(); m_audioEffects.append(clsid); } } break; } break; #endif //QT_NO_PHONON_EFFECT default: break; } return ret; } QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(Phonon::ObjectDescriptionType type, int index) const { QHash<QByteArray, QVariant> ret; switch (type) { case Phonon::AudioOutputDeviceType: { #ifdef Q_OS_WINCE ret["name"] = QLatin1String("default audio device"); #else const AudioMoniker &mon = m_audioOutputs[index]; LPOLESTR str = 0; HRESULT hr = mon->GetDisplayName(0,0, &str); if (SUCCEEDED(hr)) { QString name = QString::fromUtf16((unsigned short*)str); ComPointer<IMalloc> alloc; ::CoGetMalloc(1, alloc.pparam()); alloc->Free(str); ret["name"] = name.mid(name.indexOf('\\') + 1); } #endif } break; #ifndef QT_NO_PHONON_EFFECT case Phonon::EffectType: { WCHAR name[80]; // 80 is clearly stated in the MSDN doc HRESULT hr = ::DMOGetName(m_audioEffects[index], name); if (SUCCEEDED(hr)) { ret["name"] = QString::fromUtf16((unsigned short*)name); } } break; #endif //QT_NO_PHONON_EFFECT default: break; } return ret; } bool Backend::endConnectionChange(QSet<QObject *> objects) { //end of a transaction HRESULT hr = E_FAIL; if (!objects.isEmpty()) { Q_FOREACH(QObject *o, objects) { if (BackendNode *node = qobject_cast<BackendNode*>(o)) { MediaObject *mo = node->mediaObject(); if (mo && m_graphState.contains(mo)) { switch(m_graphState[mo]) { case Phonon::ErrorState: case Phonon::StoppedState: case Phonon::LoadingState: //nothing to do break; case Phonon::PausedState: mo->pause(); break; default: mo->play(); break; } if (mo->state() != Phonon::ErrorState) { hr = S_OK; } m_graphState.remove(mo); } } } } return SUCCEEDED(hr); } bool Backend::startConnectionChange(QSet<QObject *> objects) { //start a transaction QSet<MediaObject*> mediaObjects; //let's save the state of the graph (before we stop it) Q_FOREACH(QObject *o, objects) { if (BackendNode *node = qobject_cast<BackendNode*>(o)) { if (MediaObject *mo = node->mediaObject()) { mediaObjects << mo; } } } Q_FOREACH(MediaObject *mo, mediaObjects) { m_graphState[mo] = mo->state(); mo->ensureStopped(); //we have to stop the graph.. } return objects.isEmpty() || !mediaObjects.isEmpty(); } bool Backend::connectNodes(QObject *_source, QObject *_sink) { BackendNode *source = qobject_cast<BackendNode*>(_source); if (!source) { return false; } BackendNode *sink = qobject_cast<BackendNode*>(_sink); if (!sink) { return false; } //setting the graph if needed if (source->mediaObject() == 0 && sink->mediaObject() == 0) { //error: no graph selected return false; } else if (source->mediaObject() && source->mediaObject() != sink->mediaObject()) { //this' graph becomes the common one source->mediaObject()->grabNode(sink); } else if (source->mediaObject() == 0) { //sink's graph becomes the common one sink->mediaObject()->grabNode(source); } return source->mediaObject()->connectNodes(source, sink); } bool Backend::disconnectNodes(QObject *_source, QObject *_sink) { BackendNode *source = qobject_cast<BackendNode*>(_source); if (!source) { return false; } BackendNode *sink = qobject_cast<BackendNode*>(_sink); if (!sink) { return false; } return source->mediaObject() == 0 || source->mediaObject()->disconnectNodes(source, sink); } } } QT_END_NAMESPACE #include "moc_backend.cpp"
make autotest path when reconnecting a path with the exact same source and sink.
make autotest path when reconnecting a path with the exact same source and sink.
C++
lgpl-2.1
shadeslayer/phonon-gstreamer,KDE/phonon-xine,KDE/phonon-mmf,KDE/phonon-gstreamer,KDE/phonon-waveout,KDE/phonon-gstreamer,shadeslayer/phonon-gstreamer,KDE/phonon-directshow,KDE/phonon-directshow,KDE/phonon-quicktime,KDE/phonon-xine,shadeslayer/phonon-gstreamer,KDE/phonon-xine
634967958f70e977335c865ce2b411c87560d62f
src/saiga/vulkan/memory/BaseChunkAllocator.cpp
src/saiga/vulkan/memory/BaseChunkAllocator.cpp
// // Created by Peter Eichinger on 30.10.18. // #include "BaseChunkAllocator.h" #include "saiga/core/imgui/imgui.h" #include "saiga/core/util/easylogging++.h" #include "saiga/core/util/tostring.h" #include "BufferChunkAllocator.h" #include "ChunkCreator.h" namespace Saiga::Vulkan::Memory { MemoryLocation* BaseChunkAllocator::allocate(vk::DeviceSize size) { std::scoped_lock alloc_lock(allocationMutex); ChunkIterator chunkAlloc; FreeIterator freeSpace; std::tie(chunkAlloc, freeSpace) = strategy->findRange(chunks.begin(), chunks.end(), size); MemoryLocation* val = allocate_in_free_space(size, chunkAlloc, freeSpace); return val; } MemoryLocation* BaseChunkAllocator::allocate_in_free_space(vk::DeviceSize size, ChunkIterator& chunkAlloc, FreeIterator& freeSpace) { MemoryLocation* val; if (chunkAlloc == chunks.end()) { chunkAlloc = createNewChunk(); freeSpace = chunkAlloc->freeList.begin(); } auto memoryStart = freeSpace->offset; freeSpace->offset += size; freeSpace->size -= size; if (freeSpace->size == 0) { chunkAlloc->freeList.erase(freeSpace); } findNewMax(chunkAlloc); // MemoryLocation{iter->buffer, iter->chunk->memory, offset, size, iter->mappedPointer}; auto targetLocation = std::make_unique<MemoryLocation>(chunkAlloc->buffer, chunkAlloc->chunk->memory, memoryStart, size, chunkAlloc->mappedPointer); auto memoryEnd = memoryStart + size; auto insertionPoint = lower_bound(chunkAlloc->allocations.begin(), chunkAlloc->allocations.end(), memoryEnd, [](const auto& element, vk::DeviceSize value) { return element->offset < value; }); val = chunkAlloc->allocations.insert(insertionPoint, move(targetLocation))->get(); chunkAlloc->allocated += size; return val; } void BaseChunkAllocator::findNewMax(ChunkIterator& chunkAlloc) const { auto& freeList = chunkAlloc->freeList; if (chunkAlloc->freeList.empty()) { chunkAlloc->maxFreeRange = std::nullopt; return; } chunkAlloc->maxFreeRange = *max_element(freeList.begin(), freeList.end(), [](auto& first, auto& second) { return first.size < second.size; }); } void BaseChunkAllocator::deallocate(MemoryLocation* location) { std::scoped_lock alloc_lock(allocationMutex); ChunkIterator fChunk; AllocationIterator fLoc; std::tie(fChunk, fLoc) = find_allocation(location); auto& chunkAllocs = fChunk->allocations; SAIGA_ASSERT(fLoc != chunkAllocs.end(), "Allocation is not part of the chunk"); LOG(INFO) << "Deallocating " << location->size << " bytes in chunk/offset [" << distance(chunks.begin(), fChunk) << "/" << (*fLoc)->offset << "]"; add_to_free_list(fChunk, *(fLoc->get())); findNewMax(fChunk); chunkAllocs.erase(fLoc); fChunk->allocated -= location->size; while (chunks.size() >= 2) { auto last = chunks.end() - 1; auto stol = chunks.end() - 2; if (!last->allocations.empty() || !stol->allocations.empty()) { break; } m_device.destroy(last->buffer); m_chunkAllocator->deallocate(last->chunk); last--; stol--; chunks.pop_back(); //chunks.erase(last + 1, chunks.end()); } } void BaseChunkAllocator::destroy() { for (auto& alloc : chunks) { m_device.destroy(alloc.buffer); } } bool BaseChunkAllocator::memory_is_free(vk::DeviceMemory memory, FreeListEntry free_mem) { std::scoped_lock lock(allocationMutex); auto chunk = std::find_if(chunks.begin(), chunks.end(), [&](const auto& chunk_entry) { return chunk_entry.chunk->memory == memory; }); SAIGA_ASSERT(chunk != chunks.end(), "Wrong allocator"); if (chunk->freeList.empty()) { return false; } auto found = std::lower_bound(chunk->freeList.begin(), chunk->freeList.end(), free_mem, [](const auto& free_entry, const auto& value) { return free_entry.offset < value.offset; }); // if (found->offset > free_mem.offset) //{ // return false; //} // // if (found->offset + found->size < free_mem.offset + free_mem.size) //{ // return false; //} return found->offset == free_mem.offset && found->size == free_mem.size; } MemoryLocation* BaseChunkAllocator::reserve_space(vk::DeviceMemory memory, FreeListEntry freeListEntry, vk::DeviceSize size) { std::scoped_lock lock(allocationMutex); auto chunk = std::find_if(chunks.begin(), chunks.end(), [&](const auto& chunk_entry) { return chunk_entry.chunk->memory == memory; }); SAIGA_ASSERT(chunk != chunks.end(), "Wrong allocator"); auto free = std::find(chunk->freeList.begin(), chunk->freeList.end(), freeListEntry); SAIGA_ASSERT(free != chunk->freeList.end(), "Free space not found"); return allocate_in_free_space(size, chunk, free); } void BaseChunkAllocator::move_allocation(MemoryLocation* target, MemoryLocation* source) { std::scoped_lock lock(allocationMutex); const auto size = source->size; MemoryLocation source_copy = *source; ChunkIterator target_chunk, source_chunk; AllocationIterator target_alloc, source_alloc; std::tie(target_chunk, target_alloc) = find_allocation(target); std::tie(source_chunk, source_alloc) = find_allocation(source); *source = *target; // copy values from target to source; source->mark_dynamic(); // target_chunk->allocated -= size; source_chunk->allocated -= size; std::move(source_alloc, std::next(source_alloc), target_alloc); source_chunk->allocations.erase(source_alloc); add_to_free_list(source_chunk, source_copy); findNewMax(source_chunk); } void BaseChunkAllocator::add_to_free_list(const ChunkIterator& chunk, const MemoryLocation& location) const { auto& freeList = chunk->freeList; auto found = lower_bound(freeList.begin(), freeList.end(), location, [](const auto& free_entry, const auto& value) { return free_entry.offset < value.offset; }); FreeIterator free; auto previous = prev(found); if (found != freeList.begin() && previous->end() == location.offset) { previous->size += location.size; free = previous; } else { free = freeList.insert(found, FreeListEntry{location.offset, location.size}); found = next(free); } if (found != freeList.end() && free->end() == found->offset) { free->size += found->size; freeList.erase(found); } } std::pair<ChunkIterator, AllocationIterator> BaseChunkAllocator::find_allocation(MemoryLocation* location) { auto fChunk = std::find_if(chunks.begin(), chunks.end(), [&](ChunkAllocation const& alloc) { return alloc.chunk->memory == location->memory; }); SAIGA_ASSERT(fChunk != chunks.end(), "Allocation was not done with this allocator!"); auto& chunkAllocs = fChunk->allocations; auto fLoc = std::lower_bound(chunkAllocs.begin(), chunkAllocs.end(), location, [](const auto& element, const auto& value) { return element->offset < value->offset; }); return std::make_pair(fChunk, fLoc); } } // namespace Saiga::Vulkan::Memory
// // Created by Peter Eichinger on 30.10.18. // #include "BaseChunkAllocator.h" #include "saiga/core/imgui/imgui.h" #include "saiga/core/util/easylogging++.h" #include "saiga/core/util/tostring.h" #include "BufferChunkAllocator.h" #include "ChunkCreator.h" namespace Saiga::Vulkan::Memory { MemoryLocation* BaseChunkAllocator::allocate(vk::DeviceSize size) { std::scoped_lock alloc_lock(allocationMutex); ChunkIterator chunkAlloc; FreeIterator freeSpace; std::tie(chunkAlloc, freeSpace) = strategy->findRange(chunks.begin(), chunks.end(), size); MemoryLocation* val = allocate_in_free_space(size, chunkAlloc, freeSpace); return val; } MemoryLocation* BaseChunkAllocator::allocate_in_free_space(vk::DeviceSize size, ChunkIterator& chunkAlloc, FreeIterator& freeSpace) { MemoryLocation* val; if (chunkAlloc == chunks.end()) { chunkAlloc = createNewChunk(); freeSpace = chunkAlloc->freeList.begin(); } auto memoryStart = freeSpace->offset; freeSpace->offset += size; freeSpace->size -= size; if (freeSpace->size == 0) { chunkAlloc->freeList.erase(freeSpace); } findNewMax(chunkAlloc); // MemoryLocation{iter->buffer, iter->chunk->memory, offset, size, iter->mappedPointer}; auto targetLocation = std::make_unique<MemoryLocation>(chunkAlloc->buffer, chunkAlloc->chunk->memory, memoryStart, size, chunkAlloc->mappedPointer); auto memoryEnd = memoryStart + size; auto insertionPoint = lower_bound(chunkAlloc->allocations.begin(), chunkAlloc->allocations.end(), memoryEnd, [](const auto& element, vk::DeviceSize value) { return element->offset < value; }); val = chunkAlloc->allocations.insert(insertionPoint, move(targetLocation))->get(); chunkAlloc->allocated += size; return val; } void BaseChunkAllocator::findNewMax(ChunkIterator& chunkAlloc) const { auto& freeList = chunkAlloc->freeList; if (chunkAlloc->freeList.empty()) { chunkAlloc->maxFreeRange = std::nullopt; return; } chunkAlloc->maxFreeRange = *max_element(freeList.begin(), freeList.end(), [](auto& first, auto& second) { return first.size < second.size; }); } void BaseChunkAllocator::deallocate(MemoryLocation* location) { std::scoped_lock alloc_lock(allocationMutex); ChunkIterator fChunk; AllocationIterator fLoc; std::tie(fChunk, fLoc) = find_allocation(location); auto& chunkAllocs = fChunk->allocations; SAIGA_ASSERT(fLoc != chunkAllocs.end(), "Allocation is not part of the chunk"); LOG(INFO) << "Deallocating " << location->size << " bytes in chunk/offset [" << distance(chunks.begin(), fChunk) << "/" << (*fLoc)->offset << "]"; fChunk->allocated -= location->size; add_to_free_list(fChunk, *(fLoc->get())); findNewMax(fChunk); chunkAllocs.erase(fLoc); while (chunks.size() >= 2) { auto last = chunks.end() - 1; auto stol = chunks.end() - 2; if (!last->allocations.empty() || !stol->allocations.empty()) { break; } m_device.destroy(last->buffer); m_chunkAllocator->deallocate(last->chunk); last--; stol--; chunks.pop_back(); //chunks.erase(last + 1, chunks.end()); } } void BaseChunkAllocator::destroy() { for (auto& alloc : chunks) { m_device.destroy(alloc.buffer); } } bool BaseChunkAllocator::memory_is_free(vk::DeviceMemory memory, FreeListEntry free_mem) { std::scoped_lock lock(allocationMutex); auto chunk = std::find_if(chunks.begin(), chunks.end(), [&](const auto& chunk_entry) { return chunk_entry.chunk->memory == memory; }); SAIGA_ASSERT(chunk != chunks.end(), "Wrong allocator"); if (chunk->freeList.empty()) { return false; } auto found = std::lower_bound(chunk->freeList.begin(), chunk->freeList.end(), free_mem, [](const auto& free_entry, const auto& value) { return free_entry.offset < value.offset; }); // if (found->offset > free_mem.offset) //{ // return false; //} // // if (found->offset + found->size < free_mem.offset + free_mem.size) //{ // return false; //} return found->offset == free_mem.offset && found->size == free_mem.size; } MemoryLocation* BaseChunkAllocator::reserve_space(vk::DeviceMemory memory, FreeListEntry freeListEntry, vk::DeviceSize size) { std::scoped_lock lock(allocationMutex); auto chunk = std::find_if(chunks.begin(), chunks.end(), [&](const auto& chunk_entry) { return chunk_entry.chunk->memory == memory; }); SAIGA_ASSERT(chunk != chunks.end(), "Wrong allocator"); auto free = std::find(chunk->freeList.begin(), chunk->freeList.end(), freeListEntry); SAIGA_ASSERT(free != chunk->freeList.end(), "Free space not found"); return allocate_in_free_space(size, chunk, free); } void BaseChunkAllocator::move_allocation(MemoryLocation* target, MemoryLocation* source) { std::scoped_lock lock(allocationMutex); const auto size = source->size; MemoryLocation source_copy = *source; ChunkIterator target_chunk, source_chunk; AllocationIterator target_alloc, source_alloc; std::tie(target_chunk, target_alloc) = find_allocation(target); std::tie(source_chunk, source_alloc) = find_allocation(source); *source = *target; // copy values from target to source; source->mark_dynamic(); // target_chunk->allocated -= size; source_chunk->allocated -= size; std::move(source_alloc, std::next(source_alloc), target_alloc); source_chunk->allocations.erase(source_alloc); add_to_free_list(source_chunk, source_copy); findNewMax(source_chunk); } void BaseChunkAllocator::add_to_free_list(const ChunkIterator& chunk, const MemoryLocation& location) const { auto& freeList = chunk->freeList; auto found = lower_bound(freeList.begin(), freeList.end(), location, [](const auto& free_entry, const auto& value) { return free_entry.offset < value.offset; }); FreeIterator free; auto previous = prev(found); if (found != freeList.begin() && previous->end() == location.offset) { previous->size += location.size; free = previous; } else { free = freeList.insert(found, FreeListEntry{location.offset, location.size}); found = next(free); } if (found != freeList.end() && free->end() == found->offset) { free->size += found->size; freeList.erase(found); } } std::pair<ChunkIterator, AllocationIterator> BaseChunkAllocator::find_allocation(MemoryLocation* location) { auto fChunk = std::find_if(chunks.begin(), chunks.end(), [&](ChunkAllocation const& alloc) { return alloc.chunk->memory == location->memory; }); SAIGA_ASSERT(fChunk != chunks.end(), "Allocation was not done with this allocator!"); auto& chunkAllocs = fChunk->allocations; auto fLoc = std::lower_bound(chunkAllocs.begin(), chunkAllocs.end(), location, [](const auto& element, const auto& value) { return element->offset < value->offset; }); return std::make_pair(fChunk, fLoc); } } // namespace Saiga::Vulkan::Memory
Fix base chunk allocator valgrind error
Fix base chunk allocator valgrind error
C++
mit
darglein/saiga,darglein/saiga,darglein/saiga
cffb9cabecb963f193a26778c61add174efe9aae
src/cal3d/bone.cpp
src/cal3d/bone.cpp
//****************************************************************************// // bone.cpp // // Copyright (C) 2001, 2002 Bruno 'Beosil' Heidelberger // //****************************************************************************// // This library is free software; you can redistribute it and/or modify it // // under the terms of the GNU Lesser General Public License as published by // // the Free Software Foundation; either version 2.1 of the License, or (at // // your option) any later version. // //****************************************************************************// #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "cal3d/error.h" #include "cal3d/bone.h" #include "cal3d/coremesh.h" #include "cal3d/coresubmesh.h" #include "cal3d/corebone.h" #include "cal3d/matrix.h" #include "cal3d/skeleton.h" #include "cal3d/coreskeleton.h" CalBone::CalBone(const CalCoreBone& coreBone) : parentId(coreBone.parentId) , coreRelativeTransform(coreBone.relativeTransform) , coreBoneSpaceTransform(coreBone.boneSpaceTransform) { resetPose(); } void CalBone::resetPose() { relativeTransform = coreRelativeTransform; // if no animations are applied, use this m_accumulatedWeight = 0.0f; m_accumulatedReplacementAttenuation = 1.0f; m_meshScaleAbsolute.set(1, 1, 1); } /*****************************************************************************/ /** Interpolates the current state to another state. * * This function interpolates the current state (relative translation and * rotation) of the bone instance to another state of a given weight. * * @param replace If true, subsequent animations will have their weight attenuated by 1 - rampValue. * @param rampValue Amount to attenuate weight when ramping in/out the animation. *****************************************************************************/ void CalBone::blendPose( const cal3d::Transform& transform, bool replace, const float rampValue ) { const float attenuatedWeight = rampValue * m_accumulatedReplacementAttenuation; if (replace) { m_accumulatedReplacementAttenuation *= (1.0f - rampValue); } m_accumulatedWeight += attenuatedWeight; float factor = m_accumulatedWeight ? attenuatedWeight / m_accumulatedWeight : 0.0f; assert(factor <= 1.0f); relativeTransform = blend(factor, relativeTransform, transform); } BoneTransform CalBone::calculateAbsolutePose(const CalBone* bones, bool includeRootTransform) { if (parentId == -1) { if (includeRootTransform) { // no parent, this means absolute state == relative state absoluteTransform = relativeTransform; } else { absoluteTransform = cal3d::Transform(); } } else { absoluteTransform = bones[parentId].absoluteTransform * relativeTransform; } CalVector boneSpaceTranslation(coreBoneSpaceTransform.translation); bool meshScalingOn = m_meshScaleAbsolute.x != 1 || m_meshScaleAbsolute.y != 1 || m_meshScaleAbsolute.z != 1; if (meshScalingOn) { // The mesh transformation is intended to apply to the vector from the // bone node to the vert, relative to the model's global coordinate system. // For example, even though the head node's X axis aims up, the model's // global coordinate system has X to stage right, Z up, and Y stage back. // // The standard vert transformation is: // v = (vmesh - boneAbsPosInJpose) * boneAbsRotInAnimPose + boneAbsPosInAnimPose // // Cal3d does the calculation by: // u = (umesh * transformMatrix) + translationBoneSpace // // where translationBoneSpace = "coreBoneTranslationBoneSpace" * boneAbsRotInAnimPose + boneAbsPosInAnimPose // and transformMatrix = "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // // I don't know what "coreBoneRotBoneSpace" and "coreBoneTranslationBoneSpace" actually are, // but to add scale to the scandard vert transformation, I simply do: // // v' = vmesh * scalevec * boneAbsRotInAnimPose // - boneAbsPosInJpose * scalevec * boneAbsRotInAnimPose // + boneAbsPosInAnimPose // // Essentially, the boneAbsPosInJpose is just an extra vector added to // each vertex that we want to subtract out. We must transform the extra // vector in exactly the same way we transform the vmesh. Therefore if we scale the mesh, we // must also scale the boneAbsPosInJpose. // // Expanding out the u2 equation, we have: // // u = umesh * "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // + "coreBoneTranslationBoneSpace" * boneAbsRotInAnimPose // + boneAbsPosInAnimPose // // We assume that "coreBoneTranslationBoneSpace" = vectorThatMustBeSubtractedFromUmesh * "coreBoneRotBoneSpace": // // u = umesh * "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // + vectorThatMustBeSubtractedFromUmesh * "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // + boneAbsPosInAnimPose // // We assume that scale should be applied to umesh, not umesh * "coreBoneRotBoneSpace": // // u = umesh * scaleVec * "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // + "coreBoneTranslationBoneSpace" * "coreBoneRotBoneSpaceInverse" * scaleVec * "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // + boneAbsPosInAnimPose // // which yields, // // transformMatrix' = scaleVec * "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // // and, // // translationBoneSpace' = // coreBoneTranslationBoneSpace * "coreBoneRotBoneSpaceInverse" * scaleVec * "coreBoneRotBoneSpace" // * boneAbsRotInAnimPose // + boneAbsPosInAnimPose //boneSpaceTranslation *= m_meshScaleAbsolute; boneSpaceTranslation = coreBoneSpaceTransform.rotation * ((-coreBoneSpaceTransform.rotation * boneSpaceTranslation) * m_meshScaleAbsolute); } CalMatrix boneSpaceRotationAndScale(coreBoneSpaceTransform.rotation); if (meshScalingOn) { // By applying each scale component to the row, instead of the column, we // are effectively making the scale apply prior to the rotationBoneSpace. boneSpaceRotationAndScale.dxdx *= m_meshScaleAbsolute.x; boneSpaceRotationAndScale.dydx *= m_meshScaleAbsolute.x; boneSpaceRotationAndScale.dzdx *= m_meshScaleAbsolute.x; boneSpaceRotationAndScale.dxdy *= m_meshScaleAbsolute.y; boneSpaceRotationAndScale.dydy *= m_meshScaleAbsolute.y; boneSpaceRotationAndScale.dzdy *= m_meshScaleAbsolute.y; boneSpaceRotationAndScale.dxdz *= m_meshScaleAbsolute.z; boneSpaceRotationAndScale.dydz *= m_meshScaleAbsolute.z; boneSpaceRotationAndScale.dzdz *= m_meshScaleAbsolute.z; } return BoneTransform( CalMatrix(absoluteTransform.rotation) * boneSpaceRotationAndScale, absoluteTransform * boneSpaceTranslation); }
//****************************************************************************// // bone.cpp // // Copyright (C) 2001, 2002 Bruno 'Beosil' Heidelberger // //****************************************************************************// // This library is free software; you can redistribute it and/or modify it // // under the terms of the GNU Lesser General Public License as published by // // the Free Software Foundation; either version 2.1 of the License, or (at // // your option) any later version. // //****************************************************************************// #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "cal3d/error.h" #include "cal3d/bone.h" #include "cal3d/coremesh.h" #include "cal3d/coresubmesh.h" #include "cal3d/corebone.h" #include "cal3d/matrix.h" #include "cal3d/skeleton.h" #include "cal3d/coreskeleton.h" CalBone::CalBone(const CalCoreBone& coreBone) : parentId(coreBone.parentId) , coreRelativeTransform(coreBone.relativeTransform) , coreBoneSpaceTransform(coreBone.boneSpaceTransform) { resetPose(); } void CalBone::resetPose() { relativeTransform = coreRelativeTransform; // if no animations are applied, use this m_accumulatedWeight = 0.0f; m_accumulatedReplacementAttenuation = 1.0f; m_meshScaleAbsolute.set(1, 1, 1); } /*****************************************************************************/ /** Interpolates the current state to another state. * * This function interpolates the current state (relative translation and * rotation) of the bone instance to another state of a given weight. * * @param replace If true, subsequent animations will have their weight attenuated by 1 - rampValue. * @param rampValue Amount to attenuate weight when ramping in/out the animation. *****************************************************************************/ void CalBone::blendPose( const cal3d::Transform& transform, bool replace, const float rampValue ) { const float attenuatedWeight = rampValue * m_accumulatedReplacementAttenuation; if (replace) { m_accumulatedReplacementAttenuation *= (1.0f - rampValue); } m_accumulatedWeight += attenuatedWeight; float factor = m_accumulatedWeight ? attenuatedWeight / m_accumulatedWeight : 0.0f; assert(factor <= 1.0f); relativeTransform = blend(factor, relativeTransform, transform); } BoneTransform CalBone::calculateAbsolutePose(const CalBone* bones, bool includeRootTransform) { if (parentId == -1) { if (includeRootTransform) { // no parent, this means absolute state == relative state absoluteTransform = relativeTransform; } else { absoluteTransform = cal3d::Transform(); } } else { absoluteTransform = bones[parentId].absoluteTransform * relativeTransform; } CalVector boneSpaceTranslation(coreBoneSpaceTransform.translation); bool meshScalingOn = m_meshScaleAbsolute.x != 1 || m_meshScaleAbsolute.y != 1 || m_meshScaleAbsolute.z != 1; if (meshScalingOn) { // The mesh transformation is intended to apply to the vector from the // bone node to the vert, relative to the model's global coordinate system. // For example, even though the head node's X axis aims up, the model's // global coordinate system has X to stage right, Z up, and Y stage back. // // The standard vert transformation is: // v = (vmesh - boneAbsPosInJpose) * boneAbsRotInAnimPose + boneAbsPosInAnimPose // // Cal3d does the calculation by: // u = (umesh * transformMatrix) + translationBoneSpace // // where translationBoneSpace = "coreBoneTranslationBoneSpace" * boneAbsRotInAnimPose + boneAbsPosInAnimPose // and transformMatrix = "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // // I don't know what "coreBoneRotBoneSpace" and "coreBoneTranslationBoneSpace" actually are, // but to add scale to the scandard vert transformation, I simply do: // // v' = vmesh * scalevec * boneAbsRotInAnimPose // - boneAbsPosInJpose * scalevec * boneAbsRotInAnimPose // + boneAbsPosInAnimPose // // Essentially, the boneAbsPosInJpose is just an extra vector added to // each vertex that we want to subtract out. We must transform the extra // vector in exactly the same way we transform the vmesh. Therefore if we scale the mesh, we // must also scale the boneAbsPosInJpose. // // Expanding out the u2 equation, we have: // // u = umesh * "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // + "coreBoneTranslationBoneSpace" * boneAbsRotInAnimPose // + boneAbsPosInAnimPose // // We assume that "coreBoneTranslationBoneSpace" = vectorThatMustBeSubtractedFromUmesh * "coreBoneRotBoneSpace": // // u = umesh * "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // + vectorThatMustBeSubtractedFromUmesh * "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // + boneAbsPosInAnimPose // // We assume that scale should be applied to umesh, not umesh * "coreBoneRotBoneSpace": // // u = umesh * scaleVec * "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // + "coreBoneTranslationBoneSpace" * "coreBoneRotBoneSpaceInverse" * scaleVec * "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // + boneAbsPosInAnimPose // // which yields, // // transformMatrix' = scaleVec * "coreBoneRotBoneSpace" * boneAbsRotInAnimPose // // and, // // translationBoneSpace' = // coreBoneTranslationBoneSpace * "coreBoneRotBoneSpaceInverse" * scaleVec * "coreBoneRotBoneSpace" // * boneAbsRotInAnimPose // + boneAbsPosInAnimPose boneSpaceTranslation = coreBoneSpaceTransform.rotation * ((-coreBoneSpaceTransform.rotation * boneSpaceTranslation) * m_meshScaleAbsolute); } CalMatrix boneSpaceRotationAndScale(coreBoneSpaceTransform.rotation); if (meshScalingOn) { // By applying each scale component to the row, instead of the column, we // are effectively making the scale apply prior to the rotationBoneSpace. boneSpaceRotationAndScale.dxdx *= m_meshScaleAbsolute.x; boneSpaceRotationAndScale.dydx *= m_meshScaleAbsolute.x; boneSpaceRotationAndScale.dzdx *= m_meshScaleAbsolute.x; boneSpaceRotationAndScale.dxdy *= m_meshScaleAbsolute.y; boneSpaceRotationAndScale.dydy *= m_meshScaleAbsolute.y; boneSpaceRotationAndScale.dzdy *= m_meshScaleAbsolute.y; boneSpaceRotationAndScale.dxdz *= m_meshScaleAbsolute.z; boneSpaceRotationAndScale.dydz *= m_meshScaleAbsolute.z; boneSpaceRotationAndScale.dzdz *= m_meshScaleAbsolute.z; } return BoneTransform( CalMatrix(absoluteTransform.rotation) * boneSpaceRotationAndScale, absoluteTransform * boneSpaceTranslation); }
clarify some documentation
clarify some documentation git-svn-id: febc42a3fd39fb08e5ae2b2182bc5ab0a583559c@117023 07c76cb3-cb09-0410-85de-c24d39f1912e
C++
lgpl-2.1
imvu/cal3d,imvu/cal3d,imvu/cal3d,imvu/cal3d
c304142b4053fd33ab10ca7beb9049d3379f4c85
TestMore/CondExpAD.cpp
TestMore/CondExpAD.cpp
// BEGIN SHORT COPYRIGHT /* ----------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-05 Bradley M. Bell This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ------------------------------------------------------------------------ */ // END SHORT COPYRIGHT /* Test of CondExp with AD< AD< Base > > types */ # include <CppAD/CppAD.h> typedef CppAD::AD< double > ADdouble; typedef CppAD::AD< ADdouble > ADADdouble; bool CondExpAD(void) { bool ok = true; using namespace CppAD; // ADdouble independent variable vector CppADvector< ADdouble > Xa(3); Xa[0] = -1.; Xa[1] = 0.; Xa[2] = 1.; Independent(Xa); // ADdouble independent variable vector CppADvector< ADADdouble > Xaa(3); Xaa[0] = Xa[0]; Xaa[1] = Xa[1]; Xaa[2] = Xa[2]; Independent(Xaa); // ADADdouble parameter ADADdouble p = ADADdouble(Xa[0]); ADADdouble q = ADADdouble(Xa[1]); ADADdouble r = ADADdouble(Xa[2]); // ADADdouble dependent variable vector CppADvector< ADADdouble > Yaa(8); // CondExp(parameter, parameter, parameter) Yaa[0] = CondExp(p, q, r); // CondExp(parameter, parameter, variable) Yaa[1] = CondExp(p, q, Xaa[2]); // CondExp(parameter, varaible, parameter) Yaa[2] = CondExp(p, Xaa[1], r); // CondExp(parameter, variable, variable) Yaa[3] = CondExp(p, Xaa[1], Xaa[2]); // CondExp(variable, variable, variable) Yaa[5] = CondExp(Xaa[0], Xaa[1], Xaa[2]); // CondExp(variable, variable, parameter) Yaa[4] = CondExp(Xaa[0], Xaa[1], r); // CondExp(variable, parameter, variable) Yaa[6] = CondExp(Xaa[0], q, Xaa[2]); // CondExp(variable, parameter, parameter) Yaa[7] = CondExp(Xaa[0], q, r); // create fa: Xaa -> Yaa function object ADFun< ADdouble > fa(Xaa, Yaa); // function values CppADvector< ADdouble > Ya(8); Ya = fa.Forward(0, Xa); // create f: Xa -> Ya function object ADFun<double> f(Xa, Ya); // now evaluate the function object CppADvector<double> x(3); CppADvector<double> y(8); x[0] = 1.; x[1] = 0.; x[2] = -1.; y = f.Forward(0, x); // Yaa[0] = CondExp( p, q, r); // y[0] = CondExp(x[0], x[1], x[2]); if( x[0] > 0. ) ok &= (y[0] == x[1]); else ok &= (y[0] == x[2]); // Yaa[1] = CondExp( p, q, Xaa[2]); // y[1] = CondExp(x[0], x[1], x[2]); if( x[0] > 0. ) ok &= (y[1] == x[1]); else ok &= (y[1] == x[2]); // Yaa[2] = CondExp( p, Xaa[1], r); // y[3] = CondExp(x[0], x[1], x[2]); if( x[0] > 0. ) ok &= (y[2] == x[1]); else ok &= (y[2] == x[2]); // Yaa[3] = CondExp( p, Xaa[1], Xaa[2]); // y[3] = CondExp(x[0], x[1], x[2]); if( x[0] > 0. ) ok &= (y[3] == x[1]); else ok &= (y[3] == x[2]); // Yaa[5] = CondExp(Xaa[0], Xaa[1], Xaa[2]); // y[5] = CondExp( x[0], x[1], x[2]); if( x[0] > 0. ) ok &= (y[5] == x[1]); else ok &= (y[5] == x[2]); // Yaa[4] = CondExp(Xaa[0], Xaa[1], r); // y[4] = CondExp( x[0], x[1], x[2]); if( x[0] > 0. ) ok &= (y[4] == x[1]); else ok &= (y[4] == x[2]); // Yaa[6] = CondExp(Xaa[0], q, Xaa[2]); // y[6] = CondExp( x[0], x[1], x[2]); if( x[0] > 0. ) ok &= (y[6] == x[1]); else ok &= (y[6] == x[2]); // Yaa[7] = CondExp(Xaa[0], q, r); // y[7] = CondExp( x[0], x[1], x[2]); if( x[0] > 0. ) ok &= (y[7] == x[1]); else ok &= (y[7] == x[2]); // check forward mode derivatives CppADvector<double> dx(3); CppADvector<double> dy(8); dx[0] = 1.; dx[1] = 2.; dx[2] = 3.; dy = f.Forward(1, dx); if( x[0] > 0. ) ok &= (dy[0] == dx[1]); else ok &= (dy[0] == dx[2]); if( x[0] > 0. ) ok &= (dy[1] == dx[1]); else ok &= (dy[1] == dx[2]); if( x[0] > 0. ) ok &= (dy[2] == dx[1]); else ok &= (dy[2] == dx[2]); if( x[0] > 0. ) ok &= (dy[3] == dx[1]); else ok &= (dy[3] == dx[2]); if( x[0] > 0. ) ok &= (dy[5] == dx[1]); else ok &= (dy[5] == dx[2]); if( x[0] > 0. ) ok &= (dy[4] == dx[1]); else ok &= (dy[4] == dx[2]); if( x[0] > 0. ) ok &= (dy[6] == dx[1]); else ok &= (dy[6] == dx[2]); if( x[0] > 0. ) ok &= (dy[7] == dx[1]); else ok &= (dy[7] == dx[2]); // check reverse mode derivatives size_t i; for(i = 0; i < 8; i++) dy[i] = double(i); dx = f.Reverse(1, dy); CppADvector<double> sum(3); sum[0] = sum[1] = sum[2] = 0.; if( x[0] > 0. ) sum[1] += dy[0]; else sum[2] += dy[0]; if( x[0] > 0. ) sum[1] += dy[1]; else sum[2] += dy[1]; if( x[0] > 0. ) sum[1] += dy[2]; else sum[2] += dy[2]; if( x[0] > 0. ) sum[1] += dy[3]; else sum[2] += dy[3]; if( x[0] > 0. ) sum[1] += dy[5]; else sum[2] += dy[5]; if( x[0] > 0. ) sum[1] += dy[4]; else sum[2] += dy[4]; if( x[0] > 0. ) sum[1] += dy[6]; else sum[2] += dy[6]; if( x[0] > 0. ) sum[1] += dy[7]; else sum[2] += dy[7]; return ok; } // END PROGRAM
// BEGIN SHORT COPYRIGHT /* ----------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-05 Bradley M. Bell This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ------------------------------------------------------------------------ */ // END SHORT COPYRIGHT /* Test of CondExp with AD< AD< Base > > types */ # include <CppAD/CppAD.h> typedef CppAD::AD< double > ADdouble; typedef CppAD::AD< ADdouble > ADADdouble; bool CondExpAD(void) { bool ok = true; using namespace CppAD; size_t n = 3; size_t m = 8; // ADdouble independent variable vector CppADvector< ADdouble > Xa(n); Xa[0] = -1.; Xa[1] = 0.; Xa[2] = 1.; Independent(Xa); // ADdouble independent variable vector CppADvector< ADADdouble > Xaa(n); Xaa[0] = Xa[0]; Xaa[1] = Xa[1]; Xaa[2] = Xa[2]; Independent(Xaa); // ADADdouble parameter ADADdouble p = ADADdouble(Xa[0]); ADADdouble q = ADADdouble(Xa[1]); ADADdouble r = ADADdouble(Xa[2]); // ADADdouble dependent variable vector CppADvector< ADADdouble > Yaa(m); // CondExp(parameter, parameter, parameter) Yaa[0] = CondExp(p, q, r); // CondExp(parameter, parameter, variable) Yaa[1] = CondExp(p, q, Xaa[2]); // CondExp(parameter, varaible, parameter) Yaa[2] = CondExp(p, Xaa[1], r); // CondExp(parameter, variable, variable) Yaa[3] = CondExp(p, Xaa[1], Xaa[2]); // CondExp(variable, variable, variable) Yaa[5] = CondExp(Xaa[0], Xaa[1], Xaa[2]); // CondExp(variable, variable, parameter) Yaa[4] = CondExp(Xaa[0], Xaa[1], r); // CondExp(variable, parameter, variable) Yaa[6] = CondExp(Xaa[0], q, Xaa[2]); // CondExp(variable, parameter, parameter) Yaa[7] = CondExp(Xaa[0], q, r); // create fa: Xaa -> Yaa function object ADFun< ADdouble > fa(Xaa, Yaa); // function values CppADvector< ADdouble > Ya(m); Ya = fa.Forward(0, Xa); // create f: Xa -> Ya function object ADFun<double> f(Xa, Ya); // check result of function evaluation CppADvector<double> x(n); CppADvector<double> y(m); x[0] = 1.; x[1] = 0.; x[2] = -1.; y = f.Forward(0, x); size_t i; for(i = 0; i < m; i++) { // y[i] = CondExp(x[0], x[1], x[2]) if( x[0] > 0 ) ok &= (y[i] == x[1]); else ok &= (y[i] == x[2]); } // check forward mode derivatives CppADvector<double> dx(n); CppADvector<double> dy(m); dx[0] = 1.; dx[1] = 2.; dx[2] = 3.; dy = f.Forward(1, dx); for(i = 0; i < m; i++) { if( x[0] > 0. ) ok &= (dy[i] == dx[1]); else ok &= (dy[i] == dx[2]); } // calculate Jacobian CppADvector<double> J(m * n); size_t j; for(i = 0; i < m; i++) { for(j = 0; j < n; j++) J[i * n + j] = 0.; if( x[0] > 0. ) J[i * n + 1] = 1.; else J[i * n + 2] = 1.; } // check reverse mode derivatives for(i = 0; i < m; i++) dy[i] = double(i); dx = f.Reverse(1, dy); double sum; for(j = 0; j < n; j++) { sum = 0; for(i = 0; i < m; i++) sum += dy[i] * J[i * n + j]; ok &= (sum == dx[j]); } return ok; } // END PROGRAM
simplify and add missing check of reverse mode
simplify and add missing check of reverse mode git-svn-id: 3f5418f4deb1796ec361794c2e3ca0aec3c9c1fd@209 0e562018-b8fb-0310-a933-ecf073c7c197
C++
epl-1.0
wegamekinglc/CppAD,wegamekinglc/CppAD,kaskr/CppAD,kaskr/CppAD,kaskr/CppAD,utke1/cppad,tkelman/CppAD-oldmirror,utke1/cppad,kaskr/CppAD,wegamekinglc/CppAD,wegamekinglc/CppAD,wegamekinglc/CppAD,tkelman/CppAD-oldmirror,utke1/cppad,tkelman/CppAD-oldmirror,tkelman/CppAD-oldmirror,utke1/cppad,kaskr/CppAD
5876c3f089da4f69a1279f69eb9229bced13cde2
servers/register_server_types.cpp
servers/register_server_types.cpp
/*************************************************************************/ /* register_server_types.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "register_server_types.h" #include "core/engine.h" #include "core/project_settings.h" #include "arvr/arvr_interface.h" #include "arvr/arvr_positional_tracker.h" #include "arvr_server.h" #include "audio/audio_effect.h" #include "audio/audio_stream.h" #include "audio/effects/audio_effect_amplify.h" #include "audio/effects/audio_effect_chorus.h" #include "audio/effects/audio_effect_compressor.h" #include "audio/effects/audio_effect_delay.h" #include "audio/effects/audio_effect_distortion.h" #include "audio/effects/audio_effect_eq.h" #include "audio/effects/audio_effect_filter.h" #include "audio/effects/audio_effect_limiter.h" #include "audio/effects/audio_effect_panner.h" #include "audio/effects/audio_effect_phaser.h" #include "audio/effects/audio_effect_pitch_shift.h" #include "audio/effects/audio_effect_record.h" #include "audio/effects/audio_effect_reverb.h" #include "audio/effects/audio_effect_stereo_enhance.h" #include "audio_server.h" #include "core/script_debugger_remote.h" #include "physics/physics_server_sw.h" #include "physics_2d/physics_2d_server_sw.h" #include "physics_2d/physics_2d_server_wrap_mt.h" #include "physics_2d_server.h" #include "physics_server.h" #include "visual/shader_types.h" #include "visual_server.h" static void _debugger_get_resource_usage(List<ScriptDebuggerRemote::ResourceUsage> *r_usage) { List<VS::TextureInfo> tinfo; VS::get_singleton()->texture_debug_usage(&tinfo); for (List<VS::TextureInfo>::Element *E = tinfo.front(); E; E = E->next()) { ScriptDebuggerRemote::ResourceUsage usage; usage.path = E->get().path; usage.vram = E->get().bytes; usage.id = E->get().texture; usage.type = "Texture"; usage.format = itos(E->get().width) + "x" + itos(E->get().height) + " " + Image::get_format_name(E->get().format); r_usage->push_back(usage); } } ShaderTypes *shader_types = NULL; PhysicsServer *_createGodotPhysicsCallback() { WARN_PRINT("The GodotPhysics 3D physics engine is deprecated and will be removed in Godot 3.2. You should use the Bullet physics engine instead (configurable in your project settings)."); return memnew(PhysicsServerSW); } Physics2DServer *_createGodotPhysics2DCallback() { return Physics2DServerWrapMT::init_server<Physics2DServerSW>(); } void register_server_types() { ClassDB::register_virtual_class<VisualServer>(); ClassDB::register_class<AudioServer>(); ClassDB::register_virtual_class<PhysicsServer>(); ClassDB::register_virtual_class<Physics2DServer>(); ClassDB::register_class<ARVRServer>(); shader_types = memnew(ShaderTypes); ClassDB::register_virtual_class<ARVRInterface>(); ClassDB::register_class<ARVRPositionalTracker>(); ClassDB::register_virtual_class<AudioStream>(); ClassDB::register_virtual_class<AudioStreamPlayback>(); ClassDB::register_class<AudioStreamMicrophone>(); ClassDB::register_class<AudioStreamRandomPitch>(); ClassDB::register_virtual_class<AudioEffect>(); ClassDB::register_class<AudioEffectEQ>(); ClassDB::register_class<AudioEffectFilter>(); ClassDB::register_class<AudioBusLayout>(); { //audio effects ClassDB::register_class<AudioEffectAmplify>(); ClassDB::register_class<AudioEffectReverb>(); ClassDB::register_class<AudioEffectLowPassFilter>(); ClassDB::register_class<AudioEffectHighPassFilter>(); ClassDB::register_class<AudioEffectBandPassFilter>(); ClassDB::register_class<AudioEffectNotchFilter>(); ClassDB::register_class<AudioEffectBandLimitFilter>(); ClassDB::register_class<AudioEffectLowShelfFilter>(); ClassDB::register_class<AudioEffectHighShelfFilter>(); ClassDB::register_class<AudioEffectEQ6>(); ClassDB::register_class<AudioEffectEQ10>(); ClassDB::register_class<AudioEffectEQ21>(); ClassDB::register_class<AudioEffectDistortion>(); ClassDB::register_class<AudioEffectStereoEnhance>(); ClassDB::register_class<AudioEffectPanner>(); ClassDB::register_class<AudioEffectChorus>(); ClassDB::register_class<AudioEffectDelay>(); ClassDB::register_class<AudioEffectCompressor>(); ClassDB::register_class<AudioEffectLimiter>(); ClassDB::register_class<AudioEffectPitchShift>(); ClassDB::register_class<AudioEffectPhaser>(); ClassDB::register_class<AudioEffectRecord>(); } ClassDB::register_virtual_class<Physics2DDirectBodyState>(); ClassDB::register_virtual_class<Physics2DDirectSpaceState>(); ClassDB::register_virtual_class<Physics2DShapeQueryResult>(); ClassDB::register_class<Physics2DTestMotionResult>(); ClassDB::register_class<Physics2DShapeQueryParameters>(); ClassDB::register_class<PhysicsShapeQueryParameters>(); ClassDB::register_virtual_class<PhysicsDirectBodyState>(); ClassDB::register_virtual_class<PhysicsDirectSpaceState>(); ClassDB::register_virtual_class<PhysicsShapeQueryResult>(); ScriptDebuggerRemote::resource_usage_func = _debugger_get_resource_usage; // Physics 2D GLOBAL_DEF(Physics2DServerManager::setting_property_name, "DEFAULT"); ProjectSettings::get_singleton()->set_custom_property_info(Physics2DServerManager::setting_property_name, PropertyInfo(Variant::STRING, Physics2DServerManager::setting_property_name, PROPERTY_HINT_ENUM, "DEFAULT")); Physics2DServerManager::register_server("GodotPhysics", &_createGodotPhysics2DCallback); Physics2DServerManager::set_default_server("GodotPhysics"); // Physics 3D GLOBAL_DEF(PhysicsServerManager::setting_property_name, "DEFAULT"); ProjectSettings::get_singleton()->set_custom_property_info(PhysicsServerManager::setting_property_name, PropertyInfo(Variant::STRING, PhysicsServerManager::setting_property_name, PROPERTY_HINT_ENUM, "DEFAULT")); PhysicsServerManager::register_server("GodotPhysics - deprecated", &_createGodotPhysicsCallback); PhysicsServerManager::set_default_server("GodotPhysics - deprecated"); } void unregister_server_types() { memdelete(shader_types); } void register_server_singletons() { Engine::get_singleton()->add_singleton(Engine::Singleton("VisualServer", VisualServer::get_singleton())); Engine::get_singleton()->add_singleton(Engine::Singleton("AudioServer", AudioServer::get_singleton())); Engine::get_singleton()->add_singleton(Engine::Singleton("PhysicsServer", PhysicsServer::get_singleton())); Engine::get_singleton()->add_singleton(Engine::Singleton("Physics2DServer", Physics2DServer::get_singleton())); Engine::get_singleton()->add_singleton(Engine::Singleton("ARVRServer", ARVRServer::get_singleton())); }
/*************************************************************************/ /* register_server_types.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "register_server_types.h" #include "core/engine.h" #include "core/project_settings.h" #include "arvr/arvr_interface.h" #include "arvr/arvr_positional_tracker.h" #include "arvr_server.h" #include "audio/audio_effect.h" #include "audio/audio_stream.h" #include "audio/effects/audio_effect_amplify.h" #include "audio/effects/audio_effect_chorus.h" #include "audio/effects/audio_effect_compressor.h" #include "audio/effects/audio_effect_delay.h" #include "audio/effects/audio_effect_distortion.h" #include "audio/effects/audio_effect_eq.h" #include "audio/effects/audio_effect_filter.h" #include "audio/effects/audio_effect_limiter.h" #include "audio/effects/audio_effect_panner.h" #include "audio/effects/audio_effect_phaser.h" #include "audio/effects/audio_effect_pitch_shift.h" #include "audio/effects/audio_effect_record.h" #include "audio/effects/audio_effect_reverb.h" #include "audio/effects/audio_effect_stereo_enhance.h" #include "audio_server.h" #include "core/script_debugger_remote.h" #include "physics/physics_server_sw.h" #include "physics_2d/physics_2d_server_sw.h" #include "physics_2d/physics_2d_server_wrap_mt.h" #include "physics_2d_server.h" #include "physics_server.h" #include "visual/shader_types.h" #include "visual_server.h" static void _debugger_get_resource_usage(List<ScriptDebuggerRemote::ResourceUsage> *r_usage) { List<VS::TextureInfo> tinfo; VS::get_singleton()->texture_debug_usage(&tinfo); for (List<VS::TextureInfo>::Element *E = tinfo.front(); E; E = E->next()) { ScriptDebuggerRemote::ResourceUsage usage; usage.path = E->get().path; usage.vram = E->get().bytes; usage.id = E->get().texture; usage.type = "Texture"; usage.format = itos(E->get().width) + "x" + itos(E->get().height) + " " + Image::get_format_name(E->get().format); r_usage->push_back(usage); } } ShaderTypes *shader_types = NULL; PhysicsServer *_createGodotPhysicsCallback() { return memnew(PhysicsServerSW); } Physics2DServer *_createGodotPhysics2DCallback() { return Physics2DServerWrapMT::init_server<Physics2DServerSW>(); } void register_server_types() { ClassDB::register_virtual_class<VisualServer>(); ClassDB::register_class<AudioServer>(); ClassDB::register_virtual_class<PhysicsServer>(); ClassDB::register_virtual_class<Physics2DServer>(); ClassDB::register_class<ARVRServer>(); shader_types = memnew(ShaderTypes); ClassDB::register_virtual_class<ARVRInterface>(); ClassDB::register_class<ARVRPositionalTracker>(); ClassDB::register_virtual_class<AudioStream>(); ClassDB::register_virtual_class<AudioStreamPlayback>(); ClassDB::register_class<AudioStreamMicrophone>(); ClassDB::register_class<AudioStreamRandomPitch>(); ClassDB::register_virtual_class<AudioEffect>(); ClassDB::register_class<AudioEffectEQ>(); ClassDB::register_class<AudioEffectFilter>(); ClassDB::register_class<AudioBusLayout>(); { //audio effects ClassDB::register_class<AudioEffectAmplify>(); ClassDB::register_class<AudioEffectReverb>(); ClassDB::register_class<AudioEffectLowPassFilter>(); ClassDB::register_class<AudioEffectHighPassFilter>(); ClassDB::register_class<AudioEffectBandPassFilter>(); ClassDB::register_class<AudioEffectNotchFilter>(); ClassDB::register_class<AudioEffectBandLimitFilter>(); ClassDB::register_class<AudioEffectLowShelfFilter>(); ClassDB::register_class<AudioEffectHighShelfFilter>(); ClassDB::register_class<AudioEffectEQ6>(); ClassDB::register_class<AudioEffectEQ10>(); ClassDB::register_class<AudioEffectEQ21>(); ClassDB::register_class<AudioEffectDistortion>(); ClassDB::register_class<AudioEffectStereoEnhance>(); ClassDB::register_class<AudioEffectPanner>(); ClassDB::register_class<AudioEffectChorus>(); ClassDB::register_class<AudioEffectDelay>(); ClassDB::register_class<AudioEffectCompressor>(); ClassDB::register_class<AudioEffectLimiter>(); ClassDB::register_class<AudioEffectPitchShift>(); ClassDB::register_class<AudioEffectPhaser>(); ClassDB::register_class<AudioEffectRecord>(); } ClassDB::register_virtual_class<Physics2DDirectBodyState>(); ClassDB::register_virtual_class<Physics2DDirectSpaceState>(); ClassDB::register_virtual_class<Physics2DShapeQueryResult>(); ClassDB::register_class<Physics2DTestMotionResult>(); ClassDB::register_class<Physics2DShapeQueryParameters>(); ClassDB::register_class<PhysicsShapeQueryParameters>(); ClassDB::register_virtual_class<PhysicsDirectBodyState>(); ClassDB::register_virtual_class<PhysicsDirectSpaceState>(); ClassDB::register_virtual_class<PhysicsShapeQueryResult>(); ScriptDebuggerRemote::resource_usage_func = _debugger_get_resource_usage; // Physics 2D GLOBAL_DEF(Physics2DServerManager::setting_property_name, "DEFAULT"); ProjectSettings::get_singleton()->set_custom_property_info(Physics2DServerManager::setting_property_name, PropertyInfo(Variant::STRING, Physics2DServerManager::setting_property_name, PROPERTY_HINT_ENUM, "DEFAULT")); Physics2DServerManager::register_server("GodotPhysics", &_createGodotPhysics2DCallback); Physics2DServerManager::set_default_server("GodotPhysics"); // Physics 3D GLOBAL_DEF(PhysicsServerManager::setting_property_name, "DEFAULT"); ProjectSettings::get_singleton()->set_custom_property_info(PhysicsServerManager::setting_property_name, PropertyInfo(Variant::STRING, PhysicsServerManager::setting_property_name, PROPERTY_HINT_ENUM, "DEFAULT")); PhysicsServerManager::register_server("GodotPhysics", &_createGodotPhysicsCallback); PhysicsServerManager::set_default_server("GodotPhysics"); } void unregister_server_types() { memdelete(shader_types); } void register_server_singletons() { Engine::get_singleton()->add_singleton(Engine::Singleton("VisualServer", VisualServer::get_singleton())); Engine::get_singleton()->add_singleton(Engine::Singleton("AudioServer", AudioServer::get_singleton())); Engine::get_singleton()->add_singleton(Engine::Singleton("PhysicsServer", PhysicsServer::get_singleton())); Engine::get_singleton()->add_singleton(Engine::Singleton("Physics2DServer", Physics2DServer::get_singleton())); Engine::get_singleton()->add_singleton(Engine::Singleton("ARVRServer", ARVRServer::get_singleton())); }
Revert " Deprecated Godot 3D physics engine"
Revert " Deprecated Godot 3D physics engine" This reverts commit 5de5a4140b9a397935737c6ce0088602be6840d7. @reduz still intends to rework it in the future, and it's convenient to test if issues are specific to Bullet or not, so we keep it around for the time being.
C++
mit
ex/godot,akien-mga/godot,BastiaanOlij/godot,godotengine/godot,Shockblast/godot,ex/godot,ex/godot,firefly2442/godot,firefly2442/godot,BastiaanOlij/godot,akien-mga/godot,Valentactive/godot,josempans/godot,vnen/godot,guilhermefelipecgs/godot,guilhermefelipecgs/godot,godotengine/godot,groud/godot,okamstudio/godot,Paulloz/godot,Shockblast/godot,DmitriySalnikov/godot,vkbsb/godot,okamstudio/godot,honix/godot,firefly2442/godot,honix/godot,honix/godot,DmitriySalnikov/godot,BastiaanOlij/godot,firefly2442/godot,sanikoyes/godot,BastiaanOlij/godot,vnen/godot,guilhermefelipecgs/godot,sanikoyes/godot,Shockblast/godot,pkowal1982/godot,BastiaanOlij/godot,pkowal1982/godot,groud/godot,DmitriySalnikov/godot,DmitriySalnikov/godot,honix/godot,ZuBsPaCe/godot,sanikoyes/godot,Zylann/godot,godotengine/godot,vnen/godot,pkowal1982/godot,Zylann/godot,groud/godot,Shockblast/godot,akien-mga/godot,okamstudio/godot,Valentactive/godot,MarianoGnu/godot,vnen/godot,okamstudio/godot,Paulloz/godot,vnen/godot,groud/godot,BastiaanOlij/godot,Paulloz/godot,josempans/godot,guilhermefelipecgs/godot,ZuBsPaCe/godot,josempans/godot,pkowal1982/godot,Shockblast/godot,ZuBsPaCe/godot,honix/godot,josempans/godot,DmitriySalnikov/godot,Valentactive/godot,godotengine/godot,josempans/godot,vkbsb/godot,vnen/godot,Paulloz/godot,guilhermefelipecgs/godot,josempans/godot,okamstudio/godot,vkbsb/godot,Faless/godot,groud/godot,Faless/godot,Zylann/godot,MarianoGnu/godot,ex/godot,Zylann/godot,vkbsb/godot,DmitriySalnikov/godot,firefly2442/godot,vnen/godot,Faless/godot,vkbsb/godot,pkowal1982/godot,Paulloz/godot,Faless/godot,Valentactive/godot,vkbsb/godot,sanikoyes/godot,Faless/godot,okamstudio/godot,vkbsb/godot,ex/godot,okamstudio/godot,MarianoGnu/godot,ex/godot,MarianoGnu/godot,MarianoGnu/godot,vnen/godot,ZuBsPaCe/godot,Shockblast/godot,firefly2442/godot,ZuBsPaCe/godot,okamstudio/godot,groud/godot,akien-mga/godot,sanikoyes/godot,sanikoyes/godot,pkowal1982/godot,okamstudio/godot,godotengine/godot,Zylann/godot,ex/godot,MarianoGnu/godot,Faless/godot,guilhermefelipecgs/godot,vkbsb/godot,Valentactive/godot,MarianoGnu/godot,godotengine/godot,josempans/godot,pkowal1982/godot,josempans/godot,godotengine/godot,Shockblast/godot,firefly2442/godot,guilhermefelipecgs/godot,BastiaanOlij/godot,sanikoyes/godot,akien-mga/godot,BastiaanOlij/godot,ZuBsPaCe/godot,akien-mga/godot,pkowal1982/godot,Paulloz/godot,akien-mga/godot,Shockblast/godot,ex/godot,Zylann/godot,Faless/godot,Valentactive/godot,Faless/godot,ZuBsPaCe/godot,MarianoGnu/godot,firefly2442/godot,guilhermefelipecgs/godot,Zylann/godot,sanikoyes/godot,akien-mga/godot,Valentactive/godot,godotengine/godot,honix/godot,DmitriySalnikov/godot,Zylann/godot,Paulloz/godot,okamstudio/godot,ZuBsPaCe/godot,Valentactive/godot
8d48570e8182c309972ee49252ee742fc7eb3053
simple-consistency-stress-test.cc
simple-consistency-stress-test.cc
// Copyright (c) 2012, Cornell University // 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 HyperDex 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. // The purpose of this test is to expose consistency errors. // C #include <cstdlib> #include <stdint.h> // Popt #include <popt.h> // C++ #include <iostream> // STL #include <map> #include <tr1/memory> #include <vector> // po6 #include <po6/threads/barrier.h> #include <po6/threads/mutex.h> #include <po6/threads/thread.h> // e #include <e/guard.h> // HyperClient #include <hyperclient.h> static int64_t window = 128; static int64_t repetitions = 1024; static int64_t threads = 16; static const char* space = "consistency"; static const char* host = "127.0.0.1"; static uint16_t port = 1234; static std::auto_ptr<po6::threads::barrier> barrier; static po6::threads::mutex results_lock; static int done = 0; static std::map<hyperclient_returncode, uint64_t> failed_puts; static std::map<hyperclient_returncode, uint64_t> failed_loops; static std::map<hyperclient_returncode, uint64_t> ops; static uint64_t failed_writes = 0; static uint64_t inconsistencies = 0; extern "C" { static struct poptOption popts[] = { POPT_AUTOHELP {"window-size", 'w', POPT_ARG_LONG, &window, 'w', "the number of sequential keys which will be used for the test", "keys"}, {"repetitiions", 'r', POPT_ARG_LONG, &repetitions, 'r', "the number of tests which will be run before exiting", "number"}, {"threads", 't', POPT_ARG_LONG, &threads, 't', "the number of threads which will check for inconsistencies", "number"}, {"space", 's', POPT_ARG_STRING, &space, 's', "the HyperDex space to use", "space"}, {"host", 'h', POPT_ARG_STRING, &host, 'h', "the IP address of the coordinator", "IP"}, {"port", 'p', POPT_ARG_LONG, &port, 'p', "the port number of the coordinator", "port"}, POPT_TABLEEND }; } // extern "C" static void writer_thread(); static void reader_thread(); int main(int argc, const char* argv[]) { poptContext poptcon; poptcon = poptGetContext(NULL, argc, (const char**) argv, popts, POPT_CONTEXT_POSIXMEHARDER); e::guard g = e::makeguard(poptFreeContext, poptcon); g.use_variable(); int rc; while ((rc = poptGetNextOpt(poptcon)) != -1) { switch (rc) { case 'w': if (window < 0) { std::cerr << "window-size must be >= 0" << std::endl; return EXIT_FAILURE; } break; case 'r': if (repetitions < 0) { std::cerr << "repetitions must be >= 0" << std::endl; return EXIT_FAILURE; } break; case 't': if (threads < 0) { std::cerr << "threads must be >= 0" << std::endl; return EXIT_FAILURE; } break; case 's': break; case 'h': break; case 'p': break; case POPT_ERROR_NOARG: case POPT_ERROR_BADOPT: case POPT_ERROR_BADNUMBER: case POPT_ERROR_OVERFLOW: std::cerr << poptStrerror(rc) << " " << poptBadOption(poptcon, 0) << std::endl; return EXIT_FAILURE; case POPT_ERROR_OPTSTOODEEP: case POPT_ERROR_BADQUOTE: case POPT_ERROR_ERRNO: default: std::cerr << "logic error in argument parsing" << std::endl; return EXIT_FAILURE; } } barrier.reset(new po6::threads::barrier(threads + 1)); po6::threads::thread writer(writer_thread); writer.start(); std::vector<std::tr1::shared_ptr<po6::threads::thread> > readers; for (int64_t i = 0; i < threads; ++i) { std::tr1::shared_ptr<po6::threads::thread> tptr(new po6::threads::thread(reader_thread)); readers.push_back(tptr); tptr->start(); } writer.join(); bool success = __sync_bool_compare_and_swap(&done, 0, 1); assert(success); for (int64_t i = 0; i < threads; ++i) { readers[i]->join(); } po6::threads::mutex::hold hold(&results_lock); typedef std::map<hyperclient_returncode, uint64_t>::iterator result_iter_t; std::cout << "Failed puts:" << std::endl; for (result_iter_t o = failed_puts.begin(); o != failed_puts.end(); ++o) { std::cout << o->first << "\t" << o->second << std::endl; } std::cout << std::endl << "Failed loops:" << std::endl; for (result_iter_t o = failed_loops.begin(); o != failed_loops.end(); ++o) { std::cout << o->first << "\t" << o->second << std::endl; } std::cout << std::endl << "Normal ops:" << std::endl; for (result_iter_t o = ops.begin(); o != ops.end(); ++o) { std::cout << o->first << "\t" << o->second << std::endl; } std::cout << std::endl << "failed writes: " << failed_writes << std::endl << "Inconsistencies: " << inconsistencies << std::endl; return EXIT_SUCCESS; } static void writer_thread() { std::map<hyperclient_returncode, uint64_t> lfailed_puts; std::map<hyperclient_returncode, uint64_t> lfailed_loops; std::map<hyperclient_returncode, uint64_t> lops; uint64_t lfailed_writes = 0; hyperclient cl(host, port); bool fail = false; for (int64_t i = 0; i < window; ++i) { int64_t key = htobe64(i); int64_t did; hyperclient_returncode dstatus; const char* keystr = reinterpret_cast<const char*>(&key); did = cl.del(space, keystr, sizeof(key), &dstatus); if (did < 0) { std::cerr << "delete failed with " << dstatus << std::endl; fail = true; break; } int64_t lid; hyperclient_returncode lstatus; lid = cl.loop(-1, &lstatus); if (lid < 0) { std::cerr << "loop failed with " << lstatus << std::endl; fail = true; break; } assert(lid == did); if (dstatus != HYPERCLIENT_SUCCESS && dstatus != HYPERCLIENT_NOTFOUND) { std::cerr << "delete returned " << dstatus << std::endl; fail = true; break; } } barrier->wait(); if (fail) { std::cerr << "the above errors are fatal" << std::endl; return; } std::cout << "starting the consistency stress test" << std::endl; for (int64_t r = 0; r < repetitions; ++r) { for (int64_t i = 0; i < window; ++i) { uint64_t count = 0; for (count = 0; count < 65536; ++count) { int64_t key = htobe64(i); int64_t val = htobe64(r); int64_t pid; hyperclient_attribute attr; hyperclient_returncode pstatus; const char* keystr = reinterpret_cast<const char*>(&key); attr.attr = "repetition"; attr.value = reinterpret_cast<const char*>(&val); attr.value_sz = sizeof(val); pid = cl.put(space, keystr, sizeof(key), &attr, 1, &pstatus); if (pid < 0) { ++lfailed_puts[pstatus]; continue; } int64_t lid; hyperclient_returncode lstatus; lid = cl.loop(-1, &lstatus); if (lid < 0) { ++lfailed_loops[lstatus]; continue; } assert(lid == pid); ++lops[pstatus]; break; } if (count == 65536) { ++lfailed_writes; } } std::cout << "done " << r << "/" << repetitions << std::endl; } po6::threads::mutex::hold hold(&results_lock); typedef std::map<hyperclient_returncode, uint64_t>::iterator result_iter_t; for (result_iter_t o = lfailed_puts.begin(); o != lfailed_puts.end(); ++o) { failed_puts[o->first] += o->second; } for (result_iter_t o = lfailed_loops.begin(); o != lfailed_loops.end(); ++o) { failed_loops[o->first] += o->second; } for (result_iter_t o = lops.begin(); o != lops.end(); ++o) { ops[o->first] += o->second; } failed_writes = lfailed_writes; } static void reader_thread() { std::map<hyperclient_returncode, uint64_t> lfailed_puts; std::map<hyperclient_returncode, uint64_t> lfailed_loops; std::map<hyperclient_returncode, uint64_t> lops; uint64_t linconsistencies = 0; hyperclient cl(host, port); barrier->wait(); while (!__sync_bool_compare_and_swap(&done, 1, 1)) { int64_t oldval = 0; for (int64_t i = window - 1; i >= 0; --i) { while (true) { int64_t key = htobe64(i); int64_t gid; hyperclient_attribute* attrs = NULL; size_t attrs_sz = 0; hyperclient_returncode gstatus; const char* keystr = reinterpret_cast<const char*>(&key); gid = cl.get(space, keystr, sizeof(key), &gstatus, &attrs, &attrs_sz); if (gid < 0) { ++lfailed_puts[gstatus]; continue; } int64_t lid; hyperclient_returncode lstatus; lid = cl.loop(-1, &lstatus); if (lid < 0) { ++lfailed_loops[lstatus]; continue; } assert(lid == gid); ++lops[gstatus]; if (gstatus == HYPERCLIENT_SUCCESS) { assert(attrs_sz == 1); assert(strcmp(attrs[0].attr, "repetition") == 0); int64_t val = 0; memmove(&val, attrs[0].value, attrs[0].value_sz); val = be64toh(val); if (val < oldval) { ++inconsistencies; } oldval = val; } if (attrs) { hyperclient_destroy_attrs(attrs, attrs_sz); } break; } } } po6::threads::mutex::hold hold(&results_lock); typedef std::map<hyperclient_returncode, uint64_t>::iterator result_iter_t; for (result_iter_t o = lfailed_puts.begin(); o != lfailed_puts.end(); ++o) { failed_puts[o->first] += o->second; } for (result_iter_t o = lfailed_loops.begin(); o != lfailed_loops.end(); ++o) { failed_loops[o->first] += o->second; } for (result_iter_t o = lops.begin(); o != lops.end(); ++o) { ops[o->first] += o->second; } inconsistencies += linconsistencies; }
// Copyright (c) 2012, Cornell University // 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 HyperDex 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. // The purpose of this test is to expose consistency errors. // C #include <cstdlib> #include <stdint.h> // Popt #include <popt.h> // C++ #include <iostream> // STL #include <map> #include <tr1/memory> #include <vector> // po6 #include <po6/threads/barrier.h> #include <po6/threads/mutex.h> #include <po6/threads/thread.h> // e #include <e/guard.h> // HyperClient #include <hyperclient.h> static int64_t window = 128; static int64_t repetitions = 1024; static int64_t threads = 16; static const char* space = "consistency"; static const char* host = "127.0.0.1"; static uint16_t port = 1234; static std::auto_ptr<po6::threads::barrier> barrier; static po6::threads::mutex results_lock; static int done = 0; static std::map<hyperclient_returncode, uint64_t> failed_puts; static std::map<hyperclient_returncode, uint64_t> failed_loops; static std::map<hyperclient_returncode, uint64_t> ops; static uint64_t failed_writes = 0; static uint64_t inconsistencies = 0; extern "C" { static struct poptOption popts[] = { POPT_AUTOHELP {"window-size", 'w', POPT_ARG_LONG, &window, 'w', "the number of sequential keys which will be used for the test", "keys"}, {"repetitiions", 'r', POPT_ARG_LONG, &repetitions, 'r', "the number of tests which will be run before exiting", "number"}, {"threads", 't', POPT_ARG_LONG, &threads, 't', "the number of threads which will check for inconsistencies", "number"}, {"space", 's', POPT_ARG_STRING, &space, 's', "the HyperDex space to use", "space"}, {"host", 'h', POPT_ARG_STRING, &host, 'h', "the IP address of the coordinator", "IP"}, {"port", 'p', POPT_ARG_LONG, &port, 'p', "the port number of the coordinator", "port"}, POPT_TABLEEND }; } // extern "C" static void writer_thread(); static void reader_thread(); int main(int argc, const char* argv[]) { poptContext poptcon; poptcon = poptGetContext(NULL, argc, (const char**) argv, popts, POPT_CONTEXT_POSIXMEHARDER); e::guard g = e::makeguard(poptFreeContext, poptcon); g.use_variable(); int rc; while ((rc = poptGetNextOpt(poptcon)) != -1) { switch (rc) { case 'w': if (window < 0) { std::cerr << "window-size must be >= 0" << std::endl; return EXIT_FAILURE; } break; case 'r': if (repetitions < 0) { std::cerr << "repetitions must be >= 0" << std::endl; return EXIT_FAILURE; } break; case 't': if (threads < 0) { std::cerr << "threads must be >= 0" << std::endl; return EXIT_FAILURE; } break; case 's': break; case 'h': break; case 'p': break; case POPT_ERROR_NOARG: case POPT_ERROR_BADOPT: case POPT_ERROR_BADNUMBER: case POPT_ERROR_OVERFLOW: std::cerr << poptStrerror(rc) << " " << poptBadOption(poptcon, 0) << std::endl; return EXIT_FAILURE; case POPT_ERROR_OPTSTOODEEP: case POPT_ERROR_BADQUOTE: case POPT_ERROR_ERRNO: default: std::cerr << "logic error in argument parsing" << std::endl; return EXIT_FAILURE; } } barrier.reset(new po6::threads::barrier(threads + 1)); po6::threads::thread writer(writer_thread); writer.start(); std::vector<std::tr1::shared_ptr<po6::threads::thread> > readers; for (int64_t i = 0; i < threads; ++i) { std::tr1::shared_ptr<po6::threads::thread> tptr(new po6::threads::thread(reader_thread)); readers.push_back(tptr); tptr->start(); } writer.join(); bool success = __sync_bool_compare_and_swap(&done, 0, 1); assert(success); for (int64_t i = 0; i < threads; ++i) { readers[i]->join(); } po6::threads::mutex::hold hold(&results_lock); typedef std::map<hyperclient_returncode, uint64_t>::iterator result_iter_t; std::cout << "Failed puts:" << std::endl; for (result_iter_t o = failed_puts.begin(); o != failed_puts.end(); ++o) { std::cout << o->first << "\t" << o->second << std::endl; } std::cout << std::endl << "Failed loops:" << std::endl; for (result_iter_t o = failed_loops.begin(); o != failed_loops.end(); ++o) { std::cout << o->first << "\t" << o->second << std::endl; } std::cout << std::endl << "Normal ops:" << std::endl; for (result_iter_t o = ops.begin(); o != ops.end(); ++o) { std::cout << o->first << "\t" << o->second << std::endl; } std::cout << std::endl << "failed writes: " << failed_writes << std::endl << "Inconsistencies: " << inconsistencies << std::endl; return EXIT_SUCCESS; } static void writer_thread() { std::map<hyperclient_returncode, uint64_t> lfailed_puts; std::map<hyperclient_returncode, uint64_t> lfailed_loops; std::map<hyperclient_returncode, uint64_t> lops; uint64_t lfailed_writes = 0; hyperclient cl(host, port); bool fail = false; for (int64_t i = 0; i < window; ++i) { int64_t key = htobe64(i); int64_t did; hyperclient_returncode dstatus; const char* keystr = reinterpret_cast<const char*>(&key); did = cl.del(space, keystr, sizeof(key), &dstatus); if (did < 0) { std::cerr << "delete failed with " << dstatus << std::endl; fail = true; break; } int64_t lid; hyperclient_returncode lstatus; lid = cl.loop(-1, &lstatus); if (lid < 0) { std::cerr << "loop failed with " << lstatus << std::endl; fail = true; break; } assert(lid == did); if (dstatus != HYPERCLIENT_SUCCESS && dstatus != HYPERCLIENT_NOTFOUND) { std::cerr << "delete returned " << dstatus << std::endl; fail = true; break; } } barrier->wait(); if (fail) { std::cerr << "the above errors are fatal" << std::endl; return; } std::cout << "starting the consistency stress test" << std::endl; for (int64_t r = 0; r < repetitions; ++r) { for (int64_t i = 0; i < window; ++i) { uint64_t count = 0; for (count = 0; count < 65536; ++count) { int64_t key = htobe64(i); int64_t val = htobe64(r); int64_t pid; hyperclient_attribute attr; hyperclient_returncode pstatus; const char* keystr = reinterpret_cast<const char*>(&key); attr.attr = "repetition"; attr.value = reinterpret_cast<const char*>(&val); attr.value_sz = sizeof(val); pid = cl.put(space, keystr, sizeof(key), &attr, 1, &pstatus); if (pid < 0) { ++lfailed_puts[pstatus]; continue; } int64_t lid; hyperclient_returncode lstatus; lid = cl.loop(-1, &lstatus); if (lid < 0) { ++lfailed_loops[lstatus]; continue; } assert(lid == pid); ++lops[pstatus]; break; } if (count == 65536) { ++lfailed_writes; } } std::cout << "done " << r << "/" << repetitions << std::endl; } po6::threads::mutex::hold hold(&results_lock); typedef std::map<hyperclient_returncode, uint64_t>::iterator result_iter_t; for (result_iter_t o = lfailed_puts.begin(); o != lfailed_puts.end(); ++o) { failed_puts[o->first] += o->second; } for (result_iter_t o = lfailed_loops.begin(); o != lfailed_loops.end(); ++o) { failed_loops[o->first] += o->second; } for (result_iter_t o = lops.begin(); o != lops.end(); ++o) { ops[o->first] += o->second; } failed_writes = lfailed_writes; } static void reader_thread() { std::map<hyperclient_returncode, uint64_t> lfailed_puts; std::map<hyperclient_returncode, uint64_t> lfailed_loops; std::map<hyperclient_returncode, uint64_t> lops; uint64_t linconsistencies = 0; hyperclient cl(host, port); barrier->wait(); while (!__sync_bool_compare_and_swap(&done, 1, 1)) { for (int64_t i = window - 1; i >= 0; --i) { int64_t oldval = 0; while (true) { int64_t key = htobe64(i); int64_t gid; hyperclient_attribute* attrs = NULL; size_t attrs_sz = 0; hyperclient_returncode gstatus; const char* keystr = reinterpret_cast<const char*>(&key); gid = cl.get(space, keystr, sizeof(key), &gstatus, &attrs, &attrs_sz); if (gid < 0) { ++lfailed_puts[gstatus]; continue; } int64_t lid; hyperclient_returncode lstatus; lid = cl.loop(-1, &lstatus); if (lid < 0) { ++lfailed_loops[lstatus]; continue; } assert(lid == gid); ++lops[gstatus]; if (gstatus == HYPERCLIENT_SUCCESS) { assert(attrs_sz == 1); assert(strcmp(attrs[0].attr, "repetition") == 0); int64_t val = 0; memmove(&val, attrs[0].value, attrs[0].value_sz); val = be64toh(val); if (val < oldval) { ++inconsistencies; } oldval = val; } if (attrs) { hyperclient_destroy_attrs(attrs, attrs_sz); } break; } } } po6::threads::mutex::hold hold(&results_lock); typedef std::map<hyperclient_returncode, uint64_t>::iterator result_iter_t; for (result_iter_t o = lfailed_puts.begin(); o != lfailed_puts.end(); ++o) { failed_puts[o->first] += o->second; } for (result_iter_t o = lfailed_loops.begin(); o != lfailed_loops.end(); ++o) { failed_loops[o->first] += o->second; } for (result_iter_t o = lops.begin(); o != lops.end(); ++o) { ops[o->first] += o->second; } inconsistencies += linconsistencies; }
Fix an inconsistency on very large windows.
Fix an inconsistency on very large windows. The problem is the following: A read of item 0 could see repetition i + 1, and then a read of item n could see repetition i. It would report this as an inconsistency. The fix is to reset the old value on every iteration of the reader threads. This is not a problem in the server, but in the consistency checker.
C++
bsd-3-clause
jtk54/HyperDex,jtk54/HyperDex,tempbottle/HyperDex,pombredanne/HyperDex,rescrv/HyperDex,tempbottle/HyperDex,rescrv/HyperDex,UIKit0/HyperDex,tempbottle/HyperDex,rescrv/HyperDex,vashstorm/HyperDex,vashstorm/HyperDex,UIKit0/HyperDex,cactorium/HyperDex,pombredanne/HyperDex,vashstorm/HyperDex,rescrv/HyperDex,cactorium/HyperDex,tempbottle/HyperDex,vashstorm/HyperDex,UIKit0/HyperDex,hyc/HyperDex,jtk54/HyperDex,hyc/HyperDex,jtk54/HyperDex,UIKit0/HyperDex,tempbottle/HyperDex,rescrv/HyperDex,jtk54/HyperDex,UIKit0/HyperDex,tempbottle/HyperDex,hyc/HyperDex,hyc/HyperDex,hyc/HyperDex,tempbottle/HyperDex,vashstorm/HyperDex,UIKit0/HyperDex,vashstorm/HyperDex,UIKit0/HyperDex,UIKit0/HyperDex,cactorium/HyperDex,rescrv/HyperDex,pombredanne/HyperDex,jtk54/HyperDex,pombredanne/HyperDex,hyc/HyperDex,pombredanne/HyperDex,pombredanne/HyperDex,cactorium/HyperDex,cactorium/HyperDex,hyc/HyperDex,jtk54/HyperDex,UIKit0/HyperDex,cactorium/HyperDex,vashstorm/HyperDex,hyc/HyperDex,pombredanne/HyperDex,vashstorm/HyperDex,cactorium/HyperDex,pombredanne/HyperDex,jtk54/HyperDex,vashstorm/HyperDex,tempbottle/HyperDex,tempbottle/HyperDex,pombredanne/HyperDex,rescrv/HyperDex,jtk54/HyperDex,cactorium/HyperDex,rescrv/HyperDex,cactorium/HyperDex,rescrv/HyperDex
ce6e2f6f81b59386b3b5f606a799fef47d994536
src/connection.hpp
src/connection.hpp
#ifndef RIAKPP_CONNECTION_HPP_ #define RIAKPP_CONNECTION_HPP_ #include <cstdint> #include <functional> #include <string> #include <system_error> namespace riak { // TODO(cristicbz): Add method for cancelling requests. Destructors should // cancel all requests then wait for them to return. class connection { public: typedef std::function<void(std::string, std::error_code)> response_handler; struct request { request() noexcept {} inline request(std::string messsage, int64_t deadline_ms, response_handler on_response) noexcept; inline void reset() noexcept; std::string message; int64_t deadline_ms = -1; response_handler on_response; }; virtual ~connection() {} inline void send(const std::string& message, int64_t deadline_ms, const response_handler& on_response); virtual void send_and_consume_request(request& request) = 0; virtual void shutdown() {} }; void connection::send(const std::string& message, int64_t deadline_ms, const response_handler& on_response) { request new_request{message, deadline_ms, on_response}; send_and_consume_request(new_request); } connection::request::request(std::string message, int64_t deadline_ms, response_handler on_response) noexcept : message{std::move(message)}, deadline_ms{deadline_ms}, on_response{std::move(on_response)} {} void connection::request::reset() noexcept { deadline_ms = -1; std::string().swap(message); response_handler().swap(on_response); } } // namespace riak #endif // #ifndef RIAKPP_CONNECTION_HPP_
#ifndef RIAKPP_CONNECTION_HPP_ #define RIAKPP_CONNECTION_HPP_ #include <cstdint> #include <functional> #include <string> #include <system_error> namespace riak { // TODO(cristicbz): Add method for cancelling requests. Destructors should // cancel all requests then wait for them to return. class connection { public: typedef std::function<void(std::string, std::error_code)> response_handler; struct request { request() noexcept {} inline request(std::string messsage, int64_t deadline_ms, response_handler on_response) noexcept; std::string message; int64_t deadline_ms = 1500; response_handler on_response; }; virtual ~connection() {} inline void send(const std::string& message, int64_t deadline_ms, const response_handler& on_response); virtual void send_and_consume_request(request& request) = 0; virtual void shutdown() {} }; void connection::send(const std::string& message, int64_t deadline_ms, const response_handler& on_response) { request new_request{message, deadline_ms, on_response}; send_and_consume_request(new_request); } connection::request::request(std::string message, int64_t deadline_ms, response_handler on_response) noexcept : message{std::move(message)}, deadline_ms{deadline_ms}, on_response{std::move(on_response)} {} } // namespace riak #endif // #ifndef RIAKPP_CONNECTION_HPP_
use deadline by default
use deadline by default
C++
apache-2.0
reinfer/riakpp,reinfer/riakpp
b956ab5c44c379aff33d55c2238c9c5d68c8f831
apps/test/Test.cpp
apps/test/Test.cpp
#include "Polaris_PCH.h" using namespace polaris; // Test agent prototype struct Agent ADD_DEBUG_INFO { tag_as_prototype; template<typename T> void Initialize() { this_component()->Initialize(); this_component()->Load_Event<ComponentType>(&Agent_Event,1,0); } static void Agent_Event(ComponentType* _this,Event_Response& response) { if (iteration() != 20) { response.next._iteration = 20; response.next._sub_iteration = 0; } else { response.next._iteration = END; response.next._sub_iteration = END; } _this->Do_Event(); } void Reschedule_Agent(int iter) { // Everything works fine until here - I think I need some way from RTTI instead of this_component() to make sure // the correct Execution_Component_Manager gets updated. this_component()->Reschedule<ComponentType>(iter, 0); } }; implementation struct Base_Agent_Implementation : public Polaris_Component<MasterType,INHERIT(Base_Agent_Implementation),Execution_Object> { void Initialize() { _data = 1; } void Do_Event() { cout <<"BASE_AGENT: event fired at " << iteration()<<endl; } m_data(int,data,NONE,NONE); }; implementation struct Derived_Agent_Implementation : public Base_Agent_Implementation<MasterType,INHERIT(Derived_Agent_Implementation)> { typedef Agent<ComponentType> this_itf; void Initialize() { _data = 5; } void Do_Event() { cout <<"DERIVED_AGENT: event fired at " << iteration()<<endl; this_itf* pthis = (this_itf*)this; pthis->Reschedule_Agent(26); } }; prototype struct Helper { tag_as_prototype; template<typename T> void Initialize() { this_component()->Initialize<T>(); } accessor(agent_container,NONE,NONE); }; implementation struct Helper_Implementation : public Polaris_Component<MasterType,INHERIT(Helper_Implementation),Execution_Object> { template<typename T> void Initialize() { typedef Agent<typename MasterType::base_agent_type> base_itf; typedef Agent<typename MasterType::derived_agent_type> derived_itf; base_itf* base_agent=(base_itf*)Allocate<typename MasterType::base_agent_type>(); base_agent->Initialize<NT>(); derived_itf* derived_agent=(derived_itf*)Allocate<typename MasterType::derived_agent_type>(); derived_agent->Initialize<NT>(); this->_agent_container.push_back((base_itf*)derived_agent); this->_agent_container.push_back(base_agent); Load_Event<ComponentType>(&Helper_Event,0,0); } static void Helper_Event(ComponentType* _this,Event_Response& response) { // Pretending here that we don't know which type derived_agent is so using interface to base type (as in activity model) typedef Agent<typename MasterType::base_agent_type> base_itf; if (iteration() < 10) { response.next._iteration = iteration()+1; response.next._sub_iteration = 0; } else if (iteration() == 10) { base_itf* b = (base_itf*)_this->_agent_container[0]; response.next._iteration = iteration()+1; response.next._sub_iteration = 0; b->Reschedule_Agent(iteration()+1); } else { base_itf* b = (base_itf*)_this->_agent_container[1]; response.next._iteration = END; response.next._sub_iteration = END; b->Reschedule_Agent(iteration()+1); } cout <<"HELPER_AGENT: event fired at " << iteration() <<", next event to fire at " << response.next._iteration<<endl; } m_container(std::vector<Agent<typename MasterType::base_agent_type>*>,agent_container,NONE,NONE); }; struct MasterType { typedef MasterType M; typedef Base_Agent_Implementation<M> base_agent_type; typedef Derived_Agent_Implementation<M> derived_agent_type; // Add all of the types used in your code here }; int main(int argc, char *argv[]) { //---------------------------------------------------------- // Initialize basic simulation Simulation_Configuration cfg; cfg.Multi_Threaded_Setup(100, 1); INITIALIZE_SIMULATION(cfg); //------------------------------------------------------------- // Initialize random variable generators GLOBALS::Normal_RNG.Initialize(); GLOBALS::Uniform_RNG.Initialize(); GLOBALS::Normal_RNG.Set_Seed<int>(); GLOBALS::Uniform_RNG.Set_Seed<int>(); //---------------------------------------------------------- // Your code here typedef Agent<MasterType::base_agent_type> base_itf; typedef Agent<MasterType::derived_agent_type> derived_itf; base_itf* agent1 = (base_itf*)Allocate<MasterType::base_agent_type>(); derived_itf* agent2 = (derived_itf*)Allocate<MasterType::derived_agent_type>(); agent1->Initialize<NT>(); agent2->Initialize<NT>(); START(); char test; cin >> test; }
#include "Antares/Antares.h" using namespace polaris; // Test agent prototype struct Agent ADD_DEBUG_INFO { tag_as_prototype; template<typename T> void Initialize() { this_component()->Initialize(); this_component()->Load_Event<ComponentType>(&Agent_Event,1,0); } static void Agent_Event(ComponentType* _this,Event_Response& response) { if (iteration() < 20) { response.next._iteration = 20; response.next._sub_iteration = 0; _this->Do_Event(response); } else { response.next._iteration = END; response.next._sub_iteration = END; } } void Reschedule_Agent(int iter) { this_component()->Reschedule<ComponentType>(iter, 0); } void Reschedule_Agent(int iter, Event_Response& response) { this_component()->Reschedule<ComponentType>(iter, 0); response.next._iteration = iter; response.next._sub_iteration = 0; } }; implementation struct Base_Agent_Implementation : public Polaris_Component<MasterType,INHERIT(Base_Agent_Implementation),Execution_Object> { void Initialize() { _data = 1; } void Do_Event(Event_Response& response) { cout <<"BASE_AGENT: event fired at " << iteration()<<", next event to fire at " << response.next._iteration<<endl; } m_data(int,data,NONE,NONE); // Functions static void Initialize_Type() { _base_agent_layer = Allocate_New_Layer<MT>(string("Base Agent")); Antares_Layer_Configuration cfg =; cfg.Configure_Dynamic_Points(); _base_agent_layer->Initialize<NT>(cfg); } // Drawing functions for 3D vehicle layer void Draw(float rotation_rad, True_Color_RGBA<NT> _color) { /// DRAW BOTTOM /// float x = _centroid._x; float y = _centroid._y; float z = 5.0f; Quad_Element_Colored bottom_elem; bottom_elem._color._r = _color._r; bottom_elem._color._g = _color._g; bottom_elem._color._b = _color._b; bottom_elem._color._a = _color._a; float cosa = cos(this->_current_link->heading()); float sina = sin(this->_current_link->heading()); bottom_elem._v1._x = x + _length/2.0 * cosa - _width/2.0 * sina ; bottom_elem._v1._y = y + _length/2.0 * sina + _width/2.0 * cosa ; bottom_elem._v1._z = z; bottom_elem._v2._x = x - _length/2.0 * cosa - _width/2.0 * sina; bottom_elem._v2._y = y - _length/2.0 * sina + _width/2.0 * cosa; bottom_elem._v2._z = z; bottom_elem._v3._x = x - _length/2.0 * cosa + _width/2.0 * sina; bottom_elem._v3._y = y - _length/2.0 * sina - _width/2.0 * cosa; bottom_elem._v3._z = z; bottom_elem._v4._x = x + _length/2.0 * cosa + _width/2.0 * sina; bottom_elem._v4._y = y + _length/2.0 * sina - _width/2.0 * cosa; bottom_elem._v4._z = z; Scale_Coordinates<MT>(bottom_elem._v1); Scale_Coordinates<MT>(bottom_elem._v2); Scale_Coordinates<MT>(bottom_elem._v3); Scale_Coordinates<MT>(bottom_elem._v4); _vehicles_layer->Push_Element<Regular_Element>(&bottom_elem); /// DRAW TOP /// Quad_Element_Colored top_elem; top_elem._color._r = _color._r; top_elem._color._g = _color._g; top_elem._color._b = _color._b; top_elem._color._a = _color._a; top_elem._v1._x = x + (_length/2.0- 30.0) * cosa - _width/2.0 * sina ; top_elem._v1._y = y + (_length/2.0- 30.0) * sina + _width/2.0 * cosa; top_elem._v1._z = z + _height; top_elem._v2._x = x - _length/2.0 * cosa - _width/2.0 * sina ; top_elem._v2._y = y - _length/2.0 * sina + _width/2.0 * cosa; top_elem._v2._z = z + _height; top_elem._v3._x = x - _length/2.0 * cosa + _width/2.0 * sina ; top_elem._v3._y = y - _length/2.0 * sina - _width/2.0 * cosa; top_elem._v3._z = z + _height; top_elem._v4._x = x + (_length/2.0 - 30.0) * cosa + _width/2.0 * sina ; top_elem._v4._y = y + (_length/2.0 - 30.0) * sina - _width/2.0 * cosa; top_elem._v4._z = z + _height; Scale_Coordinates<MT>(top_elem._v1); Scale_Coordinates<MT>(top_elem._v2); Scale_Coordinates<MT>(top_elem._v3); Scale_Coordinates<MT>(top_elem._v4); _vehicles_layer->Push_Element<Regular_Element>(&top_elem); /// DRAW FRONT /// Quad_Element_Colored front_elem; front_elem._color._r = _color._r; front_elem._color._g = _color._g; front_elem._color._b = _color._b; front_elem._color._a = _color._a; front_elem._v1._x = x + _length/2.0 * cosa - _width/2.0 * sina; //_length/2.0; front_elem._v1._y = y + _length/2.0 * sina + _width/2.0 * cosa; //_width/2.0; front_elem._v1._z = z; front_elem._v2._x = x + (_length/2.0 - 15.0) * cosa - _width/2.0 * sina; //(_length/2.0 - 15.0) front_elem._v2._y = y + (_length/2.0 - 15.0) * sina + _width/2.0 * cosa;//_width/2.0; front_elem._v2._z = z + _height/2.0; front_elem._v3._x = x + (_length/2.0 - 15.0) * cosa + _width/2.0 * sina;//_length/2.0 - 15.0; front_elem._v3._y = y + (_length/2.0 - 15.0) * sina - _width/2.0 * cosa;//-_width/2.0; front_elem._v3._z = z + _height/2.0; front_elem._v4._x = x + _length/2.0 * cosa + _width/2.0 * sina; //_length/2.0; front_elem._v4._y = y + _length/2.0 * sina - _width/2.0 * cosa; //-_width/2.0; front_elem._v4._z = z; Scale_Coordinates<MT>(front_elem._v1); Scale_Coordinates<MT>(front_elem._v2); Scale_Coordinates<MT>(front_elem._v3); Scale_Coordinates<MT>(front_elem._v4); _vehicles_layer->Push_Element<Regular_Element>(&front_elem); /// DRAW FRONT /// Quad_Element_Colored front_window_elem; front_window_elem._color._r = 170; front_window_elem._color._g = 170; front_window_elem._color._b = 255; front_window_elem._color._a = 255; front_window_elem._v1._x = x + (_length/2.0 - 15.0) * cosa - _width/2.0 * sina;//_length/2.0 - 15.0; front_window_elem._v1._y = y + (_length/2.0 - 15.0) * sina + _width/2.0 * cosa;//_width/2.0; front_window_elem._v1._z = z + _height/2.0; front_window_elem._v2._x = x + (_length/2.0 - 30.0) * cosa - _width/2.0 * sina;//_length/2.0 - 30.0; front_window_elem._v2._y = y + (_length/2.0 - 30.0) * sina + _width/2.0 * cosa;//_width/2.0; front_window_elem._v2._z = z + _height; front_window_elem._v3._x = x + (_length/2.0 - 30.0) * cosa + _width/2.0 * sina;//_length/2.0 - 30.0; front_window_elem._v3._y = y + (_length/2.0 - 30.0) * sina - _width/2.0 * cosa;//- _width/2.0; front_window_elem._v3._z = z + _height; front_window_elem._v4._x = x + (_length/2.0 - 15.0) * cosa + _width/2.0 * sina;//_length/2.0 - 15.0; front_window_elem._v4._y = y + (_length/2.0 - 15.0) * sina - _width/2.0 * cosa;//- _width/2.0; front_window_elem._v4._z = z + _height/2.0; Scale_Coordinates<MT>(front_window_elem._v1); Scale_Coordinates<MT>(front_window_elem._v2); Scale_Coordinates<MT>(front_window_elem._v3); Scale_Coordinates<MT>(front_window_elem._v4); _vehicles_layer->Push_Element<Regular_Element>(&front_window_elem); /// DRAW PASSENGER SIDE /// Quad_Element_Colored pass_elem; pass_elem._color._r = _color._r; pass_elem._color._g = _color._g; pass_elem._color._b = _color._b-20; pass_elem._color._a = _color._a; pass_elem._v1._x = x + _length/2.0 * cosa + _width/2.0 * sina; //_length/2.0; pass_elem._v1._y = y + _length/2.0 * sina - _width/2.0 * cosa;//- _width/2.0; pass_elem._v1._z = z; pass_elem._v2._x = x + (_length/2.0 - 30.0) * cosa + _width/2.0 * sina;//_length/2.0 - 30.0; pass_elem._v2._y = y + (_length/2.0 - 30.0) * sina - _width/2.0 * cosa;//- _width/2.0; pass_elem._v2._z = z + _height; pass_elem._v3._x = x - _length/2.0 * cosa + _width/2.0 * sina;// - _length/2.0; pass_elem._v3._y = y - _length/2.0 * sina - _width/2.0 * cosa;// - _width/2.0; pass_elem._v3._z = z + _height; pass_elem._v4._x = x - _length/2.0 * cosa + _width/2.0 * sina;//- _length/2.0; pass_elem._v4._y = y - _length/2.0 * sina - _width/2.0 * cosa;//- _width/2.0; pass_elem._v4._z = z; Scale_Coordinates<MT>(pass_elem._v1); Scale_Coordinates<MT>(pass_elem._v2); Scale_Coordinates<MT>(pass_elem._v3); Scale_Coordinates<MT>(pass_elem._v4); _vehicles_layer->Push_Element<Regular_Element>(&pass_elem); /// DRAW DRIVER SIDE /// Quad_Element_Colored driver_elem; driver_elem._color._r = _color._r; driver_elem._color._g = _color._g; driver_elem._color._b = _color._b-20; driver_elem._color._a = _color._a; driver_elem._v1._x = x + _length/2.0 * cosa - _width/2.0 * sina; //_length/2.0; driver_elem._v1._y = y + _length/2.0 * sina + _width/2.0 * cosa; //_width/2.0; driver_elem._v1._z = z; driver_elem._v2._x = x + (_length/2.0 - 30.0) * cosa - _width/2.0 * sina; //_length/2.0 - 30.0; driver_elem._v2._y = y + (_length/2.0 - 30.0) * sina + _width/2.0 * cosa; //_width/2.0; driver_elem._v2._z = z + _height; driver_elem._v3._x = x - _length/2.0 * cosa - _width/2.0 * sina; //- _length/2.0; driver_elem._v3._y = y - _length/2.0 * sina + _width/2.0 * cosa; //_width/2.0; driver_elem._v3._z = z + _height; driver_elem._v4._x = x - _length/2.0 * cosa - _width/2.0 * sina; //- _length/2.0; driver_elem._v4._y = y - _length/2.0 * sina + _width/2.0 * cosa; //_width/2.0; driver_elem._v4._z = z; Scale_Coordinates<MT>(driver_elem._v1); Scale_Coordinates<MT>(driver_elem._v2); Scale_Coordinates<MT>(driver_elem._v3); Scale_Coordinates<MT>(driver_elem._v4); _vehicles_layer->Push_Element<Regular_Element>(&driver_elem); /// DRAW BACK SIDE /// Quad_Element_Colored back_elem; back_elem._color._r = _color._r; back_elem._color._g = _color._g; back_elem._color._b = _color._b; back_elem._color._a = _color._a; back_elem._v1._x = x - _length/2.0 * cosa - _width/2.0 * sina; //- _length/2.0; back_elem._v1._y = y - _length/2.0 * sina + _width/2.0 * cosa; //_width/2.0; back_elem._v1._z = z; back_elem._v2._x = x - _length/2.0 * cosa + _width/2.0 * sina; //- _length/2.0; back_elem._v2._y = y - _length/2.0 * sina - _width/2.0 * cosa; //- _width/2.0; back_elem._v2._z = z; back_elem._v3._x = x - _length/2.0 * cosa + _width/2.0 * sina; //- _length/2.0; back_elem._v3._y = y - _length/2.0 * sina - _width/2.0 * cosa; //- _width/2.0; back_elem._v3._z = z + _height/2.0; back_elem._v4._x = x - _length/2.0 * cosa - _width/2.0 * sina; //- _length/2.0; back_elem._v4._y = y - _length/2.0 * sina + _width/2.0 * cosa; //_width/2.0; back_elem._v4._z = z + _height/2.0; Scale_Coordinates<MT>(back_elem._v1); Scale_Coordinates<MT>(back_elem._v2); Scale_Coordinates<MT>(back_elem._v3); Scale_Coordinates<MT>(back_elem._v4); _vehicles_layer->Push_Element<Regular_Element>(&back_elem); /// DRAW BACK SIDE WINDOW /// Quad_Element_Colored back_window_elem; back_window_elem._color._r = 170; back_window_elem._color._g = 170; back_window_elem._color._b = 255; back_window_elem._color._a = 255; back_window_elem._v1._x = x - _length/2.0 * cosa - _width/2.0 * sina; //- _length/2.0; back_window_elem._v1._y = y - _length/2.0 * sina + _width/2.0 * cosa; //_width/2.0; back_window_elem._v1._z = z + _height/2.0; back_window_elem._v2._x = x - _length/2.0 * cosa + _width/2.0 * sina; //- _length/2.0; back_window_elem._v2._y = y - _length/2.0 * sina - _width/2.0 * cosa; //- _width/2.0; back_window_elem._v2._z = z + _height/2.0; back_window_elem._v3._x = x - _length/2.0 * cosa + _width/2.0 * sina; //- _length/2.0; back_window_elem._v3._y = y - _length/2.0 * sina - _width/2.0 * cosa; //- _width/2.0; back_window_elem._v3._z = z + _height; back_window_elem._v4._x = x - _length/2.0 * cosa - _width/2.0 * sina; //- _length/2.0; back_window_elem._v4._y = y - _length/2.0 * sina + _width/2.0 * cosa; //_width/2.0; back_window_elem._v4._z = z + _height; Scale_Coordinates<MT>(back_window_elem._v1); Scale_Coordinates<MT>(back_window_elem._v2); Scale_Coordinates<MT>(back_window_elem._v3); Scale_Coordinates<MT>(back_window_elem._v4); _vehicles_layer->Push_Element<Regular_Element>(&back_window_elem); } static Antares_Layer<typename MasterType::antares_layer_type>* _base_agent_layer; }; implementation struct Derived_Agent_Implementation : public Base_Agent_Implementation<MasterType,INHERIT(Derived_Agent_Implementation)> { typedef Agent<ComponentType> this_itf; void Initialize() { _data = 5; } void Do_Event(Event_Response& response) { cout <<"DERIVED_AGENT: event fired at " << iteration()<<", next event to fire at " << response.next._iteration<<endl; this_itf* pthis = (this_itf*)this; pthis->Reschedule_Agent(iteration()+5, response); } }; prototype struct Helper { tag_as_prototype; template<typename T> void Initialize() { this_component()->Initialize<T>(); } accessor(agent_container,NONE,NONE); }; implementation struct Helper_Implementation : public Polaris_Component<MasterType,INHERIT(Helper_Implementation),Execution_Object> { template<typename T> void Initialize() { typedef Agent<typename MasterType::base_agent_type> base_itf; typedef Agent<typename MasterType::derived_agent_type> derived_itf; base_itf* base_agent=(base_itf*)Allocate<typename MasterType::base_agent_type>(); base_agent->Initialize<NT>(); derived_itf* derived_agent=(derived_itf*)Allocate<typename MasterType::derived_agent_type>(); derived_agent->Initialize<NT>(); this->_agent_container.push_back((base_itf*)derived_agent); this->_agent_container.push_back(base_agent); Load_Event<ComponentType>(&Helper_Event,0,0); } static void Helper_Event(ComponentType* _this,Event_Response& response) { // Pretending here that we don't know which type derived_agent is so using interface to base type (as in activity model) typedef Agent<typename MasterType::base_agent_type> base_itf; if (iteration() < 10) { response.next._iteration = iteration()+1; response.next._sub_iteration = 0; } else if (iteration() == 10) { base_itf* b = (base_itf*)_this->_agent_container[0]; response.next._iteration = iteration()+1; response.next._sub_iteration = 0; b->Reschedule_Agent(iteration()+1); } else { base_itf* b = (base_itf*)_this->_agent_container[1]; response.next._iteration = END; response.next._sub_iteration = END; b->Reschedule_Agent(iteration()+1); } cout <<"HELPER_AGENT: event fired at " << iteration() <<", next event to fire at " << response.next._iteration<<endl; } m_container(std::vector<Agent<typename MasterType::base_agent_type>*>,agent_container,NONE,NONE); }; struct MasterType { //================================================================================= // REQUIRED ANTARES TYPES typedef Conductor_Implementation<MasterType> conductor_type; typedef Control_Panel_Implementation<MasterType> control_panel_type; typedef Time_Panel_Implementation<MasterType> time_panel_type; typedef Information_Panel_Implementation<MasterType> information_panel_type; typedef Canvas_Implementation<MasterType> canvas_type; typedef Antares_Layer_Implementation<MasterType> antares_layer_type; typedef Layer_Options_Implementation<MasterType> layer_options_type; typedef Attributes_Panel_Implementation<MasterType> attributes_panel_type; typedef Control_Dialog_Implementation<MasterType> control_dialog_type; typedef Information_Page_Implementation<MasterType> information_page_type; typedef Splash_Panel_Implementation<MasterType> splash_panel_type; //================================================================================= typedef MasterType M; typedef Base_Agent_Implementation<M> base_agent_type; typedef Derived_Agent_Implementation<M> derived_agent_type; typedef Helper_Implementation<M> helper_type; // Add all of the types used in your code here }; int main(int argc, char *argv[]) { //---------------------------------------------------------- // Initialize basic simulation Simulation_Configuration cfg; cfg.Multi_Threaded_Setup(100, 1); INITIALIZE_SIMULATION(cfg); // initialize the visualizer environment START_UI(MasterType,0,0,1000,1000); //---------------------------------------------------------- // Your code here typedef Helper<MasterType::helper_type> helper_itf; helper_itf* main_agent = (helper_itf*)Allocate<MasterType::helper_type>(); main_agent->Initialize<NT>(); START(); char test; cin >> test; }
Update to test application
Update to test application
C++
bsd-3-clause
anl-tracc/polaris,Symcies/polaris,anl-tracc/polaris,anl-tracc/polaris,Symcies/polaris,Symcies/polaris,anl-tracc/polaris
55e7f46889a6d0a9496ba50faa4764a40b5dbcf2
source/algorithms/class_fdmrg.cpp
source/algorithms/class_fdmrg.cpp
// // Created by david on 2018-01-31. // #include "class_fdmrg.h" #include <config/nmspc_settings.h> #include <tensors/state/class_state_finite.h> #include <tools/common/io.h> #include <tools/common/log.h> #include <tools/common/fmt.h> #include <tools/common/prof.h> #include <tools/finite/io.h> #include <tools/finite/measure.h> #include <tools/finite/ops.h> #include <tools/finite/opt.h> class_fdmrg::class_fdmrg(std::shared_ptr<h5pp::File> h5pp_file_) : class_algorithm_finite(std::move(h5pp_file_), AlgorithmType::fDMRG) { tools::log->trace("Constructing class_fdmrg"); } void class_fdmrg::resume() { // Resume can imply many things // 1) Resume a simulation which terminated prematurely // 2) Resume a previously successful simulation. This may be desireable if the config // wants something that is not present in the file. // a) A certain number of states // b) A state inside of a particular energy window // c) The ground or "roof" states // To guide the behavior, we check the setting ResumePolicy. auto state_prefix = tools::common::io::h5resume::find_resumable_state(*h5pp_file, algo_type); if(state_prefix.empty()) throw std::runtime_error("Could not resume: no valid state candidates found for resume"); tools::log->info("Resuming state [{}]", state_prefix); tools::finite::io::h5resume::load_tensors(*h5pp_file, state_prefix, tensors, status); // Our first task is to decide on a state name for the newly loaded state // The simplest is to inferr it from the state prefix itself auto name = tools::common::io::h5resume::extract_state_name(state_prefix); // Initialize a custom task list std::list<fdmrg_task> task_list; if(not status.algorithm_has_finished) { // This could be a checkpoint state // Simply "continue" the algorithm until convergence if(name.find("emax") != std::string::npos) task_list.emplace_back(fdmrg_task::FIND_HIGHEST_STATE); else if(name.find("emin") != std::string::npos) task_list.emplace_back(fdmrg_task::FIND_GROUND_STATE); else throw std::runtime_error(fmt::format("Unrecognized state name for fdmrg: [{}]", name)); task_list.emplace_back(fdmrg_task::POST_DEFAULT); run_task_list(task_list); } // If we reached this point the current state has finished for one reason or another. // TODO: We may still have some more things to do, e.g. the config may be asking for more states } void class_fdmrg::run_task_list(std::list<fdmrg_task> &task_list) { while(not task_list.empty()) { auto task = task_list.front(); switch(task) { case fdmrg_task::INIT_RANDOMIZE_MODEL: randomize_model(); break; case fdmrg_task::INIT_RANDOMIZE_INTO_PRODUCT_STATE: randomize_state(ResetReason::INIT, StateType::RANDOM_PRODUCT_STATE); break; case fdmrg_task::INIT_RANDOMIZE_INTO_ENTANGLED_STATE: randomize_state(ResetReason::INIT, StateType::RANDOM_ENTANGLED_STATE); break; case fdmrg_task::INIT_BOND_DIM_LIMITS: init_bond_dimension_limits(); break; case fdmrg_task::INIT_WRITE_MODEL: write_to_file(StorageReason::MODEL); break; case fdmrg_task::INIT_CLEAR_STATUS: status.clear(); break; case fdmrg_task::INIT_DEFAULT: run_preprocessing(); break; case fdmrg_task::FIND_GROUND_STATE: ritz = StateRitz::SR; state_name = "state_e_min"; run_algorithm(); break; case fdmrg_task::FIND_HIGHEST_STATE: ritz = StateRitz::LR; state_name = "state_e_max"; run_algorithm(); break; case fdmrg_task::POST_WRITE_RESULT: write_to_file(StorageReason::FINISHED); break; case fdmrg_task::POST_PRINT_RESULT: print_status_full(); break; case fdmrg_task::POST_DEFAULT: run_postprocessing(); break; } task_list.pop_front(); } } void class_fdmrg::run_default_task_list() { std::list<fdmrg_task> default_task_list = { fdmrg_task::INIT_DEFAULT, fdmrg_task::FIND_GROUND_STATE, fdmrg_task::POST_DEFAULT, }; run_task_list(default_task_list); if(not default_task_list.empty()) { for(auto &task : default_task_list) tools::log->critical("Unfinished task: {}", enum2str(task)); throw std::runtime_error("Simulation ended with unfinished tasks"); } } void class_fdmrg::run_preprocessing() { tools::log->info("Running {} preprocessing", algo_name); tools::common::profile::t_pre->tic(); status.clear(); randomize_model(); // First use of random! init_bond_dimension_limits(); randomize_state(ResetReason::INIT, settings::strategy::initial_state); auto spin_components = tools::finite::measure::spin_components(*tensors.state); tools::log->info("Initial spin components: {}", spin_components); tools::common::profile::t_pre->toc(); tools::log->info("Finished {} preprocessing", algo_name); } void class_fdmrg::run_algorithm() { if(state_name.empty()) state_name = ritz == StateRitz::SR ? "state_emin" : "state_emax"; tools::common::profile::reset_for_run_algorithm(); tools::log->info("Starting {} algorithm with model [{}] for state [{}]", algo_name, enum2str(settings::model::model_type), state_name); tools::common::profile::t_sim->tic(); while(true) { single_fdmrg_step(); print_status_update(); write_to_file(); check_convergence(); update_bond_dimension_limit(); // Will update bond dimension if the state precision is being limited by bond dimension try_projection(); reduce_mpo_energy(); // It's important not to perform the last move. // That last state would not get optimized if(tensors.position_is_any_edge()) { if(status.iter >= settings::fdmrg::max_iters) { stop_reason = StopReason::MAX_ITERS; break; } if(status.algorithm_has_succeeded) { stop_reason = StopReason::SUCCEEDED; break; } if(status.algorithm_has_to_stop) { stop_reason = StopReason::SATURATED; break; } if(status.num_resets > settings::strategy::max_resets) { stop_reason = StopReason::MAX_RESET; break; } } // Update record holder if(tensors.position_is_any_edge() or tensors.measurements.energy_variance_per_site) { tools::log->trace("Updating variance record holder"); auto var = tools::finite::measure::energy_variance_per_site(tensors); if(var < status.lowest_recorded_variance_per_site) status.lowest_recorded_variance_per_site = var; } tools::log->trace("Finished step {}, iter {}, pos {}, dir {}", status.step, status.iter, status.position, status.direction); move_center_point(); } tools::log->info("Finished {} simulation of state [{}] -- stop reason: {}", algo_name, state_name, enum2str(stop_reason)); status.algorithm_has_finished = true; tools::common::profile::t_sim->toc(); } void class_fdmrg::single_fdmrg_step() { /*! * \fn void single_DMRG_step(std::string ritz) */ tools::log->trace("Starting single fdmrg step with ritz [{}]", enum2str(ritz)); tensors.activate_sites(settings::precision::max_size_part_diag, settings::strategy::multisite_max_sites); Eigen::Tensor<Scalar, 3> multisite_tensor = tools::finite::opt::find_ground_state(tensors, ritz); tensors.merge_multisite_tensor(multisite_tensor, status.chi_lim); status.wall_time = tools::common::profile::t_tot->get_measured_time(); status.algo_time = tools::common::profile::t_sim->get_measured_time(); } void class_fdmrg::check_convergence() { tools::common::profile::t_con->tic(); if(tensors.position_is_any_edge()) { check_convergence_variance(); check_convergence_entg_entropy(); } status.algorithm_has_converged = status.variance_mpo_has_converged and status.entanglement_has_converged; status.algorithm_has_saturated = status.variance_mpo_saturated_for >= min_saturation_iters and status.entanglement_saturated_for >= min_saturation_iters; status.algorithm_has_succeeded = status.algorithm_has_converged and status.algorithm_has_saturated; status.algorithm_has_got_stuck = status.algorithm_has_saturated and not status.algorithm_has_succeeded; if(tensors.state->position_is_any_edge()) status.algorithm_has_stuck_for = status.algorithm_has_got_stuck ? status.algorithm_has_stuck_for + 1 : 0; status.algorithm_has_to_stop = status.algorithm_has_stuck_for >= max_stuck_iters; if(tensors.state->position_is_any_edge()) { tools::log->debug("Algorithm has converged: {}", status.algorithm_has_converged); tools::log->debug("Algorithm has saturated: {}", status.algorithm_has_saturated); tools::log->debug("Algorithm has succeeded: {}", status.algorithm_has_succeeded); tools::log->debug("Algorithm has got stuck: {}", status.algorithm_has_got_stuck); tools::log->debug("Algorithm has stuck for: {}", status.algorithm_has_stuck_for); tools::log->debug("Algorithm has to stop : {}", status.algorithm_has_to_stop); } tools::common::profile::t_con->toc(); } bool class_fdmrg::cfg_algorithm_is_on() { return settings::fdmrg::on; } long class_fdmrg::cfg_chi_lim_max() { return settings::fdmrg::chi_lim_max; } size_t class_fdmrg::cfg_print_freq() { return settings::fdmrg::print_freq; } bool class_fdmrg::cfg_chi_lim_grow() { return settings::fdmrg::chi_lim_grow; } long class_fdmrg::cfg_chi_lim_init() { return settings::fdmrg::chi_lim_init; } bool class_fdmrg::cfg_store_wave_function() { return settings::fdmrg::store_wavefn; }
// // Created by david on 2018-01-31. // #include "class_fdmrg.h" #include <config/nmspc_settings.h> #include <tensors/state/class_state_finite.h> #include <tools/common/io.h> #include <tools/common/log.h> #include <tools/common/fmt.h> #include <tools/common/prof.h> #include <tools/finite/io.h> #include <tools/finite/measure.h> #include <tools/finite/ops.h> #include <tools/finite/opt.h> class_fdmrg::class_fdmrg(std::shared_ptr<h5pp::File> h5pp_file_) : class_algorithm_finite(std::move(h5pp_file_), AlgorithmType::fDMRG) { tools::log->trace("Constructing class_fdmrg"); } void class_fdmrg::resume() { // Resume can imply many things // 1) Resume a simulation which terminated prematurely // 2) Resume a previously successful simulation. This may be desireable if the config // wants something that is not present in the file. // a) A certain number of states // b) A state inside of a particular energy window // c) The ground or "roof" states // To guide the behavior, we check the setting ResumePolicy. auto state_prefix = tools::common::io::h5resume::find_resumable_state(*h5pp_file, algo_type); if(state_prefix.empty()) throw std::runtime_error("Could not resume: no valid state candidates found for resume"); tools::log->info("Resuming state [{}]", state_prefix); tools::finite::io::h5resume::load_tensors(*h5pp_file, state_prefix, tensors, status); // Our first task is to decide on a state name for the newly loaded state // The simplest is to inferr it from the state prefix itself auto name = tools::common::io::h5resume::extract_state_name(state_prefix); // Initialize a custom task list std::list<fdmrg_task> task_list; if(not status.algorithm_has_finished) { // This could be a checkpoint state // Simply "continue" the algorithm until convergence if(name.find("emax") != std::string::npos) task_list.emplace_back(fdmrg_task::FIND_HIGHEST_STATE); else if(name.find("emin") != std::string::npos) task_list.emplace_back(fdmrg_task::FIND_GROUND_STATE); else throw std::runtime_error(fmt::format("Unrecognized state name for fdmrg: [{}]", name)); task_list.emplace_back(fdmrg_task::POST_DEFAULT); run_task_list(task_list); } // If we reached this point the current state has finished for one reason or another. // TODO: We may still have some more things to do, e.g. the config may be asking for more states } void class_fdmrg::run_task_list(std::list<fdmrg_task> &task_list) { while(not task_list.empty()) { auto task = task_list.front(); switch(task) { case fdmrg_task::INIT_RANDOMIZE_MODEL: randomize_model(); break; case fdmrg_task::INIT_RANDOMIZE_INTO_PRODUCT_STATE: randomize_state(ResetReason::INIT, StateType::RANDOM_PRODUCT_STATE); break; case fdmrg_task::INIT_RANDOMIZE_INTO_ENTANGLED_STATE: randomize_state(ResetReason::INIT, StateType::RANDOM_ENTANGLED_STATE); break; case fdmrg_task::INIT_BOND_DIM_LIMITS: init_bond_dimension_limits(); break; case fdmrg_task::INIT_WRITE_MODEL: write_to_file(StorageReason::MODEL); break; case fdmrg_task::INIT_CLEAR_STATUS: status.clear(); break; case fdmrg_task::INIT_DEFAULT: run_preprocessing(); break; case fdmrg_task::FIND_GROUND_STATE: ritz = StateRitz::SR; state_name = "state_e_min"; run_algorithm(); break; case fdmrg_task::FIND_HIGHEST_STATE: ritz = StateRitz::LR; state_name = "state_e_max"; run_algorithm(); break; case fdmrg_task::POST_WRITE_RESULT: write_to_file(StorageReason::FINISHED); break; case fdmrg_task::POST_PRINT_RESULT: print_status_full(); break; case fdmrg_task::POST_DEFAULT: run_postprocessing(); break; } task_list.pop_front(); } } void class_fdmrg::run_default_task_list() { std::list<fdmrg_task> default_task_list = { fdmrg_task::INIT_DEFAULT, fdmrg_task::FIND_GROUND_STATE, fdmrg_task::POST_DEFAULT, }; run_task_list(default_task_list); if(not default_task_list.empty()) { for(auto &task : default_task_list) tools::log->critical("Unfinished task: {}", enum2str(task)); throw std::runtime_error("Simulation ended with unfinished tasks"); } } void class_fdmrg::run_preprocessing() { tools::log->info("Running {} preprocessing", algo_name); tools::common::profile::t_pre->tic(); status.clear(); randomize_model(); // First use of random! init_bond_dimension_limits(); randomize_state(ResetReason::INIT, settings::strategy::initial_state); auto spin_components = tools::finite::measure::spin_components(*tensors.state); tools::log->info("Initial spin components: {}", spin_components); tools::common::profile::t_pre->toc(); tools::log->info("Finished {} preprocessing", algo_name); } void class_fdmrg::run_algorithm() { if(state_name.empty()) state_name = ritz == StateRitz::SR ? "state_emin" : "state_emax"; tools::common::profile::reset_for_run_algorithm(); tools::log->info("Starting {} algorithm with model [{}] for state [{}]", algo_name, enum2str(settings::model::model_type), state_name); tools::common::profile::t_sim->tic(); while(true) { single_fdmrg_step(); print_status_update(); write_to_file(); check_convergence(); update_bond_dimension_limit(); // Will update bond dimension if the state precision is being limited by bond dimension try_projection(); reduce_mpo_energy(); // It's important not to perform the last move. // That last state would not get optimized if(tensors.position_is_any_edge()) { if(status.iter >= settings::fdmrg::max_iters) { stop_reason = StopReason::MAX_ITERS; break; } if(status.algorithm_has_succeeded) { stop_reason = StopReason::SUCCEEDED; break; } if(status.algorithm_has_to_stop) { stop_reason = StopReason::SATURATED; break; } if(status.num_resets > settings::strategy::max_resets) { stop_reason = StopReason::MAX_RESET; break; } } // Update record holder if(tensors.position_is_any_edge() or tensors.measurements.energy_variance_per_site) { tools::log->trace("Updating variance record holder"); auto var = tools::finite::measure::energy_variance_per_site(tensors); if(var < status.lowest_recorded_variance_per_site) status.lowest_recorded_variance_per_site = var; } tools::log->trace("Finished step {}, iter {}, pos {}, dir {}", status.step, status.iter, status.position, status.direction); move_center_point(); } tools::log->info("Finished {} simulation of state [{}] -- stop reason: {}", algo_name, state_name, enum2str(stop_reason)); status.algorithm_has_finished = true; tools::common::profile::t_sim->toc(); } void class_fdmrg::single_fdmrg_step() { /*! * \fn void single_DMRG_step(std::string ritz) */ tools::log->trace("Starting single fdmrg step with ritz [{}]", enum2str(ritz)); tensors.activate_sites(settings::precision::max_size_part_diag, settings::strategy::multisite_max_sites); Eigen::Tensor<Scalar, 3> multisite_tensor = tools::finite::opt::find_ground_state(tensors, ritz); if constexpr (settings::debug) tools::log->debug("Variance after opt: {:.8f}",std::log10(tools::finite::measure::energy_variance_per_site(multisite_tensor,tensors))); tensors.merge_multisite_tensor(multisite_tensor, status.chi_lim); if constexpr (settings::debug) tools::log->debug("Variance after svd: {:.8f} | trunc: {}",std::log10(tools::finite::measure::energy_variance_per_site(tensors)), tools::finite::measure::truncation_errors_active(*tensors.state)); status.wall_time = tools::common::profile::t_tot->get_measured_time(); status.algo_time = tools::common::profile::t_sim->get_measured_time(); } void class_fdmrg::check_convergence() { tools::common::profile::t_con->tic(); if(tensors.position_is_any_edge()) { check_convergence_variance(); check_convergence_entg_entropy(); } status.algorithm_has_converged = status.variance_mpo_has_converged and status.entanglement_has_converged; status.algorithm_has_saturated = status.variance_mpo_saturated_for >= min_saturation_iters and status.entanglement_saturated_for >= min_saturation_iters; status.algorithm_has_succeeded = status.algorithm_has_converged and status.algorithm_has_saturated; status.algorithm_has_got_stuck = status.algorithm_has_saturated and not status.algorithm_has_succeeded; if(tensors.state->position_is_any_edge()) status.algorithm_has_stuck_for = status.algorithm_has_got_stuck ? status.algorithm_has_stuck_for + 1 : 0; status.algorithm_has_to_stop = status.algorithm_has_stuck_for >= max_stuck_iters; if(tensors.state->position_is_any_edge()) { tools::log->debug("Algorithm has converged: {}", status.algorithm_has_converged); tools::log->debug("Algorithm has saturated: {}", status.algorithm_has_saturated); tools::log->debug("Algorithm has succeeded: {}", status.algorithm_has_succeeded); tools::log->debug("Algorithm has got stuck: {}", status.algorithm_has_got_stuck); tools::log->debug("Algorithm has stuck for: {}", status.algorithm_has_stuck_for); tools::log->debug("Algorithm has to stop : {}", status.algorithm_has_to_stop); } tools::common::profile::t_con->toc(); } bool class_fdmrg::cfg_algorithm_is_on() { return settings::fdmrg::on; } long class_fdmrg::cfg_chi_lim_max() { return settings::fdmrg::chi_lim_max; } size_t class_fdmrg::cfg_print_freq() { return settings::fdmrg::print_freq; } bool class_fdmrg::cfg_chi_lim_grow() { return settings::fdmrg::chi_lim_grow; } long class_fdmrg::cfg_chi_lim_init() { return settings::fdmrg::chi_lim_init; } bool class_fdmrg::cfg_store_wave_function() { return settings::fdmrg::store_wavefn; }
Print variance change in debug mode to detect svd errors
Print variance change in debug mode to detect svd errors Former-commit-id: bd2d4b19c32488afeb210134b69c02b7122d304d
C++
mit
DavidAce/DMRG,DavidAce/DMRG,DavidAce/DMRG,DavidAce/DMRG
0e1d9038cc94ca63b2c36d3cade5a1ddb6452e30
src/core/Debug.cpp
src/core/Debug.cpp
/* (c) Copyright 2012-2013 DirectFB integrated media GmbH (c) Copyright 2001-2013 The world wide DirectFB Open Source Community (directfb.org) (c) Copyright 2000-2004 Convergence (integrated media) GmbH All rights reserved. Written by Denis Oliver Kropp <[email protected]>, Andreas Hundt <[email protected]>, Sven Neumann <[email protected]>, Ville Syrjälä <[email protected]> and Claudio Ciccani <[email protected]>. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //#define DIRECT_ENABLE_DEBUG #include <config.h> #include <fusion/Debug.h> #include "Debug.h" extern "C" { #include <directfb_strings.h> #include <directfb_util.h> #include <core/core_strings.h> #include <core/surface_buffer.h> } /*********************************************************************************************************************/ // Core enums template<> ToString<CoreSurfaceTypeFlags>::ToString( const CoreSurfaceTypeFlags &flags ) { static const DirectFBCoreSurfaceTypeFlagsNames(flags_names); for (int i=0, n=0; flags_names[i].flag; i++) { if (flags & flags_names[i].flag) PrintF( "%s%s", n++ ? "," : "", flags_names[i].name ); } } // DirectFB enums template<> ToString<DFBAccelerationMask>::ToString( const DFBAccelerationMask &accel ) { static const DirectFBAccelerationMaskNames(accelerationmask_names); for (int i=0, n=0; accelerationmask_names[i].mask; i++) { if (accel & accelerationmask_names[i].mask) PrintF( "%s%s", n++ ? "," : "", accelerationmask_names[i].name ); } } template<> ToString<DFBSurfaceBlittingFlags>::ToString( const DFBSurfaceBlittingFlags &flags ) { static const DirectFBSurfaceBlittingFlagsNames(flags_names); for (int i=0, n=0; flags_names[i].flag; i++) { if (flags & flags_names[i].flag) PrintF( "%s%s", n++ ? "," : "", flags_names[i].name ); } } template<> ToString<DFBSurfaceCapabilities>::ToString( const DFBSurfaceCapabilities &caps ) { static const DirectFBSurfaceCapabilitiesNames(caps_names); for (int i=0, n=0; caps_names[i].capability; i++) { if (caps & caps_names[i].capability) PrintF( "%s%s", n++ ? "," : "", caps_names[i].name ); } } template<> ToString<DFBSurfaceDrawingFlags>::ToString( const DFBSurfaceDrawingFlags &flags ) { static const DirectFBSurfaceDrawingFlagsNames(flags_names); for (int i=0, n=0; flags_names[i].flag; i++) { if (flags & flags_names[i].flag) PrintF( "%s%s", n++ ? "," : "", flags_names[i].name ); } } template<> ToString<DFBSurfacePixelFormat>::ToString( const DFBSurfacePixelFormat &format ) { for (int i=0; dfb_pixelformat_names[i].format; i++) { if (format == dfb_pixelformat_names[i].format) { PrintF( "%s", dfb_pixelformat_names[i].name ); return; } } PrintF( "_INVALID_<0x%08x>", format ); } // DirectFB types template<> ToString<DFBDimension>::ToString( const DFBDimension &v ) { PrintF( "%dx%d", v.w, v.h ); } // CoreSurface types template<> ToString<CoreSurfaceConfig>::ToString( const CoreSurfaceConfig &config ) { int buffers = 0; if (config.caps & DSCAPS_TRIPLE) buffers = 3; else if (config.caps & DSCAPS_DOUBLE) buffers = 2; else buffers = 1; PrintF( "size:%dx%d format:%s caps:%s bufs:%d", config.size.w, config.size.h, ToString<DFBSurfacePixelFormat>(config.format).buffer(), ToString<DFBSurfaceCapabilities>(config.caps).buffer(), buffers ); } // CoreSurface objects template<> ToString<CoreSurfaceAllocation>::ToString( const CoreSurfaceAllocation &allocation ) { PrintF( "{CoreSurfaceAllocation %s [%d] type:%s resid:%lu %s}", ToString<FusionObject>(allocation.object).buffer(), allocation.index, ToString<CoreSurfaceTypeFlags>(allocation.type).buffer(), allocation.resource_id, ToString<CoreSurfaceConfig>(allocation.config).buffer() ); } template<> ToString<CoreSurfaceBuffer>::ToString( const CoreSurfaceBuffer &buffer ) { PrintF( "{CoreSurfaceBuffer %s [%d] allocs:%d type:%s resid:%lu %s}", ToString<FusionObject>(buffer.object).buffer(), buffer.index, buffer.allocs.count, ToString<CoreSurfaceTypeFlags>(buffer.type).buffer(), buffer.resource_id, ToString<CoreSurfaceConfig>(buffer.config).buffer() ); } /*********************************************************************************************************************/ extern "C" { const char * ToString_CoreSurfaceTypeFlags( CoreSurfaceTypeFlags v ) { return ToString<CoreSurfaceTypeFlags>( v ).CopyTLS(); } const char * ToString_DFBAccelerationMask( DFBAccelerationMask v ) { return ToString<DFBAccelerationMask>( v ).CopyTLS(); } const char * ToString_DFBSurfaceBlittingFlags( DFBSurfaceBlittingFlags v ) { return ToString<DFBSurfaceBlittingFlags>( v ).CopyTLS(); } const char * ToString_DFBSurfaceCapabilities( DFBSurfaceCapabilities v ) { return ToString<DFBSurfaceCapabilities>( v ).CopyTLS(); } const char * ToString_DFBSurfaceDrawingFlags( DFBSurfaceDrawingFlags v ) { return ToString<DFBSurfaceDrawingFlags>( v ).CopyTLS(); } const char * ToString_DFBSurfacePixelFormat( DFBSurfacePixelFormat v ) { return ToString<DFBSurfacePixelFormat>( v ).CopyTLS(); } const char * DFB_ToString_DFBDimension( const DFBDimension *v ) { return ToString<DFBDimension>( *v ).CopyTLS(); } const char * ToString_CoreSurfaceConfig( const CoreSurfaceConfig *v ) { return ToString<CoreSurfaceConfig>( *v ).CopyTLS(); } const char * ToString_CoreSurfaceAllocation( const CoreSurfaceAllocation *v ) { return ToString<CoreSurfaceAllocation>( *v ).CopyTLS(); } const char * ToString_CoreSurfaceBuffer( const CoreSurfaceBuffer *v ) { return ToString<CoreSurfaceBuffer>( *v ).CopyTLS(); } }
/* (c) Copyright 2012-2013 DirectFB integrated media GmbH (c) Copyright 2001-2013 The world wide DirectFB Open Source Community (directfb.org) (c) Copyright 2000-2004 Convergence (integrated media) GmbH All rights reserved. Written by Denis Oliver Kropp <[email protected]>, Andreas Hundt <[email protected]>, Sven Neumann <[email protected]>, Ville Syrjälä <[email protected]> and Claudio Ciccani <[email protected]>. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //#define DIRECT_ENABLE_DEBUG #include <config.h> #include <fusion/Debug.h> #include "Debug.h" extern "C" { #include <directfb_strings.h> #include <directfb_util.h> #include <core/core_strings.h> #include <core/surface_buffer.h> } /*********************************************************************************************************************/ // Core enums template<> ToString<CoreSurfaceTypeFlags>::ToString( const CoreSurfaceTypeFlags &flags ) { static const DirectFBCoreSurfaceTypeFlagsNames(flags_names); for (int i=0, n=0; flags_names[i].flag; i++) { if (flags & flags_names[i].flag) PrintF( "%s%s", n++ ? "," : "", flags_names[i].name ); } } // DirectFB enums template<> ToString<DFBAccelerationMask>::ToString( const DFBAccelerationMask &accel ) { static const DirectFBAccelerationMaskNames(accelerationmask_names); for (int i=0, n=0; accelerationmask_names[i].mask; i++) { if (accel & accelerationmask_names[i].mask) PrintF( "%s%s", n++ ? "," : "", accelerationmask_names[i].name ); } } template<> ToString<DFBSurfaceBlittingFlags>::ToString( const DFBSurfaceBlittingFlags &flags ) { static const DirectFBSurfaceBlittingFlagsNames(flags_names); for (int i=0, n=0; flags_names[i].flag; i++) { if (flags & flags_names[i].flag) PrintF( "%s%s", n++ ? "," : "", flags_names[i].name ); } } template<> ToString<DFBSurfaceCapabilities>::ToString( const DFBSurfaceCapabilities &caps ) { static const DirectFBSurfaceCapabilitiesNames(caps_names); for (int i=0, n=0; caps_names[i].capability; i++) { if (caps & caps_names[i].capability) PrintF( "%s%s", n++ ? "," : "", caps_names[i].name ); } } template<> ToString<DFBSurfaceDrawingFlags>::ToString( const DFBSurfaceDrawingFlags &flags ) { static const DirectFBSurfaceDrawingFlagsNames(flags_names); for (int i=0, n=0; flags_names[i].flag; i++) { if (flags & flags_names[i].flag) PrintF( "%s%s", n++ ? "," : "", flags_names[i].name ); } } template<> ToString<DFBSurfacePixelFormat>::ToString( const DFBSurfacePixelFormat &format ) { for (int i=0; dfb_pixelformat_names[i].format; i++) { if (format == dfb_pixelformat_names[i].format) { PrintF( "%s", dfb_pixelformat_names[i].name ); return; } } PrintF( "_INVALID_<0x%08x>", format ); } template<> ToString<DFBSurfacePorterDuffRule>::ToString( const DFBSurfacePorterDuffRule &rule ) { static const DirectFBPorterDuffRuleNames(rules_names); for (int i=0; rules_names[i].rule; i++) { if (rule == rules_names[i].rule) { PrintF( "%s", rules_names[i].name ); return; } } if (rule == DSPD_NONE) PrintF( "NONE" ); else PrintF( "_INVALID_<0x%08x>", rule ); } // DirectFB types template<> ToString<DFBDimension>::ToString( const DFBDimension &v ) { PrintF( "%dx%d", v.w, v.h ); } // CoreSurface types template<> ToString<CoreSurfaceConfig>::ToString( const CoreSurfaceConfig &config ) { int buffers = 0; if (config.caps & DSCAPS_TRIPLE) buffers = 3; else if (config.caps & DSCAPS_DOUBLE) buffers = 2; else buffers = 1; PrintF( "size:%dx%d format:%s caps:%s bufs:%d", config.size.w, config.size.h, ToString<DFBSurfacePixelFormat>(config.format).buffer(), ToString<DFBSurfaceCapabilities>(config.caps).buffer(), buffers ); } // CoreSurface objects template<> ToString<CoreSurfaceAllocation>::ToString( const CoreSurfaceAllocation &allocation ) { PrintF( "{CoreSurfaceAllocation %s [%d] type:%s resid:%lu %s}", ToString<FusionObject>(allocation.object).buffer(), allocation.index, ToString<CoreSurfaceTypeFlags>(allocation.type).buffer(), allocation.resource_id, ToString<CoreSurfaceConfig>(allocation.config).buffer() ); } template<> ToString<CoreSurfaceBuffer>::ToString( const CoreSurfaceBuffer &buffer ) { PrintF( "{CoreSurfaceBuffer %s [%d] allocs:%d type:%s resid:%lu %s}", ToString<FusionObject>(buffer.object).buffer(), buffer.index, buffer.allocs.count, ToString<CoreSurfaceTypeFlags>(buffer.type).buffer(), buffer.resource_id, ToString<CoreSurfaceConfig>(buffer.config).buffer() ); } /*********************************************************************************************************************/ extern "C" { const char * ToString_CoreSurfaceTypeFlags( CoreSurfaceTypeFlags v ) { return ToString<CoreSurfaceTypeFlags>( v ).CopyTLS(); } const char * ToString_DFBAccelerationMask( DFBAccelerationMask v ) { return ToString<DFBAccelerationMask>( v ).CopyTLS(); } const char * ToString_DFBSurfaceBlittingFlags( DFBSurfaceBlittingFlags v ) { return ToString<DFBSurfaceBlittingFlags>( v ).CopyTLS(); } const char * ToString_DFBSurfaceCapabilities( DFBSurfaceCapabilities v ) { return ToString<DFBSurfaceCapabilities>( v ).CopyTLS(); } const char * ToString_DFBSurfaceDrawingFlags( DFBSurfaceDrawingFlags v ) { return ToString<DFBSurfaceDrawingFlags>( v ).CopyTLS(); } const char * ToString_DFBSurfacePixelFormat( DFBSurfacePixelFormat v ) { return ToString<DFBSurfacePixelFormat>( v ).CopyTLS(); } const char * DFB_ToString_DFBDimension( const DFBDimension *v ) { return ToString<DFBDimension>( *v ).CopyTLS(); } const char * ToString_CoreSurfaceConfig( const CoreSurfaceConfig *v ) { return ToString<CoreSurfaceConfig>( *v ).CopyTLS(); } const char * ToString_CoreSurfaceAllocation( const CoreSurfaceAllocation *v ) { return ToString<CoreSurfaceAllocation>( *v ).CopyTLS(); } const char * ToString_CoreSurfaceBuffer( const CoreSurfaceBuffer *v ) { return ToString<CoreSurfaceBuffer>( *v ).CopyTLS(); } }
Add ToString<DFBSurfacePorterDuffRule>.
Debug: Add ToString<DFBSurfacePorterDuffRule>.
C++
lgpl-2.1
deniskropp/DirectFB,kevleyski/directfb,sklnet/DirectFB,djbclark/directfb-core-DirectFB,lancebaiyouview/DirectFB,jcdubois/DirectFB,kaostao/directfb,dfbdok/DirectFB1,kevleyski/DirectFB-1,sklnet/DirectFB,kevleyski/directfb,mtsekm/test,DirectFB/directfb,kevleyski/directfb,kaostao/directfb,kevleyski/DirectFB-1,djbclark/directfb-core-DirectFB,kevleyski/directfb,mtsekm/test,djbclark/directfb-core-DirectFB,Distrotech/DirectFB,kaostao/directfb,kevleyski/DirectFB-1,sklnet/DirectFB,Distrotech/DirectFB,lancebaiyouview/DirectFB,djbclark/directfb-core-DirectFB,deniskropp/DirectFB,lancebaiyouview/DirectFB,Distrotech/DirectFB,jcdubois/DirectFB,dfbdok/DirectFB1,kevleyski/DirectFB-1,jcdubois/DirectFB,DirectFB/directfb,DirectFB/directfb,sklnet/DirectFB,lancebaiyouview/DirectFB,deniskropp/DirectFB,deniskropp/DirectFB,mtsekm/test,dfbdok/DirectFB1
55dca3667a5bfbe8a2b6ce232295465b393558db
lib/qsort.tas.cpp
lib/qsort.tas.cpp
#include "common.th" #define elem(Dest, Base, Index) \ Dest <- E * Index ; \ Dest <- Dest + Base ; \ // #define swap(i0, i1) \ pushall(c,d,e,f) \ f <- i0 \ g <- i1 \ call(do_swap) \ popall(c,d,e,f) \ // do_swap: l <- c k <- e o <- o - e c <- o + 1 elem(d,l,f) /* E is already width */ call(memcpy) elem(c,l,f) elem(d,l,g) e <- k call(memcpy) elem(c,l,g) d <- o + 1 e <- k call(memcpy) o <- o + k ret // c <- base // d <- number of elements // e <- size of element // f <- comparator #define SI M #define II J #define PI H #define LI I #define BASE C .global qsort qsort: pushall(g,h,i,j,k,l,m) h <- d < 2 // test for base case jnzrel(h,L_qsort_done) PI <- d >> 1 // partition index LI <- d - 1 // last index // partitioning swap(h,i) SI <- 0 // store index II <- 0 // i index L_qsort_partition: k <- II < LI jzrel(k,L_qsort_partition_done) pushall(c) elem(k, BASE, II) elem(d, BASE, LI) c <- k callr(f) // call comparator popall(c) k <- b < 0 jzrel(k,L_qsort_noswap) swap(II,SI) SI <- SI + 1 L_qsort_noswap: II <- II + 1 goto(L_qsort_partition) L_qsort_partition_done: swap(SI,LI) PI <- SI // recursive cases -------------------- // save argument registers m <- c j <- e k <- f // C is already elem(c,c,0) d <- PI // E is already width // F is already callback call(qsort) // restore argument registers c <- m d <- LI - PI e <- j f <- k PI <- PI + 1 elem(k,BASE,PI) c <- k // TODO tail call call(qsort) L_qsort_done: popall(g,h,i,j,k,l,m) ret
#include "common.th" #define elem(Dest, Base, Index) \ Dest <- E * Index ; \ Dest <- Dest + Base ; \ // #define swap(i0, i1) \ pushall(c,d,e,f) ; \ f <- i0 ; \ g <- i1 ; \ call(do_swap) ; \ popall(c,d,e,f) \ // do_swap: l <- c k <- e o <- o - e c <- o + 1 elem(d,l,f) /* E is already width */ call(memcpy) elem(c,l,f) elem(d,l,g) e <- k call(memcpy) elem(c,l,g) d <- o + 1 e <- k call(memcpy) o <- o + k ret // c <- base // d <- number of elements // e <- size of element // f <- comparator #define SI M #define II J #define PI H #define LI I #define BASE C .global qsort qsort: pushall(g,h,i,j,k,l,m) h <- d < 2 // test for base case jnzrel(h,L_qsort_done) PI <- d >> 1 // partition index LI <- d - 1 // last index // partitioning swap(h,i) SI <- 0 // store index II <- 0 // i index L_qsort_partition: k <- II < LI jzrel(k,L_qsort_partition_done) pushall(c) elem(k, BASE, II) elem(d, BASE, LI) c <- k callr(f) // call comparator popall(c) k <- b < 0 jzrel(k,L_qsort_noswap) swap(II,SI) SI <- SI + 1 L_qsort_noswap: II <- II + 1 goto(L_qsort_partition) L_qsort_partition_done: swap(SI,LI) PI <- SI // recursive cases -------------------- // save argument registers m <- c j <- e k <- f // C is already elem(c,c,0) d <- PI // E is already width // F is already callback call(qsort) // restore argument registers c <- m d <- LI - PI e <- j f <- k PI <- PI + 1 elem(k,BASE,PI) c <- k // TODO tail call call(qsort) L_qsort_done: popall(g,h,i,j,k,l,m) ret
Add explicit statement separators to qsort
Add explicit statement separators to qsort
C++
mit
kulp/tenyr,kulp/tenyr,kulp/tenyr
00d40b5018b0f7621646489a996bdacadaf1c9be
src/css_parser.cxx
src/css_parser.cxx
/* * Simple parser for CSS (Cascading Style Sheets). * * author: Max Kellermann <[email protected]> */ #include "css_parser.hxx" #include "css_syntax.hxx" #include "pool.hxx" #include "istream/istream.hxx" #include "util/CharUtil.hxx" enum CssParserState { CSS_PARSER_NONE, CSS_PARSER_BLOCK, CSS_PARSER_CLASS_NAME, CSS_PARSER_XML_ID, CSS_PARSER_DISCARD_QUOTED, CSS_PARSER_PROPERTY, CSS_PARSER_POST_PROPERTY, CSS_PARSER_PRE_VALUE, CSS_PARSER_VALUE, CSS_PARSER_PRE_URL, CSS_PARSER_URL, /** * An '@' was found. Feeding characters into "name". */ CSS_PARSER_AT, CSS_PARSER_PRE_IMPORT, CSS_PARSER_IMPORT, }; struct CssParser { struct pool *pool; bool block; struct istream *input; off_t position; const CssParserHandler *handler; void *handler_ctx; /* internal state */ CssParserState state; char quote; off_t name_start; size_t name_length; char name[64]; size_t value_length; char value[64]; off_t url_start; size_t url_length; char url[1024]; CssParser(struct pool *pool, struct istream *input, bool block, const CssParserHandler *handler, void *handler_ctx); }; static const char * skip_whitespace(const char *p, const char *end) { while (p < end && IsWhitespaceOrNull(*p)) ++p; return p; } gcc_pure static bool at_url_start(const char *p, size_t length) { return length >= 4 && memcmp(p + length - 4, "url(", 4) == 0 && (/* just url(): */ length == 4 || /* url() after another token: */ IsWhitespaceOrNull(p[length - 5])); } static size_t css_parser_feed(CssParser *parser, const char *start, size_t length) { assert(parser != nullptr); assert(parser->input != nullptr); assert(start != nullptr); assert(length > 0); const char *buffer = start, *end = start + length, *p; size_t nbytes; CssParserValue url; while (buffer < end) { switch (parser->state) { case CSS_PARSER_NONE: do { switch (*buffer) { case '{': /* start of block */ parser->state = CSS_PARSER_BLOCK; if (parser->handler->block != nullptr) parser->handler->block(parser->handler_ctx); break; case '.': if (parser->handler->class_name != nullptr) { parser->state = CSS_PARSER_CLASS_NAME; parser->name_start = parser->position + (off_t)(buffer - start) + 1; parser->name_length = 0; } break; case '#': if (parser->handler->xml_id != nullptr) { parser->state = CSS_PARSER_XML_ID; parser->name_start = parser->position + (off_t)(buffer - start) + 1; parser->name_length = 0; } break; case '@': if (parser->handler->import != nullptr) { parser->state = CSS_PARSER_AT; parser->name_length = 0; } break; } ++buffer; } while (buffer < end && parser->state == CSS_PARSER_NONE); break; case CSS_PARSER_CLASS_NAME: do { if (!is_css_nmchar(*buffer)) { if (parser->name_length > 0) { CssParserValue name = { .start = parser->name_start, .end = parser->position + (off_t)(buffer - start), }; strref_set(&name.value, parser->name, parser->name_length); parser->handler->class_name(&name, parser->handler_ctx); } parser->state = CSS_PARSER_NONE; break; } if (parser->name_length < sizeof(parser->name) - 1) parser->name[parser->name_length++] = *buffer; ++buffer; } while (buffer < end); break; case CSS_PARSER_XML_ID: do { if (!is_css_nmchar(*buffer)) { if (parser->name_length > 0) { CssParserValue name = { .start = parser->name_start, .end = parser->position + (off_t)(buffer - start), }; strref_set(&name.value, parser->name, parser->name_length); parser->handler->xml_id(&name, parser->handler_ctx); } parser->state = CSS_PARSER_NONE; break; } if (parser->name_length < sizeof(parser->name) - 1) parser->name[parser->name_length++] = *buffer; ++buffer; } while (buffer < end); break; case CSS_PARSER_BLOCK: do { switch (*buffer) { case '}': /* end of block */ if (parser->block) break; parser->state = CSS_PARSER_NONE; break; case ':': /* colon introduces property value */ parser->state = CSS_PARSER_PRE_VALUE; parser->name_length = 0; break; case '\'': case '"': parser->state = CSS_PARSER_DISCARD_QUOTED; parser->quote = *buffer; break; default: if (is_css_ident_start(*buffer) && parser->handler->property_keyword != nullptr) { parser->state = CSS_PARSER_PROPERTY; parser->name_start = parser->position + (off_t)(buffer - start); parser->name[0] = *buffer; parser->name_length = 1; } } ++buffer; } while (buffer < end && parser->state == CSS_PARSER_BLOCK); break; case CSS_PARSER_DISCARD_QUOTED: p = (const char *)memchr(buffer, parser->quote, end - buffer); if (p == nullptr) { nbytes = end - start; parser->position += (off_t)nbytes; return nbytes; } parser->state = CSS_PARSER_BLOCK; buffer = p + 1; break; case CSS_PARSER_PROPERTY: while (buffer < end) { if (!is_css_ident_char(*buffer)) { parser->state = CSS_PARSER_POST_PROPERTY; break; } if (parser->name_length < sizeof(parser->name) - 1) parser->name[parser->name_length++] = *buffer; ++buffer; } break; case CSS_PARSER_POST_PROPERTY: do { switch (*buffer) { case '}': /* end of block */ if (parser->block) break; parser->state = CSS_PARSER_NONE; break; case ':': /* colon introduces property value */ parser->state = CSS_PARSER_PRE_VALUE; break; case '\'': case '"': parser->state = CSS_PARSER_DISCARD_QUOTED; parser->quote = *buffer; break; } ++buffer; } while (buffer < end && parser->state == CSS_PARSER_BLOCK); break; case CSS_PARSER_PRE_VALUE: buffer = skip_whitespace(buffer, end); if (buffer < end) { switch (*buffer) { case '}': /* end of block */ if (parser->block) break; parser->state = CSS_PARSER_NONE; ++buffer; break; case ';': parser->state = CSS_PARSER_BLOCK; ++buffer; break; default: parser->state = CSS_PARSER_VALUE; parser->value_length = 0; } } break; case CSS_PARSER_VALUE: do { switch (*buffer) { case '}': /* end of block */ if (parser->block) break; parser->state = CSS_PARSER_NONE; break; case ';': if (parser->name_length > 0) { assert(parser->handler->property_keyword != nullptr); parser->name[parser->name_length] = 0; parser->value[parser->value_length] = 0; parser->handler->property_keyword(parser->name, parser->value, parser->name_start, parser->position + (off_t)(buffer - start) + 1, parser->handler_ctx); } parser->state = CSS_PARSER_BLOCK; break; case '\'': case '"': parser->state = CSS_PARSER_DISCARD_QUOTED; parser->quote = *buffer; break; default: if (parser->value_length >= sizeof(parser->value)) break; parser->value[parser->value_length++] = *buffer; if (parser->handler->url != nullptr && at_url_start(parser->value, parser->value_length)) parser->state = CSS_PARSER_PRE_URL; } ++buffer; } while (buffer < end && parser->state == CSS_PARSER_VALUE); break; case CSS_PARSER_PRE_URL: buffer = skip_whitespace(buffer, end); if (buffer < end) { switch (*buffer) { case '}': /* end of block */ if (parser->block) break; parser->state = CSS_PARSER_NONE; ++buffer; break; case '\'': case '"': parser->state = CSS_PARSER_URL; parser->quote = *buffer++; parser->url_start = parser->position + (off_t)(buffer - start); parser->url_length = 0; break; default: parser->state = CSS_PARSER_BLOCK; } } break; case CSS_PARSER_URL: p = (const char *)memchr(buffer, parser->quote, end - buffer); if (p == nullptr) { size_t copy = end - buffer; if (copy > sizeof(parser->url) - parser->url_length) copy = sizeof(parser->url) - parser->url_length; memcpy(parser->url + parser->url_length, buffer, copy); parser->url_length += copy; nbytes = end - start; parser->position += (off_t)nbytes; return nbytes; } /* found the end of the URL - copy the rest, and invoke the handler method "url()" */ nbytes = p - buffer; if (nbytes > sizeof(parser->url) - parser->url_length) nbytes = sizeof(parser->url) - parser->url_length; memcpy(parser->url + parser->url_length, buffer, nbytes); parser->url_length += nbytes; buffer = p + 1; parser->state = CSS_PARSER_BLOCK; url.start = parser->url_start; url.end = parser->position + (off_t)(p - start); strref_set(&url.value, parser->url, parser->url_length); parser->handler->url(&url, parser->handler_ctx); if (parser->input == nullptr) return 0; break; case CSS_PARSER_AT: do { if (!is_css_nmchar(*buffer)) { if (parser->name_length == 6 && memcmp(parser->name, "import", 6) == 0) parser->state = CSS_PARSER_PRE_IMPORT; else parser->state = CSS_PARSER_NONE; break; } if (parser->name_length < sizeof(parser->name) - 1) parser->name[parser->name_length++] = *buffer; ++buffer; } while (buffer < end); break; case CSS_PARSER_PRE_IMPORT: do { if (!IsWhitespaceOrNull(*buffer)) { if (*buffer == '"') { ++buffer; parser->state = CSS_PARSER_IMPORT; parser->url_start = parser->position + (off_t)(buffer - start); parser->url_length = 0; } else parser->state = CSS_PARSER_NONE; break; } ++buffer; } while (buffer < end); break; case CSS_PARSER_IMPORT: p = (const char *)memchr(buffer, '"', end - buffer); if (p == nullptr) { size_t copy = end - buffer; if (copy > sizeof(parser->url) - parser->url_length) copy = sizeof(parser->url) - parser->url_length; memcpy(parser->url + parser->url_length, buffer, copy); parser->url_length += copy; nbytes = end - start; parser->position += (off_t)nbytes; return nbytes; } /* found the end of the URL - copy the rest, and invoke the handler method "import()" */ nbytes = p - buffer; if (nbytes > sizeof(parser->url) - parser->url_length) nbytes = sizeof(parser->url) - parser->url_length; memcpy(parser->url + parser->url_length, buffer, nbytes); parser->url_length += nbytes; buffer = p + 1; parser->state = CSS_PARSER_NONE; url.start = parser->url_start; url.end = parser->position + (off_t)(p - start); strref_set(&url.value, parser->url, parser->url_length); parser->handler->import(&url, parser->handler_ctx); if (parser->input == nullptr) return 0; break; } } assert(parser->input != nullptr); parser->position += length; return length; } /* * istream handler * */ static size_t css_parser_input_data(const void *data, size_t length, void *ctx) { CssParser *parser = (CssParser *)ctx; const ScopePoolRef ref(*parser->pool TRACE_ARGS); return css_parser_feed(parser, (const char *)data, length); } static void css_parser_input_eof(void *ctx) { CssParser *parser = (CssParser *)ctx; assert(parser->input != nullptr); parser->input = nullptr; parser->handler->eof(parser->handler_ctx, parser->position); pool_unref(parser->pool); } static void css_parser_input_abort(GError *error, void *ctx) { CssParser *parser = (CssParser *)ctx; assert(parser->input != nullptr); parser->input = nullptr; parser->handler->error(error, parser->handler_ctx); pool_unref(parser->pool); } static const struct istream_handler css_parser_input_handler = { .data = css_parser_input_data, .eof = css_parser_input_eof, .abort = css_parser_input_abort, }; /* * constructor * */ CssParser::CssParser(struct pool *_pool, struct istream *_input, bool _block, const CssParserHandler *_handler, void *_handler_ctx) :pool(_pool), block(_block), position(0), handler(_handler), handler_ctx(_handler_ctx), state(block ? CSS_PARSER_BLOCK : CSS_PARSER_NONE) { istream_assign_handler(&input, _input, &css_parser_input_handler, this, 0); } CssParser * css_parser_new(struct pool *pool, struct istream *input, bool block, const CssParserHandler *handler, void *handler_ctx) { assert(pool != nullptr); assert(input != nullptr); assert(handler != nullptr); assert(handler->eof != nullptr); assert(handler->error != nullptr); pool_ref(pool); return NewFromPool<CssParser>(*pool, pool, input, block, handler, handler_ctx); } void css_parser_close(CssParser *parser) { assert(parser != nullptr); assert(parser->input != nullptr); istream_close(parser->input); pool_unref(parser->pool); } void css_parser_read(CssParser *parser) { assert(parser != nullptr); assert(parser->input != nullptr); istream_read(parser->input); }
/* * Simple parser for CSS (Cascading Style Sheets). * * author: Max Kellermann <[email protected]> */ #include "css_parser.hxx" #include "css_syntax.hxx" #include "pool.hxx" #include "istream/istream.hxx" #include "util/CharUtil.hxx" #include "util/TrivialArray.hxx" #include "util/StringView.hxx" enum CssParserState { CSS_PARSER_NONE, CSS_PARSER_BLOCK, CSS_PARSER_CLASS_NAME, CSS_PARSER_XML_ID, CSS_PARSER_DISCARD_QUOTED, CSS_PARSER_PROPERTY, CSS_PARSER_POST_PROPERTY, CSS_PARSER_PRE_VALUE, CSS_PARSER_VALUE, CSS_PARSER_PRE_URL, CSS_PARSER_URL, /** * An '@' was found. Feeding characters into "name". */ CSS_PARSER_AT, CSS_PARSER_PRE_IMPORT, CSS_PARSER_IMPORT, }; struct CssParser { template<size_t max> class StringBuffer : public TrivialArray<char, max> { public: using TrivialArray<char, max>::capacity; using TrivialArray<char, max>::size; using TrivialArray<char, max>::raw; using TrivialArray<char, max>::end; size_t GetRemainingSpace() const { return capacity() - size(); } void AppendTruncated(StringView p) { size_t n = std::min(p.size, GetRemainingSpace()); std::copy_n(p.data, n, end()); this->the_size += n; } constexpr operator struct strref() const { return {size(), raw()}; } constexpr operator StringView() const { return {raw(), size()}; } gcc_pure bool Equals(StringView other) const { return other.Equals(*this); } }; struct pool *pool; bool block; struct istream *input; off_t position; const CssParserHandler *handler; void *handler_ctx; /* internal state */ CssParserState state; char quote; off_t name_start; StringBuffer<64> name_buffer; StringBuffer<64> value_buffer; off_t url_start; StringBuffer<1024> url_buffer; CssParser(struct pool *pool, struct istream *input, bool block, const CssParserHandler *handler, void *handler_ctx); }; static const char * skip_whitespace(const char *p, const char *end) { while (p < end && IsWhitespaceOrNull(*p)) ++p; return p; } gcc_pure static bool at_url_start(const char *p, size_t length) { return length >= 4 && memcmp(p + length - 4, "url(", 4) == 0 && (/* just url(): */ length == 4 || /* url() after another token: */ IsWhitespaceOrNull(p[length - 5])); } static size_t css_parser_feed(CssParser *parser, const char *start, size_t length) { assert(parser != nullptr); assert(parser->input != nullptr); assert(start != nullptr); assert(length > 0); const char *buffer = start, *end = start + length, *p; size_t nbytes; CssParserValue url; while (buffer < end) { switch (parser->state) { case CSS_PARSER_NONE: do { switch (*buffer) { case '{': /* start of block */ parser->state = CSS_PARSER_BLOCK; if (parser->handler->block != nullptr) parser->handler->block(parser->handler_ctx); break; case '.': if (parser->handler->class_name != nullptr) { parser->state = CSS_PARSER_CLASS_NAME; parser->name_start = parser->position + (off_t)(buffer - start) + 1; parser->name_buffer.clear(); } break; case '#': if (parser->handler->xml_id != nullptr) { parser->state = CSS_PARSER_XML_ID; parser->name_start = parser->position + (off_t)(buffer - start) + 1; parser->name_buffer.clear(); } break; case '@': if (parser->handler->import != nullptr) { parser->state = CSS_PARSER_AT; parser->name_buffer.clear(); } break; } ++buffer; } while (buffer < end && parser->state == CSS_PARSER_NONE); break; case CSS_PARSER_CLASS_NAME: do { if (!is_css_nmchar(*buffer)) { if (!parser->name_buffer.empty()) { CssParserValue name = { .start = parser->name_start, .end = parser->position + (off_t)(buffer - start), }; name.value = parser->name_buffer; parser->handler->class_name(&name, parser->handler_ctx); } parser->state = CSS_PARSER_NONE; break; } if (parser->name_buffer.size() < parser->name_buffer.capacity() - 1) parser->name_buffer.push_back(*buffer); ++buffer; } while (buffer < end); break; case CSS_PARSER_XML_ID: do { if (!is_css_nmchar(*buffer)) { if (!parser->name_buffer.empty()) { CssParserValue name = { .start = parser->name_start, .end = parser->position + (off_t)(buffer - start), }; name.value = parser->name_buffer; parser->handler->xml_id(&name, parser->handler_ctx); } parser->state = CSS_PARSER_NONE; break; } if (parser->name_buffer.size() < parser->name_buffer.capacity() - 1) parser->name_buffer.push_back(*buffer); ++buffer; } while (buffer < end); break; case CSS_PARSER_BLOCK: do { switch (*buffer) { case '}': /* end of block */ if (parser->block) break; parser->state = CSS_PARSER_NONE; break; case ':': /* colon introduces property value */ parser->state = CSS_PARSER_PRE_VALUE; parser->name_buffer.clear(); break; case '\'': case '"': parser->state = CSS_PARSER_DISCARD_QUOTED; parser->quote = *buffer; break; default: if (is_css_ident_start(*buffer) && parser->handler->property_keyword != nullptr) { parser->state = CSS_PARSER_PROPERTY; parser->name_start = parser->position + (off_t)(buffer - start); parser->name_buffer.clear(); parser->name_buffer.push_back(*buffer); } } ++buffer; } while (buffer < end && parser->state == CSS_PARSER_BLOCK); break; case CSS_PARSER_DISCARD_QUOTED: p = (const char *)memchr(buffer, parser->quote, end - buffer); if (p == nullptr) { nbytes = end - start; parser->position += (off_t)nbytes; return nbytes; } parser->state = CSS_PARSER_BLOCK; buffer = p + 1; break; case CSS_PARSER_PROPERTY: while (buffer < end) { if (!is_css_ident_char(*buffer)) { parser->state = CSS_PARSER_POST_PROPERTY; break; } if (parser->name_buffer.size() < parser->name_buffer.capacity() - 1) parser->name_buffer.push_back(*buffer); ++buffer; } break; case CSS_PARSER_POST_PROPERTY: do { switch (*buffer) { case '}': /* end of block */ if (parser->block) break; parser->state = CSS_PARSER_NONE; break; case ':': /* colon introduces property value */ parser->state = CSS_PARSER_PRE_VALUE; break; case '\'': case '"': parser->state = CSS_PARSER_DISCARD_QUOTED; parser->quote = *buffer; break; } ++buffer; } while (buffer < end && parser->state == CSS_PARSER_BLOCK); break; case CSS_PARSER_PRE_VALUE: buffer = skip_whitespace(buffer, end); if (buffer < end) { switch (*buffer) { case '}': /* end of block */ if (parser->block) break; parser->state = CSS_PARSER_NONE; ++buffer; break; case ';': parser->state = CSS_PARSER_BLOCK; ++buffer; break; default: parser->state = CSS_PARSER_VALUE; parser->value_buffer.clear(); } } break; case CSS_PARSER_VALUE: do { switch (*buffer) { case '}': /* end of block */ if (parser->block) break; parser->state = CSS_PARSER_NONE; break; case ';': if (!parser->name_buffer.empty()) { assert(parser->handler->property_keyword != nullptr); parser->name_buffer.push_back('\0'); parser->value_buffer.push_back('\0'); parser->handler->property_keyword(parser->name_buffer.raw(), parser->value_buffer.raw(), parser->name_start, parser->position + (off_t)(buffer - start) + 1, parser->handler_ctx); } parser->state = CSS_PARSER_BLOCK; break; case '\'': case '"': parser->state = CSS_PARSER_DISCARD_QUOTED; parser->quote = *buffer; break; default: if (parser->value_buffer.full()) break; parser->value_buffer.push_back(*buffer); if (parser->handler->url != nullptr && at_url_start(parser->value_buffer.raw(), parser->value_buffer.size())) parser->state = CSS_PARSER_PRE_URL; } ++buffer; } while (buffer < end && parser->state == CSS_PARSER_VALUE); break; case CSS_PARSER_PRE_URL: buffer = skip_whitespace(buffer, end); if (buffer < end) { switch (*buffer) { case '}': /* end of block */ if (parser->block) break; parser->state = CSS_PARSER_NONE; ++buffer; break; case '\'': case '"': parser->state = CSS_PARSER_URL; parser->quote = *buffer++; parser->url_start = parser->position + (off_t)(buffer - start); parser->url_buffer.clear(); break; default: parser->state = CSS_PARSER_BLOCK; } } break; case CSS_PARSER_URL: p = (const char *)memchr(buffer, parser->quote, end - buffer); if (p == nullptr) { nbytes = end - start; parser->url_buffer.AppendTruncated({buffer, nbytes}); parser->position += (off_t)nbytes; return nbytes; } /* found the end of the URL - copy the rest, and invoke the handler method "url()" */ nbytes = p - buffer; parser->url_buffer.AppendTruncated({buffer, nbytes}); buffer = p + 1; parser->state = CSS_PARSER_BLOCK; url.start = parser->url_start; url.end = parser->position + (off_t)(p - start); url.value = parser->url_buffer; parser->handler->url(&url, parser->handler_ctx); if (parser->input == nullptr) return 0; break; case CSS_PARSER_AT: do { if (!is_css_nmchar(*buffer)) { if (parser->name_buffer.Equals({"import", 6})) parser->state = CSS_PARSER_PRE_IMPORT; else parser->state = CSS_PARSER_NONE; break; } if (parser->name_buffer.size() < parser->name_buffer.capacity() - 1) parser->name_buffer.push_back(*buffer); ++buffer; } while (buffer < end); break; case CSS_PARSER_PRE_IMPORT: do { if (!IsWhitespaceOrNull(*buffer)) { if (*buffer == '"') { ++buffer; parser->state = CSS_PARSER_IMPORT; parser->url_start = parser->position + (off_t)(buffer - start); parser->url_buffer.clear(); } else parser->state = CSS_PARSER_NONE; break; } ++buffer; } while (buffer < end); break; case CSS_PARSER_IMPORT: p = (const char *)memchr(buffer, '"', end - buffer); if (p == nullptr) { nbytes = end - start; parser->url_buffer.AppendTruncated({buffer, nbytes}); parser->position += (off_t)nbytes; return nbytes; } /* found the end of the URL - copy the rest, and invoke the handler method "import()" */ nbytes = p - buffer; parser->url_buffer.AppendTruncated({buffer, nbytes}); buffer = p + 1; parser->state = CSS_PARSER_NONE; url.start = parser->url_start; url.end = parser->position + (off_t)(p - start); url.value = parser->url_buffer; parser->handler->import(&url, parser->handler_ctx); if (parser->input == nullptr) return 0; break; } } assert(parser->input != nullptr); parser->position += length; return length; } /* * istream handler * */ static size_t css_parser_input_data(const void *data, size_t length, void *ctx) { CssParser *parser = (CssParser *)ctx; const ScopePoolRef ref(*parser->pool TRACE_ARGS); return css_parser_feed(parser, (const char *)data, length); } static void css_parser_input_eof(void *ctx) { CssParser *parser = (CssParser *)ctx; assert(parser->input != nullptr); parser->input = nullptr; parser->handler->eof(parser->handler_ctx, parser->position); pool_unref(parser->pool); } static void css_parser_input_abort(GError *error, void *ctx) { CssParser *parser = (CssParser *)ctx; assert(parser->input != nullptr); parser->input = nullptr; parser->handler->error(error, parser->handler_ctx); pool_unref(parser->pool); } static const struct istream_handler css_parser_input_handler = { .data = css_parser_input_data, .eof = css_parser_input_eof, .abort = css_parser_input_abort, }; /* * constructor * */ CssParser::CssParser(struct pool *_pool, struct istream *_input, bool _block, const CssParserHandler *_handler, void *_handler_ctx) :pool(_pool), block(_block), position(0), handler(_handler), handler_ctx(_handler_ctx), state(block ? CSS_PARSER_BLOCK : CSS_PARSER_NONE) { istream_assign_handler(&input, _input, &css_parser_input_handler, this, 0); } CssParser * css_parser_new(struct pool *pool, struct istream *input, bool block, const CssParserHandler *handler, void *handler_ctx) { assert(pool != nullptr); assert(input != nullptr); assert(handler != nullptr); assert(handler->eof != nullptr); assert(handler->error != nullptr); pool_ref(pool); return NewFromPool<CssParser>(*pool, pool, input, block, handler, handler_ctx); } void css_parser_close(CssParser *parser) { assert(parser != nullptr); assert(parser->input != nullptr); istream_close(parser->input); pool_unref(parser->pool); } void css_parser_read(CssParser *parser) { assert(parser != nullptr); assert(parser->input != nullptr); istream_read(parser->input); }
use TrivialArray for name, value and url buffers
css_parser: use TrivialArray for name, value and url buffers
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
b40d173e257fb8f1cc9335d2cc0691fa338b7aa2
library/cpp/sandesh_connection.cc
library/cpp/sandesh_connection.cc
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ // // sandesh_connection.cc // // Sandesh connection management implementation // #include <io/tcp_session.h> #include <io/tcp_server.h> #include <base/logging.h> #include <sandesh/protocol/TXMLProtocol.h> #include <sandesh/sandesh_types.h> #include <sandesh/sandesh.h> #include <sandesh/sandesh_ctrl_types.h> #include <sandesh/common/vns_types.h> #include <sandesh/common/vns_constants.h> #include "sandesh_uve.h" #include "sandesh_session.h" #include "sandesh_client.h" #include "sandesh_server.h" #include "sandesh_connection.h" using namespace std; using boost::system::error_code; #define CONNECTION_LOG(_Level, _Msg) \ do { \ if (LoggingDisabled()) break; \ log4cplus::Logger _Xlogger = log4cplus::Logger::getRoot(); \ if (_Xlogger.isEnabledFor(log4cplus::_Level##_LOG_LEVEL)) { \ log4cplus::tostringstream _Xbuf; \ if (!state_machine()->generator_key().empty()) { \ _Xbuf << state_machine()->generator_key() << " (" << \ GetTaskInstance() << ") "; \ } \ if (session()) { \ _Xbuf << session()->ToString() << " "; \ } \ _Xbuf << _Msg; \ _Xlogger.forcedLog(log4cplus::_Level##_LOG_LEVEL, \ _Xbuf.str()); \ } \ } while (false) SandeshConnection::SandeshConnection(const char *prefix, TcpServer *server, Endpoint endpoint, int task_instance, int task_id) : is_deleted_(false), server_(server), endpoint_(endpoint), admin_down_(false), session_(NULL), task_instance_(task_instance), task_id_(task_id), state_machine_(new SandeshStateMachine(prefix, this)) { } SandeshConnection::~SandeshConnection() { } void SandeshConnection::set_session(SandeshSession *session) { session_ = session; } SandeshSession *SandeshConnection::session() const { return session_; } void SandeshConnection::ReceiveMsg(const std::string &msg, SandeshSession *session) { state_machine_->OnSandeshMessage(session, msg); } bool SandeshConnection::SendSandesh(Sandesh *snh) { if (!session_) { return false; } ssm::SsmState state = state_machine_->get_state(); if (state != ssm::SERVER_INIT && state != ssm::ESTABLISHED) { return false; } // XXX No bounded work queue session_->send_queue()->Enqueue(snh); return true; } void SandeshConnection::AcceptSession(SandeshSession *session) { session->SetReceiveMsgCb(boost::bind(&SandeshConnection::ReceiveMsg, this, _1, _2)); session->SetConnection(this); state_machine_->PassiveOpen(session); } SandeshStateMachine *SandeshConnection::state_machine() const { return state_machine_.get(); } void SandeshConnection::SetAdminState(bool down) { if (admin_down_ != down) { admin_down_ = down; state_machine_->SetAdminState(down); } } void SandeshConnection::Shutdown() { is_deleted_ = true; deleter()->Delete(); } bool SandeshConnection::MayDelete() const { // XXX Do we have any dependencies? return true; } class SandeshServerConnection::DeleteActor : public LifetimeActor { public: DeleteActor(SandeshServer *server, SandeshServerConnection *parent) : LifetimeActor(server->lifetime_manager()), server_(server), parent_(parent) { } virtual bool MayDelete() const { return parent_->MayDelete(); } virtual void Shutdown() { SandeshSession *session = NULL; if (parent_->state_machine()) { session = parent_->state_machine()->session(); parent_->state_machine()->clear_session(); } if (session) { server_->DeleteSession(session); } parent_->is_deleted_ = true; } virtual void Destroy() { parent_->Destroy(); } private: SandeshServer *server_; SandeshServerConnection *parent_; }; SandeshServerConnection::SandeshServerConnection( TcpServer *server, Endpoint endpoint, int task_instance, int task_id) : SandeshConnection("SandeshServer: ", server, endpoint, task_instance, task_id), deleter_(new DeleteActor(dynamic_cast<SandeshServer *>(server), this)), server_delete_ref_(this, dynamic_cast<SandeshServer *>(server)->deleter()) { } SandeshServerConnection::~SandeshServerConnection() { } void SandeshServerConnection::ManagedDelete() { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return; } sserver->lifetime_manager()->Enqueue(deleter_.get()); } bool SandeshServerConnection::ProcessSandeshCtrlMessage(const std::string &msg, const SandeshHeader &header, const std::string sandesh_name, const uint32_t header_offset) { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return false; } Sandesh *ctrl_snh = SandeshSession::DecodeCtrlSandesh(msg, header, sandesh_name, header_offset); bool ret = sserver->ReceiveSandeshCtrlMsg(state_machine(), session(), ctrl_snh); ctrl_snh->Release(); return ret; } bool SandeshServerConnection::ProcessResourceUpdate(bool rsc) { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return false; } return sserver->ReceiveResourceUpdate(session(), rsc); } bool SandeshServerConnection::ProcessSandeshMessage( const SandeshMessage *msg, bool resource) { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return false; } sserver->ReceiveSandeshMsg(session(), msg, resource); return true; } void SandeshServerConnection::ProcessDisconnect(SandeshSession * sess) { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return; } sserver->DisconnectSession(sess); } LifetimeManager *SandeshServerConnection::lifetime_manager() { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return NULL; } return sserver->lifetime_manager(); } void SandeshServerConnection::Destroy() { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return; } int index = GetTaskInstance(); if (index != -1) { sserver->FreeConnectionIndex(index); } // Deletes self - should always be the last sserver->RemoveConnection(this); }; LifetimeActor *SandeshServerConnection::deleter() { return deleter_.get(); }
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ // // sandesh_connection.cc // // Sandesh connection management implementation // #include <io/tcp_session.h> #include <io/tcp_server.h> #include <base/logging.h> #include <sandesh/protocol/TXMLProtocol.h> #include <sandesh/sandesh_types.h> #include <sandesh/sandesh.h> #include <sandesh/sandesh_ctrl_types.h> #include <sandesh/common/vns_types.h> #include <sandesh/common/vns_constants.h> #include "sandesh_uve.h" #include "sandesh_session.h" #include "sandesh_client.h" #include "sandesh_server.h" #include "sandesh_connection.h" using namespace std; using boost::system::error_code; #define CONNECTION_LOG(_Level, _Msg) \ do { \ if (LoggingDisabled()) break; \ log4cplus::Logger _Xlogger = log4cplus::Logger::getRoot(); \ if (_Xlogger.isEnabledFor(log4cplus::_Level##_LOG_LEVEL)) { \ log4cplus::tostringstream _Xbuf; \ if (!state_machine()->generator_key().empty()) { \ _Xbuf << state_machine()->generator_key() << " (" << \ GetTaskInstance() << ") "; \ } \ if (session()) { \ _Xbuf << session()->ToString() << " "; \ } \ _Xbuf << _Msg; \ _Xlogger.forcedLog(log4cplus::_Level##_LOG_LEVEL, \ _Xbuf.str()); \ } \ } while (false) SandeshConnection::SandeshConnection(const char *prefix, TcpServer *server, Endpoint endpoint, int task_instance, int task_id) : is_deleted_(false), server_(server), endpoint_(endpoint), admin_down_(false), session_(NULL), task_instance_(task_instance), task_id_(task_id), state_machine_(new SandeshStateMachine(prefix, this)) { } SandeshConnection::~SandeshConnection() { } void SandeshConnection::set_session(SandeshSession *session) { session_ = session; } SandeshSession *SandeshConnection::session() const { return session_; } void SandeshConnection::ReceiveMsg(const std::string &msg, SandeshSession *session) { state_machine_->OnSandeshMessage(session, msg); } bool SandeshConnection::SendSandesh(Sandesh *snh) { if (!session_) { return false; } ssm::SsmState state = state_machine_->get_state(); if (state != ssm::SERVER_INIT && state != ssm::ESTABLISHED) { return false; } // XXX No bounded work queue session_->send_queue()->Enqueue(snh); return true; } void SandeshConnection::AcceptSession(SandeshSession *session) { session->SetReceiveMsgCb(boost::bind(&SandeshConnection::ReceiveMsg, this, _1, _2)); session->SetConnection(this); state_machine_->PassiveOpen(session); } SandeshStateMachine *SandeshConnection::state_machine() const { return state_machine_.get(); } void SandeshConnection::SetAdminState(bool down) { if (admin_down_ != down) { admin_down_ = down; state_machine_->SetAdminState(down); } } void SandeshConnection::Shutdown() { is_deleted_ = true; deleter()->Delete(); } bool SandeshConnection::MayDelete() const { // XXX Do we have any dependencies? return true; } class SandeshServerConnection::DeleteActor : public LifetimeActor { public: DeleteActor(SandeshServer *server, SandeshServerConnection *parent) : LifetimeActor(server->lifetime_manager()), server_(server), parent_(parent) { } virtual bool MayDelete() const { return parent_->MayDelete(); } virtual void Shutdown() { SandeshSession *session = NULL; if (parent_->state_machine()) { session = parent_->state_machine()->session(); parent_->state_machine()->clear_session(); } if (session) { server_->DeleteSession(session); } parent_->is_deleted_ = true; } virtual void Destroy() { parent_->Destroy(); } private: SandeshServer *server_; SandeshServerConnection *parent_; }; SandeshServerConnection::SandeshServerConnection( TcpServer *server, Endpoint endpoint, int task_instance, int task_id) : SandeshConnection("SandeshServer: ", server, endpoint, task_instance, task_id), deleter_(new DeleteActor(dynamic_cast<SandeshServer *>(server), this)), server_delete_ref_(this, dynamic_cast<SandeshServer *>(server)->deleter()) { } SandeshServerConnection::~SandeshServerConnection() { } void SandeshServerConnection::ManagedDelete() { deleter_->Delete(); } bool SandeshServerConnection::ProcessSandeshCtrlMessage(const std::string &msg, const SandeshHeader &header, const std::string sandesh_name, const uint32_t header_offset) { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return false; } Sandesh *ctrl_snh = SandeshSession::DecodeCtrlSandesh(msg, header, sandesh_name, header_offset); bool ret = sserver->ReceiveSandeshCtrlMsg(state_machine(), session(), ctrl_snh); ctrl_snh->Release(); return ret; } bool SandeshServerConnection::ProcessResourceUpdate(bool rsc) { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return false; } return sserver->ReceiveResourceUpdate(session(), rsc); } bool SandeshServerConnection::ProcessSandeshMessage( const SandeshMessage *msg, bool resource) { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return false; } sserver->ReceiveSandeshMsg(session(), msg, resource); return true; } void SandeshServerConnection::ProcessDisconnect(SandeshSession * sess) { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return; } sserver->DisconnectSession(sess); } LifetimeManager *SandeshServerConnection::lifetime_manager() { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return NULL; } return sserver->lifetime_manager(); } void SandeshServerConnection::Destroy() { SandeshServer *sserver = dynamic_cast<SandeshServer *>(server()); if (!sserver) { CONNECTION_LOG(ERROR, __func__ << " No Server"); return; } int index = GetTaskInstance(); if (index != -1) { sserver->FreeConnectionIndex(index); } // Deletes self - should always be the last sserver->RemoveConnection(this); }; LifetimeActor *SandeshServerConnection::deleter() { return deleter_.get(); }
Use correct LifetimeActor method to trigger deletion of object.
Use correct LifetimeActor method to trigger deletion of object. Ran into this when fixing an issue in lifetime manager. Clients should call Delete instead of simply enqueueing the DeleteActor to the LifetimeManager. The main difference is that the Delete method has protection against duplicate Enqueue. Will separately make changes to LifetimeManager code to make Enqueue a private method. Change-Id: Ic6224d822e37d07aa067244c77490e17965e5db1
C++
apache-2.0
toabctl/contrail-sandesh,Juniper/contrail-sandesh,vpramo/contrail-sandesh,varunarya10/contrail-sandesh,safchain/contrail-sandesh,vpramo/contrail-sandesh,vpramo/contrail-sandesh,safchain/contrail-sandesh,toabctl/contrail-sandesh,Juniper/contrail-sandesh,varunarya10/contrail-sandesh,Juniper/contrail-sandesh,toabctl/contrail-sandesh,vpramo/contrail-sandesh,safchain/contrail-sandesh,safchain/contrail-sandesh,varunarya10/contrail-sandesh,Juniper/contrail-sandesh,toabctl/contrail-sandesh,varunarya10/contrail-sandesh
386aea249bb16eef206c4c487bfab6c02a8f4ff7
tree/treeplayer/test/dataframe/dataframe_callbacks.cxx
tree/treeplayer/test/dataframe/dataframe_callbacks.cxx
#include "ROOT/TDataFrame.hxx" #include "TRandom.h" #include "TROOT.h" #include "gtest/gtest.h" #include <limits> using namespace ROOT::Experimental; using namespace ROOT::Experimental::TDF; using namespace ROOT::Detail::TDF; /********* FIXTURES *********/ static constexpr ULong64_t gNEvents = 8ull; // fixture that provides a TDF with no data-source and a single column "x" containing normal-distributed doubles class TDFCallbacks : public ::testing::Test { private: TDataFrame fLoopManager; TInterface<TLoopManager> DefineRandomCol() { TRandom r; return fLoopManager.Define("x", [r]() mutable { return r.Gaus(); }); } protected: TDFCallbacks() : fLoopManager(gNEvents), tdf(DefineRandomCol()) {} TInterface<TLoopManager> tdf; }; #ifdef R__USE_IMT static constexpr unsigned int gNSlots = 4u; // fixture that enables implicit MT and provides a TDF with no data-source and a single column "x" containing // normal-distributed doubles class TDFCallbacksMT : public ::testing::Test { class TIMTEnabler { public: TIMTEnabler(unsigned int sl) { ROOT::EnableImplicitMT(sl); } ~TIMTEnabler() { ROOT::DisableImplicitMT(); } }; private: TIMTEnabler fIMTEnabler; TDataFrame fLoopManager; TInterface<TLoopManager> DefineRandomCol() { std::vector<TRandom> rs(gNSlots); return fLoopManager.DefineSlot("x", [rs](unsigned int slot) mutable { return rs[slot].Gaus(); }); } protected: TDFCallbacksMT() : fIMTEnabler(gNSlots), fLoopManager(gNEvents), tdf(DefineRandomCol()) {} TInterface<TLoopManager> tdf; }; #endif /********* TESTS *********/ TEST_F(TDFCallbacks, Histo1DWithFillTOHelper) { // Histo1D<double> + OnPartialResult + FillTOHelper auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x"); using value_t = typename decltype(h)::Value_t; ULong64_t i = 0ull; ULong64_t everyN = 1ull; h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) { i += everyN; EXPECT_EQ(h_.GetEntries(), i); }); *h; EXPECT_EQ(gNEvents, i); } TEST_F(TDFCallbacks, JittedHisto1DWithFillTOHelper) { // Histo1D + Jitting + OnPartialResult + FillTOHelper auto h = tdf.Histo1D({"", "", 128, -2., 2.}, "x"); using value_t = typename decltype(h)::Value_t; ULong64_t i = 0ull; ULong64_t everyN = 1ull; h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) { i += everyN; EXPECT_EQ(h_.GetEntries(), i); }); *h; EXPECT_EQ(gNEvents, i); } TEST_F(TDFCallbacks, Histo1DWithFillHelper) { // Histo1D<double> + OnPartialResult + FillHelper auto h = tdf.Histo1D<double>("x"); using value_t = typename decltype(h)::Value_t; ULong64_t i = 0ull; ULong64_t everyN = 1ull; h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) { i += everyN; EXPECT_EQ(h_.GetEntries(), i); }); *h; EXPECT_EQ(gNEvents, i); } TEST_F(TDFCallbacks, JittedHisto1DWithFillHelper) { // Histo1D + Jitting + OnPartialResult + FillHelper auto h = tdf.Histo1D("x"); using value_t = typename decltype(h)::Value_t; ULong64_t i = 0ull; ULong64_t everyN = 1ull; h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) { i += everyN; EXPECT_EQ(h_.GetEntries(), i); }); *h; EXPECT_EQ(gNEvents, i); } TEST_F(TDFCallbacks, Min) { // Min + OnPartialResult auto m = tdf.Min<double>("x"); double runningMin = std::numeric_limits<double>::max(); m.OnPartialResult(2, [&runningMin](double x) { EXPECT_LE(x, runningMin); runningMin = x; }); *m; EXPECT_DOUBLE_EQ(runningMin, *m); } TEST_F(TDFCallbacks, JittedMin) { // Min + Jitting + OnPartialResult auto m = tdf.Min("x"); double runningMin = std::numeric_limits<double>::max(); m.OnPartialResult(2, [&runningMin](double x) { EXPECT_LE(x, runningMin); runningMin = x; }); *m; EXPECT_DOUBLE_EQ(runningMin, *m); } TEST_F(TDFCallbacks, Max) { // Max + OnPartialResult auto m = tdf.Max<double>("x"); double runningMax = std::numeric_limits<double>::lowest(); m.OnPartialResult(2, [&runningMax](double x) { EXPECT_GE(x, runningMax); runningMax = x; }); *m; EXPECT_DOUBLE_EQ(runningMax, *m); } TEST_F(TDFCallbacks, JittedMax) { // Max + Jitting + OnPartialResult auto m = tdf.Max("x"); double runningMax = std::numeric_limits<double>::lowest(); m.OnPartialResult(2, [&runningMax](double x) { EXPECT_GE(x, runningMax); runningMax = x; }); *m; EXPECT_DOUBLE_EQ(runningMax, *m); } TEST_F(TDFCallbacks, Mean) { // Mean + OnPartialResult auto m = tdf.Mean<double>("x"); // TODO find a better way to check that the running mean makes sense bool called = false; m.OnPartialResult(gNEvents / 2, [&called](double) { called = true; }); *m; EXPECT_TRUE(called); } TEST_F(TDFCallbacks, JittedMean) { // Mean + Jitting + OnPartialResult auto m = tdf.Mean("x"); // TODO find a better way to check that the running mean makes sense bool called = false; m.OnPartialResult(gNEvents / 2, [&called](double) { called = true; }); *m; EXPECT_TRUE(called); } TEST_F(TDFCallbacks, Take) { // Take + OnPartialResult auto t = tdf.Take<double>("x"); unsigned int i = 0u; t.OnPartialResult(1, [&](decltype(t)::Value_t &t_) { ++i; EXPECT_EQ(t_.size(), i); }); *t; } TEST_F(TDFCallbacks, Count) { // Count + OnPartialResult auto c = tdf.Count(); ULong64_t i = 0ull; c.OnPartialResult(1, [&](decltype(c)::Value_t c_) { ++i; EXPECT_EQ(c_, i); }); *c; EXPECT_EQ(*c, i); } TEST_F(TDFCallbacks, Reduce) { // Reduce + OnPartialResult double runningMin; auto m = tdf.Min<double>("x").OnPartialResult(1, [&runningMin](double m_) { runningMin = m_; }); auto r = tdf.Reduce([](double x1, double x2) { return std::min(x1, x2); }, {"x"}, 0.); r.OnPartialResult(1, [&runningMin](double r_) { EXPECT_DOUBLE_EQ(r_, runningMin); }); *r; } TEST_F(TDFCallbacks, Chaining) { // Chaining of multiple OnPartialResult[Slot] calls unsigned int i = 0u; auto c = tdf.Count() .OnPartialResult(1, [&i](ULong64_t) { ++i; }) .OnPartialResultSlot(1, [&i](unsigned int, ULong64_t) {++i; }); *c; EXPECT_EQ(i, gNEvents * 2); } TEST_F(TDFCallbacks, OrderOfExecution) { // Test that callbacks are executed in the order they are registered unsigned int i = 0u; auto c = tdf.Count(); c.OnPartialResult(1, [&i](ULong64_t) { EXPECT_EQ(i, 0u); i = 42u; }); c.OnPartialResultSlot(1, [&i](unsigned int slot, ULong64_t) { if (slot == 0u) { EXPECT_EQ(i, 42u); i = 0u; } }); *c; EXPECT_EQ(i, 0u); } TEST_F(TDFCallbacks, ExecuteOnce) { // OnPartialResult(kOnce) auto c = tdf.Count(); unsigned int callCount = 0; c.OnPartialResult(0, [&callCount](ULong64_t) { callCount++; }); *c; EXPECT_EQ(callCount, 1u); } TEST_F(TDFCallbacks, MultipleCallbacks) { // registration of multiple callbacks on the same partial result auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x"); using value_t = typename decltype(h)::Value_t; ULong64_t everyN = 1ull; ULong64_t i = 0ull; h.OnPartialResult(everyN, [&i, everyN](value_t &h_) { i += everyN; EXPECT_EQ(h_.GetEntries(), i); }); everyN = 2ull; ULong64_t i2 = 0ull; h.OnPartialResult(everyN, [&i2, everyN](value_t &h_) { i2 += everyN; EXPECT_EQ(h_.GetEntries(), i2); }); *h; } TEST_F(TDFCallbacks, MultipleEventLoops) { // callbacks must be de-registered after the event-loop is run auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x"); using value_t = typename decltype(h)::Value_t; ULong64_t i = 0ull; h.OnPartialResult(1ull, [&i](value_t &) { ++i; }); *h; auto h2 = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x"); *h2; EXPECT_EQ(i, gNEvents); } class FunctorClass { unsigned int &i_; public: FunctorClass(unsigned int &i) : i_(i) {} void operator()(ULong64_t) { ++i_; } }; TEST_F(TDFCallbacks, FunctorClass) { unsigned int i = 0; *(tdf.Count().OnPartialResult(1, FunctorClass(i))); EXPECT_EQ(i, gNEvents); } unsigned int freeFunctionCounter = 0; void FreeFunction(ULong64_t) { freeFunctionCounter++; } TEST_F(TDFCallbacks, FreeFunction) { *(tdf.Count().OnPartialResult(1, FreeFunction)); EXPECT_EQ(freeFunctionCounter, gNEvents); } #ifdef R__USE_IMT /******** Multi-thread tests **********/ TEST_F(TDFCallbacksMT, ExecuteOncePerSlot) { // OnPartialResultSlot(kOnce) auto c = tdf.Count(); std::atomic_uint callCount(0u); c.OnPartialResultSlot(c.kOnce, [&callCount](unsigned int, ULong64_t) { callCount++; }); *c; EXPECT_EQ(callCount, gNSlots * 2); // TDF spawns two tasks per slot } TEST_F(TDFCallbacksMT, Histo1DWithFillTOHelper) { // Histo1D<double> + OnPartialResultSlot + FillTOHelper auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x"); using value_t = typename decltype(h)::Value_t; std::array<ULong64_t, gNSlots> is; is.fill(0ull); constexpr ULong64_t everyN = 1ull; h.OnPartialResultSlot(everyN, [&is](unsigned int slot, value_t &h_) { is[slot] += everyN; EXPECT_EQ(h_.GetEntries(), is[slot]); }); *h; EXPECT_EQ(gNEvents, std::accumulate(is.begin(), is.end(), 0ull)); } TEST_F(TDFCallbacksMT, Histo1DWithFillHelper) { // Histo1D<double> + OnPartialResultSlot + FillHelper auto h = tdf.Histo1D<double>("x"); using value_t = typename decltype(h)::Value_t; std::array<ULong64_t, gNSlots> is; is.fill(0ull); constexpr ULong64_t everyN = 1ull; h.OnPartialResultSlot(everyN, [&is, &everyN](unsigned int slot, value_t &h_) { is[slot] += everyN; EXPECT_EQ(h_.GetEntries(), is[slot]); }); *h; EXPECT_EQ(gNEvents, std::accumulate(is.begin(), is.end(), 0ull)); } #endif
#include "ROOT/TDataFrame.hxx" #include "TRandom.h" #include "TROOT.h" #include "gtest/gtest.h" #include <limits> using namespace ROOT::Experimental; using namespace ROOT::Experimental::TDF; using namespace ROOT::Detail::TDF; /********* FIXTURES *********/ static constexpr ULong64_t gNEvents = 8ull; // fixture that provides a TDF with no data-source and a single column "x" containing normal-distributed doubles class TDFCallbacks : public ::testing::Test { private: TDataFrame fLoopManager; TInterface<TLoopManager> DefineRandomCol() { TRandom r; return fLoopManager.Define("x", [r]() mutable { return r.Gaus(); }); } protected: TDFCallbacks() : fLoopManager(gNEvents), tdf(DefineRandomCol()) {} TInterface<TLoopManager> tdf; }; #ifdef R__USE_IMT static constexpr unsigned int gNSlots = 4u; // fixture that enables implicit MT and provides a TDF with no data-source and a single column "x" containing // normal-distributed doubles class TDFCallbacksMT : public ::testing::Test { class TIMTEnabler { public: TIMTEnabler(unsigned int sl) { ROOT::EnableImplicitMT(sl); } ~TIMTEnabler() { ROOT::DisableImplicitMT(); } }; private: TIMTEnabler fIMTEnabler; TDataFrame fLoopManager; TInterface<TLoopManager> DefineRandomCol() { std::vector<TRandom> rs(gNSlots); return fLoopManager.DefineSlot("x", [rs](unsigned int slot) mutable { return rs[slot].Gaus(); }); } protected: TDFCallbacksMT() : fIMTEnabler(gNSlots), fLoopManager(gNEvents), tdf(DefineRandomCol()) {} TInterface<TLoopManager> tdf; }; #endif /********* TESTS *********/ TEST_F(TDFCallbacks, Histo1DWithFillTOHelper) { // Histo1D<double> + OnPartialResult + FillTOHelper auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x"); using value_t = typename decltype(h)::Value_t; ULong64_t i = 0ull; ULong64_t everyN = 1ull; h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) { i += everyN; EXPECT_EQ(h_.GetEntries(), i); }); *h; EXPECT_EQ(gNEvents, i); } TEST_F(TDFCallbacks, JittedHisto1DWithFillTOHelper) { // Histo1D + Jitting + OnPartialResult + FillTOHelper auto h = tdf.Histo1D({"", "", 128, -2., 2.}, "x"); using value_t = typename decltype(h)::Value_t; ULong64_t i = 0ull; ULong64_t everyN = 1ull; h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) { i += everyN; EXPECT_EQ(h_.GetEntries(), i); }); *h; EXPECT_EQ(gNEvents, i); } TEST_F(TDFCallbacks, Histo1DWithFillHelper) { // Histo1D<double> + OnPartialResult + FillHelper auto h = tdf.Histo1D<double>("x"); using value_t = typename decltype(h)::Value_t; ULong64_t i = 0ull; ULong64_t everyN = 1ull; h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) { i += everyN; EXPECT_EQ(h_.GetEntries(), i); }); *h; EXPECT_EQ(gNEvents, i); } TEST_F(TDFCallbacks, JittedHisto1DWithFillHelper) { // Histo1D + Jitting + OnPartialResult + FillHelper auto h = tdf.Histo1D("x"); using value_t = typename decltype(h)::Value_t; ULong64_t i = 0ull; ULong64_t everyN = 1ull; h.OnPartialResult(everyN, [&i, &everyN](value_t &h_) { i += everyN; EXPECT_EQ(h_.GetEntries(), i); }); *h; EXPECT_EQ(gNEvents, i); } TEST_F(TDFCallbacks, Min) { // Min + OnPartialResult auto m = tdf.Min<double>("x"); double runningMin = std::numeric_limits<double>::max(); m.OnPartialResult(2, [&runningMin](double x) { EXPECT_LE(x, runningMin); runningMin = x; }); *m; EXPECT_DOUBLE_EQ(runningMin, *m); } TEST_F(TDFCallbacks, JittedMin) { // Min + Jitting + OnPartialResult auto m = tdf.Min("x"); double runningMin = std::numeric_limits<double>::max(); m.OnPartialResult(2, [&runningMin](double x) { EXPECT_LE(x, runningMin); runningMin = x; }); *m; EXPECT_DOUBLE_EQ(runningMin, *m); } TEST_F(TDFCallbacks, Max) { // Max + OnPartialResult auto m = tdf.Max<double>("x"); double runningMax = std::numeric_limits<double>::lowest(); m.OnPartialResult(2, [&runningMax](double x) { EXPECT_GE(x, runningMax); runningMax = x; }); *m; EXPECT_DOUBLE_EQ(runningMax, *m); } TEST_F(TDFCallbacks, JittedMax) { // Max + Jitting + OnPartialResult auto m = tdf.Max("x"); double runningMax = std::numeric_limits<double>::lowest(); m.OnPartialResult(2, [&runningMax](double x) { EXPECT_GE(x, runningMax); runningMax = x; }); *m; EXPECT_DOUBLE_EQ(runningMax, *m); } TEST_F(TDFCallbacks, Mean) { // Mean + OnPartialResult auto m = tdf.Mean<double>("x"); // TODO find a better way to check that the running mean makes sense bool called = false; m.OnPartialResult(gNEvents / 2, [&called](double) { called = true; }); *m; EXPECT_TRUE(called); } TEST_F(TDFCallbacks, JittedMean) { // Mean + Jitting + OnPartialResult auto m = tdf.Mean("x"); // TODO find a better way to check that the running mean makes sense bool called = false; m.OnPartialResult(gNEvents / 2, [&called](double) { called = true; }); *m; EXPECT_TRUE(called); } TEST_F(TDFCallbacks, Take) { // Take + OnPartialResult auto t = tdf.Take<double>("x"); unsigned int i = 0u; t.OnPartialResult(1, [&](decltype(t)::Value_t &t_) { ++i; EXPECT_EQ(t_.size(), i); }); *t; } TEST_F(TDFCallbacks, Count) { // Count + OnPartialResult auto c = tdf.Count(); ULong64_t i = 0ull; c.OnPartialResult(1, [&](decltype(c)::Value_t c_) { ++i; EXPECT_EQ(c_, i); }); *c; EXPECT_EQ(*c, i); } TEST_F(TDFCallbacks, Reduce) { // Reduce + OnPartialResult double runningMin; auto m = tdf.Min<double>("x").OnPartialResult(1, [&runningMin](double m_) { runningMin = m_; }); auto r = tdf.Reduce([](double x1, double x2) { return std::min(x1, x2); }, {"x"}, 0.); r.OnPartialResult(1, [&runningMin](double r_) { EXPECT_DOUBLE_EQ(r_, runningMin); }); *r; } TEST_F(TDFCallbacks, Chaining) { // Chaining of multiple OnPartialResult[Slot] calls unsigned int i = 0u; auto c = tdf.Count() .OnPartialResult(1, [&i](ULong64_t) { ++i; }) .OnPartialResultSlot(1, [&i](unsigned int, ULong64_t) {++i; }); *c; EXPECT_EQ(i, gNEvents * 2); } TEST_F(TDFCallbacks, OrderOfExecution) { // Test that callbacks are executed in the order they are registered unsigned int i = 0u; auto c = tdf.Count(); c.OnPartialResult(1, [&i](ULong64_t) { EXPECT_EQ(i, 0u); i = 42u; }); c.OnPartialResultSlot(1, [&i](unsigned int slot, ULong64_t) { if (slot == 0u) { EXPECT_EQ(i, 42u); i = 0u; } }); *c; EXPECT_EQ(i, 0u); } TEST_F(TDFCallbacks, ExecuteOnce) { // OnPartialResult(kOnce) auto c = tdf.Count(); unsigned int callCount = 0; c.OnPartialResult(0, [&callCount](ULong64_t) { callCount++; }); *c; EXPECT_EQ(callCount, 1u); } TEST_F(TDFCallbacks, MultipleCallbacks) { // registration of multiple callbacks on the same partial result auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x"); using value_t = typename decltype(h)::Value_t; ULong64_t everyN = 1ull; ULong64_t i = 0ull; h.OnPartialResult(everyN, [&i, everyN](value_t &h_) { i += everyN; EXPECT_EQ(h_.GetEntries(), i); }); everyN = 2ull; ULong64_t i2 = 0ull; h.OnPartialResult(everyN, [&i2, everyN](value_t &h_) { i2 += everyN; EXPECT_EQ(h_.GetEntries(), i2); }); *h; } TEST_F(TDFCallbacks, MultipleEventLoops) { // callbacks must be de-registered after the event-loop is run auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x"); using value_t = typename decltype(h)::Value_t; ULong64_t i = 0ull; h.OnPartialResult(1ull, [&i](value_t &) { ++i; }); *h; auto h2 = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x"); *h2; EXPECT_EQ(i, gNEvents); } class FunctorClass { unsigned int &i_; public: FunctorClass(unsigned int &i) : i_(i) {} void operator()(ULong64_t) { ++i_; } }; TEST_F(TDFCallbacks, FunctorClass) { unsigned int i = 0; *(tdf.Count().OnPartialResult(1, FunctorClass(i))); EXPECT_EQ(i, gNEvents); } unsigned int freeFunctionCounter = 0; void FreeFunction(ULong64_t) { freeFunctionCounter++; } TEST_F(TDFCallbacks, FreeFunction) { *(tdf.Count().OnPartialResult(1, FreeFunction)); EXPECT_EQ(freeFunctionCounter, gNEvents); } #ifdef R__USE_IMT /******** Multi-thread tests **********/ TEST_F(TDFCallbacksMT, ExecuteOncePerSlot) { // OnPartialResultSlot(kOnce) auto c = tdf.Count(); std::atomic_uint callCount(0u); c.OnPartialResultSlot(c.kOnce, [&callCount](unsigned int, ULong64_t) { callCount++; }); *c; EXPECT_EQ(callCount, gNSlots * 2); // TDF spawns two tasks per slot } TEST_F(TDFCallbacksMT, Histo1DWithFillTOHelper) { // Histo1D<double> + OnPartialResultSlot + FillTOHelper auto h = tdf.Histo1D<double>({"", "", 128, -2., 2.}, "x"); using value_t = typename decltype(h)::Value_t; std::array<ULong64_t, gNSlots> is; is.fill(0ull); constexpr ULong64_t everyN = 1ull; h.OnPartialResultSlot(everyN, [&is](unsigned int slot, value_t &h_) { is[slot] += everyN; EXPECT_EQ(h_.GetEntries(), is[slot]); }); *h; EXPECT_EQ(gNEvents, std::accumulate(is.begin(), is.end(), 0ull)); } TEST_F(TDFCallbacksMT, Histo1DWithFillHelper) { // Histo1D<double> + OnPartialResultSlot + FillHelper auto h = tdf.Histo1D<double>("x"); using value_t = typename decltype(h)::Value_t; std::array<ULong64_t, gNSlots> is; is.fill(0ull); constexpr ULong64_t everyN = 1ull; h.OnPartialResultSlot(everyN, [&is](unsigned int slot, value_t &h_) { is[slot] += everyN; EXPECT_EQ(h_.GetEntries(), is[slot]); }); *h; EXPECT_EQ(gNEvents, std::accumulate(is.begin(), is.end(), 0ull)); } #endif
Remove warning in dataframe_callbacks
[TDF] Remove warning in dataframe_callbacks
C++
lgpl-2.1
olifre/root,karies/root,root-mirror/root,karies/root,root-mirror/root,zzxuanyuan/root,zzxuanyuan/root,zzxuanyuan/root,olifre/root,root-mirror/root,root-mirror/root,zzxuanyuan/root,root-mirror/root,olifre/root,zzxuanyuan/root,zzxuanyuan/root,karies/root,karies/root,zzxuanyuan/root,karies/root,olifre/root,olifre/root,root-mirror/root,karies/root,olifre/root,root-mirror/root,zzxuanyuan/root,zzxuanyuan/root,root-mirror/root,karies/root,karies/root,olifre/root,karies/root,root-mirror/root,karies/root,olifre/root,olifre/root,zzxuanyuan/root,root-mirror/root,olifre/root,karies/root,root-mirror/root,olifre/root,zzxuanyuan/root,zzxuanyuan/root
f01b108c7546ec42fdb8433bcbe0b54fe51b0887
src/data/vocab.cpp
src/data/vocab.cpp
#include <sstream> #include <algorithm> #include "data/vocab.h" #include "common/utils.h" #include "common/file_stream.h" #include "3rd_party/exception.h" #include "3rd_party/yaml-cpp/yaml.h" Vocab::Vocab() { } size_t Vocab::operator[](const std::string& word) const { auto it = str2id_.find(word); if(it != str2id_.end()) return it->second; else return 1; } Words Vocab::operator()(const std::vector<std::string>& lineTokens, bool addEOS) const { Words words(lineTokens.size()); std::transform(lineTokens.begin(), lineTokens.end(), words.begin(), [&](const std::string& w) { return (*this)[w]; }); if(addEOS) words.push_back(EOS); return words; } Words Vocab::operator()(const std::string& line, bool addEOS) const { std::vector<std::string> lineTokens; Split(line, lineTokens, " "); return (*this)(lineTokens, addEOS); } std::vector<std::string> Vocab::operator()(const Words& sentence, bool ignoreEOS) const { std::vector<std::string> decoded; for(size_t i = 0; i < sentence.size(); ++i) { if(sentence[i] != EOS || !ignoreEOS) { decoded.push_back((*this)[sentence[i]]); } } return decoded; } const std::string& Vocab::operator[](size_t id) const { UTIL_THROW_IF2(id >= id2str_.size(), "Unknown word id: " << id); return id2str_[id]; } size_t Vocab::size() const { return id2str_.size(); } void Vocab::load(const std::string& path, int max) { YAML::Node vocab = YAML::Load(InputFileStream(path)); for(auto&& pair : vocab) { auto str = pair.first.as<std::string>(); auto id = pair.second.as<Word>(); if (id < (Word)max) { str2id_[str] = id; if(id >= id2str_.size()) id2str_.resize(id + 1); id2str_[id] = str; } } UTIL_THROW_IF2(id2str_.empty(), "Empty vocabulary " << path); id2str_[0] = "</s>"; } class Vocab::VocabFreqOrderer { public: bool operator()(const Vocab::Str2Id::value_type* a, const Vocab::Str2Id::value_type* b) const { return a->second < b->second; } }; void Vocab::create(const std::string& vocabPath, int max, const std::string& trainPath) { UTIL_THROW_IF2(boost::filesystem::exists(vocabPath), "Vocab file " << vocabPath << " exist. Not overwriting"); //std::cerr << "Vocab::create" << std::endl; InputFileStream trainStrm(trainPath); // create freqency list, reuse Str2Id but use Id to store freq Str2Id vocab; std::string line; while (getline((std::istream&)trainStrm, line)) { //std::cerr << "line=" << line << std::endl; std::vector<std::string> toks; Split(line, toks); for (const std::string &tok: toks) { Str2Id::iterator iter = vocab.find(tok); if (iter == vocab.end()) { //std::cerr << "tok=" << tok << std::endl; vocab[tok] = 1; } else { //std::cerr << "tok=" << tok << std::endl; size_t &count = iter->second; ++count; } } } // put into vector & sort std::vector<const Str2Id::value_type*> vocabVec; vocabVec.reserve(max); for (const Str2Id::value_type &p: vocab) { //std::cerr << p.first << "=" << p.second << std::endl; vocabVec.push_back(&p); } std::sort(vocabVec.rbegin(), vocabVec.rend(), VocabFreqOrderer()); // put into class variables // AND write to file size_t vocabSize = std::min((size_t) max, vocab.size()); id2str_.resize(vocabSize); OutputFileStream vocabStrm(vocabPath); (std::ostream&) vocabStrm << "{" << std::endl; for (size_t i = 0; i < vocabSize; ++i) { const Str2Id::value_type *p = vocabVec[i]; //std::cerr << p->first << "=" << p->second << std::endl; const std::string &str = p->first; str2id_[str] = i; id2str_.push_back(str); vocabStrm << "\"" << str << "\": " << i; if (i < vocabSize - 1) { vocabStrm << ","; } (std::ostream&) vocabStrm << std::endl; } (std::ostream&) vocabStrm << "}" << std::endl; }
#include <sstream> #include <algorithm> #include "data/vocab.h" #include "common/utils.h" #include "common/file_stream.h" #include "3rd_party/exception.h" #include "3rd_party/yaml-cpp/yaml.h" Vocab::Vocab() { } size_t Vocab::operator[](const std::string& word) const { auto it = str2id_.find(word); if(it != str2id_.end()) return it->second; else return 1; } Words Vocab::operator()(const std::vector<std::string>& lineTokens, bool addEOS) const { Words words(lineTokens.size()); std::transform(lineTokens.begin(), lineTokens.end(), words.begin(), [&](const std::string& w) { return (*this)[w]; }); if(addEOS) words.push_back(EOS); return words; } Words Vocab::operator()(const std::string& line, bool addEOS) const { std::vector<std::string> lineTokens; Split(line, lineTokens, " "); return (*this)(lineTokens, addEOS); } std::vector<std::string> Vocab::operator()(const Words& sentence, bool ignoreEOS) const { std::vector<std::string> decoded; for(size_t i = 0; i < sentence.size(); ++i) { if(sentence[i] != EOS || !ignoreEOS) { decoded.push_back((*this)[sentence[i]]); } } return decoded; } const std::string& Vocab::operator[](size_t id) const { UTIL_THROW_IF2(id >= id2str_.size(), "Unknown word id: " << id); return id2str_[id]; } size_t Vocab::size() const { return id2str_.size(); } void Vocab::load(const std::string& path, int max) { YAML::Node vocab = YAML::Load(InputFileStream(path)); for(auto&& pair : vocab) { auto str = pair.first.as<std::string>(); auto id = pair.second.as<Word>(); if (id < (Word)max) { str2id_[str] = id; if(id >= id2str_.size()) id2str_.resize(id + 1); id2str_[id] = str; } } UTIL_THROW_IF2(id2str_.empty(), "Empty vocabulary " << path); id2str_[0] = "</s>"; } class Vocab::VocabFreqOrderer { public: bool operator()(const Vocab::Str2Id::value_type* a, const Vocab::Str2Id::value_type* b) const { return a->second < b->second; } }; void Vocab::create(const std::string& vocabPath, int max, const std::string& trainPath) { UTIL_THROW_IF2(boost::filesystem::exists(vocabPath), "Vocab file " << vocabPath << " exist. Not overwriting"); //std::cerr << "Vocab::create" << std::endl; InputFileStream trainStrm(trainPath); // create freqency list, reuse Str2Id but use Id to store freq Str2Id vocab; std::string line; while (getline((std::istream&)trainStrm, line)) { //std::cerr << "line=" << line << std::endl; std::vector<std::string> toks; Split(line, toks); for (const std::string &tok: toks) { Str2Id::iterator iter = vocab.find(tok); if (iter == vocab.end()) { //std::cerr << "tok=" << tok << std::endl; vocab[tok] = 1; } else { //std::cerr << "tok=" << tok << std::endl; size_t &count = iter->second; ++count; } } } // put into vector & sort std::vector<const Str2Id::value_type*> vocabVec; vocabVec.reserve(max); for (const Str2Id::value_type &p: vocab) { //std::cerr << p.first << "=" << p.second << std::endl; vocabVec.push_back(&p); } std::sort(vocabVec.rbegin(), vocabVec.rend(), VocabFreqOrderer()); // put into class variables // AND write to file size_t vocabSize = std::min((size_t) max, vocab.size()); id2str_.resize(vocabSize); OutputFileStream vocabStrm(vocabPath); vocabStrm << "{\n" << "\"eos\": 0,\n" << "\"UNK\": 1,\n"; for (size_t i = 0; i < vocabSize; ++i) { const Str2Id::value_type *p = vocabVec[i]; //std::cerr << p->first << "=" << p->second << std::endl; const std::string &str = p->first; str2id_[str] = i; id2str_.push_back(str); vocabStrm << "\"" << str << "\": " << (i + 2); if (i < vocabSize - 1) { vocabStrm << ","; } (std::ostream&) vocabStrm << std::endl; } (std::ostream&) vocabStrm << "}" << std::endl; }
add eos and UNK
add eos and UNK
C++
mit
marian-nmt/marian-train,emjotde/amunmt,marian-nmt/marian-train,DianaDespa/marian-train,emjotde/Marian,emjotde/amunmt,emjotde/amunn,emjotde/amunn,emjotde/amunn,emjotde/Marian,amunmt/marian,DianaDespa/marian-train,emjotde/amunn,emjotde/amunmt,emjotde/amunmt,amunmt/marian,DianaDespa/marian-train,marian-nmt/marian-train,amunmt/marian,DianaDespa/marian-train,DianaDespa/marian-train,marian-nmt/marian-train,marian-nmt/marian-train