text
stringlengths
54
60.6k
<commit_before>#include <algorithm> #include <stack> #include <variant> #include "dDNNFTreeDecompositionBuilder.h" /* Turn a bounded-treewidth circuit c for which a tree decomposition td * is provided into a dNNF rooted at root, following the construction in * Section 5.1 of https://arxiv.org/pdf/1811.02944 */ dDNNF&& dDNNFTreeDecompositionBuilder::build() && { // We make the tree decomposition friendly td.makeFriendly(root_id); // We look for bags responsible for each variable for(bag_t i{0}; i<td.bags.size(); ++i) { const auto &b = td.getBag(i); if(td.getChildren(i).empty() && b.size()==1 && c.getGateType(*b.begin()) == BooleanGate::IN) responsible_bag[*b.begin()] = i; } // A friendly tree decomposition has leaf bags for every variable // nodes. Let's just check that to be safe. assert(responsible_bag.size()==c.inputs.size()); // Create the input and negated input gates for(auto g: c.inputs) { auto gate = d.setGate(BooleanGate::IN, c.getProb(g)); auto not_gate = d.setGate(BooleanGate::NOT); d.addWire(not_gate, gate); input_gate[g]=gate; negated_input_gate[g]=not_gate; } gate_vector_t<dDNNFGate> result_gates = builddDNNF(); auto result_id = d.setGate("root", BooleanGate::OR); for(const auto &p: result_gates) { if(p.suspicious.empty() && p.valuation.find(root_id)->second) { d.addWire(result_id, p.id); break; } } return std::move(d); } constexpr bool isStrong(BooleanGate type, bool value) { switch(type) { case BooleanGate::OR: return value; case BooleanGate::AND: return !value; case BooleanGate::IN: return false; default: return true; } } static bool isConnectible(const dDNNFTreeDecompositionBuilder::suspicious_t &suspicious, const TreeDecomposition::Bag &b) { for(const auto &g: suspicious) { if(b.find(g)==b.end()) return false; } return true; } dDNNFTreeDecompositionBuilder::gate_vector_t<dDNNFTreeDecompositionBuilder::dDNNFGate> dDNNFTreeDecompositionBuilder::builddDNNFLeaf( bag_t bag) { // If the bag is empty, it behaves as if it was not there if(td.getBag(bag).size()==0) return {}; // Otherwise, since we have a friendly decomposition, we have a // single gate auto single_gate = *td.getBag(bag).begin(); // We check if this bag is responsible for an input variable if(c.getGateType(single_gate)==BooleanGate::IN && responsible_bag.find(single_gate)->second==bag) { // No need to create an extra gate, just point to the variable and // negated variable gate; no suspicious gate. dDNNFGate pos = { input_gate.find(single_gate)->second, {std::make_pair(single_gate,true)}, suspicious_t{} }; dDNNFGate neg = { negated_input_gate.find(single_gate)->second, {std::make_pair(single_gate,false)}, suspicious_t{} }; return { std::move(pos), std::move(neg) }; } else { gate_vector_t<dDNNFGate> result_gates; // We create two TRUE gates (AND gates with no inputs) for(auto v: {true, false}) { // Optimization: we know the root is set to True, so no need to // construct valuations incompatible with this if(single_gate==root_id && !v) continue; suspicious_t suspicious; if(isStrong(c.getGateType(single_gate), v)) suspicious.insert(single_gate); result_gates.emplace_back( d.setGate(BooleanGate::AND), valuation_t{std::make_pair(single_gate, v)}, std::move(suspicious) ); } return result_gates; } } bool dDNNFTreeDecompositionBuilder::isAlmostValuation( const valuation_t &valuation) const { for(const auto &p1: valuation) { for(const auto &p2: valuation) { if(p1.first==p2.first) continue; if(!isStrong(c.getGateType(p1.first),p2.second)) continue; if(circuitHasWire(p1.first,p2.first)) { switch(c.getGateType(p1.first)) { case BooleanGate::AND: case BooleanGate::OR: if(p1.second!=p2.second) return false; break; case BooleanGate::NOT: if(p1.second==p2.second) return false; default: ; } } } } return true; } dDNNFTreeDecompositionBuilder::suspicious_t dDNNFTreeDecompositionBuilder::getInnocent( const valuation_t &valuation, const suspicious_t &innocent) const { suspicious_t result = innocent; for(const auto &[g1,val]: valuation) { if(innocent.find(g1)!=innocent.end()) continue; // We check if it is strong, if not it is innocent if(!isStrong(c.getGateType(g1), valuation.find(g1)->second)) { result.insert(g1); continue; } // We have a strong gate not innocented by the children bags, // it is only innocent if we also have in the bag an input to // that gate which is strong for that gate for(const auto &[g2, value]: valuation) { if(g2==g1) continue; if(circuitHasWire(g1,g2)) { if(isStrong(c.getGateType(g1), value)) { result.insert(g1); break; } } } } return result; } std::ostream &operator<<(std::ostream &o, const dDNNFTreeDecompositionBuilder::gates_to_or_t &gates_to_or) { for(auto &[valuation, m]: gates_to_or) { o << "{"; bool first=true; for(auto &[var, val]: valuation) { if(!first) o << ","; o << "(" << var << "," << val << ")"; first=false; } o << "}: "; for(auto &[innocent, gates]: m) { o << "{"; bool first=true; for(auto &x: innocent) { if(!first) o << ","; o << x; first=false; } o << "} "; o << "["; first=true; for(auto &x: gates) { if(!first) o << ","; o << x; first=false; } o << "] "; } o << "\n"; } return o; } dDNNFTreeDecompositionBuilder::gates_to_or_t dDNNFTreeDecompositionBuilder::collectGatesToOr( bag_t bag, const gate_vector_t<dDNNFGate> &children_gates, const gates_to_or_t &partial) { gates_to_or_t gates_to_or; for(auto g: children_gates) { // We check all suspicious gates are in the bag of the parent if(!isConnectible(g.suspicious,td.getBag(bag))) continue; // Find all valuations in partial that are compatible with this partial // valuation, if it exists auto compatibleValuation = [&g](const auto &p) { for(const auto &[var, val]: p.first) { auto it = g.valuation.find(var); if(it != g.valuation.end() && it->second != val) return false; } return true; }; for (auto it = std::find_if(partial.begin(), partial.end(), compatibleValuation); it != partial.end(); it = std::find_if(std::next(it), partial.end(), compatibleValuation)) { auto &[matching_valuation, m] = *it; valuation_t valuation = matching_valuation; suspicious_t extra_innocent{}; for(auto &[var, val]: g.valuation) { if(td.getBag(bag).find(var)!=td.getBag(bag).end()) { if(matching_valuation.find(var)==matching_valuation.end()) valuation[var]=val; if(g.suspicious.find(var)==g.suspicious.end()) { extra_innocent.insert(var); } } } // We check valuation is still an almost-valuation if(!isAlmostValuation(valuation)) continue; for(auto &[innocent, gates]: m) { suspicious_t new_innocent = std::move(extra_innocent); for(auto s: innocent) new_innocent.insert(s); new_innocent = getInnocent(valuation, new_innocent); if(gates.empty()) gates_to_or[valuation][new_innocent].push_back(g.id); else { for(auto g2: gates) { gate_t and_gate; // We optimize a bit by avoiding creating an AND gate if there // is only one child, or if a second child is a TRUE gate gate_t gates_children[2]; unsigned nb = 0; if(!(d.getGateType(g.id)==BooleanGate::AND && d.getWires(g.id).empty())) gates_children[nb++]=g.id; if(!(d.getGateType(g2)==BooleanGate::AND && d.getWires(g2).empty())) gates_children[nb++]=g2; if(nb==0) { // We have one (or two) TRUE gates; we just reuse it -- even // though we reuse a child gate, connections will still make // sense as the valuation and suspicious set been correctly // computed and_gate = g.id; } else if(nb==1) { // Only one non-TRUE gate; we reuse it. Similarly as in the // previous case, even though we reuse this gate, the connections // made from it will still take into account the valuation and // suspicious set and_gate = gates_children[0]; } else { and_gate = d.setGate(BooleanGate::AND); for(auto x: gates_children) { d.addWire(and_gate, x); } } gates_to_or[valuation][new_innocent].push_back(and_gate); } } } } } return gates_to_or; } dDNNFTreeDecompositionBuilder::gate_vector_t<dDNNFTreeDecompositionBuilder::dDNNFGate> dDNNFTreeDecompositionBuilder::builddDNNF() { // Unfortunately, tree decompositions can be quite deep so we need to // simulate recursion with a heap-based stack, to avoid exhausting the // actual memory stack struct RecursionParams { bag_t bag; size_t children_processed; gates_to_or_t gates_to_or; RecursionParams(bag_t b, size_t c, gates_to_or_t g) : bag(b), children_processed(c), gates_to_or(std::move(g)) {} RecursionParams(bag_t b) : bag(b), children_processed(0) { gates_to_or_t::mapped_type m; m[suspicious_t{}] = {}; gates_to_or[valuation_t{}] = std::move(m); } }; using RecursionResult = gate_vector_t<dDNNFGate>; std::stack<std::variant<RecursionParams,RecursionResult>> stack; stack.emplace(RecursionParams{td.root}); while(!stack.empty()) { RecursionResult result; if(stack.top().index()==1) { // RecursionResult result = std::move(std::get<1>(stack.top())); stack.pop(); if(stack.empty()) return result; } auto [bag, children_processed, gates_to_or] = std::move(std::get<0>(stack.top())); stack.pop(); if(td.getChildren(bag).empty()) { auto x = builddDNNFLeaf(bag); stack.emplace(x); } else { if(children_processed>0) { gates_to_or = collectGatesToOr(bag, result, gates_to_or); } if(children_processed==td.getChildren(bag).size()) { gate_vector_t<dDNNFGate> result_gates; for(auto &[valuation, m]: gates_to_or) { for(auto &[innocent, gates]: m) { gate_t result_gate; assert(gates.size()!=0); suspicious_t suspicious; for(auto &[var, val]: valuation) if(innocent.find(var)==innocent.end()) suspicious.insert(var); if(gates.size()==1) result_gate = *gates.begin(); else { result_gate = d.setGate(BooleanGate::OR); for(auto &g: gates) { d.addWire(result_gate, g); } } result_gates.emplace_back(result_gate, std::move(valuation), std::move(suspicious)); } } stack.emplace(std::move(result_gates)); } else { stack.emplace(RecursionParams{bag, children_processed+1, std::move(gates_to_or)}); stack.emplace(RecursionParams{td.getChildren(bag)[children_processed]}); } } } // We return from within the while loop, when we hit the last return // value assert(false); } std::ostream &operator<<(std::ostream &o, const dDNNFTreeDecompositionBuilder::dDNNFGate &g) { o << g.id << "; {"; bool first=true; for(const auto &p: g.valuation) { if(!first) o << ","; first=false; o << "(" << p.first << "," << p.second << ")"; } o << "}; {"; first=true; for(auto x: g.suspicious) { if(!first) o << ","; first=false; o << x; } o << "}"; return o; } bool dDNNFTreeDecompositionBuilder::circuitHasWire(gate_t f, gate_t t) const { return wiresSet.find(std::make_pair(f,t))!=wiresSet.end(); } <commit_msg>Fix wrong std::move<commit_after>#include <algorithm> #include <stack> #include <variant> #include "dDNNFTreeDecompositionBuilder.h" /* Turn a bounded-treewidth circuit c for which a tree decomposition td * is provided into a dNNF rooted at root, following the construction in * Section 5.1 of https://arxiv.org/pdf/1811.02944 */ dDNNF&& dDNNFTreeDecompositionBuilder::build() && { // We make the tree decomposition friendly td.makeFriendly(root_id); // We look for bags responsible for each variable for(bag_t i{0}; i<td.bags.size(); ++i) { const auto &b = td.getBag(i); if(td.getChildren(i).empty() && b.size()==1 && c.getGateType(*b.begin()) == BooleanGate::IN) responsible_bag[*b.begin()] = i; } // A friendly tree decomposition has leaf bags for every variable // nodes. Let's just check that to be safe. assert(responsible_bag.size()==c.inputs.size()); // Create the input and negated input gates for(auto g: c.inputs) { auto gate = d.setGate(BooleanGate::IN, c.getProb(g)); auto not_gate = d.setGate(BooleanGate::NOT); d.addWire(not_gate, gate); input_gate[g]=gate; negated_input_gate[g]=not_gate; } gate_vector_t<dDNNFGate> result_gates = builddDNNF(); auto result_id = d.setGate("root", BooleanGate::OR); for(const auto &p: result_gates) { if(p.suspicious.empty() && p.valuation.find(root_id)->second) { d.addWire(result_id, p.id); break; } } return std::move(d); } constexpr bool isStrong(BooleanGate type, bool value) { switch(type) { case BooleanGate::OR: return value; case BooleanGate::AND: return !value; case BooleanGate::IN: return false; default: return true; } } static bool isConnectible(const dDNNFTreeDecompositionBuilder::suspicious_t &suspicious, const TreeDecomposition::Bag &b) { for(const auto &g: suspicious) { if(b.find(g)==b.end()) return false; } return true; } dDNNFTreeDecompositionBuilder::gate_vector_t<dDNNFTreeDecompositionBuilder::dDNNFGate> dDNNFTreeDecompositionBuilder::builddDNNFLeaf( bag_t bag) { // If the bag is empty, it behaves as if it was not there if(td.getBag(bag).size()==0) return {}; // Otherwise, since we have a friendly decomposition, we have a // single gate auto single_gate = *td.getBag(bag).begin(); // We check if this bag is responsible for an input variable if(c.getGateType(single_gate)==BooleanGate::IN && responsible_bag.find(single_gate)->second==bag) { // No need to create an extra gate, just point to the variable and // negated variable gate; no suspicious gate. dDNNFGate pos = { input_gate.find(single_gate)->second, {std::make_pair(single_gate,true)}, suspicious_t{} }; dDNNFGate neg = { negated_input_gate.find(single_gate)->second, {std::make_pair(single_gate,false)}, suspicious_t{} }; return { std::move(pos), std::move(neg) }; } else { gate_vector_t<dDNNFGate> result_gates; // We create two TRUE gates (AND gates with no inputs) for(auto v: {true, false}) { // Optimization: we know the root is set to True, so no need to // construct valuations incompatible with this if(single_gate==root_id && !v) continue; suspicious_t suspicious; if(isStrong(c.getGateType(single_gate), v)) suspicious.insert(single_gate); result_gates.emplace_back( d.setGate(BooleanGate::AND), valuation_t{std::make_pair(single_gate, v)}, std::move(suspicious) ); } return result_gates; } } bool dDNNFTreeDecompositionBuilder::isAlmostValuation( const valuation_t &valuation) const { for(const auto &p1: valuation) { for(const auto &p2: valuation) { if(p1.first==p2.first) continue; if(!isStrong(c.getGateType(p1.first),p2.second)) continue; if(circuitHasWire(p1.first,p2.first)) { switch(c.getGateType(p1.first)) { case BooleanGate::AND: case BooleanGate::OR: if(p1.second!=p2.second) return false; break; case BooleanGate::NOT: if(p1.second==p2.second) return false; default: ; } } } } return true; } dDNNFTreeDecompositionBuilder::suspicious_t dDNNFTreeDecompositionBuilder::getInnocent( const valuation_t &valuation, const suspicious_t &innocent) const { suspicious_t result = innocent; for(const auto &[g1,val]: valuation) { if(innocent.find(g1)!=innocent.end()) continue; // We check if it is strong, if not it is innocent if(!isStrong(c.getGateType(g1), valuation.find(g1)->second)) { result.insert(g1); continue; } // We have a strong gate not innocented by the children bags, // it is only innocent if we also have in the bag an input to // that gate which is strong for that gate for(const auto &[g2, value]: valuation) { if(g2==g1) continue; if(circuitHasWire(g1,g2)) { if(isStrong(c.getGateType(g1), value)) { result.insert(g1); break; } } } } return result; } std::ostream &operator<<(std::ostream &o, const dDNNFTreeDecompositionBuilder::gates_to_or_t &gates_to_or) { for(auto &[valuation, m]: gates_to_or) { o << "{"; bool first=true; for(auto &[var, val]: valuation) { if(!first) o << ","; o << "(" << var << "," << val << ")"; first=false; } o << "}: "; for(auto &[innocent, gates]: m) { o << "{"; bool first=true; for(auto &x: innocent) { if(!first) o << ","; o << x; first=false; } o << "} "; o << "["; first=true; for(auto &x: gates) { if(!first) o << ","; o << x; first=false; } o << "] "; } o << "\n"; } return o; } dDNNFTreeDecompositionBuilder::gates_to_or_t dDNNFTreeDecompositionBuilder::collectGatesToOr( bag_t bag, const gate_vector_t<dDNNFGate> &children_gates, const gates_to_or_t &partial) { gates_to_or_t gates_to_or; for(auto g: children_gates) { // We check all suspicious gates are in the bag of the parent if(!isConnectible(g.suspicious,td.getBag(bag))) continue; // Find all valuations in partial that are compatible with this partial // valuation, if it exists auto compatibleValuation = [&g](const auto &p) { for(const auto &[var, val]: p.first) { auto it = g.valuation.find(var); if(it != g.valuation.end() && it->second != val) return false; } return true; }; for (auto it = std::find_if(partial.begin(), partial.end(), compatibleValuation); it != partial.end(); it = std::find_if(std::next(it), partial.end(), compatibleValuation)) { auto &[matching_valuation, m] = *it; valuation_t valuation = matching_valuation; suspicious_t extra_innocent{}; for(auto &[var, val]: g.valuation) { if(td.getBag(bag).find(var)!=td.getBag(bag).end()) { if(matching_valuation.find(var)==matching_valuation.end()) valuation[var]=val; if(g.suspicious.find(var)==g.suspicious.end()) { extra_innocent.insert(var); } } } // We check valuation is still an almost-valuation if(!isAlmostValuation(valuation)) continue; for(auto &[innocent, gates]: m) { suspicious_t new_innocent = extra_innocent; for(auto s: innocent) new_innocent.insert(s); new_innocent = getInnocent(valuation, new_innocent); if(gates.empty()) gates_to_or[valuation][new_innocent].push_back(g.id); else { for(auto g2: gates) { gate_t and_gate; // We optimize a bit by avoiding creating an AND gate if there // is only one child, or if a second child is a TRUE gate gate_t gates_children[2]; unsigned nb = 0; if(!(d.getGateType(g.id)==BooleanGate::AND && d.getWires(g.id).empty())) gates_children[nb++]=g.id; if(!(d.getGateType(g2)==BooleanGate::AND && d.getWires(g2).empty())) gates_children[nb++]=g2; if(nb==0) { // We have one (or two) TRUE gates; we just reuse it -- even // though we reuse a child gate, connections will still make // sense as the valuation and suspicious set been correctly // computed and_gate = g.id; } else if(nb==1) { // Only one non-TRUE gate; we reuse it. Similarly as in the // previous case, even though we reuse this gate, the connections // made from it will still take into account the valuation and // suspicious set and_gate = gates_children[0]; } else { and_gate = d.setGate(BooleanGate::AND); for(auto x: gates_children) { d.addWire(and_gate, x); } } gates_to_or[valuation][new_innocent].push_back(and_gate); } } } } } return gates_to_or; } dDNNFTreeDecompositionBuilder::gate_vector_t<dDNNFTreeDecompositionBuilder::dDNNFGate> dDNNFTreeDecompositionBuilder::builddDNNF() { // Unfortunately, tree decompositions can be quite deep so we need to // simulate recursion with a heap-based stack, to avoid exhausting the // actual memory stack struct RecursionParams { bag_t bag; size_t children_processed; gates_to_or_t gates_to_or; RecursionParams(bag_t b, size_t c, gates_to_or_t g) : bag(b), children_processed(c), gates_to_or(std::move(g)) {} RecursionParams(bag_t b) : bag(b), children_processed(0) { gates_to_or_t::mapped_type m; m[suspicious_t{}] = {}; gates_to_or[valuation_t{}] = std::move(m); } }; using RecursionResult = gate_vector_t<dDNNFGate>; std::stack<std::variant<RecursionParams,RecursionResult>> stack; stack.emplace(RecursionParams{td.root}); while(!stack.empty()) { RecursionResult result; if(stack.top().index()==1) { // RecursionResult result = std::move(std::get<1>(stack.top())); stack.pop(); if(stack.empty()) return result; } auto [bag, children_processed, gates_to_or] = std::move(std::get<0>(stack.top())); stack.pop(); if(td.getChildren(bag).empty()) { auto x = builddDNNFLeaf(bag); stack.emplace(x); } else { if(children_processed>0) { gates_to_or = collectGatesToOr(bag, result, gates_to_or); } if(children_processed==td.getChildren(bag).size()) { gate_vector_t<dDNNFGate> result_gates; for(auto &[valuation, m]: gates_to_or) { for(auto &[innocent, gates]: m) { gate_t result_gate; assert(gates.size()!=0); suspicious_t suspicious; for(auto &[var, val]: valuation) if(innocent.find(var)==innocent.end()) suspicious.insert(var); if(gates.size()==1) result_gate = *gates.begin(); else { result_gate = d.setGate(BooleanGate::OR); for(auto &g: gates) { d.addWire(result_gate, g); } } result_gates.emplace_back(result_gate, std::move(valuation), std::move(suspicious)); } } stack.emplace(std::move(result_gates)); } else { stack.emplace(RecursionParams{bag, children_processed+1, std::move(gates_to_or)}); stack.emplace(RecursionParams{td.getChildren(bag)[children_processed]}); } } } // We return from within the while loop, when we hit the last return // value assert(false); } std::ostream &operator<<(std::ostream &o, const dDNNFTreeDecompositionBuilder::dDNNFGate &g) { o << g.id << "; {"; bool first=true; for(const auto &p: g.valuation) { if(!first) o << ","; first=false; o << "(" << p.first << "," << p.second << ")"; } o << "}; {"; first=true; for(auto x: g.suspicious) { if(!first) o << ","; first=false; o << x; } o << "}"; return o; } bool dDNNFTreeDecompositionBuilder::circuitHasWire(gate_t f, gate_t t) const { return wiresSet.find(std::make_pair(f,t))!=wiresSet.end(); } <|endoftext|>
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*- uiserver/uiserver.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra 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. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "uiserver.h" #include "assuanserverconnection.h" #include "assuancommand.h" #include "kleo-assuan.h" #include "detail_p.h" #include <ktempdir.h> #include <QTcpServer> #include <QTcpSocket> #include <QFile> #include <QDir> #include <QTextStream> #include <QEventLoop> #include <QTimer> #include <boost/range/empty.hpp> #include <boost/bind.hpp> #include <stdexcept> #include <cassert> #ifdef Q_OS_WIN32 # include <windows.h> # include <io.h> #else # include <sys/types.h> # include <sys/socket.h> # include <sys/un.h> # include <cstdio> # include <cerrno> # include <cstring> #endif using namespace Kleo; using namespace boost; namespace { template <typename Ex> void throw_( const QString & message ) { throw Ex( message.toUtf8().constData() ); } static QString tmpDirPrefix() { return QDir::temp().absoluteFilePath( "gpg-" ); } } class UiServer::Private : public QTcpServer { Q_OBJECT friend class ::Kleo::UiServer; UiServer * const q; public: explicit Private( UiServer * qq ); private: void makeListeningSocket(); QString makeFileName() const; protected: /* reimp */ void incomingConnection( int fd ); private Q_SLOTS: void slotConnectionClosed( Kleo::AssuanServerConnection * conn ) { connections.erase( std::remove_if( connections.begin(), connections.end(), bind( &shared_ptr<AssuanServerConnection>::get, _1 ) == conn ), connections.end() ); if ( q->isStopped() ) emit q->stopped(); } private: KTempDir tmpDir; QFile file; std::vector< shared_ptr<AssuanCommandFactory> > factories; std::vector< shared_ptr<AssuanServerConnection> > connections; }; UiServer::Private::Private( UiServer * qq ) : QTcpServer(), q( qq ), tmpDir( tmpDirPrefix() ), file(), factories(), connections() { } UiServer::UiServer( QObject * p ) : QObject( p ), d( new Private( this ) ) { } UiServer::~UiServer() {} bool UiServer::registerCommandFactory( const shared_ptr<AssuanCommandFactory> & cf ) { if ( cf && empty( std::equal_range( d->factories.begin(), d->factories.end(), cf, _detail::ByName<std::less>() ) ) ) { d->factories.push_back( cf ); std::inplace_merge( d->factories.begin(), d->factories.end() - 1, d->factories.end() ); return true; } else { qWarning( "UiServer::registerCommandFactory( %p ): factory NULL or already registered", cf ? cf.get() : 0 ); return false; } } void UiServer::start() { d->makeListeningSocket(); } void UiServer::stop() { d->close(); if ( d->file.exists() ) d->file.remove(); } bool UiServer::waitForStopped( unsigned int ms ) { if ( isStopped() ) return true; QEventLoop loop; QTimer timer; timer.setInterval( ms ); timer.setSingleShot( true ); connect( &timer, SIGNAL(timeout()), &loop, SLOT(quit()) ); connect( this, SIGNAL(stopped()), &loop, SLOT(quit()) ); loop.exec(); return !timer.isActive(); } bool UiServer::isStopped() const { return d->connections.empty() && !d->isListening() ; } bool UiServer::isStopping() const { return !d->connections.empty() && !d->isListening() ; } QString UiServer::Private::makeFileName() const { if ( tmpDir.status() != 0 ) throw_<std::runtime_error>( tr( "Couldn't create directory %1: %2" ).arg( tmpDirPrefix() + "XXXXXXXX", QString::fromLocal8Bit( strerror(errno) ) ) ); const QDir dir( tmpDir.name() ); assert( dir.exists() ); return dir.absoluteFilePath( "S.uiserver" ); } #ifndef Q_OS_WIN32 static inline QString system_error_string() { return QString::fromLocal8Bit( strerror(errno) ); } void UiServer::Private::makeListeningSocket() { // First, create a file (we do this only for the name, gmpfh) const QString fileName = makeFileName(); if ( QFile::exists( fileName ) ) throw_<std::runtime_error>( tr( "Detected another running gnupg UI server listening at %1." ).arg( fileName ) ); const QByteArray encodedFileName = QFile::encodeName( fileName ); // Create a Unix Domain Socket: const int sock = ::socket( AF_UNIX, SOCK_STREAM, 0 ); if ( sock < 0 ) throw_<std::runtime_error>( tr( "Couldn't create socket: %1" ).arg( system_error_string() ) ); try { // Bind struct sockaddr_un sa; std::memset( &sa, 0, sizeof(sa) ); sa.sun_family = AF_UNIX; std::strncpy( sa.sun_path, encodedFileName.constData(), sizeof( sa.sun_path ) ); if ( ::bind( sock, (struct sockaddr*)&sa, sizeof( sa ) ) ) throw_<std::runtime_error>( tr( "Couldn't bind to socket: %1" ).arg( system_error_string() ) ); // TODO: permissions? // Listen if ( ::listen( sock, SOMAXCONN ) ) throw_<std::runtime_error>( tr( "Couldn't listen to socket: %1" ).arg( system_error_string() ) ); if ( !setSocketDescriptor( sock ) ) throw_<std::runtime_error>( tr( "Couldn't pass socket to Qt: %1. This should not happen, please report this bug." ).arg( errorString() ) ); } catch ( ... ) { ::close( sock ); throw; } } #else // The Windows case is simpler, because we use a TCP socket here, so // we use vanilla QTcpServer: void UiServer::Private::makeListeningSocket() { // First, create a tempfile that will contain the port we're // listening on: file.setFileName( makeFileName() ); if ( !file.open( QIODevice::WriteOnly ) ) throw_<std::runtime_error>( tr( "Couldn't create temporary file: %1" ).arg( file.errorString() ) ); // now, start listening to the host: if ( !listen( QHostAddress::LocalHost ) ) throw_<std::runtime_error>( tr( "UiServer: listen failed: %1" ).arg( errorString() ) ); QTextStream( &file ) << serverPort() << endl; file.close(); } #endif void UiServer::Private::incomingConnection( int fd ) { try { const shared_ptr<AssuanServerConnection> c( new AssuanServerConnection( fd, factories ) ); connect( c.get(), SIGNAL(closed(Kleo::AssuanServerConnection*)), this, SLOT(slotConnectionClosed(Kleo::AssuanServerConnection*)) ); connections.push_back( c ); } catch ( const assuan_exception & e ) { QTcpSocket s; s.setSocketDescriptor( fd ); QTextStream( &s ) << "ERR " << e.error_code() << " " << e.what() << "\r\n"; s.waitForBytesWritten(); s.close(); } catch ( ... ) { // this should never happen... QTcpSocket s; s.setSocketDescriptor( fd ); QTextStream( &s ) << "ERR 63 unknown exception caught\r\n"; s.waitForBytesWritten(); s.close(); } } #include "uiserver.moc" #include "moc_uiserver.cpp" <commit_msg>Don't fail the is_sorted assertion AssuanServerConnection by using the corrort sorting predicate here. Hail assertions!<commit_after>/* -*- mode: c++; c-basic-offset:4 -*- uiserver/uiserver.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra 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. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "uiserver.h" #include "assuanserverconnection.h" #include "assuancommand.h" #include "kleo-assuan.h" #include "detail_p.h" #include <ktempdir.h> #include <QTcpServer> #include <QTcpSocket> #include <QFile> #include <QDir> #include <QTextStream> #include <QEventLoop> #include <QTimer> #include <boost/range/empty.hpp> #include <boost/bind.hpp> #include <stdexcept> #include <cassert> #ifdef Q_OS_WIN32 # include <windows.h> # include <io.h> #else # include <sys/types.h> # include <sys/socket.h> # include <sys/un.h> # include <cstdio> # include <cerrno> # include <cstring> #endif using namespace Kleo; using namespace boost; namespace { template <typename Ex> void throw_( const QString & message ) { throw Ex( message.toUtf8().constData() ); } static QString tmpDirPrefix() { return QDir::temp().absoluteFilePath( "gpg-" ); } } class UiServer::Private : public QTcpServer { Q_OBJECT friend class ::Kleo::UiServer; UiServer * const q; public: explicit Private( UiServer * qq ); private: void makeListeningSocket(); QString makeFileName() const; protected: /* reimp */ void incomingConnection( int fd ); private Q_SLOTS: void slotConnectionClosed( Kleo::AssuanServerConnection * conn ) { connections.erase( std::remove_if( connections.begin(), connections.end(), bind( &shared_ptr<AssuanServerConnection>::get, _1 ) == conn ), connections.end() ); if ( q->isStopped() ) emit q->stopped(); } private: KTempDir tmpDir; QFile file; std::vector< shared_ptr<AssuanCommandFactory> > factories; std::vector< shared_ptr<AssuanServerConnection> > connections; }; UiServer::Private::Private( UiServer * qq ) : QTcpServer(), q( qq ), tmpDir( tmpDirPrefix() ), file(), factories(), connections() { } UiServer::UiServer( QObject * p ) : QObject( p ), d( new Private( this ) ) { } UiServer::~UiServer() {} bool UiServer::registerCommandFactory( const shared_ptr<AssuanCommandFactory> & cf ) { if ( cf && empty( std::equal_range( d->factories.begin(), d->factories.end(), cf, _detail::ByName<std::less>() ) ) ) { d->factories.push_back( cf ); std::inplace_merge( d->factories.begin(), d->factories.end() - 1, d->factories.end(), _detail::ByName<std::less>() ); return true; } else { qWarning( "UiServer::registerCommandFactory( %p ): factory NULL or already registered", cf ? cf.get() : 0 ); return false; } } void UiServer::start() { d->makeListeningSocket(); } void UiServer::stop() { d->close(); if ( d->file.exists() ) d->file.remove(); } bool UiServer::waitForStopped( unsigned int ms ) { if ( isStopped() ) return true; QEventLoop loop; QTimer timer; timer.setInterval( ms ); timer.setSingleShot( true ); connect( &timer, SIGNAL(timeout()), &loop, SLOT(quit()) ); connect( this, SIGNAL(stopped()), &loop, SLOT(quit()) ); loop.exec(); return !timer.isActive(); } bool UiServer::isStopped() const { return d->connections.empty() && !d->isListening() ; } bool UiServer::isStopping() const { return !d->connections.empty() && !d->isListening() ; } QString UiServer::Private::makeFileName() const { if ( tmpDir.status() != 0 ) throw_<std::runtime_error>( tr( "Couldn't create directory %1: %2" ).arg( tmpDirPrefix() + "XXXXXXXX", QString::fromLocal8Bit( strerror(errno) ) ) ); const QDir dir( tmpDir.name() ); assert( dir.exists() ); return dir.absoluteFilePath( "S.uiserver" ); } #ifndef Q_OS_WIN32 static inline QString system_error_string() { return QString::fromLocal8Bit( strerror(errno) ); } void UiServer::Private::makeListeningSocket() { // First, create a file (we do this only for the name, gmpfh) const QString fileName = makeFileName(); if ( QFile::exists( fileName ) ) throw_<std::runtime_error>( tr( "Detected another running gnupg UI server listening at %1." ).arg( fileName ) ); const QByteArray encodedFileName = QFile::encodeName( fileName ); // Create a Unix Domain Socket: const int sock = ::socket( AF_UNIX, SOCK_STREAM, 0 ); if ( sock < 0 ) throw_<std::runtime_error>( tr( "Couldn't create socket: %1" ).arg( system_error_string() ) ); try { // Bind struct sockaddr_un sa; std::memset( &sa, 0, sizeof(sa) ); sa.sun_family = AF_UNIX; std::strncpy( sa.sun_path, encodedFileName.constData(), sizeof( sa.sun_path ) ); if ( ::bind( sock, (struct sockaddr*)&sa, sizeof( sa ) ) ) throw_<std::runtime_error>( tr( "Couldn't bind to socket: %1" ).arg( system_error_string() ) ); // TODO: permissions? // Listen if ( ::listen( sock, SOMAXCONN ) ) throw_<std::runtime_error>( tr( "Couldn't listen to socket: %1" ).arg( system_error_string() ) ); if ( !setSocketDescriptor( sock ) ) throw_<std::runtime_error>( tr( "Couldn't pass socket to Qt: %1. This should not happen, please report this bug." ).arg( errorString() ) ); } catch ( ... ) { ::close( sock ); throw; } } #else // The Windows case is simpler, because we use a TCP socket here, so // we use vanilla QTcpServer: void UiServer::Private::makeListeningSocket() { // First, create a tempfile that will contain the port we're // listening on: file.setFileName( makeFileName() ); if ( !file.open( QIODevice::WriteOnly ) ) throw_<std::runtime_error>( tr( "Couldn't create temporary file: %1" ).arg( file.errorString() ) ); // now, start listening to the host: if ( !listen( QHostAddress::LocalHost ) ) throw_<std::runtime_error>( tr( "UiServer: listen failed: %1" ).arg( errorString() ) ); QTextStream( &file ) << serverPort() << endl; file.close(); } #endif void UiServer::Private::incomingConnection( int fd ) { try { const shared_ptr<AssuanServerConnection> c( new AssuanServerConnection( fd, factories ) ); connect( c.get(), SIGNAL(closed(Kleo::AssuanServerConnection*)), this, SLOT(slotConnectionClosed(Kleo::AssuanServerConnection*)) ); connections.push_back( c ); } catch ( const assuan_exception & e ) { QTcpSocket s; s.setSocketDescriptor( fd ); QTextStream( &s ) << "ERR " << e.error_code() << " " << e.what() << "\r\n"; s.waitForBytesWritten(); s.close(); } catch ( ... ) { // this should never happen... QTcpSocket s; s.setSocketDescriptor( fd ); QTextStream( &s ) << "ERR 63 unknown exception caught\r\n"; s.waitForBytesWritten(); s.close(); } } #include "uiserver.moc" #include "moc_uiserver.cpp" <|endoftext|>
<commit_before>// // Implements the following classes: // // AutoDialog - An improvement to wxDialog which makes validation easier. // // AutoPanel - An improvement to wxPanel which makes validation easier. // // wxNumericValidator - A validator capable of transfering numeric values. // // Copyright (c) 2001-2006 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "AutoDialog.h" ///////////////////////////////////////////////// // wxNumericValidator::wxNumericValidator(int *val) : wxValidator() { Initialize(); m_pValInt = val; } wxNumericValidator::wxNumericValidator(float *val, int digits) : wxValidator() { Initialize(); m_pValFloat = val; m_iDigits = digits; } wxNumericValidator::wxNumericValidator(double *val, int digits) : wxValidator() { Initialize(); m_pValDouble = val; m_iDigits = digits; } wxNumericValidator::wxNumericValidator(const wxNumericValidator& val) { Initialize(); Copy(val); } /* Called by constructors to initialize ALL data members */ void wxNumericValidator::Initialize() { m_pValInt = NULL; m_pValFloat = NULL; m_pValDouble = NULL; m_iDigits = 0; m_bEnabled = true; } bool wxNumericValidator::Copy(const wxNumericValidator& val) { wxValidator::Copy(val); m_pValInt = val.m_pValInt; m_pValFloat = val.m_pValFloat; m_pValDouble = val.m_pValDouble; m_iDigits = val.m_iDigits; return true; } // Called to transfer data to the window bool wxNumericValidator::TransferToWindow() { if ( !m_validatorWindow ) return false; if ( !m_bEnabled ) return true; wxString str, format; if (m_pValInt) str.Printf(_T("%d"), *m_pValInt); if (m_pValFloat) { if (m_iDigits != -1) { format.Printf(_T("%%.%df"), m_iDigits); str.Printf(format, *m_pValFloat); } else str.Printf(_T("%.8g"), *m_pValFloat); // 8 significant digits } if (m_pValDouble) { if (m_iDigits != -1) { format.Printf(_T("%%.%dlf"), m_iDigits); str.Printf(format, *m_pValDouble); } else str.Printf(_T("%.16lg"), *m_pValDouble); // 16 significant digits } if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) ) { wxStaticText* pControl = (wxStaticText*) m_validatorWindow; if (pControl) { pControl->SetLabel(str) ; return true; } } else if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) ) { wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow; if (pControl) { pControl->SetValue(str) ; return true; } } else return false; // unrecognized control, or bad pointer return false; } // Called to transfer data from the window bool wxNumericValidator::TransferFromWindow() { if ( !m_validatorWindow ) return false; if ( !m_bEnabled ) return true; // string controls wxString str; if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) ) { wxStaticText* pControl = (wxStaticText*) m_validatorWindow; if (pControl) str = pControl->GetLabel() ; } else if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) ) { wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow; if (pControl) str = pControl->GetValue() ; } else // unrecognized control, or bad pointer return false; if (str != _T("")) { const char *ccs = str.mb_str(*wxConvCurrent); if (m_pValInt) sscanf(ccs, "%d", m_pValInt); if (m_pValFloat) sscanf(ccs, "%f", m_pValFloat); if (m_pValDouble) sscanf(ccs, "%lf", m_pValDouble); return true; } return false; } ///////////////////////////////////////////////// // void AutoDialog::AddValidator(long id, wxString *sptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; pWin->SetValidator(wxGenericValidator(sptr)); // actually clones the one we pass in } void AutoDialog::AddValidator(long id, bool *bptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; pWin->SetValidator(wxGenericValidator(bptr)); // actually clones the one we pass in } void AutoDialog::AddValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; pWin->SetValidator(wxGenericValidator(iptr)); // actually clones the one we pass in } wxNumericValidator *AutoDialog::AddNumValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return NULL; // actually clones the one we pass in pWin->SetValidator(wxNumericValidator(iptr)); return (wxNumericValidator*) pWin->GetValidator(); } wxNumericValidator *AutoDialog::AddNumValidator(long id, float *fptr, int digits) { wxWindow *pWin = FindWindow(id); if (!pWin) return NULL; // actually clones the one we pass in pWin->SetValidator(wxNumericValidator(fptr, digits)); return (wxNumericValidator*) pWin->GetValidator(); } wxNumericValidator *AutoDialog::AddNumValidator(long id, double *dptr, int digits) { wxWindow *pWin = FindWindow(id); if (!pWin) return NULL; // actually clones the one we pass in pWin->SetValidator(wxNumericValidator(dptr, digits)); return (wxNumericValidator*) pWin->GetValidator(); } ///////////////////////////////////////////////// // void AutoPanel::AddValidator(long id, wxString *sptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; pWin->SetValidator(wxGenericValidator(sptr)); // actually clones the one we pass in } void AutoPanel::AddValidator(long id, bool *bptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; pWin->SetValidator(wxGenericValidator(bptr)); // actually clones the one we pass in } void AutoPanel::AddValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; pWin->SetValidator(wxGenericValidator(iptr)); // actually clones the one we pass in } wxNumericValidator *AutoPanel::AddNumValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return NULL; // actually clones the one we pass in pWin->SetValidator(wxNumericValidator(iptr)); return (wxNumericValidator *) pWin->GetValidator(); } wxNumericValidator *AutoPanel::AddNumValidator(long id, float *fptr, int digits) { wxWindow *pWin = FindWindow(id); if (!pWin) return NULL; // actually clones the one we pass in pWin->SetValidator(wxNumericValidator(fptr, digits)); return (wxNumericValidator *) pWin->GetValidator(); } wxNumericValidator *AutoPanel::AddNumValidator(long id, double *dptr, int digits) { wxWindow *pWin = FindWindow(id); if (!pWin) return NULL; pWin->SetValidator(wxNumericValidator(dptr, digits)); // actually clones the one we pass in return (wxNumericValidator *) pWin->GetValidator(); } <commit_msg>avoid intermittent release-mode problem with mb_str temporary buffer<commit_after>// // Implements the following classes: // // AutoDialog - An improvement to wxDialog which makes validation easier. // // AutoPanel - An improvement to wxPanel which makes validation easier. // // wxNumericValidator - A validator capable of transfering numeric values. // // Copyright (c) 2001-2006 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "vtdata/vtString.h" #include "AutoDialog.h" ///////////////////////////////////////////////// // wxNumericValidator::wxNumericValidator(int *val) : wxValidator() { Initialize(); m_pValInt = val; } wxNumericValidator::wxNumericValidator(float *val, int digits) : wxValidator() { Initialize(); m_pValFloat = val; m_iDigits = digits; } wxNumericValidator::wxNumericValidator(double *val, int digits) : wxValidator() { Initialize(); m_pValDouble = val; m_iDigits = digits; } wxNumericValidator::wxNumericValidator(const wxNumericValidator& val) { Initialize(); Copy(val); } /* Called by constructors to initialize ALL data members */ void wxNumericValidator::Initialize() { m_pValInt = NULL; m_pValFloat = NULL; m_pValDouble = NULL; m_iDigits = 0; m_bEnabled = true; } bool wxNumericValidator::Copy(const wxNumericValidator& val) { wxValidator::Copy(val); m_pValInt = val.m_pValInt; m_pValFloat = val.m_pValFloat; m_pValDouble = val.m_pValDouble; m_iDigits = val.m_iDigits; return true; } // Called to transfer data to the window bool wxNumericValidator::TransferToWindow() { if ( !m_validatorWindow ) return false; if ( !m_bEnabled ) return true; wxString str, format; if (m_pValInt) str.Printf(_T("%d"), *m_pValInt); if (m_pValFloat) { if (m_iDigits != -1) { format.Printf(_T("%%.%df"), m_iDigits); str.Printf(format, *m_pValFloat); } else str.Printf(_T("%.8g"), *m_pValFloat); // 8 significant digits } if (m_pValDouble) { if (m_iDigits != -1) { format.Printf(_T("%%.%dlf"), m_iDigits); str.Printf(format, *m_pValDouble); } else str.Printf(_T("%.16lg"), *m_pValDouble); // 16 significant digits } if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) ) { wxStaticText* pControl = (wxStaticText*) m_validatorWindow; if (pControl) { pControl->SetLabel(str) ; return true; } } else if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) ) { wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow; if (pControl) { pControl->SetValue(str) ; return true; } } else return false; // unrecognized control, or bad pointer return false; } // Called to transfer data from the window bool wxNumericValidator::TransferFromWindow() { if ( !m_validatorWindow ) return false; if ( !m_bEnabled ) return true; // string controls wxString str; if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) ) { wxStaticText* pControl = (wxStaticText*) m_validatorWindow; if (pControl) str = pControl->GetLabel() ; } else if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) ) { wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow; if (pControl) str = pControl->GetValue() ; } else // unrecognized control, or bad pointer return false; if (str != _T("")) { vtString ccs = str.mb_str(*wxConvCurrent); if (m_pValInt) sscanf(ccs, "%d", m_pValInt); if (m_pValFloat) sscanf(ccs, "%f", m_pValFloat); if (m_pValDouble) sscanf(ccs, "%lf", m_pValDouble); return true; } return false; } ///////////////////////////////////////////////// // void AutoDialog::AddValidator(long id, wxString *sptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; pWin->SetValidator(wxGenericValidator(sptr)); // actually clones the one we pass in } void AutoDialog::AddValidator(long id, bool *bptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; pWin->SetValidator(wxGenericValidator(bptr)); // actually clones the one we pass in } void AutoDialog::AddValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; pWin->SetValidator(wxGenericValidator(iptr)); // actually clones the one we pass in } wxNumericValidator *AutoDialog::AddNumValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return NULL; // actually clones the one we pass in pWin->SetValidator(wxNumericValidator(iptr)); return (wxNumericValidator*) pWin->GetValidator(); } wxNumericValidator *AutoDialog::AddNumValidator(long id, float *fptr, int digits) { wxWindow *pWin = FindWindow(id); if (!pWin) return NULL; // actually clones the one we pass in pWin->SetValidator(wxNumericValidator(fptr, digits)); return (wxNumericValidator*) pWin->GetValidator(); } wxNumericValidator *AutoDialog::AddNumValidator(long id, double *dptr, int digits) { wxWindow *pWin = FindWindow(id); if (!pWin) return NULL; // actually clones the one we pass in pWin->SetValidator(wxNumericValidator(dptr, digits)); return (wxNumericValidator*) pWin->GetValidator(); } ///////////////////////////////////////////////// // void AutoPanel::AddValidator(long id, wxString *sptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; pWin->SetValidator(wxGenericValidator(sptr)); // actually clones the one we pass in } void AutoPanel::AddValidator(long id, bool *bptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; pWin->SetValidator(wxGenericValidator(bptr)); // actually clones the one we pass in } void AutoPanel::AddValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; pWin->SetValidator(wxGenericValidator(iptr)); // actually clones the one we pass in } wxNumericValidator *AutoPanel::AddNumValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return NULL; // actually clones the one we pass in pWin->SetValidator(wxNumericValidator(iptr)); return (wxNumericValidator *) pWin->GetValidator(); } wxNumericValidator *AutoPanel::AddNumValidator(long id, float *fptr, int digits) { wxWindow *pWin = FindWindow(id); if (!pWin) return NULL; // actually clones the one we pass in pWin->SetValidator(wxNumericValidator(fptr, digits)); return (wxNumericValidator *) pWin->GetValidator(); } wxNumericValidator *AutoPanel::AddNumValidator(long id, double *dptr, int digits) { wxWindow *pWin = FindWindow(id); if (!pWin) return NULL; pWin->SetValidator(wxNumericValidator(dptr, digits)); // actually clones the one we pass in return (wxNumericValidator *) pWin->GetValidator(); } <|endoftext|>
<commit_before>//===-- MachineFunction.cpp -----------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // // Collect native machine code information for a function. This allows // target-specific information about the generated code to be stored with each // function. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineCodeForInstruction.h" #include "llvm/CodeGen/SSARegMap.h" #include "llvm/CodeGen/MachineFunctionInfo.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetCacheInfo.h" #include "llvm/Function.h" #include "llvm/iOther.h" using namespace llvm; static AnnotationID MF_AID( AnnotationManager::getID("CodeGen::MachineCodeForFunction")); namespace { struct Printer : public MachineFunctionPass { std::ostream *OS; const std::string Banner; Printer (std::ostream *_OS, const std::string &_Banner) : OS (_OS), Banner (_Banner) { } const char *getPassName() const { return "MachineFunction Printer"; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } bool runOnMachineFunction(MachineFunction &MF) { (*OS) << Banner; MF.print (*OS); return false; } }; } /// Returns a newly-created MachineFunction Printer pass. The default output /// stream is std::cerr; the default banner is empty. /// FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS, const std::string &Banner) { return new Printer(OS, Banner); } namespace { struct Deleter : public MachineFunctionPass { const char *getPassName() const { return "Machine Code Deleter"; } bool runOnMachineFunction(MachineFunction &MF) { // Delete the annotation from the function now. MachineFunction::destruct(MF.getFunction()); return true; } }; } /// MachineCodeDeletion Pass - This pass deletes all of the machine code for /// the current function, which should happen after the function has been /// emitted to a .s file or to memory. FunctionPass *llvm::createMachineCodeDeleter() { return new Deleter(); } //===---------------------------------------------------------------------===// // MachineFunction implementation //===---------------------------------------------------------------------===// MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM) : Annotation(MF_AID), Fn(F), Target(TM) { SSARegMapping = new SSARegMap(); MFInfo = new MachineFunctionInfo(*this); FrameInfo = new MachineFrameInfo(); ConstantPool = new MachineConstantPool(); } MachineFunction::~MachineFunction() { delete SSARegMapping; delete MFInfo; delete FrameInfo; delete ConstantPool; } void MachineFunction::dump() const { print(std::cerr); } void MachineFunction::print(std::ostream &OS) const { OS << "\n" << *(Value*)Fn->getFunctionType() << " \"" << Fn->getName() << "\"\n"; // Print Frame Information getFrameInfo()->print(*this, OS); // Print Constant Pool getConstantPool()->print(OS); for (const_iterator BB = begin(); BB != end(); ++BB) BB->print(OS); OS << "\nEnd function \"" << Fn->getName() << "\"\n\n"; } // The next two methods are used to construct and to retrieve // the MachineCodeForFunction object for the given function. // construct() -- Allocates and initializes for a given function and target // get() -- Returns a handle to the object. // This should not be called before "construct()" // for a given Function. // MachineFunction& MachineFunction::construct(const Function *Fn, const TargetMachine &Tar) { assert(Fn->getAnnotation(MF_AID) == 0 && "Object already exists for this function!"); MachineFunction* mcInfo = new MachineFunction(Fn, Tar); Fn->addAnnotation(mcInfo); return *mcInfo; } void MachineFunction::destruct(const Function *Fn) { bool Deleted = Fn->deleteAnnotation(MF_AID); assert(Deleted && "Machine code did not exist for function!"); } MachineFunction& MachineFunction::get(const Function *F) { MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID); assert(mc && "Call construct() method first to allocate the object"); return *mc; } void MachineFunction::clearSSARegMap() { delete SSARegMapping; SSARegMapping = 0; } //===----------------------------------------------------------------------===// // MachineFrameInfo implementation //===----------------------------------------------------------------------===// /// CreateStackObject - Create a stack object for a value of the specified type. /// int MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) { return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty)); } int MachineFrameInfo::CreateStackObject(const TargetRegisterClass *RC) { return CreateStackObject(RC->getSize(), RC->getAlignment()); } void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{ int ValOffset = MF.getTarget().getFrameInfo().getOffsetOfLocalArea(); for (unsigned i = 0, e = Objects.size(); i != e; ++i) { const StackObject &SO = Objects[i]; OS << " <fi #" << (int)(i-NumFixedObjects) << "> is "; if (SO.Size == 0) OS << "variable sized"; else OS << SO.Size << " byte" << (SO.Size != 1 ? "s" : " "); if (i < NumFixedObjects) OS << " fixed"; if (i < NumFixedObjects || SO.SPOffset != -1) { int Off = SO.SPOffset + ValOffset; OS << " at location [SP"; if (Off > 0) OS << "+" << Off; else if (Off < 0) OS << Off; OS << "]"; } OS << "\n"; } if (HasVarSizedObjects) OS << " Stack frame contains variable sized objects\n"; } void MachineFrameInfo::dump(const MachineFunction &MF) const { print(MF, std::cerr); } //===----------------------------------------------------------------------===// // MachineConstantPool implementation //===----------------------------------------------------------------------===// void MachineConstantPool::print(std::ostream &OS) const { for (unsigned i = 0, e = Constants.size(); i != e; ++i) OS << " <cp #" << i << "> is" << *(Value*)Constants[i] << "\n"; } void MachineConstantPool::dump() const { print(std::cerr); } //===----------------------------------------------------------------------===// // MachineFunctionInfo implementation //===----------------------------------------------------------------------===// static unsigned ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F, unsigned &maxOptionalNumArgs) { const TargetFrameInfo &frameInfo = target.getFrameInfo(); unsigned maxSize = 0; for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) if (const CallInst *callInst = dyn_cast<CallInst>(I)) { unsigned numOperands = callInst->getNumOperands() - 1; int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs(); if (numExtra <= 0) continue; unsigned sizeForThisCall; if (frameInfo.argsOnStackHaveFixedSize()) { int argSize = frameInfo.getSizeOfEachArgOnStack(); sizeForThisCall = numExtra * (unsigned) argSize; } else { assert(0 && "UNTESTED CODE: Size per stack argument is not " "fixed on this architecture: use actual arg sizes to " "compute MaxOptionalArgsSize"); sizeForThisCall = 0; for (unsigned i = 0; i < numOperands; ++i) sizeForThisCall += target.getTargetData().getTypeSize(callInst-> getOperand(i)->getType()); } if (maxSize < sizeForThisCall) maxSize = sizeForThisCall; if ((int)maxOptionalNumArgs < numExtra) maxOptionalNumArgs = (unsigned) numExtra; } return maxSize; } // Align data larger than one L1 cache line on L1 cache line boundaries. // Align all smaller data on the next higher 2^x boundary (4, 8, ...), // but not higher than the alignment of the largest type we support // (currently a double word). -- see class TargetData). // // This function is similar to the corresponding function in EmitAssembly.cpp // but they are unrelated. This one does not align at more than a // double-word boundary whereas that one might. // inline unsigned SizeToAlignment(unsigned size, const TargetMachine& target) { unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); if (size > (unsigned) cacheLineSize / 2) return cacheLineSize; else for (unsigned sz=1; /*no condition*/; sz *= 2) if (sz >= size || sz >= target.getTargetData().getDoubleAlignment()) return sz; } void MachineFunctionInfo::CalculateArgSize() { maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(), MF.getFunction(), maxOptionalNumArgs); staticStackSize = maxOptionalArgsSize + MF.getTarget().getFrameInfo().getMinStackFrameSize(); } int MachineFunctionInfo::computeOffsetforLocalVar(const Value* val, unsigned &getPaddedSize, unsigned sizeToUse) { if (sizeToUse == 0) sizeToUse = MF.getTarget().findOptimalStorageSize(val->getType()); unsigned align = SizeToAlignment(sizeToUse, MF.getTarget()); bool growUp; int firstOffset = MF.getTarget().getFrameInfo().getFirstAutomaticVarOffset(MF, growUp); int offset = growUp? firstOffset + getAutomaticVarsSize() : firstOffset - (getAutomaticVarsSize() + sizeToUse); int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align); getPaddedSize = sizeToUse + abs(aligned - offset); return aligned; } int MachineFunctionInfo::allocateLocalVar(const Value* val, unsigned sizeToUse) { assert(! automaticVarsAreaFrozen && "Size of auto vars area has been used to compute an offset so " "no more automatic vars should be allocated!"); // Check if we've allocated a stack slot for this value already // hash_map<const Value*, int>::const_iterator pair = offsets.find(val); if (pair != offsets.end()) return pair->second; unsigned getPaddedSize; unsigned offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse); offsets[val] = offset; incrementAutomaticVarsSize(getPaddedSize); return offset; } int MachineFunctionInfo::allocateSpilledValue(const Type* type) { assert(! spillsAreaFrozen && "Size of reg spills area has been used to compute an offset so " "no more register spill slots should be allocated!"); unsigned size = MF.getTarget().getTargetData().getTypeSize(type); unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type); bool growUp; int firstOffset = MF.getTarget().getFrameInfo().getRegSpillAreaOffset(MF, growUp); int offset = growUp? firstOffset + getRegSpillsSize() : firstOffset - (getRegSpillsSize() + size); int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align); size += abs(aligned - offset); // include alignment padding in size incrementRegSpillsSize(size); // update size of reg. spills area return aligned; } int MachineFunctionInfo::pushTempValue(unsigned size) { unsigned align = SizeToAlignment(size, MF.getTarget()); bool growUp; int firstOffset = MF.getTarget().getFrameInfo().getTmpAreaOffset(MF, growUp); int offset = growUp? firstOffset + currentTmpValuesSize : firstOffset - (currentTmpValuesSize + size); int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align); size += abs(aligned - offset); // include alignment padding in size incrementTmpAreaSize(size); // update "current" size of tmp area return aligned; } void MachineFunctionInfo::popAllTempValues() { resetTmpAreaSize(); // clear tmp area to reuse } <commit_msg>Remove use of an ugly header<commit_after>//===-- MachineFunction.cpp -----------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // // Collect native machine code information for a function. This allows // target-specific information about the generated code to be stored with each // function. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/SSARegMap.h" #include "llvm/CodeGen/MachineFunctionInfo.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetCacheInfo.h" #include "llvm/Function.h" #include "llvm/iOther.h" using namespace llvm; static AnnotationID MF_AID( AnnotationManager::getID("CodeGen::MachineCodeForFunction")); namespace { struct Printer : public MachineFunctionPass { std::ostream *OS; const std::string Banner; Printer (std::ostream *_OS, const std::string &_Banner) : OS (_OS), Banner (_Banner) { } const char *getPassName() const { return "MachineFunction Printer"; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } bool runOnMachineFunction(MachineFunction &MF) { (*OS) << Banner; MF.print (*OS); return false; } }; } /// Returns a newly-created MachineFunction Printer pass. The default output /// stream is std::cerr; the default banner is empty. /// FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS, const std::string &Banner) { return new Printer(OS, Banner); } namespace { struct Deleter : public MachineFunctionPass { const char *getPassName() const { return "Machine Code Deleter"; } bool runOnMachineFunction(MachineFunction &MF) { // Delete the annotation from the function now. MachineFunction::destruct(MF.getFunction()); return true; } }; } /// MachineCodeDeletion Pass - This pass deletes all of the machine code for /// the current function, which should happen after the function has been /// emitted to a .s file or to memory. FunctionPass *llvm::createMachineCodeDeleter() { return new Deleter(); } //===---------------------------------------------------------------------===// // MachineFunction implementation //===---------------------------------------------------------------------===// MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM) : Annotation(MF_AID), Fn(F), Target(TM) { SSARegMapping = new SSARegMap(); MFInfo = new MachineFunctionInfo(*this); FrameInfo = new MachineFrameInfo(); ConstantPool = new MachineConstantPool(); } MachineFunction::~MachineFunction() { delete SSARegMapping; delete MFInfo; delete FrameInfo; delete ConstantPool; } void MachineFunction::dump() const { print(std::cerr); } void MachineFunction::print(std::ostream &OS) const { OS << "\n" << *(Value*)Fn->getFunctionType() << " \"" << Fn->getName() << "\"\n"; // Print Frame Information getFrameInfo()->print(*this, OS); // Print Constant Pool getConstantPool()->print(OS); for (const_iterator BB = begin(); BB != end(); ++BB) BB->print(OS); OS << "\nEnd function \"" << Fn->getName() << "\"\n\n"; } // The next two methods are used to construct and to retrieve // the MachineCodeForFunction object for the given function. // construct() -- Allocates and initializes for a given function and target // get() -- Returns a handle to the object. // This should not be called before "construct()" // for a given Function. // MachineFunction& MachineFunction::construct(const Function *Fn, const TargetMachine &Tar) { assert(Fn->getAnnotation(MF_AID) == 0 && "Object already exists for this function!"); MachineFunction* mcInfo = new MachineFunction(Fn, Tar); Fn->addAnnotation(mcInfo); return *mcInfo; } void MachineFunction::destruct(const Function *Fn) { bool Deleted = Fn->deleteAnnotation(MF_AID); assert(Deleted && "Machine code did not exist for function!"); } MachineFunction& MachineFunction::get(const Function *F) { MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID); assert(mc && "Call construct() method first to allocate the object"); return *mc; } void MachineFunction::clearSSARegMap() { delete SSARegMapping; SSARegMapping = 0; } //===----------------------------------------------------------------------===// // MachineFrameInfo implementation //===----------------------------------------------------------------------===// /// CreateStackObject - Create a stack object for a value of the specified type. /// int MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) { return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty)); } int MachineFrameInfo::CreateStackObject(const TargetRegisterClass *RC) { return CreateStackObject(RC->getSize(), RC->getAlignment()); } void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{ int ValOffset = MF.getTarget().getFrameInfo().getOffsetOfLocalArea(); for (unsigned i = 0, e = Objects.size(); i != e; ++i) { const StackObject &SO = Objects[i]; OS << " <fi #" << (int)(i-NumFixedObjects) << "> is "; if (SO.Size == 0) OS << "variable sized"; else OS << SO.Size << " byte" << (SO.Size != 1 ? "s" : " "); if (i < NumFixedObjects) OS << " fixed"; if (i < NumFixedObjects || SO.SPOffset != -1) { int Off = SO.SPOffset + ValOffset; OS << " at location [SP"; if (Off > 0) OS << "+" << Off; else if (Off < 0) OS << Off; OS << "]"; } OS << "\n"; } if (HasVarSizedObjects) OS << " Stack frame contains variable sized objects\n"; } void MachineFrameInfo::dump(const MachineFunction &MF) const { print(MF, std::cerr); } //===----------------------------------------------------------------------===// // MachineConstantPool implementation //===----------------------------------------------------------------------===// void MachineConstantPool::print(std::ostream &OS) const { for (unsigned i = 0, e = Constants.size(); i != e; ++i) OS << " <cp #" << i << "> is" << *(Value*)Constants[i] << "\n"; } void MachineConstantPool::dump() const { print(std::cerr); } //===----------------------------------------------------------------------===// // MachineFunctionInfo implementation //===----------------------------------------------------------------------===// static unsigned ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F, unsigned &maxOptionalNumArgs) { const TargetFrameInfo &frameInfo = target.getFrameInfo(); unsigned maxSize = 0; for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) if (const CallInst *callInst = dyn_cast<CallInst>(I)) { unsigned numOperands = callInst->getNumOperands() - 1; int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs(); if (numExtra <= 0) continue; unsigned sizeForThisCall; if (frameInfo.argsOnStackHaveFixedSize()) { int argSize = frameInfo.getSizeOfEachArgOnStack(); sizeForThisCall = numExtra * (unsigned) argSize; } else { assert(0 && "UNTESTED CODE: Size per stack argument is not " "fixed on this architecture: use actual arg sizes to " "compute MaxOptionalArgsSize"); sizeForThisCall = 0; for (unsigned i = 0; i < numOperands; ++i) sizeForThisCall += target.getTargetData().getTypeSize(callInst-> getOperand(i)->getType()); } if (maxSize < sizeForThisCall) maxSize = sizeForThisCall; if ((int)maxOptionalNumArgs < numExtra) maxOptionalNumArgs = (unsigned) numExtra; } return maxSize; } // Align data larger than one L1 cache line on L1 cache line boundaries. // Align all smaller data on the next higher 2^x boundary (4, 8, ...), // but not higher than the alignment of the largest type we support // (currently a double word). -- see class TargetData). // // This function is similar to the corresponding function in EmitAssembly.cpp // but they are unrelated. This one does not align at more than a // double-word boundary whereas that one might. // inline unsigned SizeToAlignment(unsigned size, const TargetMachine& target) { unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); if (size > (unsigned) cacheLineSize / 2) return cacheLineSize; else for (unsigned sz=1; /*no condition*/; sz *= 2) if (sz >= size || sz >= target.getTargetData().getDoubleAlignment()) return sz; } void MachineFunctionInfo::CalculateArgSize() { maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(), MF.getFunction(), maxOptionalNumArgs); staticStackSize = maxOptionalArgsSize + MF.getTarget().getFrameInfo().getMinStackFrameSize(); } int MachineFunctionInfo::computeOffsetforLocalVar(const Value* val, unsigned &getPaddedSize, unsigned sizeToUse) { if (sizeToUse == 0) sizeToUse = MF.getTarget().findOptimalStorageSize(val->getType()); unsigned align = SizeToAlignment(sizeToUse, MF.getTarget()); bool growUp; int firstOffset = MF.getTarget().getFrameInfo().getFirstAutomaticVarOffset(MF, growUp); int offset = growUp? firstOffset + getAutomaticVarsSize() : firstOffset - (getAutomaticVarsSize() + sizeToUse); int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align); getPaddedSize = sizeToUse + abs(aligned - offset); return aligned; } int MachineFunctionInfo::allocateLocalVar(const Value* val, unsigned sizeToUse) { assert(! automaticVarsAreaFrozen && "Size of auto vars area has been used to compute an offset so " "no more automatic vars should be allocated!"); // Check if we've allocated a stack slot for this value already // hash_map<const Value*, int>::const_iterator pair = offsets.find(val); if (pair != offsets.end()) return pair->second; unsigned getPaddedSize; unsigned offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse); offsets[val] = offset; incrementAutomaticVarsSize(getPaddedSize); return offset; } int MachineFunctionInfo::allocateSpilledValue(const Type* type) { assert(! spillsAreaFrozen && "Size of reg spills area has been used to compute an offset so " "no more register spill slots should be allocated!"); unsigned size = MF.getTarget().getTargetData().getTypeSize(type); unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type); bool growUp; int firstOffset = MF.getTarget().getFrameInfo().getRegSpillAreaOffset(MF, growUp); int offset = growUp? firstOffset + getRegSpillsSize() : firstOffset - (getRegSpillsSize() + size); int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align); size += abs(aligned - offset); // include alignment padding in size incrementRegSpillsSize(size); // update size of reg. spills area return aligned; } int MachineFunctionInfo::pushTempValue(unsigned size) { unsigned align = SizeToAlignment(size, MF.getTarget()); bool growUp; int firstOffset = MF.getTarget().getFrameInfo().getTmpAreaOffset(MF, growUp); int offset = growUp? firstOffset + currentTmpValuesSize : firstOffset - (currentTmpValuesSize + size); int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align); size += abs(aligned - offset); // include alignment padding in size incrementTmpAreaSize(size); // update "current" size of tmp area return aligned; } void MachineFunctionInfo::popAllTempValues() { resetTmpAreaSize(); // clear tmp area to reuse } <|endoftext|>
<commit_before>//===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Nate Begeman and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the X86 specific subclass of TargetSubtarget. // //===----------------------------------------------------------------------===// #include "X86Subtarget.h" #include "llvm/Module.h" #include "X86GenSubtarget.inc" using namespace llvm; // FIXME: temporary. #include "llvm/Support/CommandLine.h" namespace { cl::opt<bool> EnableSSE("enable-x86-sse", cl::Hidden, cl::desc("Enable sse on X86")); } /// GetCpuIDAndInfo - Execute the specified cpuid and return the 4 values in the /// specified arguments. If we can't run cpuid on the host, return true. static bool GetCpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX, unsigned *rECX, unsigned *rEDX) { #if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86) #if defined(__GNUC__) asm ("pushl\t%%ebx\n\t" "cpuid\n\t" "movl\t%%ebx, %%esi\n\t" "popl\t%%ebx" : "=a" (*rEAX), "=S" (*rEBX), "=c" (*rECX), "=d" (*rEDX) : "a" (value)); return false; #elif defined(_MSC_VER) __asm { mov eax,value cpuid mov esi,rEAX mov dword ptr [esi],eax mov esi,rEBX mov dword ptr [esi],ebx mov esi,rECX mov dword ptr [esi],ecx mov esi,rEDX mov dword ptr [esi],edx } return false; #endif #endif return true; } static const char *GetCurrentX86CPU() { unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; if (GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX)) return "generic"; unsigned Family = (EAX & (0xffffffff >> (32 - 4)) << 8) >> 8; // Bits 8 - 11 unsigned Model = (EAX & (0xffffffff >> (32 - 4)) << 4) >> 4; // Bits 4 - 7 GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX); bool Em64T = EDX & (1 << 29); union { unsigned u[3]; char c[12]; } text; GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1); if (memcmp(text.c, "GenuineIntel", 12) == 0) { switch (Family) { case 3: return "i386"; case 4: return "i486"; case 5: switch (Model) { case 4: return "pentium-mmx"; default: return "pentium"; } case 6: switch (Model) { case 1: return "pentiumpro"; case 3: case 5: case 6: return "pentium2"; case 7: case 8: case 10: case 11: return "pentium3"; case 9: case 13: return "pentium-m"; case 14: return "yonah"; default: return "i686"; } case 15: { switch (Model) { case 3: case 4: return (Em64T) ? "nocona" : "prescott"; default: return (Em64T) ? "x86-64" : "pentium4"; } } default: return "generic"; } } else if (memcmp(text.c, "AuthenticAMD", 12) == 0) { // FIXME: fill in remaining family/model combinations switch (Family) { case 15: return (Em64T) ? "athlon64" : "athlon"; default: return "generic"; } } else { return "generic"; } } X86Subtarget::X86Subtarget(const Module &M, const std::string &FS) { stackAlignment = 8; indirectExternAndWeakGlobals = false; X86SSELevel = NoMMXSSE; X863DNowLevel = NoThreeDNow; Is64Bit = false; // Determine default and user specified characteristics std::string CPU = GetCurrentX86CPU(); // Parse features string. ParseSubtargetFeatures(FS, CPU); // Default to ELF unless otherwise specified. TargetType = isELF; // FIXME: Force these off until they work. An llc-beta option should turn // them back on. if (!EnableSSE) { X86SSELevel = NoMMXSSE; X863DNowLevel = NoThreeDNow; } // Set the boolean corresponding to the current target triple, or the default // if one cannot be determined, to true. const std::string& TT = M.getTargetTriple(); if (TT.length() > 5) { if (TT.find("cygwin") != std::string::npos || TT.find("mingw") != std::string::npos) TargetType = isCygwin; else if (TT.find("darwin") != std::string::npos) TargetType = isDarwin; else if (TT.find("win32") != std::string::npos) TargetType = isWindows; } else if (TT.empty()) { #if defined(__CYGWIN__) || defined(__MINGW32__) TargetType = isCygwin; #elif defined(__APPLE__) TargetType = isDarwin; #elif defined(_WIN32) TargetType = isWindows; #endif } if (TargetType == isDarwin) { stackAlignment = 16; indirectExternAndWeakGlobals = true; } } <commit_msg>Flesh out AMD family/models.<commit_after>//===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Nate Begeman and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the X86 specific subclass of TargetSubtarget. // //===----------------------------------------------------------------------===// #include "X86Subtarget.h" #include "llvm/Module.h" #include "X86GenSubtarget.inc" using namespace llvm; // FIXME: temporary. #include "llvm/Support/CommandLine.h" namespace { cl::opt<bool> EnableSSE("enable-x86-sse", cl::Hidden, cl::desc("Enable sse on X86")); } /// GetCpuIDAndInfo - Execute the specified cpuid and return the 4 values in the /// specified arguments. If we can't run cpuid on the host, return true. static bool GetCpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX, unsigned *rECX, unsigned *rEDX) { #if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86) #if defined(__GNUC__) asm ("pushl\t%%ebx\n\t" "cpuid\n\t" "movl\t%%ebx, %%esi\n\t" "popl\t%%ebx" : "=a" (*rEAX), "=S" (*rEBX), "=c" (*rECX), "=d" (*rEDX) : "a" (value)); return false; #elif defined(_MSC_VER) __asm { mov eax,value cpuid mov esi,rEAX mov dword ptr [esi],eax mov esi,rEBX mov dword ptr [esi],ebx mov esi,rECX mov dword ptr [esi],ecx mov esi,rEDX mov dword ptr [esi],edx } return false; #endif #endif return true; } static const char *GetCurrentX86CPU() { unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; if (GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX)) return "generic"; unsigned Family = (EAX & (0xffffffff >> (32 - 4)) << 8) >> 8; // Bits 8 - 11 unsigned Model = (EAX & (0xffffffff >> (32 - 4)) << 4) >> 4; // Bits 4 - 7 GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX); bool Em64T = EDX & (1 << 29); union { unsigned u[3]; char c[12]; } text; GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1); if (memcmp(text.c, "GenuineIntel", 12) == 0) { switch (Family) { case 3: return "i386"; case 4: return "i486"; case 5: switch (Model) { case 4: return "pentium-mmx"; default: return "pentium"; } case 6: switch (Model) { case 1: return "pentiumpro"; case 3: case 5: case 6: return "pentium2"; case 7: case 8: case 10: case 11: return "pentium3"; case 9: case 13: return "pentium-m"; case 14: return "yonah"; default: return "i686"; } case 15: { switch (Model) { case 3: case 4: return (Em64T) ? "nocona" : "prescott"; default: return (Em64T) ? "x86-64" : "pentium4"; } } default: return "generic"; } } else if (memcmp(text.c, "AuthenticAMD", 12) == 0) { // FIXME: this poorly matches the generated SubtargetFeatureKV table. There // appears to be no way to generate the wide variety of AMD-specific targets // from the information returned from CPUID. switch (Family) { case 4: return "i486"; case 5: switch (Model) { case 6: case 7: return "k6"; case 8: return "k6-2"; case 9: case 13: return "k6-3"; default: return "pentium"; } case 6: switch (Model) { case 4: return "athlon-tbird"; case 6: case 7: case 8: return "athlon-mp"; case 10: return "athlon-xp"; default: return "athlon"; } case 15: switch (Model) { case 5: return "athlon-fx"; // also opteron default: return "athlon64"; } default: return "generic"; } } else { return "generic"; } } X86Subtarget::X86Subtarget(const Module &M, const std::string &FS) { stackAlignment = 8; indirectExternAndWeakGlobals = false; X86SSELevel = NoMMXSSE; X863DNowLevel = NoThreeDNow; Is64Bit = false; // Determine default and user specified characteristics std::string CPU = GetCurrentX86CPU(); // Parse features string. ParseSubtargetFeatures(FS, CPU); // Default to ELF unless otherwise specified. TargetType = isELF; // FIXME: Force these off until they work. An llc-beta option should turn // them back on. if (!EnableSSE) { X86SSELevel = NoMMXSSE; X863DNowLevel = NoThreeDNow; } // Set the boolean corresponding to the current target triple, or the default // if one cannot be determined, to true. const std::string& TT = M.getTargetTriple(); if (TT.length() > 5) { if (TT.find("cygwin") != std::string::npos || TT.find("mingw") != std::string::npos) TargetType = isCygwin; else if (TT.find("darwin") != std::string::npos) TargetType = isDarwin; else if (TT.find("win32") != std::string::npos) TargetType = isWindows; } else if (TT.empty()) { #if defined(__CYGWIN__) || defined(__MINGW32__) TargetType = isCygwin; #elif defined(__APPLE__) TargetType = isDarwin; #elif defined(_WIN32) TargetType = isWindows; #endif } if (TargetType == isDarwin) { stackAlignment = 16; indirectExternAndWeakGlobals = true; } } <|endoftext|>
<commit_before>//===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the X86 specific subclass of TargetSubtarget. // //===----------------------------------------------------------------------===// #include "X86Subtarget.h" #include "X86GenSubtarget.inc" #include "llvm/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; static cl::opt<X86Subtarget::AsmWriterFlavorTy> AsmWriterFlavor("x86-asm-syntax", cl::init(X86Subtarget::Unset), cl::desc("Choose style of code to emit from X86 backend:"), cl::values( clEnumValN(X86Subtarget::ATT, "att", " Emit AT&T-style assembly"), clEnumValN(X86Subtarget::Intel, "intel", " Emit Intel-style assembly"), clEnumValEnd)); /// True if accessing the GV requires an extra load. For Windows, dllimported /// symbols are indirect, loading the value at address GV rather then the /// value of GV itself. This means that the GlobalAddress must be in the base /// or index register of the address, not the GV offset field. bool X86Subtarget::GVRequiresExtraLoad(const GlobalValue* GV, const TargetMachine& TM, bool isDirectCall) const { // FIXME: PIC if (TM.getRelocationModel() != Reloc::Static) { if (isTargetDarwin()) { return (!isDirectCall && (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage() || GV->hasCommonLinkage() || (GV->isDeclaration() && !GV->hasNotBeenReadFromBitcode()))); } else if (isTargetELF()) { // Extra load is needed for all externally visible. if (isDirectCall) return false; if (GV->hasInternalLinkage() || (GV->hasHiddenVisibility() && !GV->isDeclaration())) return false; return true; } else if (isTargetCygMing() || isTargetWindows()) { return (GV->hasDLLImportLinkage()); } } return false; } /// This function returns the name of a function which has an interface /// like the non-standard bzero function, if such a function exists on /// the current subtarget and it is considered prefereable over /// memset with zero passed as the second argument. Otherwise it /// returns null. const char *X86Subtarget::getBZeroEntry() const { // Darwin 10 has a __bzero entry point for this purpose. if (getDarwinVers() >= 10) return "__bzero"; return 0; } /// GetCpuIDAndInfo - Execute the specified cpuid and return the 4 values in the /// specified arguments. If we can't run cpuid on the host, return true. bool X86::GetCpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX, unsigned *rECX, unsigned *rEDX) { #if defined(__x86_64__) // gcc doesn't know cpuid would clobber ebx/rbx. Preseve it manually. asm ("movq\t%%rbx, %%rsi\n\t" "cpuid\n\t" "xchgq\t%%rbx, %%rsi\n\t" : "=a" (*rEAX), "=S" (*rEBX), "=c" (*rECX), "=d" (*rEDX) : "a" (value)); return false; #elif defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86) #if defined(__GNUC__) asm ("movl\t%%ebx, %%esi\n\t" "cpuid\n\t" "xchgl\t%%ebx, %%esi\n\t" : "=a" (*rEAX), "=S" (*rEBX), "=c" (*rECX), "=d" (*rEDX) : "a" (value)); return false; #elif defined(_MSC_VER) __asm { mov eax,value cpuid mov esi,rEAX mov dword ptr [esi],eax mov esi,rEBX mov dword ptr [esi],ebx mov esi,rECX mov dword ptr [esi],ecx mov esi,rEDX mov dword ptr [esi],edx } return false; #endif #endif return true; } void X86Subtarget::AutoDetectSubtargetFeatures() { unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; union { unsigned u[3]; char c[12]; } text; if (X86::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1)) return; X86::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX); if ((EDX >> 23) & 0x1) X86SSELevel = MMX; if ((EDX >> 25) & 0x1) X86SSELevel = SSE1; if ((EDX >> 26) & 0x1) X86SSELevel = SSE2; if (ECX & 0x1) X86SSELevel = SSE3; if ((ECX >> 9) & 0x1) X86SSELevel = SSSE3; if ((ECX >> 19) & 0x1) X86SSELevel = SSE41; if ((ECX >> 20) & 0x1) X86SSELevel = SSE42; if (memcmp(text.c, "GenuineIntel", 12) == 0 || memcmp(text.c, "AuthenticAMD", 12) == 0) { X86::GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX); HasX86_64 = (EDX >> 29) & 0x1; } } static const char *GetCurrentX86CPU() { unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; if (X86::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX)) return "generic"; unsigned Family = (EAX >> 8) & 0xf; // Bits 8 - 11 unsigned Model = (EAX >> 4) & 0xf; // Bits 4 - 7 X86::GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX); bool Em64T = (EDX >> 29) & 0x1; union { unsigned u[3]; char c[12]; } text; X86::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1); if (memcmp(text.c, "GenuineIntel", 12) == 0) { switch (Family) { case 3: return "i386"; case 4: return "i486"; case 5: switch (Model) { case 4: return "pentium-mmx"; default: return "pentium"; } case 6: switch (Model) { case 1: return "pentiumpro"; case 3: case 5: case 6: return "pentium2"; case 7: case 8: case 10: case 11: return "pentium3"; case 9: case 13: return "pentium-m"; case 14: return "yonah"; case 15: return "core2"; default: return "i686"; } case 15: { switch (Model) { case 3: case 4: return (Em64T) ? "nocona" : "prescott"; default: return (Em64T) ? "x86-64" : "pentium4"; } } default: return "generic"; } } else if (memcmp(text.c, "AuthenticAMD", 12) == 0) { // FIXME: this poorly matches the generated SubtargetFeatureKV table. There // appears to be no way to generate the wide variety of AMD-specific targets // from the information returned from CPUID. switch (Family) { case 4: return "i486"; case 5: switch (Model) { case 6: case 7: return "k6"; case 8: return "k6-2"; case 9: case 13: return "k6-3"; default: return "pentium"; } case 6: switch (Model) { case 4: return "athlon-tbird"; case 6: case 7: case 8: return "athlon-mp"; case 10: return "athlon-xp"; default: return "athlon"; } case 15: switch (Model) { case 1: return "opteron"; case 5: return "athlon-fx"; // also opteron default: return "athlon64"; } default: return "generic"; } } else { return "generic"; } } X86Subtarget::X86Subtarget(const Module &M, const std::string &FS, bool is64Bit) : AsmFlavor(AsmWriterFlavor) , PICStyle(PICStyle::None) , X86SSELevel(NoMMXSSE) , X863DNowLevel(NoThreeDNow) , HasX86_64(false) , DarwinVers(0) , IsLinux(false) , stackAlignment(8) // FIXME: this is a known good value for Yonah. How about others? , MaxInlineSizeThreshold(128) , Is64Bit(is64Bit) , TargetType(isELF) { // Default to ELF unless otherwise specified. // Determine default and user specified characteristics if (!FS.empty()) { // If feature string is not empty, parse features string. std::string CPU = GetCurrentX86CPU(); ParseSubtargetFeatures(FS, CPU); } else { // Otherwise, use CPUID to auto-detect feature set. AutoDetectSubtargetFeatures(); } // If requesting codegen for X86-64, make sure that 64-bit and SSE2 features // are enabled. These are available on all x86-64 CPUs. if (Is64Bit) { HasX86_64 = true; if (X86SSELevel < SSE2) X86SSELevel = SSE2; } // Set the boolean corresponding to the current target triple, or the default // if one cannot be determined, to true. const std::string& TT = M.getTargetTriple(); if (TT.length() > 5) { size_t Pos; if ((Pos = TT.find("-darwin")) != std::string::npos) { TargetType = isDarwin; // Compute the darwin version number. if (isdigit(TT[Pos+7])) DarwinVers = atoi(&TT[Pos+7]); else DarwinVers = 8; // Minimum supported darwin is Tiger. } else if (TT.find("linux") != std::string::npos) { // Linux doesn't imply ELF, but we don't currently support anything else. TargetType = isELF; IsLinux = true; } else if (TT.find("cygwin") != std::string::npos) { TargetType = isCygwin; } else if (TT.find("mingw") != std::string::npos) { TargetType = isMingw; } else if (TT.find("win32") != std::string::npos) { TargetType = isWindows; } else if (TT.find("windows") != std::string::npos) { TargetType = isWindows; } } else if (TT.empty()) { #if defined(__CYGWIN__) TargetType = isCygwin; #elif defined(__MINGW32__) || defined(__MINGW64__) TargetType = isMingw; #elif defined(__APPLE__) TargetType = isDarwin; #if __APPLE_CC__ > 5400 DarwinVers = 9; // GCC 5400+ is Leopard. #else DarwinVers = 8; // Minimum supported darwin is Tiger. #endif #elif defined(_WIN32) || defined(_WIN64) TargetType = isWindows; #elif defined(__linux__) // Linux doesn't imply ELF, but we don't currently support anything else. TargetType = isELF; IsLinux = true; #endif } // If the asm syntax hasn't been overridden on the command line, use whatever // the target wants. if (AsmFlavor == X86Subtarget::Unset) { AsmFlavor = (TargetType == isWindows) ? X86Subtarget::Intel : X86Subtarget::ATT; } // Stack alignment is 16 bytes on Darwin (both 32 and 64 bit) and for all 64 // bit targets. if (TargetType == isDarwin || Is64Bit) stackAlignment = 16; if (StackAlignment) stackAlignment = StackAlignment; } <commit_msg>Revert accidentially added stuff<commit_after>//===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the X86 specific subclass of TargetSubtarget. // //===----------------------------------------------------------------------===// #include "X86Subtarget.h" #include "X86GenSubtarget.inc" #include "llvm/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; static cl::opt<X86Subtarget::AsmWriterFlavorTy> AsmWriterFlavor("x86-asm-syntax", cl::init(X86Subtarget::Unset), cl::desc("Choose style of code to emit from X86 backend:"), cl::values( clEnumValN(X86Subtarget::ATT, "att", " Emit AT&T-style assembly"), clEnumValN(X86Subtarget::Intel, "intel", " Emit Intel-style assembly"), clEnumValEnd)); /// True if accessing the GV requires an extra load. For Windows, dllimported /// symbols are indirect, loading the value at address GV rather then the /// value of GV itself. This means that the GlobalAddress must be in the base /// or index register of the address, not the GV offset field. bool X86Subtarget::GVRequiresExtraLoad(const GlobalValue* GV, const TargetMachine& TM, bool isDirectCall) const { // FIXME: PIC if (TM.getRelocationModel() != Reloc::Static) { if (isTargetDarwin()) { return (!isDirectCall && (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage() || GV->hasCommonLinkage() || (GV->isDeclaration() && !GV->hasNotBeenReadFromBitcode()))); } else if (isTargetELF()) { // Extra load is needed for all externally visible. if (isDirectCall) return false; if (GV->hasInternalLinkage() || GV->hasHiddenVisibility()) return false; return true; } else if (isTargetCygMing() || isTargetWindows()) { return (GV->hasDLLImportLinkage()); } } return false; } /// This function returns the name of a function which has an interface /// like the non-standard bzero function, if such a function exists on /// the current subtarget and it is considered prefereable over /// memset with zero passed as the second argument. Otherwise it /// returns null. const char *X86Subtarget::getBZeroEntry() const { // Darwin 10 has a __bzero entry point for this purpose. if (getDarwinVers() >= 10) return "__bzero"; return 0; } /// GetCpuIDAndInfo - Execute the specified cpuid and return the 4 values in the /// specified arguments. If we can't run cpuid on the host, return true. bool X86::GetCpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX, unsigned *rECX, unsigned *rEDX) { #if defined(__x86_64__) // gcc doesn't know cpuid would clobber ebx/rbx. Preseve it manually. asm ("movq\t%%rbx, %%rsi\n\t" "cpuid\n\t" "xchgq\t%%rbx, %%rsi\n\t" : "=a" (*rEAX), "=S" (*rEBX), "=c" (*rECX), "=d" (*rEDX) : "a" (value)); return false; #elif defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86) #if defined(__GNUC__) asm ("movl\t%%ebx, %%esi\n\t" "cpuid\n\t" "xchgl\t%%ebx, %%esi\n\t" : "=a" (*rEAX), "=S" (*rEBX), "=c" (*rECX), "=d" (*rEDX) : "a" (value)); return false; #elif defined(_MSC_VER) __asm { mov eax,value cpuid mov esi,rEAX mov dword ptr [esi],eax mov esi,rEBX mov dword ptr [esi],ebx mov esi,rECX mov dword ptr [esi],ecx mov esi,rEDX mov dword ptr [esi],edx } return false; #endif #endif return true; } void X86Subtarget::AutoDetectSubtargetFeatures() { unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; union { unsigned u[3]; char c[12]; } text; if (X86::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1)) return; X86::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX); if ((EDX >> 23) & 0x1) X86SSELevel = MMX; if ((EDX >> 25) & 0x1) X86SSELevel = SSE1; if ((EDX >> 26) & 0x1) X86SSELevel = SSE2; if (ECX & 0x1) X86SSELevel = SSE3; if ((ECX >> 9) & 0x1) X86SSELevel = SSSE3; if ((ECX >> 19) & 0x1) X86SSELevel = SSE41; if ((ECX >> 20) & 0x1) X86SSELevel = SSE42; if (memcmp(text.c, "GenuineIntel", 12) == 0 || memcmp(text.c, "AuthenticAMD", 12) == 0) { X86::GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX); HasX86_64 = (EDX >> 29) & 0x1; } } static const char *GetCurrentX86CPU() { unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; if (X86::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX)) return "generic"; unsigned Family = (EAX >> 8) & 0xf; // Bits 8 - 11 unsigned Model = (EAX >> 4) & 0xf; // Bits 4 - 7 X86::GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX); bool Em64T = (EDX >> 29) & 0x1; union { unsigned u[3]; char c[12]; } text; X86::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1); if (memcmp(text.c, "GenuineIntel", 12) == 0) { switch (Family) { case 3: return "i386"; case 4: return "i486"; case 5: switch (Model) { case 4: return "pentium-mmx"; default: return "pentium"; } case 6: switch (Model) { case 1: return "pentiumpro"; case 3: case 5: case 6: return "pentium2"; case 7: case 8: case 10: case 11: return "pentium3"; case 9: case 13: return "pentium-m"; case 14: return "yonah"; case 15: return "core2"; default: return "i686"; } case 15: { switch (Model) { case 3: case 4: return (Em64T) ? "nocona" : "prescott"; default: return (Em64T) ? "x86-64" : "pentium4"; } } default: return "generic"; } } else if (memcmp(text.c, "AuthenticAMD", 12) == 0) { // FIXME: this poorly matches the generated SubtargetFeatureKV table. There // appears to be no way to generate the wide variety of AMD-specific targets // from the information returned from CPUID. switch (Family) { case 4: return "i486"; case 5: switch (Model) { case 6: case 7: return "k6"; case 8: return "k6-2"; case 9: case 13: return "k6-3"; default: return "pentium"; } case 6: switch (Model) { case 4: return "athlon-tbird"; case 6: case 7: case 8: return "athlon-mp"; case 10: return "athlon-xp"; default: return "athlon"; } case 15: switch (Model) { case 1: return "opteron"; case 5: return "athlon-fx"; // also opteron default: return "athlon64"; } default: return "generic"; } } else { return "generic"; } } X86Subtarget::X86Subtarget(const Module &M, const std::string &FS, bool is64Bit) : AsmFlavor(AsmWriterFlavor) , PICStyle(PICStyle::None) , X86SSELevel(NoMMXSSE) , X863DNowLevel(NoThreeDNow) , HasX86_64(false) , DarwinVers(0) , IsLinux(false) , stackAlignment(8) // FIXME: this is a known good value for Yonah. How about others? , MaxInlineSizeThreshold(128) , Is64Bit(is64Bit) , TargetType(isELF) { // Default to ELF unless otherwise specified. // Determine default and user specified characteristics if (!FS.empty()) { // If feature string is not empty, parse features string. std::string CPU = GetCurrentX86CPU(); ParseSubtargetFeatures(FS, CPU); } else { // Otherwise, use CPUID to auto-detect feature set. AutoDetectSubtargetFeatures(); } // If requesting codegen for X86-64, make sure that 64-bit and SSE2 features // are enabled. These are available on all x86-64 CPUs. if (Is64Bit) { HasX86_64 = true; if (X86SSELevel < SSE2) X86SSELevel = SSE2; } // Set the boolean corresponding to the current target triple, or the default // if one cannot be determined, to true. const std::string& TT = M.getTargetTriple(); if (TT.length() > 5) { size_t Pos; if ((Pos = TT.find("-darwin")) != std::string::npos) { TargetType = isDarwin; // Compute the darwin version number. if (isdigit(TT[Pos+7])) DarwinVers = atoi(&TT[Pos+7]); else DarwinVers = 8; // Minimum supported darwin is Tiger. } else if (TT.find("linux") != std::string::npos) { // Linux doesn't imply ELF, but we don't currently support anything else. TargetType = isELF; IsLinux = true; } else if (TT.find("cygwin") != std::string::npos) { TargetType = isCygwin; } else if (TT.find("mingw") != std::string::npos) { TargetType = isMingw; } else if (TT.find("win32") != std::string::npos) { TargetType = isWindows; } else if (TT.find("windows") != std::string::npos) { TargetType = isWindows; } } else if (TT.empty()) { #if defined(__CYGWIN__) TargetType = isCygwin; #elif defined(__MINGW32__) || defined(__MINGW64__) TargetType = isMingw; #elif defined(__APPLE__) TargetType = isDarwin; #if __APPLE_CC__ > 5400 DarwinVers = 9; // GCC 5400+ is Leopard. #else DarwinVers = 8; // Minimum supported darwin is Tiger. #endif #elif defined(_WIN32) || defined(_WIN64) TargetType = isWindows; #elif defined(__linux__) // Linux doesn't imply ELF, but we don't currently support anything else. TargetType = isELF; IsLinux = true; #endif } // If the asm syntax hasn't been overridden on the command line, use whatever // the target wants. if (AsmFlavor == X86Subtarget::Unset) { AsmFlavor = (TargetType == isWindows) ? X86Subtarget::Intel : X86Subtarget::ATT; } // Stack alignment is 16 bytes on Darwin (both 32 and 64 bit) and for all 64 // bit targets. if (TargetType == isDarwin || Is64Bit) stackAlignment = 16; if (StackAlignment) stackAlignment = StackAlignment; } <|endoftext|>
<commit_before>#include "spellingproduceswarningstest.h" #include <QUrl> #include <QFileInfo> #include <QThread> #include <QStringList> #include "integrationtestbase.h" #include "signalwaiter.h" #include "../../xpiks-qt/Commands/commandmanager.h" #include "../../xpiks-qt/Models/artitemsmodel.h" #include "../../xpiks-qt/MetadataIO/metadataiocoordinator.h" #include "../../xpiks-qt/Models/artworkmetadata.h" #include "../../xpiks-qt/Models/settingsmodel.h" #include "../../xpiks-qt/Models/filteredartitemsproxymodel.h" #include "../../xpiks-qt/SpellCheck/spellchecksuggestionmodel.h" #include "../../xpiks-qt/SpellCheck/spellsuggestionsitem.h" #include "../../xpiks-qt/Models/combinedartworksmodel.h" #include "../../xpiks-qt/Common/basickeywordsmodel.h" #include "../../xpiks-qt/Common/flags.h" #include "../../xpiks-qt/Warnings/warningsservice.h" #include "../../xpiks-qt/SpellCheck/spellcheckerservice.h" #include "testshelpers.h" QString SpellingProducesWarningsTest::testName() { return QLatin1String("SpellingProducesWarningsTest"); } void SpellingProducesWarningsTest::setup() { Models::SettingsModel *settingsModel = m_CommandManager->getSettingsModel(); settingsModel->setUseSpellCheck(true); } int SpellingProducesWarningsTest::doTest() { Models::ArtItemsModel *artItemsModel = m_CommandManager->getArtItemsModel(); QList<QUrl> files; files << getImagePathForTest("images-for-tests/vector/026.jpg"); int addedCount = artItemsModel->addLocalArtworks(files); VERIFY(addedCount == files.length(), "Failed to add file"); MetadataIO::MetadataIOCoordinator *ioCoordinator = m_CommandManager->getMetadataIOCoordinator(); SignalWaiter waiter; QObject::connect(ioCoordinator, SIGNAL(metadataReadingFinished()), &waiter, SIGNAL(finished())); ioCoordinator->continueReading(true); if (!waiter.wait(20)) { VERIFY(false, "Timeout exceeded for reading metadata."); } VERIFY(!ioCoordinator->getHasErrors(), "Errors in IO Coordinator while reading"); Models::ArtworkMetadata *metadata = artItemsModel->getArtwork(0); sleepWait(3, [metadata]() { return !Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInTitle) && !Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInDescription) && !Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInKeywords); }); VERIFY(!Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInTitle), "Error for reading title"); VERIFY(!Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInDescription), "Error for reading description"); VERIFY(!Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInKeywords), "Error for reading keywords"); QString wrongWord = "abbreviatioe"; metadata->setDescription(metadata->getDescription() + ' ' + wrongWord); metadata->setTitle(metadata->getTitle() + ' ' + wrongWord); metadata->appendKeyword("correct part " + wrongWord); metadata->setIsSelected(true); Models::FilteredArtItemsProxyModel *filteredModel = m_CommandManager->getFilteredArtItemsModel(); SpellCheck::SpellCheckerService *spellCheckService = m_CommandManager->getSpellCheckerService(); SignalWaiter spellingWaiter; QObject::connect(spellCheckService, SIGNAL(spellCheckQueueIsEmpty()), &spellingWaiter, SIGNAL(finished())); filteredModel->spellCheckSelected(); if (!spellingWaiter.wait(5)) { VERIFY(false, "Timeout for waiting for first spellcheck results"); } LOG_INFO << "Spellchecking finished. Waiting for warnings..."; sleepWait(5, [=]() { return keywordsModel->hasDescriptionSpellError() && keywordsModel->hasTitleSpellError() && keywordsModel->hasKeywordsSpellError(); }); Common::BasicKeywordsModel *keywordsModel = metadata->getKeywordsModel(); VERIFY(keywordsModel->hasDescriptionSpellError(), "Description spell error not detected"); VERIFY(keywordsModel->hasTitleSpellError(), "Title spell error not detected"); VERIFY(keywordsModel->hasKeywordsSpellError(), "Keywords spell error not detected"); VERIFY(Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInTitle), "Warning was not produced for title spelling error"); VERIFY(Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInDescription), "Warning was not produced for description spelling error"); VERIFY(Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInKeywords), "Warning was not produced for keywords spelling error"); return 0; } <commit_msg>Fixed compilation error<commit_after>#include "spellingproduceswarningstest.h" #include <QUrl> #include <QFileInfo> #include <QThread> #include <QStringList> #include "integrationtestbase.h" #include "signalwaiter.h" #include "../../xpiks-qt/Commands/commandmanager.h" #include "../../xpiks-qt/Models/artitemsmodel.h" #include "../../xpiks-qt/MetadataIO/metadataiocoordinator.h" #include "../../xpiks-qt/Models/artworkmetadata.h" #include "../../xpiks-qt/Models/settingsmodel.h" #include "../../xpiks-qt/Models/filteredartitemsproxymodel.h" #include "../../xpiks-qt/SpellCheck/spellchecksuggestionmodel.h" #include "../../xpiks-qt/SpellCheck/spellsuggestionsitem.h" #include "../../xpiks-qt/Models/combinedartworksmodel.h" #include "../../xpiks-qt/Common/basickeywordsmodel.h" #include "../../xpiks-qt/Common/flags.h" #include "../../xpiks-qt/Warnings/warningsservice.h" #include "../../xpiks-qt/SpellCheck/spellcheckerservice.h" #include "testshelpers.h" QString SpellingProducesWarningsTest::testName() { return QLatin1String("SpellingProducesWarningsTest"); } void SpellingProducesWarningsTest::setup() { Models::SettingsModel *settingsModel = m_CommandManager->getSettingsModel(); settingsModel->setUseSpellCheck(true); } int SpellingProducesWarningsTest::doTest() { Models::ArtItemsModel *artItemsModel = m_CommandManager->getArtItemsModel(); QList<QUrl> files; files << getImagePathForTest("images-for-tests/vector/026.jpg"); int addedCount = artItemsModel->addLocalArtworks(files); VERIFY(addedCount == files.length(), "Failed to add file"); MetadataIO::MetadataIOCoordinator *ioCoordinator = m_CommandManager->getMetadataIOCoordinator(); SignalWaiter waiter; QObject::connect(ioCoordinator, SIGNAL(metadataReadingFinished()), &waiter, SIGNAL(finished())); ioCoordinator->continueReading(true); if (!waiter.wait(20)) { VERIFY(false, "Timeout exceeded for reading metadata."); } VERIFY(!ioCoordinator->getHasErrors(), "Errors in IO Coordinator while reading"); Models::ArtworkMetadata *metadata = artItemsModel->getArtwork(0); sleepWait(3, [metadata]() { return !Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInTitle) && !Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInDescription) && !Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInKeywords); }); VERIFY(!Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInTitle), "Error for reading title"); VERIFY(!Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInDescription), "Error for reading description"); VERIFY(!Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInKeywords), "Error for reading keywords"); QString wrongWord = "abbreviatioe"; metadata->setDescription(metadata->getDescription() + ' ' + wrongWord); metadata->setTitle(metadata->getTitle() + ' ' + wrongWord); metadata->appendKeyword("correct part " + wrongWord); metadata->setIsSelected(true); Models::FilteredArtItemsProxyModel *filteredModel = m_CommandManager->getFilteredArtItemsModel(); SpellCheck::SpellCheckerService *spellCheckService = m_CommandManager->getSpellCheckerService(); SignalWaiter spellingWaiter; QObject::connect(spellCheckService, SIGNAL(spellCheckQueueIsEmpty()), &spellingWaiter, SIGNAL(finished())); filteredModel->spellCheckSelected(); if (!spellingWaiter.wait(5)) { VERIFY(false, "Timeout for waiting for first spellcheck results"); } LOG_INFO << "Spellchecking finished. Waiting for warnings..."; Common::BasicKeywordsModel *keywordsModel = metadata->getKeywordsModel(); sleepWait(5, [=]() { return keywordsModel->hasDescriptionSpellError() && keywordsModel->hasTitleSpellError() && keywordsModel->hasKeywordsSpellError(); }); VERIFY(keywordsModel->hasDescriptionSpellError(), "Description spell error not detected"); VERIFY(keywordsModel->hasTitleSpellError(), "Title spell error not detected"); VERIFY(keywordsModel->hasKeywordsSpellError(), "Keywords spell error not detected"); VERIFY(Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInTitle), "Warning was not produced for title spelling error"); VERIFY(Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInDescription), "Warning was not produced for description spelling error"); VERIFY(Common::HasFlag(metadata->getWarningsFlags(), Common::WarningFlags::SpellErrorsInKeywords), "Warning was not produced for keywords spelling error"); return 0; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved */ #include "../../../StroikaPreComp.h" #if qHasFeature_libcurl #include <curl/curl.h> #endif #include "../../../Characters/Format.h" #include "../../../Execution/Exceptions.h" #include "Client_libcurl.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Foundation::IO::Network::Transfer; #if qHasFeature_libcurl namespace { struct ModuleInit_ { ModuleInit_ () { curl_global_init (CURL_GLOBAL_ALL); } }; } #endif #if qHasFeature_libcurl namespace { wstring mkExceptMsg_ (LibCurlException::CURLcode ccode) { return String::FromUTF8 (curl_easy_strerror (static_cast<CURLcode> (ccode))).As<wstring> (); } } /* ******************************************************************************** ************************ Transfer::LibCurlException **************************** ******************************************************************************** */ LibCurlException::LibCurlException (CURLcode ccode) : StringException (mkExceptMsg_ (ccode)) , fCurlCode_ (ccode) { } void LibCurlException::DoThrowIfError (CURLcode status) { if (status != CURLE_OK) { Execution::DoThrow (LibCurlException (status)); } } #endif #if qHasFeature_libcurl /* ******************************************************************************** ********************* Transfer::IConnection_LibCurl **************************** ******************************************************************************** */ IConnection_LibCurl::IConnection_LibCurl () : fCurlHandle_ (curl_easy_init ()) , fCURLCache_URL_ () , fResponseData_ () , fSavedHeaders_ (nullptr) { } IConnection_LibCurl::~IConnection_LibCurl () { if (fCurlHandle_ != nullptr) { curl_easy_cleanup (fCurlHandle_); } if (fSavedHeaders_ != nullptr) { curl_slist_free_all (fSavedHeaders_); fSavedHeaders_ = nullptr; } } URL IConnection_LibCurl::GetURL () const override { // needs work... - not sure this is safe - may need to cache orig... instead of reparsing... return URL (String::FromUTF8 (fCURLCache_URL_).As<wstring> ()); } void IConnection_LibCurl::SetURL (const URL& url) override { MakeHandleIfNeeded_ (); fCURLCache_URL_ = String (url.GetURL ()).AsUTF8 (); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_URL, fCURLCache_URL_.c_str ())); } void IConnection_LibCurl::Close () override { if (fCurlHandle_ != nullptr) { ::curl_easy_cleanup (fCurlHandle_); fCurlHandle_ = nullptr; } } size_t IConnection_LibCurl::ResponseWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP) { return reinterpret_cast<IConnection_LibCurl*> (userP)->ResponseWriteHandler_ (reinterpret_cast<const Byte*> (ptr), size * nmemb); } size_t IConnection_LibCurl::ResponseWriteHandler_ (const Byte* ptr, size_t nBytes) { fResponseData_.insert (fResponseData_.end (), ptr, ptr + nBytes); return nBytes; } size_t IConnection_LibCurl::ResponseHeaderWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP) { return reinterpret_cast<IConnection_LibCurl*> (userP)->ResponseHeaderWriteHandler_ (reinterpret_cast<const Byte*> (ptr), size * nmemb); } size_t IConnection_LibCurl::ResponseHeaderWriteHandler_ (const Byte* ptr, size_t nBytes) { string tmp (reinterpret_cast<const char*> (ptr), nBytes); string::size_type i = tmp.find (':'); String from; String to; if (i == string::npos) { from = String::FromUTF8 (tmp); } else { from = String::FromUTF8 (tmp.substr (0, i)); to = String::FromUTF8 (tmp.substr (i+1)); } from = from.Trim (); to = to.Trim (); fResponseHeaders_[from] = to; return nBytes; } Response IConnection_LibCurl::SendAndRequest (const Request& request) override { MakeHandleIfNeeded_ (); fResponseData_.clear (); fResponseHeaders_.clear (); //grab useragent from request headers... //curl_easy_setopt (fCurlHandle_, CURLOPT_USERAGENT, "libcurl-agent/1.0"); // grab initial headers and do POST/etc based on args in request... curl_slist* tmpH = curl_slist_append (nullptr, "Expect: "); //tmphack - really iterate over requst headers - with a few exceptions... LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HTTPHEADER, tmpH)); if (fSavedHeaders_ != nullptr) { curl_slist_free_all (fSavedHeaders_); fSavedHeaders_ = nullptr; } fSavedHeaders_ = tmpH; LibCurlException::DoThrowIfError (:: curl_easy_perform (fCurlHandle_)); Response response; response.fData = fResponseData_; long resultCode = 0; LibCurlException::DoThrowIfError (::curl_easy_getinfo (fCurlHandle_, CURLINFO_RESPONSE_CODE, &resultCode)); response.fStatus = resultCode; response.fHeaders = fResponseHeaders_; response.fData = fResponseData_; return response; } void IConnection_LibCurl::MakeHandleIfNeeded_ () { if (fCurlHandle_ == nullptr) { fCurlHandle_ = curl_easy_init (); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_URL, fCURLCache_URL_.c_str ())); } } #endif #if qHasFeature_libcurl /* ******************************************************************************** ********************* Transfer::IConnection_LibCurl **************************** ******************************************************************************** */ LibCurlConnection::LibCurlConnection () : Connection (Memory::SharedPtr<IConnection> (new IConnection_LibCurl ())) { } #endif<commit_msg>minor tweeks to Client_libcurl<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved */ #include "../../../StroikaPreComp.h" #if qHasFeature_libcurl #include <curl/curl.h> #endif #include "../../../Characters/Format.h" #include "../../../Execution/Exceptions.h" #include "Client_libcurl.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Foundation::IO::Network::Transfer; #if qHasFeature_libcurl namespace { struct ModuleInit_ { ModuleInit_ () { curl_global_init (CURL_GLOBAL_ALL); } }; } #endif #if qHasFeature_libcurl namespace { wstring mkExceptMsg_ (LibCurlException::CURLcode ccode) { return String::FromUTF8 (curl_easy_strerror (static_cast<CURLcode> (ccode))).As<wstring> (); } } /* ******************************************************************************** ************************ Transfer::LibCurlException **************************** ******************************************************************************** */ LibCurlException::LibCurlException (CURLcode ccode) : StringException (mkExceptMsg_ (ccode)) , fCurlCode_ (ccode) { } void LibCurlException::DoThrowIfError (CURLcode status) { if (status != CURLE_OK) { Execution::DoThrow (LibCurlException (status)); } } #endif #if qHasFeature_libcurl /* ******************************************************************************** ********************* Transfer::IConnection_LibCurl **************************** ******************************************************************************** */ IConnection_LibCurl::IConnection_LibCurl () : fCurlHandle_ (nullptr) , fCURLCache_URL_ () , fResponseData_ () , fSavedHeaders_ (nullptr) { } IConnection_LibCurl::~IConnection_LibCurl () { if (fCurlHandle_ != nullptr) { curl_easy_cleanup (fCurlHandle_); } if (fSavedHeaders_ != nullptr) { curl_slist_free_all (fSavedHeaders_); fSavedHeaders_ = nullptr; } } URL IConnection_LibCurl::GetURL () const override { // needs work... - not sure this is safe - may need to cache orig... instead of reparsing... return URL (String::FromUTF8 (fCURLCache_URL_).As<wstring> ()); } void IConnection_LibCurl::SetURL (const URL& url) override { MakeHandleIfNeeded_ (); fCURLCache_URL_ = String (url.GetURL ()).AsUTF8 (); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_URL, fCURLCache_URL_.c_str ())); } void IConnection_LibCurl::Close () override { if (fCurlHandle_ != nullptr) { ::curl_easy_cleanup (fCurlHandle_); fCurlHandle_ = nullptr; } } size_t IConnection_LibCurl::ResponseWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP) { return reinterpret_cast<IConnection_LibCurl*> (userP)->ResponseWriteHandler_ (reinterpret_cast<const Byte*> (ptr), size * nmemb); } size_t IConnection_LibCurl::ResponseWriteHandler_ (const Byte* ptr, size_t nBytes) { fResponseData_.insert (fResponseData_.end (), ptr, ptr + nBytes); return nBytes; } size_t IConnection_LibCurl::ResponseHeaderWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP) { return reinterpret_cast<IConnection_LibCurl*> (userP)->ResponseHeaderWriteHandler_ (reinterpret_cast<const Byte*> (ptr), size * nmemb); } size_t IConnection_LibCurl::ResponseHeaderWriteHandler_ (const Byte* ptr, size_t nBytes) { string tmp (reinterpret_cast<const char*> (ptr), nBytes); string::size_type i = tmp.find (':'); String from; String to; if (i == string::npos) { from = String::FromUTF8 (tmp); } else { from = String::FromUTF8 (tmp.substr (0, i)); to = String::FromUTF8 (tmp.substr (i+1)); } from = from.Trim (); to = to.Trim (); fResponseHeaders_[from] = to; return nBytes; } Response IConnection_LibCurl::SendAndRequest (const Request& request) override { MakeHandleIfNeeded_ (); fResponseData_.clear (); fResponseHeaders_.clear (); //grab useragent from request headers... //curl_easy_setopt (fCurlHandle_, CURLOPT_USERAGENT, "libcurl-agent/1.0"); // grab initial headers and do POST/etc based on args in request... curl_slist* tmpH = nullptr; for (map<String,String>::const_iterator i = request.fOverrideHeaders.begin (); i != request.fOverrideHeaders.end (); ++i) { tmpH = curl_slist_append (tmpH, (i->first + L": " + i->second).c_str ()); } AssertNotNull (fCurlHandle_); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HTTPHEADER, tmpH)); if (fSavedHeaders_ != nullptr) { curl_slist_free_all (fSavedHeaders_); fSavedHeaders_ = nullptr; } fSavedHeaders_ = tmpH; LibCurlException::DoThrowIfError (:: curl_easy_perform (fCurlHandle_)); Response response; response.fData = fResponseData_; long resultCode = 0; LibCurlException::DoThrowIfError (::curl_easy_getinfo (fCurlHandle_, CURLINFO_RESPONSE_CODE, &resultCode)); response.fStatus = resultCode; response.fHeaders = fResponseHeaders_; response.fData = fResponseData_; return response; } void IConnection_LibCurl::MakeHandleIfNeeded_ () { if (fCurlHandle_ == nullptr) { ThrowIfNull (fCurlHandle_ = ::curl_easy_init ()); /* * Now setup COMMON options we ALWAYS set. */ LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_URL, fCURLCache_URL_.c_str ())); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_WRITEFUNCTION, ResponseWriteHandler_)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_WRITEDATA, this)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HEADERFUNCTION, ResponseHeaderWriteHandler_)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_WRITEHEADER, this)); } } #endif #if qHasFeature_libcurl /* ******************************************************************************** ********************* Transfer::IConnection_LibCurl **************************** ******************************************************************************** */ LibCurlConnection::LibCurlConnection () : Connection (Memory::SharedPtr<IConnection> (new IConnection_LibCurl ())) { } #endif<|endoftext|>
<commit_before><commit_msg>Added a forgotten VPackBuilder.close() in Traversalnode to VPack. This caused the query planner to fail at certain cases<commit_after><|endoftext|>
<commit_before>#include "VirtualHIDManager.hpp" #define super IOService OSDefineMetaClassAndStructors(org_pqrs_driver_VirtualHIDManager, IOService); bool org_pqrs_driver_VirtualHIDManager::init(OSDictionary* dict) { if (!super::init(dict)) { return false; } attachedClientCount_ = 0; virtualHIDPointing_ = nullptr; if (auto serialNumber = OSString::withCString("org.pqrs.driver.VirtualHIDManager")) { setProperty(kIOHIDSerialNumberKey, serialNumber); serialNumber->release(); } return true; } void org_pqrs_driver_VirtualHIDManager::free(void) { super::free(); } bool org_pqrs_driver_VirtualHIDManager::start(IOService* provider) { if (!super::start(provider)) { return false; } // Publish ourselves so clients can find us // // Note: // IOHIDDevice (VirtualHIDPointing, etc) cannot create custom UserClient directly. // Therefore, we provide IOHIDManager for UserClient. registerService(); return true; } void org_pqrs_driver_VirtualHIDManager::stop(IOService* provider) { } void org_pqrs_driver_VirtualHIDManager::attachClient(void) { ++attachedClientCount_; IOLog("org_pqrs_driver_VirtualHIDManager::attachClient attachedClientCount_ = %d\n", static_cast<int>(attachedClientCount_)); createVirtualHIDPointing(); } void org_pqrs_driver_VirtualHIDManager::detachClient(void) { if (attachedClientCount_ > 0) { --attachedClientCount_; } IOLog("org_pqrs_driver_VirtualHIDManager::detachClient attachedClientCount_ = %d\n", static_cast<int>(attachedClientCount_)); if (attachedClientCount_ == 0 && virtualHIDPointing_) { terminateVirtualHIDPointing(); } } void org_pqrs_driver_VirtualHIDManager::createVirtualHIDPointing(void) { if (virtualHIDPointing_) { return; } // See IOHIDResourceDeviceUserClient::createAndStartDevice virtualHIDPointing_ = OSTypeAlloc(org_pqrs_driver_VirtualHIDPointing); if (!virtualHIDPointing_) { return; } if (!virtualHIDPointing_->init(nullptr)) { goto error; } if (!virtualHIDPointing_->attach(this)) { goto error; } if (!virtualHIDPointing_->start(this)) { virtualHIDPointing_->detach(this); goto error; } return; error: if (virtualHIDPointing_) { virtualHIDPointing_->release(); virtualHIDPointing_ = nullptr; } } void org_pqrs_driver_VirtualHIDManager::terminateVirtualHIDPointing(void) { if (!virtualHIDPointing_) { return; } virtualHIDPointing_->terminate(); virtualHIDPointing_->release(); virtualHIDPointing_ = nullptr; } IOReturn org_pqrs_driver_VirtualHIDManager::handleHIDPointingReport(IOMemoryDescriptor* report) { if (virtualHIDPointing_) { return virtualHIDPointing_->handleReport(report, kIOHIDReportTypeInput, kIOHIDOptionsTypeNone); } return kIOReturnError; } <commit_msg>call terminateVirtualHIDPointing in stop<commit_after>#include "VirtualHIDManager.hpp" #define super IOService OSDefineMetaClassAndStructors(org_pqrs_driver_VirtualHIDManager, IOService); bool org_pqrs_driver_VirtualHIDManager::init(OSDictionary* dict) { IOLog("org_pqrs_driver_VirtualHIDManager::init\n"); if (!super::init(dict)) { return false; } attachedClientCount_ = 0; virtualHIDPointing_ = nullptr; if (auto serialNumber = OSString::withCString("org.pqrs.driver.VirtualHIDManager")) { setProperty(kIOHIDSerialNumberKey, serialNumber); serialNumber->release(); } return true; } void org_pqrs_driver_VirtualHIDManager::free(void) { IOLog("org_pqrs_driver_VirtualHIDManager::free\n"); super::free(); } bool org_pqrs_driver_VirtualHIDManager::start(IOService* provider) { IOLog("org_pqrs_driver_VirtualHIDManager::start\n"); if (!super::start(provider)) { return false; } // Publish ourselves so clients can find us // // Note: // IOHIDDevice (VirtualHIDPointing, etc) cannot create custom UserClient directly. // Therefore, we provide IOHIDManager for UserClient. registerService(); return true; } void org_pqrs_driver_VirtualHIDManager::stop(IOService* provider) { IOLog("org_pqrs_driver_VirtualHIDManager::stop\n"); terminateVirtualHIDPointing(); super::stop(provider); } void org_pqrs_driver_VirtualHIDManager::attachClient(void) { ++attachedClientCount_; IOLog("org_pqrs_driver_VirtualHIDManager::attachClient attachedClientCount_ = %d\n", static_cast<int>(attachedClientCount_)); createVirtualHIDPointing(); } void org_pqrs_driver_VirtualHIDManager::detachClient(void) { if (attachedClientCount_ > 0) { --attachedClientCount_; } IOLog("org_pqrs_driver_VirtualHIDManager::detachClient attachedClientCount_ = %d\n", static_cast<int>(attachedClientCount_)); if (attachedClientCount_ == 0 && virtualHIDPointing_) { terminateVirtualHIDPointing(); } } void org_pqrs_driver_VirtualHIDManager::createVirtualHIDPointing(void) { if (virtualHIDPointing_) { return; } // See IOHIDResourceDeviceUserClient::createAndStartDevice virtualHIDPointing_ = OSTypeAlloc(org_pqrs_driver_VirtualHIDPointing); if (!virtualHIDPointing_) { return; } if (!virtualHIDPointing_->init(nullptr)) { goto error; } if (!virtualHIDPointing_->attach(this)) { goto error; } if (!virtualHIDPointing_->start(this)) { virtualHIDPointing_->detach(this); goto error; } return; error: if (virtualHIDPointing_) { virtualHIDPointing_->release(); virtualHIDPointing_ = nullptr; } } void org_pqrs_driver_VirtualHIDManager::terminateVirtualHIDPointing(void) { if (!virtualHIDPointing_) { return; } virtualHIDPointing_->terminate(); virtualHIDPointing_->release(); virtualHIDPointing_ = nullptr; } IOReturn org_pqrs_driver_VirtualHIDManager::handleHIDPointingReport(IOMemoryDescriptor* report) { if (!virtualHIDPointing_) { return kIOReturnError; } return virtualHIDPointing_->handleReport(report, kIOHIDReportTypeInput, kIOHIDOptionsTypeNone); } <|endoftext|>
<commit_before>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "TestFixtures/Decoration.hpp" #include <autowiring/AutoPacketFactory.h> #include <autowiring/AutoPacketGraph.h> #include CHRONO_HEADER #include THREAD_HEADER class AutoPacketGraphTest: public testing::Test {}; class APReceiver1 { public: APReceiver1(void) {} void AutoFilter(Decoration<0> d0) { } }; class APReceiver2 { public: APReceiver2(void) {} void AutoFilter(Decoration<0> d0, Decoration<1>& d1) { } }; class APReceiver3 { public: APReceiver3(void) {} void AutoFilter(Decoration<0> d0, Decoration<1> d1) { } }; class APReceiver4 { public: APReceiver4(void) {} void AutoFilter(Decoration<0> d0, Decoration<2> d2) { } }; TEST_F(AutoPacketGraphTest, VerifyEmptyGraphBeforeCtxtInit) { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<AutoPacketGraph> graph; ASSERT_TRUE(graph->GetEdgeCounts().empty()) << "Graph did not start out empty before context initiation"; ctxt->Initiate(); ASSERT_TRUE(graph->GetEdgeCounts().empty()) << "Graph did not stay empty after context initiation"; ctxt->SignalShutdown(); } TEST_F(AutoPacketGraphTest, VerifyEmptyGraphAfterCtxtInit) { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); ctxt->Initiate(); AutoRequired<AutoPacketGraph> graph; ASSERT_TRUE(graph->GetEdgeCounts().empty()) << "Graph did not start out empty"; ctxt->SignalShutdown(); } TEST_F(AutoPacketGraphTest, VerifySimpleEdgeFromObjectBeforeInit) { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<AutoPacketGraph> graph; AutoRequired<APReceiver1> receiver1; ASSERT_TRUE(graph->GetEdgeCounts().empty()) << "Graph should still be empty before context is initialized"; ctxt->Initiate(); ASSERT_EQ(1UL, graph->GetEdgeCounts().size()) << "Graph did not detect AutoFilter from object after being initiated"; ctxt->SignalShutdown(); } TEST_F(AutoPacketGraphTest, VerifySimpleInputFilter) { // TODO } TEST_F(AutoPacketGraphTest, VerifySimpleOutputFilter) { // TODO } TEST_F(AutoPacketGraphTest, VerifyPacketDecorationIncrementingCount) { // TODO } TEST_F(AutoPacketGraphTest, VerifyLoadAutoFilterSystem) { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<AutoPacketFactory> factory(ctxt); AutoRequired<AutoPacketGraph> graph; ctxt->Initiate(); AutoRequired<APReceiver1> receiver1; AutoRequired<APReceiver2> receiver2; AutoRequired<APReceiver3> receiver3; AutoRequired<APReceiver4> receiver4; AutoPacketGraph::t_deliveryEdges edges = graph->GetEdgeCounts(); ASSERT_EQ(7UL, edges.size()) << "Graph could not load the edges from new objects"; for (auto& itr : edges) { ASSERT_EQ(0UL, itr.second) << "Coutn should be 0 since packets have not been delivered yet"; } } <commit_msg>adding 2 quick tests<commit_after>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "TestFixtures/Decoration.hpp" #include <autowiring/AutoPacketFactory.h> #include <autowiring/AutoPacketGraph.h> #include CHRONO_HEADER #include THREAD_HEADER class AutoPacketGraphTest: public testing::Test {}; class APReceiver1 { public: APReceiver1(void) {} void AutoFilter(Decoration<0> d0) { } }; class APReceiver2 { public: APReceiver2(void) {} void AutoFilter(Decoration<0> d0, Decoration<1>& d1) { } }; class APReceiver3 { public: APReceiver3(void) {} void AutoFilter(Decoration<0> d0, Decoration<1> d1) { } }; class APReceiver4 { public: APReceiver4(void) {} void AutoFilter(Decoration<0> d0, Decoration<2> d2) { } }; TEST_F(AutoPacketGraphTest, VerifyEmptyGraphBeforeCtxtInit) { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<AutoPacketGraph> graph; ASSERT_TRUE(graph->GetEdgeCounts().empty()) << "Graph did not start out empty before context initiation"; ctxt->Initiate(); ASSERT_TRUE(graph->GetEdgeCounts().empty()) << "Graph did not stay empty after context initiation"; ctxt->SignalShutdown(); } TEST_F(AutoPacketGraphTest, VerifyEmptyGraphAfterCtxtInit) { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); ctxt->Initiate(); AutoRequired<AutoPacketGraph> graph; ASSERT_TRUE(graph->GetEdgeCounts().empty()) << "Graph did not start out empty"; ctxt->SignalShutdown(); } TEST_F(AutoPacketGraphTest, VerifySimpleEdgeFromObjectBeforeInit) { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<AutoPacketGraph> graph; AutoRequired<APReceiver1> receiver1; ASSERT_TRUE(graph->GetEdgeCounts().empty()) << "Graph should still be empty before context is initialized"; ctxt->Initiate(); ASSERT_EQ(1UL, graph->GetEdgeCounts().size()) << "Graph did not detect AutoFilter from object after being initiated"; ctxt->SignalShutdown(); } TEST_F(AutoPacketGraphTest, VerifySimpleEdgeFromNewObject) { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<AutoPacketGraph> graph; ctxt->Initiate(); ASSERT_TRUE(graph->GetEdgeCounts().empty()) << "Graph should still be empty before context is initialized"; AutoRequired<APReceiver1> receiver1; ASSERT_EQ(1UL, graph->GetEdgeCounts().size()) << "Graph did not detect AutoFilter from object after being initiated"; ctxt->SignalShutdown(); } TEST_F(AutoPacketGraphTest, VerifyLoadGraphAfterInitAndObject) { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<APReceiver1> receiver1; ctxt->Initiate(); AutoRequired<AutoPacketGraph> graph; ASSERT_EQ(1UL, graph->GetEdgeCounts().size()) << "Graph did not detect AutoFilter from object after being initiated"; ctxt->SignalShutdown(); } TEST_F(AutoPacketGraphTest, VerifySimpleInputFilter) { // TODO } TEST_F(AutoPacketGraphTest, VerifySimpleOutputFilter) { // TODO } TEST_F(AutoPacketGraphTest, VerifyPacketDecorationIncrementingCount) { // TODO } TEST_F(AutoPacketGraphTest, VerifyLoadAutoFilterSystem) { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<AutoPacketFactory> factory(ctxt); AutoRequired<AutoPacketGraph> graph; ctxt->Initiate(); AutoRequired<APReceiver1> receiver1; AutoRequired<APReceiver2> receiver2; AutoRequired<APReceiver3> receiver3; AutoRequired<APReceiver4> receiver4; AutoPacketGraph::t_deliveryEdges edges = graph->GetEdgeCounts(); { auto packet = factory->NewPacket(); packet->Decorate(Decoration<0>(0)); packet->Decorate(Decoration<2>(2)); } ASSERT_EQ(7UL, edges.size()) << "Graph could not load the edges from new objects"; for (auto& itr : edges) { ASSERT_EQ(0UL, itr.second) << "Coutn should be 0 since packets have not been delivered yet"; } ctxt->SignalShutdown(); } <|endoftext|>
<commit_before>#include <iostream> #include <iterator> #include <algorithm> #include <vector> #include <cstdlib> void assertTrue(bool actual) { std::cout << "Test " << (actual ? "Pass" : "FAIL") << std::endl; } void assertFalse(bool actual) { std::cout << "Test " << (!actual ? "Pass" : "FAIL") << std::endl; } // Binary search using a recursive algorithm. bool binary_search_recursive(const std::vector<int>::iterator begin, const std::vector<int>::iterator end, int target) { if(begin == end) return false; std::vector<int>::iterator mid = begin + std::distance(begin, end)/2; if(*mid == target) { return true; } else if(target < *mid) { return binary_search_recursive(begin, mid, target); } else { return binary_search_recursive(mid, end, target); } return false; } // Binary search using an iterative algorithm. bool binary_search_iterative(const std::vector<int>::iterator begin, const std::vector<int>::iterator end, int target) { std::vector<int>::iterator sub_range_begin = begin; std::vector<int>::iterator sub_range_end = end; while(sub_range_begin != sub_range_end) { std::vector<int>::iterator mid = sub_range_begin + std::distance(sub_range_begin, sub_range_end)/2; if(*mid == target) { return true; } else if(target < *mid) { sub_range_end = mid; } else { sub_range_begin = mid; } } return false; } int main() { const int data_size = 100; // Fill a vector with some random values std::vector<int> data(data_size); std::generate(data.begin(), data.end(), std::rand); // Remember the last element in the data set. // This will be the target value to search for. int val = data.back(); // Sort the vector std::sort(data.begin(), data.end()); // Search for the target value in each algorithm implementation assertTrue(std::binary_search(data.begin(), data.end(), val)); assertTrue(binary_search_recursive(data.begin(), data.end(), val)); assertTrue(binary_search_iterative(data.begin(), data.end(), val)); return 0; } <commit_msg>Changing to a sequential data sequence and testing negative test cases<commit_after>#include <iostream> #include <iterator> #include <algorithm> #include <vector> #include <cstdlib> void assertTrue(bool actual) { std::cout << "Test " << (actual ? "Pass" : "FAIL") << std::endl; } void assertFalse(bool actual) { std::cout << "Test " << (!actual ? "Pass" : "FAIL") << std::endl; } class IncrementingSequence { public: // Constructor IncrementingSequence(): i_(0) {} // Return an incrementing counter int operator() () { return i_++; } private: int i_; }; // Binary search using a recursive algorithm. bool binary_search_recursive(const std::vector<int>::iterator begin, const std::vector<int>::iterator end, int target) { if(begin == end) return false; std::vector<int>::iterator mid = begin + std::distance(begin, end)/2; if(*mid == target) { return true; } else if(target < *mid) { return binary_search_recursive(begin, mid, target); } else { return binary_search_recursive(mid, end, target); } return false; } // Binary search using an iterative algorithm. bool binary_search_iterative(const std::vector<int>::iterator begin, const std::vector<int>::iterator end, int target) { std::vector<int>::iterator sub_range_begin = begin; std::vector<int>::iterator sub_range_end = end; while(sub_range_begin != sub_range_end) { std::vector<int>::iterator mid = sub_range_begin + std::distance(sub_range_begin, sub_range_end)/2; if(*mid == target) { return true; } else if(target < *mid) { sub_range_end = mid; } else { sub_range_begin = mid; } } return false; } int main() { const int data_size = 100; // Fill a vector with some values std::vector<int> data(data_size); std::generate(data.begin(), data.end(), IncrementingSequence()); // Search for values in each algorithm implementation assertTrue(std::binary_search(data.begin(), data.end(), 25)); assertFalse(std::binary_search(data.begin(), data.end(), -1)); assertTrue(binary_search_recursive(data.begin(), data.end(), 25)); assertFalse(binary_search_recursive(data.begin(), data.end(), -1)); assertTrue(binary_search_iterative(data.begin(), data.end(), 25)); assertFalse(binary_search_iterative(data.begin(), data.end(), -1)); return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/log.h" #include "modules/perception/proto/perception_obstacle.pb.h" #include "modules/perception/traffic_light/base/image_lights.h" #include "ros/ros.h" #include "sensor_msgs/Image.h" using apollo::perception::traffic_light::Image; using apollo::perception::traffic_light::CameraId; using apollo::perception::PerceptionObstacles; std::map<std::string, cv::Scalar> kColorTable = { {std::string("red_light_box"), cv::Scalar(0, 0, 255)}, {std::string("green_light_box"), cv::Scalar(0, 255, 0)}, {std::string("yellow_light_box"), cv::Scalar(0, 255, 255)}, {std::string("black_light_box"), cv::Scalar(255, 90, 199)}, {std::string("unknown_light_box"), cv::Scalar(0, 76, 153)}, {std::string("projection_roi"), cv::Scalar(255, 255, 0)}, {std::string("crop_roi"), cv::Scalar(0, 255, 255)}, {std::string("debug_roi"), cv::Scalar(255, 169, 255)}}; std::vector<std::shared_ptr<Image>> g_cached_images; const int kMaxCachedImageNum = 100; void OnPerception(const PerceptionObstacles &); void OnImageShort(const sensor_msgs::ImagePtr &); void OnImageLong(const sensor_msgs::ImagePtr &); int main(int argc, char **argv) { ros::init(argc, argv, "camera_visualizer"); ros::NodeHandle n; ros::Subscriber sub_perception_debug = n.subscribe(FLAGS_perception_obstacle_topic, 1000, OnPerception); ros::Subscriber sub_tl_image_long = n.subscribe(FLAGS_image_long_topic, 1000, OnImageLong); ros::Subscriber sub_tl_image_short = n.subscribe(FLAGS_image_short_topic, 1000, OnImageShort); ros::spin(); return 0; } void OnPerception(const PerceptionObstacles &obstacles) { // TODO(all): add debug into perception debug pb and draw on image. g_cached_images.back()->GenerateMat(); cv::Mat img = g_cached_images.back()->mat(); cv::resize(img, img, cv::Size(960, 540)); cv::imshow("camera_debug_image", img); cv::waitKey(10); } void OnImage(CameraId camera_id, const sensor_msgs::ImagePtr &msg) { boost::shared_ptr<sensor_msgs::Image> img(new sensor_msgs::Image); *img = *msg; boost::shared_ptr<const sensor_msgs::Image> img_msg(img); std::shared_ptr<Image> image(new Image); if (!image->Init(img_msg->header.stamp.toSec(), camera_id, img_msg)) { std::cerr << "tl_visualizer load image failed."; } g_cached_images.push_back(image); while (g_cached_images.size() > kMaxCachedImageNum) { g_cached_images.erase(g_cached_images.begin()); } } void OnImageLong(const sensor_msgs::ImagePtr &msg) { OnImage(CameraId::LONG_FOCUS, msg); } void OnImageShort(const sensor_msgs::ImagePtr &msg) { OnImage(CameraId::SHORT_FOCUS, msg); } <commit_msg>perception: only show short camera in camera visualizer.<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/log.h" #include "modules/perception/proto/perception_obstacle.pb.h" #include "modules/perception/traffic_light/base/image_lights.h" #include "ros/ros.h" #include "sensor_msgs/Image.h" using apollo::perception::traffic_light::Image; using apollo::perception::traffic_light::CameraId; using apollo::perception::PerceptionObstacles; std::map<std::string, cv::Scalar> kColorTable = { {std::string("red_light_box"), cv::Scalar(0, 0, 255)}, {std::string("green_light_box"), cv::Scalar(0, 255, 0)}, {std::string("yellow_light_box"), cv::Scalar(0, 255, 255)}, {std::string("black_light_box"), cv::Scalar(255, 90, 199)}, {std::string("unknown_light_box"), cv::Scalar(0, 76, 153)}, {std::string("projection_roi"), cv::Scalar(255, 255, 0)}, {std::string("crop_roi"), cv::Scalar(0, 255, 255)}, {std::string("debug_roi"), cv::Scalar(255, 169, 255)}}; std::vector<std::shared_ptr<Image>> g_cached_images; const int kMaxCachedImageNum = 10; void OnPerception(const PerceptionObstacles &); void OnImageShort(const sensor_msgs::ImagePtr &); int main(int argc, char **argv) { ros::init(argc, argv, "camera_visualizer"); ros::NodeHandle n; ros::Subscriber sub_perception_debug = n.subscribe(FLAGS_perception_obstacle_topic, 1000, OnPerception); ros::Subscriber sub_tl_image_short = n.subscribe(FLAGS_image_short_topic, 1000, OnImageShort); ros::spin(); return 0; } void OnPerception(const PerceptionObstacles &obstacles) { // TODO(all): add debug into perception debug pb and draw on image. g_cached_images.back()->GenerateMat(); cv::Mat img = g_cached_images.back()->mat(); cv::resize(img, img, cv::Size(960, 540)); cv::imshow("camera_debug_image", img); cv::waitKey(10); } void OnImage(CameraId camera_id, const sensor_msgs::ImagePtr &msg) { boost::shared_ptr<sensor_msgs::Image> img(new sensor_msgs::Image); *img = *msg; boost::shared_ptr<const sensor_msgs::Image> img_msg(img); std::shared_ptr<Image> image(new Image); if (!image->Init(img_msg->header.stamp.toSec(), camera_id, img_msg)) { std::cerr << "tl_visualizer load image failed."; } g_cached_images.push_back(image); while (g_cached_images.size() > kMaxCachedImageNum) { g_cached_images.erase(g_cached_images.begin()); } } void OnImageShort(const sensor_msgs::ImagePtr &msg) { OnImage(CameraId::SHORT_FOCUS, msg); } <|endoftext|>
<commit_before>#include "../../util/token.h" #include "../../util/tokenreader.h" #include <exception> #include <iostream> #include <fstream> #include <stdlib.h> #include <string> #include <math.h> using namespace std; class Failure: public exception{ public: Failure(int num): num(num){ } int num; }; static void test1_write(const string & name){ ofstream out(name.c_str()); out << "(foo)"; out.close(); } static string randomFile(){ static char temp[64]; sprintf(temp, "/tmp/tokenXXXXXX"); return string(mktemp(temp)); } static void test1(){ try{ string file = randomFile(); test1_write(file); TokenReader reader(file); reader.readToken(); } catch (...){ throw Failure(1); } } static void test2_write(string name){ ofstream out(name.c_str()); out << "(foo"; out.close(); } static void test2(){ try{ string file = randomFile(); test2_write(file); TokenReader reader(file); reader.readToken(); throw Failure(2); } catch (const TokenException & e){ /* good */ } } static void test3_write(string file){ ofstream out(file.c_str()); out << "(foo1 (foo2 (foo3)) (foo2 (foo3)))"; out.close(); } static void test3(){ string file = randomFile(); test3_write(file); TokenReader reader(file); Token * head = reader.readToken(); vector<const Token*> tokens = head->findTokens("foo1/foo2/foo3"); if (tokens.size() != 2){ throw Failure(3); } } static void test4_write(string file){ ofstream out(file.c_str()); out << "(foo (bar cheese))"; out.close(); } static void test4(){ string file = randomFile(); test4_write(file); TokenReader reader(file); Token * head = reader.readToken(); string words; head->match("foo/bar", words); if (words != "cheese"){ throw Failure(4); } } static void test5_write(string file){ ofstream out(file.c_str()); out << "(relative-position -.5 -.5)"; out.close(); } static void test5(){ string file = randomFile(); test5_write(file); TokenReader reader(file); Token * head = reader.readToken(); double n1 = 0, n2 = 0; double epsilon = 0.00000001; if (*head != "relative-position"){ throw Failure(5); } head->view() >> n1 >> n2; if (fabs(n1 - (-0.5)) > epsilon){ throw Failure(5); } if (fabs(n2 - (-0.5)) > epsilon){ throw Failure(5); } } static void test6(){ string data = "(foo1 (foo2 (foo3)) (foo2 (foo3)))"; TokenReader reader; Token * head = reader.readTokenFromString(data); vector<const Token*> tokens = head->findTokens("foo1/foo2/foo3"); if (tokens.size() != 2){ throw Failure(6); } } int main(){ try{ test1(); test2(); test3(); test4(); test5(); test6(); cout << "All tests passed!" << endl; return 0; } catch (const Failure & f){ cout << "Test case " << f.num << " failed" << endl; return 1; } } <commit_msg>recognize more values for true/false in tokens<commit_after>#include "../../util/token.h" #include "../../util/tokenreader.h" #include <exception> #include <iostream> #include <sstream> #include <fstream> #include <stdlib.h> #include <string> #include <math.h> using namespace std; class Failure: public exception{ public: Failure(int num): num(num){ } int num; }; static void test1_write(const string & name){ ofstream out(name.c_str()); out << "(foo)"; out.close(); } static string randomFile(){ static char temp[64]; sprintf(temp, "/tmp/tokenXXXXXX"); return string(mktemp(temp)); } static void test1(){ try{ string file = randomFile(); test1_write(file); TokenReader reader(file); reader.readToken(); } catch (...){ throw Failure(1); } } static void test2_write(string name){ ofstream out(name.c_str()); out << "(foo"; out.close(); } static void test2(){ try{ string file = randomFile(); test2_write(file); TokenReader reader(file); reader.readToken(); throw Failure(2); } catch (const TokenException & e){ /* good */ } } static void test3_write(string file){ ofstream out(file.c_str()); out << "(foo1 (foo2 (foo3)) (foo2 (foo3)))"; out.close(); } static void test3(){ string file = randomFile(); test3_write(file); TokenReader reader(file); Token * head = reader.readToken(); vector<const Token*> tokens = head->findTokens("foo1/foo2/foo3"); if (tokens.size() != 2){ throw Failure(3); } } static void test4_write(string file){ ofstream out(file.c_str()); out << "(foo (bar cheese))"; out.close(); } static void test4(){ string file = randomFile(); test4_write(file); TokenReader reader(file); Token * head = reader.readToken(); string words; head->match("foo/bar", words); if (words != "cheese"){ throw Failure(4); } } static void test5_write(string file){ ofstream out(file.c_str()); out << "(relative-position -.5 -.5)"; out.close(); } static void test5(){ string file = randomFile(); test5_write(file); TokenReader reader(file); Token * head = reader.readToken(); double n1 = 0, n2 = 0; double epsilon = 0.00000001; if (*head != "relative-position"){ throw Failure(5); } head->view() >> n1 >> n2; if (fabs(n1 - (-0.5)) > epsilon){ throw Failure(5); } if (fabs(n2 - (-0.5)) > epsilon){ throw Failure(5); } } static void test6(){ string data = "(foo1 (foo2 (foo3)) (foo2 (foo3)))"; TokenReader reader; Token * head = reader.readTokenFromString(data); vector<const Token*> tokens = head->findTokens("foo1/foo2/foo3"); if (tokens.size() != 2){ throw Failure(6); } } static void test7_helper(string on, string off){ std::ostringstream out; out << "(foo " << on << " " << off << ")"; TokenReader reader; Token * head = reader.readTokenFromString(out.str()); bool xtrue = false; bool xfalse = true; head->match("foo", xtrue, xfalse); if (!xtrue || xfalse){ throw Failure(7); } } static void test7(){ test7_helper("on", "off"); test7_helper("1", "0"); test7_helper("true", "false"); test7_helper("enable", "disable"); } int main(){ try{ test1(); test2(); test3(); test4(); test5(); test6(); test7(); cout << "All tests passed!" << endl; return 0; } catch (const Failure & f){ cout << "Test case " << f.num << " failed" << endl; return 1; } } <|endoftext|>
<commit_before>/* * This file is part of the bitcoin-classic project * Copyright (C) 2017 Tom Zander <tomz@freedommail.ch> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "transaction_utils.h" #include "test/test_bitcoin.h" #include <boost/test/auto_unit_test.hpp> #include <Application.h> #include <BlocksDB.h> #include <chain.h> #include <chainparams.h> #include <primitives/transaction.h> #include <main.h> #include <consensus/validation.h> #include <vector> class MyTestingFixture : public TestingSetup { public: MyTestingFixture() : TestingSetup(CBaseChainParams::REGTEST, BlocksDbOnDisk) {} }; static CBlockIndex *createBlockIndex(CBlockIndex *prev, int height, int time, uint256 *hash) { assert(hash); CBlockIndex *index = new CBlockIndex(); index->nHeight = height; index->nTime = time; index->pprev = prev; *hash = CDiskBlockIndex(index).GetBlockHash(); index->phashBlock = hash; index->BuildSkip(); Blocks::DB::instance()->appendBlock(index, 0); Blocks::indexMap.insert(std::make_pair(*hash, index)); Blocks::DB::instance()->appendHeader(index); return index; } static CBlock createBlock(CBlockIndex *parent, const std::vector<CTransaction>& txns) { CMutableTransaction coinbase; coinbase.vin.resize(1); coinbase.vout.resize(1); coinbase.vin[0].scriptSig = CScript() << (parent->nHeight + 1) << OP_0; coinbase.vout[0].nValue = 50 * COIN; CBlock block; block.vtx.push_back(coinbase); block.nVersion = 4; block.hashPrevBlock = *parent->phashBlock; block.nTime = parent->GetMedianTimePast() + 20; block.nBits = 0x207fffff; block.nNonce = 0; block.vtx.reserve(txns.size() + 1); for (const CTransaction &tx : txns) { block.vtx.push_back(tx); } return block; } BOOST_FIXTURE_TEST_SUITE(UAHF, MyTestingFixture) BOOST_AUTO_TEST_CASE(Test_Enabling) { mapArgs["-uahfstarttime"] = "0"; MockApplication::doInit(); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFDisabled); BOOST_CHECK_EQUAL(Application::uahfStartTime(), 0); mapArgs["-uahfstarttime"] = "-1"; MockApplication::doInit(); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFDisabled); BOOST_CHECK_EQUAL(Application::uahfStartTime(), 0); mapArgs["-uahfstarttime"] = "1"; MockApplication::doInit(); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFWaiting); BOOST_CHECK_EQUAL(Application::uahfStartTime(), 1); mapArgs["-uahfstarttime"] = "12352"; MockApplication::doInit(); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFWaiting); BOOST_CHECK_EQUAL(Application::uahfStartTime(), 12352); BOOST_CHECK(Blocks::DB::instance()->uahfForkBlock() == uint256()); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFWaiting); // we use the MTP, which uses 11 blocks, so make sure we actually have those // and they say exactly what we want them to say. std::vector<uint256> hashes; hashes.resize(12); // create 20 block-indexes. CBlockIndex *tip = Blocks::indexMap.begin()->second; for (int i = 0; i < 12; ++i) { tip = createBlockIndex(tip, i + 1, 20000 + i * 100, &hashes[i]); } chainActive.SetTip(tip); // tip GMTP is 20600, the one before 20500 Blocks::DB::instance()->setUahfForkBlock(hashes[11]); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFActive); mapArgs["-uahfstarttime"] = "0"; MockApplication::doInit(); Blocks::DB::createInstance(0, false); BOOST_CHECK(Blocks::DB::instance()->uahfForkBlock() == uint256()); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFDisabled); mapArgs["-uahfstarttime"] = "12352"; MockApplication::doInit(); Blocks::DB::createInstance(0, false); Blocks::DB::instance()->CacheAllBlockInfos(); BOOST_CHECK(Blocks::DB::instance()->uahfForkBlock() == hashes[11]); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFActive); mapArgs["-uahfstarttime"] = "20500"; MockApplication::doInit(); Blocks::DB::createInstance(0, false); Blocks::DB::instance()->CacheAllBlockInfos(); BOOST_CHECK(Blocks::DB::instance()->uahfForkBlock() == hashes[11]); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFActive); mapArgs["-uahfstarttime"] = "20600"; MockApplication::doInit(); Blocks::DB::createInstance(0, false); Blocks::DB::instance()->CacheAllBlockInfos(); BOOST_CHECK(Blocks::DB::instance()->uahfForkBlock() == hashes[11]); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFRulesActive); mapArgs["-uahfstarttime"] = "20601"; MockApplication::doInit(); Blocks::DB::createInstance(0, false); Blocks::DB::instance()->CacheAllBlockInfos(); BOOST_CHECK(Blocks::DB::instance()->uahfForkBlock() == hashes[11]); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFWaiting); } BOOST_AUTO_TEST_CASE(Test_BlockValidation) { std::vector<uint256> hashes; hashes.resize(21); // create 20 block-indexes. CBlockIndex *tip = Blocks::indexMap.begin()->second; for (int i = 0; i < 20; ++i) { tip = createBlockIndex(tip, i + 1, i * 100, &hashes[i]); } // Create block with block index. std::vector<CTransaction> transactions; CBlock block = createBlock(tip, transactions); uint256 hash; mapArgs["-uahfstarttime"] = "1400"; // that makes our upcoming block the first on the new chain MockApplication::doInit(); CValidationState state; bool accepted = ContextualCheckBlock(block, state, tip); BOOST_CHECK(!accepted); BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-blk-too-small"); transactions = TxUtils::transactionsForBlock(1000000); block = createBlock(tip, transactions); BOOST_CHECK(::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > 1000000); accepted = ContextualCheckBlock(block, state, tip); BOOST_CHECK(accepted); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFWaiting); // Accept it so we can create small blocks again. tip = createBlockIndex(tip, 20, 2500, &hashes[20]); // Base transaction is valid before the fork. mapArgs["-uahfstarttime"] = "2000"; MockApplication::doInit(); transactions.clear(); CMutableTransaction tx; TxUtils::RandomTransaction(tx, TxUtils::SingleOutput); transactions.push_back(tx); block = createBlock(tip, transactions); BOOST_CHECK(ContextualCheckBlock(block, state, tip)); // Base transaction is still valid after sunset. mapArgs["-uahfstarttime"] = "1400"; MockApplication::doInit(); BOOST_CHECK(ContextualCheckBlock(block, state, tip)); // Wrong commitment, still valid. tx.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_0; transactions[0] = tx; block = createBlock(tip, transactions); BOOST_CHECK(ContextualCheckBlock(block, state, tip)); const Consensus::Params &params = Params().GetConsensus(); // Anti replay commitment, not valid anymore. tx.vout[0].scriptPubKey = CScript() << OP_RETURN << params.antiReplayOpReturnCommitment; transactions[0] = tx; block = createBlock(tip, transactions); BOOST_CHECK_EQUAL(ContextualCheckBlock(block, state, tip), false); // Anti replay commitment, **At** sunset. tip->nHeight = Params().GetConsensus().antiReplayOpReturnSunsetHeight - 1; // (remember, tip is pindexPREV) BOOST_CHECK_EQUAL(ContextualCheckBlock(block, state, tip), false); // Anti replay commitment, disabled after sunset. logDebug() << "sunset" << Params().GetConsensus().antiReplayOpReturnSunsetHeight; tip->nHeight = Params().GetConsensus().antiReplayOpReturnSunsetHeight; BOOST_CHECK(ContextualCheckBlock(block, state, tip)); // Anti replay commitment, disabled before start time. mapArgs["-uahfstarttime"] = "3000"; MockApplication::doInit(); BOOST_CHECK(ContextualCheckBlock(block, state, tip)); } BOOST_AUTO_TEST_CASE(Test_isCommitment) { std::vector<unsigned char> data{}; // Empty commitment. auto s = CScript() << OP_RETURN << data; BOOST_CHECK(s.isCommitment(data)); // Commitment to a value of the wrong size. data.push_back(42); BOOST_CHECK(!s.isCommitment(data)); // Not a commitment. s = CScript() << data; BOOST_CHECK(!s.isCommitment(data)); // Non empty commitment. s = CScript() << OP_RETURN << data; BOOST_CHECK(s.isCommitment(data)); // Commitment to the wrong value. data[0] = 0x42; BOOST_CHECK(!s.isCommitment(data)); // Commitment to a larger value. std::string str = "Bitcoin: A peer-to-peer Electronic Cash System"; data = std::vector<unsigned char>(str.begin(), str.end()); BOOST_CHECK(!s.isCommitment(data)); s = CScript() << OP_RETURN << data; BOOST_CHECK(s.isCommitment(data)); // 64 bytes commitment, still valid. data.resize(64); s = CScript() << OP_RETURN << data; BOOST_CHECK(s.isCommitment(data)); // Commitment is too large. data.push_back(23); s = CScript() << OP_RETURN << data; BOOST_CHECK(!s.isCommitment(data)); // Check with the actual replay commitment we are going to use. SelectParams(CBaseChainParams::MAIN); const Consensus::Params &params = Params().GetConsensus(); s = CScript() << OP_RETURN << params.antiReplayOpReturnCommitment; BOOST_CHECK(s.isCommitment(params.antiReplayOpReturnCommitment)); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Add some comments<commit_after>/* * This file is part of the bitcoin-classic project * Copyright (C) 2017 Tom Zander <tomz@freedommail.ch> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "transaction_utils.h" #include "test/test_bitcoin.h" #include <boost/test/auto_unit_test.hpp> #include <Application.h> #include <BlocksDB.h> #include <chain.h> #include <chainparams.h> #include <primitives/transaction.h> #include <main.h> #include <consensus/validation.h> #include <vector> class MyTestingFixture : public TestingSetup { public: MyTestingFixture() : TestingSetup(CBaseChainParams::REGTEST, BlocksDbOnDisk) {} }; static CBlockIndex *createBlockIndex(CBlockIndex *prev, int height, int time, uint256 *hash) { assert(hash); CBlockIndex *index = new CBlockIndex(); index->nHeight = height; index->nTime = time; index->pprev = prev; *hash = CDiskBlockIndex(index).GetBlockHash(); index->phashBlock = hash; index->BuildSkip(); Blocks::DB::instance()->appendBlock(index, 0); Blocks::indexMap.insert(std::make_pair(*hash, index)); Blocks::DB::instance()->appendHeader(index); return index; } static CBlock createBlock(CBlockIndex *parent, const std::vector<CTransaction>& txns) { CMutableTransaction coinbase; coinbase.vin.resize(1); coinbase.vout.resize(1); coinbase.vin[0].scriptSig = CScript() << (parent->nHeight + 1) << OP_0; coinbase.vout[0].nValue = 50 * COIN; CBlock block; block.vtx.push_back(coinbase); block.nVersion = 4; block.hashPrevBlock = *parent->phashBlock; block.nTime = parent->GetMedianTimePast() + 20; block.nBits = 0x207fffff; block.nNonce = 0; block.vtx.reserve(txns.size() + 1); for (const CTransaction &tx : txns) { block.vtx.push_back(tx); } return block; } BOOST_FIXTURE_TEST_SUITE(UAHF, MyTestingFixture) BOOST_AUTO_TEST_CASE(Test_Enabling) { mapArgs["-uahfstarttime"] = "0"; MockApplication::doInit(); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFDisabled); BOOST_CHECK_EQUAL(Application::uahfStartTime(), 0); mapArgs["-uahfstarttime"] = "-1"; MockApplication::doInit(); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFDisabled); BOOST_CHECK_EQUAL(Application::uahfStartTime(), 0); mapArgs["-uahfstarttime"] = "1"; MockApplication::doInit(); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFWaiting); BOOST_CHECK_EQUAL(Application::uahfStartTime(), 1); mapArgs["-uahfstarttime"] = "12352"; MockApplication::doInit(); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFWaiting); BOOST_CHECK_EQUAL(Application::uahfStartTime(), 12352); BOOST_CHECK(Blocks::DB::instance()->uahfForkBlock() == uint256()); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFWaiting); // we use the MTP, which uses 11 blocks, so make sure we actually have those // and they say exactly what we want them to say. std::vector<uint256> hashes; hashes.resize(12); // create 20 block-indexes. CBlockIndex *tip = Blocks::indexMap.begin()->second; for (int i = 0; i < 12; ++i) { tip = createBlockIndex(tip, i + 1, 20000 + i * 100, &hashes[i]); } chainActive.SetTip(tip); // tip GMTP is 20600, the one before 20500 Blocks::DB::instance()->setUahfForkBlock(hashes[11]); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFActive); mapArgs["-uahfstarttime"] = "0"; MockApplication::doInit(); Blocks::DB::createInstance(0, false); BOOST_CHECK(Blocks::DB::instance()->uahfForkBlock() == uint256()); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFDisabled); mapArgs["-uahfstarttime"] = "12352"; MockApplication::doInit(); Blocks::DB::createInstance(0, false); Blocks::DB::instance()->CacheAllBlockInfos(); BOOST_CHECK(Blocks::DB::instance()->uahfForkBlock() == hashes[11]); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFActive); /* UAHF spec states; * "activation time": once the MTP of the chain tip is equal to or greater * than this time, the next block must be a valid fork block. The fork block * and subsequent blocks built on it must satisfy the new consensus rules. * * "fork block": the first block built on top of a chain tip whose MTP is * greater than or equal to the activation time. */ // Defining UAHF starts at 20500 means the tip (being 20600) is our fork-block. mapArgs["-uahfstarttime"] = "20500"; MockApplication::doInit(); Blocks::DB::createInstance(0, false); Blocks::DB::instance()->CacheAllBlockInfos(); BOOST_CHECK(Blocks::DB::instance()->uahfForkBlock() == hashes[11]); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFActive); // Defining UAHF starts at 20600 means the tip is the last one before the fork block. mapArgs["-uahfstarttime"] = "20600"; MockApplication::doInit(); Blocks::DB::createInstance(0, false); Blocks::DB::instance()->CacheAllBlockInfos(); BOOST_CHECK(Blocks::DB::instance()->uahfForkBlock() == hashes[11]); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFRulesActive); // Check for off-by-one sec mapArgs["-uahfstarttime"] = "20601"; MockApplication::doInit(); Blocks::DB::createInstance(0, false); Blocks::DB::instance()->CacheAllBlockInfos(); BOOST_CHECK(Blocks::DB::instance()->uahfForkBlock() == hashes[11]); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFWaiting); } BOOST_AUTO_TEST_CASE(Test_BlockValidation) { std::vector<uint256> hashes; hashes.resize(21); // create 20 block-indexes. CBlockIndex *tip = Blocks::indexMap.begin()->second; for (int i = 0; i < 20; ++i) { tip = createBlockIndex(tip, i + 1, i * 100, &hashes[i]); } // Create block with block index. std::vector<CTransaction> transactions; CBlock block = createBlock(tip, transactions); uint256 hash; mapArgs["-uahfstarttime"] = "1400"; // that makes our upcoming block the first on the new chain MockApplication::doInit(); CValidationState state; bool accepted = ContextualCheckBlock(block, state, tip); BOOST_CHECK(!accepted); BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-blk-too-small"); transactions = TxUtils::transactionsForBlock(1000000); block = createBlock(tip, transactions); BOOST_CHECK(::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > 1000000); accepted = ContextualCheckBlock(block, state, tip); BOOST_CHECK(accepted); BOOST_CHECK_EQUAL(Application::uahfChainState(), Application::UAHFWaiting); // Accept it so we can create small blocks again. tip = createBlockIndex(tip, 20, 2500, &hashes[20]); // Base transaction is valid before the fork. mapArgs["-uahfstarttime"] = "2000"; MockApplication::doInit(); transactions.clear(); CMutableTransaction tx; TxUtils::RandomTransaction(tx, TxUtils::SingleOutput); transactions.push_back(tx); block = createBlock(tip, transactions); BOOST_CHECK(ContextualCheckBlock(block, state, tip)); // Base transaction is still valid after sunset. mapArgs["-uahfstarttime"] = "1400"; MockApplication::doInit(); BOOST_CHECK(ContextualCheckBlock(block, state, tip)); // Wrong commitment, still valid. tx.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_0; transactions[0] = tx; block = createBlock(tip, transactions); BOOST_CHECK(ContextualCheckBlock(block, state, tip)); const Consensus::Params &params = Params().GetConsensus(); // Anti replay commitment, not valid anymore. tx.vout[0].scriptPubKey = CScript() << OP_RETURN << params.antiReplayOpReturnCommitment; transactions[0] = tx; block = createBlock(tip, transactions); BOOST_CHECK_EQUAL(ContextualCheckBlock(block, state, tip), false); // Anti replay commitment, **At** sunset. tip->nHeight = Params().GetConsensus().antiReplayOpReturnSunsetHeight - 1; // (remember, tip is pindexPREV) BOOST_CHECK_EQUAL(ContextualCheckBlock(block, state, tip), false); // Anti replay commitment, disabled after sunset. logDebug() << "sunset" << Params().GetConsensus().antiReplayOpReturnSunsetHeight; tip->nHeight = Params().GetConsensus().antiReplayOpReturnSunsetHeight; BOOST_CHECK(ContextualCheckBlock(block, state, tip)); // Anti replay commitment, disabled before start time. mapArgs["-uahfstarttime"] = "3000"; MockApplication::doInit(); BOOST_CHECK(ContextualCheckBlock(block, state, tip)); } BOOST_AUTO_TEST_CASE(Test_isCommitment) { std::vector<unsigned char> data{}; // Empty commitment. auto s = CScript() << OP_RETURN << data; BOOST_CHECK(s.isCommitment(data)); // Commitment to a value of the wrong size. data.push_back(42); BOOST_CHECK(!s.isCommitment(data)); // Not a commitment. s = CScript() << data; BOOST_CHECK(!s.isCommitment(data)); // Non empty commitment. s = CScript() << OP_RETURN << data; BOOST_CHECK(s.isCommitment(data)); // Commitment to the wrong value. data[0] = 0x42; BOOST_CHECK(!s.isCommitment(data)); // Commitment to a larger value. std::string str = "Bitcoin: A peer-to-peer Electronic Cash System"; data = std::vector<unsigned char>(str.begin(), str.end()); BOOST_CHECK(!s.isCommitment(data)); s = CScript() << OP_RETURN << data; BOOST_CHECK(s.isCommitment(data)); // 64 bytes commitment, still valid. data.resize(64); s = CScript() << OP_RETURN << data; BOOST_CHECK(s.isCommitment(data)); // Commitment is too large. data.push_back(23); s = CScript() << OP_RETURN << data; BOOST_CHECK(!s.isCommitment(data)); // Check with the actual replay commitment we are going to use. SelectParams(CBaseChainParams::MAIN); const Consensus::Params &params = Params().GetConsensus(); s = CScript() << OP_RETURN << params.antiReplayOpReturnCommitment; BOOST_CHECK(s.isCommitment(params.antiReplayOpReturnCommitment)); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* * (C) 2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "tests.h" #if defined(BOTAN_HAS_ASN1) #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/asn1_print.h> #endif namespace Botan_Tests { #if defined(BOTAN_HAS_ASN1) namespace { Test::Result test_ber_stack_recursion() { Test::Result result("BER stack recursion"); // OSS-Fuzz #813 GitHub #989 try { const std::vector<uint8_t> in(10000000, 0); Botan::DataSource_Memory input(in.data(), in.size()); Botan::BER_Decoder dec(input); while(dec.more_items()) { Botan::BER_Object obj; dec.get_next(obj); } } catch(Botan::Decoding_Error&) { } result.test_success("No crash"); return result; } Test::Result test_ber_eoc_decoding_limits() { Test::Result result("BER nested indefinite length"); // OSS-Fuzz #4353 Botan::ASN1_Pretty_Printer printer; size_t max_eoc_allowed = 0; for(size_t len = 1; len < 1024; ++len) { std::vector<uint8_t> buf(4*len); /* This constructs a len deep sequence of SEQUENCES each with an indefinite length */ for(size_t i = 0; i != 2*len; i += 2) { buf[i ] = 0x30; buf[i+1] = 0x80; } // remainder of values left as zeros (EOC markers) try { printer.print(buf); } catch(Botan::BER_Decoding_Error&) { max_eoc_allowed = len - 1; break; } } result.test_eq("EOC limited to prevent stack exhaustion", max_eoc_allowed, 16); return result; } Test::Result test_asn1_utf8_ascii_parsing() { Test::Result result("ASN.1 ASCII parsing"); try { // \x13 - ASN1 tag for 'printable string' // \x06 - 6 characters of payload // ... - UTF-8 encoded (ASCII chars only) word 'Moscow' const std::string moscow = "\x13\x06\x4D\x6F\x73\x63\x6F\x77"; const std::string moscow_plain = "Moscow"; Botan::DataSource_Memory input(moscow.data()); Botan::BER_Decoder dec(input); Botan::ASN1_String str; str.decode_from(dec); result.test_eq("value()", str.value(), moscow_plain); } catch(const Botan::Decoding_Error &ex) { result.test_failure(ex.what()); } return result; } Test::Result test_asn1_utf8_parsing() { Test::Result result("ASN.1 UTF-8 parsing"); try { // \x0C - ASN1 tag for 'UTF8 string' // \x0C - 12 characters of payload // ... - UTF-8 encoded russian word for Moscow in cyrillic script const std::string moscow = "\x0C\x0C\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0"; const std::string moscow_plain = "\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0"; Botan::DataSource_Memory input(moscow.data()); Botan::BER_Decoder dec(input); Botan::ASN1_String str; str.decode_from(dec); result.test_eq("value()", str.value(), moscow_plain); } catch(const Botan::Decoding_Error &ex) { result.test_failure(ex.what()); } return result; } Test::Result test_asn1_ucs2_parsing() { Test::Result result("ASN.1 BMP string (UCS-2) parsing"); try { // \x1E - ASN1 tag for 'BMP (UCS-2) string' // \x0C - 12 characters of payload // ... - UCS-2 encoding for Moscow in cyrillic script const std::string moscow = "\x1E\x0C\x04\x1C\x04\x3E\x04\x41\x04\x3A\x04\x32\x04\x30"; const std::string moscow_plain = "\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0"; Botan::DataSource_Memory input(moscow.data()); Botan::BER_Decoder dec(input); Botan::ASN1_String str; str.decode_from(dec); result.test_eq("value()", str.value(), moscow_plain); } catch(const Botan::Decoding_Error &ex) { result.test_failure(ex.what()); } return result; } Test::Result test_asn1_ucs4_parsing() { Test::Result result("ASN.1 universal string (UCS-4) parsing"); try { // \x1C - ASN1 tag for 'universal string' // \x18 - 24 characters of payload // ... - UCS-4 encoding for Moscow in cyrillic script const Botan::byte moscow[] = "\x1C\x18\x00\x00\x04\x1C\x00\x00\x04\x3E\x00\x00\x04\x41\x00\x00\x04\x3A\x00\x00\x04\x32\x00\x00\x04\x30"; const std::string moscow_plain = "\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0"; Botan::DataSource_Memory input(moscow, sizeof(moscow)); Botan::BER_Decoder dec(input); Botan::ASN1_String str; str.decode_from(dec); result.test_eq("value()", str.value(), moscow_plain); } catch(const Botan::Decoding_Error &ex) { result.test_failure(ex.what()); } return result; } Test::Result test_asn1_ascii_encoding() { Test::Result result("ASN.1 ASCII encoding"); try { // UTF-8 encoded (ASCII chars only) word 'Moscow' const std::string moscow = "\x4D\x6F\x73\x63\x6F\x77"; Botan::ASN1_String str(moscow); Botan::DER_Encoder enc; str.encode_into(enc); auto encodingResult = enc.get_contents(); // \x13 - ASN1 tag for 'printable string' // \x06 - 6 characters of payload const auto moscowEncoded = Botan::hex_decode("13064D6F73636F77"); result.test_eq("encoding result", encodingResult, moscowEncoded); result.test_success("No crash"); } catch(const std::exception &ex) { result.test_failure(ex.what()); } return result; } Test::Result test_asn1_utf8_encoding() { Test::Result result("ASN.1 UTF-8 encoding"); try { // UTF-8 encoded russian word for Moscow in cyrillic script const std::string moscow = "\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0"; Botan::ASN1_String str(moscow); Botan::DER_Encoder enc; str.encode_into(enc); auto encodingResult = enc.get_contents(); // \x0C - ASN1 tag for 'UTF8 string' // \x0C - 12 characters of payload const auto moscowEncoded = Botan::hex_decode("0C0CD09CD0BED181D0BAD0B2D0B0"); result.test_eq("encoding result", encodingResult, moscowEncoded); result.test_success("No crash"); } catch(const std::exception &ex) { result.test_failure(ex.what()); } return result; } } class ASN1_Tests final : public Test { public: std::vector<Test::Result> run() override { std::vector<Test::Result> results; results.push_back(test_ber_stack_recursion()); results.push_back(test_ber_eoc_decoding_limits()); results.push_back(test_asn1_utf8_ascii_parsing()); results.push_back(test_asn1_utf8_parsing()); results.push_back(test_asn1_ucs2_parsing()); results.push_back(test_asn1_ucs4_parsing()); results.push_back(test_asn1_ascii_encoding()); results.push_back(test_asn1_utf8_encoding()); return results; } }; BOTAN_REGISTER_TEST("asn1", "asn1", ASN1_Tests); class ASN1_Time_Parsing_Tests final : public Text_Based_Test { public: ASN1_Time_Parsing_Tests() : Text_Based_Test("asn1_time.vec", "Tspec") {} Test::Result run_one_test(const std::string& tag_str, const VarMap& vars) override { Test::Result result("ASN.1 date parsing"); const std::string tspec = vars.get_req_str("Tspec"); if(tag_str != "UTC" && tag_str != "UTC.invalid" && tag_str != "Generalized" && tag_str != "Generalized.invalid") { throw Test_Error("Invalid tag value in ASN1 date parsing test"); } const Botan::ASN1_Type tag = (tag_str == "UTC" || tag_str == "UTC.invalid") ? Botan::ASN1_Type::UTC_TIME : Botan::ASN1_Type::GENERALIZED_TIME; const bool valid = tag_str.find(".invalid") == std::string::npos; if(valid) { Botan::ASN1_Time time(tspec, tag); result.test_success("Accepted valid time"); } else { result.test_throws("Invalid time rejected", [=]() { Botan::ASN1_Time time(tspec, tag); }); } return result; } }; BOTAN_REGISTER_TEST("asn1", "asn1_time", ASN1_Time_Parsing_Tests); class ASN1_Printer_Tests final : public Test { public: std::vector<Test::Result> run() override { Test::Result result("ASN1_Pretty_Printer"); Botan::ASN1_Pretty_Printer printer; const size_t num_tests = 6; for(size_t i = 1; i <= num_tests; ++i) { std::string i_str = std::to_string(i); const std::vector<uint8_t> input1 = Test::read_binary_data_file("asn1_print/input" + i_str + ".der"); const std::string expected1 = Test::read_data_file("asn1_print/output" + i_str + ".txt"); result.test_eq("Test " + i_str, printer.print(input1), expected1); } return {result}; } }; BOTAN_REGISTER_TEST("asn1", "asn1_printer", ASN1_Printer_Tests); #endif } <commit_msg>Test ASN.1 class/type underlying types<commit_after>/* * (C) 2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "tests.h" #if defined(BOTAN_HAS_ASN1) #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/asn1_print.h> #endif namespace Botan_Tests { #if defined(BOTAN_HAS_ASN1) namespace { Test::Result test_ber_stack_recursion() { Test::Result result("BER stack recursion"); // OSS-Fuzz #813 GitHub #989 try { const std::vector<uint8_t> in(10000000, 0); Botan::DataSource_Memory input(in.data(), in.size()); Botan::BER_Decoder dec(input); while(dec.more_items()) { Botan::BER_Object obj; dec.get_next(obj); } } catch(Botan::Decoding_Error&) { } result.test_success("No crash"); return result; } Test::Result test_ber_eoc_decoding_limits() { Test::Result result("BER nested indefinite length"); // OSS-Fuzz #4353 Botan::ASN1_Pretty_Printer printer; size_t max_eoc_allowed = 0; for(size_t len = 1; len < 1024; ++len) { std::vector<uint8_t> buf(4*len); /* This constructs a len deep sequence of SEQUENCES each with an indefinite length */ for(size_t i = 0; i != 2*len; i += 2) { buf[i ] = 0x30; buf[i+1] = 0x80; } // remainder of values left as zeros (EOC markers) try { printer.print(buf); } catch(Botan::BER_Decoding_Error&) { max_eoc_allowed = len - 1; break; } } result.test_eq("EOC limited to prevent stack exhaustion", max_eoc_allowed, 16); return result; } Test::Result test_asn1_utf8_ascii_parsing() { Test::Result result("ASN.1 ASCII parsing"); try { // \x13 - ASN1 tag for 'printable string' // \x06 - 6 characters of payload // ... - UTF-8 encoded (ASCII chars only) word 'Moscow' const std::string moscow = "\x13\x06\x4D\x6F\x73\x63\x6F\x77"; const std::string moscow_plain = "Moscow"; Botan::DataSource_Memory input(moscow.data()); Botan::BER_Decoder dec(input); Botan::ASN1_String str; str.decode_from(dec); result.test_eq("value()", str.value(), moscow_plain); } catch(const Botan::Decoding_Error &ex) { result.test_failure(ex.what()); } return result; } Test::Result test_asn1_utf8_parsing() { Test::Result result("ASN.1 UTF-8 parsing"); try { // \x0C - ASN1 tag for 'UTF8 string' // \x0C - 12 characters of payload // ... - UTF-8 encoded russian word for Moscow in cyrillic script const std::string moscow = "\x0C\x0C\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0"; const std::string moscow_plain = "\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0"; Botan::DataSource_Memory input(moscow.data()); Botan::BER_Decoder dec(input); Botan::ASN1_String str; str.decode_from(dec); result.test_eq("value()", str.value(), moscow_plain); } catch(const Botan::Decoding_Error &ex) { result.test_failure(ex.what()); } return result; } Test::Result test_asn1_ucs2_parsing() { Test::Result result("ASN.1 BMP string (UCS-2) parsing"); try { // \x1E - ASN1 tag for 'BMP (UCS-2) string' // \x0C - 12 characters of payload // ... - UCS-2 encoding for Moscow in cyrillic script const std::string moscow = "\x1E\x0C\x04\x1C\x04\x3E\x04\x41\x04\x3A\x04\x32\x04\x30"; const std::string moscow_plain = "\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0"; Botan::DataSource_Memory input(moscow.data()); Botan::BER_Decoder dec(input); Botan::ASN1_String str; str.decode_from(dec); result.test_eq("value()", str.value(), moscow_plain); } catch(const Botan::Decoding_Error &ex) { result.test_failure(ex.what()); } return result; } Test::Result test_asn1_ucs4_parsing() { Test::Result result("ASN.1 universal string (UCS-4) parsing"); try { // \x1C - ASN1 tag for 'universal string' // \x18 - 24 characters of payload // ... - UCS-4 encoding for Moscow in cyrillic script const Botan::byte moscow[] = "\x1C\x18\x00\x00\x04\x1C\x00\x00\x04\x3E\x00\x00\x04\x41\x00\x00\x04\x3A\x00\x00\x04\x32\x00\x00\x04\x30"; const std::string moscow_plain = "\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0"; Botan::DataSource_Memory input(moscow, sizeof(moscow)); Botan::BER_Decoder dec(input); Botan::ASN1_String str; str.decode_from(dec); result.test_eq("value()", str.value(), moscow_plain); } catch(const Botan::Decoding_Error &ex) { result.test_failure(ex.what()); } return result; } Test::Result test_asn1_ascii_encoding() { Test::Result result("ASN.1 ASCII encoding"); try { // UTF-8 encoded (ASCII chars only) word 'Moscow' const std::string moscow = "\x4D\x6F\x73\x63\x6F\x77"; Botan::ASN1_String str(moscow); Botan::DER_Encoder enc; str.encode_into(enc); auto encodingResult = enc.get_contents(); // \x13 - ASN1 tag for 'printable string' // \x06 - 6 characters of payload const auto moscowEncoded = Botan::hex_decode("13064D6F73636F77"); result.test_eq("encoding result", encodingResult, moscowEncoded); result.test_success("No crash"); } catch(const std::exception &ex) { result.test_failure(ex.what()); } return result; } Test::Result test_asn1_utf8_encoding() { Test::Result result("ASN.1 UTF-8 encoding"); try { // UTF-8 encoded russian word for Moscow in cyrillic script const std::string moscow = "\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0"; Botan::ASN1_String str(moscow); Botan::DER_Encoder enc; str.encode_into(enc); auto encodingResult = enc.get_contents(); // \x0C - ASN1 tag for 'UTF8 string' // \x0C - 12 characters of payload const auto moscowEncoded = Botan::hex_decode("0C0CD09CD0BED181D0BAD0B2D0B0"); result.test_eq("encoding result", encodingResult, moscowEncoded); result.test_success("No crash"); } catch(const std::exception &ex) { result.test_failure(ex.what()); } return result; } Test::Result test_asn1_tag_underlying_type() { Test::Result result("ASN.1 class and type underlying type"); if constexpr(std::is_same_v<std::underlying_type_t<Botan::ASN1_Class>, std::underlying_type_t<Botan::ASN1_Type>>) { if constexpr(!std::is_same_v<std::underlying_type_t<Botan::ASN1_Class>, std::invoke_result_t<decltype(&Botan::BER_Object::tagging), Botan::BER_Object>>) { result.test_failure("Return type of BER_Object::tagging() is different than the underlying type of ASN1_Class"); } else { result.test_success("Same types"); } } else { result.test_failure("ASN1_Class and ASN1_Type have different underlying types"); } return result; } } class ASN1_Tests final : public Test { public: std::vector<Test::Result> run() override { std::vector<Test::Result> results; results.push_back(test_ber_stack_recursion()); results.push_back(test_ber_eoc_decoding_limits()); results.push_back(test_asn1_utf8_ascii_parsing()); results.push_back(test_asn1_utf8_parsing()); results.push_back(test_asn1_ucs2_parsing()); results.push_back(test_asn1_ucs4_parsing()); results.push_back(test_asn1_ascii_encoding()); results.push_back(test_asn1_utf8_encoding()); results.push_back(test_asn1_tag_underlying_type()); return results; } }; BOTAN_REGISTER_TEST("asn1", "asn1", ASN1_Tests); class ASN1_Time_Parsing_Tests final : public Text_Based_Test { public: ASN1_Time_Parsing_Tests() : Text_Based_Test("asn1_time.vec", "Tspec") {} Test::Result run_one_test(const std::string& tag_str, const VarMap& vars) override { Test::Result result("ASN.1 date parsing"); const std::string tspec = vars.get_req_str("Tspec"); if(tag_str != "UTC" && tag_str != "UTC.invalid" && tag_str != "Generalized" && tag_str != "Generalized.invalid") { throw Test_Error("Invalid tag value in ASN1 date parsing test"); } const Botan::ASN1_Type tag = (tag_str == "UTC" || tag_str == "UTC.invalid") ? Botan::ASN1_Type::UTC_TIME : Botan::ASN1_Type::GENERALIZED_TIME; const bool valid = tag_str.find(".invalid") == std::string::npos; if(valid) { Botan::ASN1_Time time(tspec, tag); result.test_success("Accepted valid time"); } else { result.test_throws("Invalid time rejected", [=]() { Botan::ASN1_Time time(tspec, tag); }); } return result; } }; BOTAN_REGISTER_TEST("asn1", "asn1_time", ASN1_Time_Parsing_Tests); class ASN1_Printer_Tests final : public Test { public: std::vector<Test::Result> run() override { Test::Result result("ASN1_Pretty_Printer"); Botan::ASN1_Pretty_Printer printer; const size_t num_tests = 6; for(size_t i = 1; i <= num_tests; ++i) { std::string i_str = std::to_string(i); const std::vector<uint8_t> input1 = Test::read_binary_data_file("asn1_print/input" + i_str + ".der"); const std::string expected1 = Test::read_data_file("asn1_print/output" + i_str + ".txt"); result.test_eq("Test " + i_str, printer.print(input1), expected1); } return {result}; } }; BOTAN_REGISTER_TEST("asn1", "asn1_printer", ASN1_Printer_Tests); #endif } <|endoftext|>
<commit_before>#include "thread_renderer.h" #include "audio_nodes.h" #include "recorder_node.h" namespace cieq { ThreadRenderer::ThreadRenderer(AudioNodes& nodes, int frames_per_unit, int fft_size, int viewable_frames) : mViewableFrames(viewable_frames) { int num_blocks = (nodes.getBufferRecorderNode()->getNumFrames() / frames_per_unit) + 1; mSurfacePool.resize(num_blocks); mTexturePool.resize(num_blocks); for (auto index = 0; index < num_blocks; ++index) { mSurfacePool.push_back(std::make_unique<SpectralSurface>(frames_per_unit, fft_size)); mTexturePool.push_back(ci::gl::Texture::create(*mSurfacePool.back())); } mFramebuffer = ci::gl::Fbo(viewable_frames, fft_size); } void ThreadRenderer::update() { auto index = 0; for (SpectralSurfaceRef& surface : mSurfacePool) { if (*surface && surface->allRowsTouched()) { mTexturePool[index]->update(*surface); surface->reset(); } ++index; } } void ThreadRenderer::draw() { auto index = 0; ci::gl::SaveFramebufferBinding _bindings; //! draw everything to a frame buffer mFramebuffer.bindFramebuffer(); for (SpectralSurfaceRef& surface : mSurfacePool) { if (*surface) { //draw surface here. } else { //draw mTexturePool[index] here. } ++index; } mFramebuffer.unbindFramebuffer(); } SpectralSurface& ThreadRenderer::getSurface(int index) { return *(mSurfacePool[index]); } ci::gl::Texture& ThreadRenderer::getTexture(int index) { return *mTexturePool[index].get(); } } //!cieq<commit_msg>Changed thread_renderer's ctor logic<commit_after>#include "thread_renderer.h" #include "audio_nodes.h" #include "recorder_node.h" namespace cieq { ThreadRenderer::ThreadRenderer(AudioNodes& nodes, int frames_per_unit, int fft_size, int viewable_frames) : mViewableFrames(viewable_frames) { // num_blocks * (hopSize + windowSize) >= numFrames: int num_processings = (nodes.getBufferRecorderNode()->getNumFrames() / (nodes.getBufferRecorderNode()->getWindowSize() + nodes.getBufferRecorderNode()->getHopSize())); int num_blocks = num_processings / frames_per_unit + 1; for (auto index = 0; index < num_blocks; ++index) { mSurfacePool.push_back(std::make_unique<SpectralSurface>(frames_per_unit, fft_size)); mTexturePool.push_back(ci::gl::Texture::create(*mSurfacePool.back())); } mFramebuffer = ci::gl::Fbo(viewable_frames, fft_size); } void ThreadRenderer::update() { auto index = 0; for (SpectralSurfaceRef& surface : mSurfacePool) { if (*surface && surface->allRowsTouched()) { mTexturePool[index]->update(*surface); surface->reset(); } ++index; } } void ThreadRenderer::draw() { auto index = 0; ci::gl::SaveFramebufferBinding _bindings; //! draw everything to a frame buffer mFramebuffer.bindFramebuffer(); for (SpectralSurfaceRef& surface : mSurfacePool) { if (*surface) { //draw surface here. } else { //draw mTexturePool[index] here. } ++index; } mFramebuffer.unbindFramebuffer(); } SpectralSurface& ThreadRenderer::getSurface(int index) { return *(mSurfacePool[index]); } ci::gl::Texture& ThreadRenderer::getTexture(int index) { return *mTexturePool[index].get(); } } //!cieq<|endoftext|>
<commit_before>// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // // Code that is used by both the Unix corerun and coreconsole. // #include <cstdlib> #include <assert.h> #include <dirent.h> #include <dlfcn.h> #include <limits.h> #include <set> #include <string> #include <string.h> #include <sys/stat.h> // The name of the CoreCLR native runtime DLL #if defined(__APPLE__) static const char * const coreClrDll = "libcoreclr.dylib"; #else static const char * const coreClrDll = "libcoreclr.so"; #endif // Windows types used by the ExecuteAssembly function typedef unsigned int DWORD; typedef const char16_t* LPCWSTR; typedef const char* LPCSTR; typedef int32_t HRESULT; #define SUCCEEDED(Status) ((HRESULT)(Status) >= 0) // Prototype of the ExecuteAssembly function from the libcoreclr.do typedef HRESULT (*ExecuteAssemblyFunction)( LPCSTR exePath, LPCSTR coreClrPath, LPCSTR appDomainFriendlyName, int propertyCount, LPCSTR* propertyKeys, LPCSTR* propertyValues, int argc, LPCSTR* argv, LPCSTR managedAssemblyPath, LPCSTR entryPointAssemblyName, LPCSTR entryPointTypeName, LPCSTR entryPointMethodsName, DWORD* exitCode); bool GetAbsolutePath(const char* path, std::string& absolutePath) { bool result = false; char realPath[PATH_MAX]; if (realpath(path, realPath) != nullptr && realPath[0] != '\0') { absolutePath.assign(realPath); // realpath should return canonicalized path without the trailing slash assert(absolutePath.back() != '/'); result = true; } return result; } bool GetDirectory(const char* absolutePath, std::string& directory) { directory.assign(absolutePath); size_t lastSlash = directory.rfind('/'); if (lastSlash != std::string::npos) { directory.erase(lastSlash); return true; } return false; } bool GetClrFilesAbsolutePath(const char* currentExePath, const char* clrFilesPath, std::string& clrFilesAbsolutePath) { std::string clrFilesRelativePath; const char* clrFilesPathLocal = clrFilesPath; if (clrFilesPathLocal == nullptr) { // There was no CLR files path specified, use the folder of the corerun/coreconsole if (!GetDirectory(currentExePath, clrFilesRelativePath)) { perror("Failed to get directory from argv[0]"); return false; } clrFilesPathLocal = clrFilesRelativePath.c_str(); // TODO: consider using an env variable (if defined) as a fall-back. // The windows version of the corerun uses core_root env variable } if (!GetAbsolutePath(clrFilesPathLocal, clrFilesAbsolutePath)) { perror("Failed to convert CLR files path to absolute path"); return false; } return true; } void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList) { const char * const tpaExtensions[] = { ".ni.dll", // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir ".dll", ".ni.exe", ".exe", }; DIR* dir = opendir(directory); if (dir == nullptr) { return; } std::set<std::string> addedAssemblies; // Walk the directory for each extension separately so that we first get files with .ni.dll extension, // then files with .dll extension, etc. for (int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++) { const char* ext = tpaExtensions[extIndex]; int extLength = strlen(ext); struct dirent* entry; // For all entries in the directory while ((entry = readdir(dir)) != nullptr) { // We are interested in files only switch (entry->d_type) { case DT_REG: break; // Handle symlinks and file systems that do not support d_type case DT_LNK: case DT_UNKNOWN: { std::string fullFilename; fullFilename.append(directory); fullFilename.append("/"); fullFilename.append(entry->d_name); struct stat sb; if (stat(fullFilename.c_str(), &sb) == -1) { continue; } if (!S_ISREG(sb.st_mode)) { continue; } } break; default: continue; } std::string filename(entry->d_name); // Check if the extension matches the one we are looking for int extPos = filename.length() - extLength; if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0)) { continue; } std::string filenameWithoutExt(filename.substr(0, extPos)); // Make sure if we have an assembly with multiple extensions present, // we insert only one version of it. if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end()) { addedAssemblies.insert(filenameWithoutExt); tpaList.append(directory); tpaList.append("/"); tpaList.append(filename); tpaList.append(":"); } } // Rewind the directory stream to be able to iterate over it for the next extension rewinddir(dir); } closedir(dir); } int ExecuteManagedAssembly( const char* currentExeAbsolutePath, const char* clrFilesAbsolutePath, const char* managedAssemblyAbsolutePath, int managedAssemblyArgc, const char** managedAssemblyArgv) { // Indicates failure int exitCode = -1; std::string coreClrDllPath(clrFilesAbsolutePath); coreClrDllPath.append("/"); coreClrDllPath.append(coreClrDll); if (coreClrDllPath.length() >= PATH_MAX) { fprintf(stderr, "Absolute path to libcoreclr.so too long\n"); return -1; } // Get just the path component of the managed assembly path std::string appPath; GetDirectory(managedAssemblyAbsolutePath, appPath); std::string nativeDllSearchDirs(appPath); nativeDllSearchDirs.append(":"); nativeDllSearchDirs.append(clrFilesAbsolutePath); std::string tpaList; AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList); void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL); if (coreclrLib != nullptr) { ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, "ExecuteAssembly"); if (executeAssembly != nullptr) { // Allowed property names: // APPBASE // - The base path of the application from which the exe and other assemblies will be loaded // // TRUSTED_PLATFORM_ASSEMBLIES // - The list of complete paths to each of the fully trusted assemblies // // APP_PATHS // - The list of paths which will be probed by the assembly loader // // APP_NI_PATHS // - The list of additional paths that the assembly loader will probe for ngen images // // NATIVE_DLL_SEARCH_DIRECTORIES // - The list of paths that will be probed for native DLLs called by PInvoke // const char *propertyKeys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "AppDomainCompatSwitch" }; const char *propertyValues[] = { // TRUSTED_PLATFORM_ASSEMBLIES tpaList.c_str(), // APP_PATHS appPath.c_str(), // APP_NI_PATHS appPath.c_str(), // NATIVE_DLL_SEARCH_DIRECTORIES nativeDllSearchDirs.c_str(), // AppDomainCompatSwitch "UseLatestBehaviorWhenTFMNotSpecified" }; HRESULT st = executeAssembly( currentExeAbsolutePath, coreClrDllPath.c_str(), "unixcorerun", sizeof(propertyKeys) / sizeof(propertyKeys[0]), propertyKeys, propertyValues, managedAssemblyArgc, managedAssemblyArgv, managedAssemblyAbsolutePath, NULL, NULL, NULL, (DWORD*)&exitCode); if (!SUCCEEDED(st)) { fprintf(stderr, "ExecuteAssembly failed - status: 0x%08x\n", st); } } else { fprintf(stderr, "Function ExecuteAssembly not found in the libcoreclr.so\n"); } if (dlclose(coreclrLib) != 0) { fprintf(stderr, "Warning - dlclose failed\n"); } } else { char* error = dlerror(); fprintf(stderr, "dlopen failed to open the libcoreclr.so with error %s\n", error); } return exitCode; } <commit_msg>Fix exitCode from ExecuteAssembly<commit_after>// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // // Code that is used by both the Unix corerun and coreconsole. // #include <cstdlib> #include <assert.h> #include <dirent.h> #include <dlfcn.h> #include <limits.h> #include <set> #include <string> #include <string.h> #include <sys/stat.h> // The name of the CoreCLR native runtime DLL #if defined(__APPLE__) static const char * const coreClrDll = "libcoreclr.dylib"; #else static const char * const coreClrDll = "libcoreclr.so"; #endif // Windows types used by the ExecuteAssembly function typedef unsigned int DWORD; typedef const char16_t* LPCWSTR; typedef const char* LPCSTR; typedef int32_t HRESULT; #define SUCCEEDED(Status) ((HRESULT)(Status) >= 0) // Prototype of the ExecuteAssembly function from the libcoreclr.do typedef HRESULT (*ExecuteAssemblyFunction)( LPCSTR exePath, LPCSTR coreClrPath, LPCSTR appDomainFriendlyName, int propertyCount, LPCSTR* propertyKeys, LPCSTR* propertyValues, int argc, LPCSTR* argv, LPCSTR managedAssemblyPath, LPCSTR entryPointAssemblyName, LPCSTR entryPointTypeName, LPCSTR entryPointMethodsName, DWORD* exitCode); bool GetAbsolutePath(const char* path, std::string& absolutePath) { bool result = false; char realPath[PATH_MAX]; if (realpath(path, realPath) != nullptr && realPath[0] != '\0') { absolutePath.assign(realPath); // realpath should return canonicalized path without the trailing slash assert(absolutePath.back() != '/'); result = true; } return result; } bool GetDirectory(const char* absolutePath, std::string& directory) { directory.assign(absolutePath); size_t lastSlash = directory.rfind('/'); if (lastSlash != std::string::npos) { directory.erase(lastSlash); return true; } return false; } bool GetClrFilesAbsolutePath(const char* currentExePath, const char* clrFilesPath, std::string& clrFilesAbsolutePath) { std::string clrFilesRelativePath; const char* clrFilesPathLocal = clrFilesPath; if (clrFilesPathLocal == nullptr) { // There was no CLR files path specified, use the folder of the corerun/coreconsole if (!GetDirectory(currentExePath, clrFilesRelativePath)) { perror("Failed to get directory from argv[0]"); return false; } clrFilesPathLocal = clrFilesRelativePath.c_str(); // TODO: consider using an env variable (if defined) as a fall-back. // The windows version of the corerun uses core_root env variable } if (!GetAbsolutePath(clrFilesPathLocal, clrFilesAbsolutePath)) { perror("Failed to convert CLR files path to absolute path"); return false; } return true; } void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList) { const char * const tpaExtensions[] = { ".ni.dll", // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir ".dll", ".ni.exe", ".exe", }; DIR* dir = opendir(directory); if (dir == nullptr) { return; } std::set<std::string> addedAssemblies; // Walk the directory for each extension separately so that we first get files with .ni.dll extension, // then files with .dll extension, etc. for (int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++) { const char* ext = tpaExtensions[extIndex]; int extLength = strlen(ext); struct dirent* entry; // For all entries in the directory while ((entry = readdir(dir)) != nullptr) { // We are interested in files only switch (entry->d_type) { case DT_REG: break; // Handle symlinks and file systems that do not support d_type case DT_LNK: case DT_UNKNOWN: { std::string fullFilename; fullFilename.append(directory); fullFilename.append("/"); fullFilename.append(entry->d_name); struct stat sb; if (stat(fullFilename.c_str(), &sb) == -1) { continue; } if (!S_ISREG(sb.st_mode)) { continue; } } break; default: continue; } std::string filename(entry->d_name); // Check if the extension matches the one we are looking for int extPos = filename.length() - extLength; if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0)) { continue; } std::string filenameWithoutExt(filename.substr(0, extPos)); // Make sure if we have an assembly with multiple extensions present, // we insert only one version of it. if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end()) { addedAssemblies.insert(filenameWithoutExt); tpaList.append(directory); tpaList.append("/"); tpaList.append(filename); tpaList.append(":"); } } // Rewind the directory stream to be able to iterate over it for the next extension rewinddir(dir); } closedir(dir); } int ExecuteManagedAssembly( const char* currentExeAbsolutePath, const char* clrFilesAbsolutePath, const char* managedAssemblyAbsolutePath, int managedAssemblyArgc, const char** managedAssemblyArgv) { // Indicates failure int exitCode = -1; std::string coreClrDllPath(clrFilesAbsolutePath); coreClrDllPath.append("/"); coreClrDllPath.append(coreClrDll); if (coreClrDllPath.length() >= PATH_MAX) { fprintf(stderr, "Absolute path to libcoreclr.so too long\n"); return -1; } // Get just the path component of the managed assembly path std::string appPath; GetDirectory(managedAssemblyAbsolutePath, appPath); std::string nativeDllSearchDirs(appPath); nativeDllSearchDirs.append(":"); nativeDllSearchDirs.append(clrFilesAbsolutePath); std::string tpaList; AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList); void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL); if (coreclrLib != nullptr) { ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, "ExecuteAssembly"); if (executeAssembly != nullptr) { // Allowed property names: // APPBASE // - The base path of the application from which the exe and other assemblies will be loaded // // TRUSTED_PLATFORM_ASSEMBLIES // - The list of complete paths to each of the fully trusted assemblies // // APP_PATHS // - The list of paths which will be probed by the assembly loader // // APP_NI_PATHS // - The list of additional paths that the assembly loader will probe for ngen images // // NATIVE_DLL_SEARCH_DIRECTORIES // - The list of paths that will be probed for native DLLs called by PInvoke // const char *propertyKeys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "AppDomainCompatSwitch" }; const char *propertyValues[] = { // TRUSTED_PLATFORM_ASSEMBLIES tpaList.c_str(), // APP_PATHS appPath.c_str(), // APP_NI_PATHS appPath.c_str(), // NATIVE_DLL_SEARCH_DIRECTORIES nativeDllSearchDirs.c_str(), // AppDomainCompatSwitch "UseLatestBehaviorWhenTFMNotSpecified" }; HRESULT st = executeAssembly( currentExeAbsolutePath, coreClrDllPath.c_str(), "unixcorerun", sizeof(propertyKeys) / sizeof(propertyKeys[0]), propertyKeys, propertyValues, managedAssemblyArgc, managedAssemblyArgv, managedAssemblyAbsolutePath, NULL, NULL, NULL, (DWORD*)&exitCode); if (!SUCCEEDED(st)) { fprintf(stderr, "ExecuteAssembly failed - status: 0x%08x\n", st); exitCode = -1; } } else { fprintf(stderr, "Function ExecuteAssembly not found in the libcoreclr.so\n"); } if (dlclose(coreclrLib) != 0) { fprintf(stderr, "Warning - dlclose failed\n"); } } else { char* error = dlerror(); fprintf(stderr, "dlopen failed to open the libcoreclr.so with error %s\n", error); } return exitCode; } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <vector> #include <cctype> #include <boost/bind.hpp> #include "libtorrent/tracker_manager.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/aux_/session_impl.hpp" using boost::tuples::make_tuple; using boost::tuples::tuple; using boost::bind; namespace { enum { minimum_tracker_response_length = 3, http_buffer_size = 2048 }; } namespace libtorrent { timeout_handler::timeout_handler(io_service& ios) : m_start_time(time_now_hires()) , m_read_time(m_start_time) , m_timeout(ios) , m_completion_timeout(0) , m_read_timeout(0) , m_abort(false) {} void timeout_handler::set_timeout(int completion_timeout, int read_timeout) { m_completion_timeout = completion_timeout; m_read_timeout = read_timeout; m_start_time = m_read_time = time_now_hires(); if (m_abort) return; int timeout = (std::min)( m_read_timeout, (std::min)(m_completion_timeout, m_read_timeout)); error_code ec; m_timeout.expires_at(m_read_time + seconds(timeout), ec); m_timeout.async_wait(bind( &timeout_handler::timeout_callback, self(), _1)); } void timeout_handler::restart_read_timeout() { m_read_time = time_now_hires(); } void timeout_handler::cancel() { m_abort = true; m_completion_timeout = 0; error_code ec; m_timeout.cancel(ec); } void timeout_handler::timeout_callback(error_code const& error) { if (error) return; if (m_completion_timeout == 0) return; ptime now = time_now_hires(); time_duration receive_timeout = now - m_read_time; time_duration completion_timeout = now - m_start_time; if (m_read_timeout < total_seconds(receive_timeout) || m_completion_timeout < total_seconds(completion_timeout)) { on_timeout(); return; } if (m_abort) return; int timeout = (std::min)( m_read_timeout, (std::min)(m_completion_timeout, m_read_timeout)); error_code ec; m_timeout.expires_at(m_read_time + seconds(timeout), ec); m_timeout.async_wait( bind(&timeout_handler::timeout_callback, self(), _1)); } tracker_connection::tracker_connection( tracker_manager& man , tracker_request const& req , io_service& ios , boost::weak_ptr<request_callback> r) : timeout_handler(ios) , m_requester(r) , m_man(man) , m_req(req) {} boost::shared_ptr<request_callback> tracker_connection::requester() { return m_requester.lock(); } void tracker_connection::fail(error_code const& ec, int code , char const* msg, int interval, int min_interval) { boost::shared_ptr<request_callback> cb = requester(); if (cb) cb->tracker_request_error(m_req, code, ec, msg , interval == 0 ? min_interval : interval); close(); } void tracker_connection::sent_bytes(int bytes) { m_man.sent_bytes(bytes); } void tracker_connection::received_bytes(int bytes) { m_man.received_bytes(bytes); } void tracker_connection::close() { cancel(); m_man.remove_request(this); } tracker_manager::~tracker_manager() { TORRENT_ASSERT(m_abort); abort_all_requests(true); } void tracker_manager::sent_bytes(int bytes) { // mutex::scoped_lock l(m_ses.m_mutex); m_ses.m_stat.sent_tracker_bytes(bytes); } void tracker_manager::received_bytes(int bytes) { mutex::scoped_lock l(m_ses.m_mutex); m_ses.m_stat.received_tracker_bytes(bytes); } void tracker_manager::remove_request(tracker_connection const* c) { mutex_t::scoped_lock l(m_mutex); tracker_connections_t::iterator i = std::find(m_connections.begin() , m_connections.end(), boost::intrusive_ptr<const tracker_connection>(c)); if (i == m_connections.end()) return; m_connections.erase(i); } void tracker_manager::queue_request( io_service& ios , connection_queue& cc , tracker_request req , std::string const& auth , boost::weak_ptr<request_callback> c) { mutex_t::scoped_lock l(m_mutex); TORRENT_ASSERT(req.num_want >= 0); TORRENT_ASSERT(!m_abort); if (m_abort) return; if (req.event == tracker_request::stopped) req.num_want = 0; TORRENT_ASSERT(!m_abort || req.event == tracker_request::stopped); if (m_abort && req.event != tracker_request::stopped) return; std::string protocol = req.url.substr(0, req.url.find(':')); boost::intrusive_ptr<tracker_connection> con; #ifdef TORRENT_USE_OPENSSL if (protocol == "http" || protocol == "https") #else if (protocol == "http") #endif { con = new http_tracker_connection( ios, cc, *this, req, c , m_ses, m_proxy, auth #if TORRENT_USE_I2P , &m_ses.m_i2p_conn #endif ); } else if (protocol == "udp") { con = new udp_tracker_connection( ios, cc, *this, req , c, m_ses , m_proxy); } else { // we need to post the error to avoid deadlock if (boost::shared_ptr<request_callback> r = c.lock()) ios.post(boost::bind(&request_callback::tracker_request_error, r, req , -1, error_code(errors::unsupported_url_protocol) , "", 0)); return; } m_connections.push_back(con); boost::shared_ptr<request_callback> cb = con->requester(); if (cb) cb->m_manager = this; con->start(); } void tracker_manager::abort_all_requests(bool all) { // removes all connections from m_connections // except 'event=stopped'-requests mutex_t::scoped_lock l(m_mutex); m_abort = true; tracker_connections_t close_connections; for (tracker_connections_t::iterator i = m_connections.begin() , end(m_connections.end()); i != end; ++i) { intrusive_ptr<tracker_connection> c = *i; tracker_request const& req = c->tracker_req(); if (req.event == tracker_request::stopped && !all) continue; close_connections.push_back(c); #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING boost::shared_ptr<request_callback> rc = c->requester(); if (rc) rc->debug_log("aborting: " + req.url); #endif } l.unlock(); for (tracker_connections_t::iterator i = close_connections.begin() , end(close_connections.end()); i != end; ++i) { (*i)->close(); } } bool tracker_manager::empty() const { mutex_t::scoped_lock l(m_mutex); return m_connections.empty(); } int tracker_manager::num_requests() const { mutex_t::scoped_lock l(m_mutex); return m_connections.size(); } } <commit_msg>fixed tracker error report bug<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <vector> #include <cctype> #include <boost/bind.hpp> #include "libtorrent/tracker_manager.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/aux_/session_impl.hpp" using boost::tuples::make_tuple; using boost::tuples::tuple; using boost::bind; namespace { enum { minimum_tracker_response_length = 3, http_buffer_size = 2048 }; } namespace libtorrent { timeout_handler::timeout_handler(io_service& ios) : m_start_time(time_now_hires()) , m_read_time(m_start_time) , m_timeout(ios) , m_completion_timeout(0) , m_read_timeout(0) , m_abort(false) {} void timeout_handler::set_timeout(int completion_timeout, int read_timeout) { m_completion_timeout = completion_timeout; m_read_timeout = read_timeout; m_start_time = m_read_time = time_now_hires(); if (m_abort) return; int timeout = (std::min)( m_read_timeout, (std::min)(m_completion_timeout, m_read_timeout)); error_code ec; m_timeout.expires_at(m_read_time + seconds(timeout), ec); m_timeout.async_wait(bind( &timeout_handler::timeout_callback, self(), _1)); } void timeout_handler::restart_read_timeout() { m_read_time = time_now_hires(); } void timeout_handler::cancel() { m_abort = true; m_completion_timeout = 0; error_code ec; m_timeout.cancel(ec); } void timeout_handler::timeout_callback(error_code const& error) { if (error) return; if (m_completion_timeout == 0) return; ptime now = time_now_hires(); time_duration receive_timeout = now - m_read_time; time_duration completion_timeout = now - m_start_time; if (m_read_timeout < total_seconds(receive_timeout) || m_completion_timeout < total_seconds(completion_timeout)) { on_timeout(); return; } if (m_abort) return; int timeout = (std::min)( m_read_timeout, (std::min)(m_completion_timeout, m_read_timeout)); error_code ec; m_timeout.expires_at(m_read_time + seconds(timeout), ec); m_timeout.async_wait( bind(&timeout_handler::timeout_callback, self(), _1)); } tracker_connection::tracker_connection( tracker_manager& man , tracker_request const& req , io_service& ios , boost::weak_ptr<request_callback> r) : timeout_handler(ios) , m_requester(r) , m_man(man) , m_req(req) {} boost::shared_ptr<request_callback> tracker_connection::requester() { return m_requester.lock(); } void tracker_connection::fail(error_code const& ec, int code , char const* msg, int interval, int min_interval) { boost::shared_ptr<request_callback> cb = requester(); if (cb) cb->tracker_request_error(m_req, code, ec, msg ? msg : "" , interval == 0 ? min_interval : interval); close(); } void tracker_connection::sent_bytes(int bytes) { m_man.sent_bytes(bytes); } void tracker_connection::received_bytes(int bytes) { m_man.received_bytes(bytes); } void tracker_connection::close() { cancel(); m_man.remove_request(this); } tracker_manager::~tracker_manager() { TORRENT_ASSERT(m_abort); abort_all_requests(true); } void tracker_manager::sent_bytes(int bytes) { // mutex::scoped_lock l(m_ses.m_mutex); m_ses.m_stat.sent_tracker_bytes(bytes); } void tracker_manager::received_bytes(int bytes) { mutex::scoped_lock l(m_ses.m_mutex); m_ses.m_stat.received_tracker_bytes(bytes); } void tracker_manager::remove_request(tracker_connection const* c) { mutex_t::scoped_lock l(m_mutex); tracker_connections_t::iterator i = std::find(m_connections.begin() , m_connections.end(), boost::intrusive_ptr<const tracker_connection>(c)); if (i == m_connections.end()) return; m_connections.erase(i); } void tracker_manager::queue_request( io_service& ios , connection_queue& cc , tracker_request req , std::string const& auth , boost::weak_ptr<request_callback> c) { mutex_t::scoped_lock l(m_mutex); TORRENT_ASSERT(req.num_want >= 0); TORRENT_ASSERT(!m_abort); if (m_abort) return; if (req.event == tracker_request::stopped) req.num_want = 0; TORRENT_ASSERT(!m_abort || req.event == tracker_request::stopped); if (m_abort && req.event != tracker_request::stopped) return; std::string protocol = req.url.substr(0, req.url.find(':')); boost::intrusive_ptr<tracker_connection> con; #ifdef TORRENT_USE_OPENSSL if (protocol == "http" || protocol == "https") #else if (protocol == "http") #endif { con = new http_tracker_connection( ios, cc, *this, req, c , m_ses, m_proxy, auth #if TORRENT_USE_I2P , &m_ses.m_i2p_conn #endif ); } else if (protocol == "udp") { con = new udp_tracker_connection( ios, cc, *this, req , c, m_ses , m_proxy); } else { // we need to post the error to avoid deadlock if (boost::shared_ptr<request_callback> r = c.lock()) ios.post(boost::bind(&request_callback::tracker_request_error, r, req , -1, error_code(errors::unsupported_url_protocol) , "", 0)); return; } m_connections.push_back(con); boost::shared_ptr<request_callback> cb = con->requester(); if (cb) cb->m_manager = this; con->start(); } void tracker_manager::abort_all_requests(bool all) { // removes all connections from m_connections // except 'event=stopped'-requests mutex_t::scoped_lock l(m_mutex); m_abort = true; tracker_connections_t close_connections; for (tracker_connections_t::iterator i = m_connections.begin() , end(m_connections.end()); i != end; ++i) { intrusive_ptr<tracker_connection> c = *i; tracker_request const& req = c->tracker_req(); if (req.event == tracker_request::stopped && !all) continue; close_connections.push_back(c); #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING boost::shared_ptr<request_callback> rc = c->requester(); if (rc) rc->debug_log("aborting: " + req.url); #endif } l.unlock(); for (tracker_connections_t::iterator i = close_connections.begin() , end(close_connections.end()); i != end; ++i) { (*i)->close(); } } bool tracker_manager::empty() const { mutex_t::scoped_lock l(m_mutex); return m_connections.empty(); } int tracker_manager::num_requests() const { mutex_t::scoped_lock l(m_mutex); return m_connections.size(); } } <|endoftext|>
<commit_before>#include "MPU6886.h" #include <math.h> #include <Arduino.h> #include "../M5Stack.h" #include "MahonyAHRS.h" MPU6886::MPU6886(){ } void MPU6886::I2C_Read_NBytes(uint8_t driver_Addr, uint8_t start_Addr, uint8_t number_Bytes, uint8_t *read_Buffer){ M5.I2C.readBytes(driver_Addr, start_Addr, number_Bytes, read_Buffer); } void MPU6886::I2C_Write_NBytes(uint8_t driver_Addr, uint8_t start_Addr, uint8_t number_Bytes, uint8_t *write_Buffer) { M5.I2C.writeBytes(driver_Addr, start_Addr, write_Buffer, number_Bytes); } int MPU6886::Init(void) { unsigned char tempdata[1]; unsigned char regdata; Gyscale = GFS_2000DPS; Acscale = AFS_8G; Wire1.begin(21,22); I2C_Read_NBytes(MPU6886_ADDRESS, MPU6886_WHOAMI, 1, tempdata); imuId = tempdata[0]; delay(1); regdata = 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_PWR_MGMT_1, 1, &regdata); delay(10); regdata = (0x01<<7); I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_PWR_MGMT_1, 1, &regdata); delay(10); regdata = (0x01<<0); I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_PWR_MGMT_1, 1, &regdata); delay(10); // +- 8g regdata = 0x10; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_ACCEL_CONFIG, 1, &regdata); delay(1); // +- 2000 dps regdata = 0x18; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_GYRO_CONFIG, 1, &regdata); delay(1); // 1khz output regdata = 0x01; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_CONFIG, 1, &regdata); delay(1); // 2 div, FIFO 500hz out regdata = 0x01; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_SMPLRT_DIV, 1, &regdata); delay(1); regdata = 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_INT_ENABLE, 1, &regdata); delay(1); regdata = 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_ACCEL_CONFIG2, 1, &regdata); delay(1); regdata = 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_USER_CTRL, 1, &regdata); delay(1); regdata = 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_FIFO_EN, 1, &regdata); delay(1); regdata = 0x22; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_INT_PIN_CFG, 1, &regdata); delay(1); regdata = 0x01; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_INT_ENABLE, 1, &regdata); delay(10); setGyroFsr(Gyscale); setAccelFsr(Acscale); return 0; } void MPU6886::getAccelAdc(int16_t* ax, int16_t* ay, int16_t* az) { uint8_t buf[6]; I2C_Read_NBytes(MPU6886_ADDRESS, MPU6886_ACCEL_XOUT_H, 6, buf); *ax=((int16_t)buf[0]<<8)|buf[1]; *ay=((int16_t)buf[2]<<8)|buf[3]; *az=((int16_t)buf[4]<<8)|buf[5]; } void MPU6886::getGyroAdc(int16_t* gx, int16_t* gy, int16_t* gz) { uint8_t buf[6]; I2C_Read_NBytes(MPU6886_ADDRESS,MPU6886_GYRO_XOUT_H, 6, buf); *gx=((uint16_t)buf[0]<<8)|buf[1]; *gy=((uint16_t)buf[2]<<8)|buf[3]; *gz=((uint16_t)buf[4]<<8)|buf[5]; } void MPU6886::getTempAdc(int16_t *t) { uint8_t buf[2]; I2C_Read_NBytes(MPU6886_ADDRESS,MPU6886_TEMP_OUT_H,2,buf); *t=((uint16_t)buf[0]<<8)|buf[1]; } //!俯仰,航向,横滚:pitch,yaw,roll,指三维空间中飞行器的旋转状态。 void MPU6886::getAhrsData(float *pitch, float *roll, float *yaw) { float accX = 0; float accY = 0; float accZ = 0; float gyroX = 0; float gyroY = 0; float gyroZ = 0; getGyroData(&gyroX, &gyroY, &gyroZ); getAccelData(&accX, &accY, &accZ); MahonyAHRSupdateIMU(gyroX * DEG_TO_RAD, gyroY * DEG_TO_RAD, gyroZ * DEG_TO_RAD, accX, accY, accZ, pitch, roll, yaw); } // Possible gyro scales (and their register bit settings) void MPU6886::updateGres() { switch (Gyscale) { case GFS_250DPS: gRes = 250.0/32768.0; break; case GFS_500DPS: gRes = 500.0/32768.0; break; case GFS_1000DPS: gRes = 1000.0/32768.0; break; case GFS_2000DPS: gRes = 2000.0/32768.0; break; } } // Possible accelerometer scales (and their register bit settings) are: // 2 Gs (00), 4 Gs (01), 8 Gs (10), and 16 Gs (11). // Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value: void MPU6886::updateAres() { switch (Acscale) { case AFS_2G: aRes = 2.0/32768.0; break; case AFS_4G: aRes = 4.0/32768.0; break; case AFS_8G: aRes = 8.0/32768.0; break; case AFS_16G: aRes = 16.0/32768.0; break; } } void MPU6886::setGyroFsr(Gscale scale) { unsigned char regdata; regdata = (scale<<3); I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_GYRO_CONFIG, 1, &regdata); delay(10); Gyscale = scale; updateGres(); } void MPU6886::setAccelFsr(Ascale scale) { unsigned char regdata; regdata = (scale<<3); I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_ACCEL_CONFIG, 1, &regdata); delay(10); Acscale = scale; updateAres(); } void MPU6886::getAccelData(float* ax, float* ay, float* az) { int16_t accX = 0; int16_t accY = 0; int16_t accZ = 0; getAccelAdc(&accX,&accY,&accZ); *ax = (float)accX * aRes; *ay = (float)accY * aRes; *az = (float)accZ * aRes; } void MPU6886::getGyroData(float* gx, float* gy, float* gz) { int16_t gyroX = 0; int16_t gyroY = 0; int16_t gyroZ = 0; getGyroAdc(&gyroX,&gyroY,&gyroZ); *gx = (float)gyroX * gRes; *gy = (float)gyroY * gRes; *gz = (float)gyroZ * gRes; } void MPU6886::getTempData(float *t) { int16_t temp = 0; getTempAdc(&temp); *t = (float)temp / 326.8 + 25.0; } void MPU6886::setGyroOffset(uint16_t x, uint16_t y, uint16_t z) { uint8_t buf_out[6]; buf_out[0] = x >> 8; buf_out[1] = x & 0xff; buf_out[2] = y >> 8; buf_out[3] = y & 0xff; buf_out[4] = z >> 8; buf_out[5] = z & 0xff; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_GYRO_OFFSET, 6, buf_out); } void MPU6886::setFIFOEnable( bool enableflag ) { uint8_t regdata = 0; regdata = enableflag ? 0x18 : 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_FIFO_ENABLE, 1, &regdata); regdata = enableflag ? 0x40 : 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_USER_CTRL, 1, &regdata); } uint8_t MPU6886::ReadFIFO() { uint8_t ReData = 0; I2C_Read_NBytes(MPU6886_ADDRESS, MPU6886_FIFO_R_W , 1 , &ReData); return ReData; } void MPU6886::ReadFIFOBuff(uint8_t *DataBuff ,uint16_t Length) { uint8_t number = Length / 210; for(uint8_t i = 0; i < number; i++) { I2C_Read_NBytes(MPU6886_ADDRESS, MPU6886_FIFO_R_W, 210, &DataBuff[i*210]); } I2C_Read_NBytes(MPU6886_ADDRESS, MPU6886_FIFO_R_W, Length % 210, &DataBuff[number*210]); } void MPU6886::RestFIFO() { uint8_t buf_out; I2C_Read_NBytes(MPU6886_ADDRESS, MPU6886_USER_CTRL, 1, &buf_out); buf_out |= 0x04; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_USER_CTRL, 1, &buf_out); } uint16_t MPU6886::ReadFIFOCount() { uint8_t Buff[2]; uint16_t ReData = 0; I2C_Read_NBytes( MPU6886_ADDRESS, MPU6886_FIFO_COUNT, 2, Buff); ReData = (Buff[0] << 8) | Buff[1]; return ReData; }<commit_msg>Fixed MPU6886 Init I2C error<commit_after>#include "MPU6886.h" #include <math.h> #include <Arduino.h> #include "../M5Stack.h" #include "MahonyAHRS.h" MPU6886::MPU6886(){ } void MPU6886::I2C_Read_NBytes(uint8_t driver_Addr, uint8_t start_Addr, uint8_t number_Bytes, uint8_t *read_Buffer){ M5.I2C.readBytes(driver_Addr, start_Addr, number_Bytes, read_Buffer); } void MPU6886::I2C_Write_NBytes(uint8_t driver_Addr, uint8_t start_Addr, uint8_t number_Bytes, uint8_t *write_Buffer) { M5.I2C.writeBytes(driver_Addr, start_Addr, write_Buffer, number_Bytes); } int MPU6886::Init(void) { unsigned char tempdata[1]; unsigned char regdata; Gyscale = GFS_2000DPS; Acscale = AFS_8G; Wire.begin(21,22); I2C_Read_NBytes(MPU6886_ADDRESS, MPU6886_WHOAMI, 1, tempdata); imuId = tempdata[0]; delay(1); regdata = 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_PWR_MGMT_1, 1, &regdata); delay(10); regdata = (0x01<<7); I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_PWR_MGMT_1, 1, &regdata); delay(10); regdata = (0x01<<0); I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_PWR_MGMT_1, 1, &regdata); delay(10); // +- 8g regdata = 0x10; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_ACCEL_CONFIG, 1, &regdata); delay(1); // +- 2000 dps regdata = 0x18; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_GYRO_CONFIG, 1, &regdata); delay(1); // 1khz output regdata = 0x01; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_CONFIG, 1, &regdata); delay(1); // 2 div, FIFO 500hz out regdata = 0x01; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_SMPLRT_DIV, 1, &regdata); delay(1); regdata = 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_INT_ENABLE, 1, &regdata); delay(1); regdata = 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_ACCEL_CONFIG2, 1, &regdata); delay(1); regdata = 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_USER_CTRL, 1, &regdata); delay(1); regdata = 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_FIFO_EN, 1, &regdata); delay(1); regdata = 0x22; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_INT_PIN_CFG, 1, &regdata); delay(1); regdata = 0x01; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_INT_ENABLE, 1, &regdata); delay(10); setGyroFsr(Gyscale); setAccelFsr(Acscale); return 0; } void MPU6886::getAccelAdc(int16_t* ax, int16_t* ay, int16_t* az) { uint8_t buf[6]; I2C_Read_NBytes(MPU6886_ADDRESS, MPU6886_ACCEL_XOUT_H, 6, buf); *ax=((int16_t)buf[0]<<8)|buf[1]; *ay=((int16_t)buf[2]<<8)|buf[3]; *az=((int16_t)buf[4]<<8)|buf[5]; } void MPU6886::getGyroAdc(int16_t* gx, int16_t* gy, int16_t* gz) { uint8_t buf[6]; I2C_Read_NBytes(MPU6886_ADDRESS,MPU6886_GYRO_XOUT_H, 6, buf); *gx=((uint16_t)buf[0]<<8)|buf[1]; *gy=((uint16_t)buf[2]<<8)|buf[3]; *gz=((uint16_t)buf[4]<<8)|buf[5]; } void MPU6886::getTempAdc(int16_t *t) { uint8_t buf[2]; I2C_Read_NBytes(MPU6886_ADDRESS,MPU6886_TEMP_OUT_H,2,buf); *t=((uint16_t)buf[0]<<8)|buf[1]; } //!俯仰,航向,横滚:pitch,yaw,roll,指三维空间中飞行器的旋转状态。 void MPU6886::getAhrsData(float *pitch, float *roll, float *yaw) { float accX = 0; float accY = 0; float accZ = 0; float gyroX = 0; float gyroY = 0; float gyroZ = 0; getGyroData(&gyroX, &gyroY, &gyroZ); getAccelData(&accX, &accY, &accZ); MahonyAHRSupdateIMU(gyroX * DEG_TO_RAD, gyroY * DEG_TO_RAD, gyroZ * DEG_TO_RAD, accX, accY, accZ, pitch, roll, yaw); } // Possible gyro scales (and their register bit settings) void MPU6886::updateGres() { switch (Gyscale) { case GFS_250DPS: gRes = 250.0/32768.0; break; case GFS_500DPS: gRes = 500.0/32768.0; break; case GFS_1000DPS: gRes = 1000.0/32768.0; break; case GFS_2000DPS: gRes = 2000.0/32768.0; break; } } // Possible accelerometer scales (and their register bit settings) are: // 2 Gs (00), 4 Gs (01), 8 Gs (10), and 16 Gs (11). // Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value: void MPU6886::updateAres() { switch (Acscale) { case AFS_2G: aRes = 2.0/32768.0; break; case AFS_4G: aRes = 4.0/32768.0; break; case AFS_8G: aRes = 8.0/32768.0; break; case AFS_16G: aRes = 16.0/32768.0; break; } } void MPU6886::setGyroFsr(Gscale scale) { unsigned char regdata; regdata = (scale<<3); I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_GYRO_CONFIG, 1, &regdata); delay(10); Gyscale = scale; updateGres(); } void MPU6886::setAccelFsr(Ascale scale) { unsigned char regdata; regdata = (scale<<3); I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_ACCEL_CONFIG, 1, &regdata); delay(10); Acscale = scale; updateAres(); } void MPU6886::getAccelData(float* ax, float* ay, float* az) { int16_t accX = 0; int16_t accY = 0; int16_t accZ = 0; getAccelAdc(&accX,&accY,&accZ); *ax = (float)accX * aRes; *ay = (float)accY * aRes; *az = (float)accZ * aRes; } void MPU6886::getGyroData(float* gx, float* gy, float* gz) { int16_t gyroX = 0; int16_t gyroY = 0; int16_t gyroZ = 0; getGyroAdc(&gyroX,&gyroY,&gyroZ); *gx = (float)gyroX * gRes; *gy = (float)gyroY * gRes; *gz = (float)gyroZ * gRes; } void MPU6886::getTempData(float *t) { int16_t temp = 0; getTempAdc(&temp); *t = (float)temp / 326.8 + 25.0; } void MPU6886::setGyroOffset(uint16_t x, uint16_t y, uint16_t z) { uint8_t buf_out[6]; buf_out[0] = x >> 8; buf_out[1] = x & 0xff; buf_out[2] = y >> 8; buf_out[3] = y & 0xff; buf_out[4] = z >> 8; buf_out[5] = z & 0xff; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_GYRO_OFFSET, 6, buf_out); } void MPU6886::setFIFOEnable( bool enableflag ) { uint8_t regdata = 0; regdata = enableflag ? 0x18 : 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_FIFO_ENABLE, 1, &regdata); regdata = enableflag ? 0x40 : 0x00; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_USER_CTRL, 1, &regdata); } uint8_t MPU6886::ReadFIFO() { uint8_t ReData = 0; I2C_Read_NBytes(MPU6886_ADDRESS, MPU6886_FIFO_R_W , 1 , &ReData); return ReData; } void MPU6886::ReadFIFOBuff(uint8_t *DataBuff ,uint16_t Length) { uint8_t number = Length / 210; for(uint8_t i = 0; i < number; i++) { I2C_Read_NBytes(MPU6886_ADDRESS, MPU6886_FIFO_R_W, 210, &DataBuff[i*210]); } I2C_Read_NBytes(MPU6886_ADDRESS, MPU6886_FIFO_R_W, Length % 210, &DataBuff[number*210]); } void MPU6886::RestFIFO() { uint8_t buf_out; I2C_Read_NBytes(MPU6886_ADDRESS, MPU6886_USER_CTRL, 1, &buf_out); buf_out |= 0x04; I2C_Write_NBytes(MPU6886_ADDRESS, MPU6886_USER_CTRL, 1, &buf_out); } uint16_t MPU6886::ReadFIFOCount() { uint8_t Buff[2]; uint16_t ReData = 0; I2C_Read_NBytes( MPU6886_ADDRESS, MPU6886_FIFO_COUNT, 2, Buff); ReData = (Buff[0] << 8) | Buff[1]; return ReData; }<|endoftext|>
<commit_before>#include "orbit_mpi.hh" #include "wrap_utils.hh" #include "wrap_matrix.hh" #include "wrap_phase_vector.hh" #include "wrap_py_base_field_source.hh" namespace wrap_orbit_utils{ void error(const char* msg){ ORBIT_MPI_Finalize(msg); } static PyMethodDef UtilsModuleMethods[] = { {NULL,NULL} }; #ifdef __cplusplus extern "C" { #endif void initutils(){ //create new module PyObject* module = Py_InitModule("orbit_utils",UtilsModuleMethods); //add the other classes init wrap_utils_martix::initMatrix(module); wrap_utils_phase_vector::initPhaseVector(module); wrap_utils_py_base_field_source::initPyBaseFieldSource(module); } PyObject* getOrbitUtilsType(char* name){ PyObject* mod = PyImport_ImportModule("orbit_utils"); PyObject* pyType = PyObject_GetAttrString(mod,name); Py_DECREF(mod); Py_DECREF(pyType); return pyType; } #ifdef __cplusplus } #endif //end of namespace wrap_orbit_utils } <commit_msg>field source container added<commit_after>#include "orbit_mpi.hh" #include "wrap_utils.hh" #include "wrap_matrix.hh" #include "wrap_phase_vector.hh" #include "wrap_py_base_field_source.hh" #include "wrap_field_source_container.hh" namespace wrap_orbit_utils{ void error(const char* msg){ ORBIT_MPI_Finalize(msg); } static PyMethodDef UtilsModuleMethods[] = { {NULL,NULL} }; #ifdef __cplusplus extern "C" { #endif void initutils(){ //create new module PyObject* module = Py_InitModule("orbit_utils",UtilsModuleMethods); //add the other classes init wrap_utils_martix::initMatrix(module); wrap_utils_phase_vector::initPhaseVector(module); wrap_utils_py_base_field_source::initPyBaseFieldSource(module); wrap_field_source_container::initFieldSourceContainer(module); } PyObject* getOrbitUtilsType(char* name){ PyObject* mod = PyImport_ImportModule("orbit_utils"); PyObject* pyType = PyObject_GetAttrString(mod,name); Py_DECREF(mod); Py_DECREF(pyType); return pyType; } #ifdef __cplusplus } #endif //end of namespace wrap_orbit_utils } <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net) Version 1.1.0, packaged on March, 2009. http://glc-lib.sourceforge.net GLC-lib 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. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ #include "glc_repcrossmover.h" #include "glc_viewport.h" // Default constructor GLC_RepCrossMover::GLC_RepCrossMover(GLC_Viewport* pViewport) : GLC_RepMover(pViewport) { } // Copy constructor GLC_RepCrossMover::GLC_RepCrossMover(const GLC_RepCrossMover& repMover) : GLC_RepMover(repMover) { } GLC_RepCrossMover::~GLC_RepCrossMover() { } ////////////////////////////////////////////////////////////////////// // Get Functions ////////////////////////////////////////////////////////////////////// // Return a clone of the repmover GLC_RepMover* GLC_RepCrossMover::clone() const { return new GLC_RepCrossMover(*this); } ////////////////////////////////////////////////////////////////////// // OpenGL Functions ////////////////////////////////////////////////////////////////////// // Virtual interface for OpenGL Geometry set up. void GLC_RepCrossMover::glDraw() { int nLgAxe; const int winHSize= m_pViewport->getWinHSize(); const int winVSize= m_pViewport->getWinVSize(); if (winHSize > winVSize) { nLgAxe = static_cast<int>(static_cast<double>(winVSize) / 2.0); } else { nLgAxe = static_cast<int>(static_cast<double>(winHSize) / 2.0); } // Compute the length of camera's field of view const double ChampsVision = 2 * (m_pViewport->cameraHandle()->getDistEyeTarget()) * tan((m_pViewport->getFov() * glc::PI / 180.0) / 2.0); // the side of camera's square is mapped on Vertical length of window // Axis length in OpenGL unit = length(Pixel) * (dimend GL / dimens Pixel) const double dLgAxe= ((double)nLgAxe * ChampsVision / (double)winVSize) / 7; const double dDecAxe= dLgAxe / 3; glPushMatrix(); glTranslated(m_pViewport->cameraHandle()->getTarget().X(), m_pViewport->cameraHandle()->getTarget().Y(), m_pViewport->cameraHandle()->getTarget().Z() ); // Graphic propertys glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glColor4d(m_MainColor.redF(), m_MainColor.greenF(), m_MainColor.blueF(), m_MainColor.alphaF()); glLineWidth(1.0); // Display camera's target lines glBegin(GL_LINES); //X axis glVertex3d(-dLgAxe, 0, 0); glVertex3d(-dDecAxe, 0, 0); glVertex3d(dDecAxe, 0, 0); glVertex3d(dLgAxe, 0, 0); //Y axis glVertex3d(0, -dLgAxe, 0); glVertex3d(0, -dDecAxe, 0); glVertex3d(0, dDecAxe, 0); glVertex3d(0, dLgAxe, 0); //Z axis glVertex3d(0, 0, -dLgAxe); glVertex3d(0, 0, -dDecAxe); glVertex3d(0, 0, dDecAxe); glVertex3d(0, 0, dLgAxe); glEnd(); glPopMatrix(); } <commit_msg>minor commant update.<commit_after>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net) Version 1.1.0, packaged on March, 2009. http://glc-lib.sourceforge.net GLC-lib 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. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ #include "glc_repcrossmover.h" #include "glc_viewport.h" // Default constructor GLC_RepCrossMover::GLC_RepCrossMover(GLC_Viewport* pViewport) : GLC_RepMover(pViewport) { } // Copy constructor GLC_RepCrossMover::GLC_RepCrossMover(const GLC_RepCrossMover& repMover) : GLC_RepMover(repMover) { } GLC_RepCrossMover::~GLC_RepCrossMover() { } ////////////////////////////////////////////////////////////////////// // Get Functions ////////////////////////////////////////////////////////////////////// // Return a clone of the repmover GLC_RepMover* GLC_RepCrossMover::clone() const { return new GLC_RepCrossMover(*this); } ////////////////////////////////////////////////////////////////////// // OpenGL Functions ////////////////////////////////////////////////////////////////////// // Virtual interface for OpenGL Geometry set up. void GLC_RepCrossMover::glDraw() { int nLgAxe; const int winHSize= m_pViewport->getWinHSize(); const int winVSize= m_pViewport->getWinVSize(); if (winHSize > winVSize) { nLgAxe = static_cast<int>(static_cast<double>(winVSize) / 2.0); } else { nLgAxe = static_cast<int>(static_cast<double>(winHSize) / 2.0); } // Compute the length of camera's field of view const double ChampsVision = 2 * (m_pViewport->cameraHandle()->getDistEyeTarget()) * tan((m_pViewport->getFov() * glc::PI / 180.0) / 2.0); // the side of camera's square is mapped on Vertical length of window // Axis length in OpenGL unit = length(Pixel) * (dimend GL / dimens Pixel) const double dLgAxe= ((double)nLgAxe * ChampsVision / (double)winVSize) / 7; const double dDecAxe= dLgAxe / 3; glPushMatrix(); glTranslated(m_pViewport->cameraHandle()->getTarget().X(), m_pViewport->cameraHandle()->getTarget().Y(), m_pViewport->cameraHandle()->getTarget().Z() ); // Graphic properties glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glColor4d(m_MainColor.redF(), m_MainColor.greenF(), m_MainColor.blueF(), m_MainColor.alphaF()); glLineWidth(1.0); // Display camera's target lines glBegin(GL_LINES); //X axis glVertex3d(-dLgAxe, 0, 0); glVertex3d(-dDecAxe, 0, 0); glVertex3d(dDecAxe, 0, 0); glVertex3d(dLgAxe, 0, 0); //Y axis glVertex3d(0, -dLgAxe, 0); glVertex3d(0, -dDecAxe, 0); glVertex3d(0, dDecAxe, 0); glVertex3d(0, dLgAxe, 0); //Z axis glVertex3d(0, 0, -dLgAxe); glVertex3d(0, 0, -dDecAxe); glVertex3d(0, 0, dDecAxe); glVertex3d(0, 0, dLgAxe); glEnd(); glPopMatrix(); } <|endoftext|>
<commit_before>/* This file is part of khmer, https://github.com/dib-lab/khmer/, and is Copyright (C) 2010-2015, Michigan State University. Copyright (C) 2015, The Regents of the University of California. 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 Michigan State University 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. LICENSE (END) Contact: khmer-project@idyll.org */ #ifndef HASHTABLE_HH #define HASHTABLE_HH #include <stddef.h> #include <stdint.h> #include <string.h> #include <fstream> #include <iostream> #include <list> #include <map> #include <queue> #include <queue> #include <set> #include <string> #include <vector> #include "khmer.hh" #include "khmer_exception.hh" #include "kmer_hash.hh" #include "read_parsers.hh" #include "traversal.hh" #include "subset.hh" namespace khmer { class CountingHash; class Hashtable; namespace read_parsers { struct IParser; } // namespace read_parsers } // namespace khmer #define MAX_KEEPER_SIZE int(1e6) #define next_f(kmer_f, ch) ((((kmer_f) << 2) & bitmask) | (twobit_repr(ch))) #define next_r(kmer_r, ch) (((kmer_r) >> 2) | (twobit_comp(ch) << rc_left_shift)) #define prev_f(kmer_f, ch) ((kmer_f) >> 2 | twobit_repr(ch) << rc_left_shift) #define prev_r(kmer_r, ch) ((((kmer_r) << 2) & bitmask) | (twobit_comp(ch))) #define set_contains(s, e) ((s).find(e) != (s).end()) #define CALLBACK_PERIOD 100000 namespace khmer { class Hashtable: public KmerFactory // Base class implementation of a Bloom ht. { friend class SubsetPartition; friend class LabelHash; friend class Traverser; protected: unsigned int _tag_density; unsigned int _max_count; unsigned int _max_bigcount; //WordLength _ksize; HashIntoType bitmask; unsigned int _nbits_sub_1; explicit Hashtable( WordLength ksize ) : KmerFactory( ksize ), _max_count( MAX_KCOUNT ), _max_bigcount( MAX_BIGCOUNT ) { _tag_density = DEFAULT_TAG_DENSITY; if (!(_tag_density % 2 == 0)) { throw khmer_exception(); } _init_bitstuff(); partition = new SubsetPartition(this); _all_tags_spin_lock = 0; } virtual ~Hashtable( ) { delete partition; } void _init_bitstuff() { bitmask = 0; for (unsigned int i = 0; i < _ksize; i++) { bitmask = (bitmask << 2) | 3; } _nbits_sub_1 = (_ksize*2 - 2); } HashIntoType _next_hash(char ch, HashIntoType &h, HashIntoType &r) const { // left-shift the previous hash over h = h << 2; // 'or' in the current nt h |= twobit_repr(ch); // mask off the 2 bits we shifted over. h &= bitmask; // now handle reverse complement r = r >> 2; r |= (twobit_comp(ch) << _nbits_sub_1); return uniqify_rc(h, r); } void _clear_all_partitions() { if (partition != NULL) { partition->_clear_all_partitions(); } } uint32_t _all_tags_spin_lock; explicit Hashtable(const Hashtable&); Hashtable& operator=(const Hashtable&); public: SubsetPartition * partition; SeenSet all_tags; SeenSet stop_tags; SeenSet repart_small_tags; // accessor to get 'k' const WordLength ksize() const { return _ksize; } virtual void count(const char * kmer) = 0; virtual void count(HashIntoType khash) = 0; // get the count for the given k-mer. virtual const BoundedCounterType get_count(const char * kmer) const = 0; virtual const BoundedCounterType get_count(HashIntoType khash) const = 0; virtual void save(std::string) = 0; virtual void load(std::string) = 0; // count every k-mer in the string. unsigned int consume_string(const std::string &s); // checks each read for non-ACGT characters bool check_and_normalize_read(std::string &read) const; // check each read for non-ACGT characters, and then consume it. unsigned int check_and_process_read(std::string &read, bool &is_valid); // Count every k-mer in a FASTA or FASTQ file. // Note: Yes, the name 'consume_fasta' is a bit misleading, // but the FASTA format is effectively a subset of the FASTQ format // and the FASTA portion is what we care about in this case. void consume_fasta( std::string const &filename, unsigned int &total_reads, unsigned long long &n_consumed ); // Count every k-mer from a stream of FASTA or FASTQ reads, // using the supplied parser. void consume_fasta( read_parsers:: IParser * parser, unsigned int &total_reads, unsigned long long &n_consumed ); bool median_at_least(const std::string &s, unsigned int cutoff); void get_median_count(const std::string &s, BoundedCounterType &median, float &average, float &stddev); // number of unique k-mers virtual const HashIntoType n_unique_kmers() const = 0; // count number of occupied bins virtual const HashIntoType n_occupied() const = 0; // partitioning stuff void _validate_pmap() { if (partition) { partition->_validate_pmap(); } } virtual void save_tagset(std::string); virtual void load_tagset(std::string, bool clear_tags=true); // for debugging/testing purposes only! void _set_tag_density(unsigned int d) { if (!(d % 2 == 0) || !all_tags.empty()) { // must be even and tags must exist throw khmer_exception(); } _tag_density = d; } unsigned int _get_tag_density() const { return _tag_density; } void add_tag(HashIntoType tag) { all_tags.insert(tag); } void add_stop_tag(HashIntoType tag) { stop_tags.insert(tag); } // Partitioning stuff. size_t n_tags() const { return all_tags.size(); } void divide_tags_into_subsets(unsigned int subset_size, SeenSet& divvy); void add_kmer_to_tags(HashIntoType kmer) { all_tags.insert(kmer); } void clear_tags() { all_tags.clear(); } // Count every k-mer in a FASTA or FASTQ file. // Tag certain ones on the connectivity graph. void consume_fasta_and_tag( std::string const &filename, unsigned int &total_reads, unsigned long long &n_consumed ); // Count every k-mer from a stream of FASTA or FASTQ reads, // using the supplied parser. // Tag certain ones on the connectivity graph. void consume_fasta_and_tag( read_parsers:: IParser * parser, unsigned int &total_reads, unsigned long long &n_consumed ); void consume_sequence_and_tag(const std::string& seq, unsigned long long& n_consumed, SeenSet * new_tags = 0); void consume_partitioned_fasta(const std::string &filename, unsigned int &total_reads, unsigned long long &n_consumed); virtual BoundedCounterType test_and_set_bits(const char * kmer) = 0; virtual BoundedCounterType test_and_set_bits(HashIntoType khash) = 0; virtual std::vector<HashIntoType> get_tablesizes() const = 0; virtual const size_t n_tables() const = 0; size_t trim_on_stoptags(std::string sequence) const; unsigned int traverse_from_kmer(Kmer start, unsigned int radius, KmerSet &keeper, unsigned int max_count = MAX_KEEPER_SIZE) const; virtual void print_tagset(std::string); virtual void print_stop_tags(std::string); virtual void save_stop_tags(std::string); void load_stop_tags(std::string filename, bool clear_tags=true); void extract_unique_paths(std::string seq, unsigned int min_length, float min_unique_f, std::vector<std::string> &results); void calc_connected_graph_size(Kmer node, unsigned long long& count, KmerSet& keeper, const unsigned long long threshold=0, bool break_on_circum=false) const; typedef void (*kmer_cb)(const char * k, unsigned int n_reads, void *data); unsigned int kmer_degree(HashIntoType kmer_f, HashIntoType kmer_r); unsigned int kmer_degree(const char * kmer_s); // return all k-mer substrings, on the forward strand. void get_kmers(const std::string &s, std::vector<std::string> &kmers) const; // return hash values for all k-mer substrings void get_kmer_hashes(const std::string &s, std::vector<HashIntoType> &kmers) const; // return counts of all k-mers in this string. void get_kmer_counts(const std::string &s, std::vector<BoundedCounterType> &counts) const; }; } #define ACQUIRE_ALL_TAGS_SPIN_LOCK \ while (!__sync_bool_compare_and_swap( &_all_tags_spin_lock, 0, 1 )); #define RELEASE_ALL_TAGS_SPIN_LOCK \ __sync_bool_compare_and_swap( &_all_tags_spin_lock, 1, 0 ); #endif // HASHTABLE_HH <commit_msg>remove unused function _next_hash<commit_after>/* This file is part of khmer, https://github.com/dib-lab/khmer/, and is Copyright (C) 2010-2015, Michigan State University. Copyright (C) 2015, The Regents of the University of California. 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 Michigan State University 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. LICENSE (END) Contact: khmer-project@idyll.org */ #ifndef HASHTABLE_HH #define HASHTABLE_HH #include <stddef.h> #include <stdint.h> #include <string.h> #include <fstream> #include <iostream> #include <list> #include <map> #include <queue> #include <queue> #include <set> #include <string> #include <vector> #include "khmer.hh" #include "khmer_exception.hh" #include "kmer_hash.hh" #include "read_parsers.hh" #include "traversal.hh" #include "subset.hh" namespace khmer { class CountingHash; class Hashtable; namespace read_parsers { struct IParser; } // namespace read_parsers } // namespace khmer #define MAX_KEEPER_SIZE int(1e6) #define next_f(kmer_f, ch) ((((kmer_f) << 2) & bitmask) | (twobit_repr(ch))) #define next_r(kmer_r, ch) (((kmer_r) >> 2) | (twobit_comp(ch) << rc_left_shift)) #define prev_f(kmer_f, ch) ((kmer_f) >> 2 | twobit_repr(ch) << rc_left_shift) #define prev_r(kmer_r, ch) ((((kmer_r) << 2) & bitmask) | (twobit_comp(ch))) #define set_contains(s, e) ((s).find(e) != (s).end()) #define CALLBACK_PERIOD 100000 namespace khmer { class Hashtable: public KmerFactory // Base class implementation of a Bloom ht. { friend class SubsetPartition; friend class LabelHash; friend class Traverser; protected: unsigned int _tag_density; unsigned int _max_count; unsigned int _max_bigcount; //WordLength _ksize; HashIntoType bitmask; unsigned int _nbits_sub_1; explicit Hashtable( WordLength ksize ) : KmerFactory( ksize ), _max_count( MAX_KCOUNT ), _max_bigcount( MAX_BIGCOUNT ) { _tag_density = DEFAULT_TAG_DENSITY; if (!(_tag_density % 2 == 0)) { throw khmer_exception(); } _init_bitstuff(); partition = new SubsetPartition(this); _all_tags_spin_lock = 0; } virtual ~Hashtable( ) { delete partition; } void _init_bitstuff() { bitmask = 0; for (unsigned int i = 0; i < _ksize; i++) { bitmask = (bitmask << 2) | 3; } _nbits_sub_1 = (_ksize*2 - 2); } void _clear_all_partitions() { if (partition != NULL) { partition->_clear_all_partitions(); } } uint32_t _all_tags_spin_lock; explicit Hashtable(const Hashtable&); Hashtable& operator=(const Hashtable&); public: SubsetPartition * partition; SeenSet all_tags; SeenSet stop_tags; SeenSet repart_small_tags; // accessor to get 'k' const WordLength ksize() const { return _ksize; } virtual void count(const char * kmer) = 0; virtual void count(HashIntoType khash) = 0; // get the count for the given k-mer. virtual const BoundedCounterType get_count(const char * kmer) const = 0; virtual const BoundedCounterType get_count(HashIntoType khash) const = 0; virtual void save(std::string) = 0; virtual void load(std::string) = 0; // count every k-mer in the string. unsigned int consume_string(const std::string &s); // checks each read for non-ACGT characters bool check_and_normalize_read(std::string &read) const; // check each read for non-ACGT characters, and then consume it. unsigned int check_and_process_read(std::string &read, bool &is_valid); // Count every k-mer in a FASTA or FASTQ file. // Note: Yes, the name 'consume_fasta' is a bit misleading, // but the FASTA format is effectively a subset of the FASTQ format // and the FASTA portion is what we care about in this case. void consume_fasta( std::string const &filename, unsigned int &total_reads, unsigned long long &n_consumed ); // Count every k-mer from a stream of FASTA or FASTQ reads, // using the supplied parser. void consume_fasta( read_parsers:: IParser * parser, unsigned int &total_reads, unsigned long long &n_consumed ); bool median_at_least(const std::string &s, unsigned int cutoff); void get_median_count(const std::string &s, BoundedCounterType &median, float &average, float &stddev); // number of unique k-mers virtual const HashIntoType n_unique_kmers() const = 0; // count number of occupied bins virtual const HashIntoType n_occupied() const = 0; // partitioning stuff void _validate_pmap() { if (partition) { partition->_validate_pmap(); } } virtual void save_tagset(std::string); virtual void load_tagset(std::string, bool clear_tags=true); // for debugging/testing purposes only! void _set_tag_density(unsigned int d) { if (!(d % 2 == 0) || !all_tags.empty()) { // must be even and tags must exist throw khmer_exception(); } _tag_density = d; } unsigned int _get_tag_density() const { return _tag_density; } void add_tag(HashIntoType tag) { all_tags.insert(tag); } void add_stop_tag(HashIntoType tag) { stop_tags.insert(tag); } // Partitioning stuff. size_t n_tags() const { return all_tags.size(); } void divide_tags_into_subsets(unsigned int subset_size, SeenSet& divvy); void add_kmer_to_tags(HashIntoType kmer) { all_tags.insert(kmer); } void clear_tags() { all_tags.clear(); } // Count every k-mer in a FASTA or FASTQ file. // Tag certain ones on the connectivity graph. void consume_fasta_and_tag( std::string const &filename, unsigned int &total_reads, unsigned long long &n_consumed ); // Count every k-mer from a stream of FASTA or FASTQ reads, // using the supplied parser. // Tag certain ones on the connectivity graph. void consume_fasta_and_tag( read_parsers:: IParser * parser, unsigned int &total_reads, unsigned long long &n_consumed ); void consume_sequence_and_tag(const std::string& seq, unsigned long long& n_consumed, SeenSet * new_tags = 0); void consume_partitioned_fasta(const std::string &filename, unsigned int &total_reads, unsigned long long &n_consumed); virtual BoundedCounterType test_and_set_bits(const char * kmer) = 0; virtual BoundedCounterType test_and_set_bits(HashIntoType khash) = 0; virtual std::vector<HashIntoType> get_tablesizes() const = 0; virtual const size_t n_tables() const = 0; size_t trim_on_stoptags(std::string sequence) const; unsigned int traverse_from_kmer(Kmer start, unsigned int radius, KmerSet &keeper, unsigned int max_count = MAX_KEEPER_SIZE) const; virtual void print_tagset(std::string); virtual void print_stop_tags(std::string); virtual void save_stop_tags(std::string); void load_stop_tags(std::string filename, bool clear_tags=true); void extract_unique_paths(std::string seq, unsigned int min_length, float min_unique_f, std::vector<std::string> &results); void calc_connected_graph_size(Kmer node, unsigned long long& count, KmerSet& keeper, const unsigned long long threshold=0, bool break_on_circum=false) const; typedef void (*kmer_cb)(const char * k, unsigned int n_reads, void *data); unsigned int kmer_degree(HashIntoType kmer_f, HashIntoType kmer_r); unsigned int kmer_degree(const char * kmer_s); // return all k-mer substrings, on the forward strand. void get_kmers(const std::string &s, std::vector<std::string> &kmers) const; // return hash values for all k-mer substrings void get_kmer_hashes(const std::string &s, std::vector<HashIntoType> &kmers) const; // return counts of all k-mers in this string. void get_kmer_counts(const std::string &s, std::vector<BoundedCounterType> &counts) const; }; } #define ACQUIRE_ALL_TAGS_SPIN_LOCK \ while (!__sync_bool_compare_and_swap( &_all_tags_spin_lock, 0, 1 )); #define RELEASE_ALL_TAGS_SPIN_LOCK \ __sync_bool_compare_and_swap( &_all_tags_spin_lock, 1, 0 ); #endif // HASHTABLE_HH <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2013, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file main.cxx * * A simple application to demonstrate a train node. * * @author Balazs Racz * @date 1 Feb 2015 */ #define LOGLEVEL INFO #include <unistd.h> #include <fcntl.h> #include <memory> #include "nmranet/AliasAllocator.hxx" #include "nmranet/EventService.hxx" #include "nmranet/IfCan.hxx" #include "nmranet/TractionTestTrain.hxx" #include "nmranet/TractionTrain.hxx" #include "os/os.h" #include "utils/GridConnectHub.hxx" #include "utils/Hub.hxx" #include "utils/constants.hxx" #include "utils/socket_listener.hxx" NO_THREAD nt; Executor<1> g_executor(nt); Service g_service(&g_executor); CanHubFlow can_hub0(&g_service); nmranet::IfCan g_if_can(&g_executor, &can_hub0, 3, 3, 2); // This nodeid is only used for seeding the alias allocation flow. static const nmranet::NodeID NODE_ID = 0x0501010100F5ULL; static nmranet::AddAliasAllocator g_alias_allocator(NODE_ID, &g_if_can); nmranet::EventService g_event_service(&g_if_can); nmranet::TrainService traction_service(&g_if_can); int port = 12021; const char *host = "localhost"; const char *device_path = nullptr; int address = 1726; void usage(const char *e) { fprintf( stderr, "Usage: %s ([-i destination_host] [-p port] | [-d device_path]) " " [-a address]\n", e); fprintf(stderr, "Connects to an openlcb bus and exports a virtual train.\n"); fprintf(stderr, "The bus connection will be through an OpenLCB HUB on " "destination_host:port with OpenLCB over TCP " "(in GridConnect format) protocol, or through the CAN-USB device " "(also in GridConnect protocol) found at device_path. Device takes " "precedence over TCP host:port specification."); fprintf(stderr, "The default target is localhost:12021.\n"); fprintf(stderr, "Address is the virtual loco address. Default 1726.\n"); exit(1); } void parse_args(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "hp:i:d:a:")) >= 0) { switch (opt) { case 'h': usage(argv[0]); break; case 'p': port = atoi(optarg); break; case 'i': host = optarg; break; case 'd': device_path = optarg; break; case 'a': address = atoi(optarg); break; default: fprintf(stderr, "Unknown option %c\n", opt); usage(argv[0]); } } } int appl_main(int argc, char *argv[]) { parse_args(argc, argv); int conn_fd = 0; if (device_path) { conn_fd = ::open(device_path, O_RDWR); } else { conn_fd = ConnectSocket("localhost", 12021); } HASSERT(conn_fd >= 0); create_gc_port_for_can_hub(&can_hub0, conn_fd); nmranet::LoggingTrain train_impl(1732); nmranet::TrainNode train_node(&traction_service, &train_impl); g_if_can.add_addressed_message_support(); // Bootstraps the alias allocation process. g_if_can.alias_allocator()->send(g_if_can.alias_allocator()->alloc()); g_executor.thread_body(); return 0; } <commit_msg>Addsthe "IS_TRAIN" event to the traction test node.<commit_after>/** \copyright * Copyright (c) 2013, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file main.cxx * * A simple application to demonstrate a train node. * * @author Balazs Racz * @date 1 Feb 2015 */ #define LOGLEVEL INFO #include <unistd.h> #include <fcntl.h> #include <memory> #include "nmranet/AliasAllocator.hxx" #include "nmranet/EventService.hxx" #include "nmranet/EventHandlerTemplates.hxx" #include "nmranet/IfCan.hxx" #include "nmranet/TractionTestTrain.hxx" #include "nmranet/TractionTrain.hxx" #include "os/os.h" #include "utils/GridConnectHub.hxx" #include "utils/Hub.hxx" #include "utils/constants.hxx" #include "utils/socket_listener.hxx" NO_THREAD nt; Executor<1> g_executor(nt); Service g_service(&g_executor); CanHubFlow can_hub0(&g_service); nmranet::IfCan g_if_can(&g_executor, &can_hub0, 3, 3, 2); // This nodeid is only used for seeding the alias allocation flow. static const nmranet::NodeID NODE_ID = 0x0501010100F5ULL; static nmranet::AddAliasAllocator g_alias_allocator(NODE_ID, &g_if_can); nmranet::EventService g_event_service(&g_if_can); nmranet::TrainService traction_service(&g_if_can); using nmranet::Node; using nmranet::SimpleEventHandler; using nmranet::EventRegistry; using nmranet::EventReport; using nmranet::event_write_helper1; using nmranet::WriteHelper; template <uint64_t EVENT_ID> class FixedEventProducer : public SimpleEventHandler { public: FixedEventProducer(Node *node) : node_(node) { EventRegistry::instance()->register_handlerr(this, EVENT_ID, 0); } ~FixedEventProducer() { EventRegistry::instance()->unregister_handlerr(this, EVENT_ID, 0); } void HandleIdentifyGlobal(EventReport *event, BarrierNotifiable *done) OVERRIDE { if (event->dst_node && event->dst_node != node_) { return done->notify(); } event_write_helper1.WriteAsync( node_, nmranet::Defs::MTI_PRODUCER_IDENTIFIED_UNKNOWN, WriteHelper::global(), nmranet::eventid_to_buffer(EVENT_ID), done); } void HandleIdentifyProducer(EventReport *event, BarrierNotifiable *done) OVERRIDE { return HandleIdentifyGlobal(event, done); } private: Node *node_; }; int port = 12021; const char *host = "localhost"; const char *device_path = nullptr; int address = 1726; void usage(const char *e) { fprintf(stderr, "Usage: %s ([-i destination_host] [-p port] | [-d device_path]) " " [-a address]\n", e); fprintf(stderr, "Connects to an openlcb bus and exports a virtual train.\n"); fprintf(stderr, "The bus connection will be through an OpenLCB HUB on " "destination_host:port with OpenLCB over TCP " "(in GridConnect format) protocol, or through the CAN-USB device " "(also in GridConnect protocol) found at device_path. Device takes " "precedence over TCP host:port specification."); fprintf(stderr, "The default target is localhost:12021.\n"); fprintf(stderr, "Address is the virtual loco address. Default 1726.\n"); exit(1); } void parse_args(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "hp:i:d:a:")) >= 0) { switch (opt) { case 'h': usage(argv[0]); break; case 'p': port = atoi(optarg); break; case 'i': host = optarg; break; case 'd': device_path = optarg; break; case 'a': address = atoi(optarg); break; default: fprintf(stderr, "Unknown option %c\n", opt); usage(argv[0]); } } } int appl_main(int argc, char *argv[]) { parse_args(argc, argv); int conn_fd = 0; if (device_path) { conn_fd = ::open(device_path, O_RDWR); } else { conn_fd = ConnectSocket("localhost", 12021); } HASSERT(conn_fd >= 0); create_gc_port_for_can_hub(&can_hub0, conn_fd); nmranet::LoggingTrain train_impl(1732); nmranet::TrainNode train_node(&traction_service, &train_impl); FixedEventProducer<nmranet::TractionDefs::IS_TRAIN_EVENT> is_train_event_handler(&train_node); g_if_can.add_addressed_message_support(); // Bootstraps the alias allocation process. g_if_can.alias_allocator()->send(g_if_can.alias_allocator()->alloc()); g_executor.thread_body(); return 0; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_OPENCL_MATRIX_CL_HPP #define STAN_MATH_OPENCL_MATRIX_CL_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/opencl_context.hpp> #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/err/check_opencl.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/prim/arr/fun/vec_concat.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/scal/err/domain_error.hpp> #include <CL/cl.hpp> #include <iostream> #include <string> #include <vector> #include <algorithm> /** * @file stan/math/opencl/matrix_cl.hpp * @brief The matrix_cl class - allocates memory space on the OpenCL device, * functions for transfering matrices to and from OpenCL devices */ namespace stan { namespace math { // Dummy class to instantiate matrix_cl to enable for specific types. template <typename T, typename = void> class matrix_cl {}; /** * Represents a matrix on the OpenCL device. * * @tparam T an arithmetic type for the type stored in the OpenCL buffer. */ template <typename T> class matrix_cl<T, enable_if_arithmetic<T>> { private: cl::Buffer buffer_cl_; // Holds the allocated memory on the device const int rows_; const int cols_; matrix_cl_view view_; // Holds info on if matrix is a special type mutable std::vector<cl::Event> write_events_; // Tracks write jobs mutable std::vector<cl::Event> read_events_; // Tracks reads public: typedef T type; // Forward declare the methods that work in place on the matrix template <matrix_cl_view matrix_view = matrix_cl_view::Entire> void zeros(); template <TriangularMapCL triangular_map = TriangularMapCL::LowerToUpper> void triangular_transpose(); void sub_block(const matrix_cl<T, enable_if_arithmetic<T>>& A, size_t A_i, size_t A_j, size_t this_i, size_t this_j, size_t nrows, size_t ncols); int rows() const { return rows_; } int cols() const { return cols_; } int size() const { return rows_ * cols_; } const matrix_cl_view& view() const { return view_; } void view(const matrix_cl_view& view) { view_ = view; } /** * Clear the write events from the event stacks. */ inline void clear_write_events() const { write_events_.clear(); return; } /** * Clear the read events from the event stacks. */ inline void clear_read_events() const { read_events_.clear(); return; } /** * Clear the write events from the event stacks. */ inline void clear_read_write_events() const { read_events_.clear(); write_events_.clear(); return; } /** * Get the events from the event stacks. * @return The write event stack. */ inline const std::vector<cl::Event>& write_events() const { return write_events_; } /** * Get the events from the event stacks. * @return The read/write event stack. */ inline const std::vector<cl::Event>& read_events() const { return read_events_; } /** * Get the events from the event stacks. * @return The read/write event stack. */ inline const std::vector<cl::Event> read_write_events() const { return vec_concat(this->read_events(), this->write_events()); } /** * Add an event to the read event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_read_event(cl::Event new_event) const { this->read_events_.push_back(new_event); } /** * Add an event to the write event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_write_event(cl::Event new_event) const { this->write_events_.push_back(new_event); } /** * Add an event to the read/write event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_read_write_event(cl::Event new_event) const { this->read_events_.push_back(new_event); this->write_events_.push_back(new_event); } /** * Waits for the write events and clears the read event stack. */ inline void wait_for_write_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; queue.enqueueBarrierWithWaitList(&this->write_events(), &copy_event); copy_event.wait(); write_events_.clear(); return; } /** * Waits for the read events and clears the read event stack. */ inline void wait_for_read_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; queue.enqueueBarrierWithWaitList(&this->read_events(), &copy_event); copy_event.wait(); read_events_.clear(); return; } /** * Waits for read and write events to finish and clears the read, write, and * read/write event stacks. */ inline void wait_for_read_write_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; const std::vector<cl::Event> mat_events = this->read_write_events(); queue.enqueueBarrierWithWaitList(&mat_events, &copy_event); copy_event.wait(); read_events_.clear(); write_events_.clear(); return; } const cl::Buffer& buffer() const { return buffer_cl_; } cl::Buffer& buffer() { return buffer_cl_; } matrix_cl() : rows_(0), cols_(0) {} matrix_cl(const matrix_cl<T>& A) : rows_(A.rows()), cols_(A.cols()), view_(A.view()) { if (A.size() == 0) return; cl::Context& ctx = opencl_context.context(); cl::CommandQueue queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); cl::Event cstr_event; queue.enqueueCopyBuffer(A.buffer(), this->buffer(), 0, 0, A.size() * sizeof(T), &A.write_events(), &cstr_event); this->add_write_event(cstr_event); } catch (const cl::Error& e) { check_opencl_error("copy (OpenCL)->(OpenCL)", e); } } /** * Constructor for the matrix_cl that * creates a copy of the Eigen matrix on the OpenCL device. * * * @tparam R row type * @tparam C column type * @param A the Eigen matrix * * @throw <code>std::invalid_argument</code> if the * matrices do not have matching dimensions */ template <int R, int C> explicit matrix_cl(const std::vector<Eigen::Matrix<T, R, C>>& A) try : rows_(A.empty() ? 0 : A[0].size()), cols_(A.size()) { if (this->size() == 0) return; cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); // creates the OpenCL buffer to copy the Eigen // matrix to the OpenCL device buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); for (int i = 0, offset_size = 0; i < cols_; i++, offset_size += rows_) { check_size_match("matrix constructor", "input rows", A[i].size(), "matrix_cl rows", rows_); /** * Writes the contents of A[i] to the OpenCL buffer * starting at the offset sizeof(double)*start. * CL_TRUE denotes that the call is blocking as * we do not want to execute any further kernels * on the device until we are sure that the data * is finished transfering */ cl::Event write_event; queue.enqueueWriteBuffer( buffer_cl_, CL_FALSE, sizeof(double) * offset_size, sizeof(double) * rows_, A[i].data(), NULL, &write_event); this->add_write_event(write_event); } } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } /** * Constructor for the matrix_cl that * only allocates the buffer on the OpenCL device. * Regardless of `partial_view`, whole matrix is stored. * * @param rows number of matrix rows, must be greater or equal to 0 * @param cols number of matrix columns, must be greater or equal to 0 * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions * */ matrix_cl(const int& rows, const int& cols, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(rows), cols_(cols), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); try { // creates the OpenCL buffer of the provided size buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * rows_ * cols_); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Constructor for the matrix_cl that * creates a copy of the Eigen matrix on the OpenCL device. * Regardless of `partial_view`, whole matrix is stored. * * @tparam T type of data in the \c Eigen \c Matrix * @param A the \c Eigen \c Matrix * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ template <int R, int C> explicit matrix_cl(const Eigen::Matrix<T, R, C>& A, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(A.rows()), cols_(A.cols()), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Constructor for the matrix_cl that * creates a copy of the Eigen Map of Eigen Matrix of doubles * on the OpenCL device. * Regardless of `partial_view`, whole matrix in the map * is stored. * * @tparam T type of data in the \c Eigen \c Matrix * @param A the \c Eigen \c Map of the Eigen Matrix * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ template <int R, int C> explicit matrix_cl(Eigen::Map<Eigen::Matrix<T, R, C>>& A, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(A.rows()), cols_(A.cols()), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Construct from \c std::vector with given rows and columns * * @param A Standard vector * @param R Number of rows the matrix should have. * @param C Number of columns the matrix should have. * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ explicit matrix_cl(const std::vector<T>& A, const int& R, const int& C) : rows_(R), cols_(C) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Construct from \c array of doubles with given rows and columns * * @param A array of doubles * @param R Number of rows the matrix should have. * @param C Number of columns the matrix should have. * @param partial_view which part of the matrix is used * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ explicit matrix_cl(const double* A, const int& R, const int& C, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(R), cols_(C), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * size(), A, NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Assign a \c matrix_cl to another */ matrix_cl<T>& operator=(const matrix_cl<T>& a) { check_size_match("assignment of (OpenCL) matrices", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("assignment of (OpenCL) matrices", "source.cols()", a.cols(), "destination.cols()", cols()); // Need to wait for all of matrices events before destroying old buffer this->wait_for_read_write_events(); buffer_cl_ = a.buffer(); view_ = a.view(); return *this; } /** * Assign a \c matrix_cl of one arithmetic type to another */ template <typename U, typename = enable_if_arithmetic<U>> matrix_cl<T>& operator=(const matrix_cl<U>& a) { check_size_match("assignment of (OpenCL) matrices", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("assignment of (OpenCL) matrices", "source.cols()", a.cols(), "destination.cols()", cols()); // Need to wait for all of matrices events before destroying old buffer this->wait_for_read_write_events(); buffer_cl_ = a.buffer(); view_ = a.view(); return *this; } }; template <typename T> using matrix_cl_prim = matrix_cl<T, enable_if_arithmetic<T>>; template <typename T> using matrix_cl_fp = matrix_cl<T, enable_if_floating_point<T>>; } // namespace math } // namespace stan #endif #endif <commit_msg>removed the map constructor, changed the Matrix constructor to Eigen::Ref<commit_after>#ifndef STAN_MATH_OPENCL_MATRIX_CL_HPP #define STAN_MATH_OPENCL_MATRIX_CL_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/opencl_context.hpp> #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/err/check_opencl.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/prim/arr/fun/vec_concat.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/scal/err/domain_error.hpp> #include <CL/cl.hpp> #include <iostream> #include <string> #include <vector> #include <algorithm> /** * @file stan/math/opencl/matrix_cl.hpp * @brief The matrix_cl class - allocates memory space on the OpenCL device, * functions for transfering matrices to and from OpenCL devices */ namespace stan { namespace math { // Dummy class to instantiate matrix_cl to enable for specific types. template <typename T, typename = void> class matrix_cl {}; /** * Represents a matrix on the OpenCL device. * * @tparam T an arithmetic type for the type stored in the OpenCL buffer. */ template <typename T> class matrix_cl<T, enable_if_arithmetic<T>> { private: cl::Buffer buffer_cl_; // Holds the allocated memory on the device const int rows_; const int cols_; matrix_cl_view view_; // Holds info on if matrix is a special type mutable std::vector<cl::Event> write_events_; // Tracks write jobs mutable std::vector<cl::Event> read_events_; // Tracks reads public: typedef T type; // Forward declare the methods that work in place on the matrix template <matrix_cl_view matrix_view = matrix_cl_view::Entire> void zeros(); template <TriangularMapCL triangular_map = TriangularMapCL::LowerToUpper> void triangular_transpose(); void sub_block(const matrix_cl<T, enable_if_arithmetic<T>>& A, size_t A_i, size_t A_j, size_t this_i, size_t this_j, size_t nrows, size_t ncols); int rows() const { return rows_; } int cols() const { return cols_; } int size() const { return rows_ * cols_; } const matrix_cl_view& view() const { return view_; } void view(const matrix_cl_view& view) { view_ = view; } /** * Clear the write events from the event stacks. */ inline void clear_write_events() const { write_events_.clear(); return; } /** * Clear the read events from the event stacks. */ inline void clear_read_events() const { read_events_.clear(); return; } /** * Clear the write events from the event stacks. */ inline void clear_read_write_events() const { read_events_.clear(); write_events_.clear(); return; } /** * Get the events from the event stacks. * @return The write event stack. */ inline const std::vector<cl::Event>& write_events() const { return write_events_; } /** * Get the events from the event stacks. * @return The read/write event stack. */ inline const std::vector<cl::Event>& read_events() const { return read_events_; } /** * Get the events from the event stacks. * @return The read/write event stack. */ inline const std::vector<cl::Event> read_write_events() const { return vec_concat(this->read_events(), this->write_events()); } /** * Add an event to the read event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_read_event(cl::Event new_event) const { this->read_events_.push_back(new_event); } /** * Add an event to the write event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_write_event(cl::Event new_event) const { this->write_events_.push_back(new_event); } /** * Add an event to the read/write event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_read_write_event(cl::Event new_event) const { this->read_events_.push_back(new_event); this->write_events_.push_back(new_event); } /** * Waits for the write events and clears the read event stack. */ inline void wait_for_write_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; queue.enqueueBarrierWithWaitList(&this->write_events(), &copy_event); copy_event.wait(); write_events_.clear(); return; } /** * Waits for the read events and clears the read event stack. */ inline void wait_for_read_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; queue.enqueueBarrierWithWaitList(&this->read_events(), &copy_event); copy_event.wait(); read_events_.clear(); return; } /** * Waits for read and write events to finish and clears the read, write, and * read/write event stacks. */ inline void wait_for_read_write_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; const std::vector<cl::Event> mat_events = this->read_write_events(); queue.enqueueBarrierWithWaitList(&mat_events, &copy_event); copy_event.wait(); read_events_.clear(); write_events_.clear(); return; } const cl::Buffer& buffer() const { return buffer_cl_; } cl::Buffer& buffer() { return buffer_cl_; } matrix_cl() : rows_(0), cols_(0) {} matrix_cl(const matrix_cl<T>& A) : rows_(A.rows()), cols_(A.cols()), view_(A.view()) { if (A.size() == 0) return; cl::Context& ctx = opencl_context.context(); cl::CommandQueue queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); cl::Event cstr_event; queue.enqueueCopyBuffer(A.buffer(), this->buffer(), 0, 0, A.size() * sizeof(T), &A.write_events(), &cstr_event); this->add_write_event(cstr_event); } catch (const cl::Error& e) { check_opencl_error("copy (OpenCL)->(OpenCL)", e); } } /** * Constructor for the matrix_cl that * creates a copy of the Eigen matrix on the OpenCL device. * * * @tparam R row type * @tparam C column type * @param A the Eigen matrix * * @throw <code>std::invalid_argument</code> if the * matrices do not have matching dimensions */ template <int R, int C> explicit matrix_cl(const std::vector<Eigen::Matrix<T, R, C>>& A) try : rows_(A.empty() ? 0 : A[0].size()), cols_(A.size()) { if (this->size() == 0) return; cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); // creates the OpenCL buffer to copy the Eigen // matrix to the OpenCL device buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); for (int i = 0, offset_size = 0; i < cols_; i++, offset_size += rows_) { check_size_match("matrix constructor", "input rows", A[i].size(), "matrix_cl rows", rows_); /** * Writes the contents of A[i] to the OpenCL buffer * starting at the offset sizeof(double)*start. * CL_TRUE denotes that the call is blocking as * we do not want to execute any further kernels * on the device until we are sure that the data * is finished transfering */ cl::Event write_event; queue.enqueueWriteBuffer( buffer_cl_, CL_FALSE, sizeof(double) * offset_size, sizeof(double) * rows_, A[i].data(), NULL, &write_event); this->add_write_event(write_event); } } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } /** * Constructor for the matrix_cl that * only allocates the buffer on the OpenCL device. * Regardless of `partial_view`, whole matrix is stored. * * @param rows number of matrix rows, must be greater or equal to 0 * @param cols number of matrix columns, must be greater or equal to 0 * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions * */ matrix_cl(const int& rows, const int& cols, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(rows), cols_(cols), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); try { // creates the OpenCL buffer of the provided size buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * rows_ * cols_); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Constructor for the matrix_cl that * creates a copy of the Eigen matrix on the OpenCL device. * Regardless of `partial_view`, whole matrix is stored. * * @tparam T type of data in the \c Eigen \c Matrix * @param A the \c Eigen \c Matrix * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ explicit matrix_cl(const Eigen::Ref<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>& A, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(A.rows()), cols_(A.cols()), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Construct from \c std::vector with given rows and columns * * @param A Standard vector * @param R Number of rows the matrix should have. * @param C Number of columns the matrix should have. * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ explicit matrix_cl(const std::vector<T>& A, const int& R, const int& C) : rows_(R), cols_(C) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Construct from \c array of doubles with given rows and columns * * @param A array of doubles * @param R Number of rows the matrix should have. * @param C Number of columns the matrix should have. * @param partial_view which part of the matrix is used * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ explicit matrix_cl(const double* A, const int& R, const int& C, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(R), cols_(C), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * size(), A, NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Assign a \c matrix_cl to another */ matrix_cl<T>& operator=(const matrix_cl<T>& a) { check_size_match("assignment of (OpenCL) matrices", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("assignment of (OpenCL) matrices", "source.cols()", a.cols(), "destination.cols()", cols()); // Need to wait for all of matrices events before destroying old buffer this->wait_for_read_write_events(); buffer_cl_ = a.buffer(); view_ = a.view(); return *this; } /** * Assign a \c matrix_cl of one arithmetic type to another */ template <typename U, typename = enable_if_arithmetic<U>> matrix_cl<T>& operator=(const matrix_cl<U>& a) { check_size_match("assignment of (OpenCL) matrices", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("assignment of (OpenCL) matrices", "source.cols()", a.cols(), "destination.cols()", cols()); // Need to wait for all of matrices events before destroying old buffer this->wait_for_read_write_events(); buffer_cl_ = a.buffer(); view_ = a.view(); return *this; } }; template <typename T> using matrix_cl_prim = matrix_cl<T, enable_if_arithmetic<T>>; template <typename T> using matrix_cl_fp = matrix_cl<T, enable_if_floating_point<T>>; } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/bridge_task_runner.h" #include "base/message_loop/message_loop.h" namespace atom { void BridgeTaskRunner::MessageLoopIsReady() { auto message_loop = base::MessageLoop::current(); CHECK(message_loop); for (const TaskPair& task : tasks_) { message_loop->task_runner()->PostDelayedTask( std::get<0>(task), std::get<1>(task), std::get<2>(task)); } for (const TaskPair& task : non_nestable_tasks_) { message_loop->task_runner()->PostNonNestableDelayedTask( std::get<0>(task), std::get<1>(task), std::get<2>(task)); } } bool BridgeTaskRunner::PostDelayedTask( const tracked_objects::Location& from_here, base::OnceClosure task, base::TimeDelta delay) { auto message_loop = base::MessageLoop::current(); if (!message_loop) { tasks_.push_back(std::make_tuple(from_here, std::move(task), delay)); return true; } return message_loop->task_runner()->PostDelayedTask(from_here, std::move(task), delay); } bool BridgeTaskRunner::RunsTasksOnCurrentThread() const { auto message_loop = base::MessageLoop::current(); if (!message_loop) return true; return message_loop->task_runner()->RunsTasksOnCurrentThread(); } bool BridgeTaskRunner::PostNonNestableDelayedTask( const tracked_objects::Location& from_here, base::OnceClosure task, base::TimeDelta delay) { auto message_loop = base::MessageLoop::current(); if (!message_loop) { non_nestable_tasks_.push_back(std::make_tuple(from_here, std::move(task), delay)); return true; } return message_loop->task_runner()->PostNonNestableDelayedTask( from_here, task, delay); } } // namespace atom <commit_msg>Fix implicitly deleted copy constructor error<commit_after>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/bridge_task_runner.h" #include "base/message_loop/message_loop.h" namespace atom { void BridgeTaskRunner::MessageLoopIsReady() { auto message_loop = base::MessageLoop::current(); CHECK(message_loop); for (TaskPair& task : tasks_) { message_loop->task_runner()->PostDelayedTask( std::get<0>(task), std::move(std::get<1>(task)), std::get<2>(task)); } for (TaskPair& task : non_nestable_tasks_) { message_loop->task_runner()->PostNonNestableDelayedTask( std::get<0>(task), std::move(std::get<1>(task)), std::get<2>(task)); } } bool BridgeTaskRunner::PostDelayedTask( const tracked_objects::Location& from_here, base::OnceClosure task, base::TimeDelta delay) { auto message_loop = base::MessageLoop::current(); if (!message_loop) { tasks_.push_back(std::make_tuple(from_here, std::move(task), delay)); return true; } return message_loop->task_runner()->PostDelayedTask(from_here, std::move(task), delay); } bool BridgeTaskRunner::RunsTasksOnCurrentThread() const { auto message_loop = base::MessageLoop::current(); if (!message_loop) return true; return message_loop->task_runner()->RunsTasksOnCurrentThread(); } bool BridgeTaskRunner::PostNonNestableDelayedTask( const tracked_objects::Location& from_here, base::OnceClosure task, base::TimeDelta delay) { auto message_loop = base::MessageLoop::current(); if (!message_loop) { non_nestable_tasks_.push_back(std::make_tuple(from_here, std::move(task), delay)); return true; } return message_loop->task_runner()->PostNonNestableDelayedTask( from_here, std::move(task), delay); } } // namespace atom <|endoftext|>
<commit_before>class Solution { public: /* * param k : As description. * param n : As description. * return: How many k's between 0 and n. */ int digitCounts(int k, int n) { // write your code here int result = 0; int base = 1; while (n/base > 0) { int cur = (n/base)%10; int low = n-(n/base) * base;; int high = n/(base * 10); if (cur < k) { result += high*base; } else if (cur > k) { result += (high+1)*base; } else { result += high*base+low+1; } if (k==0) result-=base; base *= 10; } return result; } }; // class Solution { // public: // /* // * param k : As description. // * param n : As description. // * return: How many k's between 0 and n. // */ // int digitCounts(int k, int n) { // // write your code here // if (k<0 or k>10) return 0; // int rt_count=0,tmp_count=0; // int i,j,ys=0,n_it=n; // i=1; // int yc=0; //right // while (n_it>0){ // tmp_count=0; // ys=n_it%10; // this digit // n_it=n_it/10; // rt_count+=i*n_it; // if (k==0 and i>1) rt_count -= 1*i; // if (ys==k) rt_count += yc+1; // if (ys>k) rt_count+=i; // i*=10; // yc=yc*10+ys; //right total // // cout<<rt_count<<" "; // } // return rt_count; // } // }; //O(n *log(n)) solution ,not so great // class Solution { // public: // // param k : description of k // // param n : description of n // // return ans a integer // int digitCounts(int k, int n) { // int count = 0; // if (k == 0) { // count = 1; // } // for (int i = 1; i <= n; i++) { // int number = i; // while (number > 0) { // if (number % 10 == k) { // count += 1; // } // number /= 10; // } // } // return count; // } // };<commit_msg>Find the bug<commit_after>class Solution { public: /* * param k : As description. * param n : As description. * return: How many k's between 0 and n. */ int digitCounts(int k, int n) { // write your code here int result = 0; int base = 1; if (n==0 and k==0 ) return 1; while (n/base > 0) { int cur = (n/base)%10; int low = n-(n/base) * base;; int high = n/(base * 10); if (cur < k) { result += high*base; } else if (cur > k) { result += (high+1)*base; } else { result += high*base+low+1; } if (k==0 and base>1) result-=base; base *= 10; } return result; } }; // class Solution { // public: // /* // * param k : As description. // * param n : As description. // * return: How many k's between 0 and n. // */ // int digitCounts(int k, int n) { // // write your code here // if (k<0 or k>10) return 0; // int rt_count=0,tmp_count=0; // int i,j,ys=0,n_it=n; // i=1; // int yc=0; //right // while (n_it>0){ // tmp_count=0; // ys=n_it%10; // this digit // n_it=n_it/10; // rt_count+=i*n_it; // if (k==0 and i>1) rt_count -= 1*i; // if (ys==k) rt_count += yc+1; // if (ys>k) rt_count+=i; // i*=10; // yc=yc*10+ys; //right total // // cout<<rt_count<<" "; // } // return rt_count; // } // }; //O(n *log(n)) solution ,not so great // class Solution { // public: // // param k : description of k // // param n : description of n // // return ans a integer // int digitCounts(int k, int n) { // int count = 0; // if (k == 0) { // count = 1; // } // for (int i = 1; i <= n; i++) { // int number = i; // while (number > 0) { // if (number % 10 == k) { // count += 1; // } // number /= 10; // } // } // return count; // } // };<|endoftext|>
<commit_before> #include "astronomy/frames.hpp" #include "gtest/gtest.h" #include "physics/solar_system.hpp" namespace principia { using physics::SolarSystem; namespace astronomy { class TrappistDynamicsTest : public ::testing::Test { protected: }; TEST_F(TrappistDynamicsTest, Smoke) { SolarSystem<Trappist> trappist_system( SOLUTION_DIR / "astronomy" / "trappist_gravity_model.proto.txt", SOLUTION_DIR / "astronomy" / "trappist_initial_state_jd_2457282_805700000.proto.txt"); } } // namespace astronomy } // namespace principia <commit_msg>Prolong.<commit_after> #include "astronomy/frames.hpp" #include "geometry/named_quantities.hpp" #include "gtest/gtest.h" #include "integrators/methods.hpp" #include "integrators/symmetric_linear_multistep_integrator.hpp" #include "physics/ephemeris.hpp" #include "physics/solar_system.hpp" #include "quantities/astronomy.hpp" #include "quantities/si.hpp" namespace principia { using geometry::Instant; using geometry::Position; using integrators::SymmetricLinearMultistepIntegrator; using integrators::methods::Quinlan1999Order8A; using physics::Ephemeris; using physics::SolarSystem; using quantities::astronomy::JulianYear; using quantities::si::Day; using quantities::si::Metre; using quantities::si::Milli; namespace astronomy { class TrappistDynamicsTest : public ::testing::Test { protected: }; TEST_F(TrappistDynamicsTest, Smoke) { SolarSystem<Trappist> trappist_system( SOLUTION_DIR / "astronomy" / "trappist_gravity_model.proto.txt", SOLUTION_DIR / "astronomy" / "trappist_initial_state_jd_2457282_805700000.proto.txt"); auto const ephemeris = trappist_system.MakeEphemeris( /*fitting_tolerance=*/5 * Milli(Metre), Ephemeris<Trappist>::FixedStepParameters( SymmetricLinearMultistepIntegrator<Quinlan1999Order8A, Position<Trappist>>(), /*step=*/0.08 * Day)); Instant const a_century_later = trappist_system.epoch() + 100 * JulianYear; ephemeris->Prolong(a_century_later); } } // namespace astronomy } // namespace principia <|endoftext|>
<commit_before>class Solution { public: /* * @param n an integer * @return the nth prime number as description. */ set<int> a; int nthUglyNumber(int n) { // write your code here if (n<=0) return -1; a.clear(); a.insert(1); listAllUglyNumberFactorBy(n,2); listAllUglyNumberFactorBy(n,3); listAllUglyNumberFactorBy(n,5); set<int>::iterator it1=a.begin(); for (int i=2;i<=n;i++) { // cout<<*it1<<" "; it1++; } return *it1; } int listAllUglyNumberFactorBy(int n,int factor){ for (int i=1;i<=factor*n;i++){ if (i % factor ==0) a.insert(i); } } };<commit_msg>Change the idea<commit_after>class Solution { public: /* * @param n an integer * @return the nth prime number as description. */ set<int> a; bool isUgly(int i){ int j=i; while (j % 2==0) j=j/2; while (j % 3==0) j=j/3; while (j % 5==0) j=j/5; } int nthUglyNumber(int n) { // write your code here if (n<=0) return -1; int i,j,k=1; i=1; while (i<MAX_INT){ i++; if (isUgly(i)) { k++; if (k==n) return i; } } set<int>::iterator it1=a.begin(); for (int i=2;i<=n;i++) { cout<<*it1<<" "; it1++; } return *it1; } };<|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <set> #include <map> #include <random> #include <chrono> #include <functional> #include <algorithm> #include <cmath> #define SPLIT 20 struct Entry { double SL, SW, PL, PW; std::string Class; }; using IntPair = std::pair<int, int>; struct CompareSecond: std::binary_function<IntPair, IntPair, bool> { bool operator()(const IntPair& a, const IntPair& b) { return a.second < b.second; } }; int main(int argc, char** argv) { if (argc < 2) return 1; // preparing data std::ifstream file(argv[1]); if (!file.is_open()) return 1; std::vector<Entry> data; while (!file.eof()) { std::string line; std::getline(file, line); if ("" == line) continue; std::istringstream linein(std::move(line)); Entry entry; std::string sl, sw, pl, pw; std::getline(linein, sl, ','); entry.SL = std::stod(sl, nullptr); std::getline(linein, sw, ','); entry.SW = std::stod(sw, nullptr); std::getline(linein, pl, ','); entry.PL = std::stod(pl, nullptr); std::getline(linein, pw, ','); entry.PW = std::stod(pw, nullptr); std::getline(linein, entry.Class); data.push_back(std::move(entry)); } std::default_random_engine generator(std::chrono::system_clock::now().time_since_epoch().count()); std::uniform_int_distribution<> distribution(0, (int)data.size() - 1); std::set<int> trainingSet, testSet; for (int i = 0; i < (int)data.size(); ++i) if (distribution(generator) < SPLIT) testSet.insert(i); else trainingSet.insert(i); // generating predictions int k; std::cin >> k; std::set<std::string> predictions; for (auto test: testSet) { // finding neighbors auto compareSecond = [](const auto& a, const auto& b) { return a.second < b.second; }; std::set<IntPair, CompareSecond> distances; auto euclideanDistance = [](const Entry& entry1, const Entry& entry2) { int dSL = entry1.SL - entry2.SL, dSW = entry1.SW - entry2.SW, dPL = entry1.PL - entry2.PL, dPW = entry1.PL - entry2.PW; return sqrt(dSL * dSL + dSW * dSW + dPL * dPL + dPW * dPW); }; for (auto trainer: trainingSet) distances.insert(std::make_pair(trainer, euclideanDistance(data[test], data[trainer]))); std::set<int> neighbors; auto i = distances.begin(); for (int j = 0; j < k; ++j, ++i) neighbors.insert(i->first); // getting response std::map<std::string, int> classVotes; for (auto neighbor: neighbors) { auto response = data[neighbor].Class; if (classVotes.count(response)) ++classVotes[response]; else classVotes[response] = 1; } auto responsePos = std::max_element(classVotes.begin(), classVotes.end(), compareSecond); auto response = responsePos->first; predictions.insert(response); std::cout << "Predicted: " << response << ", actual: " << data[test].Class << std::endl; } // calculating accuracy int correctCount = 0; auto j = predictions.begin(); for (auto i = testSet.begin(); i != testSet.end(); ++i, ++j) if (data[*i].Class == *j) ++correctCount; std::cout << "Accuracy: " << 100.0 * correctCount / testSet.size() << "%" << std::endl; return 0; } <commit_msg>knn: fixed a typo in the Euclidean distance implementation<commit_after>#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <set> #include <map> #include <random> #include <chrono> #include <functional> #include <algorithm> #include <cmath> #define SPLIT 20 struct Entry { double SL, SW, PL, PW; std::string Class; }; using IntPair = std::pair<int, int>; struct CompareSecond: std::binary_function<IntPair, IntPair, bool> { bool operator()(const IntPair& a, const IntPair& b) { return a.second < b.second; } }; int main(int argc, char** argv) { if (argc < 2) return 1; // preparing data std::ifstream file(argv[1]); if (!file.is_open()) return 1; std::vector<Entry> data; while (!file.eof()) { std::string line; std::getline(file, line); if ("" == line) continue; std::istringstream linein(std::move(line)); Entry entry; std::string sl, sw, pl, pw; std::getline(linein, sl, ','); entry.SL = std::stod(sl, nullptr); std::getline(linein, sw, ','); entry.SW = std::stod(sw, nullptr); std::getline(linein, pl, ','); entry.PL = std::stod(pl, nullptr); std::getline(linein, pw, ','); entry.PW = std::stod(pw, nullptr); std::getline(linein, entry.Class); data.push_back(std::move(entry)); } std::default_random_engine generator(std::chrono::system_clock::now().time_since_epoch().count()); std::uniform_int_distribution<> distribution(0, (int)data.size() - 1); std::set<int> trainingSet, testSet; for (int i = 0; i < (int)data.size(); ++i) if (distribution(generator) < SPLIT) testSet.insert(i); else trainingSet.insert(i); // generating predictions int k; std::cin >> k; std::set<std::string> predictions; for (auto test: testSet) { // finding neighbors auto compareSecond = [](const auto& a, const auto& b) { return a.second < b.second; }; std::set<IntPair, CompareSecond> distances; auto euclideanDistance = [](const Entry& entry1, const Entry& entry2) { int dSL = entry1.SL - entry2.SL, dSW = entry1.SW - entry2.SW, dPL = entry1.PL - entry2.PL, dPW = entry1.PW - entry2.PW; return sqrt(dSL * dSL + dSW * dSW + dPL * dPL + dPW * dPW); }; for (auto trainer: trainingSet) distances.insert(std::make_pair(trainer, euclideanDistance(data[test], data[trainer]))); std::set<int> neighbors; auto i = distances.begin(); for (int j = 0; j < k; ++j, ++i) neighbors.insert(i->first); // getting response std::map<std::string, int> classVotes; for (auto neighbor: neighbors) { auto response = data[neighbor].Class; if (classVotes.count(response)) ++classVotes[response]; else classVotes[response] = 1; } auto responsePos = std::max_element(classVotes.begin(), classVotes.end(), compareSecond); auto response = responsePos->first; predictions.insert(response); std::cout << "Predicted: " << response << ", actual: " << data[test].Class << std::endl; } // calculating accuracy int correctCount = 0; auto j = predictions.begin(); for (auto i = testSet.begin(); i != testSet.end(); ++i, ++j) if (data[*i].Class == *j) ++correctCount; std::cout << "Accuracy: " << 100.0 * correctCount / testSet.size() << "%" << std::endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: testbasi.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-07 19:16:15 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _TTBASIC_HXX #define _TTBASIC_HXX #ifndef _SB_SBSTAR_HXX //autogen #include <basic/sbstar.hxx> #endif #include <basic/mybasic.hxx> class ErrorEntry; #define SBXID_TTBASIC 0x5454 // TTBasic: TT #define SBXCR_TEST2 0x54534554L // TEST class TTBasic : public MyBasic { public: SBX_DECL_PERSIST_NODATA(SBXCR_TEST2,SBXID_TTBASIC,1); TYPEINFO(); TTBasic(); ~TTBasic(); BOOL Compile( SbModule* ); static MyBasic* CreateMyBasic(); // nicht mit #ifdefs klammern, da diese Headerdatei fr testtool und basic // gleichermaen verwendet wird. DECL_LINK( CErrorImpl, ErrorEntry* ); // SbxObject *pTestObject; // fr das Testtool; ansonsten NULL void LoadIniFile(); SbTextType GetSymbolType( const String &Symbol, BOOL bWasTTControl ); // Besimmt den erweiterten Symboltyp fr das Syntaxhighlighting virtual const String GetSpechialErrorText(); virtual void ReportRuntimeError( AppBasEd *pEditWin ); virtual void DebugFindNoErrors( BOOL bDebugFindNoErrors ); }; SV_DECL_IMPL_REF(TTBasic) #endif <commit_msg>INTEGRATION: CWS changefileheader (1.6.142); FILE MERGED 2008/04/01 15:00:00 thb 1.6.142.2: #i85898# Stripping all external header guards 2008/03/28 16:03:34 rt 1.6.142.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: testbasi.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _TTBASIC_HXX #define _TTBASIC_HXX #include <basic/sbstar.hxx> #include <basic/mybasic.hxx> class ErrorEntry; #define SBXID_TTBASIC 0x5454 // TTBasic: TT #define SBXCR_TEST2 0x54534554L // TEST class TTBasic : public MyBasic { public: SBX_DECL_PERSIST_NODATA(SBXCR_TEST2,SBXID_TTBASIC,1); TYPEINFO(); TTBasic(); ~TTBasic(); BOOL Compile( SbModule* ); static MyBasic* CreateMyBasic(); // nicht mit #ifdefs klammern, da diese Headerdatei fr testtool und basic // gleichermaen verwendet wird. DECL_LINK( CErrorImpl, ErrorEntry* ); // SbxObject *pTestObject; // fr das Testtool; ansonsten NULL void LoadIniFile(); SbTextType GetSymbolType( const String &Symbol, BOOL bWasTTControl ); // Besimmt den erweiterten Symboltyp fr das Syntaxhighlighting virtual const String GetSpechialErrorText(); virtual void ReportRuntimeError( AppBasEd *pEditWin ); virtual void DebugFindNoErrors( BOOL bDebugFindNoErrors ); }; SV_DECL_IMPL_REF(TTBasic) #endif <|endoftext|>
<commit_before>// BSD 2-Clause License, see github.com/ma16/rpio #include "../invoke.h" #include <Device/Ds18x20/Bang.h> #include <Posix/base.h> #include <Ui/strto.h> #include <cstring> // memset // [todo] command line options: timing and ARM counter frequency template<size_t N> static void print(std::bitset<N> const &set) { using Bang = Device::Ds18x20::Bang ; auto crc = 0 == Bang::crc(set) ; auto string = set.to_string() ; std::reverse(string.begin(),string.end()) ; std::cout << std::hex << set.to_ullong() << ' ' << string << ' ' << (crc ? "crc:ok" : "crc:failure") << '\n' ; } static void convert(Rpi::Peripheral *rpi,Ui::ArgL *argL) { auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ; auto wait = !argL->pop_if("-n") ; argL->finalize() ; using Bang = Device::Ds18x20::Bang ; try { Bang(rpi,pin).convert() ; // [todo] retry } catch (Bang::Error &e) { std::cerr << "start conversion error:" << e.what() << '\n' ; exit(1) ; } if (wait) { unsigned count = 1 ; Proceed: ; try { auto busy = Bang(rpi,pin).isBusy() ; while (busy) { busy = Bang(rpi,pin).isBusy() ; ++count ; } } catch (Bang::Error &e) { if (0 == strcmp(e.what(),"reset")) { std::cerr << "got suspended while setting the bus low\n" ; exit(1) ; } goto Proceed ; } // [todo] measure and display the time it takes to finish // (this piece of information might be quite interesting) try { // this does only word on a single drop bus auto pad = Bang(rpi,pin).readPad() ; print(pad) ; auto ull = pad.to_ullong() ; auto temp = static_cast<int16_t>(ull & 0xffff) ; auto mode = static_cast<unsigned>((ull >> 37) & 0x3) ; auto div = 2u << mode ; std::cout << static_cast<double>(temp) / div << '\n' ; } catch (Bang::Error &e) { std::cerr << "read scratch-pad error:" << e.what() << '\n' ; exit(1) ; } } } static void pad(Rpi::Peripheral *rpi,Ui::ArgL *argL) { auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ; argL->finalize() ; using Bang = Device::Ds18x20::Bang ; try { auto pad = Bang(rpi,pin).readPad() ; print(pad) ; } catch (Bang::Error &e) { std::cerr << "error:" << e.what() << '\n' ; exit(1) ; } } static void rom(Rpi::Peripheral *rpi,Ui::ArgL *argL) { using Bang = Device::Ds18x20::Bang ; auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ; argL->finalize() ; try { auto address = Bang(rpi,pin).address() ; if (address) print(*address) ; else std::cout << "no device present\n" ; } catch (Bang::Error &e) { std::cerr << "error:" << e.what() << '\n' ; exit(1) ; } } static void search(Rpi::Peripheral *rpi,Ui::ArgL *argL) { using Bang = Device::Ds18x20::Bang ; auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ; argL->finalize() ; Bang bang(rpi,pin) ; Retry: try { auto next = bang.first() ; if (!next) { std::cout << "no device present\n" ; } while (next) { print(*next) ; next = bang.next(*next) ; } } catch (Bang::Error &e) { std::cerr << "error:" << e.what() << '\n' ; goto Retry ; } } void Console::Device::Ds18x20::invoke(Rpi::Peripheral *rpi,Ui::ArgL *argL) { if (argL->empty() || argL->peek() == "help") { std::cout << "arguments: OPTION PIN\n" << '\n' << "rom = read 64-bit ROM code\n" << "pad = read 72-bit scratch pad\n" ; return ; } std::string arg = argL->pop() ; if (false) ; else if (arg == "convert") convert(rpi,argL) ; else if (arg == "rom") rom(rpi,argL) ; else if (arg == "pad") pad(rpi,argL) ; else if (arg == "search") search(rpi,argL) ; else throw std::runtime_error("not supported option:<"+arg+'>') ; } <commit_msg>retry only last operation for search<commit_after>// BSD 2-Clause License, see github.com/ma16/rpio #include "../invoke.h" #include <Device/Ds18x20/Bang.h> #include <Posix/base.h> #include <Ui/strto.h> #include <cstring> // memset // [todo] command line options: timing and ARM counter frequency template<size_t N> static void print(std::bitset<N> const &set) { using Bang = Device::Ds18x20::Bang ; auto crc = 0 == Bang::crc(set) ; auto string = set.to_string() ; std::reverse(string.begin(),string.end()) ; std::cout << std::hex << set.to_ullong() << ' ' << string << ' ' << (crc ? "crc:ok" : "crc:failure") << '\n' ; } static void convert(Rpi::Peripheral *rpi,Ui::ArgL *argL) { auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ; auto wait = !argL->pop_if("-n") ; argL->finalize() ; using Bang = Device::Ds18x20::Bang ; try { Bang(rpi,pin).convert() ; // [todo] retry } catch (Bang::Error &e) { std::cerr << "start conversion error:" << e.what() << '\n' ; exit(1) ; } if (wait) { unsigned count = 1 ; Proceed: ; try { auto busy = Bang(rpi,pin).isBusy() ; while (busy) { busy = Bang(rpi,pin).isBusy() ; ++count ; } } catch (Bang::Error &e) { if (0 == strcmp(e.what(),"reset")) { std::cerr << "got suspended while setting the bus low\n" ; exit(1) ; } goto Proceed ; } // [todo] measure and display the time it takes to finish // (this piece of information might be quite interesting) try { // this does only word on a single drop bus auto pad = Bang(rpi,pin).readPad() ; print(pad) ; auto ull = pad.to_ullong() ; auto temp = static_cast<int16_t>(ull & 0xffff) ; auto mode = static_cast<unsigned>((ull >> 37) & 0x3) ; auto div = 2u << mode ; std::cout << static_cast<double>(temp) / div << '\n' ; } catch (Bang::Error &e) { std::cerr << "read scratch-pad error:" << e.what() << '\n' ; exit(1) ; } } } static void pad(Rpi::Peripheral *rpi,Ui::ArgL *argL) { auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ; argL->finalize() ; using Bang = Device::Ds18x20::Bang ; try { auto pad = Bang(rpi,pin).readPad() ; print(pad) ; } catch (Bang::Error &e) { std::cerr << "error:" << e.what() << '\n' ; exit(1) ; } } static void rom(Rpi::Peripheral *rpi,Ui::ArgL *argL) { using Bang = Device::Ds18x20::Bang ; auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ; argL->finalize() ; try { auto address = Bang(rpi,pin).address() ; if (address) print(*address) ; else std::cout << "no device present\n" ; } catch (Bang::Error &e) { std::cerr << "error:" << e.what() << '\n' ; exit(1) ; } } static void search(Rpi::Peripheral *rpi,Ui::ArgL *argL) { using Bang = Device::Ds18x20::Bang ; auto pin = Ui::strto(argL->pop(),Rpi::Pin()) ; argL->finalize() ; Bang bang(rpi,pin) ; auto first = [&bang] { Retry: ; try { return bang.first() ; } catch (Bang::Error &e) { std::cerr << "error:" << e.what() << '\n' ; goto Retry ; } } ; auto address = first() ; auto next = [&bang](Bang::Address const &address) { Retry: ; try { return bang.next(address) ; } catch (Bang::Error &e) { std::cerr << "error:" << e.what() << '\n' ; goto Retry ; } } ; while (address) { print(*address) ; address = next(*address) ; } } void Console::Device::Ds18x20::invoke(Rpi::Peripheral *rpi,Ui::ArgL *argL) { if (argL->empty() || argL->peek() == "help") { std::cout << "arguments: OPTION PIN\n" << '\n' << "rom = read 64-bit ROM code\n" << "pad = read 72-bit scratch pad\n" ; return ; } std::string arg = argL->pop() ; if (false) ; else if (arg == "convert") convert(rpi,argL) ; else if (arg == "rom") rom(rpi,argL) ; else if (arg == "pad") pad(rpi,argL) ; else if (arg == "search") search(rpi,argL) ; else throw std::runtime_error("not supported option:<"+arg+'>') ; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: macrconf.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2007-10-09 15:30:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFX_MACROCONF_HXX #define _SFX_MACROCONF_HXX #ifndef _SAL_CONFIG_H_ #include "sal/config.h" #endif #ifndef INCLUDED_SFX2_DLLAPI_H #include "sfx2/dllapi.h" #endif #ifndef _SAL_TYPES_H_ #include "sal/types.h" #endif #ifndef _ERRCODE_HXX //autogen #include <tools/errcode.hxx> #endif #define _SVSTDARR_USHORTS #include <svtools/svstdarr.hxx> // SvUShorts #include <sfx2/evntconf.hxx> class SfxMacroInfo; class SfxSlot; class SfxMacroInfoItem; class SfxObjectShell; class BasicManager; struct SfxMacroConfig_Impl; class SbMethod; class SbxValue; class SbxObject; class SbxArray; class SvStream; class SvxMacro; typedef SfxMacroInfo* SfxMacroInfoPtr; //#if 0 // _SOLAR__PRIVATE SV_DECL_PTRARR(SfxMacroInfoArr_Impl, SfxMacroInfoPtr, 5, 5) //#else //class SfxMacroInfoArr_Impl; //#endif class SFX2_DLLPUBLIC SfxMacroInfo { friend class SfxMacroConfig; friend class SfxEventConfiguration; friend SvStream& operator >> (SvStream& rStream, SfxMacroInfo& rInfo); friend SvStream& operator << (SvStream& rStream, const SfxMacroInfo& rInfo); String* pHelpText; sal_uInt16 nRefCnt; sal_Bool bAppBasic; String aLibName; String aModuleName; String aMethodName; sal_uInt16 nSlotId; SfxSlot* pSlot; public: SfxMacroInfo( const String& rURL ); SfxMacroInfo( bool _bAppBasic = true ); SfxMacroInfo( bool _bAppBasic, const String& rQualifiedName ); SfxMacroInfo(SfxMacroInfo& rOther); SfxMacroInfo(bool _bAppBasic, const String& rLibName, const String& rModuleName, const String& rMethodName); ~SfxMacroInfo(); sal_Bool operator==(const SfxMacroInfo& rOther) const; int Load (SvStream&); int Store (SvStream&); String GetMacroName() const; String GetQualifiedName() const; String GetFullQualifiedName() const; BasicManager* GetBasicManager() const; String GetBasicName() const; String GetHelpText() const; sal_Bool IsAppMacro() const { return bAppBasic; } const String& GetModuleName() const { return aModuleName; } const String& GetLibName() const { return aLibName; } const String& GetMethodName() const { return aMethodName; } sal_uInt16 GetSlotId() const { return nSlotId; } SfxSlot* GetSlot() const { return pSlot; } sal_Bool Compare( const SvxMacro& ) const; void SetHelpText( const String& rText ); String GetURL() const; }; //ASDBG obsolete >= 582 //ASDBG class ::com::sun::star::uno::Reference< ::com::sun::star::script::XEngine > ; //ASDBG class ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > ; class SFX2_DLLPUBLIC SfxMacroConfig { friend class SfxEventConfiguration; SAL_DLLPRIVATE static SfxMacroConfig* pMacroConfig; SfxMacroConfig_Impl* pImp; SvUShorts aIdArray; public: SfxMacroConfig(); ~SfxMacroConfig(); static SfxMacroConfig* GetOrCreate(); static String RequestHelp( sal_uInt16 nId ); static sal_Bool IsMacroSlot( sal_uInt16 nId ); static sal_Bool IsBasic( SbxObject*, const String&, BasicManager* ); static ErrCode Call( SbxObject*, const String&, BasicManager*, SbxArray *pArgs=NULL, SbxValue *pRet=NULL ); //ASDBG obsolete >= 582 //ASDBG static void CallStarScript( const ::com::sun::star::uno::Reference< ::com::sun::star::script::XEngine > & rxEngine, const String & rCode, //ASDBG const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & rSource, void *pArgs, void *pRet ); static SbMethod* GetMethod_Impl( const String&, BasicManager* ); sal_uInt16 GetSlotId(SfxMacroInfoPtr); void ReleaseSlotId(sal_uInt16 nId); void RegisterSlotId(sal_uInt16 nId); const SfxMacroInfoPtr GetMacroInfo(sal_uInt16 nId) const; sal_Bool ExecuteMacro(sal_uInt16 nId, const String& rArgs ) const; sal_Bool ExecuteMacro( SfxObjectShell*, const SvxMacro*, const String& ) const; sal_Bool CheckMacro(sal_uInt16 nId) const; sal_Bool CheckMacro( SfxObjectShell*, const SvxMacro* ) const; //#if 0 // _SOLAR__PRIVATE SAL_DLLPRIVATE static void Release_Impl(); SAL_DLLPRIVATE const SfxMacroInfoPtr GetMacroInfo_Impl( const SvxMacro *pMacro ) const; DECL_DLLPRIVATE_LINK( CallbackHdl_Impl, SfxMacroConfig*); DECL_DLLPRIVATE_LINK( EventHdl_Impl, SfxMacroInfo*); //#endif }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.150); FILE MERGED 2008/04/01 15:38:27 thb 1.3.150.3: #i85898# Stripping all external header guards 2008/04/01 12:40:36 thb 1.3.150.2: #i85898# Stripping all external header guards 2008/03/31 13:37:56 rt 1.3.150.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: macrconf.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SFX_MACROCONF_HXX #define _SFX_MACROCONF_HXX #include "sal/config.h" #include "sfx2/dllapi.h" #include "sal/types.h" #include <tools/errcode.hxx> #define _SVSTDARR_USHORTS #include <svtools/svstdarr.hxx> // SvUShorts #include <sfx2/evntconf.hxx> class SfxMacroInfo; class SfxSlot; class SfxMacroInfoItem; class SfxObjectShell; class BasicManager; struct SfxMacroConfig_Impl; class SbMethod; class SbxValue; class SbxObject; class SbxArray; class SvStream; class SvxMacro; typedef SfxMacroInfo* SfxMacroInfoPtr; //#if 0 // _SOLAR__PRIVATE SV_DECL_PTRARR(SfxMacroInfoArr_Impl, SfxMacroInfoPtr, 5, 5) //#else //class SfxMacroInfoArr_Impl; //#endif class SFX2_DLLPUBLIC SfxMacroInfo { friend class SfxMacroConfig; friend class SfxEventConfiguration; friend SvStream& operator >> (SvStream& rStream, SfxMacroInfo& rInfo); friend SvStream& operator << (SvStream& rStream, const SfxMacroInfo& rInfo); String* pHelpText; sal_uInt16 nRefCnt; sal_Bool bAppBasic; String aLibName; String aModuleName; String aMethodName; sal_uInt16 nSlotId; SfxSlot* pSlot; public: SfxMacroInfo( const String& rURL ); SfxMacroInfo( bool _bAppBasic = true ); SfxMacroInfo( bool _bAppBasic, const String& rQualifiedName ); SfxMacroInfo(SfxMacroInfo& rOther); SfxMacroInfo(bool _bAppBasic, const String& rLibName, const String& rModuleName, const String& rMethodName); ~SfxMacroInfo(); sal_Bool operator==(const SfxMacroInfo& rOther) const; int Load (SvStream&); int Store (SvStream&); String GetMacroName() const; String GetQualifiedName() const; String GetFullQualifiedName() const; BasicManager* GetBasicManager() const; String GetBasicName() const; String GetHelpText() const; sal_Bool IsAppMacro() const { return bAppBasic; } const String& GetModuleName() const { return aModuleName; } const String& GetLibName() const { return aLibName; } const String& GetMethodName() const { return aMethodName; } sal_uInt16 GetSlotId() const { return nSlotId; } SfxSlot* GetSlot() const { return pSlot; } sal_Bool Compare( const SvxMacro& ) const; void SetHelpText( const String& rText ); String GetURL() const; }; //ASDBG obsolete >= 582 //ASDBG class ::com::sun::star::uno::Reference< ::com::sun::star::script::XEngine > ; //ASDBG class ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > ; class SFX2_DLLPUBLIC SfxMacroConfig { friend class SfxEventConfiguration; SAL_DLLPRIVATE static SfxMacroConfig* pMacroConfig; SfxMacroConfig_Impl* pImp; SvUShorts aIdArray; public: SfxMacroConfig(); ~SfxMacroConfig(); static SfxMacroConfig* GetOrCreate(); static String RequestHelp( sal_uInt16 nId ); static sal_Bool IsMacroSlot( sal_uInt16 nId ); static sal_Bool IsBasic( SbxObject*, const String&, BasicManager* ); static ErrCode Call( SbxObject*, const String&, BasicManager*, SbxArray *pArgs=NULL, SbxValue *pRet=NULL ); //ASDBG obsolete >= 582 //ASDBG static void CallStarScript( const ::com::sun::star::uno::Reference< ::com::sun::star::script::XEngine > & rxEngine, const String & rCode, //ASDBG const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & rSource, void *pArgs, void *pRet ); static SbMethod* GetMethod_Impl( const String&, BasicManager* ); sal_uInt16 GetSlotId(SfxMacroInfoPtr); void ReleaseSlotId(sal_uInt16 nId); void RegisterSlotId(sal_uInt16 nId); const SfxMacroInfoPtr GetMacroInfo(sal_uInt16 nId) const; sal_Bool ExecuteMacro(sal_uInt16 nId, const String& rArgs ) const; sal_Bool ExecuteMacro( SfxObjectShell*, const SvxMacro*, const String& ) const; sal_Bool CheckMacro(sal_uInt16 nId) const; sal_Bool CheckMacro( SfxObjectShell*, const SvxMacro* ) const; //#if 0 // _SOLAR__PRIVATE SAL_DLLPRIVATE static void Release_Impl(); SAL_DLLPRIVATE const SfxMacroInfoPtr GetMacroInfo_Impl( const SvxMacro *pMacro ) const; DECL_DLLPRIVATE_LINK( CallbackHdl_Impl, SfxMacroConfig*); DECL_DLLPRIVATE_LINK( EventHdl_Impl, SfxMacroInfo*); //#endif }; #endif <|endoftext|>
<commit_before>/** * @file nystroem_method_impl.hpp * @author Ryan Curtin * @author Marcus Edel * * Implementation of the Nystroem method for approximating a kernel matrix. */ #ifndef __MLPACK_METHODS_NYSTROEM_METHOD_NYSTROEM_METHOD_IMPL_HPP #define __MLPACK_METHODS_NYSTROEM_METHOD_NYSTROEM_METHOD_IMPL_HPP // In case it hasn't been included yet. #include "nystroem_method.hpp" namespace mlpack { namespace kernel { template<typename KernelType, typename PointSelectionPolicy> NystroemMethod<KernelType, PointSelectionPolicy>::NystroemMethod( const arma::mat& data, KernelType& kernel, const size_t rank) : data(data), kernel(kernel), rank(rank) { } template<typename KernelType, typename PointSelectionPolicy> void NystroemMethod<KernelType, PointSelectionPolicy>::GetKernelMatrix( const arma::mat* seletedData, arma::mat& miniKernel, arma::mat& semiKernel) { // Assemble mini-kernel matrix. for (size_t i = 0; i < rank; ++i) for (size_t j = 0; j < rank; ++j) miniKernel(i, j) = kernel.Evaluate(seletedData->col(i), seletedData->col(j)); // Construct semi-kernel matrix with interactions between selected data and // all points. for (size_t i = 0; i < data.n_cols; ++i) for (size_t j = 0; j < rank; ++j) semiKernel(i, j) = kernel.Evaluate(data.col(i), seletedData->col(j)); // Clean the memory. delete seletedData; } template<typename KernelType, typename PointSelectionPolicy> void NystroemMethod<KernelType, PointSelectionPolicy>::GetKernelMatrix( const arma::vec& selectedPoints, arma::mat& miniKernel, arma::mat& semiKernel) { // Assemble mini-kernel matrix. for (size_t i = 0; i < rank; ++i) for (size_t j = 0; j < rank; ++j) miniKernel(i, j) = kernel.Evaluate(data.col(selectedPoints(i)), data.col(selectedPoints(j))); // Construct semi-kernel matrix with interactions between selected points and // all points. for (size_t i = 0; i < data.n_cols; ++i) for (size_t j = 0; j < rank; ++j) semiKernel(i, j) = kernel.Evaluate(data.col(i), data.col(selectedPoints(j))); } template<typename KernelType, typename PointSelectionPolicy> void NystroemMethod<KernelType, PointSelectionPolicy>::Apply(arma::mat& output) { arma::mat miniKernel(rank, rank); arma::mat semiKernel(data.n_cols, rank); GetKernelMatrix(PointSelectionPolicy::Select(data, rank), miniKernel, semiKernel); // Singular value decomposition mini-kernel matrix. arma::mat U, V; arma::vec s; arma::svd(U, s, V, miniKernel); // Construct the output matrix. arma::mat normalization = (U * arma::diagmat(1.0 / sqrt(s))); output = semiKernel * normalization * V; } }; // namespace kernel }; // namespace mlpack #endif <commit_msg>Avoid direct multiplication with a diagmat.<commit_after>/** * @file nystroem_method_impl.hpp * @author Ryan Curtin * @author Marcus Edel * * Implementation of the Nystroem method for approximating a kernel matrix. */ #ifndef __MLPACK_METHODS_NYSTROEM_METHOD_NYSTROEM_METHOD_IMPL_HPP #define __MLPACK_METHODS_NYSTROEM_METHOD_NYSTROEM_METHOD_IMPL_HPP // In case it hasn't been included yet. #include "nystroem_method.hpp" namespace mlpack { namespace kernel { template<typename KernelType, typename PointSelectionPolicy> NystroemMethod<KernelType, PointSelectionPolicy>::NystroemMethod( const arma::mat& data, KernelType& kernel, const size_t rank) : data(data), kernel(kernel), rank(rank) { } template<typename KernelType, typename PointSelectionPolicy> void NystroemMethod<KernelType, PointSelectionPolicy>::GetKernelMatrix( const arma::mat* seletedData, arma::mat& miniKernel, arma::mat& semiKernel) { // Assemble mini-kernel matrix. for (size_t i = 0; i < rank; ++i) for (size_t j = 0; j < rank; ++j) miniKernel(i, j) = kernel.Evaluate(seletedData->col(i), seletedData->col(j)); // Construct semi-kernel matrix with interactions between selected data and // all points. for (size_t i = 0; i < data.n_cols; ++i) for (size_t j = 0; j < rank; ++j) semiKernel(i, j) = kernel.Evaluate(data.col(i), seletedData->col(j)); // Clean the memory. delete seletedData; } template<typename KernelType, typename PointSelectionPolicy> void NystroemMethod<KernelType, PointSelectionPolicy>::GetKernelMatrix( const arma::vec& selectedPoints, arma::mat& miniKernel, arma::mat& semiKernel) { // Assemble mini-kernel matrix. for (size_t i = 0; i < rank; ++i) for (size_t j = 0; j < rank; ++j) miniKernel(i, j) = kernel.Evaluate(data.col(selectedPoints(i)), data.col(selectedPoints(j))); // Construct semi-kernel matrix with interactions between selected points and // all points. for (size_t i = 0; i < data.n_cols; ++i) for (size_t j = 0; j < rank; ++j) semiKernel(i, j) = kernel.Evaluate(data.col(i), data.col(selectedPoints(j))); } template<typename KernelType, typename PointSelectionPolicy> void NystroemMethod<KernelType, PointSelectionPolicy>::Apply(arma::mat& output) { arma::mat miniKernel(rank, rank); arma::mat semiKernel(data.n_cols, rank); GetKernelMatrix(PointSelectionPolicy::Select(data, rank), miniKernel, semiKernel); // Singular value decomposition mini-kernel matrix. arma::mat U, V; arma::vec s; arma::svd(U, s, V, miniKernel); // Construct the output matrix. arma::mat normalization = arma::diagmat(1.0 / sqrt(s)); output = semiKernel * U * normalization * V; } }; // namespace kernel }; // namespace mlpack #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ik_singleton.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-07 16:17:13 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef ARY_IDL_IK_SINGLETON_HXX #define ARY_IDL_IK_SINGLETON_HXX // USED SERVICES // BASE CLASSES #include <ary/idl/ik_ce.hxx> // COMPONENTS // PARAMETERS namespace ary { namespace idl { namespace ifc_singleton { using ifc_ce::Dyn_CeIterator; using ifc_ce::DocText; struct attr: public ifc_ce::attr { static Type_id AssociatedService( const CodeEntity & i_ce ); }; struct xref : public ifc_ce::xref { }; struct doc : public ifc_ce::doc { }; } // namespace ifc_singleton } // namespace idl } // namespace ary #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.80); FILE MERGED 2008/03/28 16:01:23 rt 1.2.80.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ik_singleton.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef ARY_IDL_IK_SINGLETON_HXX #define ARY_IDL_IK_SINGLETON_HXX // USED SERVICES // BASE CLASSES #include <ary/idl/ik_ce.hxx> // COMPONENTS // PARAMETERS namespace ary { namespace idl { namespace ifc_singleton { using ifc_ce::Dyn_CeIterator; using ifc_ce::DocText; struct attr: public ifc_ce::attr { static Type_id AssociatedService( const CodeEntity & i_ce ); }; struct xref : public ifc_ce::xref { }; struct doc : public ifc_ce::doc { }; } // namespace ifc_singleton } // namespace idl } // namespace ary #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: all_tags.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-11-15 13:31:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <precomp.h> #include <ary/info/all_tags.hxx> // NOT FULLY DEFINED SERVICES #include <limits> #include <ary/info/infodisp.hxx> #include <adc_cl.hxx> namespace ary { namespace info { //***************************** StdTag ***********************// StdTag::StdTag( E_AtTagId i_eId ) : eId(i_eId), // aText, pNext(0) { } bool StdTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { // Does nothing // KORR // Should be a logical exception: // csv_assert(false); return false; } UINT8 StdTag::NrOfSpecialMeaningTokens() const { return 0; } AtTag * StdTag::GetFollower() { if (pNext != 0) return pNext->GetFollower(); pNext = new StdTag(eId); return pNext; } void StdTag::do_StoreAt( DocuDisplay & o_rDisplay ) const { o_rDisplay.Display_StdTag( *this ); } DocuText * StdTag::Text() { return &aText; } //***************************** BaseTag ***********************// BaseTag::BaseTag() : // sBase // aText pNext(0) { } bool BaseTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { if ( i_nNr == 1 ) { sBase.AssignText(i_sText,"::"); return true; } return false; } const char * BaseTag::Title() const { return "Base Classes"; } UINT8 BaseTag::NrOfSpecialMeaningTokens() const { return 1; } AtTag * BaseTag::GetFollower() { if (pNext != 0) return pNext->GetFollower(); pNext = new BaseTag; return pNext; } DocuText * BaseTag::Text() { return &aText; } //***************************** ExceptionTag ***********************// ExceptionTag::ExceptionTag() : // sException, // aText pNext(0) { } bool ExceptionTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { if ( i_nNr == 1 ) { sException.AssignText(i_sText,"::"); return true; } return false; } const char * ExceptionTag::Title() const { return "Thrown Exceptions"; } UINT8 ExceptionTag::NrOfSpecialMeaningTokens() const { return 1; } AtTag * ExceptionTag::GetFollower() { if (pNext != 0) return pNext->GetFollower(); pNext = new ExceptionTag; return pNext; } DocuText * ExceptionTag::Text() { return &aText; } //***************************** ImplementsTag ***********************// ImplementsTag::ImplementsTag() : // sBase // aText pNext(0) { } bool ImplementsTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { if ( i_nNr == 1 ) { sName.AssignText(i_sText,"::"); } else { GetFollower()->Add_SpecialMeaningToken(i_sText,1); } return true; } const char * ImplementsTag::Title() const { return "Implements"; } UINT8 ImplementsTag::NrOfSpecialMeaningTokens() const { return std::numeric_limits<UINT8>::max(); } AtTag * ImplementsTag::GetFollower() { if (pNext != 0) return pNext->GetFollower(); pNext = new ImplementsTag; return pNext; } DocuText * ImplementsTag::Text() { return 0; } //***************************** KeywordTag ***********************// KeywordTag::KeywordTag() // : sKeys { } bool KeywordTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { sKeys.push_back(i_sText); return true; } const char * KeywordTag::Title() const { return "Keywords"; } UINT8 KeywordTag::NrOfSpecialMeaningTokens() const { return std::numeric_limits<UINT8>::max(); } AtTag * KeywordTag::GetFollower() { return this; } DocuText * KeywordTag::Text() { return 0; } //***************************** ParameterTag ***********************// ParameterTag::ParameterTag() : // sName // aText pNext(0) { } bool ParameterTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { if ( i_nNr == 1 ) { sName = i_sText; return true; } else if (i_nNr == 2) { uintt nLen = strlen(i_sText); if (*i_sText == '[' AND i_sText[nLen-1] == ']') { sValidRange = udmstri(i_sText+1, nLen-2); return true; } } return false; } UINT8 ParameterTag::NrOfSpecialMeaningTokens() const { return 2; } AtTag * ParameterTag::GetFollower() { if (pNext != 0) return pNext->GetFollower(); return pNext = new ParameterTag; } DocuText * ParameterTag::Text() { return &aText; } void ParameterTag::do_StoreAt( DocuDisplay & o_rDisplay ) const { o_rDisplay.Display_ParameterTag( *this ); } //***************************** SeeTag ***********************// SeeTag::SeeTag() // : sReferences { } bool SeeTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { static QualifiedName aNull_; sReferences.push_back(aNull_); sReferences.back().AssignText(i_sText,"::"); return true; } const char * SeeTag::Title() const { return "See Also"; } UINT8 SeeTag::NrOfSpecialMeaningTokens() const { return std::numeric_limits<UINT8>::max(); } AtTag * SeeTag::GetFollower() { return this; } void SeeTag::do_StoreAt( DocuDisplay & o_rDisplay ) const { o_rDisplay.Display_SeeTag( *this ); } DocuText * SeeTag::Text() { return 0; } //***************************** TemplateTag ***********************// TemplateTag::TemplateTag() : // sName // aText pNext(0) { } bool TemplateTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { if ( i_nNr == 1 ) { sName = i_sText; return true; } return false; } const char * TemplateTag::Title() const { return "Template Parameters"; } UINT8 TemplateTag::NrOfSpecialMeaningTokens() const { return 1; } AtTag * TemplateTag::GetFollower() { if (pNext != 0) return pNext->GetFollower(); return pNext = new TemplateTag; } void TemplateTag::do_StoreAt( DocuDisplay & o_rDisplay ) const { o_rDisplay.Display_TemplateTag( *this ); } DocuText * TemplateTag::Text() { return &aText; } //***************************** LabelTag ***********************// LabelTag::LabelTag() : sLabel() { } bool LabelTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { if ( i_nNr == 1 AND sLabel.length() == 0 ) { sLabel = i_sText; return true; } // KORR_FUTURE // else // Throw exception because of double label. return false; } const char * LabelTag::Title() const { return "Label"; } UINT8 LabelTag::NrOfSpecialMeaningTokens() const { return 1; } AtTag * LabelTag::GetFollower() { return this; } DocuText * LabelTag::Text() { return 0; } //***************************** SinceTag ***********************// SinceTag::SinceTag() : sVersion() { } bool SinceTag::Add_SpecialMeaningToken( const char * i_sText, intt ) { const char cCiphersend = '9' + 1; if ( sVersion.empty() AND NOT csv::in_range('0', *i_sText, cCiphersend) AND autodoc::CommandLine::Get_().DoesTransform_SinceTag() ) { return true; } if (sVersion.empty()) { sVersion = i_sText; } else { StreamLock sHelp(100); sVersion = sHelp() << sVersion << " " << i_sText << c_str; } return true; } const char * SinceTag::Title() const { return "Label"; } UINT8 SinceTag::NrOfSpecialMeaningTokens() const { return UINT8(-1); } AtTag * SinceTag::GetFollower() { return this; } void SinceTag::do_StoreAt( DocuDisplay & o_rDisplay ) const { o_rDisplay.Display_SinceTag( *this ); } DocuText * SinceTag::Text() { return 0; } } // namespace info } // namespace ary <commit_msg>INTEGRATION: CWS ooo19126 (1.3.18); FILE MERGED 2005/09/05 13:10:25 rt 1.3.18.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: all_tags.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:08:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include <ary/info/all_tags.hxx> // NOT FULLY DEFINED SERVICES #include <limits> #include <ary/info/infodisp.hxx> #include <adc_cl.hxx> namespace ary { namespace info { //***************************** StdTag ***********************// StdTag::StdTag( E_AtTagId i_eId ) : eId(i_eId), // aText, pNext(0) { } bool StdTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { // Does nothing // KORR // Should be a logical exception: // csv_assert(false); return false; } UINT8 StdTag::NrOfSpecialMeaningTokens() const { return 0; } AtTag * StdTag::GetFollower() { if (pNext != 0) return pNext->GetFollower(); pNext = new StdTag(eId); return pNext; } void StdTag::do_StoreAt( DocuDisplay & o_rDisplay ) const { o_rDisplay.Display_StdTag( *this ); } DocuText * StdTag::Text() { return &aText; } //***************************** BaseTag ***********************// BaseTag::BaseTag() : // sBase // aText pNext(0) { } bool BaseTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { if ( i_nNr == 1 ) { sBase.AssignText(i_sText,"::"); return true; } return false; } const char * BaseTag::Title() const { return "Base Classes"; } UINT8 BaseTag::NrOfSpecialMeaningTokens() const { return 1; } AtTag * BaseTag::GetFollower() { if (pNext != 0) return pNext->GetFollower(); pNext = new BaseTag; return pNext; } DocuText * BaseTag::Text() { return &aText; } //***************************** ExceptionTag ***********************// ExceptionTag::ExceptionTag() : // sException, // aText pNext(0) { } bool ExceptionTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { if ( i_nNr == 1 ) { sException.AssignText(i_sText,"::"); return true; } return false; } const char * ExceptionTag::Title() const { return "Thrown Exceptions"; } UINT8 ExceptionTag::NrOfSpecialMeaningTokens() const { return 1; } AtTag * ExceptionTag::GetFollower() { if (pNext != 0) return pNext->GetFollower(); pNext = new ExceptionTag; return pNext; } DocuText * ExceptionTag::Text() { return &aText; } //***************************** ImplementsTag ***********************// ImplementsTag::ImplementsTag() : // sBase // aText pNext(0) { } bool ImplementsTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { if ( i_nNr == 1 ) { sName.AssignText(i_sText,"::"); } else { GetFollower()->Add_SpecialMeaningToken(i_sText,1); } return true; } const char * ImplementsTag::Title() const { return "Implements"; } UINT8 ImplementsTag::NrOfSpecialMeaningTokens() const { return std::numeric_limits<UINT8>::max(); } AtTag * ImplementsTag::GetFollower() { if (pNext != 0) return pNext->GetFollower(); pNext = new ImplementsTag; return pNext; } DocuText * ImplementsTag::Text() { return 0; } //***************************** KeywordTag ***********************// KeywordTag::KeywordTag() // : sKeys { } bool KeywordTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { sKeys.push_back(i_sText); return true; } const char * KeywordTag::Title() const { return "Keywords"; } UINT8 KeywordTag::NrOfSpecialMeaningTokens() const { return std::numeric_limits<UINT8>::max(); } AtTag * KeywordTag::GetFollower() { return this; } DocuText * KeywordTag::Text() { return 0; } //***************************** ParameterTag ***********************// ParameterTag::ParameterTag() : // sName // aText pNext(0) { } bool ParameterTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { if ( i_nNr == 1 ) { sName = i_sText; return true; } else if (i_nNr == 2) { uintt nLen = strlen(i_sText); if (*i_sText == '[' AND i_sText[nLen-1] == ']') { sValidRange = udmstri(i_sText+1, nLen-2); return true; } } return false; } UINT8 ParameterTag::NrOfSpecialMeaningTokens() const { return 2; } AtTag * ParameterTag::GetFollower() { if (pNext != 0) return pNext->GetFollower(); return pNext = new ParameterTag; } DocuText * ParameterTag::Text() { return &aText; } void ParameterTag::do_StoreAt( DocuDisplay & o_rDisplay ) const { o_rDisplay.Display_ParameterTag( *this ); } //***************************** SeeTag ***********************// SeeTag::SeeTag() // : sReferences { } bool SeeTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { static QualifiedName aNull_; sReferences.push_back(aNull_); sReferences.back().AssignText(i_sText,"::"); return true; } const char * SeeTag::Title() const { return "See Also"; } UINT8 SeeTag::NrOfSpecialMeaningTokens() const { return std::numeric_limits<UINT8>::max(); } AtTag * SeeTag::GetFollower() { return this; } void SeeTag::do_StoreAt( DocuDisplay & o_rDisplay ) const { o_rDisplay.Display_SeeTag( *this ); } DocuText * SeeTag::Text() { return 0; } //***************************** TemplateTag ***********************// TemplateTag::TemplateTag() : // sName // aText pNext(0) { } bool TemplateTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { if ( i_nNr == 1 ) { sName = i_sText; return true; } return false; } const char * TemplateTag::Title() const { return "Template Parameters"; } UINT8 TemplateTag::NrOfSpecialMeaningTokens() const { return 1; } AtTag * TemplateTag::GetFollower() { if (pNext != 0) return pNext->GetFollower(); return pNext = new TemplateTag; } void TemplateTag::do_StoreAt( DocuDisplay & o_rDisplay ) const { o_rDisplay.Display_TemplateTag( *this ); } DocuText * TemplateTag::Text() { return &aText; } //***************************** LabelTag ***********************// LabelTag::LabelTag() : sLabel() { } bool LabelTag::Add_SpecialMeaningToken( const char * i_sText, intt i_nNr ) { if ( i_nNr == 1 AND sLabel.length() == 0 ) { sLabel = i_sText; return true; } // KORR_FUTURE // else // Throw exception because of double label. return false; } const char * LabelTag::Title() const { return "Label"; } UINT8 LabelTag::NrOfSpecialMeaningTokens() const { return 1; } AtTag * LabelTag::GetFollower() { return this; } DocuText * LabelTag::Text() { return 0; } //***************************** SinceTag ***********************// SinceTag::SinceTag() : sVersion() { } bool SinceTag::Add_SpecialMeaningToken( const char * i_sText, intt ) { const char cCiphersend = '9' + 1; if ( sVersion.empty() AND NOT csv::in_range('0', *i_sText, cCiphersend) AND autodoc::CommandLine::Get_().DoesTransform_SinceTag() ) { return true; } if (sVersion.empty()) { sVersion = i_sText; } else { StreamLock sHelp(100); sVersion = sHelp() << sVersion << " " << i_sText << c_str; } return true; } const char * SinceTag::Title() const { return "Label"; } UINT8 SinceTag::NrOfSpecialMeaningTokens() const { return UINT8(-1); } AtTag * SinceTag::GetFollower() { return this; } void SinceTag::do_StoreAt( DocuDisplay & o_rDisplay ) const { o_rDisplay.Display_SinceTag( *this ); } DocuText * SinceTag::Text() { return 0; } } // namespace info } // namespace ary <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: reposy.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:15:06 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // VERSION: Autodoc 2.2 #include <precomp.h> #include <reposy.hxx> // NOT FULLY DECLARED SERVICES #include <ary/x_ary.hxx> #include <ary/actions.hxx> #include <idl/i_reposypart.hxx> // S P L I T // #include <store/storage.hxx> #include <store/strg_ifc.hxx> #include <id_gener.hxx> #include <cpp/c_gate.hxx> #include <loc/l_gate.hxx> namespace ary { namespace { static Dyn<RepositoryCenter> pTheOldInstance_(0); } namespace n22 { using ::ary::Command; using ::ary::X_Ary; //***************** Repository ************// namespace { static Dyn<RepositoryCenter> pTheInstance_(0); } Repository & Repository::Create_() { if ( pTheInstance_ ) throw X_Ary(X_Ary::x_MultipleRepository); pTheInstance_ = new RepositoryCenter; // KORR_FUTURE // Create the Cpp repository: ::ary::Repository::Create_(0); return *pTheInstance_; } Repository & Repository::The_() { if ( NOT pTheInstance_ ) throw X_Ary(X_Ary::x_MissingRepository); return *pTheInstance_; } void Repository::Destroy_() { pTheInstance_ = 0; // KORR_FUTURE // Destroythe Cpp repository: ::ary::Repository::Destroy_(); } //***************** RepositoryCenter ************// RepositoryCenter::RepositoryCenter() : sDisplayedName(), aLocation(), #if 0 // Version 2.2 pCppPartition(), #endif // Version 2.2 pIdlPartition() { } RepositoryCenter::~RepositoryCenter() { } void RepositoryCenter::RunCommand_ProduceAllSecondaries() { // KORR_FUTURE } void RepositoryCenter::RunCommand_Statistic( ::ary::action::Statistic & io_rCommand ) { // KORR_FUTURE } void RepositoryCenter::do_Perform( Command & io_rCommand ) { io_rCommand.Run(*this); } const String & RepositoryCenter::inq_Name() const { return sDisplayedName; } bool RepositoryCenter::inq_HasIdl() const { return bool(pIdlPartition); } bool RepositoryCenter::inq_HasCpp() const { return pTheOldInstance_->HasCpp(); } const ::ary::idl::Gate & RepositoryCenter::inq_Gate_Idl() const { return const_cast< RepositoryCenter& >(*this).access_Gate_Idl(); } const ::ary::cpp::DisplayGate & RepositoryCenter::inq_Gate_Cpp() const { return pTheOldInstance_->DisplayGate_Cpp(); } ::ary::idl::Gate & RepositoryCenter::access_Gate_Idl() { if (NOT pIdlPartition) pIdlPartition = new idl::RepositoryPartition(*this); return pIdlPartition->TheGate(); } ::ary::cpp::RwGate & RepositoryCenter::access_Gate_Cpp() { return pTheOldInstance_->RwGate_Cpp(); } void RepositoryCenter::do_Set_Name(const String & i_sName) { sDisplayedName = i_sName; pTheOldInstance_->Set_Name(i_sName); } #if 0 // Version 2.2 /* cpp::Gate & RepositoryCenter::access_Gate_Cpp() { csv_assert( pCppPartition ); return pCppPartition->TheGate(); } const cpp::Gate & RepositoryCenter::inq_Gate_Cpp() const { csv_assert( pCppPartition ); return pCppPartition->TheGate(); } */ #endif // Version 2.2 } // namespace n22 /* ClassType-Ids ------------- cpp 1000 idl 2000 corba 3000 java 4000 information 5000 logic location 6000 phys location 7000 sec. prod. 8000 cpp --- Namespace 1000 Class 1001 Enum 1002 Typedef 1003 Function 1004 Variable 1005 EnumValue 1006 NamespaceAlias 1007 BuiltInType 1200 CeType_Final 1201 CeType_Extern 1202 PtrType 1211 RefType 1212 ConstType 1221 VolatileType 1222 ArrayType 1230 TemplateInstance 1235 FunctionPtr 1240 DataMemberPtr 1250 OperationMemberPtr 1260 TplParam_Type 1301 TplParam_Value 1302 OpSignature 1400 Define 1601 Macro 1602 idl --- Module 2000 Interface 2001 Function 2002 Service 2003 Property 2004 Enum 2005 EnumValue 2006 Typedef 2007 Struct 2008 StructElement 2009 Exception 2010 ConstantGroup 2011 Constant 2012 Singleton 2013 Attribute 2014 SglIfcService 2015 SglIfcSingleton 2016 BuiltInType 2200 CeType 2201 Sequence 2202 ExplicitType 2203 ExplicitNameRoom 2204 TemplateParamType 2205 java ---- Package 4000 Interface 4001 Class 4002 info ---- CodeInformation (IDL) 11002 */ // S P L I T // struct RepositoryCenter::CheshireCat { // DATA String sName; Dyn<store::Storage> pStorage; Dyn<Storage_Ifc> pStorage_Ifc; Dyn<IdGenerator> pIdGenerator; Dyn<cpp::Gate> pGate_Cpp; Dyn<loc::Gate> pGate_Locations; bool bHasCppContent; CheshireCat( DYN IdGenerator & let_drIds ); ~CheshireCat(); }; Repository & Repository::Create_( DYN IdGenerator * let_dpIds ) { csv_assert( NOT pTheOldInstance_ ); DYN IdGenerator * dpIds = let_dpIds != 0 ? let_dpIds : new Std_IdGenerator; pTheOldInstance_ = new RepositoryCenter( *dpIds ); return *pTheOldInstance_; } Repository & Repository::The_() { csv_assert( pTheOldInstance_ ); return *pTheOldInstance_; } void Repository::Destroy_() { pTheOldInstance_ = 0; } RepositoryCenter::RepositoryCenter( DYN IdGenerator & let_drIds ) : pi( new CheshireCat(let_drIds) ) { } RepositoryCenter::~RepositoryCenter() { } bool RepositoryCenter::HasCpp() const { return pi->bHasCppContent; } void RepositoryCenter::Set_Name( const String & i_name ) { pi->sName = i_name; } const cpp::DisplayGate & RepositoryCenter::inq_DisplayGate_Cpp() const { return *pi->pGate_Cpp; } const udmstri & RepositoryCenter::inq_Name() const { return pi->sName; } cpp::RwGate & RepositoryCenter::access_RwGate_Cpp() { pi->bHasCppContent = true; return *pi->pGate_Cpp; } RepositoryCenter:: CheshireCat::CheshireCat( DYN IdGenerator & let_drIds ) : sName(), pStorage(0), pStorage_Ifc(0), pIdGenerator( &let_drIds ), pGate_Cpp(0), pGate_Locations(0), bHasCppContent(false) { pStorage = new store::Storage; pStorage_Ifc = new Storage_Ifc( *pStorage ); pGate_Locations = new loc::Gate( pStorage_Ifc->Ifc_Locations(), *pIdGenerator ); pGate_Cpp = new cpp::Gate( *pStorage_Ifc, *pIdGenerator, *pGate_Locations ); } RepositoryCenter:: CheshireCat::~CheshireCat() { } } // namespace ary <commit_msg>INTEGRATION: CWS warnings01 (1.6.4); FILE MERGED 2005/10/18 08:35:57 np 1.6.4.1: #i53898#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: reposy.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-06-19 11:55:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // VERSION: Autodoc 2.2 #include <precomp.h> #include <reposy.hxx> // NOT FULLY DECLARED SERVICES #include <ary/x_ary.hxx> #include <ary/actions.hxx> #include <idl/i_reposypart.hxx> // S P L I T // #include <store/storage.hxx> #include <store/strg_ifc.hxx> #include <id_gener.hxx> #include <cpp/c_gate.hxx> #include <loc/l_gate.hxx> namespace ary { namespace { static Dyn<RepositoryCenter> pTheOldInstance_(0); } namespace n22 { using ::ary::Command; using ::ary::X_Ary; //***************** Repository ************// namespace { static Dyn<RepositoryCenter> pTheInstance_(0); } Repository & Repository::Create_() { if ( pTheInstance_ ) throw X_Ary(X_Ary::x_MultipleRepository); pTheInstance_ = new RepositoryCenter; // KORR_FUTURE // Create the Cpp repository: ::ary::Repository::Create_(0); return *pTheInstance_; } Repository & Repository::The_() { if ( NOT pTheInstance_ ) throw X_Ary(X_Ary::x_MissingRepository); return *pTheInstance_; } void Repository::Destroy_() { pTheInstance_ = 0; // KORR_FUTURE // Destroythe Cpp repository: ::ary::Repository::Destroy_(); } //***************** RepositoryCenter ************// RepositoryCenter::RepositoryCenter() : sDisplayedName(), aLocation(), #if 0 // Version 2.2 pCppPartition(), #endif // Version 2.2 pIdlPartition() { } RepositoryCenter::~RepositoryCenter() { } void RepositoryCenter::RunCommand_ProduceAllSecondaries() { // KORR_FUTURE } void RepositoryCenter::RunCommand_Statistic( ::ary::action::Statistic & ) { // KORR_FUTURE } void RepositoryCenter::do_Perform( Command & io_rCommand ) { io_rCommand.Run(*this); } const String & RepositoryCenter::inq_Name() const { return sDisplayedName; } bool RepositoryCenter::inq_HasIdl() const { return bool(pIdlPartition); } bool RepositoryCenter::inq_HasCpp() const { return pTheOldInstance_->HasCpp(); } const ::ary::idl::Gate & RepositoryCenter::inq_Gate_Idl() const { return const_cast< RepositoryCenter& >(*this).access_Gate_Idl(); } const ::ary::cpp::DisplayGate & RepositoryCenter::inq_Gate_Cpp() const { return pTheOldInstance_->DisplayGate_Cpp(); } ::ary::idl::Gate & RepositoryCenter::access_Gate_Idl() { if (NOT pIdlPartition) pIdlPartition = new idl::RepositoryPartition(*this); return pIdlPartition->TheGate(); } ::ary::cpp::RwGate & RepositoryCenter::access_Gate_Cpp() { return pTheOldInstance_->RwGate_Cpp(); } void RepositoryCenter::do_Set_Name(const String & i_sName) { sDisplayedName = i_sName; pTheOldInstance_->Set_Name(i_sName); } #if 0 // Version 2.2 /* cpp::Gate & RepositoryCenter::access_Gate_Cpp() { csv_assert( pCppPartition ); return pCppPartition->TheGate(); } const cpp::Gate & RepositoryCenter::inq_Gate_Cpp() const { csv_assert( pCppPartition ); return pCppPartition->TheGate(); } */ #endif // Version 2.2 } // namespace n22 /* ClassType-Ids ------------- cpp 1000 idl 2000 corba 3000 java 4000 information 5000 logic location 6000 phys location 7000 sec. prod. 8000 cpp --- Namespace 1000 Class 1001 Enum 1002 Typedef 1003 Function 1004 Variable 1005 EnumValue 1006 NamespaceAlias 1007 BuiltInType 1200 CeType_Final 1201 CeType_Extern 1202 PtrType 1211 RefType 1212 ConstType 1221 VolatileType 1222 ArrayType 1230 TemplateInstance 1235 FunctionPtr 1240 DataMemberPtr 1250 OperationMemberPtr 1260 TplParam_Type 1301 TplParam_Value 1302 OpSignature 1400 Define 1601 Macro 1602 idl --- Module 2000 Interface 2001 Function 2002 Service 2003 Property 2004 Enum 2005 EnumValue 2006 Typedef 2007 Struct 2008 StructElement 2009 Exception 2010 ConstantGroup 2011 Constant 2012 Singleton 2013 Attribute 2014 SglIfcService 2015 SglIfcSingleton 2016 BuiltInType 2200 CeType 2201 Sequence 2202 ExplicitType 2203 ExplicitNameRoom 2204 TemplateParamType 2205 java ---- Package 4000 Interface 4001 Class 4002 info ---- CodeInformation (IDL) 11002 */ // S P L I T // struct RepositoryCenter::CheshireCat { // DATA String sName; Dyn<store::Storage> pStorage; Dyn<Storage_Ifc> pStorage_Ifc; Dyn<IdGenerator> pIdGenerator; Dyn<cpp::Gate> pGate_Cpp; Dyn<loc::Gate> pGate_Locations; bool bHasCppContent; CheshireCat( DYN IdGenerator & let_drIds ); ~CheshireCat(); }; Repository & Repository::Create_( DYN IdGenerator * let_dpIds ) { csv_assert( NOT pTheOldInstance_ ); DYN IdGenerator * dpIds = let_dpIds != 0 ? let_dpIds : new Std_IdGenerator; pTheOldInstance_ = new RepositoryCenter( *dpIds ); return *pTheOldInstance_; } Repository & Repository::The_() { csv_assert( pTheOldInstance_ ); return *pTheOldInstance_; } void Repository::Destroy_() { pTheOldInstance_ = 0; } RepositoryCenter::RepositoryCenter( DYN IdGenerator & let_drIds ) : pi( new CheshireCat(let_drIds) ) { } RepositoryCenter::~RepositoryCenter() { } bool RepositoryCenter::HasCpp() const { return pi->bHasCppContent; } void RepositoryCenter::Set_Name( const String & i_name ) { pi->sName = i_name; } const cpp::DisplayGate & RepositoryCenter::inq_DisplayGate_Cpp() const { return *pi->pGate_Cpp; } const udmstri & RepositoryCenter::inq_Name() const { return pi->sName; } cpp::RwGate & RepositoryCenter::access_RwGate_Cpp() { pi->bHasCppContent = true; return *pi->pGate_Cpp; } RepositoryCenter:: CheshireCat::CheshireCat( DYN IdGenerator & let_drIds ) : sName(), pStorage(0), pStorage_Ifc(0), pIdGenerator( &let_drIds ), pGate_Cpp(0), pGate_Locations(0), bHasCppContent(false) { pStorage = new store::Storage; pStorage_Ifc = new Storage_Ifc( *pStorage ); pGate_Locations = new loc::Gate( pStorage_Ifc->Ifc_Locations(), *pIdGenerator ); pGate_Cpp = new cpp::Gate( *pStorage_Ifc, *pIdGenerator, *pGate_Locations ); } RepositoryCenter:: CheshireCat::~CheshireCat() { } } // namespace ary <|endoftext|>
<commit_before>#include "nodes/EANode/systems/ES/CMSA_ES.hpp" #include "core/utils/HierRNG.hpp" #include <math.h> #include <unsupported/Eigen/MatrixFunctions> CMSA_ES::CMSAMutation::CMSAMutation( unsigned int lambda ) : AdaptiveRealValueMutation() { this->lambda = lambda; } CMSA_ES::CMSAMutation::CMSAMutation( unsigned int lambda, double tau, double tauC ) : AdaptiveRealValueMutation() { this->lambda = lambda; this->tau = tau; this->tauC = tauC; this->tausCalculated = true; } void CMSA_ES::CMSAMutation::calculateTaus(Genome* initial) { unsigned int n = initial->genomeLength(); this->tau = 1/sqrt(2 * n); this->tauC = 1 + n * (n + 1)/(2 * this->mu); this->tausCalculated = true; } void CMSA_ES::CMSAMutation::calculateProperGenomeLengths( Genome* initial ) { this->initialGenomeLength = initial->genomeLength(); this->targetGenomeLength = initial->genomeLength() + 1; } Genome* CMSA_ES::CMSAMutation::addStdDevs(Genome* target) { std::vector<Gene*> newGenes = target->getGenomeCopy(); newGenes.push_back(this->stdDevLocus->getGene(1)); if (this->stdDevIndices.empty()) stdDevIndices.push_back(target->genomeLength()); return new Genome(newGenes, target->getSpeciesNode()); } void CMSA_ES::CMSAMutation::otherSetupSteps(Genome* initial) { unsigned int n = initial->genomeLength(); this->C = Eigen::MatrixXd::Identity(n, n); } void CMSA_ES::CMSAMutation::setMu(unsigned int mu) { this->mu = mu; } void CMSA_ES::CMSAMutation::calculateAverages(std::vector<Genome*> population) { unsigned int n = population[0]->genomeLength(); double sigmaSum; std::vector<double> xSums(n, 0); for (unsigned int i = 0; i < population.size(); i++) { // Since the stdDevs haven't necessarily been set up yet, we // need to account for that sigmaSum += !this->stdDevIndices.empty() ? population[i]->getIndex<double>(this->stdDevIndices[0]) : 1; std::vector<Gene*> genes = population[i]->getGenome(); for (unsigned int k = 0; k < n; k++) xSums[k] += genes[k]->getIndex(); } this->sigmaAvg = sigmaSum/this->mu; this->xAvg.clear(); for (unsigned int i = 0; i < xSums.size(); i++) this->xAvg.push_back(xSums[i]/this->mu); if (!this->skCollection.empty()) { Eigen::MatrixXd SAvg = Eigen::MatrixXd::Zero( this->initialGenomeLength, this->initialGenomeLength ); for (unsigned int i = 0; i < this->skCollection.size(); i++) { Eigen::VectorXd sk = this->skCollection[i]; SAvg += sk * sk.transpose(); } SAvg /= this->lambda; this->skCollection.clear(); this->C = (1 - 1/this->tauC) * this->C + SAvg/this->tauC; } } Genome* CMSA_ES::CMSAMutation::mutateProper(Genome* target) { std::vector<Gene*> newGenes = target->getGenomeCopy(); Gene* stdDevGene = newGenes[this->stdDevIndices[0]]; double sigmaK = this->sigmaAvg * exp(HierRNG::gaussian(0, 1) * this->tau); newGenes[this->stdDevIndices[0]] = stdDevGene->copy(sigmaK); delete(stdDevGene); Eigen::VectorXd R(this->initialGenomeLength); for (unsigned int i = 0; i < this->initialGenomeLength; i++) R[i] = HierRNG::gaussian(0, 1); Eigen::VectorXd sk = this->C.sqrt() * R; Eigen::VectorXd zk = sigmaK * sk; for (unsigned int i = 0; i < this->initialGenomeLength; i++) { Gene* originalGene = newGenes[i]; newGenes[i] = originalGene->copy(this->xAvg[i] + zk[i]); delete(originalGene); } this->skCollection.push_back(sk); return new Genome(newGenes, target->getSpeciesNode()); } <commit_msg>[CMSA_ES Mutation]: Fixed "uninitialized value" issues<commit_after>#include "nodes/EANode/systems/ES/CMSA_ES.hpp" #include "core/utils/HierRNG.hpp" #include <math.h> #include <unsupported/Eigen/MatrixFunctions> CMSA_ES::CMSAMutation::CMSAMutation( unsigned int lambda ) : AdaptiveRealValueMutation() { this->lambda = lambda; } CMSA_ES::CMSAMutation::CMSAMutation( unsigned int lambda, double tau, double tauC ) : AdaptiveRealValueMutation() { this->lambda = lambda; this->tau = tau; this->tauC = tauC; this->tausCalculated = true; } void CMSA_ES::CMSAMutation::calculateTaus(Genome* initial) { unsigned int n = initial->genomeLength(); this->tau = 1/sqrt(2 * n); this->tauC = 1 + n * (n + 1)/(2 * this->mu); this->tausCalculated = true; } void CMSA_ES::CMSAMutation::calculateProperGenomeLengths( Genome* initial ) { this->initialGenomeLength = initial->genomeLength(); this->targetGenomeLength = initial->genomeLength() + 1; } Genome* CMSA_ES::CMSAMutation::addStdDevs(Genome* target) { std::vector<Gene*> newGenes = target->getGenomeCopy(); newGenes.push_back(this->stdDevLocus->getGene(1)); if (this->stdDevIndices.empty()) this->stdDevIndices.push_back(target->genomeLength()); return new Genome(newGenes, target->getSpeciesNode()); } void CMSA_ES::CMSAMutation::otherSetupSteps(Genome* initial) { unsigned int n = initial->genomeLength(); this->C = Eigen::MatrixXd::Identity(n, n); } void CMSA_ES::CMSAMutation::setMu(unsigned int mu) { this->mu = mu; } void CMSA_ES::CMSAMutation::calculateAverages(std::vector<Genome*> population) { unsigned int n = population[0]->genomeLength(); double sigmaSum = 0; std::vector<double> xSums(n, 0); for (unsigned int i = 0; i < population.size(); i++) { // Since the stdDevs haven't necessarily been set up yet, we // need to account for that sigmaSum += !this->stdDevIndices.empty() ? population[i]->getIndex<double>(this->stdDevIndices[0]) : 1; std::vector<Gene*> genes = population[i]->getGenome(); for (unsigned int k = 0; k < n; k++) xSums[k] += genes[k]->getIndex(); } this->sigmaAvg = sigmaSum/this->mu; this->xAvg.clear(); for (unsigned int i = 0; i < xSums.size(); i++) this->xAvg.push_back(xSums[i]/this->mu); if (!this->skCollection.empty()) { Eigen::MatrixXd SAvg = Eigen::MatrixXd::Zero( this->initialGenomeLength, this->initialGenomeLength ); for (unsigned int i = 0; i < this->skCollection.size(); i++) { Eigen::VectorXd sk = this->skCollection[i]; SAvg += sk * sk.transpose(); } SAvg /= this->lambda; this->skCollection.clear(); this->C = (1 - 1/this->tauC) * this->C + SAvg/this->tauC; } } Genome* CMSA_ES::CMSAMutation::mutateProper(Genome* target) { std::vector<Gene*> newGenes = target->getGenomeCopy(); Gene* stdDevGene = newGenes[this->stdDevIndices[0]]; double sigmaK = this->sigmaAvg * exp(HierRNG::gaussian(0, 1) * this->tau); newGenes[this->stdDevIndices[0]] = stdDevGene->copy(sigmaK); delete(stdDevGene); Eigen::VectorXd R(this->initialGenomeLength); for (unsigned int i = 0; i < this->initialGenomeLength; i++) R[i] = HierRNG::gaussian(0, 1); Eigen::VectorXd sk = this->C.sqrt() * R; Eigen::VectorXd zk = sigmaK * sk; for (unsigned int i = 0; i < this->initialGenomeLength; i++) { Gene* originalGene = newGenes[i]; newGenes[i] = originalGene->copy(this->xAvg[i] + zk[i]); delete(originalGene); } this->skCollection.push_back(sk); return new Genome(newGenes, target->getSpeciesNode()); } <|endoftext|>
<commit_before>#pragma once #include "openMVG/robust_estimation/rand_sampling.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp" #include "openMVG/robust_estimation/robust_ransac_tools.hpp" #include <limits> #include <numeric> #include <iostream> #include <vector> #include <iterator> namespace openMVG { namespace robust{ //***************************************************** template<typename Kernel, typename Scorer> double iterativeReweightedLeastSquares(const Kernel &kernel, const Scorer &scorer, typename Kernel::Model &best_model, std::vector<std::size_t> &inliers, double mtheta = std::sqrt(2), std::size_t numIter = 4) { const std::size_t total_samples = kernel.NumSamples(); const std::size_t min_samples = Kernel::MINIMUM_LSSAMPLES; double theta = scorer.getThreshold(); // used in the iterations to update (reduce) the threshold value const double deltaTetha = (mtheta*theta - theta) / (numIter-1); std::vector<std::size_t> all_samples(total_samples); std::iota(all_samples.begin(), all_samples.end(), 0); // find inliers from best model with threshold theta inliers.clear(); scorer.Score(kernel, best_model, all_samples, &inliers, theta); if(inliers.size() < min_samples) { inliers.clear(); std::cerr << "[IRLS] returning cause inliers.size() < min_samples" << std::endl; return std::numeric_limits<double>::infinity(); } // LS model from the above inliers std::vector<typename Kernel::Model> models; kernel.FitLS(inliers, &models); assert(models.size()==1); // LS fitting must always return 1 model // change threshold for refinement theta *= mtheta; // iterative refinement for(std::size_t i = 0; i < numIter; ++i) { // find inliers on the best-so-far model // @todo maybe inliers instead of all samples to save some computation inliers.clear(); scorer.Score(kernel, models[0], all_samples, &inliers, theta); if(inliers.size() < min_samples) { inliers.clear(); std::cerr << "[IRLS] returning cause inliers.size() < min_samples" << std::endl; return std::numeric_limits<double>::infinity(); } // std::cout << "[IRLS] #" << i // << " theta: " << theta // << " num inliers: " << inliers.size() << std::endl; // compute the weights for the inliers std::vector<double> weights; kernel.computeWeights(models[0], inliers, weights); // LS with weights on inliers models.clear(); kernel.FitLS(inliers, &models, &weights); if(models.size() != 1) // LS fitting must always return 1 model { std::cerr << "[IRLS] found "<< models.size() << " models, aborting..." << std::endl; return std::numeric_limits<double>::infinity(); } // update the threshold theta -= deltaTetha; } assert(models.size()==1); best_model = models[0]; inliers.clear(); const double score = scorer.Score(kernel, best_model, all_samples, &inliers, theta); std::cout << "[IRLS] returning with num inliers: " << inliers.size() << " and score " << score << std::endl; return score; } template<typename Kernel, typename Scorer> double localOptimization(const Kernel &kernel, const Scorer &scorer, typename Kernel::Model &bestModel, std::vector<std::size_t> &bestInliers, double mtheta = std::sqrt(2), std::size_t numRep = 10, std::size_t minSampleSize = 10) { const std::size_t total_samples = kernel.NumSamples(); const std::size_t min_samples = Kernel::MINIMUM_LSSAMPLES; assert((total_samples > min_samples) && "[localOptimization] not enough data to estimate the model!"); const double theta = scorer.getThreshold(); std::vector<std::size_t> all_samples(total_samples); std::iota(all_samples.begin(), all_samples.end(), 0); std::size_t debugInit = 0; if(!bestInliers.empty()) { debugInit = bestInliers.size(); bestInliers.clear(); } double bestScore = scorer.Score(kernel, bestModel, all_samples, &bestInliers, theta); if(debugInit != 0) assert(debugInit == bestInliers.size()); // so far this is the best model std::size_t bestNumInliers = bestInliers.size(); std::cout << "[localOptim] so far best num inliers: " << bestNumInliers << std::endl; std::cout << "[localOptim] so far best model:\n" << bestModel << std::endl; std::cout << "[localOptim] so far best score: " << bestScore << std::endl; // find inliers from best model with larger threshold t*m over all the samples std::vector<std::size_t> inliersBase; scorer.Score(kernel, bestModel, all_samples, &inliersBase, theta*mtheta); assert((inliersBase.size() > min_samples) && "[localOptimization] not enough data in inliersBase to estimate the model!"); // LS model from the above inliers std::vector<typename Kernel::Model> models; kernel.FitLS(inliersBase, &models); assert(models.size()==1); // LS fitting must always return 1 model // find inliers with t again over all the samples inliersBase.clear(); scorer.Score(kernel, models[0], all_samples, &inliersBase, theta); // sample of size sampleSize from the last best inliers const std::size_t sampleSize = std::min(minSampleSize, inliersBase.size()/2); if(sampleSize <= Kernel::MINIMUM_LSSAMPLES) { std::cout << "breaking cause sampleSize is " << sampleSize << std::endl; return bestScore; } // do numRep resampling + iterative LS for(std::size_t i = 0; i < numRep; ++i) { std::vector<std::size_t> sample; UniformSample(sampleSize, inliersBase, &sample); assert(sampleSize > Kernel::MINIMUM_LSSAMPLES); assert(sample.size() > Kernel::MINIMUM_LSSAMPLES); // LS estimation from the sample models.clear(); kernel.FitLS(sample, &models); assert(models.size()==1); // LS fitting must always return 1 model // IRLS std::vector<std::size_t> inliers; const double score = iterativeReweightedLeastSquares(kernel, scorer, models[0], inliers); // store new best model if it is the case if((inliers.size() > bestNumInliers) || ((inliers.size() == bestNumInliers) && (score < bestScore))) { bestNumInliers = inliers.size(); bestScore = score; bestModel = models[0]; bestInliers.swap(inliers); std::cout << "[localOptim] new best num inliers: " << bestNumInliers << std::endl; } } return bestScore; } //@todo make visible parameters for the optimization step template<typename Kernel, typename Scorer> typename Kernel::Model LO_RANSAC( const Kernel &kernel, const Scorer &scorer, std::vector<std::size_t> *best_inliers = NULL, double *best_score = NULL, bool bVerbose = true, std::size_t max_iterations = 100, double outliers_probability = 1e-2) { assert(outliers_probability < 1.0); assert(outliers_probability > 0.0); std::size_t iteration = 0; const std::size_t min_samples = Kernel::MINIMUM_SAMPLES; const std::size_t total_samples = kernel.NumSamples(); const std::size_t really_max_iterations = 4096; std::size_t bestNumInliers = 0; double bestInlierRatio = 0.0; typename Kernel::Model bestModel; // Test if we have sufficient points for the kernel. if (total_samples < min_samples) { if (best_inliers) { best_inliers->clear(); } return bestModel; } // In this robust estimator, the scorer always works on all the data points // at once. So precompute the list ahead of time [0,..,total_samples]. std::vector<std::size_t> all_samples(total_samples); std::iota(all_samples.begin(), all_samples.end(), 0); std::vector<std::size_t> sample; for(iteration = 0; iteration < max_iterations; ++iteration) { UniformSample(min_samples, total_samples, &sample); std::vector<typename Kernel::Model> models; kernel.Fit(sample, &models); // Compute the inlier list for each fit. for(std::size_t i = 0; i < models.size(); ++i) { std::vector<std::size_t> inliers; double score = scorer.Score(kernel, models[i], all_samples, &inliers); std::cout << "sample="; std::sort(sample.begin(), sample.end()); std::copy(sample.begin(), sample.end(), std::ostream_iterator<std::size_t>(std::cout, ",")); std::cout << "\nmodel " << i << " e: " << score << std::endl; if (bestNumInliers <= inliers.size()) { bestModel = models[i]; //** LOCAL OPTIMIZATION std::cout << "Before Optim: num inliers: " << inliers.size() << " score: " << score << " Kernel::MINIMUM_LSSAMPLES: " << Kernel::MINIMUM_LSSAMPLES << std::endl; std::cout << "Model:\n" << bestModel << std::endl; if(inliers.size() > Kernel::MINIMUM_LSSAMPLES) { score = localOptimization(kernel, scorer, bestModel, inliers); } std::cout << "After Optim: num inliers: " << inliers.size() << " score: " << score << std::endl; std::cout << "Model:\n" << bestModel << std::endl; bestNumInliers = inliers.size(); bestInlierRatio = inliers.size() / double(total_samples); if (best_inliers) { best_inliers->swap(inliers); } if(bVerbose) { std::cout << " inliers=" << bestNumInliers << "/" << total_samples << " (iter=" << iteration << " ,i=" << i; std::cout << ",sample="; std::copy(sample.begin(), sample.end(), std::ostream_iterator<std::size_t>(std::cout, ",")); std::cout << ")"; } if (bestInlierRatio) { max_iterations = IterationsRequired(min_samples, outliers_probability, bestInlierRatio); // safeguard to not get stuck in a big number of iterations max_iterations = std::min(max_iterations, really_max_iterations); if(bVerbose) std::cout << " New max_iteration: " << max_iterations << std::endl; } } } } if (best_score) *best_score = bestNumInliers; if(bestNumInliers) kernel.Unnormalize(&bestModel); return bestModel; } } // namespace robust } // namespace openMVG<commit_msg>[robust] doc for loransac<commit_after>#pragma once #include "openMVG/robust_estimation/rand_sampling.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp" #include "openMVG/robust_estimation/robust_ransac_tools.hpp" #include <limits> #include <numeric> #include <iostream> #include <vector> #include <iterator> namespace openMVG { namespace robust{ /** * @brief It performs an iterative reweighted least square (IRLS) estimation of the problem * defined by \p Kernel. At each step it perform a LS estimation using weights * for each data element computed iteratively on some residual error. * This implementation follow the Algorithm 3 described in * * Karel Lebeda, Jiri Matas, Ondrej Chum: * Fixing the Locally Optimized RANSAC. BMVC 2012: 1-11 * * @tparam Kernel The kernel used in the LORansac estimator which must provide a * minimum solver and a LS solver, the latter used here for the IRLS * @see openMVG/robust_estimation/robust_estimator_LORansacKernelAdaptor.hpp * @tparam Scorer The scorer used in the LORansac estimator @see ScorerEvaluator * * @param[in] kernel The kernel used in the LORansac estimator. * @param[in] scorer The scorer used in the LORansac estimator. * @param[out] best_model The best model found at the end of the iterations. * @param[out] inliers The inliers supporting the best model. * @param[in] mtheta A threshold multiplier used to vary the threshold of the scorer. * @param[in] numIter The max number of iterations to run. * @return the score of the best model as computed by the Scorer, infinity if the * process does not converge. */ template<typename Kernel, typename Scorer> double iterativeReweightedLeastSquares(const Kernel &kernel, const Scorer &scorer, typename Kernel::Model &best_model, std::vector<std::size_t> &inliers, double mtheta = std::sqrt(2), std::size_t numIter = 4) { const std::size_t total_samples = kernel.NumSamples(); const std::size_t min_samples = Kernel::MINIMUM_LSSAMPLES; double theta = scorer.getThreshold(); // used in the iterations to update (reduce) the threshold value const double deltaTetha = (mtheta*theta - theta) / (numIter-1); std::vector<std::size_t> all_samples(total_samples); std::iota(all_samples.begin(), all_samples.end(), 0); // find inliers from best model with threshold theta inliers.clear(); scorer.Score(kernel, best_model, all_samples, &inliers, theta); if(inliers.size() < min_samples) { inliers.clear(); std::cerr << "[IRLS] returning cause inliers.size() < min_samples" << std::endl; return std::numeric_limits<double>::infinity(); } // LS model from the above inliers std::vector<typename Kernel::Model> models; kernel.FitLS(inliers, &models); assert(models.size()==1); // LS fitting must always return 1 model // change threshold for refinement theta *= mtheta; // iterative refinement for(std::size_t i = 0; i < numIter; ++i) { // find inliers on the best-so-far model // @todo maybe inliers instead of all samples to save some computation inliers.clear(); scorer.Score(kernel, models[0], all_samples, &inliers, theta); if(inliers.size() < min_samples) { inliers.clear(); std::cerr << "[IRLS] returning cause inliers.size() < min_samples" << std::endl; return std::numeric_limits<double>::infinity(); } // std::cout << "[IRLS] #" << i // << " theta: " << theta // << " num inliers: " << inliers.size() << std::endl; // compute the weights for the inliers std::vector<double> weights; kernel.computeWeights(models[0], inliers, weights); // LS with weights on inliers models.clear(); kernel.FitLS(inliers, &models, &weights); if(models.size() != 1) // LS fitting must always return 1 model { std::cerr << "[IRLS] found "<< models.size() << " models, aborting..." << std::endl; return std::numeric_limits<double>::infinity(); } // update the threshold theta -= deltaTetha; } assert(models.size()==1); best_model = models[0]; inliers.clear(); const double score = scorer.Score(kernel, best_model, all_samples, &inliers, theta); std::cout << "[IRLS] returning with num inliers: " << inliers.size() << " and score " << score << std::endl; return score; } /** * @brief The local optimization step used by LORansac. It takes as input a model * and its inliers computed by a minimal solver and refine the solution by using * IRLS (@see iterativeReweightedLeastSquares()). It first estimates a new model * using LS and its associated inliers. Then it repeatedly (\p numRep) re-estimate * a new model by LS on a randomly drawn sample of those inliers and then refine * the model by IRLS. The best found model (in terms of number of supporting inliers * is then returned. * * This implementation follow the Algorithm 2 described in * * Karel Lebeda, Jiri Matas, Ondrej Chum: * Fixing the Locally Optimized RANSAC. BMVC 2012: 1-11 * * @tparam Kernel The kernel used in the LORansac estimator which must provide a * minimum solver and a LS solver, the latter used here for the IRLS * @see openMVG/robust_estimation/robust_estimator_LORansacKernelAdaptor.hpp * @tparam Scorer The scorer used in the LORansac estimator @see ScorerEvaluator * * @param[in] kernel The kernel used in the LORansac estimator. * @param[in] scorer The scorer used in the LORansac estimator. * @param[in,out] best_model In input the model estimated by a minimum solver, as * output the best model found. * @param[out] bestInliers The inliers supporting the best model. * @param[in] mtheta A threshold multiplier used for IRLS. * @param[in] numRep The number of re-sampling/re-estimation of the model. * @param[in] minSampleSize Size of the inner sample used for re-estimation. * @return the best score of the best model as computed by Scorer. */ template<typename Kernel, typename Scorer> double localOptimization(const Kernel &kernel, const Scorer &scorer, typename Kernel::Model &bestModel, std::vector<std::size_t> &bestInliers, double mtheta = std::sqrt(2), std::size_t numRep = 10, std::size_t minSampleSize = 10) { const std::size_t total_samples = kernel.NumSamples(); const std::size_t min_samples = Kernel::MINIMUM_LSSAMPLES; assert((total_samples > min_samples) && "[localOptimization] not enough data to estimate the model!"); const double theta = scorer.getThreshold(); std::vector<std::size_t> all_samples(total_samples); std::iota(all_samples.begin(), all_samples.end(), 0); std::size_t debugInit = 0; if(!bestInliers.empty()) { debugInit = bestInliers.size(); bestInliers.clear(); } double bestScore = scorer.Score(kernel, bestModel, all_samples, &bestInliers, theta); if(debugInit != 0) assert(debugInit == bestInliers.size()); // so far this is the best model std::size_t bestNumInliers = bestInliers.size(); std::cout << "[localOptim] so far best num inliers: " << bestNumInliers << std::endl; std::cout << "[localOptim] so far best model:\n" << bestModel << std::endl; std::cout << "[localOptim] so far best score: " << bestScore << std::endl; // find inliers from best model with larger threshold t*m over all the samples std::vector<std::size_t> inliersBase; scorer.Score(kernel, bestModel, all_samples, &inliersBase, theta*mtheta); assert((inliersBase.size() > min_samples) && "[localOptimization] not enough data in inliersBase to estimate the model!"); // LS model from the above inliers std::vector<typename Kernel::Model> models; kernel.FitLS(inliersBase, &models); assert(models.size()==1); // LS fitting must always return 1 model // find inliers with t again over all the samples inliersBase.clear(); scorer.Score(kernel, models[0], all_samples, &inliersBase, theta); // sample of size sampleSize from the last best inliers const std::size_t sampleSize = std::min(minSampleSize, inliersBase.size()/2); if(sampleSize <= Kernel::MINIMUM_LSSAMPLES) { std::cout << "breaking cause sampleSize is " << sampleSize << std::endl; return bestScore; } // do numRep resampling + iterative LS for(std::size_t i = 0; i < numRep; ++i) { std::vector<std::size_t> sample; UniformSample(sampleSize, inliersBase, &sample); assert(sampleSize > Kernel::MINIMUM_LSSAMPLES); assert(sample.size() > Kernel::MINIMUM_LSSAMPLES); // LS estimation from the sample models.clear(); kernel.FitLS(sample, &models); assert(models.size()==1); // LS fitting must always return 1 model // IRLS std::vector<std::size_t> inliers; const double score = iterativeReweightedLeastSquares(kernel, scorer, models[0], inliers); // store new best model if it is the case if((inliers.size() > bestNumInliers) || ((inliers.size() == bestNumInliers) && (score < bestScore))) { bestNumInliers = inliers.size(); bestScore = score; bestModel = models[0]; bestInliers.swap(inliers); std::cout << "[localOptim] new best num inliers: " << bestNumInliers << std::endl; } } return bestScore; } //@todo make visible parameters for the optimization step /** * @brief Implementation of the LORansac framework. * * This implementation follow the Algorithm 1 described in * * Karel Lebeda, Jiri Matas, Ondrej Chum: * Fixing the Locally Optimized RANSAC. BMVC 2012: 1-11 * * @tparam Kernel The kernel used in the LORansac estimator which must provide a * minimum solver and a LS solver, the latter used here for the IRLS * @see openMVG/robust_estimation/robust_estimator_LORansacKernelAdaptor.hpp * @tparam Scorer The scorer used in the LORansac estimator @see ScorerEvaluator * * @param[in] kernel The kernel containing the problem to solve. * @param[in] scorer The scorer used to asses the model quality. * @param[out] best_inliers The indices of the samples supporting the best model. * @param[out] best_score The score of the best model, ie the number of inliers * supporting the best model. * @param[in] bVerbose Enable/Disable log messages * @param[in] max_iterations Maximum number of iterations for the ransac part. * @param[in] outliers_probability The wanted probability of picking outliers. * @return The best model found. */ template<typename Kernel, typename Scorer> typename Kernel::Model LO_RANSAC(const Kernel &kernel, const Scorer &scorer, std::vector<std::size_t> *best_inliers = NULL, double *best_score = NULL, bool bVerbose = true, std::size_t max_iterations = 100, double outliers_probability = 1e-2) { assert(outliers_probability < 1.0); assert(outliers_probability > 0.0); std::size_t iteration = 0; const std::size_t min_samples = Kernel::MINIMUM_SAMPLES; const std::size_t total_samples = kernel.NumSamples(); const std::size_t really_max_iterations = 4096; std::size_t bestNumInliers = 0; double bestInlierRatio = 0.0; typename Kernel::Model bestModel; // Test if we have sufficient points for the kernel. if (total_samples < min_samples) { if (best_inliers) { best_inliers->clear(); } return bestModel; } // In this robust estimator, the scorer always works on all the data points // at once. So precompute the list ahead of time [0,..,total_samples]. std::vector<std::size_t> all_samples(total_samples); std::iota(all_samples.begin(), all_samples.end(), 0); std::vector<std::size_t> sample; for(iteration = 0; iteration < max_iterations; ++iteration) { UniformSample(min_samples, total_samples, &sample); std::vector<typename Kernel::Model> models; kernel.Fit(sample, &models); // Compute the inlier list for each fit. for(std::size_t i = 0; i < models.size(); ++i) { std::vector<std::size_t> inliers; double score = scorer.Score(kernel, models[i], all_samples, &inliers); std::cout << "sample="; std::sort(sample.begin(), sample.end()); std::copy(sample.begin(), sample.end(), std::ostream_iterator<std::size_t>(std::cout, ",")); std::cout << "\nmodel " << i << " e: " << score << std::endl; if (bestNumInliers <= inliers.size()) { bestModel = models[i]; //** LOCAL OPTIMIZATION std::cout << "Before Optim: num inliers: " << inliers.size() << " score: " << score << " Kernel::MINIMUM_LSSAMPLES: " << Kernel::MINIMUM_LSSAMPLES << std::endl; std::cout << "Model:\n" << bestModel << std::endl; if(inliers.size() > Kernel::MINIMUM_LSSAMPLES) { score = localOptimization(kernel, scorer, bestModel, inliers); } std::cout << "After Optim: num inliers: " << inliers.size() << " score: " << score << std::endl; std::cout << "Model:\n" << bestModel << std::endl; bestNumInliers = inliers.size(); bestInlierRatio = inliers.size() / double(total_samples); if (best_inliers) { best_inliers->swap(inliers); } if(bVerbose) { std::cout << " inliers=" << bestNumInliers << "/" << total_samples << " (iter=" << iteration << " ,i=" << i; std::cout << ",sample="; std::copy(sample.begin(), sample.end(), std::ostream_iterator<std::size_t>(std::cout, ",")); std::cout << ")"; } if (bestInlierRatio) { max_iterations = IterationsRequired(min_samples, outliers_probability, bestInlierRatio); // safeguard to not get stuck in a big number of iterations max_iterations = std::min(max_iterations, really_max_iterations); if(bVerbose) std::cout << " New max_iteration: " << max_iterations << std::endl; } } } } if (best_score) *best_score = bestNumInliers; if(bestNumInliers) kernel.Unnormalize(&bestModel); return bestModel; } } // namespace robust } // namespace openMVG<|endoftext|>
<commit_before>#include <memory> #include <random> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <stdexcept> #include <cstdio> // only __FILE__ __LINE__ macros #include <map> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/rand.h> #include <openssl/pem.h> #include <openssl/bio.h> #include <openssl/x509.h> #include <cassert> #include "utils.h" using std::unique_ptr; using std::string; using std::cout; using std::cerr; using std::stringstream; using std::ifstream; using std::exception; using std::runtime_error; using std::map; using BN_ptr = std::unique_ptr<BIGNUM, decltype(&::BN_free)>; using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>; using EVP_KEY_ptr = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>; using BIO_FILE_ptr = std::unique_ptr<BIO, decltype(&::BIO_free)>; string seed_random_number_gen() { const int SEED_SZ = 128; int rc; //std::uniform_int_distribution<int> d(0, 9); //stringstream ss; //std::random_device rd1; // uses RDRND or /dev/urandom // for(int n = 0; n < SEED_SZ; ++n) { // ss << d(rd1); // } char buf[SEED_SZ]; int fd = open("/dev/random", O_RDONLY); if (fd == -1) { throw std::runtime_error("Err opening /dev/random" FILE_LINE); } int n = read(fd, buf, sizeof(buf)-1); if (n == -1) { throw std::runtime_error("Err reading /dev/random" FILE_LINE); } close(fd); cout << "Seeding SSL RNG from /dev/random...\n"; RAND_add(buf, sizeof(buf), n); buf[n] = '\0'; cout << "Generated random seed:\n"; cout << buf << '\n'; //string seed = ss.str(); //cout << seed << '\n'; // Seed the openssl RNG //cout << "Seeding SSL RNG from /dev/urandom...\n"; //RAND_add(seed.c_str(), seed.length(), seed.length()); rc = RAND_status(); if (rc != 1) throw std::runtime_error("Open SSL: " FILE_LINE); return string(buf); } void generate_key_pair(string& seed) { int rc; RSA_ptr rsa(RSA_new(), ::RSA_free); BN_ptr bn(BN_new(), ::BN_free); BIO_FILE_ptr pem1(BIO_new_file("rsa-public-1.pem", "w"), ::BIO_free); BIO_FILE_ptr pem3(BIO_new_file("rsa-private-1.pem", "w"), ::BIO_free); rc = BN_set_word(bn.get(), RSA_F4); if (rc != 1) throw std::runtime_error("Open SSL: " FILE_LINE); // Generate key rc = RSA_generate_key_ex(rsa.get(), 2048, bn.get(), NULL); if (rc != 1) throw std::runtime_error("Open SSL: " FILE_LINE); // Convert RSA to PKEY EVP_KEY_ptr pkey(EVP_PKEY_new(), ::EVP_PKEY_free); rc = EVP_PKEY_set1_RSA(pkey.get(), rsa.get()); if (rc != 1) throw std::runtime_error("Open SSL: " FILE_LINE); ////////// // Write public key in PKCS PEM rc = PEM_write_bio_RSAPublicKey(pem1.get(), rsa.get()); if (rc != 1) throw std::runtime_error("Open SSL: " FILE_LINE); // Write private key in PKCS PEM. rc = PEM_write_bio_PrivateKey(pem3.get(), pkey.get(), NULL, NULL, 0, NULL, NULL); if (rc != 1) throw std::runtime_error("Open SSL: " FILE_LINE); } int open_socket() { int fd; int retval; fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd == -1) { throw std::runtime_error("Could not open socket" FILE_LINE); } unlink(SOCK_NAME); sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, SOCK_NAME, sizeof(addr.sun_path)-1); retval = bind(fd, (struct sockaddr*)&addr, sizeof(addr)); if (retval == -1) { perror(NULL); throw std::runtime_error("bind() " FILE_LINE); } retval = listen(fd, 5); if (retval == -1) { throw std::runtime_error("listen() " FILE_LINE); } return fd; } void close_socket(int fd) { close(fd); /* remove the FIFO */ unlink(SOCK_NAME); } string read_socket(int fd) { char buf[MAX_BUF]; ssize_t num = read(fd, buf, MAX_BUF); if (num == -1) { throw std::runtime_error("read() " FILE_LINE); } printf("Received: %s\n", buf); return string(buf); } void write_socket(int fd) { ifstream pubkey_file; pubkey_file.open("rsa-public-1.pem"); string pubkey; string line; if (pubkey_file.is_open()) { while (getline(pubkey_file, line)) { cout << line << '\n'; pubkey += line; } pubkey_file.close(); } ssize_t num = write(fd, pubkey.c_str(), pubkey.length()+1); if (num == -1) { throw std::runtime_error("write() " FILE_LINE); } } int main(int argc, char* argv[]) { cout << "Starting token (pubkey) server...\n"; int fd = -1; fd = open_socket(); std::map<string, time_t> voters; try { for (;;) { string seed = seed_random_number_gen(); generate_key_pair(seed); int cli_fd = accept(fd, NULL, NULL); if (cli_fd == -1) { throw std::runtime_error("accept() " FILE_LINE); } string voter = read_socket(cli_fd); cout << "Handing out token (pubkey) for voter " << voter << '\n'; write_socket(cli_fd); voters.insert(std::make_pair(voter, time(nullptr))); close(cli_fd); } } catch (exception& ex) { cerr << ex.what() << '\n'; } catch (...) { cerr << "Unknown error!\n"; } close_socket(fd); return 0; } <commit_msg>Added give/deny token functionality<commit_after>#include <memory> #include <random> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <stdexcept> #include <cstdio> // only __FILE__ __LINE__ macros #include <map> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/rand.h> #include <openssl/pem.h> #include <openssl/bio.h> #include <openssl/x509.h> #include <cassert> #include "utils.h" using std::unique_ptr; using std::string; using std::cout; using std::cerr; using std::stringstream; using std::ifstream; using std::exception; using std::runtime_error; using std::map; using BN_ptr = std::unique_ptr<BIGNUM, decltype(&::BN_free)>; using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>; using EVP_KEY_ptr = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>; using BIO_FILE_ptr = std::unique_ptr<BIO, decltype(&::BIO_free)>; enum class TokenStatus { GIVE_TOKEN = 1, DENY_TOKEN = 2 }; string seed_random_number_gen() { const int SEED_SZ = 32; int rc; char buf[SEED_SZ]; int fd = open("/dev/random", O_RDONLY); if (fd == -1) { throw std::runtime_error("Err opening /dev/random" FILE_LINE); } int n = read(fd, buf, sizeof(buf)-1); if (n == -1) { throw std::runtime_error("Err reading /dev/random" FILE_LINE); } close(fd); cout << "Seeding SSL RNG from /dev/random...\n"; RAND_add(buf, sizeof(buf), n); buf[n] = '\0'; cout << "Generated random seed:\n"; cout << buf << '\n'; rc = RAND_status(); if (rc != 1) throw std::runtime_error("Open SSL (RAND_status()): " FILE_LINE); return string(buf); } void generate_key_pair(string& seed) { int rc; RSA_ptr rsa(RSA_new(), ::RSA_free); BN_ptr bn(BN_new(), ::BN_free); BIO_FILE_ptr pem1(BIO_new_file("rsa-public-1.pem", "w"), ::BIO_free); BIO_FILE_ptr pem3(BIO_new_file("rsa-private-1.pem", "w"), ::BIO_free); rc = BN_set_word(bn.get(), RSA_F4); if (rc != 1) throw std::runtime_error("Open SSL: " FILE_LINE); // Generate key rc = RSA_generate_key_ex(rsa.get(), 2048, bn.get(), NULL); if (rc != 1) throw std::runtime_error("Open SSL: " FILE_LINE); // Convert RSA to PKEY EVP_KEY_ptr pkey(EVP_PKEY_new(), ::EVP_PKEY_free); rc = EVP_PKEY_set1_RSA(pkey.get(), rsa.get()); if (rc != 1) throw std::runtime_error("Open SSL: " FILE_LINE); // Write public key in PKCS PEM rc = PEM_write_bio_RSAPublicKey(pem1.get(), rsa.get()); if (rc != 1) throw std::runtime_error("Open SSL: " FILE_LINE); // Write private key in PKCS PEM. rc = PEM_write_bio_PrivateKey(pem3.get(), pkey.get(), NULL, NULL, 0, NULL, NULL); if (rc != 1) throw std::runtime_error("Open SSL: " FILE_LINE); } int open_socket() { int fd; int retval; fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd == -1) { throw std::runtime_error("Could not open socket" FILE_LINE); } unlink(SOCK_NAME); sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, SOCK_NAME, sizeof(addr.sun_path)-1); retval = bind(fd, (struct sockaddr*)&addr, sizeof(addr)); if (retval == -1) { perror(NULL); throw std::runtime_error("bind() " FILE_LINE); } retval = listen(fd, 5); if (retval == -1) { throw std::runtime_error("listen() " FILE_LINE); } return fd; } void close_socket(int fd) { close(fd); /* remove the FIFO */ unlink(SOCK_NAME); } string read_socket(int fd) { char buf[MAX_BUF]; ssize_t num = read(fd, buf, MAX_BUF); if (num == -1) { throw std::runtime_error("read() " FILE_LINE); } printf("Received: %s\n", buf); return string(buf); } void write_socket(int fd, TokenStatus status) { string pubkey; if (status == TokenStatus::GIVE_TOKEN) { ifstream pubkey_file; pubkey_file.open("rsa-public-1.pem"); string line; if (pubkey_file.is_open()) { while (getline(pubkey_file, line)) { cout << line << '\n'; pubkey += line; } pubkey_file.close(); } } else { // DENY_TOKEN pubkey = "WARNING: TOKEN DENIED, VOTER ALREADY RECEIVED TOKEN!"; } ssize_t num = write(fd, pubkey.c_str(), pubkey.length()+1); if (num == -1) { throw std::runtime_error("write() " FILE_LINE); } } int main(int argc, char* argv[]) { cout << "Starting token (pubkey) server...\n"; int fd = -1; fd = open_socket(); std::map<string, time_t> voters; try { for (;;) { string seed = seed_random_number_gen(); generate_key_pair(seed); int cli_fd = accept(fd, NULL, NULL); if (cli_fd == -1) { throw std::runtime_error("accept() " FILE_LINE); } string voter = read_socket(cli_fd); auto it = voters.find(voter); if (it == voters.end()) { cout << "Handing out token (pubkey) for voter " << voter << '\n'; write_socket(cli_fd, TokenStatus::GIVE_TOKEN); } else { cout << "DENYING token (pubkey) for voter " << voter << '\n'; write_socket(cli_fd, TokenStatus::DENY_TOKEN); } voters.insert(std::make_pair(voter, time(nullptr))); close(cli_fd); } } catch (exception& ex) { cerr << ex.what() << '\n'; } catch (...) { cerr << "Unknown error!\n"; } close_socket(fd); return 0; } <|endoftext|>
<commit_before>#include "SimpleWindow.hpp" #include <QHBoxLayout> #include <QApplication> using namespace fast; void SimpleWindow::addRenderer(Renderer::pointer renderer) { mView->addRenderer(renderer); } void SimpleWindow::setMaximumFramerate(unsigned char framerate) { mFramerate = framerate; } SimpleWindow::SimpleWindow() { mFramerate = 25; mView = View::New(); QHBoxLayout *mainLayout = new QHBoxLayout; mainLayout->addWidget(mView.getPtr().get()); setLayout(mainLayout); setWindowTitle(tr("FAST")); } void SimpleWindow::runMainLoop() { show(); QApplication::exec(); } void SimpleWindow::keyPressEvent(QKeyEvent* event) { mView->keyPressEvent(event); } void SimpleWindow::mouseMoveEvent(QMouseEvent* event) { mView->mouseMoveEvent(event); } void SimpleWindow::mousePressEvent(QMouseEvent* event) { mView->mousePressEvent(event); } void SimpleWindow::mouseReleaseEvent(QMouseEvent* event) { mView->mouseReleaseEvent(event); } void SimpleWindow::setWindowSize(unsigned int w, unsigned int h) { this->resize(w,h); } <commit_msg>set default window size to 512 x 512<commit_after>#include "SimpleWindow.hpp" #include <QHBoxLayout> #include <QApplication> using namespace fast; void SimpleWindow::addRenderer(Renderer::pointer renderer) { mView->addRenderer(renderer); } void SimpleWindow::setMaximumFramerate(unsigned char framerate) { mFramerate = framerate; } SimpleWindow::SimpleWindow() { mFramerate = 25; mView = View::New(); QHBoxLayout *mainLayout = new QHBoxLayout; mainLayout->addWidget(mView.getPtr().get()); setLayout(mainLayout); setWindowTitle(tr("FAST")); resize(512,512); // default window size } void SimpleWindow::runMainLoop() { show(); QApplication::exec(); } void SimpleWindow::keyPressEvent(QKeyEvent* event) { mView->keyPressEvent(event); } void SimpleWindow::mouseMoveEvent(QMouseEvent* event) { mView->mouseMoveEvent(event); } void SimpleWindow::mousePressEvent(QMouseEvent* event) { mView->mousePressEvent(event); } void SimpleWindow::mouseReleaseEvent(QMouseEvent* event) { mView->mouseReleaseEvent(event); } void SimpleWindow::setWindowSize(unsigned int w, unsigned int h) { this->resize(w,h); } <|endoftext|>
<commit_before>// ***************************************************************************** // // Copyright (c) 2015, Southwest Research Institute® (SwRI®) // 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 Southwest Research Institute® (SwRI®) 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 <COPYRIGHT HOLDER> 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 <tile_map/tile_map_view.h> #include <cmath> #include <boost/lexical_cast.hpp> #include <boost/make_shared.hpp> #include <GL/gl.h> #include <ros/ros.h> #include <math_util/constants.h> #include <math_util/trig_util.h> #include <transform_util/earth_constants.h> #include <tile_map/image_cache.h> namespace tile_map { TileMapView::TileMapView() : base_url_("localhost"), extension_(".jpg"), max_level_(19), level_(-1), width_(100), height_(100) { ImageCachePtr image_cache = boost::make_shared<ImageCache>("/tmp/tile_map"); tile_cache_ = boost::make_shared<TextureCache>(image_cache); } void TileMapView::SetMaxLevel(int32_t level) { max_level_ = level; } void TileMapView::SetExtension(const std::string& extension) { extension_ = extension; } void TileMapView::SetBaseUrl(const std::string& url) { if (base_url_ != url) { base_url_ = url; level_ = -1; } } void TileMapView::SetTransform(const transform_util::Transform& transform) { transform_ = transform; // TODO: check if modified. for (size_t i = 0; i < tiles_.size(); i++) { tiles_[i].top_left_t = transform_ * tiles_[i].top_left; tiles_[i].top_right_t = transform_ * tiles_[i].top_right; tiles_[i].bottom_right_t = transform_ * tiles_[i].bottom_right; tiles_[i].bottom_left_t = transform_ * tiles_[i].bottom_left; } for (size_t i = 0; i < precache_above_.size(); i++) { precache_above_[i].top_left_t = transform_ * precache_above_[i].top_left; precache_above_[i].top_right_t = transform_ * precache_above_[i].top_right; precache_above_[i].bottom_right_t = transform_ * precache_above_[i].bottom_right; precache_above_[i].bottom_left_t = transform_ * precache_above_[i].bottom_left; } } void TileMapView::SetView( double latitude, double longitude, double scale, int32_t width, int32_t height) { latitude = std::max(-90.0, std::min(90.0, latitude)); longitude = std::max(-180.0, std::min(180.0, longitude)); double lat = math_util::ToRadians(latitude); // Calculate the current zoom level: // // According to http://wiki.openstreetmap.org/wiki/Zoom_levels: // meters_per_pixel = earth_circumference * cos(lat) / 2^(level + 8) // // Therefore, // level = log2(earth_circumference * cos(lat) / meters_per_pixel) - 8 // double lat_circumference = transform_util::_earth_equator_circumference * std::cos(lat) / scale; int32_t level = std::min((double)max_level_, std::max(0.0, std::ceil(std::log(lat_circumference) / std::log(2) - 8))); int64_t max_size = std::pow(2, level); int64_t center_x = std::min((double)max_size - 1.0, std::floor(((longitude + 180.0) / 360.0) * std::pow(2.0, level))); int64_t center_y = std::min((long double)max_size - 1.0, std::floor((1.0 - std::log(std::tan(lat) + 1.0 / std::cos(lat)) / math_util::_pi) / 2.0 * std::pow(2.0, level))); width_ = width; height_ = height; double max_dimension = std::max(width, height); double meters_per_pixel = transform_util::_earth_equator_circumference * std::cos(lat) / std::pow(2, level + 8); double tile_size = 256.0 * (meters_per_pixel / scale); int64_t size = std::max(1.0, std::min((double)max_size, std::ceil(0.5 * max_dimension / tile_size) * 2 + 1)); if (size > 50) { ROS_ERROR("Invalid map size: %ld", size); return; } if (size_ != size_ || level_ != level || center_x_ != center_x || center_y_ != center_y) { size_ = size; level_ = level; center_x_ = center_x; center_y_ = center_y; int64_t top = std::max(0L, center_y_ - size_ / 2); int64_t left = std::max(0L, center_x_ - size_ / 2); int64_t right = std::min(max_size, left + size_); int64_t bottom = std::min(max_size, top + size_); for (size_t i = 0; i < tiles_.size(); i++) { tile_cache_->AddTexture(tiles_[i].texture); } tiles_.clear(); for (int64_t i = top; i < bottom; i++) { for (int64_t j = left; j < right; j++) { Tile tile; InitializeTile(level_, j, i, tile); tiles_.push_back(tile); } } for (size_t i = 0; i < precache_above_.size(); i++) { tile_cache_->AddTexture(precache_above_[i].texture); } precache_above_.clear(); if (level_ > 0) { int64_t above_x = std::floor(((longitude + 180.0) / 360.0) * std::pow(2.0, level - 1)); int64_t above_y = std::floor((1.0 - std::log(std::tan(lat) + 1.0 / std::cos(lat)) / math_util::_pi) / 2.0 * std::pow(2.0, level - 1)); int64_t above_max_size = std::pow(2, level - 1); int64_t above_top = std::max(0L, above_y - (size_ - 1) / 2); int64_t above_left = std::max(0L, above_x - (size_ - 1) / 2); int64_t above_right = std::min(above_max_size, above_left + size_); int64_t above_bottom = std::min(above_max_size, above_top + size_); for (int64_t i = above_top; i < above_bottom; i++) { for (int64_t j = above_left; j < above_right; j++) { Tile tile; InitializeTile(level_ - 1, j, i, tile); precache_above_.push_back(tile); } } } } } void TileMapView::Draw() { glEnable(GL_TEXTURE_2D); for (size_t i = 0; i < precache_above_.size(); i++) { TexturePtr texture = precache_above_[i].texture; if (!texture) { bool failed; texture = tile_cache_->GetTexture(precache_above_[i].url_hash, precache_above_[i].url, failed); if (failed) { max_level_ = std::min(max_level_, precache_above_[i].level - 1); ROS_WARN("===== SETTING MAX LEVEL TO %d =====", max_level_); } } if (texture) { glBindTexture(GL_TEXTURE_2D, texture->id); glBegin(GL_TRIANGLES); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glTexCoord2f(0, 1); glVertex2d(precache_above_[i].top_left_t.x(), precache_above_[i].top_left_t.y()); glTexCoord2f(1, 1); glVertex2d(precache_above_[i].top_right_t.x(), precache_above_[i].top_right_t.y()); glTexCoord2f(1, 0); glVertex2d(precache_above_[i].bottom_right_t.x(), precache_above_[i].bottom_right_t.y()); glTexCoord2f(0, 1); glVertex2d(precache_above_[i].top_left_t.x(), precache_above_[i].top_left_t.y()); glTexCoord2f(1, 0); glVertex2d(precache_above_[i].bottom_right_t.x(), precache_above_[i].bottom_right_t.y()); glTexCoord2f(0, 0); glVertex2d(precache_above_[i].bottom_left_t.x(), precache_above_[i].bottom_left_t.y()); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); } } for (size_t i = 0; i < tiles_.size(); i++) { TexturePtr texture = tiles_[i].texture; if (!texture) { bool failed; texture = tile_cache_->GetTexture(tiles_[i].url_hash, tiles_[i].url, failed); if (failed) { max_level_ = std::min(max_level_, tiles_[i].level - 1); ROS_WARN("===== SETTING MAX LEVEL TO %d =====", max_level_); } } if (texture) { glBindTexture(GL_TEXTURE_2D, texture->id); glBegin(GL_TRIANGLES); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glTexCoord2f(0, 1); glVertex2d(tiles_[i].top_left_t.x(), tiles_[i].top_left_t.y()); glTexCoord2f(1, 1); glVertex2d(tiles_[i].top_right_t.x(), tiles_[i].top_right_t.y()); glTexCoord2f(1, 0); glVertex2d(tiles_[i].bottom_right_t.x(), tiles_[i].bottom_right_t.y()); glTexCoord2f(0, 1); glVertex2d(tiles_[i].top_left_t.x(), tiles_[i].top_left_t.y()); glTexCoord2f(1, 0); glVertex2d(tiles_[i].bottom_right_t.x(), tiles_[i].bottom_right_t.y()); glTexCoord2f(0, 0); glVertex2d(tiles_[i].bottom_left_t.x(), tiles_[i].bottom_left_t.y()); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); } } glDisable(GL_TEXTURE_2D); } void TileMapView::ToLatLon(int32_t level, int32_t x, int32_t y, double& latitude, double& longitude) { double n = std::pow(2, level); longitude = (double)x / n * 360.0 - 180.0; double r = math_util::_pi - math_util::_2pi * (double)y / n; latitude = math_util::_rad_2_deg * std::atan(0.5 * (std::exp(r) - std::exp(-r))); } void TileMapView::InitializeTile(int32_t level, int64_t x, int64_t y, Tile& tile) { tile.url = base_url_ + boost::lexical_cast<std::string>(level) + "/" + boost::lexical_cast<std::string>(x) + "/" + boost::lexical_cast<std::string>(y) + extension_; tile.url_hash = hash_function_(tile.url); tile.level = level; bool failed; tile.texture = tile_cache_->GetTexture(tile.url_hash, tile.url, failed); if (failed) { max_level_ = std::min(max_level_, level - 1); ROS_WARN("===== SETTING MAX LEVEL TO %d =====", max_level_); } double t_lat, t_lon; ToLatLon(level, x, y, t_lat, t_lon); tile.top_left = tf::Vector3(t_lon, t_lat, 0); tile.top_left_t = transform_ * tile.top_left; ToLatLon(level, x + 1, y, t_lat, t_lon); tile.top_right = tf::Vector3(t_lon, t_lat, 0); tile.top_right_t = transform_ * tile.top_right; ToLatLon(level, x + 1, y + 1, t_lat, t_lon); tile.bottom_right = tf::Vector3(t_lon, t_lat, 0); tile.bottom_right_t = transform_ * tile.bottom_right; ToLatLon(level, x, y + 1, t_lat, t_lon); tile.bottom_left = tf::Vector3(t_lon, t_lat, 0); tile.bottom_left_t = transform_ * tile.bottom_left; } } <commit_msg>only transform tile map when the transform changes<commit_after>// ***************************************************************************** // // Copyright (c) 2015, Southwest Research Institute® (SwRI®) // 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 Southwest Research Institute® (SwRI®) 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 <COPYRIGHT HOLDER> 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 <tile_map/tile_map_view.h> #include <cmath> #include <boost/lexical_cast.hpp> #include <boost/make_shared.hpp> #include <GL/gl.h> #include <ros/ros.h> #include <math_util/constants.h> #include <math_util/trig_util.h> #include <transform_util/earth_constants.h> #include <tile_map/image_cache.h> namespace tile_map { TileMapView::TileMapView() : base_url_("localhost"), extension_(".jpg"), max_level_(19), level_(-1), width_(100), height_(100) { ImageCachePtr image_cache = boost::make_shared<ImageCache>("/tmp/tile_map"); tile_cache_ = boost::make_shared<TextureCache>(image_cache); } void TileMapView::SetMaxLevel(int32_t level) { max_level_ = level; } void TileMapView::SetExtension(const std::string& extension) { extension_ = extension; } void TileMapView::SetBaseUrl(const std::string& url) { if (base_url_ != url) { base_url_ = url; level_ = -1; } } void TileMapView::SetTransform(const transform_util::Transform& transform) { if (transform.GetOrigin() == transform_.GetOrigin() && transform.GetOrientation() == transform_.GetOrientation()) { return; } transform_ = transform; for (size_t i = 0; i < tiles_.size(); i++) { tiles_[i].top_left_t = transform_ * tiles_[i].top_left; tiles_[i].top_right_t = transform_ * tiles_[i].top_right; tiles_[i].bottom_right_t = transform_ * tiles_[i].bottom_right; tiles_[i].bottom_left_t = transform_ * tiles_[i].bottom_left; } for (size_t i = 0; i < precache_above_.size(); i++) { precache_above_[i].top_left_t = transform_ * precache_above_[i].top_left; precache_above_[i].top_right_t = transform_ * precache_above_[i].top_right; precache_above_[i].bottom_right_t = transform_ * precache_above_[i].bottom_right; precache_above_[i].bottom_left_t = transform_ * precache_above_[i].bottom_left; } } void TileMapView::SetView( double latitude, double longitude, double scale, int32_t width, int32_t height) { latitude = std::max(-90.0, std::min(90.0, latitude)); longitude = std::max(-180.0, std::min(180.0, longitude)); double lat = math_util::ToRadians(latitude); // Calculate the current zoom level: // // According to http://wiki.openstreetmap.org/wiki/Zoom_levels: // meters_per_pixel = earth_circumference * cos(lat) / 2^(level + 8) // // Therefore, // level = log2(earth_circumference * cos(lat) / meters_per_pixel) - 8 // double lat_circumference = transform_util::_earth_equator_circumference * std::cos(lat) / scale; int32_t level = std::min((double)max_level_, std::max(0.0, std::ceil(std::log(lat_circumference) / std::log(2) - 8))); int64_t max_size = std::pow(2, level); int64_t center_x = std::min((double)max_size - 1.0, std::floor(((longitude + 180.0) / 360.0) * std::pow(2.0, level))); int64_t center_y = std::min((long double)max_size - 1.0, std::floor((1.0 - std::log(std::tan(lat) + 1.0 / std::cos(lat)) / math_util::_pi) / 2.0 * std::pow(2.0, level))); width_ = width; height_ = height; double max_dimension = std::max(width, height); double meters_per_pixel = transform_util::_earth_equator_circumference * std::cos(lat) / std::pow(2, level + 8); double tile_size = 256.0 * (meters_per_pixel / scale); int64_t size = std::max(1.0, std::min((double)max_size, std::ceil(0.5 * max_dimension / tile_size) * 2 + 1)); if (size > 50) { ROS_ERROR("Invalid map size: %ld", size); return; } if (size_ != size_ || level_ != level || center_x_ != center_x || center_y_ != center_y) { size_ = size; level_ = level; center_x_ = center_x; center_y_ = center_y; int64_t top = std::max(0L, center_y_ - size_ / 2); int64_t left = std::max(0L, center_x_ - size_ / 2); int64_t right = std::min(max_size, left + size_); int64_t bottom = std::min(max_size, top + size_); for (size_t i = 0; i < tiles_.size(); i++) { tile_cache_->AddTexture(tiles_[i].texture); } tiles_.clear(); for (int64_t i = top; i < bottom; i++) { for (int64_t j = left; j < right; j++) { Tile tile; InitializeTile(level_, j, i, tile); tiles_.push_back(tile); } } for (size_t i = 0; i < precache_above_.size(); i++) { tile_cache_->AddTexture(precache_above_[i].texture); } precache_above_.clear(); if (level_ > 0) { int64_t above_x = std::floor(((longitude + 180.0) / 360.0) * std::pow(2.0, level - 1)); int64_t above_y = std::floor((1.0 - std::log(std::tan(lat) + 1.0 / std::cos(lat)) / math_util::_pi) / 2.0 * std::pow(2.0, level - 1)); int64_t above_max_size = std::pow(2, level - 1); int64_t above_top = std::max(0L, above_y - (size_ - 1) / 2); int64_t above_left = std::max(0L, above_x - (size_ - 1) / 2); int64_t above_right = std::min(above_max_size, above_left + size_); int64_t above_bottom = std::min(above_max_size, above_top + size_); for (int64_t i = above_top; i < above_bottom; i++) { for (int64_t j = above_left; j < above_right; j++) { Tile tile; InitializeTile(level_ - 1, j, i, tile); precache_above_.push_back(tile); } } } } } void TileMapView::Draw() { glEnable(GL_TEXTURE_2D); for (size_t i = 0; i < precache_above_.size(); i++) { TexturePtr texture = precache_above_[i].texture; if (!texture) { bool failed; texture = tile_cache_->GetTexture(precache_above_[i].url_hash, precache_above_[i].url, failed); if (failed) { max_level_ = std::min(max_level_, precache_above_[i].level - 1); ROS_WARN("===== SETTING MAX LEVEL TO %d =====", max_level_); } } if (texture) { glBindTexture(GL_TEXTURE_2D, texture->id); glBegin(GL_TRIANGLES); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glTexCoord2f(0, 1); glVertex2d(precache_above_[i].top_left_t.x(), precache_above_[i].top_left_t.y()); glTexCoord2f(1, 1); glVertex2d(precache_above_[i].top_right_t.x(), precache_above_[i].top_right_t.y()); glTexCoord2f(1, 0); glVertex2d(precache_above_[i].bottom_right_t.x(), precache_above_[i].bottom_right_t.y()); glTexCoord2f(0, 1); glVertex2d(precache_above_[i].top_left_t.x(), precache_above_[i].top_left_t.y()); glTexCoord2f(1, 0); glVertex2d(precache_above_[i].bottom_right_t.x(), precache_above_[i].bottom_right_t.y()); glTexCoord2f(0, 0); glVertex2d(precache_above_[i].bottom_left_t.x(), precache_above_[i].bottom_left_t.y()); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); } } for (size_t i = 0; i < tiles_.size(); i++) { TexturePtr texture = tiles_[i].texture; if (!texture) { bool failed; texture = tile_cache_->GetTexture(tiles_[i].url_hash, tiles_[i].url, failed); if (failed) { max_level_ = std::min(max_level_, tiles_[i].level - 1); ROS_WARN("===== SETTING MAX LEVEL TO %d =====", max_level_); } } if (texture) { glBindTexture(GL_TEXTURE_2D, texture->id); glBegin(GL_TRIANGLES); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glTexCoord2f(0, 1); glVertex2d(tiles_[i].top_left_t.x(), tiles_[i].top_left_t.y()); glTexCoord2f(1, 1); glVertex2d(tiles_[i].top_right_t.x(), tiles_[i].top_right_t.y()); glTexCoord2f(1, 0); glVertex2d(tiles_[i].bottom_right_t.x(), tiles_[i].bottom_right_t.y()); glTexCoord2f(0, 1); glVertex2d(tiles_[i].top_left_t.x(), tiles_[i].top_left_t.y()); glTexCoord2f(1, 0); glVertex2d(tiles_[i].bottom_right_t.x(), tiles_[i].bottom_right_t.y()); glTexCoord2f(0, 0); glVertex2d(tiles_[i].bottom_left_t.x(), tiles_[i].bottom_left_t.y()); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); } } glDisable(GL_TEXTURE_2D); } void TileMapView::ToLatLon(int32_t level, int32_t x, int32_t y, double& latitude, double& longitude) { double n = std::pow(2, level); longitude = (double)x / n * 360.0 - 180.0; double r = math_util::_pi - math_util::_2pi * (double)y / n; latitude = math_util::_rad_2_deg * std::atan(0.5 * (std::exp(r) - std::exp(-r))); } void TileMapView::InitializeTile(int32_t level, int64_t x, int64_t y, Tile& tile) { tile.url = base_url_ + boost::lexical_cast<std::string>(level) + "/" + boost::lexical_cast<std::string>(x) + "/" + boost::lexical_cast<std::string>(y) + extension_; tile.url_hash = hash_function_(tile.url); tile.level = level; bool failed; tile.texture = tile_cache_->GetTexture(tile.url_hash, tile.url, failed); if (failed) { max_level_ = std::min(max_level_, level - 1); ROS_WARN("===== SETTING MAX LEVEL TO %d =====", max_level_); } double t_lat, t_lon; ToLatLon(level, x, y, t_lat, t_lon); tile.top_left = tf::Vector3(t_lon, t_lat, 0); tile.top_left_t = transform_ * tile.top_left; ToLatLon(level, x + 1, y, t_lat, t_lon); tile.top_right = tf::Vector3(t_lon, t_lat, 0); tile.top_right_t = transform_ * tile.top_right; ToLatLon(level, x + 1, y + 1, t_lat, t_lon); tile.bottom_right = tf::Vector3(t_lon, t_lat, 0); tile.bottom_right_t = transform_ * tile.bottom_right; ToLatLon(level, x, y + 1, t_lat, t_lon); tile.bottom_left = tf::Vector3(t_lon, t_lat, 0); tile.bottom_left_t = transform_ * tile.bottom_left; } } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \authors (rdo@rk9.bmstu.ru) \authors (lord.tiran@gmail.com) \date 10.05.2009 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <iostream> #define BOOST_TEST_MODULE RDORuntime_Fuzzy_Test #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdo_runtime.h" #include "simulator/runtime/rdo_fuzzy.h" // -------------------------------------------------------------------------------- OPEN_RDO_RUNTIME_NAMESPACE BOOST_AUTO_TEST_SUITE(RDORuntime_Fuzzy_Test) BOOST_AUTO_TEST_CASE(DefineAreaTest) { LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create(); BOOST_CHECK(pRuntime); LPDefineArea pDefineAreaEmpty = rdo::Factory<DefineArea>::create(); BOOST_CHECK(pDefineAreaEmpty); LPDefineArea pDefineArea = rdo::Factory<DefineArea>::create(1.0, 5.0); BOOST_CHECK(pDefineArea); RDOValue testValueFalse = 100; RDOValue testValueTrue = 3.0; BOOST_CHECK(pDefineArea->inDomain(testValueFalse)); BOOST_CHECK(pDefineArea->inDomain(testValueTrue)); } BOOST_AUTO_TEST_SUITE_END() // RDORuntime_Fuzzy_Test CLOSE_RDO_RUNTIME_NAMESPACE <commit_msg> - исправления<commit_after>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \authors (rdo@rk9.bmstu.ru) \authors (lord.tiran@gmail.com) \date 10.05.2009 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <iostream> #define BOOST_TEST_MODULE RDORuntime_Fuzzy_Test #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdo_runtime.h" #include "simulator/runtime/rdo_fuzzy.h" // -------------------------------------------------------------------------------- OPEN_RDO_RUNTIME_NAMESPACE BOOST_AUTO_TEST_SUITE(RDORuntime_Fuzzy_Test) BOOST_AUTO_TEST_CASE(DefineAreaTest) { LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create(); BOOST_CHECK(pRuntime); LPDefineArea pDefineAreaEmpty = rdo::Factory<DefineArea>::create(); BOOST_CHECK(pDefineAreaEmpty); LPDefineArea pDefineArea = rdo::Factory<DefineArea>::create(1.0, 5.0); BOOST_CHECK(pDefineArea); RDOValue testValueFalse = 100; RDOValue testValueTrue = 3.0; BOOST_CHECK_EQUAL(pDefineArea->inDomain(testValueFalse), false); BOOST_CHECK(pDefineArea->inDomain(testValueTrue)); } BOOST_AUTO_TEST_SUITE_END() // RDORuntime_Fuzzy_Test CLOSE_RDO_RUNTIME_NAMESPACE <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/metrics/stats_counters.h" #include "base/metrics/stats_table.h" #include "base/shared_memory.h" #include "base/stringprintf.h" #include "base/string_piece.h" #include "base/test/multiprocess_test.h" #include "base/threading/platform_thread.h" #include "base/threading/simple_thread.h" #include "base/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" namespace base { class StatsTableTest : public MultiProcessTest { public: void DeleteShmem(const std::string& name) { SharedMemory mem; mem.Delete(name); } }; // Open a StatsTable and verify that we can write to each of the // locations in the table. TEST_F(StatsTableTest, VerifySlots) { const std::string kTableName = "VerifySlotsStatTable"; const int kMaxThreads = 1; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); // Register a single thread. std::string thread_name = "mainThread"; int slot_id = table.RegisterThread(thread_name); EXPECT_NE(slot_id, 0); // Fill up the table with counters. std::string counter_base_name = "counter"; for (int index = 0; index < kMaxCounter; index++) { std::string counter_name = counter_base_name; base::StringAppendF(&counter_name, "counter.ctr%d", index); int counter_id = table.FindCounter(counter_name); EXPECT_GT(counter_id, 0); } // Try to allocate an additional thread. Verify it fails. slot_id = table.RegisterThread("too many threads"); EXPECT_EQ(slot_id, 0); // Try to allocate an additional counter. Verify it fails. int counter_id = table.FindCounter(counter_base_name); EXPECT_EQ(counter_id, 0); DeleteShmem(kTableName); } // CounterZero will continually be set to 0. const std::string kCounterZero = "CounterZero"; // Counter1313 will continually be set to 1313. const std::string kCounter1313 = "Counter1313"; // CounterIncrement will be incremented each time. const std::string kCounterIncrement = "CounterIncrement"; // CounterDecrement will be decremented each time. const std::string kCounterDecrement = "CounterDecrement"; // CounterMixed will be incremented by odd numbered threads and // decremented by even threads. const std::string kCounterMixed = "CounterMixed"; // The number of thread loops that we will do. const int kThreadLoops = 100; class StatsTableThread : public SimpleThread { public: StatsTableThread(std::string name, int id) : SimpleThread(name), id_(id) {} virtual void Run() OVERRIDE; private: int id_; }; void StatsTableThread::Run() { // Each thread will open the shared memory and set counters // concurrently in a loop. We'll use some pauses to // mixup the thread scheduling. StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); for (int index = 0; index < kThreadLoops; index++) { StatsCounter mixed_counter(kCounterMixed); // create this one in the loop zero_counter.Set(0); lucky13_counter.Set(1313); increment_counter.Increment(); decrement_counter.Decrement(); if (id_ % 2) mixed_counter.Decrement(); else mixed_counter.Increment(); PlatformThread::Sleep(TimeDelta::FromMilliseconds(index % 10)); } } // Create a few threads and have them poke on their counters. // See http://crbug.com/10611 for more information. #if defined(OS_MACOSX) #define MAYBE_MultipleThreads DISABLED_MultipleThreads #else #define MAYBE_MultipleThreads MultipleThreads #endif TEST_F(StatsTableTest, MAYBE_MultipleThreads) { // Create a stats table. const std::string kTableName = "MultipleThreadStatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); EXPECT_EQ(0, table.CountThreadsRegistered()); // Spin up a set of threads to go bang on the various counters. // After we join the threads, we'll make sure the counters // contain the values we expected. StatsTableThread* threads[kMaxThreads]; // Spawn the threads. for (int index = 0; index < kMaxThreads; index++) { threads[index] = new StatsTableThread("MultipleThreadsTest", index); threads[index]->Start(); } // Wait for the threads to finish. for (int index = 0; index < kMaxThreads; index++) { threads[index]->Join(); delete threads[index]; } StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); StatsCounter mixed_counter(kCounterMixed); // Verify the various counters are correct. std::string name; name = "c:" + kCounterZero; EXPECT_EQ(0, table.GetCounterValue(name)); name = "c:" + kCounter1313; EXPECT_EQ(1313 * kMaxThreads, table.GetCounterValue(name)); name = "c:" + kCounterIncrement; EXPECT_EQ(kMaxThreads * kThreadLoops, table.GetCounterValue(name)); name = "c:" + kCounterDecrement; EXPECT_EQ(-kMaxThreads * kThreadLoops, table.GetCounterValue(name)); name = "c:" + kCounterMixed; EXPECT_EQ((kMaxThreads % 2) * kThreadLoops, table.GetCounterValue(name)); EXPECT_EQ(0, table.CountThreadsRegistered()); DeleteShmem(kTableName); } const std::string kMPTableName = "MultipleProcessStatTable"; MULTIPROCESS_TEST_MAIN(StatsTableMultipleProcessMain) { // Each process will open the shared memory and set counters // concurrently in a loop. We'll use some pauses to // mixup the scheduling. StatsTable table(kMPTableName, 0, 0); StatsTable::set_current(&table); StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); for (int index = 0; index < kThreadLoops; index++) { zero_counter.Set(0); lucky13_counter.Set(1313); increment_counter.Increment(); decrement_counter.Decrement(); PlatformThread::Sleep(TimeDelta::FromMilliseconds(index % 10)); } return 0; } // Create a few processes and have them poke on their counters. // This test is slow and flaky http://crbug.com/10611 TEST_F(StatsTableTest, DISABLED_MultipleProcesses) { // Create a stats table. const int kMaxProcs = 20; const int kMaxCounter = 5; DeleteShmem(kMPTableName); StatsTable table(kMPTableName, kMaxProcs, kMaxCounter); StatsTable::set_current(&table); EXPECT_EQ(0, table.CountThreadsRegistered()); // Spin up a set of processes to go bang on the various counters. // After we join the processes, we'll make sure the counters // contain the values we expected. ProcessHandle procs[kMaxProcs]; // Spawn the processes. for (int16 index = 0; index < kMaxProcs; index++) { procs[index] = this->SpawnChild("StatsTableMultipleProcessMain", false); EXPECT_NE(kNullProcessHandle, procs[index]); } // Wait for the processes to finish. for (int index = 0; index < kMaxProcs; index++) { EXPECT_TRUE(WaitForSingleProcess(procs[index], 60 * 1000)); CloseProcessHandle(procs[index]); } StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); // Verify the various counters are correct. std::string name; name = "c:" + kCounterZero; EXPECT_EQ(0, table.GetCounterValue(name)); name = "c:" + kCounter1313; EXPECT_EQ(1313 * kMaxProcs, table.GetCounterValue(name)); name = "c:" + kCounterIncrement; EXPECT_EQ(kMaxProcs * kThreadLoops, table.GetCounterValue(name)); name = "c:" + kCounterDecrement; EXPECT_EQ(-kMaxProcs * kThreadLoops, table.GetCounterValue(name)); EXPECT_EQ(0, table.CountThreadsRegistered()); DeleteShmem(kMPTableName); } class MockStatsCounter : public StatsCounter { public: explicit MockStatsCounter(const std::string& name) : StatsCounter(name) {} int* Pointer() { return GetPtr(); } }; // Test some basic StatsCounter operations TEST_F(StatsTableTest, StatsCounter) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); MockStatsCounter foo("foo"); // Test initial state. EXPECT_TRUE(foo.Enabled()); ASSERT_NE(foo.Pointer(), static_cast<int*>(0)); EXPECT_EQ(0, *(foo.Pointer())); EXPECT_EQ(0, table.GetCounterValue("c:foo")); // Test Increment. while (*(foo.Pointer()) < 123) foo.Increment(); EXPECT_EQ(123, table.GetCounterValue("c:foo")); foo.Add(0); EXPECT_EQ(123, table.GetCounterValue("c:foo")); foo.Add(-1); EXPECT_EQ(122, table.GetCounterValue("c:foo")); // Test Set. foo.Set(0); EXPECT_EQ(0, table.GetCounterValue("c:foo")); foo.Set(100); EXPECT_EQ(100, table.GetCounterValue("c:foo")); foo.Set(-1); EXPECT_EQ(-1, table.GetCounterValue("c:foo")); foo.Set(0); EXPECT_EQ(0, table.GetCounterValue("c:foo")); // Test Decrement. foo.Subtract(1); EXPECT_EQ(-1, table.GetCounterValue("c:foo")); foo.Subtract(0); EXPECT_EQ(-1, table.GetCounterValue("c:foo")); foo.Subtract(-1); EXPECT_EQ(0, table.GetCounterValue("c:foo")); DeleteShmem(kTableName); } class MockStatsCounterTimer : public StatsCounterTimer { public: explicit MockStatsCounterTimer(const std::string& name) : StatsCounterTimer(name) {} TimeTicks start_time() { return start_time_; } TimeTicks stop_time() { return stop_time_; } }; // Test some basic StatsCounterTimer operations TEST_F(StatsTableTest, StatsCounterTimer) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); MockStatsCounterTimer bar("bar"); // Test initial state. EXPECT_FALSE(bar.Running()); EXPECT_TRUE(bar.start_time().is_null()); EXPECT_TRUE(bar.stop_time().is_null()); const TimeDelta kDuration = TimeDelta::FromMilliseconds(100); // Do some timing. bar.Start(); PlatformThread::Sleep(kDuration); bar.Stop(); EXPECT_GT(table.GetCounterValue("t:bar"), 0); EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:bar")); // Verify that timing again is additive. bar.Start(); PlatformThread::Sleep(kDuration); bar.Stop(); EXPECT_GT(table.GetCounterValue("t:bar"), 0); EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:bar")); } // Test some basic StatsRate operations // Usually fails on all platforms when run alone. http://crbug.com/131024 TEST_F(StatsTableTest, DISABLED_StatsRate) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); StatsRate baz("baz"); // Test initial state. EXPECT_FALSE(baz.Running()); EXPECT_EQ(0, table.GetCounterValue("c:baz")); EXPECT_EQ(0, table.GetCounterValue("t:baz")); const TimeDelta kDuration = TimeDelta::FromMilliseconds(100); // Do some timing. baz.Start(); PlatformThread::Sleep(kDuration); baz.Stop(); EXPECT_EQ(1, table.GetCounterValue("c:baz")); EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:baz")); // Verify that timing again is additive. baz.Start(); PlatformThread::Sleep(kDuration); baz.Stop(); EXPECT_EQ(2, table.GetCounterValue("c:baz")); EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:baz")); } // Test some basic StatsScope operations TEST_F(StatsTableTest, StatsScope) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); StatsCounterTimer foo("foo"); StatsRate bar("bar"); // Test initial state. EXPECT_EQ(0, table.GetCounterValue("t:foo")); EXPECT_EQ(0, table.GetCounterValue("t:bar")); EXPECT_EQ(0, table.GetCounterValue("c:bar")); const TimeDelta kDuration = TimeDelta::FromMilliseconds(100); // Try a scope. { StatsScope<StatsCounterTimer> timer(foo); StatsScope<StatsRate> timer2(bar); PlatformThread::Sleep(kDuration); } EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:foo")); EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:bar")); EXPECT_EQ(1, table.GetCounterValue("c:bar")); // Try a second scope. { StatsScope<StatsCounterTimer> timer(foo); StatsScope<StatsRate> timer2(bar); PlatformThread::Sleep(kDuration); } EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:foo")); EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:bar")); EXPECT_EQ(2, table.GetCounterValue("c:bar")); DeleteShmem(kTableName); } } // namespace base <commit_msg>Add shared memory cleanup before/after all tests<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/metrics/stats_counters.h" #include "base/metrics/stats_table.h" #include "base/shared_memory.h" #include "base/stringprintf.h" #include "base/string_piece.h" #include "base/test/multiprocess_test.h" #include "base/threading/platform_thread.h" #include "base/threading/simple_thread.h" #include "base/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" namespace base { class StatsTableTest : public MultiProcessTest { public: void DeleteShmem(const std::string& name) { SharedMemory mem; mem.Delete(name); } }; // Open a StatsTable and verify that we can write to each of the // locations in the table. TEST_F(StatsTableTest, VerifySlots) { const std::string kTableName = "VerifySlotsStatTable"; const int kMaxThreads = 1; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); // Register a single thread. std::string thread_name = "mainThread"; int slot_id = table.RegisterThread(thread_name); EXPECT_NE(slot_id, 0); // Fill up the table with counters. std::string counter_base_name = "counter"; for (int index = 0; index < kMaxCounter; index++) { std::string counter_name = counter_base_name; base::StringAppendF(&counter_name, "counter.ctr%d", index); int counter_id = table.FindCounter(counter_name); EXPECT_GT(counter_id, 0); } // Try to allocate an additional thread. Verify it fails. slot_id = table.RegisterThread("too many threads"); EXPECT_EQ(slot_id, 0); // Try to allocate an additional counter. Verify it fails. int counter_id = table.FindCounter(counter_base_name); EXPECT_EQ(counter_id, 0); DeleteShmem(kTableName); } // CounterZero will continually be set to 0. const std::string kCounterZero = "CounterZero"; // Counter1313 will continually be set to 1313. const std::string kCounter1313 = "Counter1313"; // CounterIncrement will be incremented each time. const std::string kCounterIncrement = "CounterIncrement"; // CounterDecrement will be decremented each time. const std::string kCounterDecrement = "CounterDecrement"; // CounterMixed will be incremented by odd numbered threads and // decremented by even threads. const std::string kCounterMixed = "CounterMixed"; // The number of thread loops that we will do. const int kThreadLoops = 100; class StatsTableThread : public SimpleThread { public: StatsTableThread(std::string name, int id) : SimpleThread(name), id_(id) {} virtual void Run() OVERRIDE; private: int id_; }; void StatsTableThread::Run() { // Each thread will open the shared memory and set counters // concurrently in a loop. We'll use some pauses to // mixup the thread scheduling. StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); for (int index = 0; index < kThreadLoops; index++) { StatsCounter mixed_counter(kCounterMixed); // create this one in the loop zero_counter.Set(0); lucky13_counter.Set(1313); increment_counter.Increment(); decrement_counter.Decrement(); if (id_ % 2) mixed_counter.Decrement(); else mixed_counter.Increment(); PlatformThread::Sleep(TimeDelta::FromMilliseconds(index % 10)); } } // Create a few threads and have them poke on their counters. // See http://crbug.com/10611 for more information. #if defined(OS_MACOSX) #define MAYBE_MultipleThreads DISABLED_MultipleThreads #else #define MAYBE_MultipleThreads MultipleThreads #endif TEST_F(StatsTableTest, MAYBE_MultipleThreads) { // Create a stats table. const std::string kTableName = "MultipleThreadStatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); EXPECT_EQ(0, table.CountThreadsRegistered()); // Spin up a set of threads to go bang on the various counters. // After we join the threads, we'll make sure the counters // contain the values we expected. StatsTableThread* threads[kMaxThreads]; // Spawn the threads. for (int index = 0; index < kMaxThreads; index++) { threads[index] = new StatsTableThread("MultipleThreadsTest", index); threads[index]->Start(); } // Wait for the threads to finish. for (int index = 0; index < kMaxThreads; index++) { threads[index]->Join(); delete threads[index]; } StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); StatsCounter mixed_counter(kCounterMixed); // Verify the various counters are correct. std::string name; name = "c:" + kCounterZero; EXPECT_EQ(0, table.GetCounterValue(name)); name = "c:" + kCounter1313; EXPECT_EQ(1313 * kMaxThreads, table.GetCounterValue(name)); name = "c:" + kCounterIncrement; EXPECT_EQ(kMaxThreads * kThreadLoops, table.GetCounterValue(name)); name = "c:" + kCounterDecrement; EXPECT_EQ(-kMaxThreads * kThreadLoops, table.GetCounterValue(name)); name = "c:" + kCounterMixed; EXPECT_EQ((kMaxThreads % 2) * kThreadLoops, table.GetCounterValue(name)); EXPECT_EQ(0, table.CountThreadsRegistered()); DeleteShmem(kTableName); } const std::string kMPTableName = "MultipleProcessStatTable"; MULTIPROCESS_TEST_MAIN(StatsTableMultipleProcessMain) { // Each process will open the shared memory and set counters // concurrently in a loop. We'll use some pauses to // mixup the scheduling. StatsTable table(kMPTableName, 0, 0); StatsTable::set_current(&table); StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); for (int index = 0; index < kThreadLoops; index++) { zero_counter.Set(0); lucky13_counter.Set(1313); increment_counter.Increment(); decrement_counter.Decrement(); PlatformThread::Sleep(TimeDelta::FromMilliseconds(index % 10)); } return 0; } // Create a few processes and have them poke on their counters. // This test is slow and flaky http://crbug.com/10611 TEST_F(StatsTableTest, DISABLED_MultipleProcesses) { // Create a stats table. const int kMaxProcs = 20; const int kMaxCounter = 5; DeleteShmem(kMPTableName); StatsTable table(kMPTableName, kMaxProcs, kMaxCounter); StatsTable::set_current(&table); EXPECT_EQ(0, table.CountThreadsRegistered()); // Spin up a set of processes to go bang on the various counters. // After we join the processes, we'll make sure the counters // contain the values we expected. ProcessHandle procs[kMaxProcs]; // Spawn the processes. for (int16 index = 0; index < kMaxProcs; index++) { procs[index] = this->SpawnChild("StatsTableMultipleProcessMain", false); EXPECT_NE(kNullProcessHandle, procs[index]); } // Wait for the processes to finish. for (int index = 0; index < kMaxProcs; index++) { EXPECT_TRUE(WaitForSingleProcess(procs[index], 60 * 1000)); CloseProcessHandle(procs[index]); } StatsCounter zero_counter(kCounterZero); StatsCounter lucky13_counter(kCounter1313); StatsCounter increment_counter(kCounterIncrement); StatsCounter decrement_counter(kCounterDecrement); // Verify the various counters are correct. std::string name; name = "c:" + kCounterZero; EXPECT_EQ(0, table.GetCounterValue(name)); name = "c:" + kCounter1313; EXPECT_EQ(1313 * kMaxProcs, table.GetCounterValue(name)); name = "c:" + kCounterIncrement; EXPECT_EQ(kMaxProcs * kThreadLoops, table.GetCounterValue(name)); name = "c:" + kCounterDecrement; EXPECT_EQ(-kMaxProcs * kThreadLoops, table.GetCounterValue(name)); EXPECT_EQ(0, table.CountThreadsRegistered()); DeleteShmem(kMPTableName); } class MockStatsCounter : public StatsCounter { public: explicit MockStatsCounter(const std::string& name) : StatsCounter(name) {} int* Pointer() { return GetPtr(); } }; // Test some basic StatsCounter operations TEST_F(StatsTableTest, StatsCounter) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); MockStatsCounter foo("foo"); // Test initial state. EXPECT_TRUE(foo.Enabled()); ASSERT_NE(foo.Pointer(), static_cast<int*>(0)); EXPECT_EQ(0, *(foo.Pointer())); EXPECT_EQ(0, table.GetCounterValue("c:foo")); // Test Increment. while (*(foo.Pointer()) < 123) foo.Increment(); EXPECT_EQ(123, table.GetCounterValue("c:foo")); foo.Add(0); EXPECT_EQ(123, table.GetCounterValue("c:foo")); foo.Add(-1); EXPECT_EQ(122, table.GetCounterValue("c:foo")); // Test Set. foo.Set(0); EXPECT_EQ(0, table.GetCounterValue("c:foo")); foo.Set(100); EXPECT_EQ(100, table.GetCounterValue("c:foo")); foo.Set(-1); EXPECT_EQ(-1, table.GetCounterValue("c:foo")); foo.Set(0); EXPECT_EQ(0, table.GetCounterValue("c:foo")); // Test Decrement. foo.Subtract(1); EXPECT_EQ(-1, table.GetCounterValue("c:foo")); foo.Subtract(0); EXPECT_EQ(-1, table.GetCounterValue("c:foo")); foo.Subtract(-1); EXPECT_EQ(0, table.GetCounterValue("c:foo")); DeleteShmem(kTableName); } class MockStatsCounterTimer : public StatsCounterTimer { public: explicit MockStatsCounterTimer(const std::string& name) : StatsCounterTimer(name) {} TimeTicks start_time() { return start_time_; } TimeTicks stop_time() { return stop_time_; } }; // Test some basic StatsCounterTimer operations TEST_F(StatsTableTest, StatsCounterTimer) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); MockStatsCounterTimer bar("bar"); // Test initial state. EXPECT_FALSE(bar.Running()); EXPECT_TRUE(bar.start_time().is_null()); EXPECT_TRUE(bar.stop_time().is_null()); const TimeDelta kDuration = TimeDelta::FromMilliseconds(100); // Do some timing. bar.Start(); PlatformThread::Sleep(kDuration); bar.Stop(); EXPECT_GT(table.GetCounterValue("t:bar"), 0); EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:bar")); // Verify that timing again is additive. bar.Start(); PlatformThread::Sleep(kDuration); bar.Stop(); EXPECT_GT(table.GetCounterValue("t:bar"), 0); EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:bar")); DeleteShmem(kTableName); } // Test some basic StatsRate operations TEST_F(StatsTableTest, StatsRate) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); StatsRate baz("baz"); // Test initial state. EXPECT_FALSE(baz.Running()); EXPECT_EQ(0, table.GetCounterValue("c:baz")); EXPECT_EQ(0, table.GetCounterValue("t:baz")); const TimeDelta kDuration = TimeDelta::FromMilliseconds(100); // Do some timing. baz.Start(); PlatformThread::Sleep(kDuration); baz.Stop(); EXPECT_EQ(1, table.GetCounterValue("c:baz")); EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:baz")); // Verify that timing again is additive. baz.Start(); PlatformThread::Sleep(kDuration); baz.Stop(); EXPECT_EQ(2, table.GetCounterValue("c:baz")); EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:baz")); DeleteShmem(kTableName); } // Test some basic StatsScope operations TEST_F(StatsTableTest, StatsScope) { // Create a stats table. const std::string kTableName = "StatTable"; const int kMaxThreads = 20; const int kMaxCounter = 5; DeleteShmem(kTableName); StatsTable table(kTableName, kMaxThreads, kMaxCounter); StatsTable::set_current(&table); StatsCounterTimer foo("foo"); StatsRate bar("bar"); // Test initial state. EXPECT_EQ(0, table.GetCounterValue("t:foo")); EXPECT_EQ(0, table.GetCounterValue("t:bar")); EXPECT_EQ(0, table.GetCounterValue("c:bar")); const TimeDelta kDuration = TimeDelta::FromMilliseconds(100); // Try a scope. { StatsScope<StatsCounterTimer> timer(foo); StatsScope<StatsRate> timer2(bar); PlatformThread::Sleep(kDuration); } EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:foo")); EXPECT_LE(kDuration.InMilliseconds(), table.GetCounterValue("t:bar")); EXPECT_EQ(1, table.GetCounterValue("c:bar")); // Try a second scope. { StatsScope<StatsCounterTimer> timer(foo); StatsScope<StatsRate> timer2(bar); PlatformThread::Sleep(kDuration); } EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:foo")); EXPECT_LE(kDuration.InMilliseconds() * 2, table.GetCounterValue("t:bar")); EXPECT_EQ(2, table.GetCounterValue("c:bar")); DeleteShmem(kTableName); } } // namespace base <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the ChemData project. Copyright 2012 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 "mongodatabase.h" #include "kmeansclusteringdialog.h" #include "ui_kmeansclusteringdialog.h" #include <QtGui> #include <QVTKWidget.h> #include <vtkNew.h> #include <vtkTable.h> #include <vtkChartXYZ.h> #include <vtkIntArray.h> #include <vtkFloatArray.h> #include <vtkContextView.h> #include <vtkLookupTable.h> #include <vtkContextScene.h> #include <vtkPlotPoints3D.h> #include <vtkRenderWindow.h> #include <vtkSmartPointer.h> #include <vtkKMeansStatistics.h> #include <chemkit/molecule.h> #include <chemkit/moleculardescriptor.h> // avoid shadow warnings from Qt's foreach by using Boost's #undef foreach #include <boost/foreach.hpp> #define foreach BOOST_FOREACH class KMeansClusteringDialogPrivate { public: QVTKWidget *vtkWidget; int kValue; std::vector<MoleculeRef> molecules; vtkSmartPointer<vtkTable> table; vtkNew<vtkContextView> chartView; vtkNew<vtkChartXYZ> chart; vtkPlotPoints3D *plot; boost::array<std::string, 3> descriptors; vtkNew<vtkLookupTable> lut; }; KMeansClusteringDialog::KMeansClusteringDialog(QWidget *parent_) : QDialog(parent_), d(new KMeansClusteringDialogPrivate), ui(new Ui::KMeansClusteringDialog) { // setup ui ui->setupUi(this); // setup descriptors setupDescriptors(); // setup vtk widget d->vtkWidget = new QVTKWidget(this); d->chartView->SetInteractor(d->vtkWidget->GetInteractor()); d->vtkWidget->SetRenderWindow(d->chartView->GetRenderWindow()); ui->viewFrameLayout->addWidget(d->vtkWidget); // setup chart xyz d->plot = 0; d->chart->SetFitToScene(true); d->chart->SetDecorateAxes(true); d->chart->SetGeometry(vtkRectf(0, 0, 600, 600)); // setup chart view d->chartView->GetScene()->AddItem(d->chart.GetPointer()); // setup k-means statistics d->kValue = 3; ui->kValueSpinBox->setValue(d->kValue); // render d->vtkWidget->update(); // connect signals connect(ui->kValueSpinBox, SIGNAL(valueChanged(int)), this, SLOT(kValueSpinBoxChanged(int))); connect(ui->xDescriptorComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(xDescriptorChanged(QString))); connect(ui->yDescriptorComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(yDescriptorChanged(QString))); connect(ui->zDescriptorComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(zDescriptorChanged(QString))); connect(d->vtkWidget, SIGNAL(mouseEvent(QMouseEvent*)), this, SLOT(viewMouseEvent(QMouseEvent*))); } KMeansClusteringDialog::~KMeansClusteringDialog() { delete d; delete ui; } void KMeansClusteringDialog::setMolecules(const std::vector<MoleculeRef> &molecules_) { // display progress dialog QProgressDialog progressDialog("Calculating Descriptors", "Cancel", 0, molecules_.size(), this); // pop-up progress dialog immediately progressDialog.setMinimumDuration(0); // connect to the database MongoDatabase *db = MongoDatabase::instance(); // set molecules d->molecules = molecules_; // remove old plot if (d->plot) { d->chart->ClearPlots(); d->plot->Delete(); d->plot = 0; } // create table for the descriptors d->table = vtkSmartPointer<vtkTable>::New(); // setup descriptor arrays boost::array<vtkFloatArray *, 3> arrays; for (size_t i = 0; i < 3; i++) { vtkFloatArray *array = vtkFloatArray::New(); array->SetName(d->descriptors[i].c_str()); arrays[i] = array; d->table->AddColumn(array); array->Delete(); } // setup color array vtkIntArray *colorArray = vtkIntArray::New(); colorArray->SetName("color"); colorArray->SetNumberOfComponents(1); d->table->AddColumn(colorArray); colorArray->Delete(); // calculate descriptors foreach (const MoleculeRef &ref, molecules_) { // stop calculating if the user clicked cancel if(progressDialog.wasCanceled()) break; // create molecule object boost::shared_ptr<const chemkit::Molecule> molecule = db->createMolecule(ref); // calculate descriptors for the molecule for (size_t i = 0; i < 3; i++) arrays[i]->InsertNextValue(molecule->descriptor(d->descriptors[i]).toFloat()); // set cluster to 0 (will be set to its real value later by running k-means) colorArray->InsertNextValue(0); // update progress dialog progressDialog.setValue(progressDialog.value() + 1); } // run k-means statstics runKMeansStatistics(); // setup plot d->plot = vtkPlotPoints3D::New(); d->plot->SetInputData(d->table.GetPointer(), d->descriptors[0], d->descriptors[1], d->descriptors[2], "color"); // setup chart d->chart->AddPlot(d->plot); // update bounds and display chart d->chart->RecalculateBounds(); d->chart->RecalculateTransform(); d->vtkWidget->update(); } std::vector<MoleculeRef> KMeansClusteringDialog::molecules() const { return d->molecules; } void KMeansClusteringDialog::setKValue(int k) { // set k value d->kValue = k; // run k-means statistics runKMeansStatistics(); // update plot with new colors (i wish this was easier) if (d->plot) { d->chart->ClearPlots(); d->plot->Delete(); d->plot = vtkPlotPoints3D::New(); d->plot->SetInputData(d->table.GetPointer(), d->descriptors[0], d->descriptors[1], d->descriptors[2], "color"); d->chart->AddPlot(d->plot); d->chart->RecalculateBounds(); d->chart->RecalculateTransform(); d->vtkWidget->update(); } } int KMeansClusteringDialog::kValue() const { return d->kValue; } void KMeansClusteringDialog::setDescriptor(int index, const QString &descriptor_) { if (index < 0 || index > 2) return; // set descriptor name d->descriptors[index] = descriptor_.toStdString(); // update setMolecules(d->molecules); } QString KMeansClusteringDialog::descriptor(int index) { if (index >= 0 && index < 3) return QString::fromStdString(d->descriptors[index]); else return QString(); } void KMeansClusteringDialog::kValueSpinBoxChanged(int value) { setKValue(value); } void KMeansClusteringDialog::resetCamera() { d->vtkWidget->update(); } void KMeansClusteringDialog::xDescriptorChanged(const QString &descriptor_) { setDescriptor(0, descriptor_); } void KMeansClusteringDialog::yDescriptorChanged(const QString &descriptor_) { setDescriptor(1, descriptor_); } void KMeansClusteringDialog::zDescriptorChanged(const QString &descriptor_) { setDescriptor(2, descriptor_); } void KMeansClusteringDialog::viewMouseEvent(QMouseEvent *event_) { // not sure how to implement this with vtkChartXYZ (void) event_; // if (event_->button() == Qt::LeftButton && // event_->type() == QMouseEvent::MouseButtonDblClick) { // vtkNew<vtkPointPicker> picker; // vtkRenderer *renderer = d->renderer.GetPointer(); // vtkRenderWindowInteractor *interactor = d->vtkWidget->GetInteractor(); // int *pos_ = interactor->GetEventPosition(); // if (picker->Pick(pos_[0], pos_[1], 0, renderer)) { // vtkIdType id = picker->GetPointId(); // if (id != -1) // emit moleculeDoubleClicked(id); // } // } } void KMeansClusteringDialog::setupDescriptors() { // populate combo boxes std::vector<std::string> descriptors = chemkit::MolecularDescriptor::descriptors(); // create map of descriptor dimensionality to list of descriptor names QMap<int, QStringList> descriptorsMap; foreach (const std::string &name, descriptors) { boost::scoped_ptr<chemkit::MolecularDescriptor> descriptor_(chemkit::MolecularDescriptor::create(name)); int dimensionality = descriptor_->dimensionality(); if (dimensionality == -1) { // descriptors with unknown dimensionality have a value of -1 so we // set it to INT_MAX in order to put them at the bottom of the list dimensionality = std::numeric_limits<int>::max(); } descriptorsMap[dimensionality].append(name.c_str()); } // list of the combo boxes for each of the x, y and z axes QList<QComboBox *> comboBoxes; comboBoxes.append(ui->xDescriptorComboBox); comboBoxes.append(ui->yDescriptorComboBox); comboBoxes.append(ui->zDescriptorComboBox); // insert each descriptor into each combo box grouped by dimensionality foreach (int key, descriptorsMap.keys()) { int dimensionality = key; const QStringList &names = descriptorsMap[key]; foreach (QComboBox *comboBox, comboBoxes) { // insert title int titleIndex = comboBox->count(); if (dimensionality != std::numeric_limits<int>::max()) comboBox->addItem(tr("%1D Descriptors").arg(dimensionality)); else comboBox->addItem(tr("Other Descriptors")); // set bold font for title and make it non-selectable QStandardItem *item = qobject_cast<QStandardItemModel *>(comboBox->model())->item(titleIndex); if (item) { QFont font_ = item->font(); font_.setBold(true); item->setFont(font_); item->setFlags(Qt::ItemIsEnabled); } // add a separator comboBox->insertSeparator(comboBox->count()); // insert name of each descriptor foreach (const QString &name, names) comboBox->addItem(name); } } // default to X = mass, Y = tpsa, and Z = vabc int massIndex = ui->xDescriptorComboBox->findText("mass"); ui->xDescriptorComboBox->setCurrentIndex(massIndex); d->descriptors[0] = "mass"; int tpsaIndex = ui->yDescriptorComboBox->findText("tpsa"); ui->yDescriptorComboBox->setCurrentIndex(tpsaIndex); d->descriptors[1] = "tpsa"; int vabcIndex = ui->zDescriptorComboBox->findText("vabc"); ui->zDescriptorComboBox->setCurrentIndex(vabcIndex); d->descriptors[2] = "vabc"; } void KMeansClusteringDialog::runKMeansStatistics() { // run k-means statistics vtkNew<vtkKMeansStatistics> kMeansStatistics; kMeansStatistics->RequestSelectedColumns(); kMeansStatistics->SetAssessOption(true); kMeansStatistics->SetDefaultNumberOfClusters(d->kValue); kMeansStatistics->SetInputData(vtkStatisticsAlgorithm::INPUT_DATA, d->table.GetPointer()); for (size_t i = 0; i < 3; i++) kMeansStatistics->SetColumnStatus(d->descriptors[i].c_str(), 1); kMeansStatistics->RequestSelectedColumns(); kMeansStatistics->Update(); // assign molecules to clusters vtkNew<vtkIntArray> clusterAssignments; clusterAssignments->SetNumberOfComponents(1); size_t clusterCount = kMeansStatistics->GetOutput()->GetNumberOfColumns(); std::vector<size_t> clusterSizes(clusterCount); for (vtkIdType r = 0; r < kMeansStatistics->GetOutput()->GetNumberOfRows(); r++) { vtkVariant v = kMeansStatistics->GetOutput()->GetValue(r, clusterCount - 1); int cluster = v.ToInt(); clusterAssignments->InsertNextValue(cluster); clusterSizes[cluster]++; } // update lookup table d->lut->SetNumberOfTableValues(d->kValue); d->lut->Build(); // update color array vtkIntArray *colorArray = vtkIntArray::SafeDownCast(d->table->GetColumnByName("color")); for(vtkIdType i = 0; i < colorArray->GetNumberOfTuples(); i++){ colorArray->SetValue(i, clusterAssignments->GetValue(i)); } d->table->Modified(); // update cluster table widget ui->clusterTableWidget->setRowCount(d->kValue); for (int row = 0; row < d->kValue; row++) { // column 0 - cluster color QTableWidgetItem *colorItem = new QTableWidgetItem; double color[4]; d->lut->GetTableValue(row, color); colorItem->setBackgroundColor(QColor::fromRgbF(color[0], color[1], color[2], 0.8f)); ui->clusterTableWidget->setItem(row, 0, colorItem); // column 1 - cluster number QTableWidgetItem *numberItem = new QTableWidgetItem(QString::number(row + 1)); numberItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); ui->clusterTableWidget->setItem(row, 1, numberItem); // column 2 - cluster size QTableWidgetItem *sizeItem = new QTableWidgetItem(QString::number(clusterSizes[row])); sizeItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); ui->clusterTableWidget->setItem(row, 2, sizeItem); } ui->clusterTableWidget->resizeColumnsToContents(); ui->clusterTableWidget->horizontalHeader()->setStretchLastSection(true); } <commit_msg>Fix missing array include in kmeansclusteringdialog.cpp<commit_after>/****************************************************************************** This source file is part of the ChemData project. Copyright 2012 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 "mongodatabase.h" #include "kmeansclusteringdialog.h" #include "ui_kmeansclusteringdialog.h" #include <QtGui> #include <QVTKWidget.h> #include <vtkNew.h> #include <vtkTable.h> #include <vtkChartXYZ.h> #include <vtkIntArray.h> #include <vtkFloatArray.h> #include <vtkContextView.h> #include <vtkLookupTable.h> #include <vtkContextScene.h> #include <vtkPlotPoints3D.h> #include <vtkRenderWindow.h> #include <vtkSmartPointer.h> #include <vtkKMeansStatistics.h> #include <boost/array.hpp> #include <chemkit/molecule.h> #include <chemkit/moleculardescriptor.h> // avoid shadow warnings from Qt's foreach by using Boost's #undef foreach #include <boost/foreach.hpp> #define foreach BOOST_FOREACH class KMeansClusteringDialogPrivate { public: QVTKWidget *vtkWidget; int kValue; std::vector<MoleculeRef> molecules; vtkSmartPointer<vtkTable> table; vtkNew<vtkContextView> chartView; vtkNew<vtkChartXYZ> chart; vtkPlotPoints3D *plot; boost::array<std::string, 3> descriptors; vtkNew<vtkLookupTable> lut; }; KMeansClusteringDialog::KMeansClusteringDialog(QWidget *parent_) : QDialog(parent_), d(new KMeansClusteringDialogPrivate), ui(new Ui::KMeansClusteringDialog) { // setup ui ui->setupUi(this); // setup descriptors setupDescriptors(); // setup vtk widget d->vtkWidget = new QVTKWidget(this); d->chartView->SetInteractor(d->vtkWidget->GetInteractor()); d->vtkWidget->SetRenderWindow(d->chartView->GetRenderWindow()); ui->viewFrameLayout->addWidget(d->vtkWidget); // setup chart xyz d->plot = 0; d->chart->SetFitToScene(true); d->chart->SetDecorateAxes(true); d->chart->SetGeometry(vtkRectf(0, 0, 600, 600)); // setup chart view d->chartView->GetScene()->AddItem(d->chart.GetPointer()); // setup k-means statistics d->kValue = 3; ui->kValueSpinBox->setValue(d->kValue); // render d->vtkWidget->update(); // connect signals connect(ui->kValueSpinBox, SIGNAL(valueChanged(int)), this, SLOT(kValueSpinBoxChanged(int))); connect(ui->xDescriptorComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(xDescriptorChanged(QString))); connect(ui->yDescriptorComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(yDescriptorChanged(QString))); connect(ui->zDescriptorComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(zDescriptorChanged(QString))); connect(d->vtkWidget, SIGNAL(mouseEvent(QMouseEvent*)), this, SLOT(viewMouseEvent(QMouseEvent*))); } KMeansClusteringDialog::~KMeansClusteringDialog() { delete d; delete ui; } void KMeansClusteringDialog::setMolecules(const std::vector<MoleculeRef> &molecules_) { // display progress dialog QProgressDialog progressDialog("Calculating Descriptors", "Cancel", 0, molecules_.size(), this); // pop-up progress dialog immediately progressDialog.setMinimumDuration(0); // connect to the database MongoDatabase *db = MongoDatabase::instance(); // set molecules d->molecules = molecules_; // remove old plot if (d->plot) { d->chart->ClearPlots(); d->plot->Delete(); d->plot = 0; } // create table for the descriptors d->table = vtkSmartPointer<vtkTable>::New(); // setup descriptor arrays boost::array<vtkFloatArray *, 3> arrays; for (size_t i = 0; i < 3; i++) { vtkFloatArray *array = vtkFloatArray::New(); array->SetName(d->descriptors[i].c_str()); arrays[i] = array; d->table->AddColumn(array); array->Delete(); } // setup color array vtkIntArray *colorArray = vtkIntArray::New(); colorArray->SetName("color"); colorArray->SetNumberOfComponents(1); d->table->AddColumn(colorArray); colorArray->Delete(); // calculate descriptors foreach (const MoleculeRef &ref, molecules_) { // stop calculating if the user clicked cancel if(progressDialog.wasCanceled()) break; // create molecule object boost::shared_ptr<const chemkit::Molecule> molecule = db->createMolecule(ref); // calculate descriptors for the molecule for (size_t i = 0; i < 3; i++) arrays[i]->InsertNextValue(molecule->descriptor(d->descriptors[i]).toFloat()); // set cluster to 0 (will be set to its real value later by running k-means) colorArray->InsertNextValue(0); // update progress dialog progressDialog.setValue(progressDialog.value() + 1); } // run k-means statstics runKMeansStatistics(); // setup plot d->plot = vtkPlotPoints3D::New(); d->plot->SetInputData(d->table.GetPointer(), d->descriptors[0], d->descriptors[1], d->descriptors[2], "color"); // setup chart d->chart->AddPlot(d->plot); // update bounds and display chart d->chart->RecalculateBounds(); d->chart->RecalculateTransform(); d->vtkWidget->update(); } std::vector<MoleculeRef> KMeansClusteringDialog::molecules() const { return d->molecules; } void KMeansClusteringDialog::setKValue(int k) { // set k value d->kValue = k; // run k-means statistics runKMeansStatistics(); // update plot with new colors (i wish this was easier) if (d->plot) { d->chart->ClearPlots(); d->plot->Delete(); d->plot = vtkPlotPoints3D::New(); d->plot->SetInputData(d->table.GetPointer(), d->descriptors[0], d->descriptors[1], d->descriptors[2], "color"); d->chart->AddPlot(d->plot); d->chart->RecalculateBounds(); d->chart->RecalculateTransform(); d->vtkWidget->update(); } } int KMeansClusteringDialog::kValue() const { return d->kValue; } void KMeansClusteringDialog::setDescriptor(int index, const QString &descriptor_) { if (index < 0 || index > 2) return; // set descriptor name d->descriptors[index] = descriptor_.toStdString(); // update setMolecules(d->molecules); } QString KMeansClusteringDialog::descriptor(int index) { if (index >= 0 && index < 3) return QString::fromStdString(d->descriptors[index]); else return QString(); } void KMeansClusteringDialog::kValueSpinBoxChanged(int value) { setKValue(value); } void KMeansClusteringDialog::resetCamera() { d->vtkWidget->update(); } void KMeansClusteringDialog::xDescriptorChanged(const QString &descriptor_) { setDescriptor(0, descriptor_); } void KMeansClusteringDialog::yDescriptorChanged(const QString &descriptor_) { setDescriptor(1, descriptor_); } void KMeansClusteringDialog::zDescriptorChanged(const QString &descriptor_) { setDescriptor(2, descriptor_); } void KMeansClusteringDialog::viewMouseEvent(QMouseEvent *event_) { // not sure how to implement this with vtkChartXYZ (void) event_; // if (event_->button() == Qt::LeftButton && // event_->type() == QMouseEvent::MouseButtonDblClick) { // vtkNew<vtkPointPicker> picker; // vtkRenderer *renderer = d->renderer.GetPointer(); // vtkRenderWindowInteractor *interactor = d->vtkWidget->GetInteractor(); // int *pos_ = interactor->GetEventPosition(); // if (picker->Pick(pos_[0], pos_[1], 0, renderer)) { // vtkIdType id = picker->GetPointId(); // if (id != -1) // emit moleculeDoubleClicked(id); // } // } } void KMeansClusteringDialog::setupDescriptors() { // populate combo boxes std::vector<std::string> descriptors = chemkit::MolecularDescriptor::descriptors(); // create map of descriptor dimensionality to list of descriptor names QMap<int, QStringList> descriptorsMap; foreach (const std::string &name, descriptors) { boost::scoped_ptr<chemkit::MolecularDescriptor> descriptor_(chemkit::MolecularDescriptor::create(name)); int dimensionality = descriptor_->dimensionality(); if (dimensionality == -1) { // descriptors with unknown dimensionality have a value of -1 so we // set it to INT_MAX in order to put them at the bottom of the list dimensionality = std::numeric_limits<int>::max(); } descriptorsMap[dimensionality].append(name.c_str()); } // list of the combo boxes for each of the x, y and z axes QList<QComboBox *> comboBoxes; comboBoxes.append(ui->xDescriptorComboBox); comboBoxes.append(ui->yDescriptorComboBox); comboBoxes.append(ui->zDescriptorComboBox); // insert each descriptor into each combo box grouped by dimensionality foreach (int key, descriptorsMap.keys()) { int dimensionality = key; const QStringList &names = descriptorsMap[key]; foreach (QComboBox *comboBox, comboBoxes) { // insert title int titleIndex = comboBox->count(); if (dimensionality != std::numeric_limits<int>::max()) comboBox->addItem(tr("%1D Descriptors").arg(dimensionality)); else comboBox->addItem(tr("Other Descriptors")); // set bold font for title and make it non-selectable QStandardItem *item = qobject_cast<QStandardItemModel *>(comboBox->model())->item(titleIndex); if (item) { QFont font_ = item->font(); font_.setBold(true); item->setFont(font_); item->setFlags(Qt::ItemIsEnabled); } // add a separator comboBox->insertSeparator(comboBox->count()); // insert name of each descriptor foreach (const QString &name, names) comboBox->addItem(name); } } // default to X = mass, Y = tpsa, and Z = vabc int massIndex = ui->xDescriptorComboBox->findText("mass"); ui->xDescriptorComboBox->setCurrentIndex(massIndex); d->descriptors[0] = "mass"; int tpsaIndex = ui->yDescriptorComboBox->findText("tpsa"); ui->yDescriptorComboBox->setCurrentIndex(tpsaIndex); d->descriptors[1] = "tpsa"; int vabcIndex = ui->zDescriptorComboBox->findText("vabc"); ui->zDescriptorComboBox->setCurrentIndex(vabcIndex); d->descriptors[2] = "vabc"; } void KMeansClusteringDialog::runKMeansStatistics() { // run k-means statistics vtkNew<vtkKMeansStatistics> kMeansStatistics; kMeansStatistics->RequestSelectedColumns(); kMeansStatistics->SetAssessOption(true); kMeansStatistics->SetDefaultNumberOfClusters(d->kValue); kMeansStatistics->SetInputData(vtkStatisticsAlgorithm::INPUT_DATA, d->table.GetPointer()); for (size_t i = 0; i < 3; i++) kMeansStatistics->SetColumnStatus(d->descriptors[i].c_str(), 1); kMeansStatistics->RequestSelectedColumns(); kMeansStatistics->Update(); // assign molecules to clusters vtkNew<vtkIntArray> clusterAssignments; clusterAssignments->SetNumberOfComponents(1); size_t clusterCount = kMeansStatistics->GetOutput()->GetNumberOfColumns(); std::vector<size_t> clusterSizes(clusterCount); for (vtkIdType r = 0; r < kMeansStatistics->GetOutput()->GetNumberOfRows(); r++) { vtkVariant v = kMeansStatistics->GetOutput()->GetValue(r, clusterCount - 1); int cluster = v.ToInt(); clusterAssignments->InsertNextValue(cluster); clusterSizes[cluster]++; } // update lookup table d->lut->SetNumberOfTableValues(d->kValue); d->lut->Build(); // update color array vtkIntArray *colorArray = vtkIntArray::SafeDownCast(d->table->GetColumnByName("color")); for(vtkIdType i = 0; i < colorArray->GetNumberOfTuples(); i++){ colorArray->SetValue(i, clusterAssignments->GetValue(i)); } d->table->Modified(); // update cluster table widget ui->clusterTableWidget->setRowCount(d->kValue); for (int row = 0; row < d->kValue; row++) { // column 0 - cluster color QTableWidgetItem *colorItem = new QTableWidgetItem; double color[4]; d->lut->GetTableValue(row, color); colorItem->setBackgroundColor(QColor::fromRgbF(color[0], color[1], color[2], 0.8f)); ui->clusterTableWidget->setItem(row, 0, colorItem); // column 1 - cluster number QTableWidgetItem *numberItem = new QTableWidgetItem(QString::number(row + 1)); numberItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); ui->clusterTableWidget->setItem(row, 1, numberItem); // column 2 - cluster size QTableWidgetItem *sizeItem = new QTableWidgetItem(QString::number(clusterSizes[row])); sizeItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); ui->clusterTableWidget->setItem(row, 2, sizeItem); } ui->clusterTableWidget->resizeColumnsToContents(); ui->clusterTableWidget->horizontalHeader()->setStretchLastSection(true); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: jvmargs.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2004-11-09 13:54:04 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __JVM_HXX #define __JVM_HXX #include <vector> #include <rtl/ustring> #include "jni.h" extern "C" { typedef jint JNICALL JNI_InitArgs_Type(void *); typedef jint JNICALL JNI_CreateVM_Type(JavaVM **, JNIEnv **, void *); } namespace stoc_javavm { class JVM { ::std::vector<rtl::OUString> _props; public: JVM() throw(); void pushProp(const ::rtl::OUString & uString); const ::std::vector< ::rtl::OUString> & getProperties() const; }; } #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.10.38); FILE MERGED 2005/09/05 17:10:57 rt 1.10.38.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: jvmargs.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2005-09-08 08:00:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __JVM_HXX #define __JVM_HXX #include <vector> #include <rtl/ustring> #include "jni.h" extern "C" { typedef jint JNICALL JNI_InitArgs_Type(void *); typedef jint JNICALL JNI_CreateVM_Type(JavaVM **, JNIEnv **, void *); } namespace stoc_javavm { class JVM { ::std::vector<rtl::OUString> _props; public: JVM() throw(); void pushProp(const ::rtl::OUString & uString); const ::std::vector< ::rtl::OUString> & getProperties() const; }; } #endif <|endoftext|>
<commit_before>/* OF-TangibleFramework . Framework for Taller de Sistemes Interactius I Universitat Pompeu Fabra Copyright (c) 2010 Carles F. Julià <carles.fernandez@upf.edu> 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 "InputGestureTuio1.12D.hpp" #include <cstring> using namespace osc; namespace tuio { void InputGestureTuio112D::ReceiveCall(const char * addr, ReceivedMessageArgumentStream & args) { if(!valid) return; if( strcmp( addr, "/tuio/2Dcur" ) == 0 ) tuio2Dcur(args); if( strcmp( addr, "/tuio/2Dobj" ) == 0 ) tuio2Dobj(args); if( strcmp( addr, "/tuio/2Dblb" ) == 0 ) tuio2Dobj(args); } void InputGestureTuio112D::tuio2Dcur(ReceivedMessageArgumentStream & args) { const char* cmd; args >> cmd; if(strcmp(cmd,"set")== 0) { int32 s_id; float xpos, ypos, xspeed, yspeed, maccel; args >> s_id >> xpos >> ypos >> xspeed >> yspeed >> maccel >> EndMessage; if(squaredInterface) { xpos = (xpos -0.125f)*1.333333f; } if(c_s_ids.find(s_id) == c_s_ids.end()) { SimpleCallEvent(CanTuio112D,addTuioCursor2D,(s_id, xpos,ypos,xspeed,yspeed,maccel )); c_s_ids.insert(s_id); } else { SimpleCallEvent(CanTuio112D,updateTuioCursor2D,(s_id, xpos,ypos,xspeed,yspeed,maccel )); } } else if( strcmp( cmd, "alive" ) == 0 ) { int32 s_id; std::set<int32> t(c_s_ids); while(!args.Eos()) { args >> s_id; t.erase(s_id); } args >> EndMessage; for (std::set<int32>::iterator it = t.begin(); it != t.end(); ++it) { s_id = *it; c_s_ids.erase(s_id); SimpleCallEvent(CanTuio112D,removeTuioCursor2D,(s_id)); } } } void InputGestureTuio112D::tuio2Dobj(ReceivedMessageArgumentStream & args) { const char* cmd; args >> cmd; if(strcmp(cmd,"set")== 0) { int32 s_id, f_id; float xpos, ypos, angle, xspeed, yspeed, rspeed, maccel, raccel; args >> s_id >> f_id >> xpos >> ypos >> angle >> xspeed >> yspeed >> rspeed >> maccel >> raccel >> EndMessage; if(squaredInterface) { xpos = (xpos -0.125f)*1.333333f; } if(o_s_ids.find(s_id) == o_s_ids.end()) { o_s_ids.insert(s_id); SimpleCallEvent(CanTuio112D,addTuioObject2D,( s_id, f_id ,xpos, ypos, angle, xspeed,yspeed, rspeed, maccel, raccel)); } else { SimpleCallEvent(CanTuio112D,updateTuioObject2D,( s_id, f_id ,xpos, ypos, angle, xspeed,yspeed, rspeed, maccel, raccel)); } } else if( strcmp( cmd, "alive" ) == 0 ) { int32 s_id; std::set<int32> t(o_s_ids); while(!args.Eos()) { args >> s_id; t.erase(s_id); } args >> EndMessage; for (std::set<int32>::iterator it = t.begin(); it != t.end(); ++it) { s_id = *it; o_s_ids.erase(s_id); SimpleCallEvent(CanTuio112D,removeTuioObject2D,(s_id)); } } } void InputGestureTuio112D::tuio2Dblb(ReceivedMessageArgumentStream & args) { const char* cmd; args >> cmd; if(strcmp(cmd,"set")== 0) { int32 s_id; float xpos, ypos, angle, width, height, area, xspeed, yspeed, rspeed, maccel, raccel; args >> s_id >> xpos >> ypos >> angle >> width >> height >> area >> xspeed >> yspeed >> rspeed >> maccel >> raccel >> EndMessage; if(b_s_ids.find(s_id) == b_s_ids.end()) { SimpleCallEvent(CanTuio112D,addTuioBlob2D,(s_id, xpos, ypos, angle, width, height, area, xspeed, yspeed, rspeed, maccel, raccel)); b_s_ids.insert(s_id); } else { SimpleCallEvent(CanTuio112D,updateTuioBlob2D,(s_id, xpos, ypos, angle, width, height, area, xspeed, yspeed, rspeed, maccel, raccel)); } } else if( strcmp( cmd, "alive" ) == 0 ) { int32 s_id; std::set<int32> t(b_s_ids); while(!args.Eos()) { args >> s_id; t.erase(s_id); } args >> EndMessage; for (std::set<int32>::iterator it = t.begin(); it != t.end(); ++it) { s_id = *it; b_s_ids.erase(s_id); SimpleCallEvent(CanTuio112D,removeTuioBlob2D,(s_id)); } } } } <commit_msg>Quick fix for rectangular interfaces (only 4:3 for now)<commit_after>/* OF-TangibleFramework . Framework for Taller de Sistemes Interactius I Universitat Pompeu Fabra Copyright (c) 2010 Carles F. Julià <carles.fernandez@upf.edu> 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 "InputGestureTuio1.12D.hpp" #include <cstring> using namespace osc; namespace tuio { void InputGestureTuio112D::ReceiveCall(const char * addr, ReceivedMessageArgumentStream & args) { if(!valid) return; if( strcmp( addr, "/tuio/2Dcur" ) == 0 ) tuio2Dcur(args); if( strcmp( addr, "/tuio/2Dobj" ) == 0 ) tuio2Dobj(args); if( strcmp( addr, "/tuio/2Dblb" ) == 0 ) tuio2Dobj(args); } void InputGestureTuio112D::tuio2Dcur(ReceivedMessageArgumentStream & args) { const char* cmd; args >> cmd; if(strcmp(cmd,"set")== 0) { int32 s_id; float xpos, ypos, xspeed, yspeed, maccel; args >> s_id >> xpos >> ypos >> xspeed >> yspeed >> maccel >> EndMessage; ///This is a quick fix, it only works with 4:3 window ratios if(squaredInterface) { xpos = (xpos -0.125f)*1.333333f; } else { xpos = xpos *1.333333f; } if(c_s_ids.find(s_id) == c_s_ids.end()) { SimpleCallEvent(CanTuio112D,addTuioCursor2D,(s_id, xpos,ypos,xspeed,yspeed,maccel )); c_s_ids.insert(s_id); } else { SimpleCallEvent(CanTuio112D,updateTuioCursor2D,(s_id, xpos,ypos,xspeed,yspeed,maccel )); } } else if( strcmp( cmd, "alive" ) == 0 ) { int32 s_id; std::set<int32> t(c_s_ids); while(!args.Eos()) { args >> s_id; t.erase(s_id); } args >> EndMessage; for (std::set<int32>::iterator it = t.begin(); it != t.end(); ++it) { s_id = *it; c_s_ids.erase(s_id); SimpleCallEvent(CanTuio112D,removeTuioCursor2D,(s_id)); } } } void InputGestureTuio112D::tuio2Dobj(ReceivedMessageArgumentStream & args) { const char* cmd; args >> cmd; if(strcmp(cmd,"set")== 0) { int32 s_id, f_id; float xpos, ypos, angle, xspeed, yspeed, rspeed, maccel, raccel; args >> s_id >> f_id >> xpos >> ypos >> angle >> xspeed >> yspeed >> rspeed >> maccel >> raccel >> EndMessage; ///This is a quick fix, it only works with 4:3 window ratios if(squaredInterface) { xpos = (xpos -0.125f)*1.333333f; } else { xpos = xpos *1.333333f; } if(o_s_ids.find(s_id) == o_s_ids.end()) { o_s_ids.insert(s_id); SimpleCallEvent(CanTuio112D,addTuioObject2D,( s_id, f_id ,xpos, ypos, angle, xspeed,yspeed, rspeed, maccel, raccel)); } else { SimpleCallEvent(CanTuio112D,updateTuioObject2D,( s_id, f_id ,xpos, ypos, angle, xspeed,yspeed, rspeed, maccel, raccel)); } } else if( strcmp( cmd, "alive" ) == 0 ) { int32 s_id; std::set<int32> t(o_s_ids); while(!args.Eos()) { args >> s_id; t.erase(s_id); } args >> EndMessage; for (std::set<int32>::iterator it = t.begin(); it != t.end(); ++it) { s_id = *it; o_s_ids.erase(s_id); SimpleCallEvent(CanTuio112D,removeTuioObject2D,(s_id)); } } } void InputGestureTuio112D::tuio2Dblb(ReceivedMessageArgumentStream & args) { const char* cmd; args >> cmd; if(strcmp(cmd,"set")== 0) { int32 s_id; float xpos, ypos, angle, width, height, area, xspeed, yspeed, rspeed, maccel, raccel; args >> s_id >> xpos >> ypos >> angle >> width >> height >> area >> xspeed >> yspeed >> rspeed >> maccel >> raccel >> EndMessage; if(b_s_ids.find(s_id) == b_s_ids.end()) { SimpleCallEvent(CanTuio112D,addTuioBlob2D,(s_id, xpos, ypos, angle, width, height, area, xspeed, yspeed, rspeed, maccel, raccel)); b_s_ids.insert(s_id); } else { SimpleCallEvent(CanTuio112D,updateTuioBlob2D,(s_id, xpos, ypos, angle, width, height, area, xspeed, yspeed, rspeed, maccel, raccel)); } } else if( strcmp( cmd, "alive" ) == 0 ) { int32 s_id; std::set<int32> t(b_s_ids); while(!args.Eos()) { args >> s_id; t.erase(s_id); } args >> EndMessage; for (std::set<int32>::iterator it = t.begin(); it != t.end(); ++it) { s_id = *it; b_s_ids.erase(s_id); SimpleCallEvent(CanTuio112D,removeTuioBlob2D,(s_id)); } } } } <|endoftext|>
<commit_before>/***************************************************************************** Copyright 2004 Steve M�nard 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 <jpype_python.h> PyObject* JPypeModule::startup(PyObject* obj, PyObject* args) { TRACE_IN("startup"); try { PyObject* vmOpt; PyObject* vmPath; char ignoreUnrecognized = true; JPyArg::parseTuple(args, "OO!b|", &vmPath, &PyTuple_Type, &vmOpt, &ignoreUnrecognized); if (! (JPyString::check(vmPath))) { RAISE(JPypeException, "First paramter must be a string or unicode"); } string cVmPath = JPyString::asString(vmPath); StringVector args; for (int i = 0; i < JPyObject::length(vmOpt); i++) { PyObject* obj = JPySequence::getItem(vmOpt, i); if (JPyString::check(obj)) { // TODO support unicode string v = JPyString::asString(obj); args.push_back(v); } else if (JPySequence::check(obj)) { //String name = arg[0]; //Callable value = arg[1]; // TODO complete this for the hooks .... } else { RAISE(JPypeException, "VM Arguments must be string or tuple"); } } JPEnv::loadJVM(cVmPath, ignoreUnrecognized, args); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; TRACE_OUT; } PyObject* JPypeModule::attach(PyObject* obj, PyObject* args) { TRACE_IN("attach"); try { PyObject* vmPath; JPyArg::parseTuple(args, "O", &vmPath); if (! (JPyString::check(vmPath))) { RAISE(JPypeException, "First paramter must be a string or unicode"); } string cVmPath = JPyString::asString(vmPath); JPEnv::attachJVM(cVmPath); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; TRACE_OUT; } PyObject* JPypeModule::dumpJVMStats(PyObject* obj) { cerr << "JVM activity report :" << endl; //cerr << "\tmethod calls : " << methodCalls << endl; //cerr << "\tstatic method calls : " << staticMethodCalls << endl; //cerr << "\tconstructor calls : " << constructorCalls << endl; //cerr << "\tproxy callbacks : " << JProxy::getCallbackCount() << endl; //cerr << "\tfield gets : " << fieldGets << endl; //cerr << "\tfield sets : " << fieldSets << endl; cerr << "\tclasses loaded : " << JPTypeManager::getLoadedClasses() << endl; Py_INCREF(Py_None); return Py_None; } PyObject* JPypeModule::shutdown(PyObject* obj) { TRACE_IN("shutdown"); try { dumpJVMStats(obj); JPEnv::getJava()->checkInitialized(); JPTypeManager::shutdown(); if (JPEnv::getJava()->DestroyJavaVM() ) { RAISE(JPypeException, "Unable to destroy JVM"); } JPEnv::getJava()->shutdown(); cerr << "JVM has been shutdown" << endl; Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; TRACE_OUT; } PyObject* JPypeModule::synchronized(PyObject* obj, PyObject* args) { JPCleaner cleaner; TRACE_IN("synchronized"); try { PyObject* o; JPyArg::parseTuple(args, "O!", &PyCapsule_Type, &o); string desc = (char*)JPyCObject::getDesc(o); jobject obj; if (desc == "JPObject") { JPObject* jpo = (JPObject*)JPyCObject::asVoidPtr(o); obj = jpo->getObject(); cleaner.addLocal(obj); } else if (desc == "JPClass") { JPClass* jpo = (JPClass*)JPyCObject::asVoidPtr(o); obj = jpo->getClass(); cleaner.addLocal(obj); } else if (desc == "JPArray") { JPArray* jpo = (JPArray*)JPyCObject::asVoidPtr(o); obj = jpo->getObject(); cleaner.addLocal(obj); } else if (desc == "JPArrayClass") { JPArrayClass* jpo = (JPArrayClass*)JPyCObject::asVoidPtr(o); obj = jpo->getClass(); cleaner.addLocal(obj); } else if (hostEnv->isWrapper(o) && hostEnv->getWrapperTypeName(o).isObjectType()) { obj = hostEnv->getWrapperValue(o).l; cleaner.addLocal(obj); } // TODO proxy else { RAISE(JPypeException, "method only accepts object values."); } PyJPMonitor* c = PyJPMonitor::alloc(new JPMonitor(obj)); return (PyObject*)c; } PY_STANDARD_CATCH; PyErr_Clear(); Py_INCREF(Py_None); return Py_None; TRACE_OUT; } PyObject* JPypeModule::isStarted(PyObject* obj) { if (JPEnv::isInitialized()) { return JPyBoolean::getTrue(); } return JPyBoolean::getFalse(); } PyObject* JPypeModule::attachThread(PyObject* obj) { try { JPEnv::attachCurrentThread(); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::detachThread(PyObject* obj) { try { JPEnv::getJava()->DetachCurrentThread(); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::isThreadAttached(PyObject* obj) { try { if (JPEnv::isThreadAttached()) { return JPyBoolean::getTrue(); } return JPyBoolean::getFalse(); } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::raiseJava(PyObject* , PyObject* args) { try { //PyObject* arg; //JPyArg::parseTuple(args, "O", &arg); //JPObject* obj; //JPCleaner cleaner; // //if (JPyCObject::check(arg) && string((char*)JPyCObject::getDesc(arg)) == "JPObject") //{ // obj = (JPObject*)JPyCObject::asVoidPtr(arg); //} //else //{ // JPyErr::setString(PyExc_TypeError, "You can only throw a subclass of java.lang.Throwable"); // return NULL; //} // //// check if claz is an instance of Throwable //JPClass* claz = obj->getClass(); //jclass jc = claz->getClass(); //cleaner.add(jc); //if (! JPJni::isThrowable(jc)) //{ // JPyErr::setString(PyExc_TypeError, "You can only throw a subclass of java.lang.Throwable"); // return NULL; //} // //jobject jobj = obj->getObject(); //cleaner.add(jobj); //JPEnv::getJava()->Throw((jthrowable)jobj); //PyJavaException::errorOccurred(); } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::attachThreadAsDaemon(PyObject* obj) { try { JPEnv::attachCurrentThreadAsDaemon(); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::startReferenceQueue(PyObject* obj, PyObject* args) { try { int i; JPyArg::parseTuple(args, "i", &i); JPJni::startJPypeReferenceQueue(i == 1); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::stopReferenceQueue(PyObject* obj) { try { JPJni::stopJPypeReferenceQueue(); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::setConvertStringObjects(PyObject* obj, PyObject* args) { try { PyObject* flag; JPyArg::parseTuple(args, "O", &flag); if (JPyBoolean::isTrue(flag)) { JPEnv::getJava()->setConvertStringObjects(true); } else { JPEnv::getJava()->setConvertStringObjects(false); } Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; } <commit_msg>[jvm-shutdown] disable jvm activity report<commit_after>/***************************************************************************** Copyright 2004 Steve M�nard 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 <jpype_python.h> PyObject* JPypeModule::startup(PyObject* obj, PyObject* args) { TRACE_IN("startup"); try { PyObject* vmOpt; PyObject* vmPath; char ignoreUnrecognized = true; JPyArg::parseTuple(args, "OO!b|", &vmPath, &PyTuple_Type, &vmOpt, &ignoreUnrecognized); if (! (JPyString::check(vmPath))) { RAISE(JPypeException, "First paramter must be a string or unicode"); } string cVmPath = JPyString::asString(vmPath); StringVector args; for (int i = 0; i < JPyObject::length(vmOpt); i++) { PyObject* obj = JPySequence::getItem(vmOpt, i); if (JPyString::check(obj)) { // TODO support unicode string v = JPyString::asString(obj); args.push_back(v); } else if (JPySequence::check(obj)) { //String name = arg[0]; //Callable value = arg[1]; // TODO complete this for the hooks .... } else { RAISE(JPypeException, "VM Arguments must be string or tuple"); } } JPEnv::loadJVM(cVmPath, ignoreUnrecognized, args); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; TRACE_OUT; } PyObject* JPypeModule::attach(PyObject* obj, PyObject* args) { TRACE_IN("attach"); try { PyObject* vmPath; JPyArg::parseTuple(args, "O", &vmPath); if (! (JPyString::check(vmPath))) { RAISE(JPypeException, "First paramter must be a string or unicode"); } string cVmPath = JPyString::asString(vmPath); JPEnv::attachJVM(cVmPath); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH return NULL; TRACE_OUT; } PyObject* JPypeModule::dumpJVMStats(PyObject* obj) { cerr << "JVM activity report :" << endl; //cerr << "\tmethod calls : " << methodCalls << endl; //cerr << "\tstatic method calls : " << staticMethodCalls << endl; //cerr << "\tconstructor calls : " << constructorCalls << endl; //cerr << "\tproxy callbacks : " << JProxy::getCallbackCount() << endl; //cerr << "\tfield gets : " << fieldGets << endl; //cerr << "\tfield sets : " << fieldSets << endl; cerr << "\tclasses loaded : " << JPTypeManager::getLoadedClasses() << endl; Py_INCREF(Py_None); return Py_None; } PyObject* JPypeModule::shutdown(PyObject* obj) { TRACE_IN("shutdown"); try { //dumpJVMStats(obj); JPEnv::getJava()->checkInitialized(); JPTypeManager::shutdown(); if (JPEnv::getJava()->DestroyJavaVM() ) { RAISE(JPypeException, "Unable to destroy JVM"); } JPEnv::getJava()->shutdown(); cerr << "JVM has been shutdown" << endl; Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; TRACE_OUT; } PyObject* JPypeModule::synchronized(PyObject* obj, PyObject* args) { JPCleaner cleaner; TRACE_IN("synchronized"); try { PyObject* o; JPyArg::parseTuple(args, "O!", &PyCapsule_Type, &o); string desc = (char*)JPyCObject::getDesc(o); jobject obj; if (desc == "JPObject") { JPObject* jpo = (JPObject*)JPyCObject::asVoidPtr(o); obj = jpo->getObject(); cleaner.addLocal(obj); } else if (desc == "JPClass") { JPClass* jpo = (JPClass*)JPyCObject::asVoidPtr(o); obj = jpo->getClass(); cleaner.addLocal(obj); } else if (desc == "JPArray") { JPArray* jpo = (JPArray*)JPyCObject::asVoidPtr(o); obj = jpo->getObject(); cleaner.addLocal(obj); } else if (desc == "JPArrayClass") { JPArrayClass* jpo = (JPArrayClass*)JPyCObject::asVoidPtr(o); obj = jpo->getClass(); cleaner.addLocal(obj); } else if (hostEnv->isWrapper(o) && hostEnv->getWrapperTypeName(o).isObjectType()) { obj = hostEnv->getWrapperValue(o).l; cleaner.addLocal(obj); } // TODO proxy else { RAISE(JPypeException, "method only accepts object values."); } PyJPMonitor* c = PyJPMonitor::alloc(new JPMonitor(obj)); return (PyObject*)c; } PY_STANDARD_CATCH; PyErr_Clear(); Py_INCREF(Py_None); return Py_None; TRACE_OUT; } PyObject* JPypeModule::isStarted(PyObject* obj) { if (JPEnv::isInitialized()) { return JPyBoolean::getTrue(); } return JPyBoolean::getFalse(); } PyObject* JPypeModule::attachThread(PyObject* obj) { try { JPEnv::attachCurrentThread(); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::detachThread(PyObject* obj) { try { JPEnv::getJava()->DetachCurrentThread(); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::isThreadAttached(PyObject* obj) { try { if (JPEnv::isThreadAttached()) { return JPyBoolean::getTrue(); } return JPyBoolean::getFalse(); } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::raiseJava(PyObject* , PyObject* args) { try { //PyObject* arg; //JPyArg::parseTuple(args, "O", &arg); //JPObject* obj; //JPCleaner cleaner; // //if (JPyCObject::check(arg) && string((char*)JPyCObject::getDesc(arg)) == "JPObject") //{ // obj = (JPObject*)JPyCObject::asVoidPtr(arg); //} //else //{ // JPyErr::setString(PyExc_TypeError, "You can only throw a subclass of java.lang.Throwable"); // return NULL; //} // //// check if claz is an instance of Throwable //JPClass* claz = obj->getClass(); //jclass jc = claz->getClass(); //cleaner.add(jc); //if (! JPJni::isThrowable(jc)) //{ // JPyErr::setString(PyExc_TypeError, "You can only throw a subclass of java.lang.Throwable"); // return NULL; //} // //jobject jobj = obj->getObject(); //cleaner.add(jobj); //JPEnv::getJava()->Throw((jthrowable)jobj); //PyJavaException::errorOccurred(); } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::attachThreadAsDaemon(PyObject* obj) { try { JPEnv::attachCurrentThreadAsDaemon(); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::startReferenceQueue(PyObject* obj, PyObject* args) { try { int i; JPyArg::parseTuple(args, "i", &i); JPJni::startJPypeReferenceQueue(i == 1); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::stopReferenceQueue(PyObject* obj) { try { JPJni::stopJPypeReferenceQueue(); Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; } PyObject* JPypeModule::setConvertStringObjects(PyObject* obj, PyObject* args) { try { PyObject* flag; JPyArg::parseTuple(args, "O", &flag); if (JPyBoolean::isTrue(flag)) { JPEnv::getJava()->setConvertStringObjects(true); } else { JPEnv::getJava()->setConvertStringObjects(false); } Py_INCREF(Py_None); return Py_None; } PY_STANDARD_CATCH; return NULL; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "highlight.h" #include <QtGui/QPainter> namespace QmlJSDebugger { namespace QtQuick2 { Highlight::Highlight(QQuickItem *item, QQuickItem *parent) : QQuickPaintedItem(parent) { setItem(item); } void Highlight::setItem(QQuickItem *item) { if (m_item) m_item.data()->disconnect(this); if (item) { connect(item, SIGNAL(xChanged()), SLOT(adjust())); connect(item, SIGNAL(yChanged()), SLOT(adjust())); connect(item, SIGNAL(widthChanged()), SLOT(adjust())); connect(item, SIGNAL(heightChanged()), SLOT(adjust())); connect(item, SIGNAL(rotationChanged()), SLOT(adjust())); connect(item, SIGNAL(transformOriginChanged(TransformOrigin)), SLOT(adjust())); } m_item = item; adjust(); } void Highlight::adjust() { const QQuickItem *item = m_item.data(); setSize(QSizeF(item->width(), item->height())); setPos(parentItem()->mapFromItem(item->parentItem(), item->pos())); setRotation(item->rotation()); setTransformOrigin(item->transformOrigin()); } void HoverHighlight::paint(QPainter *painter) { painter->setPen(QColor(108, 141, 221)); painter->drawRect(QRect(0, 0, width() - 1, height() - 1)); } void SelectionHighlight::paint(QPainter *painter) { painter->setPen(QPen(QColor(0, 22, 159))); painter->drawRect(QRect(1, 1, width() - 3, height() - 3)); painter->setPen(QColor(158, 199, 255)); painter->drawRect(QRect(0, 0, width() - 1, height() - 1)); } } // namespace QtQuick2 } // namespace QmlJSDebugger <commit_msg>Debugger: Inspect tool - changes made to highlight on selection<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "highlight.h" #include <QtGui/QPainter> namespace QmlJSDebugger { namespace QtQuick2 { Highlight::Highlight(QQuickItem *item, QQuickItem *parent) : QQuickPaintedItem(parent) { setItem(item); } void Highlight::setItem(QQuickItem *item) { if (m_item) m_item.data()->disconnect(this); if (item) { connect(item, SIGNAL(xChanged()), SLOT(adjust())); connect(item, SIGNAL(yChanged()), SLOT(adjust())); connect(item, SIGNAL(widthChanged()), SLOT(adjust())); connect(item, SIGNAL(heightChanged()), SLOT(adjust())); connect(item, SIGNAL(rotationChanged()), SLOT(adjust())); connect(item, SIGNAL(transformOriginChanged(TransformOrigin)), SLOT(adjust())); } m_item = item; adjust(); } void Highlight::adjust() { const QQuickItem *item = m_item.data(); setSize(QSizeF(item->width(), item->height())); setPos(parentItem()->mapFromItem(item->parentItem(), item->pos())); setRotation(item->rotation()); setTransformOrigin(item->transformOrigin()); } void HoverHighlight::paint(QPainter *painter) { painter->setPen(QColor(108, 141, 221)); painter->drawRect(QRect(0, 0, width() - 1, height() - 1)); } void SelectionHighlight::paint(QPainter *painter) { if (height() >= 10 && width() >= 10) { QColor colorHighlight = Qt::green; painter->fillRect(QRectF(0, 0, width(), 5), colorHighlight); painter->fillRect(QRectF(0, height()-5, width(), 5), colorHighlight); painter->fillRect(QRectF(0, 5, 5, height() - 10), colorHighlight); painter->fillRect(QRectF(width()-5, 5, 5, height() - 10), colorHighlight); } painter->setPen(QPen(QColor(0, 22, 159))); painter->drawRect(QRect(1, 1, width() - 3, height() - 3)); painter->setPen(QColor(158, 199, 255)); painter->drawRect(QRect(0, 0, width() - 1, height() - 1)); } } // namespace QtQuick2 } // namespace QmlJSDebugger <|endoftext|>
<commit_before>//============================================================================== // Heun solver class //============================================================================== #include "heunsolver.h" //============================================================================== namespace OpenCOR { namespace HeunSolver { //============================================================================== HeunSolver::HeunSolver() : mStep(DefaultStep), mK(0), mYk(0) { } //============================================================================== HeunSolver::~HeunSolver() { // Delete some internal objects delete[] mK; delete[] mYk; } //============================================================================== void HeunSolver::initialize(const double &pVoiStart, const int &pStatesCount, double *pConstants, double *pStates, double *pRates, double *pAlgebraic, ComputeRatesFunction pComputeRates) { // Initialise the ODE solver itself OpenCOR::CoreSolver::CoreOdeSolver::initialize(pVoiStart, pStatesCount, pConstants, pStates, pRates, pAlgebraic, pComputeRates); // Retrieve the solver's properties if (mProperties.contains(StepProperty)) { mStep = mProperties.value(StepProperty).toDouble(); if (!mStep) emit error(QObject::tr("the 'step' property value cannot be equal to zero")); } else { emit error(QObject::tr("the 'step' property value could not be retrieved")); } // (Re-)create our various arrays delete[] mK; delete[] mYk; mK = new double[pStatesCount]; mYk = new double[pStatesCount]; } //============================================================================== void HeunSolver::solve(double &pVoi, const double &pVoiEnd) const { // k = h * f(t_n, Y_n) // Y_n+1 = Y_n + h / 2 * (f(t_n, Y_n) + f(t_n + h, Y_n + k)) double voiStart = pVoi; int stepNumber = 0; double realStep = mStep; double realHalfStep = 0.5*realStep; while (pVoi != pVoiEnd) { // Check that the time step is correct if (pVoi+realStep > pVoiEnd) { realStep = pVoiEnd-pVoi; realHalfStep = 0.5*realStep; } // Compute f(t_n, Y_n) mComputeRates(pVoi, mConstants, mRates, mStates, mAlgebraic); // Compute k and Yk for (int i = 0; i < mStatesCount; ++i) { mK[i] = mRates[i]; mYk[i] = mStates[i]+realStep*mK[i]; } // Compute f(t_n + h, Y_n + k) mComputeRates(pVoi+realStep, mConstants, mRates, mYk, mAlgebraic); // Compute Y_n+1 for (int i = 0; i < mStatesCount; ++i) mStates[i] += realHalfStep*(mK[i]+mRates[i]); // Advance through time if (realStep != mStep) pVoi = pVoiEnd; else pVoi = voiStart+(++stepNumber)*mStep; } } //============================================================================== } // namespace HeunSolver } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up.<commit_after>//============================================================================== // Heun solver class //============================================================================== #include "heunsolver.h" //============================================================================== namespace OpenCOR { namespace HeunSolver { //============================================================================== HeunSolver::HeunSolver() : mStep(DefaultStep), mK(0), mYk(0) { } //============================================================================== HeunSolver::~HeunSolver() { // Delete some internal objects delete[] mK; delete[] mYk; } //============================================================================== void HeunSolver::initialize(const double &pVoiStart, const int &pStatesCount, double *pConstants, double *pStates, double *pRates, double *pAlgebraic, ComputeRatesFunction pComputeRates) { // Initialise the ODE solver itself OpenCOR::CoreSolver::CoreOdeSolver::initialize(pVoiStart, pStatesCount, pConstants, pStates, pRates, pAlgebraic, pComputeRates); // Retrieve the solver's properties if (mProperties.contains(StepProperty)) { mStep = mProperties.value(StepProperty).toDouble(); if (!mStep) emit error(QObject::tr("the 'step' property value cannot be equal to zero")); } else { emit error(QObject::tr("the 'step' property value could not be retrieved")); } // (Re-)create our various arrays delete[] mK; delete[] mYk; mK = new double[pStatesCount]; mYk = new double[pStatesCount]; } //============================================================================== void HeunSolver::solve(double &pVoi, const double &pVoiEnd) const { // k = h * f(t_n, Y_n) // Y_n+1 = Y_n + h / 2 * ( f(t_n, Y_n) + f(t_n + h, Y_n + k) ) double voiStart = pVoi; int stepNumber = 0; double realStep = mStep; double realHalfStep = 0.5*realStep; while (pVoi != pVoiEnd) { // Check that the time step is correct if (pVoi+realStep > pVoiEnd) { realStep = pVoiEnd-pVoi; realHalfStep = 0.5*realStep; } // Compute f(t_n, Y_n) mComputeRates(pVoi, mConstants, mRates, mStates, mAlgebraic); // Compute k and Yk for (int i = 0; i < mStatesCount; ++i) { mK[i] = mRates[i]; mYk[i] = mStates[i]+realStep*mK[i]; } // Compute f(t_n + h, Y_n + k) mComputeRates(pVoi+realStep, mConstants, mRates, mYk, mAlgebraic); // Compute Y_n+1 for (int i = 0; i < mStatesCount; ++i) mStates[i] += realHalfStep*(mK[i]+mRates[i]); // Advance through time if (realStep != mStep) pVoi = pVoiEnd; else pVoi = voiStart+(++stepNumber)*mStep; } } //============================================================================== } // namespace HeunSolver } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/ssl_config_service.h" #if defined(OS_WIN) #include "net/base/ssl_config_service_win.h" #elif defined(OS_MACOSX) #include "net/base/ssl_config_service_mac.h" #else #include "net/base/ssl_config_service_defaults.h" #endif namespace net { // static SSLConfigService* SSLConfigService::CreateSystemSSLConfigService() { #if defined(OS_WIN) return new SSLConfigServiceWin; #elif defined(OS_MACOSX) return new SSLConfigServiceMac; #else return new SSLConfigServiceDefaults; #endif } // static bool SSLConfigService::IsKnownStrictTLSServer(const std::string& hostname) { // If you wish to add an entry to this list, please contact agl AT chromium // DOT org. // // If this list starts growing, it'll need to be something more efficient // than a linear list. static const char kStrictServers[][20] = { "www.google.com", "mail.google.com", "www.gmail.com", "docs.google.com", "clients1.google.com", // Removed until we update the XMPP servers with the renegotiation // extension. // "gmail.com", }; for (size_t i = 0; i < arraysize(kStrictServers); i++) { if (strcmp(hostname.c_str(), kStrictServers[i]) == 0) return true; } return false; } } // namespace net <commit_msg>Add sunshinepress.org to the list of renegotiation extension required hosts.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/ssl_config_service.h" #if defined(OS_WIN) #include "net/base/ssl_config_service_win.h" #elif defined(OS_MACOSX) #include "net/base/ssl_config_service_mac.h" #else #include "net/base/ssl_config_service_defaults.h" #endif namespace net { // static SSLConfigService* SSLConfigService::CreateSystemSSLConfigService() { #if defined(OS_WIN) return new SSLConfigServiceWin; #elif defined(OS_MACOSX) return new SSLConfigServiceMac; #else return new SSLConfigServiceDefaults; #endif } // static bool SSLConfigService::IsKnownStrictTLSServer(const std::string& hostname) { // If you wish to add an entry to this list, please contact agl AT chromium // DOT org. // // If this list starts growing, it'll need to be something more efficient // than a linear list. static const char kStrictServers[][22] = { "www.google.com", "mail.google.com", "www.gmail.com", "docs.google.com", "clients1.google.com", "sunshinepress.org", "www.sunshinepress.org", // Removed until we update the XMPP servers with the renegotiation // extension. // "gmail.com", }; for (size_t i = 0; i < arraysize(kStrictServers); i++) { // Note that the hostname is normalised to lower-case by this point. if (strcmp(hostname.c_str(), kStrictServers[i]) == 0) return true; } return false; } } // namespace net <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/http/http_network_layer.h" #include "base/field_trial.h" #include "base/logging.h" #include "base/string_util.h" #include "net/http/http_network_session.h" #include "net/http/http_network_transaction.h" #include "net/socket/client_socket_factory.h" #include "net/spdy/spdy_framer.h" #include "net/spdy/spdy_network_transaction.h" #include "net/spdy/spdy_session.h" #include "net/spdy/spdy_session_pool.h" namespace net { //----------------------------------------------------------------------------- // static HttpTransactionFactory* HttpNetworkLayer::CreateFactory( HostResolver* host_resolver, ProxyService* proxy_service, SSLConfigService* ssl_config_service, HttpAuthHandlerFactory* http_auth_handler_factory, HttpNetworkDelegate* network_delegate, NetLog* net_log) { DCHECK(proxy_service); return new HttpNetworkLayer(ClientSocketFactory::GetDefaultFactory(), host_resolver, proxy_service, ssl_config_service, http_auth_handler_factory, network_delegate, net_log); } // static HttpTransactionFactory* HttpNetworkLayer::CreateFactory( HttpNetworkSession* session) { DCHECK(session); return new HttpNetworkLayer(session); } //----------------------------------------------------------------------------- HttpNetworkLayer::HttpNetworkLayer( ClientSocketFactory* socket_factory, HostResolver* host_resolver, ProxyService* proxy_service, SSLConfigService* ssl_config_service, HttpAuthHandlerFactory* http_auth_handler_factory, HttpNetworkDelegate* network_delegate, NetLog* net_log) : socket_factory_(socket_factory), host_resolver_(host_resolver), proxy_service_(proxy_service), ssl_config_service_(ssl_config_service), session_(NULL), spdy_session_pool_(NULL), http_auth_handler_factory_(http_auth_handler_factory), network_delegate_(network_delegate), net_log_(net_log), suspended_(false) { DCHECK(proxy_service_); DCHECK(ssl_config_service_.get()); } HttpNetworkLayer::HttpNetworkLayer(HttpNetworkSession* session) : socket_factory_(ClientSocketFactory::GetDefaultFactory()), ssl_config_service_(NULL), session_(session), spdy_session_pool_(session->spdy_session_pool()), http_auth_handler_factory_(NULL), network_delegate_(NULL), net_log_(NULL), suspended_(false) { DCHECK(session_.get()); } HttpNetworkLayer::~HttpNetworkLayer() { } int HttpNetworkLayer::CreateTransaction(scoped_ptr<HttpTransaction>* trans) { if (suspended_) return ERR_NETWORK_IO_SUSPENDED; trans->reset(new HttpNetworkTransaction(GetSession())); return OK; } HttpCache* HttpNetworkLayer::GetCache() { return NULL; } void HttpNetworkLayer::Suspend(bool suspend) { suspended_ = suspend; if (suspend && session_) session_->tcp_socket_pool()->CloseIdleSockets(); } HttpNetworkSession* HttpNetworkLayer::GetSession() { if (!session_) { DCHECK(proxy_service_); SpdySessionPool* spdy_pool = new SpdySessionPool(); session_ = new HttpNetworkSession(host_resolver_, proxy_service_, socket_factory_, ssl_config_service_, spdy_pool, http_auth_handler_factory_, network_delegate_, net_log_); // These were just temps for lazy-initializing HttpNetworkSession. host_resolver_ = NULL; proxy_service_ = NULL; socket_factory_ = NULL; http_auth_handler_factory_ = NULL; net_log_ = NULL; network_delegate_ = NULL; } return session_; } // static void HttpNetworkLayer::EnableSpdy(const std::string& mode) { static const char kSSL[] = "ssl"; static const char kDisableSSL[] = "no-ssl"; static const char kDisableCompression[] = "no-compress"; static const char kDisableAltProtocols[] = "no-alt-protocols"; static const char kEnableVersionOne[] = "v1"; // If flow-control is enabled, received WINDOW_UPDATE and SETTINGS // messages are processed and outstanding window size is actually obeyed // when sending data frames, and WINDOW_UPDATE messages are generated // when data is consumed. static const char kEnableFlowControl[] = "flow-control"; // We want an A/B experiment between SPDY enabled and SPDY disabled, // but only for pages where SPDY *could have been* negotiated. To do // this, we use NPN, but prevent it from negotiating SPDY. If the // server negotiates HTTP, rather than SPDY, today that will only happen // on servers that installed NPN (and could have done SPDY). But this is // a bit of a hack, as this correlation between NPN and SPDY is not // really guaranteed. static const char kEnableNPN[] = "npn"; static const char kEnableNpnHttpOnly[] = "npn-http"; // Except for the first element, the order is irrelevant. First element // specifies the fallback in case nothing matches // (SSLClientSocket::kNextProtoNoOverlap). Otherwise, the SSL library // will choose the first overlapping protocol in the server's list, since // it presumedly has a better understanding of which protocol we should // use, therefore the rest of the ordering here is not important. static const char kNpnProtosFull[] = "\x08http/1.1\x06spdy/2"; // This is a temporary hack to pretend we support version 1. static const char kNpnProtosFullV1[] = "\x08http/1.1\x06spdy/1\x06spdy/2"; // No spdy specified. static const char kNpnProtosHttpOnly[] = "\x08http/1.1\x07http1.1"; std::vector<std::string> spdy_options; SplitString(mode, ',', &spdy_options); bool use_alt_protocols = true; for (std::vector<std::string>::iterator it = spdy_options.begin(); it != spdy_options.end(); ++it) { const std::string& option = *it; if (option == kDisableSSL) { SpdySession::SetSSLMode(false); // Disable SSL HttpNetworkTransaction::SetUseSSLOverSpdyWithoutNPN(false); HttpNetworkTransaction::SetUseSpdyWithoutNPN(true); } else if (option == kSSL) { HttpNetworkTransaction::SetUseSSLOverSpdyWithoutNPN(true); HttpNetworkTransaction::SetUseSpdyWithoutNPN(true); } else if (option == kDisableCompression) { spdy::SpdyFramer::set_enable_compression_default(false); } else if (option == kEnableNPN) { HttpNetworkTransaction::SetUseAlternateProtocols(use_alt_protocols); HttpNetworkTransaction::SetNextProtos(kNpnProtosFull); } else if (option == kEnableNpnHttpOnly) { // Avoid alternate protocol in this case. Otherwise, browser will try SSL // and then fallback to http. This introduces extra load. HttpNetworkTransaction::SetUseAlternateProtocols(false); HttpNetworkTransaction::SetNextProtos(kNpnProtosHttpOnly); } else if (option == kEnableVersionOne) { spdy::SpdyFramer::set_protocol_version(1); HttpNetworkTransaction::SetNextProtos(kNpnProtosFullV1); } else if (option == kDisableAltProtocols) { use_alt_protocols = false; HttpNetworkTransaction::SetUseAlternateProtocols(false); } else if (option == kEnableFlowControl) { SpdySession::SetFlowControl(true); } else if (option.empty() && it == spdy_options.begin()) { continue; } else { LOG(DFATAL) << "Unrecognized spdy option: " << option; } } } } // namespace net <commit_msg>Modify the SPDY v1 hack to only advertise v1 and not v2 over NPN. There is no point in advertising a protocol that won't work. (When in v1 mode, the protocol frames will all say v1, which, to a v2 server will likely be broken<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/http/http_network_layer.h" #include "base/field_trial.h" #include "base/logging.h" #include "base/string_util.h" #include "net/http/http_network_session.h" #include "net/http/http_network_transaction.h" #include "net/socket/client_socket_factory.h" #include "net/spdy/spdy_framer.h" #include "net/spdy/spdy_network_transaction.h" #include "net/spdy/spdy_session.h" #include "net/spdy/spdy_session_pool.h" namespace net { //----------------------------------------------------------------------------- // static HttpTransactionFactory* HttpNetworkLayer::CreateFactory( HostResolver* host_resolver, ProxyService* proxy_service, SSLConfigService* ssl_config_service, HttpAuthHandlerFactory* http_auth_handler_factory, HttpNetworkDelegate* network_delegate, NetLog* net_log) { DCHECK(proxy_service); return new HttpNetworkLayer(ClientSocketFactory::GetDefaultFactory(), host_resolver, proxy_service, ssl_config_service, http_auth_handler_factory, network_delegate, net_log); } // static HttpTransactionFactory* HttpNetworkLayer::CreateFactory( HttpNetworkSession* session) { DCHECK(session); return new HttpNetworkLayer(session); } //----------------------------------------------------------------------------- HttpNetworkLayer::HttpNetworkLayer( ClientSocketFactory* socket_factory, HostResolver* host_resolver, ProxyService* proxy_service, SSLConfigService* ssl_config_service, HttpAuthHandlerFactory* http_auth_handler_factory, HttpNetworkDelegate* network_delegate, NetLog* net_log) : socket_factory_(socket_factory), host_resolver_(host_resolver), proxy_service_(proxy_service), ssl_config_service_(ssl_config_service), session_(NULL), spdy_session_pool_(NULL), http_auth_handler_factory_(http_auth_handler_factory), network_delegate_(network_delegate), net_log_(net_log), suspended_(false) { DCHECK(proxy_service_); DCHECK(ssl_config_service_.get()); } HttpNetworkLayer::HttpNetworkLayer(HttpNetworkSession* session) : socket_factory_(ClientSocketFactory::GetDefaultFactory()), ssl_config_service_(NULL), session_(session), spdy_session_pool_(session->spdy_session_pool()), http_auth_handler_factory_(NULL), network_delegate_(NULL), net_log_(NULL), suspended_(false) { DCHECK(session_.get()); } HttpNetworkLayer::~HttpNetworkLayer() { } int HttpNetworkLayer::CreateTransaction(scoped_ptr<HttpTransaction>* trans) { if (suspended_) return ERR_NETWORK_IO_SUSPENDED; trans->reset(new HttpNetworkTransaction(GetSession())); return OK; } HttpCache* HttpNetworkLayer::GetCache() { return NULL; } void HttpNetworkLayer::Suspend(bool suspend) { suspended_ = suspend; if (suspend && session_) session_->tcp_socket_pool()->CloseIdleSockets(); } HttpNetworkSession* HttpNetworkLayer::GetSession() { if (!session_) { DCHECK(proxy_service_); SpdySessionPool* spdy_pool = new SpdySessionPool(); session_ = new HttpNetworkSession(host_resolver_, proxy_service_, socket_factory_, ssl_config_service_, spdy_pool, http_auth_handler_factory_, network_delegate_, net_log_); // These were just temps for lazy-initializing HttpNetworkSession. host_resolver_ = NULL; proxy_service_ = NULL; socket_factory_ = NULL; http_auth_handler_factory_ = NULL; net_log_ = NULL; network_delegate_ = NULL; } return session_; } // static void HttpNetworkLayer::EnableSpdy(const std::string& mode) { static const char kSSL[] = "ssl"; static const char kDisableSSL[] = "no-ssl"; static const char kDisableCompression[] = "no-compress"; static const char kDisableAltProtocols[] = "no-alt-protocols"; static const char kEnableVersionOne[] = "v1"; // If flow-control is enabled, received WINDOW_UPDATE and SETTINGS // messages are processed and outstanding window size is actually obeyed // when sending data frames, and WINDOW_UPDATE messages are generated // when data is consumed. static const char kEnableFlowControl[] = "flow-control"; // We want an A/B experiment between SPDY enabled and SPDY disabled, // but only for pages where SPDY *could have been* negotiated. To do // this, we use NPN, but prevent it from negotiating SPDY. If the // server negotiates HTTP, rather than SPDY, today that will only happen // on servers that installed NPN (and could have done SPDY). But this is // a bit of a hack, as this correlation between NPN and SPDY is not // really guaranteed. static const char kEnableNPN[] = "npn"; static const char kEnableNpnHttpOnly[] = "npn-http"; // Except for the first element, the order is irrelevant. First element // specifies the fallback in case nothing matches // (SSLClientSocket::kNextProtoNoOverlap). Otherwise, the SSL library // will choose the first overlapping protocol in the server's list, since // it presumedly has a better understanding of which protocol we should // use, therefore the rest of the ordering here is not important. static const char kNpnProtosFull[] = "\x08http/1.1\x06spdy/2"; // This is a temporary hack to pretend we support version 1. static const char kNpnProtosFullV1[] = "\x08http/1.1\x06spdy/1"; // No spdy specified. static const char kNpnProtosHttpOnly[] = "\x08http/1.1\x07http1.1"; std::vector<std::string> spdy_options; SplitString(mode, ',', &spdy_options); bool use_alt_protocols = true; for (std::vector<std::string>::iterator it = spdy_options.begin(); it != spdy_options.end(); ++it) { const std::string& option = *it; if (option == kDisableSSL) { SpdySession::SetSSLMode(false); // Disable SSL HttpNetworkTransaction::SetUseSSLOverSpdyWithoutNPN(false); HttpNetworkTransaction::SetUseSpdyWithoutNPN(true); } else if (option == kSSL) { HttpNetworkTransaction::SetUseSSLOverSpdyWithoutNPN(true); HttpNetworkTransaction::SetUseSpdyWithoutNPN(true); } else if (option == kDisableCompression) { spdy::SpdyFramer::set_enable_compression_default(false); } else if (option == kEnableNPN) { HttpNetworkTransaction::SetUseAlternateProtocols(use_alt_protocols); HttpNetworkTransaction::SetNextProtos(kNpnProtosFull); } else if (option == kEnableNpnHttpOnly) { // Avoid alternate protocol in this case. Otherwise, browser will try SSL // and then fallback to http. This introduces extra load. HttpNetworkTransaction::SetUseAlternateProtocols(false); HttpNetworkTransaction::SetNextProtos(kNpnProtosHttpOnly); } else if (option == kEnableVersionOne) { spdy::SpdyFramer::set_protocol_version(1); HttpNetworkTransaction::SetNextProtos(kNpnProtosFullV1); } else if (option == kDisableAltProtocols) { use_alt_protocols = false; HttpNetworkTransaction::SetUseAlternateProtocols(false); } else if (option == kEnableFlowControl) { SpdySession::SetFlowControl(true); } else if (option.empty() && it == spdy_options.begin()) { continue; } else { LOG(DFATAL) << "Unrecognized spdy option: " << option; } } } } // namespace net <|endoftext|>
<commit_before>// Debugging Settings #define DEBUG #define DEBUG_V1 #define DEBUG_V2 #define DEBUG_V3 //#define DEBUG_V4 #include <iostream> #include <iomanip> #include <memory> #include <random> #include <iterator> #include <functional> #include <ctime> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <memory.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/resource.h> #include <math.h> #include <bsl_memory.h> #include <bslma_testallocator.h> #include <bslma_newdeleteallocator.h> #include <bsls_stopwatch.h> #include <bdlma_sequentialpool.h> #include <bdlma_sequentialallocator.h> #include <bdlma_bufferedsequentialallocator.h> #include <bdlma_multipoolallocator.h> #include <vector> #include <list> #include "benchmark_common.h" // Debugging #include <typeinfo> #include <assert.h> using namespace BloombergLP; // Global Variables #ifdef DEBUG int AF_RF_PRODUCT = 256; #else int AF_RF_PRODUCT = 2560; #endif // DEBUG template<typename ALLOC> class AllocSubsystem { public: ALLOC d_alloc; std::list<int, alloc_adaptor<int, ALLOC> > d_list; AllocSubsystem() : d_alloc(), d_list(&d_alloc) {} }; class DefaultSubsystem { public: std::list<int> d_list; DefaultSubsystem() : d_list() {} }; // Convenience typedefs struct subsystems { typedef DefaultSubsystem def; typedef AllocSubsystem<BloombergLP::bdlma::MultipoolAllocator> multipool; }; template<typename VECTOR> double access_lists(VECTOR *vec, int af, int rf) { #ifdef DEBUG_V3 std::cout << "Accessing Lists" << std::endl; #endif // DEBUG_V3 std::clock_t c_start = std::clock(); for (size_t r = 0; r < rf; r++) { for (size_t i = 0; i < vec->size(); i++) { for (size_t a = 0; a < af; a++) { for (auto it = (*vec)[i]->d_list.begin(); it != (*vec)[i]->d_list.end(); ++it) { (*it)++; // Increment int to cause loop to have some effect } clobber(); // TODO will this hurt caching? } } } std::clock_t c_end = std::clock(); #ifdef DEBUG_V3 std::cout << "Finished accessing Lists" << std::endl; #endif // DEBUG_V3 return (c_end - c_start) * 1.0 / CLOCKS_PER_SEC; } template<typename SUBSYS> double run_combination(int G, int S, int af, int sf, int rf) { // G = Total system size (# subsystems * elements in subsystems). Given as power of 2 (size really = 2^G) // S = Elements per subsystem. Given as power of 2 (size really = 2^S) // af = Access Factor - Number of iterations through a subsystem (linked list) before moving to the next // sf = Shuffle Factor - Number of elements popped from each list and pushed to a randomly chosen list // Note: -ve value means access occurs before shuffle // rf = Repeat Factor - Number of times the subsystems are iterated over int k = std::abs(G) - std::abs(S); size_t expanded_S = 1, expanded_k = 1; expanded_S <<= S; expanded_k <<= k; #ifdef DEBUG_V3 std::cout << "Total number of lists (k) = 2^" << k << " (aka " << expanded_k << ")" << std::endl; std::cout << "Total number of elements per sub system (S) = 2^" << S << " (aka " << expanded_S << ")" << std::endl; #endif // DEBUG_V3 std::vector<SUBSYS *> vec; // Create data under test vec.reserve(expanded_k); for (size_t i = 0; i < expanded_k; i++) { vec.emplace_back(new SUBSYS()); // Never deallocated because we exit immediately after this function reutrns anyway for (size_t j = 0; j < expanded_S; j++) { vec.back()->d_list.emplace_back((int)j); } } #ifdef DEBUG_V3 std::cout << "Created vector with " << vec.size() << " elements" << std::endl; #endif // DEBUG_V3 double result = 0.0; if (sf < 0) { // Access the data #ifdef DEBUG_V3 std::cout << "Accessing data BEFORE shuffling" << std::endl; #endif // DEBUG_V3 result = access_lists(&vec, af, rf); } // Shuffle the data #ifdef DEBUG_V3 std::cout << "Shuffling data " << std::abs(sf) << " times" << std::endl; #endif // DEBUG_V3 std::default_random_engine generator(1); // Consistent seed to get the same (pseudo) random distribution each time std::uniform_int_distribution<size_t> position_distribution(0, vec.size() - 1); for (size_t i = 0; i < std::abs(sf); i++) { for (size_t j = 0; j < vec.size(); j++) { if(j%100000 == 0) { std::cout << "j:" << j << std::endl; } #ifdef DEBUG_V4 std::cout << "Generating position" << std::endl; #endif // DEBUG_V4 size_t pos = position_distribution(generator); if (vec[j]->d_list.size() > 0) { // TODO: not quite what is in the paper #ifdef DEBUG_V4 std::cout << "Grabbing front element of list at " << j << std::endl; #endif // DEBUG_V4 int popped = vec[j]->d_list.front(); #ifdef DEBUG_V4 std::cout << "Emplacing " << popped << " into list at " << pos << std::endl; #endif // DEBUG_V4 vec[pos]->d_list.emplace_back(popped); #ifdef DEBUG_V4 std::cout << "Popping from front of list at " << j << " with " << vec[j]->d_list.size() << " elements" << std::endl; #endif // DEBUG_V4 vec[j]->d_list.pop_front(); } #ifdef DEBUG_V4 std::cout << "Finished iteration" << std::endl; #endif // DEBUG_V4 } } if (sf > 0) { // Access the data #ifdef DEBUG_V3 std::cout << "Accessing data AFTER shuffling" << std::endl; #endif // DEBUG_V3 result = access_lists(&vec, af, rf); } #ifdef DEBUG_V3 std::cout << "Deleting memory from vecor" << std::endl; #endif // DEBUG_V3 //for (size_t i = 0; i < vec.size(); i++) //{ // delete vec[i]; //} #ifdef DEBUG_V3 std::cout << "Done running combination" << std::endl; #endif // DEBUG_V3 return result; } void generate_table(int G, int alloc_num) { int sf = 5; for (int S = 0; S >= 0; S--) { // S = 21 std::cout << "S=" << S << " " << std::flush; for (int af = 256; af >= 1; af >>= 1) { int rf = AF_RF_PRODUCT / af; #ifdef DEBUG_V3 std::cout << "G: " << G << " S: " << S << " af: " << af << " sf: " << sf << " rf: " << rf << std::endl; #endif int pid = fork(); if (pid == 0) { // Child process double result = 0; switch (alloc_num) { case 0: { result = run_combination<typename subsystems::def>(G, S, af, sf, rf); break; } case 7: { result = run_combination<typename subsystems::multipool>(G, S, af, sf, rf); break; } } std::cout << result << " " << std::flush; exit(0); } else { int error; wait(&error); if (error) { std::cout << "Error code " << error << "at G: " << G << " S: " << S << " af: " << af << " sf: " << sf << " rf: " << rf << std::endl; } } } std::cout << std::endl; } } int main(int argc, char *argv[]) { // TODO: Notes: // 1) Incremented int by 1 on each iteration of af, to prevent compiler optimizing away loop (also used Chandler's // optimizer-defeating functions to access the ints after each iteration -- could this be a problem with caching?) // 2) Couldn't follow paper exactly, because popping off subsystems iteratively (then pushing randmonly) means that on // 2nd (and further) iterations through the list, some subsystems will not have an element to pop. // For baseline, G = 10^7, af = 10 std::cout << "Started" << std::endl; //size_t default_subsystem_size = sizeof(subsystems::def); //size_t alloc_subsystem_size = sizeof(subsystems::multipool); //size_t list_size = sizeof(subsystems::multipool::d_list); //size_t int_size = sizeof(int); //size_t ptr_size = sizeof(void *); //int G = 20; //std::cout << "Object Sizes" << std::endl; //std::cout << "Def: " << default_subsystem_size << " Alloc: " << alloc_subsystem_size << " List: " << list_size << " Int: " << int_size << " Pointer: " << ptr_size << std::endl; // //std::cout << "Total Sizes: " << std::endl; //std::cout << "Def: " << default_subsystem_size*(1 << G) << " Alloc: " << alloc_subsystem_size*(1 << G) << " List: " << list_size*(1 << G) << " Int: " << int_size*(1 << G) << " Pointer: " << ptr_size*(1 << G)*2 << std::endl; //std::cout << "Total Usage" << std::endl; //std::cout << default_subsystem_size*(1 << G) + int_size*(1 << G) + 2 * ptr_size*(1 << G) << std::endl; //struct rlimit rlim; //getrlimit(RLIMIT_AS, &rlim); //std::cout << "Limit: " << rlim.rlim_cur << std::endl; // //char * arr = new char[92274688]; //escape(arr); //arr[92274687] = 0; //std::vector<typename subsystems::def> vec; //std::allocator<int> alloc; //vec.emplace_back(alloc); //std::vector<typename subsystems::multipool> vec_1; //BloombergLP::bdlma::MultipoolAllocator alloc_1; //vec_1.emplace_back(alloc_1); //{ // std::cout << "Creating allocator" << std::endl; // BloombergLP::bdlma::MultipoolAllocator alloc; // std::cout << "Creating Vector" << std::endl; // typename vectors::multipool vector(&alloc); // std::cout << "Creating List" << std::endl; // vector.emplace_back(&alloc); // std::cout << "Adding to list" << std::endl; // vector[0].push_back(3); // std::cout << "Reading from List/Vector" << std::endl; // std::cout << vector[0].back() << std::endl; // std::cout << "Destroying Vector/List" << std::endl; //} std::cout << "Problem Size 2^21 Without Allocators" << std::endl; generate_table(21, 0); //std::cout << "Problem Size 2^25 Without Allocators" << std::endl; //generate_table(25, 0); //std::cout << "Problem Size 2^21 With Allocators" << std::endl; //generate_table(21, 7); //std::cout << "Problem Size 2^25 With Allocators" << std::endl; //generate_table(25, 7); //run_combination<typename subsystems::multipool>(2, 1, 5, 5, 5); std::cout << "Done" << std::endl; } <commit_msg>Removed old code<commit_after>// Debugging Settings #define DEBUG #define DEBUG_V1 #define DEBUG_V2 #define DEBUG_V3 //#define DEBUG_V4 #include <iostream> #include <iomanip> #include <memory> #include <random> #include <iterator> #include <functional> #include <ctime> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <memory.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/resource.h> #include <math.h> #include <bsl_memory.h> #include <bslma_testallocator.h> #include <bslma_newdeleteallocator.h> #include <bsls_stopwatch.h> #include <bdlma_sequentialpool.h> #include <bdlma_sequentialallocator.h> #include <bdlma_bufferedsequentialallocator.h> #include <bdlma_multipoolallocator.h> #include <vector> #include <list> #include "benchmark_common.h" // Debugging #include <typeinfo> #include <assert.h> using namespace BloombergLP; // Global Variables #ifdef DEBUG int AF_RF_PRODUCT = 256; #else int AF_RF_PRODUCT = 2560; #endif // DEBUG template<typename ALLOC> class AllocSubsystem { public: ALLOC d_alloc; std::list<int, alloc_adaptor<int, ALLOC> > d_list; AllocSubsystem() : d_alloc(), d_list(&d_alloc) {} }; class DefaultSubsystem { public: std::list<int> d_list; DefaultSubsystem() : d_list() {} }; // Convenience typedefs struct subsystems { typedef DefaultSubsystem def; typedef AllocSubsystem<BloombergLP::bdlma::MultipoolAllocator> multipool; }; template<typename VECTOR> double access_lists(VECTOR *vec, int af, int rf) { #ifdef DEBUG_V3 std::cout << "Accessing Lists" << std::endl; #endif // DEBUG_V3 std::clock_t c_start = std::clock(); for (size_t r = 0; r < rf; r++) { for (size_t i = 0; i < vec->size(); i++) { for (size_t a = 0; a < af; a++) { for (auto it = (*vec)[i]->d_list.begin(); it != (*vec)[i]->d_list.end(); ++it) { (*it)++; // Increment int to cause loop to have some effect } clobber(); // TODO will this hurt caching? } } } std::clock_t c_end = std::clock(); #ifdef DEBUG_V3 std::cout << "Finished accessing Lists" << std::endl; #endif // DEBUG_V3 return (c_end - c_start) * 1.0 / CLOCKS_PER_SEC; } template<typename SUBSYS> double run_combination(int G, int S, int af, int sf, int rf) { // G = Total system size (# subsystems * elements in subsystems). Given as power of 2 (size really = 2^G) // S = Elements per subsystem. Given as power of 2 (size really = 2^S) // af = Access Factor - Number of iterations through a subsystem (linked list) before moving to the next // sf = Shuffle Factor - Number of elements popped from each list and pushed to a randomly chosen list // Note: -ve value means access occurs before shuffle // rf = Repeat Factor - Number of times the subsystems are iterated over int k = std::abs(G) - std::abs(S); size_t expanded_S = 1, expanded_k = 1; expanded_S <<= S; expanded_k <<= k; #ifdef DEBUG_V3 std::cout << "Total number of lists (k) = 2^" << k << " (aka " << expanded_k << ")" << std::endl; std::cout << "Total number of elements per sub system (S) = 2^" << S << " (aka " << expanded_S << ")" << std::endl; #endif // DEBUG_V3 std::vector<SUBSYS *> vec; // Create data under test vec.reserve(expanded_k); for (size_t i = 0; i < expanded_k; i++) { vec.emplace_back(new SUBSYS()); // Never deallocated because we exit immediately after this function reutrns anyway for (size_t j = 0; j < expanded_S; j++) { vec.back()->d_list.emplace_back((int)j); } } #ifdef DEBUG_V3 std::cout << "Created vector with " << vec.size() << " elements" << std::endl; #endif // DEBUG_V3 double result = 0.0; if (sf < 0) { // Access the data #ifdef DEBUG_V3 std::cout << "Accessing data BEFORE shuffling" << std::endl; #endif // DEBUG_V3 result = access_lists(&vec, af, rf); } // Shuffle the data #ifdef DEBUG_V3 std::cout << "Shuffling data " << std::abs(sf) << " times" << std::endl; #endif // DEBUG_V3 std::default_random_engine generator(1); // Consistent seed to get the same (pseudo) random distribution each time std::uniform_int_distribution<size_t> position_distribution(0, vec.size() - 1); for (size_t i = 0; i < std::abs(sf); i++) { for (size_t j = 0; j < vec.size(); j++) { if(j%100000 == 0) { std::cout << "j:" << j << std::endl; } #ifdef DEBUG_V4 std::cout << "Generating position" << std::endl; #endif // DEBUG_V4 size_t pos = position_distribution(generator); if (vec[j]->d_list.size() > 0) { // TODO: not quite what is in the paper #ifdef DEBUG_V4 std::cout << "Grabbing front element of list at " << j << std::endl; #endif // DEBUG_V4 int popped = vec[j]->d_list.front(); #ifdef DEBUG_V4 std::cout << "Emplacing " << popped << " into list at " << pos << std::endl; #endif // DEBUG_V4 vec[pos]->d_list.emplace_back(popped); #ifdef DEBUG_V4 std::cout << "Popping from front of list at " << j << " with " << vec[j]->d_list.size() << " elements" << std::endl; #endif // DEBUG_V4 vec[j]->d_list.pop_front(); } #ifdef DEBUG_V4 std::cout << "Finished iteration" << std::endl; #endif // DEBUG_V4 } } if (sf > 0) { // Access the data #ifdef DEBUG_V3 std::cout << "Accessing data AFTER shuffling" << std::endl; #endif // DEBUG_V3 result = access_lists(&vec, af, rf); } #ifdef DEBUG_V3 std::cout << "Done running combination" << std::endl; #endif // DEBUG_V3 return result; } void generate_table(int G, int alloc_num) { int sf = 5; for (int S = 0; S >= 0; S--) { // S = 21 std::cout << "S=" << S << " " << std::flush; for (int af = 256; af >= 1; af >>= 1) { int rf = AF_RF_PRODUCT / af; #ifdef DEBUG_V3 std::cout << "G: " << G << " S: " << S << " af: " << af << " sf: " << sf << " rf: " << rf << std::endl; #endif int pid = fork(); if (pid == 0) { // Child process double result = 0; switch (alloc_num) { case 0: { result = run_combination<typename subsystems::def>(G, S, af, sf, rf); break; } case 7: { result = run_combination<typename subsystems::multipool>(G, S, af, sf, rf); break; } } std::cout << result << " " << std::flush; exit(0); } else { int error; wait(&error); if (error) { std::cout << "Error code " << error << "at G: " << G << " S: " << S << " af: " << af << " sf: " << sf << " rf: " << rf << std::endl; } } } std::cout << std::endl; } } int main(int argc, char *argv[]) { // TODO: Notes: // 1) Incremented int by 1 on each iteration of af, to prevent compiler optimizing away loop (also used Chandler's // optimizer-defeating functions to access the ints after each iteration -- could this be a problem with caching?) // 2) Couldn't follow paper exactly, because popping off subsystems iteratively (then pushing randmonly) means that on // 2nd (and further) iterations through the list, some subsystems will not have an element to pop. // For baseline, G = 10^7, af = 10 std::cout << "Started" << std::endl; std::cout << "Problem Size 2^21 Without Allocators" << std::endl; generate_table(21, 0); std::cout << "Problem Size 2^25 Without Allocators" << std::endl; generate_table(25, 0); std::cout << "Problem Size 2^21 With Allocators" << std::endl; generate_table(21, 7); std::cout << "Problem Size 2^25 With Allocators" << std::endl; generate_table(25, 7); std::cout << "Done" << std::endl; } <|endoftext|>
<commit_before>#include <unistd.h> #include <string> #include <iostream> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include "FatSystem.h" #include "FatFilename.h" #include "FatEntry.h" #include "utils.h" using namespace std; /** * Opens the FAT resource */ FatSystem::FatSystem(string filename) : strange(0), totalSize(-1), listDeleted(false), contiguous(false) { fd = open(filename.c_str(), O_RDONLY); } FatSystem::~FatSystem() { close(fd); } /** * Reading some data */ void FatSystem::readData(int address, char *buffer, int size) { if (totalSize != -1 && address+size > totalSize) { cout << "! Trying to read outside the disk" << endl; } lseek(fd, address, SEEK_SET); read(fd, buffer, size); } /** * Parses FAT header */ void FatSystem::parseHeader() { char buffer[128]; readData(0x0, buffer, sizeof(buffer)); bytesPerSector = FAT_READ_SHORT(buffer, FAT_BYTES_PER_SECTOR); sectorsPerCluster = buffer[FAT_SECTORS_PER_CLUSTER]; reservedSectors = FAT_READ_SHORT(buffer, FAT_RESERVED_SECTORS); fats = buffer[FAT_FATS]; sectorsPerFat = FAT_READ_LONG(buffer, FAT_SECTORS_PER_FAT); rootDirectory = FAT_READ_LONG(buffer, FAT_ROOT_DIRECTORY); totalSectors = FAT_READ_LONG(buffer, FAT_TOTAL_SECTORS); diskLabel = string(buffer+FAT_DISK_LABEL, FAT_DISK_LABEL_SIZE); oemName = string(buffer+FAT_DISK_OEM, FAT_DISK_OEM_SIZE); fsType = string(buffer+FAT_DISK_FS, FAT_DISK_FS_SIZE); if (bytesPerSector != 512) { printf("WARNING: Bytes per sector is not 512 (%d)\n", bytesPerSector); strange++; } if (sectorsPerCluster > 128) { printf("WARNING: Sectors per cluster high (%d)\n", sectorsPerCluster); strange++; } if (reservedSectors != 0x20) { printf("WARNING: Reserved sectors !=0x20 (0x%08x)\n", reservedSectors); strange++; } if (fats != 2) { printf("WARNING: Fats number different of 2 (%d)\n", fats); strange++; } if (rootDirectory != 2) { printf("WARNING: Root directory is not 2 (%d)\n", rootDirectory); strange++; } } /** * Returns the 32-bit fat value for the given cluster number */ int FatSystem::nextCluster(int cluster) { char buffer[4]; if (contiguous) { return cluster+1; } readData(fatStart+4*cluster, buffer, sizeof(buffer)); int next = FAT_READ_LONG(buffer, 0); if (next >= 0x0ffffff0) { return FAT_LAST; } else { return next; } } int FatSystem::clusterAddress(int cluster) { return (dataStart + bytesPerSector*sectorsPerCluster*(cluster-2)); } vector<FatEntry> FatSystem::getEntries(int cluster) { vector<FatEntry> entries; FatFilename filename; if (cluster == 0) { cluster = rootDirectory; } do { int address = clusterAddress(cluster); char buffer[FAT_ENTRY_SIZE]; int i; for (i=0; i<bytesPerSector*sectorsPerCluster; i+=sizeof(buffer)) { // Reading data readData(address, buffer, sizeof(buffer)); address += sizeof(buffer); // Creating entry FatEntry entry; entry.attributes = buffer[FAT_ATTRIBUTES]; if (entry.attributes & FAT_ATTRIBUTES_LONGFILE) { // Long file part filename.append(buffer); } else { entry.shortName = string(buffer, 11); entry.longName = filename.getFilename(); entry.cluster = FAT_READ_SHORT(buffer, FAT_CLUSTER_LOW) | (FAT_READ_SHORT(buffer, FAT_CLUSTER_HIGH)<<16); entry.size = FAT_READ_LONG(buffer, FAT_FILESIZE); if (entry.attributes&FAT_ATTRIBUTES_DIR || entry.attributes&FAT_ATTRIBUTES_FILE) { entries.push_back(entry); } } } cluster = nextCluster(cluster); } while (cluster != FAT_LAST); return entries; } void FatSystem::list(FatPath &path) { int cluster; if (findDirectory(path, &cluster)) { list(cluster); } } void FatSystem::list(int cluster) { vector<FatEntry> entries = getEntries(cluster); vector<FatEntry>::iterator it; for (it=entries.begin(); it!=entries.end(); it++) { FatEntry &entry = *it; if (entry.isErased() && !listDeleted) { continue; } if (entry.isDirectory()) { printf("d"); } else { printf("f"); } string name = entry.getFilename(); if (entry.isDirectory()) { name += "/"; } printf(" %-40s", name.c_str()); printf(" c=%d", entry.cluster); if (!entry.isDirectory()) { printf(" s=%d", entry.size); } if (entry.isHidden()) { printf(" h"); } if (entry.isErased()) { printf(" d"); } printf("\n"); } } void FatSystem::readFile(int cluster, int size, FILE *f) { if (f == NULL) { f = stdout; } while ((size!=0) && cluster!=FAT_LAST) { int toRead = size; if (toRead > bytesPerCluster || size < 0) { toRead = bytesPerCluster; } char buffer[bytesPerCluster]; readData(clusterAddress(cluster), buffer, toRead); if (size != -1) { size -= toRead; } // Write file data to the given file fwrite(buffer, toRead, 1, f); cluster = nextCluster(cluster); if (cluster == 0) { fprintf(stderr, "! One of your file's cluster is 0 (maybe FAT is broken, you should try -c)\n"); } } } bool FatSystem::init() { // Parsing header parseHeader(); // Computing values fatStart = bytesPerSector*reservedSectors; dataStart = fatStart + fats*sectorsPerFat*bytesPerSector; bytesPerCluster = bytesPerSector*sectorsPerCluster; totalSize = totalSectors*bytesPerSector; fatSize = sectorsPerFat*bytesPerSector; return strange == 0; } void FatSystem::infos() { cout << "FAT Filesystem informations" << endl << endl; cout << "Filesystem type: " << fsType << endl; cout << "OEM name: " << oemName << endl; cout << "Total sectors: " << totalSectors << endl; cout << "Disk size: " << totalSize << endl; cout << "Bytes per sector: " << bytesPerSector << endl; cout << "Sectors per cluster: " << sectorsPerCluster << endl; cout << "Bytes per cluster: " << bytesPerCluster << endl; cout << "Reserved sectors: " << reservedSectors << endl; cout << "Sectors per FAT: " << sectorsPerFat << endl; cout << "Fat size: " << fatSize << endl; printf("FAT start address: %08x\n", fatStart); printf("Data start address: %08x\n", dataStart); cout << "Root directory cluster: " << rootDirectory << endl; cout << "Disk label: " << diskLabel << endl; } bool FatSystem::findDirectory(FatPath &path, int *cluster) { vector<string> parts = path.getParts(); *cluster = rootDirectory; for (int i=0; i<parts.size(); i++) { if (parts[i] != "") { vector<FatEntry> entries = getEntries(*cluster); vector<FatEntry>::iterator it; bool found = false; for (it=entries.begin(); it!=entries.end(); it++) { FatEntry &entry = *it; string name = entry.getFilename(); if (name == parts[i]) { *cluster = entry.cluster; found = true; } } if (!found) { cerr << "Error: directory " << path.getPath() << " not found" << endl; return false; } } } return true; } bool FatSystem::findFile(FatPath &path, int *cluster, int *size, bool *erased) { string dirname = path.getDirname(); string basename = path.getBasename(); FatPath parent(dirname); int parentCluster; if (findDirectory(parent, &parentCluster)) { vector<FatEntry> entries = getEntries(parentCluster); vector<FatEntry>::iterator it; for (it=entries.begin(); it!=entries.end(); it++) { FatEntry &entry = (*it); if (entry.getFilename() == path.getBasename()) { *cluster = entry.cluster; *size = entry.size; *erased = entry.isErased(); return true; } } } return false; } void FatSystem::readFile(FatPath &path, FILE *f) { bool contiguousSave = contiguous; contiguous = false; int cluster, size; bool erased; if (findFile(path, &cluster, &size, &erased)) { contiguous = contiguousSave; if (erased && nextCluster(cluster)==0) { fprintf(stderr, "! Trying to read a deleted file, auto-enabling contiguous mode\n"); contiguous = true; } readFile(cluster, size, f); } } void FatSystem::setListDeleted(bool listDeleted_) { listDeleted = listDeleted_; } void FatSystem::setContiguous(bool contiguous_) { contiguous = contiguous_; } void FatSystem::extractEntry(FatEntry &entry, string directory) { vector<FatEntry> entries = getEntries(entry.cluster); vector<FatEntry>::iterator it; mkdir(directory.c_str(), 0755); for (it=entries.begin(); it!=entries.end(); it++) { FatEntry &entry = (*it); if (!entry.isErased()) { string name = entry.getFilename(); if (name == "." || name == "..") { continue; } string fullname = directory + "/" + name; if (entry.isDirectory()) { cout << "Entering " << fullname << endl; extractEntry(entry, fullname); } else { cout << "Extracting " << fullname << endl; FILE *output = fopen(fullname.c_str(), "w+"); if (output != NULL) { readFile(entry.cluster, entry.size, output); fclose(output); } else { fprintf(stderr, "! Unable to open %s\n", fullname.c_str()); } } } } } void FatSystem::extract(string directory) { FatEntry entry = rootEntry(); extractEntry(entry, directory); } FatEntry FatSystem::rootEntry() { FatEntry entry; entry.longName = "/"; entry.attributes = FAT_ATTRIBUTES_DIR; entry.cluster = rootDirectory; return entry; } <commit_msg>Extracting deleted files<commit_after>#include <unistd.h> #include <string> #include <iostream> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include "FatSystem.h" #include "FatFilename.h" #include "FatEntry.h" #include "utils.h" using namespace std; /** * Opens the FAT resource */ FatSystem::FatSystem(string filename) : strange(0), totalSize(-1), listDeleted(false), contiguous(false) { fd = open(filename.c_str(), O_RDONLY); } FatSystem::~FatSystem() { close(fd); } /** * Reading some data */ void FatSystem::readData(int address, char *buffer, int size) { if (totalSize != -1 && address+size > totalSize) { cout << "! Trying to read outside the disk" << endl; } lseek(fd, address, SEEK_SET); read(fd, buffer, size); } /** * Parses FAT header */ void FatSystem::parseHeader() { char buffer[128]; readData(0x0, buffer, sizeof(buffer)); bytesPerSector = FAT_READ_SHORT(buffer, FAT_BYTES_PER_SECTOR); sectorsPerCluster = buffer[FAT_SECTORS_PER_CLUSTER]; reservedSectors = FAT_READ_SHORT(buffer, FAT_RESERVED_SECTORS); fats = buffer[FAT_FATS]; sectorsPerFat = FAT_READ_LONG(buffer, FAT_SECTORS_PER_FAT); rootDirectory = FAT_READ_LONG(buffer, FAT_ROOT_DIRECTORY); totalSectors = FAT_READ_LONG(buffer, FAT_TOTAL_SECTORS); diskLabel = string(buffer+FAT_DISK_LABEL, FAT_DISK_LABEL_SIZE); oemName = string(buffer+FAT_DISK_OEM, FAT_DISK_OEM_SIZE); fsType = string(buffer+FAT_DISK_FS, FAT_DISK_FS_SIZE); if (bytesPerSector != 512) { printf("WARNING: Bytes per sector is not 512 (%d)\n", bytesPerSector); strange++; } if (sectorsPerCluster > 128) { printf("WARNING: Sectors per cluster high (%d)\n", sectorsPerCluster); strange++; } if (reservedSectors != 0x20) { printf("WARNING: Reserved sectors !=0x20 (0x%08x)\n", reservedSectors); strange++; } if (fats != 2) { printf("WARNING: Fats number different of 2 (%d)\n", fats); strange++; } if (rootDirectory != 2) { printf("WARNING: Root directory is not 2 (%d)\n", rootDirectory); strange++; } } /** * Returns the 32-bit fat value for the given cluster number */ int FatSystem::nextCluster(int cluster) { char buffer[4]; if (contiguous) { return cluster+1; } readData(fatStart+4*cluster, buffer, sizeof(buffer)); int next = FAT_READ_LONG(buffer, 0); if (next >= 0x0ffffff0) { return FAT_LAST; } else { return next; } } int FatSystem::clusterAddress(int cluster) { return (dataStart + bytesPerSector*sectorsPerCluster*(cluster-2)); } vector<FatEntry> FatSystem::getEntries(int cluster) { vector<FatEntry> entries; FatFilename filename; if (cluster == 0) { cluster = rootDirectory; } do { int address = clusterAddress(cluster); char buffer[FAT_ENTRY_SIZE]; int i; for (i=0; i<bytesPerSector*sectorsPerCluster; i+=sizeof(buffer)) { // Reading data readData(address, buffer, sizeof(buffer)); address += sizeof(buffer); // Creating entry FatEntry entry; entry.attributes = buffer[FAT_ATTRIBUTES]; if (entry.attributes & FAT_ATTRIBUTES_LONGFILE) { // Long file part filename.append(buffer); } else { entry.shortName = string(buffer, 11); entry.longName = filename.getFilename(); entry.cluster = FAT_READ_SHORT(buffer, FAT_CLUSTER_LOW) | (FAT_READ_SHORT(buffer, FAT_CLUSTER_HIGH)<<16); entry.size = FAT_READ_LONG(buffer, FAT_FILESIZE); if (entry.attributes&FAT_ATTRIBUTES_DIR || entry.attributes&FAT_ATTRIBUTES_FILE) { entries.push_back(entry); } } } cluster = nextCluster(cluster); } while (cluster != FAT_LAST); return entries; } void FatSystem::list(FatPath &path) { int cluster; if (findDirectory(path, &cluster)) { list(cluster); } } void FatSystem::list(int cluster) { vector<FatEntry> entries = getEntries(cluster); vector<FatEntry>::iterator it; for (it=entries.begin(); it!=entries.end(); it++) { FatEntry &entry = *it; if (entry.isErased() && !listDeleted) { continue; } if (entry.isDirectory()) { printf("d"); } else { printf("f"); } string name = entry.getFilename(); if (entry.isDirectory()) { name += "/"; } printf(" %-40s", name.c_str()); printf(" c=%d", entry.cluster); if (!entry.isDirectory()) { printf(" s=%d", entry.size); } if (entry.isHidden()) { printf(" h"); } if (entry.isErased()) { printf(" d"); } printf("\n"); } } void FatSystem::readFile(int cluster, int size, FILE *f) { if (f == NULL) { f = stdout; } while ((size!=0) && cluster!=FAT_LAST) { int toRead = size; if (toRead > bytesPerCluster || size < 0) { toRead = bytesPerCluster; } char buffer[bytesPerCluster]; readData(clusterAddress(cluster), buffer, toRead); if (size != -1) { size -= toRead; } // Write file data to the given file fwrite(buffer, toRead, 1, f); cluster = nextCluster(cluster); if (cluster == 0) { fprintf(stderr, "! One of your file's cluster is 0 (maybe FAT is broken, you should try -c)\n"); } } } bool FatSystem::init() { // Parsing header parseHeader(); // Computing values fatStart = bytesPerSector*reservedSectors; dataStart = fatStart + fats*sectorsPerFat*bytesPerSector; bytesPerCluster = bytesPerSector*sectorsPerCluster; totalSize = totalSectors*bytesPerSector; fatSize = sectorsPerFat*bytesPerSector; return strange == 0; } void FatSystem::infos() { cout << "FAT Filesystem informations" << endl << endl; cout << "Filesystem type: " << fsType << endl; cout << "OEM name: " << oemName << endl; cout << "Total sectors: " << totalSectors << endl; cout << "Disk size: " << totalSize << endl; cout << "Bytes per sector: " << bytesPerSector << endl; cout << "Sectors per cluster: " << sectorsPerCluster << endl; cout << "Bytes per cluster: " << bytesPerCluster << endl; cout << "Reserved sectors: " << reservedSectors << endl; cout << "Sectors per FAT: " << sectorsPerFat << endl; cout << "Fat size: " << fatSize << endl; printf("FAT start address: %08x\n", fatStart); printf("Data start address: %08x\n", dataStart); cout << "Root directory cluster: " << rootDirectory << endl; cout << "Disk label: " << diskLabel << endl; } bool FatSystem::findDirectory(FatPath &path, int *cluster) { vector<string> parts = path.getParts(); *cluster = rootDirectory; for (int i=0; i<parts.size(); i++) { if (parts[i] != "") { vector<FatEntry> entries = getEntries(*cluster); vector<FatEntry>::iterator it; bool found = false; for (it=entries.begin(); it!=entries.end(); it++) { FatEntry &entry = *it; string name = entry.getFilename(); if (name == parts[i]) { *cluster = entry.cluster; found = true; } } if (!found) { cerr << "Error: directory " << path.getPath() << " not found" << endl; return false; } } } return true; } bool FatSystem::findFile(FatPath &path, int *cluster, int *size, bool *erased) { string dirname = path.getDirname(); string basename = path.getBasename(); FatPath parent(dirname); int parentCluster; if (findDirectory(parent, &parentCluster)) { vector<FatEntry> entries = getEntries(parentCluster); vector<FatEntry>::iterator it; for (it=entries.begin(); it!=entries.end(); it++) { FatEntry &entry = (*it); if (entry.getFilename() == path.getBasename()) { *cluster = entry.cluster; *size = entry.size; *erased = entry.isErased(); return true; } } } return false; } void FatSystem::readFile(FatPath &path, FILE *f) { bool contiguousSave = contiguous; contiguous = false; int cluster, size; bool erased; if (findFile(path, &cluster, &size, &erased)) { contiguous = contiguousSave; if (erased && nextCluster(cluster)==0) { fprintf(stderr, "! Trying to read a deleted file, auto-enabling contiguous mode\n"); contiguous = true; } readFile(cluster, size, f); } } void FatSystem::setListDeleted(bool listDeleted_) { listDeleted = listDeleted_; } void FatSystem::setContiguous(bool contiguous_) { contiguous = contiguous_; } void FatSystem::extractEntry(FatEntry &entry, string directory) { vector<FatEntry> entries = getEntries(entry.cluster); vector<FatEntry>::iterator it; mkdir(directory.c_str(), 0755); for (it=entries.begin(); it!=entries.end(); it++) { FatEntry &entry = (*it); if (listDeleted || (!entry.isErased())) { string name = entry.getFilename(); if (name == "." || name == "..") { continue; } string fullname = directory + "/" + name; if (entry.isDirectory()) { cout << "Entering " << fullname << endl; extractEntry(entry, fullname); } else { cout << "Extracting " << fullname << endl; FILE *output = fopen(fullname.c_str(), "w+"); if (output != NULL) { bool contiguousSave = contiguous; if (entry.isErased() && nextCluster(entry.cluster)==0) { fprintf(stderr, "! Trying to read a deleted file, auto-enabling contiguous mode\n"); contiguous = true; } readFile(entry.cluster, entry.size, output); fclose(output); contiguous = contiguousSave; } else { fprintf(stderr, "! Unable to open %s\n", fullname.c_str()); } } } } } void FatSystem::extract(string directory) { FatEntry entry = rootEntry(); extractEntry(entry, directory); } FatEntry FatSystem::rootEntry() { FatEntry entry; entry.longName = "/"; entry.attributes = FAT_ATTRIBUTES_DIR; entry.cluster = rootDirectory; return entry; } <|endoftext|>
<commit_before># define CATCH_CONFIG_RUNNER # include "catch.hpp" # include <cmath> # include <string> int gcd(int a, int b) { if (b == 0) { return a; } else if(a==0) { return b; } else { return gcd(b, a%b); } } double mileToKilometer(double mile) { double kilometer; kilometer = mile*1.60934; return kilometer; } float ZylinderOberfl(float r, float h) { float oberfl = (2*M_PI*r*r)+(2*M_PI*r*h); return oberfl; } float ZylinderVol(float r, float h) { float vol = M_PI*(r*r)*h return vol; } float frac(float x) { int y = (int)x; int z = y-x; return z; } int checksum(int Zahl) { int sum = 0; while(Zahl>0) { sum += Zahl%10; Zahl /= 10; } return sum; } int sumMultiples() { int sum = 0; for (int i = 0; i <= 1000; i++) { if (i % 3 == 0) { sum += i; } else if (i % 5 == 0) { sum += i; } } return sum; } TEST_CASE("describe_gcd ", "[gcd]") { REQUIRE(gcd(2, 4) == 2); REQUIRE(gcd(6, 9) == 3); REQUIRE(gcd(3, 7) == 1); } TEST_CASE("describe_sumMultiples ", "[sumMultiples]") { REQUIRE(sumMultiples() ==234168); } TEST_CASE("describe_checksum ", "[checksum]") { REQUIRE(checksum(15) == 6); REQUIRE(checksum(25) == 7); REQUIRE(checksum(35) == 8); } TEST_CASE("describe_ZylinderVol","[ZylinderVol]") { REQUIRE(ZylinderVol(1,2) == Approx(6.283)); } TEST_CASE("describe_ZylinderOberfl","[ZylinderOberfl]") { REQUIRE(ZylinderOberfl(1,2) == Approx(18.85)); } TEST_CASE("describe_mileToKilometer","[mileToKilometer]") { REQUIRE(mileToKilometer(1) == Approx(1.60934)); REQUIRE(mileToKilometer(2) == Approx(3,21869)); REQUIRE(mileToKilometer(5) == Approx(8,04672)); } TEST_CASE("describe_frac","[frac]") { REQUIRE(frac(1.11) == Approx(0.11)); REQUIRE(frac(45.1234) == Approx(0.1234)); } int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } <commit_msg>Update tests.cpp<commit_after># define CATCH_CONFIG_RUNNER # include "catch.hpp" # include <cmath> # include <string> int gcd(int a, int b) { if (b == 0) { return a; } else if(a==0) { return b; } else if(a<b) { return gcd(b, a%b); } else { return gcd(b, a%b); } } double mileToKilometer(double mile) { double kilometer; kilometer = mile*1.60934; return kilometer; } float ZylinderOberfl(float r, float h) { float oberfl = (2*M_PI*r*r)+(2*M_PI*r*h); return oberfl; } float ZylinderVol(float r, float h) { float vol = M_PI*(r*r)*h return vol; } float frac(float x) { int y = (int)x; int z = y-x; return z; } int checksum(int Zahl) { int sum = 0; while(Zahl>0) { sum += Zahl%10; Zahl /= 10; } return sum; } int sumMultiples() { int sum = 0; for (int i = 0; i <= 1000; i++) { if (i % 3 == 0) { sum += i; } else if (i % 5 == 0) { sum += i; } } return sum; } TEST_CASE("describe_gcd ", "[gcd]") { REQUIRE(gcd(2, 4) == 2); REQUIRE(gcd(6, 9) == 3); REQUIRE(gcd(3, 7) == 1); } TEST_CASE("describe_sumMultiples ", "[sumMultiples]") { REQUIRE(sumMultiples() ==234168); } TEST_CASE("describe_checksum ", "[checksum]") { REQUIRE(checksum(15) == 6); REQUIRE(checksum(25) == 7); REQUIRE(checksum(35) == 8); } TEST_CASE("describe_ZylinderVol","[ZylinderVol]") { REQUIRE(ZylinderVol(1,2) == Approx(6.283)); } TEST_CASE("describe_ZylinderOberfl","[ZylinderOberfl]") { REQUIRE(ZylinderOberfl(1,2) == Approx(18.85)); } TEST_CASE("describe_mileToKilometer","[mileToKilometer]") { REQUIRE(mileToKilometer(1) == Approx(1.60934)); REQUIRE(mileToKilometer(2) == Approx(3,21869)); REQUIRE(mileToKilometer(5) == Approx(8,04672)); } TEST_CASE("describe_frac","[frac]") { REQUIRE(frac(1.11) == Approx(0.11)); REQUIRE(frac(45.1234) == Approx(0.1234)); } int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } <|endoftext|>
<commit_before>// gui.cpp // GUI for mancala game, using gtkmm // Copyright Matthew Chandler 2012 #include <iostream> #include <gdkmm/general.h> #include <glibmm/fileutils.h> #include <gtkmm/messagedialog.h> #include "gui.h" Mancala_draw::Mancala_draw(Mancala_win * Win): win(Win) { add_events(Gdk::BUTTON_PRESS_MASK); signal_button_press_event().connect(sigc::mem_fun(*this, &Mancala_draw::mouse_down)); try { bg_store = Gdk::Pixbuf::create_from_file("img/bg_store.png"); } catch(const Glib::FileError& ex) { std::cerr<<"FileError: "<<ex.what()<<std::endl; } catch(const Gdk::PixbufError& ex) { std::cerr<<"PixbufError: "<< ex.what()<<std::endl; } } bool Mancala_draw::on_draw(const Cairo::RefPtr<Cairo::Context>& cr) { Gtk::Allocation alloc = get_allocation(); cr->save(); cr->scale(alloc.get_width() / (double)bg_store->get_width() / (win->b.num_bowls + 2), alloc.get_height() / (double)bg_store->get_height()); Gdk::Cairo::set_source_pixbuf(cr, bg_store); cr->paint(); cr->restore(); cr->save(); cr->translate(alloc.get_width() * (1.0 - 1.0 / (win->b.num_bowls + 2)), 0); cr->scale(alloc.get_width() / (double)bg_store->get_width() / (win->b.num_bowls + 2), alloc.get_height() / (double)bg_store->get_height()); Gdk::Cairo::set_source_pixbuf(cr, bg_store); cr->paint(); cr->restore(); cr->set_source_rgb(1.0, 0.0, 0.0); for(int i = 1; i < win->b.num_bowls + 2; ++i) { cr->move_to(alloc.get_width() * (i / (double)(win->b.num_bowls + 2)), 0.0); cr->line_to(alloc.get_width() * (i / (double)(win->b.num_bowls + 2)), alloc.get_height()); cr->stroke(); } cr->move_to(1.0 / (win->b.num_bowls + 2) * alloc.get_width(), alloc.get_height() * .5); cr->line_to((1.0 - 1.0 / (win->b.num_bowls + 2)) * alloc.get_width(), alloc.get_height() * .5); cr->stroke(); Pango::FontDescription font("Monospace"); font.set_size(std::min(alloc.get_width(), alloc.get_height()) * .1 * Pango::SCALE); int tex_w, tex_h; cr->set_source_rgb(0.0, 0.0, 0.0); // draw # for left store std::ostringstream l_store_str; l_store_str<<win->b.bowls[win->b.p2_store].count; Glib::RefPtr<Pango::Layout> l_store_txt = create_pango_layout(l_store_str.str()); l_store_txt->set_font_description(font); l_store_txt->get_pixel_size(tex_w, tex_h); cr->move_to(alloc.get_width() * 1.0 / (2.0 * (win->b.num_bowls + 2)) - tex_w * .5, (alloc.get_height() - tex_h) * .5); l_store_txt->show_in_cairo_context(cr); // draw # for right store std::ostringstream r_store_str; r_store_str<<win->b.bowls[win->b.p1_store].count; Glib::RefPtr<Pango::Layout> r_store_txt = create_pango_layout(r_store_str.str()); r_store_txt->set_font_description(font); r_store_txt->get_pixel_size(tex_w, tex_h); cr->move_to(alloc.get_width() * (1.0 - 1.0 / (2.0 * (win->b.num_bowls + 2))) - tex_w * .5, (alloc.get_height() - tex_h) * .5); r_store_txt->show_in_cairo_context(cr); // draw #s for bowls for(int i = 0; i < win->b.num_bowls; ++i) { //upper row std::ostringstream upper_str; upper_str<<win->b.bowls[win->b.bowls[win->b.p1_start + i].across].count; Glib::RefPtr<Pango::Layout> upper_txt = create_pango_layout(upper_str.str()); upper_txt->set_font_description(font); upper_txt->get_pixel_size(tex_w, tex_h); cr->move_to(alloc.get_width() * (2 * i + 3) / (2.0 * (win->b.num_bowls + 2)) - tex_w * .5, alloc.get_height() * .25 - tex_h * .5); upper_txt->show_in_cairo_context(cr); //lower row std::ostringstream lower_str; lower_str<<win->b.bowls[win->b.p1_start + i].count; Glib::RefPtr<Pango::Layout> lower_txt = create_pango_layout(lower_str.str()); lower_txt->set_font_description(font); lower_txt->get_pixel_size(tex_w, tex_h); cr->move_to(alloc.get_width() * (2 * i + 3) / (2.0 * (win->b.num_bowls + 2)) - tex_w * .5, alloc.get_height() * .75 - tex_h * .5); lower_txt->show_in_cairo_context(cr); } return true; } bool Mancala_draw::mouse_down(GdkEventButton * event) { Gtk::Allocation alloc = get_allocation(); int grid_x = (int)((win->b.num_bowls + 2) * event->x / alloc.get_width()); int grid_y = (event->y / alloc.get_height() <= .5)? 0 : 1; if(grid_x > 0 && grid_x < win->b.num_bowls + 1 && !win->b.finished()) { if(win->player == 1 && grid_y == 1) { win->move(grid_x - 1); } if(win->player == 2 && grid_y == 0); } return true; } Mancala_win::Mancala_win(): main_box(Gtk::ORIENTATION_VERTICAL), hint_box(Gtk::ORIENTATION_HORIZONTAL), new_game_box(Gtk::ORIENTATION_HORIZONTAL), hint_b("Hint"), new_game_b("New Game"), draw(this), player(1) { // set window properties set_border_width(10); set_default_size(800,400); set_title("Mancala"); // add widgets to contatiners add(main_box); main_box.pack_start(player_label, Gtk::PACK_SHRINK); main_box.pack_start(draw); main_box.pack_end(new_game_box, Gtk::PACK_SHRINK); new_game_box.pack_start(new_game_b, Gtk::PACK_EXPAND_PADDING); main_box.pack_end(hint_box, Gtk::PACK_SHRINK); hint_box.pack_start(hint_b, Gtk::PACK_EXPAND_PADDING); hint_b.signal_clicked().connect(sigc::mem_fun(*this, &Mancala_win::hint)); new_game_b.signal_clicked().connect(sigc::mem_fun(*this, &Mancala_win::new_game)); // set all labels for number of seeds update_board(); show_all_children(); } // make a move (called by button signals) void Mancala_win::move(const int i) { if(b.bowls[b.p1_start + i].count <= 0) return; if(!b.move(i)) { //player = (player == 1)? 2 : 1; b.swapsides(); int ai_move = 0; do { if(b.finished()) break; ai_move = choosemove(b); } while(b.move(ai_move)); b.swapsides(); } update_board(); // check to see if the game is over if(b.finished()) { Glib::ustring msg; // check for a tie if(b.bowls[b.p1_store].count == b.bowls[b.p2_store].count) msg = "Tie"; // determine the current player, and then see if they won or lost else if(player == 1) if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count) msg = "Player 1 wins"; else msg = "Player 2 wins"; else if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count) msg = "Player 2 wins"; else msg = "Player 1 wins"; // was the win full of win? if(abs(b.bowls[b.p1_store].count - b.bowls[b.p2_store].count) >= 10) msg += "\nFATALITY"; //create and show a dialog announcing the winner Gtk::MessageDialog dlg(*this, "Game Over"); dlg.set_secondary_text(msg); dlg.run(); //make the game unplayable hint_b.set_state(Gtk::STATE_INSENSITIVE); } } // get a hint, will highlight a bowl void Mancala_win::hint() { // use AI function to find best move int bestmove = choosemove(b); } // start a new game void Mancala_win::new_game() { hint_b.set_state(Gtk::STATE_NORMAL); b = Board(); update_board(); } // update the numbers for each bowl / store void Mancala_win::update_board() { // Show who's turn it is TODO: ugly if(player == 1) player_label.set_text("Player 1"); else player_label.set_text("Player 2"); draw.queue_draw(); } <commit_msg>cleaned and optimized drawing scaling math<commit_after>// gui.cpp // GUI for mancala game, using gtkmm // Copyright Matthew Chandler 2012 #include <iostream> #include <gdkmm/general.h> #include <glibmm/fileutils.h> #include <gtkmm/messagedialog.h> #include "gui.h" Mancala_draw::Mancala_draw(Mancala_win * Win): win(Win) { add_events(Gdk::BUTTON_PRESS_MASK); signal_button_press_event().connect(sigc::mem_fun(*this, &Mancala_draw::mouse_down)); try { bg_store = Gdk::Pixbuf::create_from_file("img/bg_store.png"); } catch(const Glib::FileError& ex) { std::cerr<<"FileError: "<<ex.what()<<std::endl; } catch(const Gdk::PixbufError& ex) { std::cerr<<"PixbufError: "<< ex.what()<<std::endl; } } bool Mancala_draw::on_draw(const Cairo::RefPtr<Cairo::Context>& cr) { int num_cells = win->b.num_bowls + 2; double inv_num_cells = 1.0 / num_cells; Gtk::Allocation alloc = get_allocation(); cr->save(); cr->scale(alloc.get_width() / (double)bg_store->get_width() * inv_num_cells, alloc.get_height() / (double)bg_store->get_height()); Gdk::Cairo::set_source_pixbuf(cr, bg_store); cr->paint(); cr->restore(); cr->save(); cr->translate(alloc.get_width() * (1.0 - inv_num_cells), 0); cr->scale(alloc.get_width() / (double)bg_store->get_width() * inv_num_cells, alloc.get_height() / (double)bg_store->get_height()); Gdk::Cairo::set_source_pixbuf(cr, bg_store); cr->paint(); cr->restore(); cr->set_source_rgb(1.0, 0.0, 0.0); for(int i = 1; i < num_cells; ++i) { cr->move_to(alloc.get_width() * (i * inv_num_cells), 0.0); cr->line_to(alloc.get_width() * (i * inv_num_cells), alloc.get_height()); cr->stroke(); } cr->move_to(inv_num_cells * alloc.get_width(), alloc.get_height() * .5); cr->line_to((1.0 - inv_num_cells) * alloc.get_width(), alloc.get_height() * .5); cr->stroke(); Pango::FontDescription font("Monospace"); font.set_size(std::min(alloc.get_width(), alloc.get_height()) * .1 * Pango::SCALE); int tex_w, tex_h; cr->set_source_rgb(0.0, 0.0, 0.0); // draw # for left store std::ostringstream l_store_str; l_store_str<<win->b.bowls[win->b.p2_store].count; Glib::RefPtr<Pango::Layout> l_store_txt = create_pango_layout(l_store_str.str()); l_store_txt->set_font_description(font); l_store_txt->get_pixel_size(tex_w, tex_h); cr->move_to(alloc.get_width() * .5 * inv_num_cells - tex_w * .5, (alloc.get_height() - tex_h) * .5); l_store_txt->show_in_cairo_context(cr); // draw # for right store std::ostringstream r_store_str; r_store_str<<win->b.bowls[win->b.p1_store].count; Glib::RefPtr<Pango::Layout> r_store_txt = create_pango_layout(r_store_str.str()); r_store_txt->set_font_description(font); r_store_txt->get_pixel_size(tex_w, tex_h); cr->move_to(alloc.get_width() * (1.0 - .5 * inv_num_cells) - tex_w * .5, (alloc.get_height() - tex_h) * .5); r_store_txt->show_in_cairo_context(cr); // draw #s for bowls for(int i = 0; i < win->b.num_bowls; ++i) { //upper row std::ostringstream upper_str; upper_str<<win->b.bowls[win->b.bowls[win->b.p1_start + i].across].count; Glib::RefPtr<Pango::Layout> upper_txt = create_pango_layout(upper_str.str()); upper_txt->set_font_description(font); upper_txt->get_pixel_size(tex_w, tex_h); cr->move_to(alloc.get_width() * (2 * i + 3) * .5 * inv_num_cells - tex_w * .5, alloc.get_height() * .25 - tex_h * .5); upper_txt->show_in_cairo_context(cr); //lower row std::ostringstream lower_str; lower_str<<win->b.bowls[win->b.p1_start + i].count; Glib::RefPtr<Pango::Layout> lower_txt = create_pango_layout(lower_str.str()); lower_txt->set_font_description(font); lower_txt->get_pixel_size(tex_w, tex_h); cr->move_to(alloc.get_width() * (2 * i + 3) * .5 * inv_num_cells - tex_w * .5, alloc.get_height() * .75 - tex_h * .5); lower_txt->show_in_cairo_context(cr); } return true; } bool Mancala_draw::mouse_down(GdkEventButton * event) { Gtk::Allocation alloc = get_allocation(); int grid_x = (int)((win->b.num_bowls + 2) * event->x / alloc.get_width()); int grid_y = (event->y / alloc.get_height() <= .5)? 0 : 1; if(grid_x > 0 && grid_x < win->b.num_bowls + 1 && !win->b.finished()) { if(win->player == 1 && grid_y == 1) { win->move(grid_x - 1); } if(win->player == 2 && grid_y == 0); } return true; } Mancala_win::Mancala_win(): main_box(Gtk::ORIENTATION_VERTICAL), hint_box(Gtk::ORIENTATION_HORIZONTAL), new_game_box(Gtk::ORIENTATION_HORIZONTAL), hint_b("Hint"), new_game_b("New Game"), draw(this), player(1) { // set window properties set_border_width(10); set_default_size(800,400); set_title("Mancala"); // add widgets to contatiners add(main_box); main_box.pack_start(player_label, Gtk::PACK_SHRINK); main_box.pack_start(draw); main_box.pack_end(new_game_box, Gtk::PACK_SHRINK); new_game_box.pack_start(new_game_b, Gtk::PACK_EXPAND_PADDING); main_box.pack_end(hint_box, Gtk::PACK_SHRINK); hint_box.pack_start(hint_b, Gtk::PACK_EXPAND_PADDING); hint_b.signal_clicked().connect(sigc::mem_fun(*this, &Mancala_win::hint)); new_game_b.signal_clicked().connect(sigc::mem_fun(*this, &Mancala_win::new_game)); // set all labels for number of seeds update_board(); show_all_children(); } // make a move (called by button signals) void Mancala_win::move(const int i) { if(b.bowls[b.p1_start + i].count <= 0) return; if(!b.move(i)) { //player = (player == 1)? 2 : 1; b.swapsides(); int ai_move = 0; do { if(b.finished()) break; ai_move = choosemove(b); } while(b.move(ai_move)); b.swapsides(); } update_board(); // check to see if the game is over if(b.finished()) { Glib::ustring msg; // check for a tie if(b.bowls[b.p1_store].count == b.bowls[b.p2_store].count) msg = "Tie"; // determine the current player, and then see if they won or lost else if(player == 1) if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count) msg = "Player 1 wins"; else msg = "Player 2 wins"; else if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count) msg = "Player 2 wins"; else msg = "Player 1 wins"; // was the win full of win? if(abs(b.bowls[b.p1_store].count - b.bowls[b.p2_store].count) >= 10) msg += "\nFATALITY"; //create and show a dialog announcing the winner Gtk::MessageDialog dlg(*this, "Game Over"); dlg.set_secondary_text(msg); dlg.run(); //make the game unplayable hint_b.set_state(Gtk::STATE_INSENSITIVE); } } // get a hint, will highlight a bowl void Mancala_win::hint() { // use AI function to find best move int bestmove = choosemove(b); } // start a new game void Mancala_win::new_game() { hint_b.set_state(Gtk::STATE_NORMAL); b = Board(); update_board(); } // update the numbers for each bowl / store void Mancala_win::update_board() { // Show who's turn it is TODO: ugly if(player == 1) player_label.set_text("Player 1"); else player_label.set_text("Player 2"); draw.queue_draw(); } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The Descent map loader // // NAME : Hog // PURPOSE : Providing a decoder and wrapper for the Descent .HOG format. // COPYRIGHT : (c) 2011 Sean Donnellan. All Rights Reserved. // AUTHORS : Sean Donnellan (darkdonno@gmail.com) // DESCRIPTION : A decoder for the HOG file format that is used by Parallax // Software in the computer game, Descent. // // The file format is as follows: // // - Magic number which is 3 bytes and corresponding to the // string "DHF" // - A series of files which are preceded by a short header, // which describes the name of the file and the numer of bytes. // // | "DHF" - 3 bytes // |---------------- Start of the first file // | filename - 13 bytes // | size - 4 bytes // | data - the size of this part is by the size before it. // |---------------- The next header/file comes straight after. // | filename - 13 bytes // | size - 4 bytes // | data - the size of this part is by the size before it. // //===----------------------------------------------------------------------===// ///// // Developer notes // Different file formats: http://www.descent2.com/ddn/kb/files/ // ///// #include "cube.hpp" #include "hogreader.hpp" #include "hogiterator.hpp" #include "rdl.hpp" #include <memory> #include <iterator> #include <utility> #include <vector> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _MSC_VER static_assert(sizeof(uint8_t) == 1, "The size of uint8_t is incorrect it must be 1-byte"); static_assert(sizeof(uint32_t) == 4, "The size of uint32_t is incorrect it must be 4-bytes"); static_assert(sizeof(uint8_t) == sizeof(char), "The size of a char must be 1-byte"); #endif // The 3-byte MAGIC number at the start of the file format used to identifiy the // file as being a Descent HOG file. static uint8_t magic[3] = { 'D', 'H', 'F' }; HogReader::iterator HogReader::begin() { // Sync back up to the start just after the magic number. if (IsValid()) { fseek(myFile, sizeof(magic), SEEK_SET); if (fread(&myChildFile.name, 13, 1, myFile) != 1) HogReaderIterator(); if (fread(&myChildFile.size, 4, 1, myFile) != 1) HogReaderIterator(); } return HogReaderIterator(*this); } HogReader::iterator HogReader::end() { return HogReaderIterator(); } HogReader::HogReader(const char* filename) : myFile(nullptr), hasReadFile(false) { myFile = fopen(filename, "rb"); myChildFile.name[0] = '\0'; myChildFile.size = 0; if (!myFile) return; const size_t count = 1; if (fread(myHeader, sizeof(myHeader), count, myFile) != count) { myHeader[0] = '\0'; // Failed to load. return; } // Read in the header for the first file. if (IsValid()) { if (fread(&myChildFile.name, 13, 1, myFile) != 1) return; if (fread(&myChildFile.size, 4, 1, myFile) != 1) return; } } HogReader::~HogReader() { if (myFile) fclose(myFile); } bool HogReader::IsValid() const { if (!myFile) return false; return memcmp(myHeader, magic, 3) == 0; } bool HogReader::NextFile() { // Skip the current file. if (feof(myFile)) return false; if (!hasReadFile) { // The data for the current file has not been read so skip over the data // section // for the file. if (fseek(myFile, myChildFile.size, SEEK_CUR) != 0) return false; } // Read in the header for the next file. if (fread(&myChildFile.name, 13, 1, myFile) != 1) return false; if (fread(&myChildFile.size, 4, 1, myFile) != 1) return false; hasReadFile = false; // We haven't read the next file yet. return true; } const char* HogReader::CurrentFileName() const { return myChildFile.name; } unsigned int HogReader::CurrentFileSize() const { return myChildFile.size; } std::vector<uint8_t> HogReader::CurrentFile() { std::vector<uint8_t> fileData; // TODO: Allow this to seek-back and read it again. // // For now ensure the current file hasn't been read yet. assert(!hasReadFile); // Skip the current file. if (feof(myFile)) return fileData; const unsigned int size = CurrentFileSize(); // Size in bytes fileData.resize(size); if (fread(fileData.data(), size, 1, myFile) != 1) { fileData.clear(); } return fileData; } #include <algorithm> #include <iostream> #include <string> struct Quad { size_t a; size_t b; size_t c; size_t d; }; void Quads(const Cube& cube, std::vector<Quad>* quads) { const uint16_t* const vertices = cube.vertices; // Vertices: // 0 - left, front, top // 1 - left, front, bottom // 2 - right, front, bottom // 3 - right, front, top // 4 - left, back, top // 5 - left, back, bottom // 6 - right, back, bottom // 7 - right, back, top // Neighbours: enum Neighbour { Left, Top, Right, Bottom, Back, Front }; if (cube.neighbors[Left] == -1) { const Quad quad = { vertices[0], vertices[1], vertices[5], vertices[4] }; quads->push_back(quad); } if (cube.neighbors[Top] == -1) { const Quad quad = { vertices[0], vertices[3], vertices[7], vertices[4] }; quads->push_back(quad); } if (cube.neighbors[Right] == -1) { const Quad quad = { vertices[2], vertices[3], vertices[7], vertices[6] }; quads->push_back(quad); } if (cube.neighbors[Bottom] == -1) { const Quad quad = { vertices[1], vertices[2], vertices[6], vertices[4] }; quads->push_back(quad); } if (cube.neighbors[Front] == -1) { const Quad quad = { vertices[0], vertices[1], vertices[2], vertices[3] }; quads->push_back(quad); } if (cube.neighbors[Back] == -1) { const Quad quad = { vertices[4], vertices[5], vertices[6], vertices[7] }; quads->push_back(quad); } } std::vector<Quad> Quads(const std::vector<Cube>& Cubes) { // Generate quads from the sides of the cubes. std::vector<Quad> quads; for (auto cube = Cubes.cbegin(), cubeEnd = Cubes.cend(); cube != cubeEnd; ++cube) { Quads(*cube, &quads); } return quads; } int main(int argc, char* argv[]) { if (argc != 2) { printf("usage: %s filename\n", argv[0]); return 1; } HogReader reader(argv[1]); if (!reader.IsValid()) { fprintf(stderr, "error to open the hog file"); return 1; } enum Mode { ListAllFiles, ExportToPly, Debug // Performs some other task during development. }; const Mode mode = ExportToPly; if (mode == ListAllFiles) { printf("%-13s Size\n", "Name"); printf("=====================\n"); std::for_each(reader.begin(), reader.end(), [](HogReader::iterator::value_type item) { printf("%-13s %d\n", item.name, item.size); }); } else if (mode == ExportToPly) { auto file = std::find_if(reader.begin(), reader.end(), [](const HogReader::iterator::value_type & v)->bool { return strcmp(v.name, "level02.rdl") == 0; }); // TODO: Provide a way to get to the file data from the iterator. const auto data = reader.CurrentFile(); RdlReader rdlReader(data); const auto vertices = rdlReader.Vertices(); const auto cubes = rdlReader.Cubes(); const auto quads = Quads(cubes); const bool verticesOnly = false; const size_t faceCount = 0; std::cout << "ply" << std::endl; std::cout << "format ascii 1.0" << std::endl; std::cout << "comment An exported Descent 1 level (" << (*file).name << ")" << std::endl; std::cout << "element vertex " << vertices.size() << std::endl; std::cout << "property float x" << std::endl; std::cout << "property float y" << std::endl; std::cout << "property float z" << std::endl; if (!verticesOnly) { std::cout << "element face " << quads.size() << std::endl; std::cout << "property list uchar int vertex_index" << std::endl; } std::cout << "end_header" << std::endl; std::for_each(vertices.begin(), vertices.end(), [](Vertex v) { printf("%f %f %f\n", v.x, v.y, v.z); }); if (!verticesOnly) { std::for_each(quads.begin(), quads.end(), [](const Quad& quad) { printf("4 %d %d %d %d\n", quad.a, quad.b, quad.c, quad.d); }); } } else { // Iterate over the file list and list all the files which do not // end in the 'rdl' file extension. const std::string extentionRdl(".rdl"); std::for_each(reader.begin(), reader.end(), [&reader, &extentionRdl](HogReader::iterator::value_type n) { const std::string filename(n.name); if (!std::equal(extentionRdl.rbegin(), extentionRdl.rend(), filename.rbegin())) return; printf("File: %s Size: %d\n", n.name, reader.CurrentFileSize()); const auto data = reader.CurrentFile(); RdlReader rdlReader(data); if (!rdlReader.IsValid()) return; // Print out the vertices. const auto vertices = rdlReader.Vertices(); printf("Vertex count: %d\n", vertices.size()); std::for_each(vertices.begin(), vertices.end(), [](Vertex v) { printf("%16f %16f %16f\n", v.x, v.y, v.z); }); }); } return 0; } <commit_msg>Removed an unused variable.<commit_after>//===----------------------------------------------------------------------===// // // The Descent map loader // // NAME : Hog // PURPOSE : Providing a decoder and wrapper for the Descent .HOG format. // COPYRIGHT : (c) 2011 Sean Donnellan. All Rights Reserved. // AUTHORS : Sean Donnellan (darkdonno@gmail.com) // DESCRIPTION : A decoder for the HOG file format that is used by Parallax // Software in the computer game, Descent. // // The file format is as follows: // // - Magic number which is 3 bytes and corresponding to the // string "DHF" // - A series of files which are preceded by a short header, // which describes the name of the file and the numer of bytes. // // | "DHF" - 3 bytes // |---------------- Start of the first file // | filename - 13 bytes // | size - 4 bytes // | data - the size of this part is by the size before it. // |---------------- The next header/file comes straight after. // | filename - 13 bytes // | size - 4 bytes // | data - the size of this part is by the size before it. // //===----------------------------------------------------------------------===// ///// // Developer notes // Different file formats: http://www.descent2.com/ddn/kb/files/ // ///// #include "cube.hpp" #include "hogreader.hpp" #include "hogiterator.hpp" #include "rdl.hpp" #include <memory> #include <iterator> #include <utility> #include <vector> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _MSC_VER static_assert(sizeof(uint8_t) == 1, "The size of uint8_t is incorrect it must be 1-byte"); static_assert(sizeof(uint32_t) == 4, "The size of uint32_t is incorrect it must be 4-bytes"); static_assert(sizeof(uint8_t) == sizeof(char), "The size of a char must be 1-byte"); #endif // The 3-byte MAGIC number at the start of the file format used to identifiy the // file as being a Descent HOG file. static uint8_t magic[3] = { 'D', 'H', 'F' }; HogReader::iterator HogReader::begin() { // Sync back up to the start just after the magic number. if (IsValid()) { fseek(myFile, sizeof(magic), SEEK_SET); if (fread(&myChildFile.name, 13, 1, myFile) != 1) HogReaderIterator(); if (fread(&myChildFile.size, 4, 1, myFile) != 1) HogReaderIterator(); } return HogReaderIterator(*this); } HogReader::iterator HogReader::end() { return HogReaderIterator(); } HogReader::HogReader(const char* filename) : myFile(nullptr), hasReadFile(false) { myFile = fopen(filename, "rb"); myChildFile.name[0] = '\0'; myChildFile.size = 0; if (!myFile) return; const size_t count = 1; if (fread(myHeader, sizeof(myHeader), count, myFile) != count) { myHeader[0] = '\0'; // Failed to load. return; } // Read in the header for the first file. if (IsValid()) { if (fread(&myChildFile.name, 13, 1, myFile) != 1) return; if (fread(&myChildFile.size, 4, 1, myFile) != 1) return; } } HogReader::~HogReader() { if (myFile) fclose(myFile); } bool HogReader::IsValid() const { if (!myFile) return false; return memcmp(myHeader, magic, 3) == 0; } bool HogReader::NextFile() { // Skip the current file. if (feof(myFile)) return false; if (!hasReadFile) { // The data for the current file has not been read so skip over the data // section // for the file. if (fseek(myFile, myChildFile.size, SEEK_CUR) != 0) return false; } // Read in the header for the next file. if (fread(&myChildFile.name, 13, 1, myFile) != 1) return false; if (fread(&myChildFile.size, 4, 1, myFile) != 1) return false; hasReadFile = false; // We haven't read the next file yet. return true; } const char* HogReader::CurrentFileName() const { return myChildFile.name; } unsigned int HogReader::CurrentFileSize() const { return myChildFile.size; } std::vector<uint8_t> HogReader::CurrentFile() { std::vector<uint8_t> fileData; // TODO: Allow this to seek-back and read it again. // // For now ensure the current file hasn't been read yet. assert(!hasReadFile); // Skip the current file. if (feof(myFile)) return fileData; const unsigned int size = CurrentFileSize(); // Size in bytes fileData.resize(size); if (fread(fileData.data(), size, 1, myFile) != 1) { fileData.clear(); } return fileData; } #include <algorithm> #include <iostream> #include <string> struct Quad { size_t a; size_t b; size_t c; size_t d; }; void Quads(const Cube& cube, std::vector<Quad>* quads) { const uint16_t* const vertices = cube.vertices; // Vertices: // 0 - left, front, top // 1 - left, front, bottom // 2 - right, front, bottom // 3 - right, front, top // 4 - left, back, top // 5 - left, back, bottom // 6 - right, back, bottom // 7 - right, back, top // Neighbours: enum Neighbour { Left, Top, Right, Bottom, Back, Front }; if (cube.neighbors[Left] == -1) { const Quad quad = { vertices[0], vertices[1], vertices[5], vertices[4] }; quads->push_back(quad); } if (cube.neighbors[Top] == -1) { const Quad quad = { vertices[0], vertices[3], vertices[7], vertices[4] }; quads->push_back(quad); } if (cube.neighbors[Right] == -1) { const Quad quad = { vertices[2], vertices[3], vertices[7], vertices[6] }; quads->push_back(quad); } if (cube.neighbors[Bottom] == -1) { const Quad quad = { vertices[1], vertices[2], vertices[6], vertices[4] }; quads->push_back(quad); } if (cube.neighbors[Front] == -1) { const Quad quad = { vertices[0], vertices[1], vertices[2], vertices[3] }; quads->push_back(quad); } if (cube.neighbors[Back] == -1) { const Quad quad = { vertices[4], vertices[5], vertices[6], vertices[7] }; quads->push_back(quad); } } std::vector<Quad> Quads(const std::vector<Cube>& Cubes) { // Generate quads from the sides of the cubes. std::vector<Quad> quads; for (auto cube = Cubes.cbegin(), cubeEnd = Cubes.cend(); cube != cubeEnd; ++cube) { Quads(*cube, &quads); } return quads; } int main(int argc, char* argv[]) { if (argc != 2) { printf("usage: %s filename\n", argv[0]); return 1; } HogReader reader(argv[1]); if (!reader.IsValid()) { fprintf(stderr, "error to open the hog file"); return 1; } enum Mode { ListAllFiles, ExportToPly, Debug // Performs some other task during development. }; const Mode mode = ExportToPly; if (mode == ListAllFiles) { printf("%-13s Size\n", "Name"); printf("=====================\n"); std::for_each(reader.begin(), reader.end(), [](HogReader::iterator::value_type item) { printf("%-13s %d\n", item.name, item.size); }); } else if (mode == ExportToPly) { auto file = std::find_if(reader.begin(), reader.end(), [](const HogReader::iterator::value_type & v)->bool { return strcmp(v.name, "level02.rdl") == 0; }); // TODO: Provide a way to get to the file data from the iterator. const auto data = reader.CurrentFile(); RdlReader rdlReader(data); const auto vertices = rdlReader.Vertices(); const auto cubes = rdlReader.Cubes(); const auto quads = Quads(cubes); const bool verticesOnly = false; std::cout << "ply" << std::endl; std::cout << "format ascii 1.0" << std::endl; std::cout << "comment An exported Descent 1 level (" << (*file).name << ")" << std::endl; std::cout << "element vertex " << vertices.size() << std::endl; std::cout << "property float x" << std::endl; std::cout << "property float y" << std::endl; std::cout << "property float z" << std::endl; if (!verticesOnly) { std::cout << "element face " << quads.size() << std::endl; std::cout << "property list uchar int vertex_index" << std::endl; } std::cout << "end_header" << std::endl; std::for_each(vertices.begin(), vertices.end(), [](Vertex v) { printf("%f %f %f\n", v.x, v.y, v.z); }); if (!verticesOnly) { std::for_each(quads.begin(), quads.end(), [](const Quad& quad) { printf("4 %d %d %d %d\n", quad.a, quad.b, quad.c, quad.d); }); } } else { // Iterate over the file list and list all the files which do not // end in the 'rdl' file extension. const std::string extentionRdl(".rdl"); std::for_each(reader.begin(), reader.end(), [&reader, &extentionRdl](HogReader::iterator::value_type n) { const std::string filename(n.name); if (!std::equal(extentionRdl.rbegin(), extentionRdl.rend(), filename.rbegin())) return; printf("File: %s Size: %d\n", n.name, reader.CurrentFileSize()); const auto data = reader.CurrentFile(); RdlReader rdlReader(data); if (!rdlReader.IsValid()) return; // Print out the vertices. const auto vertices = rdlReader.Vertices(); printf("Vertex count: %d\n", vertices.size()); std::for_each(vertices.begin(), vertices.end(), [](Vertex v) { printf("%16f %16f %16f\n", v.x, v.y, v.z); }); }); } return 0; } <|endoftext|>
<commit_before>#include "assets_editor_window.h" #include "halley/tools/project/project.h" #include "halley/core/resources/resource_locator.h" #include "halley/core/resources/standard_resources.h" #include "halley/ui/widgets/ui_label.h" #include "halley/ui/widgets/ui_list.h" #include "animation_editor.h" #include "metadata_editor.h" #include "prefab_editor.h" using namespace Halley; AssetsEditorWindow::AssetsEditorWindow(UIFactory& factory, Project& project, EditorRootStage& stage) : UIWidget("assets_editor", {}, UISizer()) , factory(factory) , project(project) , stage(stage) , curSrcPath(".") { loadResources(); makeUI(); setAssetSrcMode(true); } void AssetsEditorWindow::loadResources() { project.addAssetReloadCallback([=] (const std::vector<String>& assets) { refreshAssets(assets); }); } void AssetsEditorWindow::makeUI() { UIWidget::add(factory.makeUI("ui/halley/assets_editor_window"), 1); assetList = getWidgetAs<UIList>("assetList"); assetList->setSingleClickAccept(false); metadataEditor = getWidgetAs<MetadataEditor>("metadataEditor"); content = getWidgetAs<UIPagedPane>("content"); contentList = getWidgetAs<UIList>("contentList"); contentListDropdown = getWidgetAs<UIDropdown>("contentListDropdown"); contentListDropdownLabel = getWidgetAs<UILabel>("contentListDropdownLabel"); setHandle(UIEventType::ListSelectionChanged, "contentList", [=] (const UIEvent& event) { content->setPage(event.getStringData().toInteger()); }); setHandle(UIEventType::DropboxSelectionChanged, "contentListDropdown", [=](const UIEvent& event) { loadAsset(loadedAsset, false, false); }); setHandle(UIEventType::ListSelectionChanged, "assetType", [=] (const UIEvent& event) { listAssets(fromString<AssetType>(event.getStringData())); }); setHandle(UIEventType::ListSelectionChanged, "assetList", [=] (const UIEvent& event) { loadAsset(event.getStringData(), false, true); }); setHandle(UIEventType::ListAccept, "assetList", [=] (const UIEvent& event) { loadAsset(event.getStringData(), true, true); }); setHandle(UIEventType::TextChanged, "assetSearch", [=] (const UIEvent& event) { setFilter(event.getStringData()); }); } void AssetsEditorWindow::setAssetSrcMode(bool enabled) { assetSrcMode = enabled; getWidget("assetType")->setActive(!assetSrcMode); if (assetSrcMode) { listAssetSources(); } else { listAssets(AssetType::Sprite); } } void AssetsEditorWindow::listAssetSources() { if (!assetNames) { assetNames = project.getAssetSrcList(); std::sort(assetNames->begin(), assetNames->end()); // Is this even needed? } if (filter.isEmpty()) { setListContents(assetNames.value(), curSrcPath, false); } else { std::vector<String> filteredList; for (auto& a: assetNames.value()) { if (a.asciiLower().contains(filter)) { filteredList.push_back(a); } } setListContents(filteredList, curSrcPath, true); } } void AssetsEditorWindow::listAssets(AssetType type) { curType = type; if (curPaths.find(type) == curPaths.end()) { curPaths[type] = Path("."); } const auto curPath = curPaths[type]; auto assets = project.getGameResources().ofType(type).enumerate(); std::sort(assets.begin(), assets.end()); setListContents(assets, curPath, false); } void AssetsEditorWindow::setListContents(std::vector<String> assets, const Path& curPath, bool flat) { assetList->clear(); if (flat) { for (auto& a: assets) { assetList->addTextItem(a, LocalisedString::fromUserString(Path(a).getFilename().toString())); } } else { std::set<String> dirs; std::vector<std::pair<String, String>> files; for (auto& a: assets) { auto relPath = Path("./" + a).makeRelativeTo(curPath); if (relPath.getNumberPaths() == 1) { files.emplace_back(a, relPath.toString()); } else { auto start = relPath.getFront(1); dirs.insert(start.toString()); } } for (auto& dir: dirs) { assetList->addTextItem(dir + "/.", LocalisedString::fromUserString("[" + dir + "]")); } for (auto& file: files) { assetList->addTextItem(file.first, LocalisedString::fromUserString(file.second)); } } } void AssetsEditorWindow::refreshList() { if (assetSrcMode) { listAssetSources(); } else { listAssets(curType); } } void AssetsEditorWindow::setFilter(const String& f) { if (filter != f) { filter = f.asciiLower(); refreshList(); } } void AssetsEditorWindow::loadAsset(const String& name, bool doubleClick, bool clearDropdown) { auto& curPath = assetSrcMode ? curSrcPath : curPaths[curType]; if (name.endsWith("/.")) { if (doubleClick) { curPath = curPath / name; refreshList(); } } else { loadedAsset = name; content->clear(); contentList->clear(); curEditors.clear(); if (clearDropdown) { contentListDropdown->clear(); contentListDropdown->setActive(false); contentListDropdownLabel->setActive(false); } if (assetSrcMode) { auto assets = project.getAssetsFromFile(Path(name)); std::sort(assets.begin(), assets.end(), [] (decltype(assets)::const_reference a, decltype(assets)::const_reference b) -> bool { return b.first < a.first; }); auto useDropdown = false; std::vector<String> assetNames; if (int(assets.size()) > 3) { for (const auto& asset : assets) { if (asset.first == AssetType::Animation) { assetNames.push_back(asset.second); } } if(assetNames.size() > 0) { useDropdown = true; contentListDropdown->setActive(true); contentListDropdownLabel->setActive(true); } if (clearDropdown) { contentListDropdown->setOptions(assetNames, 0); } } for (auto& asset: assets) { if (!useDropdown || asset.second == contentListDropdown->getSelectedOptionId() || std::find(assetNames.begin(), assetNames.end(), asset.second) == assetNames.end()) { createEditorTab(asset.first, asset.second); } } if (assets.empty()) { metadataEditor->clear(); } else { const auto type = assets.at(0).first; auto effectiveMeta = project.getImportMetadata(type, assets.at(0).second); metadataEditor->setResource(project, type, Path(name), std::move(effectiveMeta)); } } else { metadataEditor->clear(); createEditorTab(curType, name); } } } void AssetsEditorWindow::refreshAssets(const std::vector<String>& assets) { assetNames.reset(); refreshList(); for (auto& editor: curEditors) { editor->reload(); } } std::shared_ptr<AssetEditor> AssetsEditorWindow::makeEditor(AssetType type, const String& name) { switch (type) { case AssetType::Sprite: case AssetType::Animation: case AssetType::Texture: return std::make_shared<AnimationEditor>(factory, project.getGameResources(), type, project); case AssetType::Prefab: case AssetType::Scene: return std::make_shared<PrefabEditor>(factory, project.getGameResources(), type, project, stage); } return {}; } void AssetsEditorWindow::createEditorTab(AssetType type, const String& name) { auto editor = makeEditor(type, name); if (editor) { editor->setResource(name); auto n = content->getNumberOfPages(); content->addPage(); content->getPage(n)->add(editor, 1); auto typeSprite = Sprite().setImage(factory.getResources(), Path("ui") / "assetTypes" / toString(type) + ".png"); const auto image = std::make_shared<UIImage>(typeSprite); const auto text = std::make_shared<UILabel>(name + "_" + toString(type) + ":label", contentList->getStyle().getTextRenderer("label"), LocalisedString::fromUserString(name)); auto item = std::make_shared<UISizer>(); item->add(image); item->add(text, 1.0f, {}, UISizerAlignFlags::CentreVertical); contentList->addItem(toString(n), item); } } AssetEditor::AssetEditor(UIFactory& factory, Resources& resources, Project& project, AssetType type) : UIWidget("assetEditor", {}, UISizer()) , factory(factory) , project(project) , resources(resources) , assetType(type) { } void AssetEditor::setResource(const String& id) { assetId = id; if (assetType == AssetType::Animation) { resource = resources.get<Animation>(assetId); } else if (assetType == AssetType::Sprite) { resource = resources.get<SpriteResource>(assetId); } else if (assetType == AssetType::Texture) { resource = resources.get<Texture>(assetId); } reload(); } void AssetEditor::clearResource() { assetId = ""; resource.reset(); reload(); } void AssetEditor::reload() { } <commit_msg>set dropdown inactive unless needed<commit_after>#include "assets_editor_window.h" #include "halley/tools/project/project.h" #include "halley/core/resources/resource_locator.h" #include "halley/core/resources/standard_resources.h" #include "halley/ui/widgets/ui_label.h" #include "halley/ui/widgets/ui_list.h" #include "animation_editor.h" #include "metadata_editor.h" #include "prefab_editor.h" using namespace Halley; AssetsEditorWindow::AssetsEditorWindow(UIFactory& factory, Project& project, EditorRootStage& stage) : UIWidget("assets_editor", {}, UISizer()) , factory(factory) , project(project) , stage(stage) , curSrcPath(".") { loadResources(); makeUI(); setAssetSrcMode(true); } void AssetsEditorWindow::loadResources() { project.addAssetReloadCallback([=] (const std::vector<String>& assets) { refreshAssets(assets); }); } void AssetsEditorWindow::makeUI() { UIWidget::add(factory.makeUI("ui/halley/assets_editor_window"), 1); assetList = getWidgetAs<UIList>("assetList"); assetList->setSingleClickAccept(false); metadataEditor = getWidgetAs<MetadataEditor>("metadataEditor"); content = getWidgetAs<UIPagedPane>("content"); contentList = getWidgetAs<UIList>("contentList"); contentListDropdown = getWidgetAs<UIDropdown>("contentListDropdown"); contentListDropdownLabel = getWidgetAs<UILabel>("contentListDropdownLabel"); setHandle(UIEventType::ListSelectionChanged, "contentList", [=] (const UIEvent& event) { content->setPage(event.getStringData().toInteger()); }); setHandle(UIEventType::DropboxSelectionChanged, "contentListDropdown", [=](const UIEvent& event) { loadAsset(loadedAsset, false, false); }); setHandle(UIEventType::ListSelectionChanged, "assetType", [=] (const UIEvent& event) { listAssets(fromString<AssetType>(event.getStringData())); }); setHandle(UIEventType::ListSelectionChanged, "assetList", [=] (const UIEvent& event) { loadAsset(event.getStringData(), false, true); }); setHandle(UIEventType::ListAccept, "assetList", [=] (const UIEvent& event) { loadAsset(event.getStringData(), true, true); }); setHandle(UIEventType::TextChanged, "assetSearch", [=] (const UIEvent& event) { setFilter(event.getStringData()); }); } void AssetsEditorWindow::setAssetSrcMode(bool enabled) { assetSrcMode = enabled; getWidget("assetType")->setActive(!assetSrcMode); if (assetSrcMode) { listAssetSources(); } else { listAssets(AssetType::Sprite); } } void AssetsEditorWindow::listAssetSources() { if (!assetNames) { assetNames = project.getAssetSrcList(); std::sort(assetNames->begin(), assetNames->end()); // Is this even needed? } if (filter.isEmpty()) { setListContents(assetNames.value(), curSrcPath, false); } else { std::vector<String> filteredList; for (auto& a: assetNames.value()) { if (a.asciiLower().contains(filter)) { filteredList.push_back(a); } } setListContents(filteredList, curSrcPath, true); } } void AssetsEditorWindow::listAssets(AssetType type) { curType = type; if (curPaths.find(type) == curPaths.end()) { curPaths[type] = Path("."); } const auto curPath = curPaths[type]; auto assets = project.getGameResources().ofType(type).enumerate(); std::sort(assets.begin(), assets.end()); setListContents(assets, curPath, false); } void AssetsEditorWindow::setListContents(std::vector<String> assets, const Path& curPath, bool flat) { assetList->clear(); if (flat) { for (auto& a: assets) { assetList->addTextItem(a, LocalisedString::fromUserString(Path(a).getFilename().toString())); } } else { std::set<String> dirs; std::vector<std::pair<String, String>> files; for (auto& a: assets) { auto relPath = Path("./" + a).makeRelativeTo(curPath); if (relPath.getNumberPaths() == 1) { files.emplace_back(a, relPath.toString()); } else { auto start = relPath.getFront(1); dirs.insert(start.toString()); } } for (auto& dir: dirs) { assetList->addTextItem(dir + "/.", LocalisedString::fromUserString("[" + dir + "]")); } for (auto& file: files) { assetList->addTextItem(file.first, LocalisedString::fromUserString(file.second)); } } } void AssetsEditorWindow::refreshList() { if (assetSrcMode) { listAssetSources(); } else { listAssets(curType); } } void AssetsEditorWindow::setFilter(const String& f) { if (filter != f) { filter = f.asciiLower(); refreshList(); } } void AssetsEditorWindow::loadAsset(const String& name, bool doubleClick, bool clearDropdown) { if (clearDropdown) { contentListDropdown->clear(); contentListDropdown->setActive(false); contentListDropdownLabel->setActive(false); } auto& curPath = assetSrcMode ? curSrcPath : curPaths[curType]; if (name.endsWith("/.")) { if (doubleClick) { curPath = curPath / name; refreshList(); } } else { loadedAsset = name; content->clear(); contentList->clear(); curEditors.clear(); if (assetSrcMode) { auto assets = project.getAssetsFromFile(Path(name)); std::sort(assets.begin(), assets.end(), [] (decltype(assets)::const_reference a, decltype(assets)::const_reference b) -> bool { return b.first < a.first; }); auto useDropdown = false; std::vector<String> assetNames; if (int(assets.size()) > 3) { for (const auto& asset : assets) { if (asset.first == AssetType::Animation) { assetNames.push_back(asset.second); } } if(assetNames.size() > 0) { useDropdown = true; contentListDropdown->setActive(true); contentListDropdownLabel->setActive(true); } if (clearDropdown) { contentListDropdown->setOptions(assetNames, 0); } } for (auto& asset: assets) { if (!useDropdown || asset.second == contentListDropdown->getSelectedOptionId() || std::find(assetNames.begin(), assetNames.end(), asset.second) == assetNames.end()) { createEditorTab(asset.first, asset.second); } } if (assets.empty()) { metadataEditor->clear(); } else { const auto type = assets.at(0).first; auto effectiveMeta = project.getImportMetadata(type, assets.at(0).second); metadataEditor->setResource(project, type, Path(name), std::move(effectiveMeta)); } } else { metadataEditor->clear(); createEditorTab(curType, name); } } } void AssetsEditorWindow::refreshAssets(const std::vector<String>& assets) { assetNames.reset(); refreshList(); for (auto& editor: curEditors) { editor->reload(); } } std::shared_ptr<AssetEditor> AssetsEditorWindow::makeEditor(AssetType type, const String& name) { switch (type) { case AssetType::Sprite: case AssetType::Animation: case AssetType::Texture: return std::make_shared<AnimationEditor>(factory, project.getGameResources(), type, project); case AssetType::Prefab: case AssetType::Scene: return std::make_shared<PrefabEditor>(factory, project.getGameResources(), type, project, stage); } return {}; } void AssetsEditorWindow::createEditorTab(AssetType type, const String& name) { auto editor = makeEditor(type, name); if (editor) { editor->setResource(name); auto n = content->getNumberOfPages(); content->addPage(); content->getPage(n)->add(editor, 1); auto typeSprite = Sprite().setImage(factory.getResources(), Path("ui") / "assetTypes" / toString(type) + ".png"); const auto image = std::make_shared<UIImage>(typeSprite); const auto text = std::make_shared<UILabel>(name + "_" + toString(type) + ":label", contentList->getStyle().getTextRenderer("label"), LocalisedString::fromUserString(name)); auto item = std::make_shared<UISizer>(); item->add(image); item->add(text, 1.0f, {}, UISizerAlignFlags::CentreVertical); contentList->addItem(toString(n), item); } } AssetEditor::AssetEditor(UIFactory& factory, Resources& resources, Project& project, AssetType type) : UIWidget("assetEditor", {}, UISizer()) , factory(factory) , project(project) , resources(resources) , assetType(type) { } void AssetEditor::setResource(const String& id) { assetId = id; if (assetType == AssetType::Animation) { resource = resources.get<Animation>(assetId); } else if (assetType == AssetType::Sprite) { resource = resources.get<SpriteResource>(assetId); } else if (assetType == AssetType::Texture) { resource = resources.get<Texture>(assetId); } reload(); } void AssetEditor::clearResource() { assetId = ""; resource.reset(); reload(); } void AssetEditor::reload() { } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ // boost #include <boost/python/suite/indexing/indexing_suite.hpp> #include <boost/python/iterator.hpp> #include <boost/python/call_method.hpp> #include <boost/python/tuple.hpp> #include <boost/python.hpp> #include <boost/scoped_array.hpp> // mapnik #include <mapnik/feature.hpp> #include <mapnik/datasource.hpp> mapnik::geometry2d & (mapnik::Feature::*get_geom1)(unsigned) = &mapnik::Feature::get_geometry; namespace boost { namespace python { struct value_converter : public boost::static_visitor<PyObject*> { PyObject * operator() (int val) const { return ::PyInt_FromLong(val); } PyObject * operator() (double val) const { return ::PyFloat_FromDouble(val); } PyObject * operator() (UnicodeString const& s) const { std::string buffer; mapnik::to_utf8(s,buffer); PyObject *obj = Py_None; obj = ::PyUnicode_DecodeUTF8(buffer.c_str(),implicit_cast<ssize_t>(buffer.length()),0); return obj; } PyObject * operator() (mapnik::value_null const& s) const { return NULL; } }; struct mapnik_value_to_python { static PyObject* convert(mapnik::value const& v) { return boost::apply_visitor(value_converter(),v.base()); } }; // Forward declaration template <class Container, bool NoProxy, class DerivedPolicies> class map_indexing_suite2; namespace detail { template <class Container, bool NoProxy> class final_map_derived_policies : public map_indexing_suite2<Container, NoProxy, final_map_derived_policies<Container, NoProxy> > {}; } template < class Container, bool NoProxy = false, class DerivedPolicies = detail::final_map_derived_policies<Container, NoProxy> > class map_indexing_suite2 : public indexing_suite< Container , DerivedPolicies , NoProxy , true , typename Container::value_type::second_type , typename Container::key_type , typename Container::key_type > { public: typedef typename Container::value_type value_type; typedef typename Container::value_type::second_type data_type; typedef typename Container::key_type key_type; typedef typename Container::key_type index_type; typedef typename Container::size_type size_type; typedef typename Container::difference_type difference_type; template <class Class> static void extension_def(Class& cl) { } static data_type& get_item(Container& container, index_type i_) { typename Container::iterator i = container.props().find(i_); if (i == container.end()) { PyErr_SetString(PyExc_KeyError, "Invalid key"); throw_error_already_set(); } return i->second; } static void set_item(Container& container, index_type i, data_type const& v) { container[i] = v; } static void delete_item(Container& container, index_type i) { container.props().erase(i); } static size_t size(Container& container) { return container.props().size(); } static bool contains(Container& container, key_type const& key) { return container.props().find(key) != container.end(); } static bool compare_index(Container& container, index_type a, index_type b) { return container.props().key_comp()(a, b); } static index_type convert_index(Container& /*container*/, PyObject* i_) { extract<key_type const&> i(i_); if (i.check()) { return i(); } else { extract<key_type> i(i_); if (i.check()) return i(); } PyErr_SetString(PyExc_TypeError, "Invalid index type"); throw_error_already_set(); return index_type(); } }; template <typename T1, typename T2> struct std_pair_to_tuple { static PyObject* convert(std::pair<T1, T2> const& p) { return boost::python::incref( boost::python::make_tuple(p.first, p.second).ptr()); } }; template <typename T1, typename T2> struct std_pair_to_python_converter { std_pair_to_python_converter() { boost::python::to_python_converter< std::pair<T1, T2>, std_pair_to_tuple<T1, T2> >(); } }; } } mapnik::feature_ptr create_feature_(int id) { return mapnik::feature_ptr(new mapnik::Feature(id)); } struct UnicodeString_from_python_str { UnicodeString_from_python_str() { boost::python::converter::registry::push_back( &convertible, &construct, boost::python::type_id<UnicodeString>()); } static void* convertible(PyObject* obj_ptr) { if (!PyString_Check(obj_ptr)) return 0; return obj_ptr; } static void construct( PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data) { const char* value = PyString_AsString(obj_ptr); if (value == 0) boost::python::throw_error_already_set(); void* storage = ( (boost::python::converter::rvalue_from_python_storage<UnicodeString>*) data)->storage.bytes; new (storage) UnicodeString(value); data->convertible = storage; } }; void export_feature() { using namespace boost::python; using mapnik::Feature; implicitly_convertible<int,mapnik::value>(); implicitly_convertible<double,mapnik::value>(); implicitly_convertible<UnicodeString,mapnik::value>(); implicitly_convertible<bool,mapnik::value>(); std_pair_to_python_converter<std::string const,mapnik::value>(); to_python_converter<mapnik::value,mapnik_value_to_python>(); UnicodeString_from_python_str(); class_<Feature,boost::shared_ptr<Feature>, boost::noncopyable>("Feature",no_init) .def("id",&Feature::id) .def("__str__",&Feature::to_string) // .add_property("properties", // make_function(&Feature::props,return_value_policy<reference_existing_object>())) // .def("add_geometry", // TODO define more mapnik::Feature methods .def("num_geometries",&Feature::num_geometries) .def("get_geometry", make_function(get_geom1,return_value_policy<reference_existing_object>())) .def("envelope", &Feature::envelope) .def("create",create_feature_) .staticmethod("create") .def(map_indexing_suite2<Feature, true >()) .def("iteritems",iterator<Feature> ()) ; //def("Feature", &create_feature_); //class_<std::map<std::string, mapnik::value> >("Properties") // .def(map_indexing_suite2<std::map<std::string, mapnik::value>, true >()) // .def("iteritems",iterator<std::map<std::string,mapnik::value> > ()) // ; } <commit_msg>comment out new unicode stuff in mapnik_feature due to #505<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ // boost #include <boost/python/suite/indexing/indexing_suite.hpp> #include <boost/python/iterator.hpp> #include <boost/python/call_method.hpp> #include <boost/python/tuple.hpp> #include <boost/python.hpp> #include <boost/scoped_array.hpp> // mapnik #include <mapnik/feature.hpp> #include <mapnik/datasource.hpp> mapnik::geometry2d & (mapnik::Feature::*get_geom1)(unsigned) = &mapnik::Feature::get_geometry; namespace boost { namespace python { struct value_converter : public boost::static_visitor<PyObject*> { PyObject * operator() (int val) const { return ::PyInt_FromLong(val); } PyObject * operator() (double val) const { return ::PyFloat_FromDouble(val); } PyObject * operator() (UnicodeString const& s) const { std::string buffer; mapnik::to_utf8(s,buffer); PyObject *obj = Py_None; obj = ::PyUnicode_DecodeUTF8(buffer.c_str(),implicit_cast<ssize_t>(buffer.length()),0); return obj; } PyObject * operator() (mapnik::value_null const& s) const { return NULL; } }; struct mapnik_value_to_python { static PyObject* convert(mapnik::value const& v) { return boost::apply_visitor(value_converter(),v.base()); } }; // Forward declaration template <class Container, bool NoProxy, class DerivedPolicies> class map_indexing_suite2; namespace detail { template <class Container, bool NoProxy> class final_map_derived_policies : public map_indexing_suite2<Container, NoProxy, final_map_derived_policies<Container, NoProxy> > {}; } template < class Container, bool NoProxy = false, class DerivedPolicies = detail::final_map_derived_policies<Container, NoProxy> > class map_indexing_suite2 : public indexing_suite< Container , DerivedPolicies , NoProxy , true , typename Container::value_type::second_type , typename Container::key_type , typename Container::key_type > { public: typedef typename Container::value_type value_type; typedef typename Container::value_type::second_type data_type; typedef typename Container::key_type key_type; typedef typename Container::key_type index_type; typedef typename Container::size_type size_type; typedef typename Container::difference_type difference_type; template <class Class> static void extension_def(Class& cl) { } static data_type& get_item(Container& container, index_type i_) { typename Container::iterator i = container.props().find(i_); if (i == container.end()) { PyErr_SetString(PyExc_KeyError, "Invalid key"); throw_error_already_set(); } return i->second; } static void set_item(Container& container, index_type i, data_type const& v) { container[i] = v; } static void delete_item(Container& container, index_type i) { container.props().erase(i); } static size_t size(Container& container) { return container.props().size(); } static bool contains(Container& container, key_type const& key) { return container.props().find(key) != container.end(); } static bool compare_index(Container& container, index_type a, index_type b) { return container.props().key_comp()(a, b); } static index_type convert_index(Container& /*container*/, PyObject* i_) { extract<key_type const&> i(i_); if (i.check()) { return i(); } else { extract<key_type> i(i_); if (i.check()) return i(); } PyErr_SetString(PyExc_TypeError, "Invalid index type"); throw_error_already_set(); return index_type(); } }; template <typename T1, typename T2> struct std_pair_to_tuple { static PyObject* convert(std::pair<T1, T2> const& p) { return boost::python::incref( boost::python::make_tuple(p.first, p.second).ptr()); } }; template <typename T1, typename T2> struct std_pair_to_python_converter { std_pair_to_python_converter() { boost::python::to_python_converter< std::pair<T1, T2>, std_pair_to_tuple<T1, T2> >(); } }; } } /* mapnik::feature_ptr create_feature_(int id) { return mapnik::feature_ptr(new mapnik::Feature(id)); } struct UnicodeString_from_python_str { UnicodeString_from_python_str() { boost::python::converter::registry::push_back( &convertible, &construct, boost::python::type_id<UnicodeString>()); } static void* convertible(PyObject* obj_ptr) { if (!PyString_Check(obj_ptr)) return 0; return obj_ptr; } static void construct( PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data) { const char* value = PyString_AsString(obj_ptr); if (value == 0) boost::python::throw_error_already_set(); void* storage = ( (boost::python::converter::rvalue_from_python_storage<UnicodeString>*) data)->storage.bytes; new (storage) UnicodeString(value); data->convertible = storage; } }; */ void export_feature() { using namespace boost::python; using mapnik::Feature; implicitly_convertible<int,mapnik::value>(); implicitly_convertible<double,mapnik::value>(); //implicitly_convertible<UnicodeString,mapnik::value>(); implicitly_convertible<bool,mapnik::value>(); std_pair_to_python_converter<std::string const,mapnik::value>(); to_python_converter<mapnik::value,mapnik_value_to_python>(); //UnicodeString_from_python_str(); class_<Feature,boost::shared_ptr<Feature>, boost::noncopyable>("Feature",no_init) .def("id",&Feature::id) .def("__str__",&Feature::to_string) // .add_property("properties", // make_function(&Feature::props,return_value_policy<reference_existing_object>())) // .def("add_geometry", // TODO define more mapnik::Feature methods .def("num_geometries",&Feature::num_geometries) .def("get_geometry", make_function(get_geom1,return_value_policy<reference_existing_object>())) .def("envelope", &Feature::envelope) //.def("create",create_feature_) //.staticmethod("create") .def(map_indexing_suite2<Feature, true >()) .def("iteritems",iterator<Feature> ()) ; //def("Feature", &create_feature_); //class_<std::map<std::string, mapnik::value> >("Properties") // .def(map_indexing_suite2<std::map<std::string, mapnik::value>, true >()) // .def("iteritems",iterator<std::map<std::string,mapnik::value> > ()) // ; } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 <threading/Formatter.h> #include "MetronJSON.h" using metron::formatter::MetronJSON; using threading::formatter::JSON; using threading::MsgThread; using threading::Field; using threading::Value; MetronJSON::MetronJSON(string sn, MsgThread* t, TimeFormat tf) : JSON(t, tf) , stream_name(sn) { } MetronJSON::~MetronJSON() {} bool MetronJSON::Describe(ODesc* desc, int num_fields, const Field* const* fields, Value** vals) const { desc->AddRaw("{"); // prepend the stream name desc->AddRaw("\""); desc->AddRaw(stream_name); desc->AddRaw("\", "); // append the JSON formatted log record itself JSON::Describe(desc, num_fields, fields, vals); desc->AddRaw("}"); return true; } <commit_msg>METRON-52: Bro Plugin Header has comma instead of colon (dlyle65535 via cestella) closes apache/incubator-metron#31<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 <threading/Formatter.h> #include "MetronJSON.h" using metron::formatter::MetronJSON; using threading::formatter::JSON; using threading::MsgThread; using threading::Field; using threading::Value; MetronJSON::MetronJSON(string sn, MsgThread* t, TimeFormat tf) : JSON(t, tf) , stream_name(sn) { } MetronJSON::~MetronJSON() {} bool MetronJSON::Describe(ODesc* desc, int num_fields, const Field* const* fields, Value** vals) const { desc->AddRaw("{"); // prepend the stream name desc->AddRaw("\""); desc->AddRaw(stream_name); desc->AddRaw("\": "); // append the JSON formatted log record itself JSON::Describe(desc, num_fields, fields, vals); desc->AddRaw("}"); return true; } <|endoftext|>
<commit_before>#include "jsonmerge_tests.h" #include "../Common/defines.h" #include "../../xpiks-qt/Helpers/jsonhelper.h" #include "../../xpiks-qt/Helpers/localconfig.h" void JsonMergeTests::initTestCase() { LOG_DEBUG << "App path: " << QDir::currentPath(); } void JsonMergeTests::mergeTwoFilesObjects() { QFileInfo infoOld("jsons-for-tests/old.json"); QFileInfo infoNew("jsons-for-tests/new.json"); QFileInfo infoGold("jsons-for-tests/gold.json"); QString pathTo = infoOld.absoluteFilePath(); QString pathWith = infoNew.absoluteFilePath(); QString pathGold = infoGold.absoluteFilePath(); QVERIFY(infoOld.exists()); QVERIFY(infoNew.exists()); QVERIFY(infoGold.exists()); Helpers::LocalConfig localConfigWith(pathWith); Helpers::LocalConfig localConfigTo(pathTo); Helpers::LocalConfig localConfigGold(pathGold); localConfigWith.initConfig(); localConfigTo.initConfig(); localConfigGold.initConfig(); Helpers::mergeJson(localConfigTo.getConfig(), localConfigWith.getConfig(), 0, *this); QVERIFY(localConfigGold.getConfig() == localConfigTo.getConfig()); } void JsonMergeTests::mergeTwoFilesStrings() { QFileInfo infoOld("jsons-for-tests/oldS.json"); QFileInfo infoNew("jsons-for-tests/newS.json"); QFileInfo infoGold("jsons-for-tests/goldS.json"); QString pathTo = infoOld.absoluteFilePath(); QString pathWith = infoNew.absoluteFilePath(); QString pathGold = infoGold.absoluteFilePath(); QVERIFY(infoOld.exists()); QVERIFY(infoNew.exists()); QVERIFY(infoGold.exists()); Helpers::LocalConfig localConfigWith(pathWith); Helpers::LocalConfig localConfigTo(pathTo); Helpers::LocalConfig localConfigGold(pathGold); localConfigWith.initConfig(); localConfigTo.initConfig(); localConfigGold.initConfig(); Helpers::mergeJson(localConfigTo.getConfig(), localConfigWith.getConfig(), 0, *this); QVERIFY(localConfigGold.getConfig() == localConfigTo.getConfig()); } <commit_msg>Fixed relative include path<commit_after>#include "jsonmerge_tests.h" #include "../../xpiks-qt/Common/defines.h" #include "../../xpiks-qt/Helpers/jsonhelper.h" #include "../../xpiks-qt/Helpers/localconfig.h" void JsonMergeTests::initTestCase() { LOG_DEBUG << "App path: " << QDir::currentPath(); } void JsonMergeTests::mergeTwoFilesObjects() { QFileInfo infoOld("jsons-for-tests/old.json"); QFileInfo infoNew("jsons-for-tests/new.json"); QFileInfo infoGold("jsons-for-tests/gold.json"); QString pathTo = infoOld.absoluteFilePath(); QString pathWith = infoNew.absoluteFilePath(); QString pathGold = infoGold.absoluteFilePath(); QVERIFY(infoOld.exists()); QVERIFY(infoNew.exists()); QVERIFY(infoGold.exists()); Helpers::LocalConfig localConfigWith(pathWith); Helpers::LocalConfig localConfigTo(pathTo); Helpers::LocalConfig localConfigGold(pathGold); localConfigWith.initConfig(); localConfigTo.initConfig(); localConfigGold.initConfig(); Helpers::mergeJson(localConfigTo.getConfig(), localConfigWith.getConfig(), 0, *this); QVERIFY(localConfigGold.getConfig() == localConfigTo.getConfig()); } void JsonMergeTests::mergeTwoFilesStrings() { QFileInfo infoOld("jsons-for-tests/oldS.json"); QFileInfo infoNew("jsons-for-tests/newS.json"); QFileInfo infoGold("jsons-for-tests/goldS.json"); QString pathTo = infoOld.absoluteFilePath(); QString pathWith = infoNew.absoluteFilePath(); QString pathGold = infoGold.absoluteFilePath(); QVERIFY(infoOld.exists()); QVERIFY(infoNew.exists()); QVERIFY(infoGold.exists()); Helpers::LocalConfig localConfigWith(pathWith); Helpers::LocalConfig localConfigTo(pathTo); Helpers::LocalConfig localConfigGold(pathGold); localConfigWith.initConfig(); localConfigTo.initConfig(); localConfigGold.initConfig(); Helpers::mergeJson(localConfigTo.getConfig(), localConfigWith.getConfig(), 0, *this); QVERIFY(localConfigGold.getConfig() == localConfigTo.getConfig()); } <|endoftext|>
<commit_before>/* * Copyright (c) 2017 Samsung Electronics Co., Ltd. * * 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 "test-harness.h" #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <vector> #include <map> #include <cstring> #include <testcase.h> namespace TestHarness { typedef std::map<int32_t, TestCase> RunningTestCases; const char* basename(const char* path) { const char* ptr=path; const char* slash=NULL; for( ; *ptr != '\0' ; ++ptr ) { if(*ptr == '/') slash=ptr; } if(slash != NULL) ++slash; return slash; } int32_t RunTestCase( struct ::testcase_s& testCase ) { int32_t result = EXIT_STATUS_TESTCASE_FAILED; // dont want to catch exception as we want to be able to get // gdb stack trace from the first error // by default tests should all always pass with no exceptions if( testCase.startup ) { testCase.startup(); } try { result = testCase.function(); } catch( const char* ) { // just catch test fail exception, return is already set to EXIT_STATUS_TESTCASE_FAILED } if( testCase.cleanup ) { testCase.cleanup(); } return result; } int32_t RunTestCaseInChildProcess( struct ::testcase_s& testCase, bool suppressOutput ) { int32_t testResult = EXIT_STATUS_TESTCASE_FAILED; int32_t pid = fork(); if( pid == 0 ) // Child process { if( suppressOutput ) { close(STDOUT_FILENO); close(STDERR_FILENO); } else { printf("\n"); for(int32_t i=0; i<80; ++i) printf("#"); printf("\nTC: %s\n", testCase.name); fflush(stdout); } int32_t status = RunTestCase( testCase ); if( ! suppressOutput ) { fflush(stdout); fflush(stderr); fclose(stdout); fclose(stderr); } exit( status ); } else if(pid == -1) { perror("fork"); exit(EXIT_STATUS_FORK_FAILED); } else // Parent process { int32_t status = 0; int32_t childPid = waitpid(pid, &status, 0); if( childPid == -1 ) { perror("waitpid"); exit(EXIT_STATUS_WAITPID_FAILED); } if( WIFEXITED(status) ) { if( childPid > 0 ) { testResult = WEXITSTATUS(status); if( testResult ) { printf("Test case %s failed: %d\n", testCase.name, testResult); } } } else if(WIFSIGNALED(status) ) { int32_t signal = WTERMSIG(status); testResult = EXIT_STATUS_TESTCASE_ABORTED; if( signal == SIGABRT ) { printf("Test case %s failed: test case asserted\n", testCase.name ); } else { printf("Test case %s failed: exit with signal %s\n", testCase.name, strsignal(WTERMSIG(status))); } } else if(WIFSTOPPED(status)) { printf("Test case %s failed: stopped with signal %s\n", testCase.name, strsignal(WSTOPSIG(status))); } } fflush(stdout); fflush(stderr); return testResult; } void OutputStatistics( const char* processName, int32_t numPasses, int32_t numFailures ) { FILE* fp=fopen("summary.xml", "a"); if( fp != NULL ) { fprintf( fp, " <suite name=\"%s\">\n" " <total_case>%d</total_case>\n" " <pass_case>%d</pass_case>\n" " <pass_rate>%5.2f</pass_rate>\n" " <fail_case>%d</fail_case>\n" " <fail_rate>%5.2f</fail_rate>\n" " <block_case>0</block_case>\n" " <block_rate>0.00</block_rate>\n" " <na_case>0</na_case>\n" " <na_rate>0.00</na_rate>\n" " </suite>\n", basename(processName), numPasses+numFailures, numPasses, (float)numPasses/(numPasses+numFailures), numFailures, (float)numFailures/(numPasses+numFailures) ); fclose(fp); } } int32_t RunAll( const char* processName, ::testcase tc_array[] ) { int32_t numFailures = 0; int32_t numPasses = 0; // Run test cases in child process( to kill output/handle signals ), but run serially. for( uint32_t i=0; tc_array[i].name; i++) { int32_t result = RunTestCaseInChildProcess( tc_array[i], false ); if( result == 0 ) { numPasses++; } else { numFailures++; } } OutputStatistics( processName, numPasses, numFailures); return numFailures; } // Constantly runs up to MAX_NUM_CHILDREN processes int32_t RunAllInParallel( const char* processName, ::testcase tc_array[], bool reRunFailed) { int32_t numFailures = 0; int32_t numPasses = 0; RunningTestCases children; std::vector<int32_t> failedTestCases; // Fork up to MAX_NUM_CHILDREN processes, then // wait. As soon as a proc completes, fork the next. int32_t nextTestCase = 0; int32_t numRunningChildren = 0; while( tc_array[nextTestCase].name || numRunningChildren > 0) { // Create more children (up to the max number or til the end of the array) while( numRunningChildren < MAX_NUM_CHILDREN && tc_array[nextTestCase].name ) { int32_t pid = fork(); if( pid == 0 ) // Child process { close(STDOUT_FILENO); close(STDERR_FILENO); exit( RunTestCase( tc_array[nextTestCase] ) ); } else if(pid == -1) { perror("fork"); exit(EXIT_STATUS_FORK_FAILED); } else // Parent process { TestCase tc(nextTestCase, tc_array[nextTestCase].name); children[pid] = tc; nextTestCase++; numRunningChildren++; } } // Wait for the next child to finish int32_t status=0; int32_t childPid = waitpid(-1, &status, 0); if( childPid == -1 ) { perror("waitpid"); exit(EXIT_STATUS_WAITPID_FAILED); } if( WIFEXITED(status) ) { if( childPid > 0 ) { int32_t testResult = WEXITSTATUS(status); if( testResult ) { printf("Test case %s failed: %d\n", children[childPid].testCaseName, testResult); failedTestCases.push_back(children[childPid].testCase); numFailures++; } else { numPasses++; } numRunningChildren--; } } else if( WIFSIGNALED(status) || WIFSTOPPED(status)) { status = WIFSIGNALED(status)?WTERMSIG(status):WSTOPSIG(status); if( childPid > 0 ) { RunningTestCases::iterator iter = children.find(childPid); if( iter != children.end() ) { printf("Test case %s exited with signal %s\n", iter->second.testCaseName, strsignal(status)); failedTestCases.push_back(iter->second.testCase); } else { printf("Unknown child process: %d signaled %s\n", childPid, strsignal(status)); } numFailures++; numRunningChildren--; } } } OutputStatistics( processName, numPasses, numFailures ); if( reRunFailed ) { for( uint32_t i=0; i<failedTestCases.size(); i++) { char* testCaseStrapline; int32_t numChars = asprintf(&testCaseStrapline, "Test case %s", tc_array[failedTestCases[i]].name ); printf("\n%s\n", testCaseStrapline); for(int32_t j=0; j<numChars; j++) { printf("="); } printf("\n"); RunTestCaseInChildProcess( tc_array[failedTestCases[i] ], false ); } } return numFailures; } int32_t FindAndRunTestCase(::testcase tc_array[], const char* testCaseName) { int32_t result = EXIT_STATUS_TESTCASE_NOT_FOUND; for( int32_t i = 0; tc_array[i].name; i++ ) { if( !strcmp(testCaseName, tc_array[i].name) ) { return RunTestCase( tc_array[i] ); } } printf("Unknown testcase name: \"%s\"\n", testCaseName); return result; } void Usage(const char* program) { printf("Usage: \n" " %s <testcase name>\t\t Execute a test case\n" " %s \t\t Execute all test cases in parallel\n" " %s -r\t\t Execute all test cases in parallel, rerunning failed test cases\n" " %s -s\t\t Execute all test cases serially\n", program, program, program, program); } } // namespace <commit_msg>Fix random crash in TCT when stderr is closed but we try to write to it<commit_after>/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. * * 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 "test-harness.h" #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <vector> #include <map> #include <cstring> #include <testcase.h> #include <fcntl.h> namespace TestHarness { typedef std::map<int32_t, TestCase> RunningTestCases; const char* basename(const char* path) { const char* ptr=path; const char* slash=NULL; for( ; *ptr != '\0' ; ++ptr ) { if(*ptr == '/') slash=ptr; } if(slash != NULL) ++slash; return slash; } void SuppressLogOutput() { // Close stdout and stderr to suppress the log output close(STDOUT_FILENO); // File descriptor number for stdout is 1 close(STDERR_FILENO); // File descriptor number for stderr is 2 // The POSIX specification requires that /dev/null must be provided, // The open function always chooses the lowest unused file descriptor // It is sufficient for stdout to be writable. open("/dev/null", O_WRONLY); // Redirect file descriptor number 1 (i.e. stdout) to /dev/null // When stderr is opened it must be both readable and writable. open("/dev/null", O_RDWR); // Redirect file descriptor number 2 (i.e. stderr) to /dev/null } int32_t RunTestCase( struct ::testcase_s& testCase ) { int32_t result = EXIT_STATUS_TESTCASE_FAILED; // dont want to catch exception as we want to be able to get // gdb stack trace from the first error // by default tests should all always pass with no exceptions if( testCase.startup ) { testCase.startup(); } try { result = testCase.function(); } catch( const char* ) { // just catch test fail exception, return is already set to EXIT_STATUS_TESTCASE_FAILED } if( testCase.cleanup ) { testCase.cleanup(); } return result; } int32_t RunTestCaseInChildProcess( struct ::testcase_s& testCase, bool suppressOutput ) { int32_t testResult = EXIT_STATUS_TESTCASE_FAILED; int32_t pid = fork(); if( pid == 0 ) // Child process { if( suppressOutput ) { SuppressLogOutput(); } else { printf("\n"); for(int32_t i=0; i<80; ++i) printf("#"); printf("\nTC: %s\n", testCase.name); fflush(stdout); } int32_t status = RunTestCase( testCase ); if( ! suppressOutput ) { fflush(stdout); fflush(stderr); fclose(stdout); fclose(stderr); } exit( status ); } else if(pid == -1) { perror("fork"); exit(EXIT_STATUS_FORK_FAILED); } else // Parent process { int32_t status = 0; int32_t childPid = waitpid(pid, &status, 0); if( childPid == -1 ) { perror("waitpid"); exit(EXIT_STATUS_WAITPID_FAILED); } if( WIFEXITED(status) ) { if( childPid > 0 ) { testResult = WEXITSTATUS(status); if( testResult ) { printf("Test case %s failed: %d\n", testCase.name, testResult); } } } else if(WIFSIGNALED(status) ) { int32_t signal = WTERMSIG(status); testResult = EXIT_STATUS_TESTCASE_ABORTED; if( signal == SIGABRT ) { printf("Test case %s failed: test case asserted\n", testCase.name ); } else { printf("Test case %s failed: exit with signal %s\n", testCase.name, strsignal(WTERMSIG(status))); } } else if(WIFSTOPPED(status)) { printf("Test case %s failed: stopped with signal %s\n", testCase.name, strsignal(WSTOPSIG(status))); } } fflush(stdout); fflush(stderr); return testResult; } void OutputStatistics( const char* processName, int32_t numPasses, int32_t numFailures ) { FILE* fp=fopen("summary.xml", "a"); if( fp != NULL ) { fprintf( fp, " <suite name=\"%s\">\n" " <total_case>%d</total_case>\n" " <pass_case>%d</pass_case>\n" " <pass_rate>%5.2f</pass_rate>\n" " <fail_case>%d</fail_case>\n" " <fail_rate>%5.2f</fail_rate>\n" " <block_case>0</block_case>\n" " <block_rate>0.00</block_rate>\n" " <na_case>0</na_case>\n" " <na_rate>0.00</na_rate>\n" " </suite>\n", basename(processName), numPasses+numFailures, numPasses, (float)numPasses/(numPasses+numFailures), numFailures, (float)numFailures/(numPasses+numFailures) ); fclose(fp); } } int32_t RunAll( const char* processName, ::testcase tc_array[] ) { int32_t numFailures = 0; int32_t numPasses = 0; // Run test cases in child process( to kill output/handle signals ), but run serially. for( uint32_t i=0; tc_array[i].name; i++) { int32_t result = RunTestCaseInChildProcess( tc_array[i], false ); if( result == 0 ) { numPasses++; } else { numFailures++; } } OutputStatistics( processName, numPasses, numFailures); return numFailures; } // Constantly runs up to MAX_NUM_CHILDREN processes int32_t RunAllInParallel( const char* processName, ::testcase tc_array[], bool reRunFailed) { int32_t numFailures = 0; int32_t numPasses = 0; RunningTestCases children; std::vector<int32_t> failedTestCases; // Fork up to MAX_NUM_CHILDREN processes, then // wait. As soon as a proc completes, fork the next. int32_t nextTestCase = 0; int32_t numRunningChildren = 0; while( tc_array[nextTestCase].name || numRunningChildren > 0) { // Create more children (up to the max number or til the end of the array) while( numRunningChildren < MAX_NUM_CHILDREN && tc_array[nextTestCase].name ) { int32_t pid = fork(); if( pid == 0 ) // Child process { SuppressLogOutput(); exit( RunTestCase( tc_array[nextTestCase] ) ); } else if(pid == -1) { perror("fork"); exit(EXIT_STATUS_FORK_FAILED); } else // Parent process { TestCase tc(nextTestCase, tc_array[nextTestCase].name); children[pid] = tc; nextTestCase++; numRunningChildren++; } } // Wait for the next child to finish int32_t status=0; int32_t childPid = waitpid(-1, &status, 0); if( childPid == -1 ) { perror("waitpid"); exit(EXIT_STATUS_WAITPID_FAILED); } if( WIFEXITED(status) ) { if( childPid > 0 ) { int32_t testResult = WEXITSTATUS(status); if( testResult ) { printf("Test case %s failed: %d\n", children[childPid].testCaseName, testResult); failedTestCases.push_back(children[childPid].testCase); numFailures++; } else { numPasses++; } numRunningChildren--; } } else if( WIFSIGNALED(status) || WIFSTOPPED(status)) { status = WIFSIGNALED(status)?WTERMSIG(status):WSTOPSIG(status); if( childPid > 0 ) { RunningTestCases::iterator iter = children.find(childPid); if( iter != children.end() ) { printf("Test case %s exited with signal %s\n", iter->second.testCaseName, strsignal(status)); failedTestCases.push_back(iter->second.testCase); } else { printf("Unknown child process: %d signaled %s\n", childPid, strsignal(status)); } numFailures++; numRunningChildren--; } } } OutputStatistics( processName, numPasses, numFailures ); if( reRunFailed ) { for( uint32_t i=0; i<failedTestCases.size(); i++) { char* testCaseStrapline; int32_t numChars = asprintf(&testCaseStrapline, "Test case %s", tc_array[failedTestCases[i]].name ); printf("\n%s\n", testCaseStrapline); for(int32_t j=0; j<numChars; j++) { printf("="); } printf("\n"); RunTestCaseInChildProcess( tc_array[failedTestCases[i] ], false ); } } return numFailures; } int32_t FindAndRunTestCase(::testcase tc_array[], const char* testCaseName) { int32_t result = EXIT_STATUS_TESTCASE_NOT_FOUND; for( int32_t i = 0; tc_array[i].name; i++ ) { if( !strcmp(testCaseName, tc_array[i].name) ) { return RunTestCase( tc_array[i] ); } } printf("Unknown testcase name: \"%s\"\n", testCaseName); return result; } void Usage(const char* program) { printf("Usage: \n" " %s <testcase name>\t\t Execute a test case\n" " %s \t\t Execute all test cases in parallel\n" " %s -r\t\t Execute all test cases in parallel, rerunning failed test cases\n" " %s -s\t\t Execute all test cases serially\n", program, program, program, program); } } // namespace <|endoftext|>
<commit_before>#pragma once #include <string> #include <vector> #include <unordered_map> #include <memory> #include <functional> namespace warbler { enum ConsoleArgType { STRING, INT, FLOAT }; struct ConsoleArg { ConsoleArg() : intValue(0), floatValue(0.0) {} ConsoleArgType type; int intValue; double floatValue; std::string stringValue; }; typedef std::vector<const ConsoleArg> t_consoleArgs; typedef std::shared_ptr<t_consoleArgs> t_consoleArgs_ptr; typedef std::function<void(t_consoleArgs_ptr)> t_commandHandler; typedef std::vector<ConsoleArgType> t_consoleArgTypes; typedef std::shared_ptr<t_consoleArgTypes> t_consoleArgTypes_ptr; struct ConsoleCommand { ConsoleCommand() : handler(nullptr), argTypes(nullptr) {} ConsoleCommand(t_commandHandler handler, t_consoleArgTypes_ptr argTypes) : handler(handler), argTypes(argTypes) { } t_commandHandler handler; t_consoleArgTypes_ptr argTypes; }; struct ConsoleCommandSignature { ConsoleCommandSignature(): argCount(0) {} std::string name; int argCount; }; typedef std::vector<const ConsoleCommand> t_commandHandlers; typedef std::shared_ptr<t_commandHandlers> t_commandHandlers_ptr; typedef std::unordered_map<std::string, t_commandHandlers_ptr> t_commandHandlerMap; class Console { public: Console(); Console(Console& rhs); virtual ~Console(); void registerCommand(const std::string &name, t_commandHandler, t_consoleArgTypes_ptr argTypes); void executeCommand(const std::string command) const; private: t_commandHandlers_ptr _getHandlersByName(const std::string &name) const; ConsoleCommandSignature _getCommandSignature(const std::string &input) const; ConsoleCommand _getConsoleCommand(const ConsoleCommandSignature &signature) const; t_consoleArgs_ptr _getConsoleArgs(const std::string &input, const ConsoleCommand command) const; t_commandHandlerMap _commandHandlerMap = t_commandHandlerMap(); static bool _isNumber(const std::string &input); static bool _isInteger(const std::string &input); }; }<commit_msg>Remove unnecessary initializer.<commit_after>#pragma once #include <string> #include <vector> #include <unordered_map> #include <memory> #include <functional> namespace warbler { enum ConsoleArgType { STRING, INT, FLOAT }; struct ConsoleArg { ConsoleArg() : intValue(0), floatValue(0.0) {} ConsoleArgType type; int intValue; double floatValue; std::string stringValue; }; typedef std::vector<const ConsoleArg> t_consoleArgs; typedef std::shared_ptr<t_consoleArgs> t_consoleArgs_ptr; typedef std::function<void(t_consoleArgs_ptr)> t_commandHandler; typedef std::vector<ConsoleArgType> t_consoleArgTypes; typedef std::shared_ptr<t_consoleArgTypes> t_consoleArgTypes_ptr; struct ConsoleCommand { ConsoleCommand() : handler(nullptr), argTypes(nullptr) {} ConsoleCommand(t_commandHandler handler, t_consoleArgTypes_ptr argTypes) : handler(handler), argTypes(argTypes) { } t_commandHandler handler; t_consoleArgTypes_ptr argTypes; }; struct ConsoleCommandSignature { ConsoleCommandSignature(): argCount(0) {} std::string name; int argCount; }; typedef std::vector<const ConsoleCommand> t_commandHandlers; typedef std::shared_ptr<t_commandHandlers> t_commandHandlers_ptr; typedef std::unordered_map<std::string, t_commandHandlers_ptr> t_commandHandlerMap; class Console { public: Console(); Console(Console& rhs); virtual ~Console(); void registerCommand(const std::string &name, t_commandHandler, t_consoleArgTypes_ptr argTypes); void executeCommand(const std::string command) const; private: t_commandHandlers_ptr _getHandlersByName(const std::string &name) const; ConsoleCommandSignature _getCommandSignature(const std::string &input) const; ConsoleCommand _getConsoleCommand(const ConsoleCommandSignature &signature) const; t_consoleArgs_ptr _getConsoleArgs(const std::string &input, const ConsoleCommand command) const; t_commandHandlerMap _commandHandlerMap; static bool _isNumber(const std::string &input); static bool _isInteger(const std::string &input); }; }<|endoftext|>
<commit_before>/** * @copyright * ==================================================================== * Copyright (c) 2007 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== * @endcopyright * * @file StatusCallback.cpp * @brief Implementation of the class StatusCallback */ #include "StatusCallback.h" #include "EnumMapper.h" #include "SVNClient.h" #include "JNIUtil.h" #include "svn_time.h" #include "../include/org_tigris_subversion_javahl_NodeKind.h" #include "../include/org_tigris_subversion_javahl_Revision.h" #include "../include/org_tigris_subversion_javahl_StatusKind.h" /** * Create a StatusCallback object * @param jcallback the Java callback object. */ StatusCallback::StatusCallback(jobject jcallback) { m_callback = jcallback; } /** * Destroy a StatusCallback object */ StatusCallback::~StatusCallback() { // the m_callback does not need to be destroyed, because it is the passed // in parameter to the Java SVNClient.status method. } svn_error_t * StatusCallback::callback(void *baton, const char *path, svn_wc_status2_t *status, apr_pool_t *pool) { if (baton) ((StatusCallback *)baton)->doStatus(path, status); } /** * Callback called for a single status item. */ svn_error_t * StatusCallback::doStatus(const char *path, svn_wc_status2_t *status) { JNIEnv *env = JNIUtil::getEnv(); static jmethodID mid = 0; // the method id will not change during // the time this library is loaded, so // it can be cached. if (mid == 0) { jclass clazz = env->FindClass(JAVA_PACKAGE"/StatusCallback"); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; mid = env->GetMethodID(clazz, "doStatus", "(L"JAVA_PACKAGE"/Status;)V"); if (JNIUtil::isJavaExceptionThrown() || mid == 0) return SVN_NO_ERROR; env->DeleteLocalRef(clazz); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; } jobject jStatus = createJavaStatus(path, status); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->CallVoidMethod(m_callback, mid, jStatus); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->DeleteLocalRef(jStatus); // We return here regardless of whether an exception is thrown or not, // so we do not need to explicitly check for one. return SVN_NO_ERROR; } jobject StatusCallback::createJavaStatus(const char *path, svn_wc_status2_t *status) { JNIEnv *env = JNIUtil::getEnv(); jclass clazz = env->FindClass(JAVA_PACKAGE"/Status"); if (JNIUtil::isJavaExceptionThrown()) return NULL; static jmethodID mid = 0; if (mid == 0) { mid = env->GetMethodID(clazz, "<init>", "(Ljava/lang/String;Ljava/lang/String;" "IJJJLjava/lang/String;IIIIZZ" "Ljava/lang/String;Ljava/lang/String;" "Ljava/lang/String;Ljava/lang/String;" "JZLjava/lang/String;Ljava/lang/String;" "Ljava/lang/String;" "JLorg/tigris/subversion/javahl/Lock;" "JJILjava/lang/String;Ljava/lang/String;)V"); if (JNIUtil::isJavaExceptionThrown()) return NULL; } jstring jPath = JNIUtil::makeJString(path); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jUrl = NULL; jint jNodeKind = org_tigris_subversion_javahl_NodeKind_unknown; jlong jRevision = org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM; jlong jLastChangedRevision = org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM; jlong jLastChangedDate = 0; jstring jLastCommitAuthor = NULL; jint jTextType = org_tigris_subversion_javahl_StatusKind_none; jint jPropType = org_tigris_subversion_javahl_StatusKind_none; jint jRepositoryTextType = org_tigris_subversion_javahl_StatusKind_none; jint jRepositoryPropType = org_tigris_subversion_javahl_StatusKind_none; jboolean jIsLocked = JNI_FALSE; jboolean jIsCopied = JNI_FALSE; jboolean jIsSwitched = JNI_FALSE; jstring jConflictOld = NULL; jstring jConflictNew = NULL; jstring jConflictWorking = NULL; jstring jURLCopiedFrom = NULL; jlong jRevisionCopiedFrom = org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM; jstring jLockToken = NULL; jstring jLockComment = NULL; jstring jLockOwner = NULL; jlong jLockCreationDate = 0; jobject jLock = NULL; jlong jOODLastCmtRevision = org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM; jlong jOODLastCmtDate = 0; jint jOODKind = org_tigris_subversion_javahl_NodeKind_none; jstring jOODLastCmtAuthor = NULL; jstring jChangelist = NULL; if (status != NULL) { jTextType = EnumMapper::mapStatusKind(status->text_status); jPropType = EnumMapper::mapStatusKind(status->prop_status); jRepositoryTextType = EnumMapper::mapStatusKind( status->repos_text_status); jRepositoryPropType = EnumMapper::mapStatusKind( status->repos_prop_status); jIsCopied = (status->copied == 1) ? JNI_TRUE: JNI_FALSE; jIsLocked = (status->locked == 1) ? JNI_TRUE: JNI_FALSE; jIsSwitched = (status->switched == 1) ? JNI_TRUE: JNI_FALSE; jLock = SVNClient::createJavaLock(status->repos_lock); if (JNIUtil::isJavaExceptionThrown()) return NULL; jUrl = JNIUtil::makeJString(status->url); if (JNIUtil::isJavaExceptionThrown()) return NULL; jOODLastCmtRevision = status->ood_last_cmt_rev; jOODLastCmtDate = status->ood_last_cmt_date; jOODKind = EnumMapper::mapNodeKind(status->ood_kind); jOODLastCmtAuthor = JNIUtil::makeJString(status->ood_last_cmt_author); if (JNIUtil::isJavaExceptionThrown()) return NULL; svn_wc_entry_t *entry = status->entry; if (entry != NULL) { jNodeKind = EnumMapper::mapNodeKind(entry->kind); jRevision = entry->revision; jLastChangedRevision = entry->cmt_rev; jLastChangedDate = entry->cmt_date; jLastCommitAuthor = JNIUtil::makeJString(entry->cmt_author); if (JNIUtil::isJavaExceptionThrown()) return NULL; jConflictNew = JNIUtil::makeJString(entry->conflict_new); if (JNIUtil::isJavaExceptionThrown()) return NULL; jConflictOld = JNIUtil::makeJString(entry->conflict_old); if (JNIUtil::isJavaExceptionThrown()) return NULL; jConflictWorking= JNIUtil::makeJString(entry->conflict_wrk); if (JNIUtil::isJavaExceptionThrown()) return NULL; jURLCopiedFrom = JNIUtil::makeJString(entry->copyfrom_url); if (JNIUtil::isJavaExceptionThrown()) return NULL; jRevisionCopiedFrom = entry->copyfrom_rev; jLockToken = JNIUtil::makeJString(entry->lock_token); if (JNIUtil::isJavaExceptionThrown()) return NULL; jLockComment = JNIUtil::makeJString(entry->lock_comment); if (JNIUtil::isJavaExceptionThrown()) return NULL; jLockOwner = JNIUtil::makeJString(entry->lock_owner); if (JNIUtil::isJavaExceptionThrown()) return NULL; jLockCreationDate = entry->lock_creation_date; jChangelist = JNIUtil::makeJString(entry->changelist); if (JNIUtil::isJavaExceptionThrown()) return NULL; } } jobject ret = env->NewObject(clazz, mid, jPath, jUrl, jNodeKind, jRevision, jLastChangedRevision, jLastChangedDate, jLastCommitAuthor, jTextType, jPropType, jRepositoryTextType, jRepositoryPropType, jIsLocked, jIsCopied, jConflictOld, jConflictNew, jConflictWorking, jURLCopiedFrom, jRevisionCopiedFrom, jIsSwitched, jLockToken, jLockOwner, jLockComment, jLockCreationDate, jLock, jOODLastCmtRevision, jOODLastCmtDate, jOODKind, jOODLastCmtAuthor, jChangelist); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(clazz); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jPath); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jUrl); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jLastCommitAuthor); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jConflictNew); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jConflictOld); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jConflictWorking); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jURLCopiedFrom); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jLockComment); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jLockOwner); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jLockToken); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jLock); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jOODLastCmtAuthor); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jChangelist); if (JNIUtil::isJavaExceptionThrown()) return NULL; return ret; } <commit_msg>* subversion/bindings/javahl/native/StatusCallback.cpp (StatusCallback::callback): Following up on r33739, return SVN_NO_ERROR to fix compilation.<commit_after>/** * @copyright * ==================================================================== * Copyright (c) 2007 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== * @endcopyright * * @file StatusCallback.cpp * @brief Implementation of the class StatusCallback */ #include "StatusCallback.h" #include "EnumMapper.h" #include "SVNClient.h" #include "JNIUtil.h" #include "svn_time.h" #include "../include/org_tigris_subversion_javahl_NodeKind.h" #include "../include/org_tigris_subversion_javahl_Revision.h" #include "../include/org_tigris_subversion_javahl_StatusKind.h" /** * Create a StatusCallback object * @param jcallback the Java callback object. */ StatusCallback::StatusCallback(jobject jcallback) { m_callback = jcallback; } /** * Destroy a StatusCallback object */ StatusCallback::~StatusCallback() { // the m_callback does not need to be destroyed, because it is the passed // in parameter to the Java SVNClient.status method. } svn_error_t * StatusCallback::callback(void *baton, const char *path, svn_wc_status2_t *status, apr_pool_t *pool) { if (baton) ((StatusCallback *)baton)->doStatus(path, status); return SVN_NO_ERROR; } /** * Callback called for a single status item. */ svn_error_t * StatusCallback::doStatus(const char *path, svn_wc_status2_t *status) { JNIEnv *env = JNIUtil::getEnv(); static jmethodID mid = 0; // the method id will not change during // the time this library is loaded, so // it can be cached. if (mid == 0) { jclass clazz = env->FindClass(JAVA_PACKAGE"/StatusCallback"); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; mid = env->GetMethodID(clazz, "doStatus", "(L"JAVA_PACKAGE"/Status;)V"); if (JNIUtil::isJavaExceptionThrown() || mid == 0) return SVN_NO_ERROR; env->DeleteLocalRef(clazz); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; } jobject jStatus = createJavaStatus(path, status); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->CallVoidMethod(m_callback, mid, jStatus); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->DeleteLocalRef(jStatus); // We return here regardless of whether an exception is thrown or not, // so we do not need to explicitly check for one. return SVN_NO_ERROR; } jobject StatusCallback::createJavaStatus(const char *path, svn_wc_status2_t *status) { JNIEnv *env = JNIUtil::getEnv(); jclass clazz = env->FindClass(JAVA_PACKAGE"/Status"); if (JNIUtil::isJavaExceptionThrown()) return NULL; static jmethodID mid = 0; if (mid == 0) { mid = env->GetMethodID(clazz, "<init>", "(Ljava/lang/String;Ljava/lang/String;" "IJJJLjava/lang/String;IIIIZZ" "Ljava/lang/String;Ljava/lang/String;" "Ljava/lang/String;Ljava/lang/String;" "JZLjava/lang/String;Ljava/lang/String;" "Ljava/lang/String;" "JLorg/tigris/subversion/javahl/Lock;" "JJILjava/lang/String;Ljava/lang/String;)V"); if (JNIUtil::isJavaExceptionThrown()) return NULL; } jstring jPath = JNIUtil::makeJString(path); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jUrl = NULL; jint jNodeKind = org_tigris_subversion_javahl_NodeKind_unknown; jlong jRevision = org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM; jlong jLastChangedRevision = org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM; jlong jLastChangedDate = 0; jstring jLastCommitAuthor = NULL; jint jTextType = org_tigris_subversion_javahl_StatusKind_none; jint jPropType = org_tigris_subversion_javahl_StatusKind_none; jint jRepositoryTextType = org_tigris_subversion_javahl_StatusKind_none; jint jRepositoryPropType = org_tigris_subversion_javahl_StatusKind_none; jboolean jIsLocked = JNI_FALSE; jboolean jIsCopied = JNI_FALSE; jboolean jIsSwitched = JNI_FALSE; jstring jConflictOld = NULL; jstring jConflictNew = NULL; jstring jConflictWorking = NULL; jstring jURLCopiedFrom = NULL; jlong jRevisionCopiedFrom = org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM; jstring jLockToken = NULL; jstring jLockComment = NULL; jstring jLockOwner = NULL; jlong jLockCreationDate = 0; jobject jLock = NULL; jlong jOODLastCmtRevision = org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM; jlong jOODLastCmtDate = 0; jint jOODKind = org_tigris_subversion_javahl_NodeKind_none; jstring jOODLastCmtAuthor = NULL; jstring jChangelist = NULL; if (status != NULL) { jTextType = EnumMapper::mapStatusKind(status->text_status); jPropType = EnumMapper::mapStatusKind(status->prop_status); jRepositoryTextType = EnumMapper::mapStatusKind( status->repos_text_status); jRepositoryPropType = EnumMapper::mapStatusKind( status->repos_prop_status); jIsCopied = (status->copied == 1) ? JNI_TRUE: JNI_FALSE; jIsLocked = (status->locked == 1) ? JNI_TRUE: JNI_FALSE; jIsSwitched = (status->switched == 1) ? JNI_TRUE: JNI_FALSE; jLock = SVNClient::createJavaLock(status->repos_lock); if (JNIUtil::isJavaExceptionThrown()) return NULL; jUrl = JNIUtil::makeJString(status->url); if (JNIUtil::isJavaExceptionThrown()) return NULL; jOODLastCmtRevision = status->ood_last_cmt_rev; jOODLastCmtDate = status->ood_last_cmt_date; jOODKind = EnumMapper::mapNodeKind(status->ood_kind); jOODLastCmtAuthor = JNIUtil::makeJString(status->ood_last_cmt_author); if (JNIUtil::isJavaExceptionThrown()) return NULL; svn_wc_entry_t *entry = status->entry; if (entry != NULL) { jNodeKind = EnumMapper::mapNodeKind(entry->kind); jRevision = entry->revision; jLastChangedRevision = entry->cmt_rev; jLastChangedDate = entry->cmt_date; jLastCommitAuthor = JNIUtil::makeJString(entry->cmt_author); if (JNIUtil::isJavaExceptionThrown()) return NULL; jConflictNew = JNIUtil::makeJString(entry->conflict_new); if (JNIUtil::isJavaExceptionThrown()) return NULL; jConflictOld = JNIUtil::makeJString(entry->conflict_old); if (JNIUtil::isJavaExceptionThrown()) return NULL; jConflictWorking= JNIUtil::makeJString(entry->conflict_wrk); if (JNIUtil::isJavaExceptionThrown()) return NULL; jURLCopiedFrom = JNIUtil::makeJString(entry->copyfrom_url); if (JNIUtil::isJavaExceptionThrown()) return NULL; jRevisionCopiedFrom = entry->copyfrom_rev; jLockToken = JNIUtil::makeJString(entry->lock_token); if (JNIUtil::isJavaExceptionThrown()) return NULL; jLockComment = JNIUtil::makeJString(entry->lock_comment); if (JNIUtil::isJavaExceptionThrown()) return NULL; jLockOwner = JNIUtil::makeJString(entry->lock_owner); if (JNIUtil::isJavaExceptionThrown()) return NULL; jLockCreationDate = entry->lock_creation_date; jChangelist = JNIUtil::makeJString(entry->changelist); if (JNIUtil::isJavaExceptionThrown()) return NULL; } } jobject ret = env->NewObject(clazz, mid, jPath, jUrl, jNodeKind, jRevision, jLastChangedRevision, jLastChangedDate, jLastCommitAuthor, jTextType, jPropType, jRepositoryTextType, jRepositoryPropType, jIsLocked, jIsCopied, jConflictOld, jConflictNew, jConflictWorking, jURLCopiedFrom, jRevisionCopiedFrom, jIsSwitched, jLockToken, jLockOwner, jLockComment, jLockCreationDate, jLock, jOODLastCmtRevision, jOODLastCmtDate, jOODKind, jOODLastCmtAuthor, jChangelist); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(clazz); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jPath); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jUrl); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jLastCommitAuthor); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jConflictNew); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jConflictOld); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jConflictWorking); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jURLCopiedFrom); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jLockComment); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jLockOwner); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jLockToken); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jLock); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jOODLastCmtAuthor); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jChangelist); if (JNIUtil::isJavaExceptionThrown()) return NULL; return ret; } <|endoftext|>
<commit_before>/* Ameba implementation of NetworkInterfaceAPI * Copyright (c) 2015 ARM Limited * * 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 "mbed.h" #include "rtos.h" #include "RTWInterface.h" #include "mbed_interface.h" #include "rtw_emac.h" #include "wifi_constants.h" #include "wifi_conf.h" #include "lwip_stack.h" #include "osdep_service.h" struct netif *xnetif[2]; static struct netif lwap_netif; extern struct netif *netif_default; RTWInterface::RTWInterface() : _dhcp(true), _ip_address(), _netmask(), _gateway() { nsapi_error_t ret; ret = init(); if (ret != NSAPI_ERROR_OK){ printf("Error init RTWInterface!(%d)\r\n", ret); } } static void *scan_sema; static const signed int maxApNum = 4; static signed int ApNum; static WiFiAccessPoint *SCANED_AP[maxApNum]; /*maximum store 15 APs*/ nsapi_error_t RTWInterface::set_network(const char *ip_address, const char *netmask, const char *gateway) { _dhcp = false; strncpy(_ip_address, ip_address ? ip_address : "", sizeof(_ip_address)); strncpy(_netmask, netmask ? netmask : "", sizeof(_netmask)); strncpy(_gateway, gateway ? gateway : "", sizeof(_gateway)); return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::set_dhcp(bool dhcp) { _dhcp = dhcp; return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::init() { emac_interface_t *emac; int ret; //printf("\r\nInitializing emac ...\r\n"); emac = wlan_emac_init_interface(); if (!emac) { return NSAPI_ERROR_DEVICE_ERROR; } emac->ops.power_up(emac); //printf("Initializing lwip ...\r\n"); ret = mbed_lwip_init(emac); if (ret != 0) { return ret; } xnetif[0] = netif_default; return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::deinit() { return mbed_lwip_bringdown(); } /* * we may call connect multiple times */ nsapi_error_t RTWInterface::set_credentials(const char *ssid, const char *pass, nsapi_security_t security) { strncpy(_ssid, ssid, 255); strncpy(_pass, pass, 255); _security = security; return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::connect() { int ret; rtw_security_t sec; if (!_ssid || (!_pass && _security != NSAPI_SECURITY_NONE)) { printf("Invalid credentials\r\n"); return NSAPI_ERROR_PARAMETER; } switch (_security) { case NSAPI_SECURITY_WPA2: sec = RTW_SECURITY_WPA2_MIXED_PSK; break; case NSAPI_SECURITY_NONE: default: sec = RTW_SECURITY_OPEN; break; } printf("Connecting to: %s ... \r\n", _ssid); ret = wifi_connect(_ssid, sec, _pass, strlen(_ssid), strlen(_pass), 0, (void *)NULL); if (ret != RTW_SUCCESS) { printf("failed: %d\r\n", ret); return NSAPI_ERROR_NO_CONNECTION; } //printf("connected\r\n"); wlan_emac_link_up(0); return mbed_lwip_bringup(_dhcp, _ip_address[0] ? _ip_address : 0, _netmask[0] ? _netmask : 0, _gateway[0] ? _gateway : 0); } static rtw_result_t scan_result_handler( rtw_scan_handler_result_t* malloced_scan_result ) { if (malloced_scan_result->scan_complete != RTW_TRUE) { rtw_scan_result_t* record = &malloced_scan_result->ap_details; record->SSID.val[record->SSID.len] = 0; /* Ensure the SSID is null terminated */ if(ApNum>maxApNum) return RTW_SUCCESS; nsapi_wifi_ap_t ap; memset((void*)&ap, 0x00, sizeof(nsapi_wifi_ap_t)); memcpy(ap.ssid, record->SSID.val, record->SSID.len); memcpy(ap.bssid, record->BSSID.octet, 6); ap.security = (record->security == RTW_SECURITY_OPEN)?NSAPI_SECURITY_NONE : (record->security == RTW_SECURITY_WEP_PSK)?NSAPI_SECURITY_WEP: (record->security == RTW_SECURITY_WPA_TKIP_PSK || record->security == RTW_SECURITY_WPA_AES_PSK)? NSAPI_SECURITY_WPA: (record->security == RTW_SECURITY_WPA2_AES_PSK || \ record->security == RTW_SECURITY_WPA2_TKIP_PSK || \ record->security == RTW_SECURITY_WPA2_MIXED_PSK)?NSAPI_SECURITY_WPA2: (record->security == RTW_SECURITY_WPA_WPA2_MIXED)?NSAPI_SECURITY_WPA_WPA2:NSAPI_SECURITY_UNKNOWN; ap.rssi = record->signal_strength; ap.channel = record->channel; SCANED_AP[ApNum++] = new WiFiAccessPoint(ap); } else{ // scan done rtw_up_sema(&scan_sema); } return RTW_SUCCESS; } nsapi_error_t RTWInterface::scan(WiFiAccessPoint *res, unsigned count) { // blocked if(count == 0){ ApNum = 0; rtw_init_sema(&scan_sema, 0); if(wifi_scan_networks(scan_result_handler, NULL) != RTW_SUCCESS){ printf("wifi scan failed\n\r"); //return NSAPI_ERROR_DEVICE_ERROR; goto error; } if(rtw_down_timeout_sema( &scan_sema, 15000 ) == RTW_FALSE) { printf("wifi scan timeout\r\n"); //return NSAPI_ERROR_DEVICE_ERROR; goto error; } rtw_free_sema(&scan_sema); return ApNum; }else if(count > 0 && res != NULL){ count = count < maxApNum ? count : maxApNum; for(int i = 0; i < count; i++){ memcpy(&res[i], SCANED_AP[i], sizeof(WiFiAccessPoint)); delete[] SCANED_AP[i]; } return (signed int)count; } return NSAPI_ERROR_OK; error: rtw_free_sema(&scan_sema); return NSAPI_ERROR_DEVICE_ERROR; } nsapi_error_t RTWInterface::set_channel(uint8_t channel) { if(wifi_set_channel(channel) == 0) return NSAPI_ERROR_OK; return NSAPI_ERROR_DEVICE_ERROR; } int8_t RTWInterface::get_rssi() { return NSAPI_ERROR_UNSUPPORTED; } nsapi_error_t RTWInterface::connect(const char *ssid, const char *pass, nsapi_security_t security, uint8_t channel) { set_credentials(ssid, pass, security); return connect(); } nsapi_error_t RTWInterface::disconnect() { char essid[33]; if(wifi_is_connected_to_ap() != RTW_SUCCESS) return NSAPI_ERROR_NO_CONNECTION; printf("Deassociating AP ...\r\n"); if(wifi_disconnect()<0){ return NSAPI_ERROR_DEVICE_ERROR; } while(1){ if(wext_get_ssid(WLAN0_NAME, (unsigned char *) essid) < 0) { printf("WIFI disconnected\n\r"); break; } } return NSAPI_ERROR_OK; } int RTWInterface::is_connected() { // wifi_is_connected_to_ap return 0 on connected return !wifi_is_connected_to_ap(); } const char *RTWInterface::get_mac_address() { return mbed_lwip_get_mac_address(); } const char *RTWInterface::get_ip_address() { if (mbed_lwip_get_ip_address(_ip_address, sizeof _ip_address)) { return _ip_address; } return 0; } const char *RTWInterface::get_netmask() { if (mbed_lwip_get_netmask(_netmask, sizeof _netmask)) { return _netmask; } return 0; } const char *RTWInterface::get_gateway() { if (mbed_lwip_get_gateway(_gateway, sizeof _gateway)) { return _gateway; } return 0; } NetworkStack *RTWInterface::get_stack() { return nsapi_create_stack(&lwip_stack); } <commit_msg>Update RTWInterface.cpp<commit_after>/* Ameba implementation of NetworkInterfaceAPI * Copyright (c) 2015 ARM Limited * * 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 "mbed.h" #include "rtos.h" #include "RTWInterface.h" #include "mbed_interface.h" #include "rtw_emac.h" #include "wifi_constants.h" #include "wifi_conf.h" #include "lwip_stack.h" #include "osdep_service.h" struct netif *xnetif[2]; static struct netif lwap_netif; extern struct netif *netif_default; RTWInterface::RTWInterface() : _dhcp(true), _ip_address(), _netmask(), _gateway() { nsapi_error_t ret; ret = init(); if (ret != NSAPI_ERROR_OK){ printf("Error init RTWInterface!(%d)\r\n", ret); } } static void *scan_sema; static const signed int maxApNum = 4; static signed int ApNum; static WiFiAccessPoint *SCANED_AP[maxApNum]; /*maximum store 15 APs*/ nsapi_error_t RTWInterface::set_network(const char *ip_address, const char *netmask, const char *gateway) { _dhcp = false; strncpy(_ip_address, ip_address ? ip_address : "", sizeof(_ip_address)); strncpy(_netmask, netmask ? netmask : "", sizeof(_netmask)); strncpy(_gateway, gateway ? gateway : "", sizeof(_gateway)); return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::set_dhcp(bool dhcp) { _dhcp = dhcp; return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::init() { emac_interface_t *emac; int ret; //printf("\r\nInitializing emac ...\r\n"); emac = wlan_emac_init_interface(); if (!emac) { return NSAPI_ERROR_DEVICE_ERROR; } emac->ops.power_up(emac); //printf("Initializing lwip ...\r\n"); ret = mbed_lwip_init(emac); if (ret != 0) { return ret; } xnetif[0] = netif_default; return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::deinit() { return mbed_lwip_bringdown(); } /* * we may call connect multiple times */ nsapi_error_t RTWInterface::set_credentials(const char *ssid, const char *pass, nsapi_security_t security) { strncpy(_ssid, ssid, 255); strncpy(_pass, pass, 255); _security = security; return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::connect() { int ret; rtw_security_t sec; if (!_ssid || (!_pass && _security != NSAPI_SECURITY_NONE)) { printf("Invalid credentials\r\n"); return NSAPI_ERROR_PARAMETER; } switch (_security) { case NSAPI_SECURITY_WPA2: sec = RTW_SECURITY_WPA2_MIXED_PSK; break; case NSAPI_SECURITY_NONE: default: sec = RTW_SECURITY_OPEN; break; } printf("Connecting to: %s ... \r\n", _ssid); ret = wifi_connect(_ssid, sec, _pass, strlen(_ssid), strlen(_pass), 0, (void *)NULL); if (ret != RTW_SUCCESS) { printf("failed: %d\r\n", ret); return NSAPI_ERROR_NO_CONNECTION; } //printf("connected\r\n"); wlan_emac_link_up(0); return mbed_lwip_bringup(_dhcp, _ip_address[0] ? _ip_address : 0, _netmask[0] ? _netmask : 0, _gateway[0] ? _gateway : 0); } static rtw_result_t scan_result_handler( rtw_scan_handler_result_t* malloced_scan_result ) { if (malloced_scan_result->scan_complete != RTW_TRUE) { rtw_scan_result_t* record = &malloced_scan_result->ap_details; record->SSID.val[record->SSID.len] = 0; /* Ensure the SSID is null terminated */ if(ApNum>maxApNum) return RTW_SUCCESS; nsapi_wifi_ap_t ap; memset((void*)&ap, 0x00, sizeof(nsapi_wifi_ap_t)); memcpy(ap.ssid, record->SSID.val, record->SSID.len); memcpy(ap.bssid, record->BSSID.octet, 6); ap.security = (record->security == RTW_SECURITY_OPEN)?NSAPI_SECURITY_NONE : (record->security == RTW_SECURITY_WEP_PSK)?NSAPI_SECURITY_WEP: (record->security == RTW_SECURITY_WPA_TKIP_PSK || record->security == RTW_SECURITY_WPA_AES_PSK)? NSAPI_SECURITY_WPA: (record->security == RTW_SECURITY_WPA2_AES_PSK || \ record->security == RTW_SECURITY_WPA2_TKIP_PSK || \ record->security == RTW_SECURITY_WPA2_MIXED_PSK)?NSAPI_SECURITY_WPA2: (record->security == RTW_SECURITY_WPA_WPA2_MIXED)?NSAPI_SECURITY_WPA_WPA2:NSAPI_SECURITY_UNKNOWN; ap.rssi = record->signal_strength; ap.channel = record->channel; SCANED_AP[ApNum++] = new WiFiAccessPoint(ap); } else{ // scan done rtw_up_sema(&scan_sema); } return RTW_SUCCESS; } nsapi_error_t RTWInterface::scan(WiFiAccessPoint *res, unsigned count) { // blocked if(count == 0){ ApNum = 0; rtw_init_sema(&scan_sema, 0); if(wifi_scan_networks(scan_result_handler, NULL) != RTW_SUCCESS){ printf("wifi scan failed\n\r"); //return NSAPI_ERROR_DEVICE_ERROR; goto error; } if(rtw_down_timeout_sema( &scan_sema, 15000 ) == RTW_FALSE) { printf("wifi scan timeout\r\n"); //return NSAPI_ERROR_DEVICE_ERROR; goto error; } rtw_free_sema(&scan_sema); return ApNum; }else if(count > 0 && res != NULL){ count = count < maxApNum ? count : maxApNum; for(int i = 0; i < count; i++){ memcpy(&res[i], SCANED_AP[i], sizeof(WiFiAccessPoint)); delete[] SCANED_AP[i]; } return (signed int)count; } return NSAPI_ERROR_OK; error: rtw_free_sema(&scan_sema); return NSAPI_ERROR_DEVICE_ERROR; } nsapi_error_t RTWInterface::set_channel(uint8_t channel) { if(wifi_set_channel(channel) == 0) return NSAPI_ERROR_OK; return NSAPI_ERROR_DEVICE_ERROR; } int8_t RTWInterface::get_rssi() { return NSAPI_ERROR_UNSUPPORTED; } nsapi_error_t RTWInterface::connect(const char *ssid, const char *pass, nsapi_security_t security, uint8_t channel) { set_credentials(ssid, pass, security); return connect(); } nsapi_error_t RTWInterface::disconnect() { char essid[33]; if(wifi_is_connected_to_ap() != RTW_SUCCESS) return NSAPI_ERROR_NO_CONNECTION; printf("Deassociating AP ...\r\n"); if(wifi_disconnect()<0){ return NSAPI_ERROR_DEVICE_ERROR; } while(1){ if(wext_get_ssid(WLAN0_NAME, (unsigned char *) essid) < 0) { printf("WIFI disconnected\n\r"); break; } } return NSAPI_ERROR_OK; } int RTWInterface::is_connected() { // wifi_is_connected_to_ap return 0 on connected return !wifi_is_connected_to_ap(); } const char *RTWInterface::get_mac_address() { return mbed_lwip_get_mac_address(); } const char *RTWInterface::get_ip_address() { if (mbed_lwip_get_ip_address(_ip_address, sizeof _ip_address)) { return _ip_address; } return 0; } const char *RTWInterface::get_netmask() { if (mbed_lwip_get_netmask(_netmask, sizeof _netmask)) { return _netmask; } return 0; } const char *RTWInterface::get_gateway() { if (mbed_lwip_get_gateway(_gateway, sizeof _gateway)) { return _gateway; } return 0; } NetworkStack *RTWInterface::get_stack() { return nsapi_create_stack(&lwip_stack); } <|endoftext|>
<commit_before>/* Ameba implementation of NetworkInterfaceAPI * Copyright (c) 2015 ARM Limited * * 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 "mbed.h" #include "rtos.h" #include "RTWInterface.h" #include "mbed_interface.h" #include "rtw_emac.h" #include "wifi_constants.h" #include "wifi_conf.h" #include "lwip_stack.h" #include "osdep_service.h" struct netif *xnetif[2]; static struct netif lwap_netif; extern struct netif *netif_default; RTWInterface::RTWInterface() : _dhcp(true), _ip_address(), _netmask(), _gateway() { nsapi_error_t ret; ret = init(); if (ret != NSAPI_ERROR_OK){ printf("Error init RTWInterface!(%d)\r\n", ret); } } static void *scan_sema; static const signed int maxApNum = 4; static signed int ApNum; static WiFiAccessPoint *SCANED_AP[maxApNum]; /*maximum store 15 APs*/ nsapi_error_t RTWInterface::set_network(const char *ip_address, const char *netmask, const char *gateway) { _dhcp = false; strncpy(_ip_address, ip_address ? ip_address : "", sizeof(_ip_address)); strncpy(_netmask, netmask ? netmask : "", sizeof(_netmask)); strncpy(_gateway, gateway ? gateway : "", sizeof(_gateway)); return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::set_dhcp(bool dhcp) { _dhcp = dhcp; return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::init() { emac_interface_t *emac; int ret; //printf("\r\nInitializing emac ...\r\n"); emac = wlan_emac_init_interface(); if (!emac) { return NSAPI_ERROR_DEVICE_ERROR; } emac->ops.power_up(emac); //printf("Initializing lwip ...\r\n"); ret = mbed_lwip_init(emac); if (ret != 0) { return ret; } xnetif[0] = netif_default; return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::deinit() { return mbed_lwip_bringdown(); } /* * we may call connect multiple times */ nsapi_error_t RTWInterface::set_credentials(const char *ssid, const char *pass, nsapi_security_t security) { strncpy(_ssid, ssid, 255); strncpy(_pass, pass, 255); _security = security; return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::connect() { int ret; rtw_security_t sec; if (!_ssid || (!_pass && _security != NSAPI_SECURITY_NONE)) { printf("Invalid credentials\r\n"); return NSAPI_ERROR_PARAMETER; } switch (_security) { case NSAPI_SECURITY_WPA2: sec = RTW_SECURITY_WPA2_MIXED_PSK; break; case NSAPI_SECURITY_NONE: default: sec = RTW_SECURITY_OPEN; break; } printf("Connecting to: %s ... \r\n", _ssid); ret = wifi_connect(_ssid, sec, _pass, strlen(_ssid), strlen(_pass), 0, (void *)NULL); if (ret != RTW_SUCCESS) { printf("failed: %d\r\n", ret); return NSAPI_ERROR_NO_CONNECTION; } //printf("connected\r\n"); wlan_emac_link_up(0); return mbed_lwip_bringup(_dhcp, _ip_address[0] ? _ip_address : 0, _netmask[0] ? _netmask : 0, _gateway[0] ? _gateway : 0); } static rtw_result_t scan_result_handler( rtw_scan_handler_result_t* malloced_scan_result ) { if (malloced_scan_result->scan_complete != RTW_TRUE) { rtw_scan_result_t* record = &malloced_scan_result->ap_details; record->SSID.val[record->SSID.len] = 0; /* Ensure the SSID is null terminated */ if(ApNum>maxApNum) return RTW_SUCCESS; nsapi_wifi_ap_t ap; memset((void*)&ap, 0x00, sizeof(nsapi_wifi_ap_t)); memcpy(ap.ssid, record->SSID.val, record->SSID.len); memcpy(ap.bssid, record->BSSID.octet, 6); ap.security = (record->security == RTW_SECURITY_OPEN)?NSAPI_SECURITY_NONE : (record->security == RTW_SECURITY_WEP_PSK)?NSAPI_SECURITY_WEP: (record->security == RTW_SECURITY_WPA_TKIP_PSK || record->security == RTW_SECURITY_WPA_AES_PSK)? NSAPI_SECURITY_WPA: (record->security == RTW_SECURITY_WPA2_AES_PSK || \ record->security == RTW_SECURITY_WPA2_TKIP_PSK || \ record->security == RTW_SECURITY_WPA2_MIXED_PSK)?NSAPI_SECURITY_WPA2: (record->security == RTW_SECURITY_WPA_WPA2_MIXED)?NSAPI_SECURITY_WPA_WPA2:NSAPI_SECURITY_UNKNOWN; ap.rssi = record->signal_strength; ap.channel = record->channel; SCANED_AP[ApNum++] = new WiFiAccessPoint(ap); } else{ // scan done rtw_up_sema(&scan_sema); } return RTW_SUCCESS; } nsapi_error_t RTWInterface::scan(WiFiAccessPoint *res, unsigned count) { // blocked if(count == 0){ ApNum = 0; rtw_init_sema(&scan_sema, 0); if(wifi_scan_networks(scan_result_handler, NULL) != RTW_SUCCESS){ printf("wifi scan failed\n\r"); //return NSAPI_ERROR_DEVICE_ERROR; goto error; } if(rtw_down_timeout_sema( &scan_sema, 15000 ) == RTW_FALSE) { printf("wifi scan timeout\r\n"); //return NSAPI_ERROR_DEVICE_ERROR; goto error; } rtw_free_sema(&scan_sema); return ApNum; }else if(count > 0 && res != NULL){ count = count < maxApNum ? count : maxApNum; for(int i = 0; i < count; i++){ memcpy(&res[i], SCANED_AP[i], sizeof(WiFiAccessPoint)); delete[] SCANED_AP[i]; } return (signed int)count; } return NSAPI_ERROR_OK; error: rtw_free_sema(&scan_sema); return NSAPI_ERROR_DEVICE_ERROR; } nsapi_error_t RTWInterface::set_channel(uint8_t channel) { if(wifi_set_channel(channel) == 0) return NSAPI_ERROR_OK; return NSAPI_ERROR_DEVICE_ERROR; } int8_t RTWInterface::get_rssi() { return NSAPI_ERROR_UNSUPPORTED; } nsapi_error_t RTWInterface::connect(const char *ssid, const char *pass, nsapi_security_t security, uint8_t channel) { set_credentials(ssid, pass, security); return connect(); } nsapi_error_t RTWInterface::disconnect() { char essid[33]; if(wifi_is_connected_to_ap() != RTW_SUCCESS) return NSAPI_ERROR_NO_CONNECTION; printf("Deassociating AP ...\r\n"); if(wifi_disconnect()<0){ return NSAPI_ERROR_DEVICE_ERROR; } while(1){ if(wext_get_ssid(WLAN0_NAME, (unsigned char *) essid) < 0) { printf("WIFI disconnected\n\r"); break; } } return NSAPI_ERROR_OK; } int RTWInterface::is_connected() { // wifi_is_connected_to_ap return 0 on connected return !wifi_is_connected_to_ap(); } const char *RTWInterface::get_mac_address() { return mbed_lwip_get_mac_address(); } const char *RTWInterface::get_ip_address() { if (mbed_lwip_get_ip_address(_ip_address, sizeof _ip_address)) { return _ip_address; } return 0; } const char *RTWInterface::get_netmask() { if (mbed_lwip_get_netmask(_netmask, sizeof _netmask)) { return _netmask; } return 0; } const char *RTWInterface::get_gateway() { if (mbed_lwip_get_gateway(_gateway, sizeof _gateway)) { return _gateway; } return 0; } NetworkStack *RTWInterface::get_stack() { return nsapi_create_stack(&lwip_stack); } <commit_msg>Update RTWInterface.cpp<commit_after>/* Ameba implementation of NetworkInterfaceAPI * Copyright (c) 2015 ARM Limited * * 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 "mbed.h" #include "rtos.h" #include "RTWInterface.h" #include "mbed_interface.h" #include "rtw_emac.h" #include "wifi_constants.h" #include "wifi_conf.h" #include "lwip_stack.h" #include "osdep_service.h" struct netif *xnetif[2]; static struct netif lwap_netif; extern struct netif *netif_default; RTWInterface::RTWInterface() : _dhcp(true), _ip_address(), _netmask(), _gateway() { nsapi_error_t ret; ret = init(); if (ret != NSAPI_ERROR_OK){ printf("Error init RTWInterface!(%d)\r\n", ret); } } static void *scan_sema; static const signed int maxApNum = 4; static signed int ApNum; static WiFiAccessPoint *SCANED_AP[maxApNum]; /*maximum store 15 APs*/ nsapi_error_t RTWInterface::set_network(const char *ip_address, const char *netmask, const char *gateway) { _dhcp = false; strncpy(_ip_address, ip_address ? ip_address : "", sizeof(_ip_address)); strncpy(_netmask, netmask ? netmask : "", sizeof(_netmask)); strncpy(_gateway, gateway ? gateway : "", sizeof(_gateway)); return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::set_dhcp(bool dhcp) { _dhcp = dhcp; return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::init() { emac_interface_t *emac; int ret; //printf("\r\nInitializing emac ...\r\n"); emac = wlan_emac_init_interface(); if (!emac) { return NSAPI_ERROR_DEVICE_ERROR; } emac->ops.power_up(emac); //printf("Initializing lwip ...\r\n"); ret = mbed_lwip_init(emac); if (ret != 0) { return ret; } xnetif[0] = netif_default; return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::deinit() { return mbed_lwip_bringdown(); } /* * we may call connect multiple times */ nsapi_error_t RTWInterface::set_credentials(const char *ssid, const char *pass, nsapi_security_t security) { strncpy(_ssid, ssid, 255); strncpy(_pass, pass, 255); _security = security; return NSAPI_ERROR_OK; } nsapi_error_t RTWInterface::connect() { int ret; rtw_security_t sec; if (!_ssid || (!_pass && _security != NSAPI_SECURITY_NONE)) { printf("Invalid credentials\r\n"); return NSAPI_ERROR_PARAMETER; } switch (_security) { case NSAPI_SECURITY_WPA2: sec = RTW_SECURITY_WPA2_MIXED_PSK; break; case NSAPI_SECURITY_NONE: default: sec = RTW_SECURITY_OPEN; break; } printf("Connecting to: %s ... \r\n", _ssid); ret = wifi_connect(_ssid, sec, _pass, strlen(_ssid), strlen(_pass), 0, (void *)NULL); if (ret != RTW_SUCCESS) { printf("failed: %d\r\n", ret); return NSAPI_ERROR_NO_CONNECTION; } //printf("connected\r\n"); wlan_emac_link_up(0); return mbed_lwip_bringup(_dhcp, _ip_address[0] ? _ip_address : 0, _netmask[0] ? _netmask : 0, _gateway[0] ? _gateway : 0); } static rtw_result_t scan_result_handler( rtw_scan_handler_result_t* malloced_scan_result ) { if (malloced_scan_result->scan_complete != RTW_TRUE) { rtw_scan_result_t* record = &malloced_scan_result->ap_details; record->SSID.val[record->SSID.len] = 0; /* Ensure the SSID is null terminated */ if(ApNum>maxApNum) return RTW_SUCCESS; nsapi_wifi_ap_t ap; memset((void*)&ap, 0x00, sizeof(nsapi_wifi_ap_t)); memcpy(ap.ssid, record->SSID.val, record->SSID.len); memcpy(ap.bssid, record->BSSID.octet, 6); ap.security = (record->security == RTW_SECURITY_OPEN)?NSAPI_SECURITY_NONE : (record->security == RTW_SECURITY_WEP_PSK)?NSAPI_SECURITY_WEP: (record->security == RTW_SECURITY_WPA_TKIP_PSK || record->security == RTW_SECURITY_WPA_AES_PSK)? NSAPI_SECURITY_WPA: (record->security == RTW_SECURITY_WPA2_AES_PSK || \ record->security == RTW_SECURITY_WPA2_TKIP_PSK || \ record->security == RTW_SECURITY_WPA2_MIXED_PSK)?NSAPI_SECURITY_WPA2: (record->security == RTW_SECURITY_WPA_WPA2_MIXED)?NSAPI_SECURITY_WPA_WPA2:NSAPI_SECURITY_UNKNOWN; ap.rssi = record->signal_strength; ap.channel = record->channel; SCANED_AP[ApNum++] = new WiFiAccessPoint(ap); } else{ // scan done rtw_up_sema(&scan_sema); } return RTW_SUCCESS; } nsapi_error_t RTWInterface::scan(WiFiAccessPoint *res, unsigned count) { // blocked if(count == 0){ ApNum = 0; rtw_init_sema(&scan_sema, 0); if(wifi_scan_networks(scan_result_handler, NULL) != RTW_SUCCESS){ printf("wifi scan failed\n\r"); //return NSAPI_ERROR_DEVICE_ERROR; goto error; } if(rtw_down_timeout_sema( &scan_sema, 15000 ) == RTW_FALSE) { printf("wifi scan timeout\r\n"); //return NSAPI_ERROR_DEVICE_ERROR; goto error; } rtw_free_sema(&scan_sema); return ApNum; }else if(count > 0 && res != NULL){ count = count < maxApNum ? count : maxApNum; for(int i = 0; i < count; i++){ memcpy(&res[i], SCANED_AP[i], sizeof(WiFiAccessPoint)); delete[] SCANED_AP[i]; } return (signed int)count; } return NSAPI_ERROR_OK; error: rtw_free_sema(&scan_sema); return NSAPI_ERROR_DEVICE_ERROR; } nsapi_error_t RTWInterface::set_channel(uint8_t channel) { if(wifi_set_channel(channel) == 0) return NSAPI_ERROR_OK; return NSAPI_ERROR_DEVICE_ERROR; } int8_t RTWInterface::get_rssi() { return NSAPI_ERROR_UNSUPPORTED; } nsapi_error_t RTWInterface::connect(const char *ssid, const char *pass, nsapi_security_t security, uint8_t channel) { set_credentials(ssid, pass, security); return connect(); } nsapi_error_t RTWInterface::disconnect() { char essid[33]; if(wifi_is_connected_to_ap() != RTW_SUCCESS) return NSAPI_ERROR_NO_CONNECTION; printf("Deassociating AP ...\r\n"); if(wifi_disconnect()<0){ return NSAPI_ERROR_DEVICE_ERROR; } while(1){ if(wext_get_ssid(WLAN0_NAME, (unsigned char *) essid) < 0) { printf("WIFI disconnected\n\r"); break; } } return NSAPI_ERROR_OK; } int RTWInterface::is_connected() { // wifi_is_connected_to_ap return 0 on connected return !wifi_is_connected_to_ap(); } const char *RTWInterface::get_mac_address() { return mbed_lwip_get_mac_address(); } const char *RTWInterface::get_ip_address() { if (mbed_lwip_get_ip_address(_ip_address, sizeof _ip_address)) { return _ip_address; } return 0; } const char *RTWInterface::get_netmask() { if (mbed_lwip_get_netmask(_netmask, sizeof _netmask)) { return _netmask; } return 0; } const char *RTWInterface::get_gateway() { if (mbed_lwip_get_gateway(_gateway, sizeof _gateway)) { return _gateway; } return 0; } NetworkStack *RTWInterface::get_stack() { return nsapi_create_stack(&lwip_stack); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/browser.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/extensions/extension_error_reporter.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_details.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/net_util.h" class RenderViewHostManagerTest : public InProcessBrowserTest { public: RenderViewHostManagerTest() { EnableDOMAutomation(); } }; // Test for crbug.com/24447. Following a cross-site link with rel=noreferrer // and target=_blank should create a new SiteInstance. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, SwapProcessWithRelNoreferrerAndTargetBlank) { // Start two servers with different sites. const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> http_server = HTTPTestServer::CreateServer(kDocRoot, NULL); scoped_refptr<HTTPSTestServer> https_server = HTTPSTestServer::CreateGoodServer(kDocRoot); // Load a page with links that open in a new window. ui_test_utils::NavigateToURL(browser(), http_server->TestServerPage( "files/click-noreferrer-links.html")); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance != NULL); // Test clicking a rel=noreferrer + target=blank link. bool success = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(clickNoRefTargetBlankLink());", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition to finish. ui_test_utils::WaitForLoadStop( &(browser()->GetSelectedTabContents()->controller())); // Opens in new tab. EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(1, browser()->selected_index()); EXPECT_EQ(L"Title Of Awesomeness", browser()->GetSelectedTabContents()->GetTitle()); // Should have a new SiteInstance. scoped_refptr<SiteInstance> noref_blank_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, noref_blank_site_instance); } // Test for crbug.com/24447. Following a cross-site link with just // target=_blank should not create a new SiteInstance. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, DontSwapProcessWithOnlyTargetBlank) { // Start two servers with different sites. const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> http_server = HTTPTestServer::CreateServer(kDocRoot, NULL); scoped_refptr<HTTPSTestServer> https_server = HTTPSTestServer::CreateGoodServer(kDocRoot); // Load a page with links that open in a new window. ui_test_utils::NavigateToURL(browser(), http_server->TestServerPage( "files/click-noreferrer-links.html")); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance != NULL); // Test clicking a target=blank link. bool success = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(clickTargetBlankLink());", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition to finish. ui_test_utils::WaitForLoadStop( &(browser()->GetSelectedTabContents()->controller())); // Opens in new tab. EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(1, browser()->selected_index()); EXPECT_EQ(L"Title Of Awesomeness", browser()->GetSelectedTabContents()->GetTitle()); // Should have the same SiteInstance. scoped_refptr<SiteInstance> blank_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, blank_site_instance); } // Test for crbug.com/24447. Following a cross-site link with rel=noreferrer // and no target=_blank should not create a new SiteInstance. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, DontSwapProcessWithOnlyRelNoreferrer) { // Start two servers with different sites. const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> http_server = HTTPTestServer::CreateServer(kDocRoot, NULL); scoped_refptr<HTTPSTestServer> https_server = HTTPSTestServer::CreateGoodServer(kDocRoot); // Load a page with links that open in a new window. ui_test_utils::NavigateToURL(browser(), http_server->TestServerPage( "files/click-noreferrer-links.html")); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance != NULL); // Test clicking a rel=noreferrer link. bool success = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(clickNoRefLink());", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition to finish. ui_test_utils::WaitForLoadStop( &(browser()->GetSelectedTabContents()->controller())); // Opens in same tab. EXPECT_EQ(1, browser()->tab_count()); EXPECT_EQ(0, browser()->selected_index()); EXPECT_EQ(L"Title Of Awesomeness", browser()->GetSelectedTabContents()->GetTitle()); // Should have the same SiteInstance. scoped_refptr<SiteInstance> noref_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, noref_site_instance); } // Test for crbug.com/14505. This tests that chrome:// urls are still functional // after download of a file while viewing another chrome://. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, ChromeURLAfterDownload) { GURL downloads_url("chrome://downloads"); GURL extensions_url("chrome://extensions"); FilePath zip_download; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download)); zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip"); GURL zip_url = net::FilePathToFileURL(zip_download); ui_test_utils::NavigateToURL(browser(), downloads_url); ui_test_utils::NavigateToURL(browser(), zip_url); ui_test_utils::WaitForDownloadCount( browser()->profile()->GetDownloadManager(), 1); ui_test_utils::NavigateToURL(browser(), extensions_url); TabContents *contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(contents); bool domui_responded = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( contents->render_view_host(), L"", L"window.domAutomationController.send(window.domui_responded_);", &domui_responded)); EXPECT_TRUE(domui_responded); } class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } // NotificationObserver virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::BROWSER_CLOSED: MessageLoopForUI::current()->Quit(); break; } } private: NotificationRegistrar registrar_; }; // Test for crbug.com/12745. This tests that if a download is initiated from // a chrome:// page that has registered and onunload handler, the browser // will be able to close. // TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix // must be found before this can be re-enabled. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, DISABLED_BrowserCloseAfterDownload) { GURL downloads_url("chrome://downloads"); FilePath zip_download; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download)); zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip"); ASSERT_TRUE(file_util::PathExists(zip_download)); GURL zip_url = net::FilePathToFileURL(zip_download); ui_test_utils::NavigateToURL(browser(), downloads_url); TabContents *contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(contents); bool result = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( contents->render_view_host(), L"", L"window.onunload = function() { var do_nothing = 0; }; " L"window.domAutomationController.send(true);", &result)); EXPECT_TRUE(result); ui_test_utils::NavigateToURL(browser(), zip_url); ui_test_utils::WaitForDownloadCount( browser()->profile()->GetDownloadManager(), 1); browser()->CloseWindow(); BrowserClosedObserver wait_for_close(browser()); } <commit_msg>Disable RenderViewHostManagerTest.ChromeURLAfterDownload because it hangs flakily in Windows.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/browser.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/extensions/extension_error_reporter.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_details.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/net_util.h" class RenderViewHostManagerTest : public InProcessBrowserTest { public: RenderViewHostManagerTest() { EnableDOMAutomation(); } }; // Test for crbug.com/24447. Following a cross-site link with rel=noreferrer // and target=_blank should create a new SiteInstance. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, SwapProcessWithRelNoreferrerAndTargetBlank) { // Start two servers with different sites. const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> http_server = HTTPTestServer::CreateServer(kDocRoot, NULL); scoped_refptr<HTTPSTestServer> https_server = HTTPSTestServer::CreateGoodServer(kDocRoot); // Load a page with links that open in a new window. ui_test_utils::NavigateToURL(browser(), http_server->TestServerPage( "files/click-noreferrer-links.html")); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance != NULL); // Test clicking a rel=noreferrer + target=blank link. bool success = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(clickNoRefTargetBlankLink());", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition to finish. ui_test_utils::WaitForLoadStop( &(browser()->GetSelectedTabContents()->controller())); // Opens in new tab. EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(1, browser()->selected_index()); EXPECT_EQ(L"Title Of Awesomeness", browser()->GetSelectedTabContents()->GetTitle()); // Should have a new SiteInstance. scoped_refptr<SiteInstance> noref_blank_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_NE(orig_site_instance, noref_blank_site_instance); } // Test for crbug.com/24447. Following a cross-site link with just // target=_blank should not create a new SiteInstance. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, DontSwapProcessWithOnlyTargetBlank) { // Start two servers with different sites. const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> http_server = HTTPTestServer::CreateServer(kDocRoot, NULL); scoped_refptr<HTTPSTestServer> https_server = HTTPSTestServer::CreateGoodServer(kDocRoot); // Load a page with links that open in a new window. ui_test_utils::NavigateToURL(browser(), http_server->TestServerPage( "files/click-noreferrer-links.html")); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance != NULL); // Test clicking a target=blank link. bool success = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(clickTargetBlankLink());", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition to finish. ui_test_utils::WaitForLoadStop( &(browser()->GetSelectedTabContents()->controller())); // Opens in new tab. EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(1, browser()->selected_index()); EXPECT_EQ(L"Title Of Awesomeness", browser()->GetSelectedTabContents()->GetTitle()); // Should have the same SiteInstance. scoped_refptr<SiteInstance> blank_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, blank_site_instance); } // Test for crbug.com/24447. Following a cross-site link with rel=noreferrer // and no target=_blank should not create a new SiteInstance. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, DontSwapProcessWithOnlyRelNoreferrer) { // Start two servers with different sites. const wchar_t kDocRoot[] = L"chrome/test/data"; scoped_refptr<HTTPTestServer> http_server = HTTPTestServer::CreateServer(kDocRoot, NULL); scoped_refptr<HTTPSTestServer> https_server = HTTPSTestServer::CreateGoodServer(kDocRoot); // Load a page with links that open in a new window. ui_test_utils::NavigateToURL(browser(), http_server->TestServerPage( "files/click-noreferrer-links.html")); // Get the original SiteInstance for later comparison. scoped_refptr<SiteInstance> orig_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_TRUE(orig_site_instance != NULL); // Test clicking a rel=noreferrer link. bool success = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(clickNoRefLink());", &success)); EXPECT_TRUE(success); // Wait for the cross-site transition to finish. ui_test_utils::WaitForLoadStop( &(browser()->GetSelectedTabContents()->controller())); // Opens in same tab. EXPECT_EQ(1, browser()->tab_count()); EXPECT_EQ(0, browser()->selected_index()); EXPECT_EQ(L"Title Of Awesomeness", browser()->GetSelectedTabContents()->GetTitle()); // Should have the same SiteInstance. scoped_refptr<SiteInstance> noref_site_instance( browser()->GetSelectedTabContents()->GetSiteInstance()); EXPECT_EQ(orig_site_instance, noref_site_instance); } // Hangs flakily in Win, http://crbug.com/45040. #if defined(OS_WIN) #define MAYBE_ChromeURLAfterDownload DISABLED_ChromeURLAfterDownload #else #defne MAYBE_ChromeURLAfterDownload ChromeURLAfterDownload #endif // defined(OS_WIN) // Test for crbug.com/14505. This tests that chrome:// urls are still functional // after download of a file while viewing another chrome://. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, MAYBE_ChromeURLAfterDownload) { GURL downloads_url("chrome://downloads"); GURL extensions_url("chrome://extensions"); FilePath zip_download; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download)); zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip"); GURL zip_url = net::FilePathToFileURL(zip_download); ui_test_utils::NavigateToURL(browser(), downloads_url); ui_test_utils::NavigateToURL(browser(), zip_url); ui_test_utils::WaitForDownloadCount( browser()->profile()->GetDownloadManager(), 1); ui_test_utils::NavigateToURL(browser(), extensions_url); TabContents *contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(contents); bool domui_responded = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( contents->render_view_host(), L"", L"window.domAutomationController.send(window.domui_responded_);", &domui_responded)); EXPECT_TRUE(domui_responded); } class BrowserClosedObserver : public NotificationObserver { public: explicit BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } // NotificationObserver virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::BROWSER_CLOSED: MessageLoopForUI::current()->Quit(); break; } } private: NotificationRegistrar registrar_; }; // Test for crbug.com/12745. This tests that if a download is initiated from // a chrome:// page that has registered and onunload handler, the browser // will be able to close. // TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix // must be found before this can be re-enabled. IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, DISABLED_BrowserCloseAfterDownload) { GURL downloads_url("chrome://downloads"); FilePath zip_download; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download)); zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip"); ASSERT_TRUE(file_util::PathExists(zip_download)); GURL zip_url = net::FilePathToFileURL(zip_download); ui_test_utils::NavigateToURL(browser(), downloads_url); TabContents *contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(contents); bool result = false; EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( contents->render_view_host(), L"", L"window.onunload = function() { var do_nothing = 0; }; " L"window.domAutomationController.send(true);", &result)); EXPECT_TRUE(result); ui_test_utils::NavigateToURL(browser(), zip_url); ui_test_utils::WaitForDownloadCount( browser()->profile()->GetDownloadManager(), 1); browser()->CloseWindow(); BrowserClosedObserver wait_for_close(browser()); } <|endoftext|>
<commit_before>/* Copyright 2015 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. ==============================================================================*/ // See docs in ../ops/array_ops.cc. #define EIGEN_USE_THREADS #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM #define EIGEN_USE_GPU #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM #include "tensorflow/core/kernels/linalg/matrix_set_diag_op.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #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_shape.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/linalg/matrix_diag_op.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; template <typename Device, typename T> class MatrixSetDiagOp : public OpKernel { public: explicit MatrixSetDiagOp(OpKernelConstruction* context) : OpKernel(context) { // MatrixSetDiagV3-specific. if (context->HasAttr("align")) { functor::ReadAlignment(context, &left_align_superdiagonal_, &left_align_subdiagonal_); } } void Compute(OpKernelContext* context) override { const Tensor& input = context->input(0); const Tensor& diag = context->input(1); // MatrixSetDiag and MatrixSetDiagV2 both use this OpKernel. MatrixSetDiag // only has two inputs, so we have to check the number of inputs before // reading additional parameters in MatrixSetDiagV2. int32_t lower_diag_index = 0; int32_t upper_diag_index = 0; // MatrixSetDiagV2-specific. if (context->num_inputs() > kNumV1Inputs) { auto& diag_index = context->input(2); OP_REQUIRES(context, TensorShapeUtils::IsScalar(diag_index.shape()) || TensorShapeUtils::IsVector(diag_index.shape()), errors::InvalidArgument( "diag_index must be a scalar or vector, received shape: ", diag_index.shape().DebugString())); lower_diag_index = diag_index.flat<int32>()(0); upper_diag_index = lower_diag_index; if (TensorShapeUtils::IsVector(diag_index.shape())) { auto diag_index_size = diag_index.dim_size(0); OP_REQUIRES( context, 0 < diag_index_size && diag_index_size <= 2, errors::InvalidArgument( "diag_index must have only one or two elements, received ", diag_index_size, " elements.")); if (diag_index_size > 1) { upper_diag_index = diag_index.flat<int32>()(1); } } } const TensorShape& input_shape = input.shape(); const TensorShape& diag_shape = diag.shape(); const int input_rank = input_shape.dims(); // Preliminary validation of sizes. OP_REQUIRES(context, TensorShapeUtils::IsMatrixOrHigher(input_shape), errors::InvalidArgument( "input must be at least 2-dim, received shape: ", input.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVectorOrHigher(diag_shape), errors::InvalidArgument( "diagonal must be at least 1-dim, received shape: ", diag_shape.DebugString())); // Make sure lower_diag_index and upper_diag_index is valid. const Eigen::Index num_rows = input_shape.dim_size(input_rank - 2); const Eigen::Index num_cols = input_shape.dim_size(input_rank - 1); OP_REQUIRES( // Checks lower_diag_index == 0 for when matrix shape = 0. context, (-num_rows < lower_diag_index && lower_diag_index < num_cols) || lower_diag_index == 0, errors::InvalidArgument( "lower_diag_index is out of bound: ", lower_diag_index, " It must be between ", -num_rows, " and ", num_cols)); OP_REQUIRES(context, (-num_rows < upper_diag_index && upper_diag_index < num_cols) || upper_diag_index == 0, errors::InvalidArgument( "upper_diag_index is out of bound: ", upper_diag_index, " It must be between ", -num_rows, " and ", num_cols)); OP_REQUIRES( context, lower_diag_index <= upper_diag_index, errors::InvalidArgument( "lower_diag_index must not be larger than upper_diag_index: ", lower_diag_index, " > ", upper_diag_index)); // Check if diag size is consistent with input. const Eigen::Index num_diags = upper_diag_index - lower_diag_index + 1; OP_REQUIRES( context, lower_diag_index == upper_diag_index || (diag_shape.dim_size(input_rank - 2) == num_diags), errors::InvalidArgument("The number of diagonals provided in `diag` " "is not consistent with `lower_diag_index` and " "`upper_diag_index`")); TensorShape expected_diag_shape = input_shape; expected_diag_shape.RemoveLastDims(2); if (num_diags > 1) expected_diag_shape.AddDim(num_diags); const int32_t max_diag_len = std::min(num_rows + std::min(upper_diag_index, 0), num_cols - std::max(lower_diag_index, 0)); expected_diag_shape.AddDim(max_diag_len); OP_REQUIRES( context, expected_diag_shape == diag_shape, errors::InvalidArgument( "Either first dimensions of diagonal don't match input.shape[:-2], " "or diagonal.shape[:-1] is not equal to the longests diagonal in " "range [lower_diag_index:upper_diag_index].\nInput shape: ", input_shape.DebugString(), "\nDiagonal shape: ", diag_shape.DebugString(), "\nExpected diagonal shape: ", expected_diag_shape.DebugString())); if (input.NumElements() == 0) { // This is a no-op. context->set_output(0, input); return; } auto input_reshaped = input.flat_inner_dims<T, 3>(); auto diag_reshaped = diag.flat<T>(); Tensor* output = nullptr; OP_REQUIRES_OK(context, context->forward_input_or_allocate_output( {0}, 0, input_shape, &output)); auto output_reshaped = output->flat_inner_dims<T, 3>(); functor::MatrixSetDiag<Device, T>::Compute( context, context->eigen_device<Device>(), input_reshaped, diag_reshaped, output_reshaped, lower_diag_index, upper_diag_index, max_diag_len, left_align_superdiagonal_, left_align_subdiagonal_); } private: bool left_align_superdiagonal_ = true; bool left_align_subdiagonal_ = true; static constexpr int kNumV1Inputs = 2; TF_DISALLOW_COPY_AND_ASSIGN(MatrixSetDiagOp); }; #define REGISTER_MATRIX_SET_DIAG(type) \ REGISTER_KERNEL_BUILDER( \ Name("MatrixSetDiag").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ MatrixSetDiagOp<CPUDevice, type>); \ REGISTER_KERNEL_BUILDER( \ Name("MatrixSetDiagV2").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ MatrixSetDiagOp<CPUDevice, type>); \ REGISTER_KERNEL_BUILDER( \ Name("MatrixSetDiagV3").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ MatrixSetDiagOp<CPUDevice, type>); TF_CALL_POD_TYPES(REGISTER_MATRIX_SET_DIAG); #undef REGISTER_MATRIX_SET_DIAG // Registration of the deprecated kernel. // Delete after 10mar2017. #define REGISTER_BATCH_MATRIX_SET_DIAG(type) \ REGISTER_KERNEL_BUILDER( \ Name("BatchMatrixSetDiag").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ MatrixSetDiagOp<CPUDevice, type>); TF_CALL_POD_TYPES(REGISTER_BATCH_MATRIX_SET_DIAG); #undef REGISTER_BATCH_MATRIX_SET_DIAG namespace functor { // Implementation of the functor specialization for CPU. template <typename T> struct MatrixSetDiag<CPUDevice, T> { static void Compute(OpKernelContext* context, const CPUDevice& device, typename TTypes<T, 3>::ConstTensor& input, typename TTypes<T>::ConstTensor& diag, typename TTypes<T, 3>::Tensor& output, const Eigen::Index lower_diag_index, const Eigen::Index upper_diag_index, const Eigen::Index max_diag_len, const bool left_align_superdiagonal, const bool left_align_subdiagonal) { if (input.data() != output.data()) { output.device(device) = input; } const Eigen::Index num_diags = upper_diag_index - lower_diag_index + 1; auto compute_shard = [&output, &diag, &upper_diag_index, &max_diag_len, &num_diags, &left_align_superdiagonal, &left_align_subdiagonal](Eigen::Index begin, Eigen::Index end) { const Eigen::Index num_rows = output.dimension(1); const Eigen::Index num_cols = output.dimension(2); Eigen::Index diag_base_index = begin * num_diags * max_diag_len; for (Eigen::Index batch = begin; batch < end; ++batch) { for (Eigen::Index m = 0; m < num_diags; ++m) { const Eigen::Index diag_index = upper_diag_index - m; int diag_len, content_offset; std::tie(diag_len, content_offset) = ComputeDiagLenAndContentOffset( diag_index, max_diag_len, num_rows, num_cols, left_align_superdiagonal, left_align_subdiagonal); // Make two separate cases to save some index calculations. if (diag_index >= 0) { for (Eigen::Index n = 0; n < diag_len; ++n) { output(batch, n, n + diag_index) = diag(diag_base_index + n + content_offset); } } else { for (Eigen::Index n = 0; n < diag_len; ++n) { output(batch, n - diag_index, n) = diag(diag_base_index + n + content_offset); } } diag_base_index += max_diag_len; } } }; auto thread_pool = context->device()->tensorflow_cpu_worker_threads()->workers; // TODO(penporn): Tune for the best constant in cost_per_batch. const Eigen::Index cost_per_batch = 10 * num_diags * max_diag_len; thread_pool->ParallelFor(output.dimension(0), cost_per_batch, std::move(compute_shard)); } }; } // namespace functor #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T) \ template <> \ void MatrixSetDiag<GPUDevice, T>::Compute( \ OpKernelContext* context, const GPUDevice& device, \ typename TTypes<T, 3>::ConstTensor& input, \ typename TTypes<T>::ConstTensor& diag, \ typename TTypes<T, 3>::Tensor& output, \ const Eigen::Index lower_diag_index, \ const Eigen::Index upper_diag_index, const Eigen::Index max_diag_len, \ const bool left_align_superdiagonal, const bool left_align_subdiagonal); \ extern template struct MatrixSetDiag<GPUDevice, T>; TF_CALL_GPU_ALL_TYPES(DECLARE_GPU_SPEC); } // namespace functor // Registration of the GPU implementations. #define REGISTER_MATRIX_SET_DIAG_GPU(type) \ REGISTER_KERNEL_BUILDER( \ Name("MatrixSetDiag").Device(DEVICE_GPU).TypeConstraint<type>("T"), \ MatrixSetDiagOp<GPUDevice, type>); \ REGISTER_KERNEL_BUILDER(Name("MatrixSetDiagV2") \ .Device(DEVICE_GPU) \ .TypeConstraint<type>("T") \ .HostMemory("k"), \ MatrixSetDiagOp<GPUDevice, type>); \ REGISTER_KERNEL_BUILDER(Name("MatrixSetDiagV3") \ .Device(DEVICE_GPU) \ .TypeConstraint<type>("T") \ .HostMemory("k"), \ MatrixSetDiagOp<GPUDevice, type>); TF_CALL_GPU_ALL_TYPES(REGISTER_MATRIX_SET_DIAG_GPU); #undef REGISTER_MATRIX_SET_DIAG_GPU // Registration of the deprecated kernel. // Delete after 10mar2017. #define REGISTER_BATCH_MATRIX_SET_DIAG_GPU(type) \ REGISTER_KERNEL_BUILDER( \ Name("BatchMatrixSetDiag").Device(DEVICE_GPU).TypeConstraint<type>("T"), \ MatrixSetDiagOp<GPUDevice, type>); TF_CALL_GPU_NUMBER_TYPES(REGISTER_BATCH_MATRIX_SET_DIAG_GPU); #undef REGISTER_BATCH_MATRIX_SET_DIAG_GPU #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM } // namespace tensorflow <commit_msg>Add one missing valdiation to `matrix_set_diag_op.cc`<commit_after>/* Copyright 2015 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. ==============================================================================*/ // See docs in ../ops/array_ops.cc. #define EIGEN_USE_THREADS #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM #define EIGEN_USE_GPU #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM #include "tensorflow/core/kernels/linalg/matrix_set_diag_op.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #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_shape.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/linalg/matrix_diag_op.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; template <typename Device, typename T> class MatrixSetDiagOp : public OpKernel { public: explicit MatrixSetDiagOp(OpKernelConstruction* context) : OpKernel(context) { // MatrixSetDiagV3-specific. if (context->HasAttr("align")) { functor::ReadAlignment(context, &left_align_superdiagonal_, &left_align_subdiagonal_); } } void Compute(OpKernelContext* context) override { const Tensor& input = context->input(0); const Tensor& diag = context->input(1); // MatrixSetDiag and MatrixSetDiagV2 both use this OpKernel. MatrixSetDiag // only has two inputs, so we have to check the number of inputs before // reading additional parameters in MatrixSetDiagV2. int32_t lower_diag_index = 0; int32_t upper_diag_index = 0; // MatrixSetDiagV2-specific. if (context->num_inputs() > kNumV1Inputs) { auto& diag_index = context->input(2); OP_REQUIRES(context, TensorShapeUtils::IsScalar(diag_index.shape()) || TensorShapeUtils::IsVector(diag_index.shape()), errors::InvalidArgument( "diag_index must be a scalar or vector, received shape: ", diag_index.shape().DebugString())); OP_REQUIRES( context, diag_index.NumElements() > 0, errors::InvalidArgument("diag_index must have at least one element")); lower_diag_index = diag_index.flat<int32>()(0); upper_diag_index = lower_diag_index; if (TensorShapeUtils::IsVector(diag_index.shape())) { auto diag_index_size = diag_index.dim_size(0); OP_REQUIRES( context, 0 < diag_index_size && diag_index_size <= 2, errors::InvalidArgument( "diag_index must have only one or two elements, received ", diag_index_size, " elements.")); if (diag_index_size > 1) { upper_diag_index = diag_index.flat<int32>()(1); } } } const TensorShape& input_shape = input.shape(); const TensorShape& diag_shape = diag.shape(); const int input_rank = input_shape.dims(); // Preliminary validation of sizes. OP_REQUIRES(context, TensorShapeUtils::IsMatrixOrHigher(input_shape), errors::InvalidArgument( "input must be at least 2-dim, received shape: ", input.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVectorOrHigher(diag_shape), errors::InvalidArgument( "diagonal must be at least 1-dim, received shape: ", diag_shape.DebugString())); // Make sure lower_diag_index and upper_diag_index is valid. const Eigen::Index num_rows = input_shape.dim_size(input_rank - 2); const Eigen::Index num_cols = input_shape.dim_size(input_rank - 1); OP_REQUIRES( // Checks lower_diag_index == 0 for when matrix shape = 0. context, (-num_rows < lower_diag_index && lower_diag_index < num_cols) || lower_diag_index == 0, errors::InvalidArgument( "lower_diag_index is out of bound: ", lower_diag_index, " It must be between ", -num_rows, " and ", num_cols)); OP_REQUIRES(context, (-num_rows < upper_diag_index && upper_diag_index < num_cols) || upper_diag_index == 0, errors::InvalidArgument( "upper_diag_index is out of bound: ", upper_diag_index, " It must be between ", -num_rows, " and ", num_cols)); OP_REQUIRES( context, lower_diag_index <= upper_diag_index, errors::InvalidArgument( "lower_diag_index must not be larger than upper_diag_index: ", lower_diag_index, " > ", upper_diag_index)); // Check if diag size is consistent with input. const Eigen::Index num_diags = upper_diag_index - lower_diag_index + 1; OP_REQUIRES( context, lower_diag_index == upper_diag_index || (diag_shape.dim_size(input_rank - 2) == num_diags), errors::InvalidArgument("The number of diagonals provided in `diag` " "is not consistent with `lower_diag_index` and " "`upper_diag_index`")); TensorShape expected_diag_shape = input_shape; expected_diag_shape.RemoveLastDims(2); if (num_diags > 1) expected_diag_shape.AddDim(num_diags); const int32_t max_diag_len = std::min(num_rows + std::min(upper_diag_index, 0), num_cols - std::max(lower_diag_index, 0)); expected_diag_shape.AddDim(max_diag_len); OP_REQUIRES( context, expected_diag_shape == diag_shape, errors::InvalidArgument( "Either first dimensions of diagonal don't match input.shape[:-2], " "or diagonal.shape[:-1] is not equal to the longests diagonal in " "range [lower_diag_index:upper_diag_index].\nInput shape: ", input_shape.DebugString(), "\nDiagonal shape: ", diag_shape.DebugString(), "\nExpected diagonal shape: ", expected_diag_shape.DebugString())); if (input.NumElements() == 0) { // This is a no-op. context->set_output(0, input); return; } auto input_reshaped = input.flat_inner_dims<T, 3>(); auto diag_reshaped = diag.flat<T>(); Tensor* output = nullptr; OP_REQUIRES_OK(context, context->forward_input_or_allocate_output( {0}, 0, input_shape, &output)); auto output_reshaped = output->flat_inner_dims<T, 3>(); functor::MatrixSetDiag<Device, T>::Compute( context, context->eigen_device<Device>(), input_reshaped, diag_reshaped, output_reshaped, lower_diag_index, upper_diag_index, max_diag_len, left_align_superdiagonal_, left_align_subdiagonal_); } private: bool left_align_superdiagonal_ = true; bool left_align_subdiagonal_ = true; static constexpr int kNumV1Inputs = 2; TF_DISALLOW_COPY_AND_ASSIGN(MatrixSetDiagOp); }; #define REGISTER_MATRIX_SET_DIAG(type) \ REGISTER_KERNEL_BUILDER( \ Name("MatrixSetDiag").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ MatrixSetDiagOp<CPUDevice, type>); \ REGISTER_KERNEL_BUILDER( \ Name("MatrixSetDiagV2").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ MatrixSetDiagOp<CPUDevice, type>); \ REGISTER_KERNEL_BUILDER( \ Name("MatrixSetDiagV3").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ MatrixSetDiagOp<CPUDevice, type>); TF_CALL_POD_TYPES(REGISTER_MATRIX_SET_DIAG); #undef REGISTER_MATRIX_SET_DIAG // Registration of the deprecated kernel. // Delete after 10mar2017. #define REGISTER_BATCH_MATRIX_SET_DIAG(type) \ REGISTER_KERNEL_BUILDER( \ Name("BatchMatrixSetDiag").Device(DEVICE_CPU).TypeConstraint<type>("T"), \ MatrixSetDiagOp<CPUDevice, type>); TF_CALL_POD_TYPES(REGISTER_BATCH_MATRIX_SET_DIAG); #undef REGISTER_BATCH_MATRIX_SET_DIAG namespace functor { // Implementation of the functor specialization for CPU. template <typename T> struct MatrixSetDiag<CPUDevice, T> { static void Compute(OpKernelContext* context, const CPUDevice& device, typename TTypes<T, 3>::ConstTensor& input, typename TTypes<T>::ConstTensor& diag, typename TTypes<T, 3>::Tensor& output, const Eigen::Index lower_diag_index, const Eigen::Index upper_diag_index, const Eigen::Index max_diag_len, const bool left_align_superdiagonal, const bool left_align_subdiagonal) { if (input.data() != output.data()) { output.device(device) = input; } const Eigen::Index num_diags = upper_diag_index - lower_diag_index + 1; auto compute_shard = [&output, &diag, &upper_diag_index, &max_diag_len, &num_diags, &left_align_superdiagonal, &left_align_subdiagonal](Eigen::Index begin, Eigen::Index end) { const Eigen::Index num_rows = output.dimension(1); const Eigen::Index num_cols = output.dimension(2); Eigen::Index diag_base_index = begin * num_diags * max_diag_len; for (Eigen::Index batch = begin; batch < end; ++batch) { for (Eigen::Index m = 0; m < num_diags; ++m) { const Eigen::Index diag_index = upper_diag_index - m; int diag_len, content_offset; std::tie(diag_len, content_offset) = ComputeDiagLenAndContentOffset( diag_index, max_diag_len, num_rows, num_cols, left_align_superdiagonal, left_align_subdiagonal); // Make two separate cases to save some index calculations. if (diag_index >= 0) { for (Eigen::Index n = 0; n < diag_len; ++n) { output(batch, n, n + diag_index) = diag(diag_base_index + n + content_offset); } } else { for (Eigen::Index n = 0; n < diag_len; ++n) { output(batch, n - diag_index, n) = diag(diag_base_index + n + content_offset); } } diag_base_index += max_diag_len; } } }; auto thread_pool = context->device()->tensorflow_cpu_worker_threads()->workers; // TODO(penporn): Tune for the best constant in cost_per_batch. const Eigen::Index cost_per_batch = 10 * num_diags * max_diag_len; thread_pool->ParallelFor(output.dimension(0), cost_per_batch, std::move(compute_shard)); } }; } // namespace functor #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T) \ template <> \ void MatrixSetDiag<GPUDevice, T>::Compute( \ OpKernelContext* context, const GPUDevice& device, \ typename TTypes<T, 3>::ConstTensor& input, \ typename TTypes<T>::ConstTensor& diag, \ typename TTypes<T, 3>::Tensor& output, \ const Eigen::Index lower_diag_index, \ const Eigen::Index upper_diag_index, const Eigen::Index max_diag_len, \ const bool left_align_superdiagonal, const bool left_align_subdiagonal); \ extern template struct MatrixSetDiag<GPUDevice, T>; TF_CALL_GPU_ALL_TYPES(DECLARE_GPU_SPEC); } // namespace functor // Registration of the GPU implementations. #define REGISTER_MATRIX_SET_DIAG_GPU(type) \ REGISTER_KERNEL_BUILDER( \ Name("MatrixSetDiag").Device(DEVICE_GPU).TypeConstraint<type>("T"), \ MatrixSetDiagOp<GPUDevice, type>); \ REGISTER_KERNEL_BUILDER(Name("MatrixSetDiagV2") \ .Device(DEVICE_GPU) \ .TypeConstraint<type>("T") \ .HostMemory("k"), \ MatrixSetDiagOp<GPUDevice, type>); \ REGISTER_KERNEL_BUILDER(Name("MatrixSetDiagV3") \ .Device(DEVICE_GPU) \ .TypeConstraint<type>("T") \ .HostMemory("k"), \ MatrixSetDiagOp<GPUDevice, type>); TF_CALL_GPU_ALL_TYPES(REGISTER_MATRIX_SET_DIAG_GPU); #undef REGISTER_MATRIX_SET_DIAG_GPU // Registration of the deprecated kernel. // Delete after 10mar2017. #define REGISTER_BATCH_MATRIX_SET_DIAG_GPU(type) \ REGISTER_KERNEL_BUILDER( \ Name("BatchMatrixSetDiag").Device(DEVICE_GPU).TypeConstraint<type>("T"), \ MatrixSetDiagOp<GPUDevice, type>); TF_CALL_GPU_NUMBER_TYPES(REGISTER_BATCH_MATRIX_SET_DIAG_GPU); #undef REGISTER_BATCH_MATRIX_SET_DIAG_GPU #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM } // namespace tensorflow <|endoftext|>
<commit_before>/* Copyright (C) 2018 INRA * * 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 <array> #include "private.hpp" #include "utils.hpp" #ifdef BARYONYX_HAVE_NLOPT #include <nlopt.hpp> #include <utility> #endif struct manual_course { std::array<double, 5> theta = { { 0.0, 0.3, 0.5, 0.7, 1.0 } }; std::array<double, 5> delta = { { -1, 1e-2, 0.05, 0.001, 0.0003 } }; std::array<double, 5> kappa_min = { { 0, 1e-2, 0.05, 0.1, 0.3 } }; std::array<double, 5> kappa_step = { { 1e-7, 1e-5, 1e-3, 1e-2, 1e-1 } }; std::array<double, 5> init_random = { { 0.0, 0.3, 0.5, 0.7, 1.0 } }; std::array<int, 5> it = { { 0, 0, 0, 0, 0 } }; void reset() { std::fill(it.begin(), it.end(), 0); } bool next() { auto size = static_cast<int>(it.size() - 1); for (int i = size; i >= 0; --i) { if (it[i] + 1 > 4) { it[i] = 0; } else { ++it[i]; return true; } } return false; } }; static baryonyx::result manual_optimize(const baryonyx::context_ptr& ctx, baryonyx::problem& pb) { ctx->parameters.auto_tune = baryonyx::solver_parameters::auto_tune_parameters::disabled; manual_course array; std::array<int, 5> best_params; double best = +HUGE_VAL; do { ctx->parameters.theta = array.theta[array.it[0]]; ctx->parameters.delta = array.delta[array.it[1]]; ctx->parameters.kappa_min = array.kappa_min[array.it[2]]; ctx->parameters.kappa_step = array.kappa_step[array.it[3]]; ctx->parameters.init_random = array.init_random[array.it[4]]; auto copy_pb = pb; auto ret = baryonyx::optimize(ctx, copy_pb); if (ret) { if (best > ret.solutions.back().value) { best = ret.solutions.back().value; best_params = array.it; } } } while (array.next()); baryonyx::notice( ctx, " - manual optimization found solution {}: with theta:{} " "delta:{} kappa-min:{} kappa-step:{} init-random:{}\n", best, array.theta[array.it[0]], array.delta[array.it[1]], array.kappa_min[array.it[2]], array.kappa_step[array.it[3]], array.init_random[array.it[4]]); return baryonyx::optimize(ctx, pb); } #ifdef BARYONYX_HAVE_NLOPT enum param { param_theta = 0, // param_delta, param_kappa_min, param_kappa_step, param_init_random }; struct nlopt_data { nlopt_data(const baryonyx::context_ptr& ctx_, baryonyx::problem pb_) : ctx(ctx_) , pb(std::move(pb_)) {} const baryonyx::context_ptr& ctx; const baryonyx::problem pb; }; static double nlopt_optimize_fun(const std::vector<double>& x, std::vector<double>& /*grad*/, void* data_orig) { try { auto* data = reinterpret_cast<nlopt_data*>(data_orig); data->ctx->parameters.theta = x[static_cast<int>(param_theta)]; // data->ctx->parameters.delta = x[static_cast<int>(param_delta)]; data->ctx->parameters.kappa_min = x[static_cast<int>(param_kappa_min)]; data->ctx->parameters.kappa_step = x[static_cast<int>(param_kappa_step)]; data->ctx->parameters.init_random = x[static_cast<int>(param_init_random)]; auto copy_pb(data->pb); auto ret = baryonyx::optimize(data->ctx, copy_pb); if (not(ret)) return HUGE_VAL; // baryonyx::notice(data->ctx, // "theta: {} delta: {} kappa_min: {} kappa_step: {} " // "init_random: {}: {}\n", // data->ctx->parameters.theta, // data->ctx->parameters.delta, // data->ctx->parameters.kappa_min, // data->ctx->parameters.kappa_step, // data->ctx->parameters.init_random, // ret.solutions.back().value); baryonyx::notice(data->ctx, "theta: {} kappa_min: {} kappa_step: {} " "init_random: {}: {}\n", data->ctx->parameters.theta, data->ctx->parameters.kappa_min, data->ctx->parameters.kappa_step, data->ctx->parameters.init_random, ret.solutions.back().value); return ret.solutions.back().value; } catch (const std::exception& e) { fmt::print("Exception in nlopt_optimize_fun: {}\n", e.what()); } return HUGE_VAL; } static baryonyx::result nlopt_optimize(const baryonyx::context_ptr& ctx, baryonyx::problem& pb) { auto old_log_priority = ctx->log_priority; ctx->log_priority = baryonyx::context::message_type::notice; ctx->parameters.auto_tune = baryonyx::solver_parameters::auto_tune_parameters::disabled; nlopt_data data(ctx, pb); const std::vector<double> low{ 0, 0.0, 1e-7, 0 }; const std::vector<double> up{ 1, 0.5, 0.01, 1 }; std::vector<double> x{ 0.5, 0, 0.001, 0.5 }; nlopt::opt opt(nlopt::LN_NELDERMEAD, 4); opt.set_maxtime(3600); opt.set_vector_storage(100); opt.set_lower_bounds(low); opt.set_upper_bounds(up); opt.set_min_objective(nlopt_optimize_fun, reinterpret_cast<void*>(&data)); // // Seems interesting to loop over: // - more time-limit // - more loop-limit // - more optimization algorithms. // double value; auto result = opt.optimize(x, value); ctx->log_priority = old_log_priority; if (result >= 1 or result == -4) { baryonyx::notice( ctx, " - nlopt optimization found solution {}: with theta:xxx " "delta:{} kappa-min:{} kappa-step:{} init-random:{}\n", value, x[param_theta], // x[param_delta], x[param_kappa_min], x[param_kappa_step], x[param_init_random]); ctx->parameters.theta = x[param_theta]; // ctx->parameters.delta = x[param_delta]; ctx->parameters.kappa_min = x[param_kappa_min]; ctx->parameters.kappa_step = x[param_kappa_step]; ctx->parameters.init_random = x[param_init_random]; return baryonyx::optimize(ctx, pb); } else { baryonyx::notice(ctx, " - nlopt optimization fail. Toggle to manual " "parameters optimization.\n"); return manual_optimize(ctx, pb); } } #endif namespace baryonyx { namespace itm { baryonyx::result automatic_optimizer(const baryonyx::context_ptr& ctx, baryonyx::problem& pb, int thread) { baryonyx::notice(ctx, "- Automatic optimization starts\n"); assert(ctx->parameters.auto_tune != baryonyx::solver_parameters::auto_tune_parameters::disabled); (void)thread; #ifdef BARYONYX_HAVE_NLOPT if (ctx->parameters.auto_tune == baryonyx::solver_parameters::auto_tune_parameters::manual) return ::manual_optimize(ctx, pb); else return ::nlopt_optimize(ctx, pb); #else if (ctx->auto_tune == context::auto_tune_parameters::nlop) baryonyx::error(ctx, "Baryonyx does not have nlopt. " "Toggle to manual parameters optimization.\n"); return ::manual_optimize(ctx, pb); #endif } } // namespace itm } // namespace baryonyx <commit_msg>auto: fix code if nlopt is not available<commit_after>/* Copyright (C) 2018 INRA * * 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 <array> #include "private.hpp" #include "utils.hpp" #ifdef BARYONYX_HAVE_NLOPT #include <nlopt.hpp> #include <utility> #endif struct manual_course { std::array<double, 5> theta = { { 0.0, 0.3, 0.5, 0.7, 1.0 } }; std::array<double, 5> delta = { { -1, 1e-2, 0.05, 0.001, 0.0003 } }; std::array<double, 5> kappa_min = { { 0, 1e-2, 0.05, 0.1, 0.3 } }; std::array<double, 5> kappa_step = { { 1e-7, 1e-5, 1e-3, 1e-2, 1e-1 } }; std::array<double, 5> init_random = { { 0.0, 0.3, 0.5, 0.7, 1.0 } }; std::array<int, 5> it = { { 0, 0, 0, 0, 0 } }; void reset() { std::fill(it.begin(), it.end(), 0); } bool next() { auto size = static_cast<int>(it.size() - 1); for (int i = size; i >= 0; --i) { if (it[i] + 1 > 4) { it[i] = 0; } else { ++it[i]; return true; } } return false; } }; static baryonyx::result manual_optimize(const baryonyx::context_ptr& ctx, baryonyx::problem& pb) { ctx->parameters.auto_tune = baryonyx::solver_parameters::auto_tune_parameters::disabled; manual_course array; std::array<int, 5> best_params; double best = +HUGE_VAL; do { ctx->parameters.theta = array.theta[array.it[0]]; ctx->parameters.delta = array.delta[array.it[1]]; ctx->parameters.kappa_min = array.kappa_min[array.it[2]]; ctx->parameters.kappa_step = array.kappa_step[array.it[3]]; ctx->parameters.init_random = array.init_random[array.it[4]]; auto copy_pb = pb; auto ret = baryonyx::optimize(ctx, copy_pb); if (ret) { if (best > ret.solutions.back().value) { best = ret.solutions.back().value; best_params = array.it; } } } while (array.next()); baryonyx::notice( ctx, " - manual optimization found solution {}: with theta:{} " "delta:{} kappa-min:{} kappa-step:{} init-random:{}\n", best, array.theta[array.it[0]], array.delta[array.it[1]], array.kappa_min[array.it[2]], array.kappa_step[array.it[3]], array.init_random[array.it[4]]); return baryonyx::optimize(ctx, pb); } #ifdef BARYONYX_HAVE_NLOPT enum param { param_theta = 0, // param_delta, param_kappa_min, param_kappa_step, param_init_random }; struct nlopt_data { nlopt_data(const baryonyx::context_ptr& ctx_, baryonyx::problem pb_) : ctx(ctx_) , pb(std::move(pb_)) {} const baryonyx::context_ptr& ctx; const baryonyx::problem pb; }; static double nlopt_optimize_fun(const std::vector<double>& x, std::vector<double>& /*grad*/, void* data_orig) { try { auto* data = reinterpret_cast<nlopt_data*>(data_orig); data->ctx->parameters.theta = x[static_cast<int>(param_theta)]; // data->ctx->parameters.delta = x[static_cast<int>(param_delta)]; data->ctx->parameters.kappa_min = x[static_cast<int>(param_kappa_min)]; data->ctx->parameters.kappa_step = x[static_cast<int>(param_kappa_step)]; data->ctx->parameters.init_random = x[static_cast<int>(param_init_random)]; auto copy_pb(data->pb); auto ret = baryonyx::optimize(data->ctx, copy_pb); if (not(ret)) return HUGE_VAL; // baryonyx::notice(data->ctx, // "theta: {} delta: {} kappa_min: {} kappa_step: {} " // "init_random: {}: {}\n", // data->ctx->parameters.theta, // data->ctx->parameters.delta, // data->ctx->parameters.kappa_min, // data->ctx->parameters.kappa_step, // data->ctx->parameters.init_random, // ret.solutions.back().value); baryonyx::notice(data->ctx, "theta: {} kappa_min: {} kappa_step: {} " "init_random: {}: {}\n", data->ctx->parameters.theta, data->ctx->parameters.kappa_min, data->ctx->parameters.kappa_step, data->ctx->parameters.init_random, ret.solutions.back().value); return ret.solutions.back().value; } catch (const std::exception& e) { fmt::print("Exception in nlopt_optimize_fun: {}\n", e.what()); } return HUGE_VAL; } static baryonyx::result nlopt_optimize(const baryonyx::context_ptr& ctx, baryonyx::problem& pb) { auto old_log_priority = ctx->log_priority; ctx->log_priority = baryonyx::context::message_type::notice; ctx->parameters.auto_tune = baryonyx::solver_parameters::auto_tune_parameters::disabled; nlopt_data data(ctx, pb); const std::vector<double> low{ 0, 0.0, 1e-7, 0 }; const std::vector<double> up{ 1, 0.5, 0.01, 1 }; std::vector<double> x{ 0.5, 0, 0.001, 0.5 }; nlopt::opt opt(nlopt::LN_NELDERMEAD, 4); opt.set_maxtime(3600); opt.set_vector_storage(100); opt.set_lower_bounds(low); opt.set_upper_bounds(up); opt.set_min_objective(nlopt_optimize_fun, reinterpret_cast<void*>(&data)); // // Seems interesting to loop over: // - more time-limit // - more loop-limit // - more optimization algorithms. // double value; auto result = opt.optimize(x, value); ctx->log_priority = old_log_priority; if (result >= 1 or result == -4) { baryonyx::notice( ctx, " - nlopt optimization found solution {}: with theta:xxx " "delta:{} kappa-min:{} kappa-step:{} init-random:{}\n", value, x[param_theta], // x[param_delta], x[param_kappa_min], x[param_kappa_step], x[param_init_random]); ctx->parameters.theta = x[param_theta]; // ctx->parameters.delta = x[param_delta]; ctx->parameters.kappa_min = x[param_kappa_min]; ctx->parameters.kappa_step = x[param_kappa_step]; ctx->parameters.init_random = x[param_init_random]; return baryonyx::optimize(ctx, pb); } else { baryonyx::notice(ctx, " - nlopt optimization fail. Toggle to manual " "parameters optimization.\n"); return manual_optimize(ctx, pb); } } #endif namespace baryonyx { namespace itm { baryonyx::result automatic_optimizer(const baryonyx::context_ptr& ctx, baryonyx::problem& pb, int thread) { baryonyx::notice(ctx, "- Automatic optimization starts\n"); assert(ctx->parameters.auto_tune != baryonyx::solver_parameters::auto_tune_parameters::disabled); (void)thread; #ifdef BARYONYX_HAVE_NLOPT if (ctx->parameters.auto_tune == baryonyx::solver_parameters::auto_tune_parameters::manual) return ::manual_optimize(ctx, pb); else return ::nlopt_optimize(ctx, pb); #else if (ctx->parameters.auto_tune == context::auto_tune_parameters::nlop) baryonyx::error(ctx, "Baryonyx does not have nlopt. " "Toggle to manual parameters optimization.\n"); return ::manual_optimize(ctx, pb); #endif } } // namespace itm } // namespace baryonyx <|endoftext|>
<commit_before>#include <pxp-agent/util/daemonize.hpp> #include <pxp-agent/configuration.hpp> #define LEATHERMAN_LOGGING_NAMESPACE "puppetlabs.pxp_agent.util.daemonize" #include <leatherman/logging/logging.hpp> #include <sys/types.h> #include <stdlib.h> // exit() #include <unistd.h> // _exit(), getpid(), fork(), setsid(), chdir() #include <sys/wait.h> // waitpid() #include <sys/stat.h> // umask() #include <signal.h> #include <stdio.h> #include <memory> #include <vector> namespace PXPAgent { namespace Util { const mode_t UMASK_FLAGS { 002 }; const std::string DEFAULT_DAEMON_WORKING_DIR = "/"; static void sigHandler(int sig) { // NOTE(ale): if issued by the init process, between SIGTERM and // the successive SIGKILL there are only 5 s - must be fast auto pidfile = Configuration::Instance().get<std::string>("pidfile"); LOG_INFO("Caught signal {1} - removing PID file '{2}'", std::to_string(sig), pidfile); PIDFile pidf { pidfile }; pidf.cleanup(); exit(EXIT_SUCCESS); } static void dumbSigHandler(int sig) {} std::unique_ptr<PIDFile> daemonize() { // Check if we're already a daemon if (getppid() == 1) { // Parent is init process (PID 1) LOG_INFO("Already a daemon with PID={1}", std::to_string(getpid())); return nullptr; } // Set umask; child processes will inherit umask(UMASK_FLAGS); // Check PID file; get read lock; ensure we can obtain write lock auto pidfile = Configuration::Instance().get<std::string>("pidfile"); std::unique_ptr<PIDFile> pidf_ptr { new PIDFile(pidfile) }; auto removeLockAndExit = [&pidf_ptr] () { pidf_ptr->cleanupWhenDone(); exit(EXIT_FAILURE); }; if (pidf_ptr->isExecuting()) { auto pid = pidf_ptr->read(); LOG_ERROR("Already running with PID={1}", pid); removeLockAndExit(); } try { pidf_ptr->lockRead(); LOG_DEBUG("Obtained a read lock for the PID file; no other pxp-agent " "daemon should be executing"); } catch (const PIDFile::Error& e) { LOG_ERROR("Failed get a read lock for the PID file: {1}", e.what()); removeLockAndExit(); } try { if (pidf_ptr->canLockWrite()) { LOG_DEBUG("It is possible to get a write lock for the PID file; no " "other pxp-agent daemonization should be in progress"); } else { LOG_ERROR("Cannot acquire the write lock for the PID file; please " "ensure that there is no other pxp-agent instance executing"); removeLockAndExit(); } } catch (const PIDFile::Error& e) { LOG_ERROR("Failed to check if we can lock the PID file: {1}", e.what()); removeLockAndExit(); } // First fork - run in background auto first_child_pid = fork(); switch (first_child_pid) { case -1: LOG_ERROR("Failed to perform the first fork; {1} ({2})", strerror(errno), errno); removeLockAndExit(); case 0: // CHILD - will fork and exit soon LOG_DEBUG("First child spawned, with PID={1}", std::to_string(getpid())); break; default: // PARENT - wait for the child, to avoid a zombie process // and don't unlock the PID file waitpid(first_child_pid, nullptr, 0); // Exit with _exit(); note that after a fork(), only one // of parent and child should terminate with exit() _exit(EXIT_SUCCESS); } // Get the read lock try { pidf_ptr->lockRead(); LOG_DEBUG("Obtained the read lock after first fork"); } catch (const PIDFile::Error& e) { LOG_ERROR("Failed get a read lock after first fork: {1}", e.what()); removeLockAndExit(); } // Create a new group session and become leader in order to // disassociate from a possible controlling terminal later if (setsid() == -1) { LOG_ERROR("Failed to create new session for first child process; " "{1} ({2})", strerror(errno), errno); removeLockAndExit(); } // Prepare signal mask for the second fork in order to catch the // child signal: block the child signal for now in order to avoid // races and change signal disposition for SIGUSR1 sigset_t block_mask, orig_mask, empty_mask; struct sigaction sa; sigemptyset(&block_mask); sigaddset(&block_mask, SIGUSR1); if (sigprocmask(SIG_BLOCK, &block_mask, &orig_mask) == -1) { LOG_ERROR("Failed to set the signal mask after first fork"); removeLockAndExit(); } sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sa.sa_handler = dumbSigHandler; if (sigaction(SIGUSR1, &sa, NULL) == -1) { LOG_ERROR("Failed to set SIGUSR1 disposition after first fork"); removeLockAndExit(); } // Second fork - the child won't be a session leader and won't be // associated with any controlling terminal auto second_child_pid = fork(); switch (second_child_pid) { case -1: LOG_ERROR("Failed to perform the second fork; {1} ({2})", strerror(errno), errno); removeLockAndExit(); case 0: // CHILD - will be the pxp-agent! break; default: // PARENT - wait for the child signal to avoid unlocking // the PID file sigemptyset(&empty_mask); if (sigsuspend(&empty_mask) == -1 && errno != EINTR) { LOG_ERROR("Unexpected error while waiting for pending signals " "after second fork; {1} ({2})", strerror(errno), errno); } _exit(EXIT_SUCCESS); } // Get read lock, signal the parent, and restore signal mask try { pidf_ptr->lockRead(); LOG_DEBUG("Obtained the read lock after second fork"); } catch (const PIDFile::Error& e) { LOG_ERROR("Failed get a read lock after second fork: {1}", e.what()); kill(getppid(), SIGUSR1); removeLockAndExit(); } kill(getppid(), SIGUSR1); if (sigprocmask(SIG_SETMASK, &orig_mask, NULL) == -1) { LOG_ERROR("Failed to reset signal mask after second fork; " "{1} ({2})", strerror(errno), errno); removeLockAndExit(); } auto agent_pid = getpid(); LOG_DEBUG("Second child spawned, with PID={1}", agent_pid); // Convert the read lock to a write lock and write PID to file LOG_DEBUG("Converting the read lock to write lock after second fork"); try { pidf_ptr->lockWrite(true); // blocking call LOG_DEBUG("Successfully converted read lock to write lock"); } catch (const PIDFile::Error& e) { LOG_ERROR("Failed to convert to write lock after second fork: {1}", e.what()); removeLockAndExit(); } pidf_ptr->write(agent_pid); // Change work directory if (chdir(DEFAULT_DAEMON_WORKING_DIR.data())) { LOG_ERROR("Failed to change work directory to '{1}'; {2} ({3})", DEFAULT_DAEMON_WORKING_DIR, strerror(errno), errno); removeLockAndExit(); } else { LOG_DEBUG("Changed working directory to '{1}'", DEFAULT_DAEMON_WORKING_DIR); } // Change signal dispositions // HERE(ale): don't touch SIGUSR2; it's used to reopen the logfile for (auto s : std::vector<int> { SIGINT, SIGTERM, SIGQUIT }) { if (signal(s, sigHandler) == SIG_ERR) { LOG_ERROR("Failed to set signal handler for sig {1}", s); removeLockAndExit(); } } signal(SIGCHLD, SIG_DFL); signal(SIGTSTP, SIG_IGN); signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGHUP, SIG_IGN); // Redirect standard files; we always use boost::log anyway auto tmpin = freopen("/dev/null", "r", stdin); if (tmpin == nullptr) { LOG_WARNING("Failed to redirect stdin to /dev/null; {1} ({2})", strerror(errno), errno); } auto tmpout = freopen("/dev/null", "w", stdout); if (tmpout == nullptr) { LOG_WARNING("Failed to redirect stdout to /dev/null; {1} ({2})", strerror(errno), errno); } auto tmperr = freopen("/dev/null", "w", stderr); if (tmperr == nullptr) { LOG_WARNING("Failed to redirect stderr to /dev/null; {1} ({2})", strerror(errno), errno); } LOG_INFO("Daemonization completed; pxp-agent PID={1}, PID lock file in '{2}'", agent_pid, pidfile); // Set PIDFile dtor to clean itself up and return pointer for RAII pidf_ptr->cleanupWhenDone(); return pidf_ptr; } } // namespace Util } // namespace PXPAgent <commit_msg>(PCP-736) Remove umask settings<commit_after>#include <pxp-agent/util/daemonize.hpp> #include <pxp-agent/configuration.hpp> #define LEATHERMAN_LOGGING_NAMESPACE "puppetlabs.pxp_agent.util.daemonize" #include <leatherman/logging/logging.hpp> #include <sys/types.h> #include <stdlib.h> // exit() #include <unistd.h> // _exit(), getpid(), fork(), setsid(), chdir() #include <sys/wait.h> // waitpid() #include <signal.h> #include <stdio.h> #include <memory> #include <vector> namespace PXPAgent { namespace Util { const std::string DEFAULT_DAEMON_WORKING_DIR = "/"; static void sigHandler(int sig) { // NOTE(ale): if issued by the init process, between SIGTERM and // the successive SIGKILL there are only 5 s - must be fast auto pidfile = Configuration::Instance().get<std::string>("pidfile"); LOG_INFO("Caught signal {1} - removing PID file '{2}'", std::to_string(sig), pidfile); PIDFile pidf { pidfile }; pidf.cleanup(); exit(EXIT_SUCCESS); } static void dumbSigHandler(int sig) {} std::unique_ptr<PIDFile> daemonize() { // Check if we're already a daemon if (getppid() == 1) { // Parent is init process (PID 1) LOG_INFO("Already a daemon with PID={1}", std::to_string(getpid())); return nullptr; } // Check PID file; get read lock; ensure we can obtain write lock auto pidfile = Configuration::Instance().get<std::string>("pidfile"); std::unique_ptr<PIDFile> pidf_ptr { new PIDFile(pidfile) }; auto removeLockAndExit = [&pidf_ptr] () { pidf_ptr->cleanupWhenDone(); exit(EXIT_FAILURE); }; if (pidf_ptr->isExecuting()) { auto pid = pidf_ptr->read(); LOG_ERROR("Already running with PID={1}", pid); removeLockAndExit(); } try { pidf_ptr->lockRead(); LOG_DEBUG("Obtained a read lock for the PID file; no other pxp-agent " "daemon should be executing"); } catch (const PIDFile::Error& e) { LOG_ERROR("Failed get a read lock for the PID file: {1}", e.what()); removeLockAndExit(); } try { if (pidf_ptr->canLockWrite()) { LOG_DEBUG("It is possible to get a write lock for the PID file; no " "other pxp-agent daemonization should be in progress"); } else { LOG_ERROR("Cannot acquire the write lock for the PID file; please " "ensure that there is no other pxp-agent instance executing"); removeLockAndExit(); } } catch (const PIDFile::Error& e) { LOG_ERROR("Failed to check if we can lock the PID file: {1}", e.what()); removeLockAndExit(); } // First fork - run in background auto first_child_pid = fork(); switch (first_child_pid) { case -1: LOG_ERROR("Failed to perform the first fork; {1} ({2})", strerror(errno), errno); removeLockAndExit(); case 0: // CHILD - will fork and exit soon LOG_DEBUG("First child spawned, with PID={1}", std::to_string(getpid())); break; default: // PARENT - wait for the child, to avoid a zombie process // and don't unlock the PID file waitpid(first_child_pid, nullptr, 0); // Exit with _exit(); note that after a fork(), only one // of parent and child should terminate with exit() _exit(EXIT_SUCCESS); } // Get the read lock try { pidf_ptr->lockRead(); LOG_DEBUG("Obtained the read lock after first fork"); } catch (const PIDFile::Error& e) { LOG_ERROR("Failed get a read lock after first fork: {1}", e.what()); removeLockAndExit(); } // Create a new group session and become leader in order to // disassociate from a possible controlling terminal later if (setsid() == -1) { LOG_ERROR("Failed to create new session for first child process; " "{1} ({2})", strerror(errno), errno); removeLockAndExit(); } // Prepare signal mask for the second fork in order to catch the // child signal: block the child signal for now in order to avoid // races and change signal disposition for SIGUSR1 sigset_t block_mask, orig_mask, empty_mask; struct sigaction sa; sigemptyset(&block_mask); sigaddset(&block_mask, SIGUSR1); if (sigprocmask(SIG_BLOCK, &block_mask, &orig_mask) == -1) { LOG_ERROR("Failed to set the signal mask after first fork"); removeLockAndExit(); } sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sa.sa_handler = dumbSigHandler; if (sigaction(SIGUSR1, &sa, NULL) == -1) { LOG_ERROR("Failed to set SIGUSR1 disposition after first fork"); removeLockAndExit(); } // Second fork - the child won't be a session leader and won't be // associated with any controlling terminal auto second_child_pid = fork(); switch (second_child_pid) { case -1: LOG_ERROR("Failed to perform the second fork; {1} ({2})", strerror(errno), errno); removeLockAndExit(); case 0: // CHILD - will be the pxp-agent! break; default: // PARENT - wait for the child signal to avoid unlocking // the PID file sigemptyset(&empty_mask); if (sigsuspend(&empty_mask) == -1 && errno != EINTR) { LOG_ERROR("Unexpected error while waiting for pending signals " "after second fork; {1} ({2})", strerror(errno), errno); } _exit(EXIT_SUCCESS); } // Get read lock, signal the parent, and restore signal mask try { pidf_ptr->lockRead(); LOG_DEBUG("Obtained the read lock after second fork"); } catch (const PIDFile::Error& e) { LOG_ERROR("Failed get a read lock after second fork: {1}", e.what()); kill(getppid(), SIGUSR1); removeLockAndExit(); } kill(getppid(), SIGUSR1); if (sigprocmask(SIG_SETMASK, &orig_mask, NULL) == -1) { LOG_ERROR("Failed to reset signal mask after second fork; " "{1} ({2})", strerror(errno), errno); removeLockAndExit(); } auto agent_pid = getpid(); LOG_DEBUG("Second child spawned, with PID={1}", agent_pid); // Convert the read lock to a write lock and write PID to file LOG_DEBUG("Converting the read lock to write lock after second fork"); try { pidf_ptr->lockWrite(true); // blocking call LOG_DEBUG("Successfully converted read lock to write lock"); } catch (const PIDFile::Error& e) { LOG_ERROR("Failed to convert to write lock after second fork: {1}", e.what()); removeLockAndExit(); } pidf_ptr->write(agent_pid); // Change work directory if (chdir(DEFAULT_DAEMON_WORKING_DIR.data())) { LOG_ERROR("Failed to change work directory to '{1}'; {2} ({3})", DEFAULT_DAEMON_WORKING_DIR, strerror(errno), errno); removeLockAndExit(); } else { LOG_DEBUG("Changed working directory to '{1}'", DEFAULT_DAEMON_WORKING_DIR); } // Change signal dispositions // HERE(ale): don't touch SIGUSR2; it's used to reopen the logfile for (auto s : std::vector<int> { SIGINT, SIGTERM, SIGQUIT }) { if (signal(s, sigHandler) == SIG_ERR) { LOG_ERROR("Failed to set signal handler for sig {1}", s); removeLockAndExit(); } } signal(SIGCHLD, SIG_DFL); signal(SIGTSTP, SIG_IGN); signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGHUP, SIG_IGN); // Redirect standard files; we always use boost::log anyway auto tmpin = freopen("/dev/null", "r", stdin); if (tmpin == nullptr) { LOG_WARNING("Failed to redirect stdin to /dev/null; {1} ({2})", strerror(errno), errno); } auto tmpout = freopen("/dev/null", "w", stdout); if (tmpout == nullptr) { LOG_WARNING("Failed to redirect stdout to /dev/null; {1} ({2})", strerror(errno), errno); } auto tmperr = freopen("/dev/null", "w", stderr); if (tmperr == nullptr) { LOG_WARNING("Failed to redirect stderr to /dev/null; {1} ({2})", strerror(errno), errno); } LOG_INFO("Daemonization completed; pxp-agent PID={1}, PID lock file in '{2}'", agent_pid, pidfile); // Set PIDFile dtor to clean itself up and return pointer for RAII pidf_ptr->cleanupWhenDone(); return pidf_ptr; } } // namespace Util } // namespace PXPAgent <|endoftext|>
<commit_before>// RUN: %clangxx %s -o %t && %run %t // UNSUPPORTED: ios #include <assert.h> #include <grp.h> #include <memory> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> std::string any_group; const int N = 123456; void Check(const char *str) { if (!str) return; assert(strlen(str) != N); } void Check(const passwd *result) { Check(result->pw_name); Check(result->pw_passwd); assert(result->pw_uid != N); assert(result->pw_gid != N); #if !defined(__ANDROID__) Check(result->pw_gecos); #endif Check(result->pw_dir); #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) assert(result->pw_change != N); Check(result->pw_class); assert(result->pw_expire != N); #endif #if defined(__FreeBSD__) assert(result->pw_fields != N); #endif // SunOS also has pw_age and pw_comment which are documented as unused. } void Check(const group *result) { Check(result->gr_name); Check(result->gr_passwd); assert(result->gr_gid != N); for (char **mem = result->gr_mem; *mem; ++mem) Check(*mem); if (any_group.empty()) any_group = result->gr_name; } template <class T, class Fn, class... Args> void test(Fn f, Args... args) { T *result = f(args...); Check(result); } template <class T, class Fn, class... Args> void test_r(Fn f, Args... args) { T gr; T *result; char buff[10000]; assert(!f(args..., &gr, buff, sizeof(buff), &result)); Check(&gr); Check(result); } int main(int argc, const char *argv[]) { test<passwd>(&getpwuid, 0); test<passwd>(&getpwnam, "root"); test<group>(&getgrgid, 0); // Disable this test for now since it seems to hit a bug in EGLIBC 2.19 //test<group>(&getgrnam, any_group.c_str()); #if !defined(__ANDROID__) setpwent(); test<passwd>(&getpwent); setgrent(); test<group>(&getgrent); #if !defined(__APPLE__) setpwent(); test_r<passwd>(&getpwent_r); setgrent(); test_r<group>(&getgrent_r); #endif test_r<passwd>(&getpwuid_r, 0); test_r<passwd>(&getpwnam_r, "root"); test_r<group>(&getgrgid_r, 0); // Disable this test for now since it seems to hit a bug in EGLIBC 2.19 //test_r<group>(&getgrnam_r, any_group.c_str()); #if defined(__linux__) auto pwd_file = [] { return std::unique_ptr<FILE, decltype(&fclose)>(fopen("/etc/passwd", "r"), &fclose); }; auto gr_file = [] { return std::unique_ptr<FILE, decltype(&fclose)>(fopen("/etc/group", "r"), &fclose); }; test<passwd>(&fgetpwent, pwd_file().get()); test<group>(&fgetgrent, gr_file().get()); test_r<passwd>(&fgetpwent_r, pwd_file().get()); test_r<group>(&fgetgrent_r, gr_file().get()); #endif #endif // __ANDROID__ return 0; } <commit_msg>Revert "Temporarily disable calls to getgrnam/getgrnam_r in test due to it hitting unrelated issues in EGLIBC 2.19."<commit_after>// RUN: %clangxx %s -o %t && %run %t // UNSUPPORTED: ios #include <assert.h> #include <grp.h> #include <memory> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> std::string any_group; const int N = 123456; void Check(const char *str) { if (!str) return; assert(strlen(str) != N); } void Check(const passwd *result) { Check(result->pw_name); Check(result->pw_passwd); assert(result->pw_uid != N); assert(result->pw_gid != N); #if !defined(__ANDROID__) Check(result->pw_gecos); #endif Check(result->pw_dir); #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) assert(result->pw_change != N); Check(result->pw_class); assert(result->pw_expire != N); #endif #if defined(__FreeBSD__) assert(result->pw_fields != N); #endif // SunOS also has pw_age and pw_comment which are documented as unused. } void Check(const group *result) { Check(result->gr_name); Check(result->gr_passwd); assert(result->gr_gid != N); for (char **mem = result->gr_mem; *mem; ++mem) Check(*mem); if (any_group.empty()) any_group = result->gr_name; } template <class T, class Fn, class... Args> void test(Fn f, Args... args) { T *result = f(args...); Check(result); } template <class T, class Fn, class... Args> void test_r(Fn f, Args... args) { T gr; T *result; char buff[10000]; assert(!f(args..., &gr, buff, sizeof(buff), &result)); Check(&gr); Check(result); } int main(int argc, const char *argv[]) { test<passwd>(&getpwuid, 0); test<passwd>(&getpwnam, "root"); test<group>(&getgrgid, 0); test<group>(&getgrnam, any_group.c_str()); #if !defined(__ANDROID__) setpwent(); test<passwd>(&getpwent); setgrent(); test<group>(&getgrent); #if !defined(__APPLE__) setpwent(); test_r<passwd>(&getpwent_r); setgrent(); test_r<group>(&getgrent_r); #endif test_r<passwd>(&getpwuid_r, 0); test_r<passwd>(&getpwnam_r, "root"); test_r<group>(&getgrgid_r, 0); test_r<group>(&getgrnam_r, any_group.c_str()); #if defined(__linux__) auto pwd_file = [] { return std::unique_ptr<FILE, decltype(&fclose)>(fopen("/etc/passwd", "r"), &fclose); }; auto gr_file = [] { return std::unique_ptr<FILE, decltype(&fclose)>(fopen("/etc/group", "r"), &fclose); }; test<passwd>(&fgetpwent, pwd_file().get()); test<group>(&fgetgrent, gr_file().get()); test_r<passwd>(&fgetpwent_r, pwd_file().get()); test_r<group>(&fgetgrent_r, gr_file().get()); #endif #endif // __ANDROID__ return 0; } <|endoftext|>
<commit_before>// RUN: %clangxx -fsanitize=function %s -O3 -g -o %t // RUN: %run %t 2>&1 | FileCheck %s // Verify that we can disable symbolization if needed: // RUN: %env_ubsan_opts=symbolize=0 %run %t 2>&1 | FileCheck %s --check-prefix=NOSYM #include <stdint.h> void f() {} void g(int x) {} void make_valid_call() { // CHECK-NOT: runtime error: call to function g reinterpret_cast<void (*)(int)>(reinterpret_cast<uintptr_t>(g))(42); } void make_invalid_call() { // CHECK: function.cpp:[[@LINE+4]]:3: runtime error: call to function f() through pointer to incorrect function type 'void (*)(int)' // CHECK-NEXT: function.cpp:[[@LINE-11]]: note: f() defined here // NOSYM: function.cpp:[[@LINE+2]]:3: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int)' // NOSYM-NEXT: ({{.*}}+0x{{.*}}): note: (unknown) defined here reinterpret_cast<void (*)(int)>(reinterpret_cast<uintptr_t>(f))(42); } int main(void) { make_valid_call(); make_invalid_call(); // Check that no more errors will be printed. // CHECK-NOT: runtime error: call to function // NOSYM-NOT: runtime error: call to function make_invalid_call(); } <commit_msg>XFAIL ubsan/TestCases/TypeCheck/Function/function.cpp on Windows<commit_after>// RUN: %clangxx -fsanitize=function %s -O3 -g -o %t // RUN: %run %t 2>&1 | FileCheck %s // Verify that we can disable symbolization if needed: // RUN: %env_ubsan_opts=symbolize=0 %run %t 2>&1 | FileCheck %s --check-prefix=NOSYM // XFAIL: win32,win64 #include <stdint.h> void f() {} void g(int x) {} void make_valid_call() { // CHECK-NOT: runtime error: call to function g reinterpret_cast<void (*)(int)>(reinterpret_cast<uintptr_t>(g))(42); } void make_invalid_call() { // CHECK: function.cpp:[[@LINE+4]]:3: runtime error: call to function f() through pointer to incorrect function type 'void (*)(int)' // CHECK-NEXT: function.cpp:[[@LINE-11]]: note: f() defined here // NOSYM: function.cpp:[[@LINE+2]]:3: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int)' // NOSYM-NEXT: ({{.*}}+0x{{.*}}): note: (unknown) defined here reinterpret_cast<void (*)(int)>(reinterpret_cast<uintptr_t>(f))(42); } int main(void) { make_valid_call(); make_invalid_call(); // Check that no more errors will be printed. // CHECK-NOT: runtime error: call to function // NOSYM-NOT: runtime error: call to function make_invalid_call(); } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. 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 MathTools.cpp \author Jens Krueger SCI Institute University of Utah \version 1.11 \date October 2008 */ #include "MathTools.h" #include <algorithm> UINT32 MathTools::Log(UINT32 value, UINT32 base) { return UINT32(log(float(value)) / log(float(base))); } float MathTools::Log(float value, float base) { return log(value) / log(base); } UINT32 MathTools::Pow(UINT32 base, UINT32 exponent) { return UINT32(0.5f+pow(float(base), float(exponent))); } UINT64 MathTools::Pow(UINT64 base, UINT64 exponent) { return UINT64(0.5+pow(double(base), double(exponent))); } UINT32 MathTools::Log2(UINT32 n) { int iLog=0; while( n>>=1 ) iLog++; return iLog; } UINT32 MathTools::Pow2(UINT32 e) { return 1<<e; } UINT64 MathTools::Log2(UINT64 n) { int iLog=0; while( n>>=1 ) iLog++; return iLog; } UINT64 MathTools::Pow2(UINT64 e) { return static_cast<UINT64>(1) << e; } UINT32 MathTools::GaussianSum(UINT32 n) { return n*(n+1)/2; } bool MathTools::IsPow2(UINT32 n) { return ((n&(n-1))==0); }; UINT32 MathTools::NextPow2(UINT32 n, bool bReturn_ID_on_Pow2) { if (bReturn_ID_on_Pow2 && IsPow2(n)) return n; return Pow2(Log2(n)+1); } bool MathTools::NaN(float f) { #ifdef USABLE_TR1 return std::tr1::isnan(f); #elif defined(_MSC_VER) return _finite(f) != 0; #else // Hack, relies on 'f' being IEEE-754! return f != f; #endif } float MathTools::Clamp(float val, float a, float b) { return std::max(a, std::min(b, val)); } UINT32 MathTools::Clamp(UINT32 val, UINT32 a, UINT32 b) { return std::max(a, std::min(b, val)); } UINT64 MathTools::Clamp(UINT64 val, UINT64 a, UINT64 b) { return std::max(a, std::min(b, val)); } int MathTools::Clamp(int val, int a, int b) { return std::max(a, std::min(b, val)); } <commit_msg>I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code. I shall not break Tom's code.....<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. 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 MathTools.cpp \author Jens Krueger SCI Institute University of Utah \version 1.11 \date October 2008 */ #include "MathTools.h" #include <algorithm> UINT32 MathTools::Log(UINT32 value, UINT32 base) { return UINT32(log(float(value)) / log(float(base))); } float MathTools::Log(float value, float base) { return log(value) / log(base); } UINT32 MathTools::Pow(UINT32 base, UINT32 exponent) { return UINT32(0.5f+pow(float(base), float(exponent))); } UINT64 MathTools::Pow(UINT64 base, UINT64 exponent) { return UINT64(0.5+pow(double(base), double(exponent))); } UINT32 MathTools::Log2(UINT32 n) { int iLog=0; while( n>>=1 ) iLog++; return iLog; } UINT32 MathTools::Pow2(UINT32 e) { return 1<<e; } UINT64 MathTools::Log2(UINT64 n) { int iLog=0; while( n>>=1 ) iLog++; return iLog; } UINT64 MathTools::Pow2(UINT64 e) { return static_cast<UINT64>(1) << e; } UINT32 MathTools::GaussianSum(UINT32 n) { return n*(n+1)/2; } bool MathTools::IsPow2(UINT32 n) { return ((n&(n-1))==0); }; UINT32 MathTools::NextPow2(UINT32 n, bool bReturn_ID_on_Pow2) { if (bReturn_ID_on_Pow2 && IsPow2(n)) return n; return Pow2(Log2(n)+1); } bool MathTools::NaN(float f) { #ifdef USABLE_TR1 return std::tr1::isnan(f); #elif defined(_MSC_VER) return _finite(f) == 0; #else // Hack, relies on 'f' being IEEE-754! return f != f; #endif } float MathTools::Clamp(float val, float a, float b) { return std::max(a, std::min(b, val)); } UINT32 MathTools::Clamp(UINT32 val, UINT32 a, UINT32 b) { return std::max(a, std::min(b, val)); } UINT64 MathTools::Clamp(UINT64 val, UINT64 a, UINT64 b) { return std::max(a, std::min(b, val)); } int MathTools::Clamp(int val, int a, int b) { return std::max(a, std::min(b, val)); } <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file MixClient.cpp * @author Arkadiy Paronyan arkadiy@ethdev.com * @date 2015 * Ethereum IDE client. */ #include "MixClient.h" #include <vector> #include <utility> #include <libdevcore/Exceptions.h> #include <libethcore/Params.h> #include <libethcore/BasicAuthority.h> #include <libethereum/CanonBlockChain.h> #include <libethereum/Transaction.h> #include <libethereum/Executive.h> #include <libethereum/ExtVM.h> #include <libethereum/BlockChain.h> #include <libevm/VM.h> #include "Exceptions.h" using namespace std; using namespace dev; using namespace dev::eth; namespace dev { namespace mix { u256 const c_mixGenesisDifficulty = 131072; //TODO: make it lower for Mix somehow namespace { } MixBlockChain::MixBlockChain(std::string const& _path, h256 _stateRoot): FullBlockChain<NoProof>(createGenesisBlock(_stateRoot), std::unordered_map<Address, Account>(), _path, WithExisting::Kill) { } bytes MixBlockChain::createGenesisBlock(h256 _stateRoot) { RLPStream block(3); block.appendList(13) << h256() << EmptyListSHA3 << h160() << _stateRoot << EmptyTrie << EmptyTrie << LogBloom() << c_mixGenesisDifficulty << 0 << 3141592 << 0 << (unsigned)0 << std::string(); block.appendRaw(RLPEmptyList); block.appendRaw(RLPEmptyList); return block.out(); } MixClient::MixClient(std::string const& _dbPath): m_dbPath(_dbPath) { resetState(std::unordered_map<Address, Account>()); } MixClient::~MixClient() { } void MixClient::resetState(std::unordered_map<Address, Account> const& _accounts, Secret const& _miner) { WriteGuard l(x_state); Guard fl(x_filtersWatches); m_filters.clear(); for (auto& i: m_specialFilters) i.second.clear(); m_watches.clear(); m_stateDB = OverlayDB(); SecureTrieDB<Address, MemoryDB> accountState(&m_stateDB); accountState.init(); dev::eth::commit(_accounts, accountState); h256 stateRoot = accountState.root(); m_bc.reset(); m_bc.reset(new MixBlockChain(m_dbPath, stateRoot)); Block b(m_stateDB, BaseState::PreExisting, KeyPair(_miner).address()); b.sync(bc()); m_preMine = b; m_postMine = b; WriteGuard lx(x_executions); m_executions.clear(); } Transaction MixClient::replaceGas(Transaction const& _t, u256 const& _gas, Secret const& _secret) { Transaction ret; if (_secret) { if (_t.isCreation()) ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce(), _secret); else ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce(), _secret); } else { if (_t.isCreation()) ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce()); else ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce()); ret.forceSender(_t.safeSender()); } return ret; } // TODO: prototype changed - will need rejigging. ExecutionResult MixClient::debugTransaction(Transaction const& _t, State const& _state, EnvInfo const& _envInfo, bool _call) { State execState = _state; execState.addBalance(_t.sender(), _t.gas() * _t.gasPrice()); //give it enough balance for gas estimation eth::ExecutionResult er; Executive execution(execState, _envInfo); execution.setResultRecipient(er); ExecutionResult d; d.address = _t.receiveAddress(); d.sender = _t.sender(); d.value = _t.value(); d.inputParameters = _t.data(); d.executonIndex = m_executions.size(); if (!_call) d.transactionIndex = m_postMine.pending().size(); try { execution.initialize(_t); execution.execute(); } catch (Exception const& _e) { d.excepted = toTransactionException(_e); d.transactionData.push_back(_t.data()); return d; } std::vector<MachineState> machineStates; std::vector<unsigned> levels; std::vector<MachineCode> codes; std::map<bytes const*, unsigned> codeIndexes; std::vector<bytes> data; std::map<bytesConstRef const*, unsigned> dataIndexes; bytes const* lastCode = nullptr; bytesConstRef const* lastData = nullptr; unsigned codeIndex = 0; unsigned dataIndex = 0; auto onOp = [&](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, void* voidVM, void const* voidExt) { VM& vm = *static_cast<VM*>(voidVM); ExtVM const& ext = *static_cast<ExtVM const*>(voidExt); if (lastCode == nullptr || lastCode != &ext.code) { auto const& iter = codeIndexes.find(&ext.code); if (iter != codeIndexes.end()) codeIndex = iter->second; else { codeIndex = codes.size(); codes.push_back(MachineCode({ext.myAddress, ext.code})); codeIndexes[&ext.code] = codeIndex; } lastCode = &ext.code; } if (lastData == nullptr || lastData != &ext.data) { auto const& iter = dataIndexes.find(&ext.data); if (iter != dataIndexes.end()) dataIndex = iter->second; else { dataIndex = data.size(); data.push_back(ext.data.toBytes()); dataIndexes[&ext.data] = dataIndex; } lastData = &ext.data; } if (levels.size() < ext.depth) levels.push_back(machineStates.size() - 1); else levels.resize(ext.depth); machineStates.push_back(MachineState{ steps, vm.curPC(), inst, newMemSize, static_cast<u256>(gas), vm.stack(), vm.memory(), gasCost, ext.state().storage(ext.myAddress), std::move(levels), codeIndex, dataIndex }); }; execution.go(onOp); execution.finalize(); d.excepted = er.excepted; d.result = er; d.machineStates = machineStates; d.executionCode = std::move(codes); d.transactionData = std::move(data); d.gasUsed = er.gasUsed + er.gasRefunded + c_callStipend; if (_t.isCreation()) d.contractAddress = right160(sha3(rlpList(_t.sender(), _t.nonce()))); return d; } void MixClient::executeTransaction(Transaction const& _t, Block& _block, bool _call, bool _gasAuto, Secret const& _secret) { Transaction t = _gasAuto ? replaceGas(_t, m_postMine.gasLimitRemaining()) : _t; // do debugging run first EnvInfo envInfo(bc().info(), bc().lastHashes()); ExecutionResult d = debugTransaction(t, _block.state(), envInfo, _call); // execute on a state if (!_call && d.excepted == TransactionException::None) { u256 useGas = min(d.gasUsed, _block.gasLimitRemaining()); t = _gasAuto ? replaceGas(_t, useGas, _secret) : _t; eth::ExecutionResult const& er = _block.execute(envInfo.lastHashes(), t); if (t.isCreation() && _block.state().code(d.contractAddress).empty()) BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas for contract deployment")); d.gasUsed = er.gasUsed + er.gasRefunded + er.gasForDeposit + c_callStipend; LocalisedLogEntries logs; TransactionReceipt const& tr = _block.receipt(_block.pending().size() - 1); LogEntries le = tr.log(); if (le.size()) for (unsigned j = 0; j < le.size(); ++j) logs.insert(logs.begin(), LocalisedLogEntry(le[j])); d.logs = logs; } WriteGuard l(x_executions); m_executions.emplace_back(std::move(d)); } void MixClient::mine() { WriteGuard l(x_state); m_postMine.commitToSeal(bc()); NoProof::BlockHeader h(m_postMine.info()); RLPStream header; h.streamRLP(header); m_postMine.sealBlock(header.out()); bc().import(m_postMine.blockData(), m_stateDB, (ImportRequirements::Everything & ~ImportRequirements::ValidSeal) != 0); m_postMine.sync(bc()); m_preMine = m_postMine; } ExecutionResult MixClient::lastExecution() const { ReadGuard l(x_executions); return m_executions.empty() ? ExecutionResult() : m_executions.back(); } ExecutionResult MixClient::execution(unsigned _index) const { ReadGuard l(x_executions); return m_executions.at(_index); } Block MixClient::asOf(h256 const& _block) const { ReadGuard l(x_state); Block ret(m_stateDB); ret.populateFromChain(bc(), _block); return ret; } pair<h256, Address> MixClient::submitTransaction(eth::TransactionSkeleton const& _ts, Secret const& _secret, bool _gasAuto) { WriteGuard l(x_state); TransactionSkeleton ts = _ts; ts.from = toAddress(_secret); ts.nonce = m_postMine.transactionsFrom(ts.from); eth::Transaction t(ts, _secret); executeTransaction(t, m_postMine, false, _gasAuto, _secret); return make_pair(t.sha3(), toAddress(ts.from, ts.nonce)); } dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, bool _gasAuto, FudgeFactor _ff) { (void)_blockNumber; Block block = asOf(eth::PendingBlock); u256 n = block.transactionsFrom(_from); Transaction t(_value, _gasPrice, _gas, _dest, _data, n); t.forceSender(_from); if (_ff == FudgeFactor::Lenient) block.mutableState().addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); WriteGuard lw(x_state); //TODO: lock is required only for last execution state executeTransaction(t, block, true, _gasAuto); return lastExecution().result; } dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) { return call(_from, _value, _dest, _data, _gas, _gasPrice, _blockNumber, false, _ff); } dev::eth::ExecutionResult MixClient::create(Address const& _from, u256 _value, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) { (void)_blockNumber; u256 n; Block temp; { ReadGuard lr(x_state); temp = asOf(eth::PendingBlock); n = temp.transactionsFrom(_from); } Transaction t(_value, _gasPrice, _gas, _data, n); t.forceSender(_from); if (_ff == FudgeFactor::Lenient) temp.mutableState().addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); WriteGuard lw(x_state); //TODO: lock is required only for last execution state executeTransaction(t, temp, true, false); return lastExecution().result; } eth::BlockInfo MixClient::blockInfo() const { ReadGuard l(x_state); return BlockInfo(bc().block()); } void MixClient::setBeneficiary(Address _us) { WriteGuard l(x_state); m_postMine.setBeneficiary(_us); } void MixClient::startMining() { //no-op } void MixClient::stopMining() { //no-op } bool MixClient::isMining() const { return false; } uint64_t MixClient::hashrate() const { return 0; } eth::WorkingProgress MixClient::miningProgress() const { return eth::WorkingProgress(); } } } <commit_msg>fixed block mining<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file MixClient.cpp * @author Arkadiy Paronyan arkadiy@ethdev.com * @date 2015 * Ethereum IDE client. */ #include "MixClient.h" #include <vector> #include <utility> #include <libdevcore/Exceptions.h> #include <libethcore/Params.h> #include <libethcore/BasicAuthority.h> #include <libethereum/CanonBlockChain.h> #include <libethereum/Transaction.h> #include <libethereum/Executive.h> #include <libethereum/ExtVM.h> #include <libethereum/BlockChain.h> #include <libevm/VM.h> #include "Exceptions.h" using namespace std; using namespace dev; using namespace dev::eth; namespace dev { namespace mix { u256 const c_mixGenesisDifficulty = 131072; //TODO: make it lower for Mix somehow namespace { } MixBlockChain::MixBlockChain(std::string const& _path, h256 _stateRoot): FullBlockChain<NoProof>(createGenesisBlock(_stateRoot), std::unordered_map<Address, Account>(), _path, WithExisting::Kill) { } bytes MixBlockChain::createGenesisBlock(h256 _stateRoot) { RLPStream block(3); block.appendList(13) << h256() << EmptyListSHA3 << h160() << _stateRoot << EmptyTrie << EmptyTrie << LogBloom() << c_mixGenesisDifficulty << 0 << 3141592 << 0 << (unsigned)0 << std::string(); block.appendRaw(RLPEmptyList); block.appendRaw(RLPEmptyList); return block.out(); } MixClient::MixClient(std::string const& _dbPath): m_dbPath(_dbPath) { resetState(std::unordered_map<Address, Account>()); } MixClient::~MixClient() { } void MixClient::resetState(std::unordered_map<Address, Account> const& _accounts, Secret const& _miner) { WriteGuard l(x_state); Guard fl(x_filtersWatches); m_filters.clear(); for (auto& i: m_specialFilters) i.second.clear(); m_watches.clear(); m_stateDB = OverlayDB(); SecureTrieDB<Address, MemoryDB> accountState(&m_stateDB); accountState.init(); dev::eth::commit(_accounts, accountState); h256 stateRoot = accountState.root(); m_bc.reset(); m_bc.reset(new MixBlockChain(m_dbPath, stateRoot)); Block b(m_stateDB, BaseState::PreExisting, KeyPair(_miner).address()); b.sync(bc()); m_preMine = b; m_postMine = b; WriteGuard lx(x_executions); m_executions.clear(); } Transaction MixClient::replaceGas(Transaction const& _t, u256 const& _gas, Secret const& _secret) { Transaction ret; if (_secret) { if (_t.isCreation()) ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce(), _secret); else ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce(), _secret); } else { if (_t.isCreation()) ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce()); else ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce()); ret.forceSender(_t.safeSender()); } return ret; } // TODO: prototype changed - will need rejigging. ExecutionResult MixClient::debugTransaction(Transaction const& _t, State const& _state, EnvInfo const& _envInfo, bool _call) { State execState = _state; execState.addBalance(_t.sender(), _t.gas() * _t.gasPrice()); //give it enough balance for gas estimation eth::ExecutionResult er; Executive execution(execState, _envInfo); execution.setResultRecipient(er); ExecutionResult d; d.address = _t.receiveAddress(); d.sender = _t.sender(); d.value = _t.value(); d.inputParameters = _t.data(); d.executonIndex = m_executions.size(); if (!_call) d.transactionIndex = m_postMine.pending().size(); try { execution.initialize(_t); execution.execute(); } catch (Exception const& _e) { d.excepted = toTransactionException(_e); d.transactionData.push_back(_t.data()); return d; } std::vector<MachineState> machineStates; std::vector<unsigned> levels; std::vector<MachineCode> codes; std::map<bytes const*, unsigned> codeIndexes; std::vector<bytes> data; std::map<bytesConstRef const*, unsigned> dataIndexes; bytes const* lastCode = nullptr; bytesConstRef const* lastData = nullptr; unsigned codeIndex = 0; unsigned dataIndex = 0; auto onOp = [&](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, void* voidVM, void const* voidExt) { VM& vm = *static_cast<VM*>(voidVM); ExtVM const& ext = *static_cast<ExtVM const*>(voidExt); if (lastCode == nullptr || lastCode != &ext.code) { auto const& iter = codeIndexes.find(&ext.code); if (iter != codeIndexes.end()) codeIndex = iter->second; else { codeIndex = codes.size(); codes.push_back(MachineCode({ext.myAddress, ext.code})); codeIndexes[&ext.code] = codeIndex; } lastCode = &ext.code; } if (lastData == nullptr || lastData != &ext.data) { auto const& iter = dataIndexes.find(&ext.data); if (iter != dataIndexes.end()) dataIndex = iter->second; else { dataIndex = data.size(); data.push_back(ext.data.toBytes()); dataIndexes[&ext.data] = dataIndex; } lastData = &ext.data; } if (levels.size() < ext.depth) levels.push_back(machineStates.size() - 1); else levels.resize(ext.depth); machineStates.push_back(MachineState{ steps, vm.curPC(), inst, newMemSize, static_cast<u256>(gas), vm.stack(), vm.memory(), gasCost, ext.state().storage(ext.myAddress), std::move(levels), codeIndex, dataIndex }); }; execution.go(onOp); execution.finalize(); d.excepted = er.excepted; d.result = er; d.machineStates = machineStates; d.executionCode = std::move(codes); d.transactionData = std::move(data); d.gasUsed = er.gasUsed + er.gasRefunded + c_callStipend; if (_t.isCreation()) d.contractAddress = right160(sha3(rlpList(_t.sender(), _t.nonce()))); return d; } void MixClient::executeTransaction(Transaction const& _t, Block& _block, bool _call, bool _gasAuto, Secret const& _secret) { Transaction t = _gasAuto ? replaceGas(_t, m_postMine.gasLimitRemaining()) : _t; // do debugging run first EnvInfo envInfo(bc().info(), bc().lastHashes()); ExecutionResult d = debugTransaction(t, _block.state(), envInfo, _call); // execute on a state if (!_call && d.excepted == TransactionException::None) { u256 useGas = min(d.gasUsed, _block.gasLimitRemaining()); t = _gasAuto ? replaceGas(_t, useGas, _secret) : _t; eth::ExecutionResult const& er = _block.execute(envInfo.lastHashes(), t); if (t.isCreation() && _block.state().code(d.contractAddress).empty()) BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas for contract deployment")); d.gasUsed = er.gasUsed + er.gasRefunded + er.gasForDeposit + c_callStipend; LocalisedLogEntries logs; TransactionReceipt const& tr = _block.receipt(_block.pending().size() - 1); LogEntries le = tr.log(); if (le.size()) for (unsigned j = 0; j < le.size(); ++j) logs.insert(logs.begin(), LocalisedLogEntry(le[j])); d.logs = logs; } WriteGuard l(x_executions); m_executions.emplace_back(std::move(d)); } void MixClient::mine() { WriteGuard l(x_state); m_postMine.commitToSeal(bc()); NoProof::BlockHeader h(m_postMine.info()); RLPStream header; h.streamRLP(header); m_postMine.sealBlock(header.out()); bc().import(m_postMine.blockData(), m_postMine.state().db(), (ImportRequirements::Everything & ~ImportRequirements::ValidSeal) != 0); m_postMine.sync(bc()); m_preMine = m_postMine; } ExecutionResult MixClient::lastExecution() const { ReadGuard l(x_executions); return m_executions.empty() ? ExecutionResult() : m_executions.back(); } ExecutionResult MixClient::execution(unsigned _index) const { ReadGuard l(x_executions); return m_executions.at(_index); } Block MixClient::asOf(h256 const& _block) const { ReadGuard l(x_state); Block ret(m_stateDB); ret.populateFromChain(bc(), _block); return ret; } pair<h256, Address> MixClient::submitTransaction(eth::TransactionSkeleton const& _ts, Secret const& _secret, bool _gasAuto) { WriteGuard l(x_state); TransactionSkeleton ts = _ts; ts.from = toAddress(_secret); ts.nonce = m_postMine.transactionsFrom(ts.from); eth::Transaction t(ts, _secret); executeTransaction(t, m_postMine, false, _gasAuto, _secret); return make_pair(t.sha3(), toAddress(ts.from, ts.nonce)); } dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, bool _gasAuto, FudgeFactor _ff) { (void)_blockNumber; Block block = asOf(eth::PendingBlock); u256 n = block.transactionsFrom(_from); Transaction t(_value, _gasPrice, _gas, _dest, _data, n); t.forceSender(_from); if (_ff == FudgeFactor::Lenient) block.mutableState().addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); WriteGuard lw(x_state); //TODO: lock is required only for last execution state executeTransaction(t, block, true, _gasAuto); return lastExecution().result; } dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) { return call(_from, _value, _dest, _data, _gas, _gasPrice, _blockNumber, false, _ff); } dev::eth::ExecutionResult MixClient::create(Address const& _from, u256 _value, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) { (void)_blockNumber; u256 n; Block temp; { ReadGuard lr(x_state); temp = asOf(eth::PendingBlock); n = temp.transactionsFrom(_from); } Transaction t(_value, _gasPrice, _gas, _data, n); t.forceSender(_from); if (_ff == FudgeFactor::Lenient) temp.mutableState().addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); WriteGuard lw(x_state); //TODO: lock is required only for last execution state executeTransaction(t, temp, true, false); return lastExecution().result; } eth::BlockInfo MixClient::blockInfo() const { ReadGuard l(x_state); return BlockInfo(bc().block()); } void MixClient::setBeneficiary(Address _us) { WriteGuard l(x_state); m_postMine.setBeneficiary(_us); } void MixClient::startMining() { //no-op } void MixClient::stopMining() { //no-op } bool MixClient::isMining() const { return false; } uint64_t MixClient::hashrate() const { return 0; } eth::WorkingProgress MixClient::miningProgress() const { return eth::WorkingProgress(); } } } <|endoftext|>
<commit_before>/* * Copyright © 2011-2012 Stéphane Raimbault <stephane.raimbault@gmail.com> * * License ISC, see LICENSE for more details. * * This library implements the Modbus protocol. * http://libmodbus.org/ * */ #include <inttypes.h> #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #include <pins_arduino.h> #endif #include "Modbusino.h" #define _MODBUS_RTU_SLAVE 0 #define _MODBUS_RTU_FUNCTION 1 #define _MODBUS_RTU_PRESET_REQ_LENGTH 6 #define _MODBUS_RTU_PRESET_RSP_LENGTH 2 #define _MODBUS_RTU_CHECKSUM_LENGTH 2 #define _MODBUSINO_RTU_MAX_ADU_LENGTH 128 /* Supported function codes */ #define _FC_READ_HOLDING_REGISTERS 0x03 #define _FC_WRITE_MULTIPLE_REGISTERS 0x10 enum { _STEP_FUNCTION = 0x01, _STEP_META, _STEP_DATA }; static uint16_t crc16(uint8_t *req, uint8_t req_length) { uint8_t j; uint16_t crc; crc = 0xFFFF; while (req_length--) { crc = crc ^ *req++; for (j = 0; j < 8; j++) { if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001; else crc = crc >> 1; } } return (crc << 8 | crc >> 8); } ModbusinoSlave::ModbusinoSlave(uint8_t slave) { if (slave >= 0 & slave <= 247) { _slave = slave; } } void ModbusinoSlave::setup(long baud) { Serial.begin(baud); } static int check_integrity(uint8_t *msg, uint8_t msg_length) { uint16_t crc_calculated; uint16_t crc_received; if (msg_length < 2) return -1; crc_calculated = crc16(msg, msg_length - 2); crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1]; /* Check CRC of msg */ if (crc_calculated == crc_received) { return msg_length; } else { return -1; } } static int build_response_basis(uint8_t slave, uint8_t function, uint8_t *rsp) { rsp[0] = slave; rsp[1] = function; return _MODBUS_RTU_PRESET_RSP_LENGTH; } static void send_msg(uint8_t *msg, uint8_t msg_length) { uint16_t crc = crc16(msg, msg_length); msg[msg_length++] = crc >> 8; msg[msg_length++] = crc & 0x00FF; Serial.write(msg, msg_length); } static uint8_t response_exception(uint8_t slave, uint8_t function, uint8_t exception_code, uint8_t *rsp) { uint8_t rsp_length; rsp_length = build_response_basis(slave, function + 0x80, rsp); /* Positive exception code */ rsp[rsp_length++] = exception_code; return rsp_length; } static void flush(void) { uint8_t i = 0; /* Wait a moment to receive the remaining garbage but avoid getting stuck * because the line is saturated */ while (Serial.available() && i++ < 10) { Serial.flush(); delay(3); } } static int receive(uint8_t *req, uint8_t _slave) { uint8_t i; uint8_t length_to_read; uint8_t req_index; uint8_t step; uint8_t function; /* We need to analyse the message step by step. At the first step, we want * to reach the function code because all packets contain this * information. */ step = _STEP_FUNCTION; length_to_read = _MODBUS_RTU_FUNCTION + 1; req_index = 0; while (length_to_read != 0) { /* The timeout is defined to ~10 ms between each bytes. Precision is not that important so I rather to avoid millis() to apply the KISS principle (millis overflows after 50 days, etc) */ if (!Serial.available()) { i = 0; while (!Serial.available()) { if (++i == 10) { /* Too late, bye */ return -1 - MODBUS_INFORMATIVE_RX_TIMEOUT; } delay(1); } } req[req_index] = Serial.read(); /* Moves the pointer to receive other data */ req_index++; /* Computes remaining bytes */ length_to_read--; if (length_to_read == 0) { if (req[_MODBUS_RTU_SLAVE] != _slave && req[_MODBUS_RTU_SLAVE != MODBUS_BROADCAST_ADDRESS]) { flush(); return -1 - MODBUS_INFORMATIVE_NOT_FOR_US; } switch (step) { case _STEP_FUNCTION: /* Function code position */ function = req[_MODBUS_RTU_FUNCTION]; if (function == _FC_READ_HOLDING_REGISTERS) { length_to_read = 4; } else if (function == _FC_WRITE_MULTIPLE_REGISTERS) { length_to_read = 5; } else { /* Wait a moment to receive the remaining garbage */ flush(); if (req[_MODBUS_RTU_SLAVE] == _slave || req[_MODBUS_RTU_SLAVE] == MODBUS_BROADCAST_ADDRESS) { /* It's for me so send an exception (reuse req) */ uint8_t rsp_length = response_exception( _slave, function, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, req); send_msg(req, rsp_length); return -1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION; } return -1; } step = _STEP_META; break; case _STEP_META: length_to_read = _MODBUS_RTU_CHECKSUM_LENGTH; if (function == _FC_WRITE_MULTIPLE_REGISTERS) length_to_read += req[_MODBUS_RTU_FUNCTION + 5]; if ((req_index + length_to_read) > _MODBUSINO_RTU_MAX_ADU_LENGTH) { flush(); if (req[_MODBUS_RTU_SLAVE] == _slave || req[_MODBUS_RTU_SLAVE] == MODBUS_BROADCAST_ADDRESS) { /* It's for me so send an exception (reuse req) */ uint8_t rsp_length = response_exception( _slave, function, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, req); send_msg(req, rsp_length); return -1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION; } return -1; } step = _STEP_DATA; break; default: break; } } } return check_integrity(req, req_index); } static void reply(uint16_t *tab_reg, uint16_t nb_reg, uint8_t *req, uint8_t req_length, uint8_t _slave) { uint8_t slave = req[_MODBUS_RTU_SLAVE]; uint8_t function = req[_MODBUS_RTU_FUNCTION]; uint16_t address = (req[_MODBUS_RTU_FUNCTION + 1] << 8) + req[_MODBUS_RTU_FUNCTION + 2]; uint16_t nb = (req[_MODBUS_RTU_FUNCTION + 3] << 8) + req[_MODBUS_RTU_FUNCTION + 4]; uint8_t rsp[_MODBUSINO_RTU_MAX_ADU_LENGTH]; uint8_t rsp_length = 0; if (slave != _slave && slave != MODBUS_BROADCAST_ADDRESS) { return; } if (address + nb > nb_reg) { rsp_length = response_exception( slave, function, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp); } else { req_length -= _MODBUS_RTU_CHECKSUM_LENGTH; if (function == _FC_READ_HOLDING_REGISTERS) { uint16_t i; rsp_length = build_response_basis(slave, function, rsp); rsp[rsp_length++] = nb << 1; for (i = address; i < address + nb; i++) { rsp[rsp_length++] = tab_reg[i] >> 8; rsp[rsp_length++] = tab_reg[i] & 0xFF; } } else { uint16_t i, j; for (i = address, j = 6; i < address + nb; i++, j += 2) { /* 6 and 7 = first value */ tab_reg[i] = (req[_MODBUS_RTU_FUNCTION + j] << 8) + req[_MODBUS_RTU_FUNCTION + j + 1]; } rsp_length = build_response_basis(slave, function, rsp); /* 4 to copy the address (2) and the no. of registers */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } send_msg(rsp, rsp_length); } int ModbusinoSlave::loop(uint16_t *tab_reg, uint16_t nb_reg) { int rc = 0; uint8_t req[_MODBUSINO_RTU_MAX_ADU_LENGTH]; if (Serial.available()) { rc = receive(req, _slave); if (rc > 0) { reply(tab_reg, nb_reg, req, rc, _slave); } } /* Returns a positive value if successful, 0 if a slave filtering has occured, -1 if an undefined error has occured, -2 for MODBUS_EXCEPTION_ILLEGAL_FUNCTION etc */ return rc; } <commit_msg>Increase ADU size to 256 for conformance (closes #6)<commit_after>/* * Copyright © 2011-2012 Stéphane Raimbault <stephane.raimbault@gmail.com> * * License ISC, see LICENSE for more details. * * This library implements the Modbus protocol. * http://libmodbus.org/ * */ #include <inttypes.h> #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #include <pins_arduino.h> #endif #include "Modbusino.h" #define _MODBUS_RTU_SLAVE 0 #define _MODBUS_RTU_FUNCTION 1 #define _MODBUS_RTU_PRESET_REQ_LENGTH 6 #define _MODBUS_RTU_PRESET_RSP_LENGTH 2 #define _MODBUS_RTU_CHECKSUM_LENGTH 2 /* As reported in https://github.com/stephane/modbusino/issues/6, the code could segfault for longer ADU */ #define _MODBUSINO_RTU_MAX_ADU_LENGTH 256 /* Supported function codes */ #define _FC_READ_HOLDING_REGISTERS 0x03 #define _FC_WRITE_MULTIPLE_REGISTERS 0x10 enum { _STEP_FUNCTION = 0x01, _STEP_META, _STEP_DATA }; static uint16_t crc16(uint8_t *req, uint8_t req_length) { uint8_t j; uint16_t crc; crc = 0xFFFF; while (req_length--) { crc = crc ^ *req++; for (j = 0; j < 8; j++) { if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001; else crc = crc >> 1; } } return (crc << 8 | crc >> 8); } ModbusinoSlave::ModbusinoSlave(uint8_t slave) { if (slave >= 0 & slave <= 247) { _slave = slave; } } void ModbusinoSlave::setup(long baud) { Serial.begin(baud); } static int check_integrity(uint8_t *msg, uint8_t msg_length) { uint16_t crc_calculated; uint16_t crc_received; if (msg_length < 2) return -1; crc_calculated = crc16(msg, msg_length - 2); crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1]; /* Check CRC of msg */ if (crc_calculated == crc_received) { return msg_length; } else { return -1; } } static int build_response_basis(uint8_t slave, uint8_t function, uint8_t *rsp) { rsp[0] = slave; rsp[1] = function; return _MODBUS_RTU_PRESET_RSP_LENGTH; } static void send_msg(uint8_t *msg, uint8_t msg_length) { uint16_t crc = crc16(msg, msg_length); msg[msg_length++] = crc >> 8; msg[msg_length++] = crc & 0x00FF; Serial.write(msg, msg_length); } static uint8_t response_exception(uint8_t slave, uint8_t function, uint8_t exception_code, uint8_t *rsp) { uint8_t rsp_length; rsp_length = build_response_basis(slave, function + 0x80, rsp); /* Positive exception code */ rsp[rsp_length++] = exception_code; return rsp_length; } static void flush(void) { uint8_t i = 0; /* Wait a moment to receive the remaining garbage but avoid getting stuck * because the line is saturated */ while (Serial.available() && i++ < 10) { Serial.flush(); delay(3); } } static int receive(uint8_t *req, uint8_t _slave) { uint8_t i; uint8_t length_to_read; uint8_t req_index; uint8_t step; uint8_t function; /* We need to analyse the message step by step. At the first step, we want * to reach the function code because all packets contain this * information. */ step = _STEP_FUNCTION; length_to_read = _MODBUS_RTU_FUNCTION + 1; req_index = 0; while (length_to_read != 0) { /* The timeout is defined to ~10 ms between each bytes. Precision is not that important so I rather to avoid millis() to apply the KISS principle (millis overflows after 50 days, etc) */ if (!Serial.available()) { i = 0; while (!Serial.available()) { if (++i == 10) { /* Too late, bye */ return -1 - MODBUS_INFORMATIVE_RX_TIMEOUT; } delay(1); } } req[req_index] = Serial.read(); /* Moves the pointer to receive other data */ req_index++; /* Computes remaining bytes */ length_to_read--; if (length_to_read == 0) { if (req[_MODBUS_RTU_SLAVE] != _slave && req[_MODBUS_RTU_SLAVE != MODBUS_BROADCAST_ADDRESS]) { flush(); return -1 - MODBUS_INFORMATIVE_NOT_FOR_US; } switch (step) { case _STEP_FUNCTION: /* Function code position */ function = req[_MODBUS_RTU_FUNCTION]; if (function == _FC_READ_HOLDING_REGISTERS) { length_to_read = 4; } else if (function == _FC_WRITE_MULTIPLE_REGISTERS) { length_to_read = 5; } else { /* Wait a moment to receive the remaining garbage */ flush(); if (req[_MODBUS_RTU_SLAVE] == _slave || req[_MODBUS_RTU_SLAVE] == MODBUS_BROADCAST_ADDRESS) { /* It's for me so send an exception (reuse req) */ uint8_t rsp_length = response_exception( _slave, function, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, req); send_msg(req, rsp_length); return -1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION; } return -1; } step = _STEP_META; break; case _STEP_META: length_to_read = _MODBUS_RTU_CHECKSUM_LENGTH; if (function == _FC_WRITE_MULTIPLE_REGISTERS) length_to_read += req[_MODBUS_RTU_FUNCTION + 5]; if ((req_index + length_to_read) > _MODBUSINO_RTU_MAX_ADU_LENGTH) { flush(); if (req[_MODBUS_RTU_SLAVE] == _slave || req[_MODBUS_RTU_SLAVE] == MODBUS_BROADCAST_ADDRESS) { /* It's for me so send an exception (reuse req) */ uint8_t rsp_length = response_exception( _slave, function, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, req); send_msg(req, rsp_length); return -1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION; } return -1; } step = _STEP_DATA; break; default: break; } } } return check_integrity(req, req_index); } static void reply(uint16_t *tab_reg, uint16_t nb_reg, uint8_t *req, uint8_t req_length, uint8_t _slave) { uint8_t slave = req[_MODBUS_RTU_SLAVE]; uint8_t function = req[_MODBUS_RTU_FUNCTION]; uint16_t address = (req[_MODBUS_RTU_FUNCTION + 1] << 8) + req[_MODBUS_RTU_FUNCTION + 2]; uint16_t nb = (req[_MODBUS_RTU_FUNCTION + 3] << 8) + req[_MODBUS_RTU_FUNCTION + 4]; uint8_t rsp[_MODBUSINO_RTU_MAX_ADU_LENGTH]; uint8_t rsp_length = 0; if (slave != _slave && slave != MODBUS_BROADCAST_ADDRESS) { return; } if (address + nb > nb_reg) { rsp_length = response_exception( slave, function, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp); } else { req_length -= _MODBUS_RTU_CHECKSUM_LENGTH; if (function == _FC_READ_HOLDING_REGISTERS) { uint16_t i; rsp_length = build_response_basis(slave, function, rsp); rsp[rsp_length++] = nb << 1; for (i = address; i < address + nb; i++) { rsp[rsp_length++] = tab_reg[i] >> 8; rsp[rsp_length++] = tab_reg[i] & 0xFF; } } else { uint16_t i, j; for (i = address, j = 6; i < address + nb; i++, j += 2) { /* 6 and 7 = first value */ tab_reg[i] = (req[_MODBUS_RTU_FUNCTION + j] << 8) + req[_MODBUS_RTU_FUNCTION + j + 1]; } rsp_length = build_response_basis(slave, function, rsp); /* 4 to copy the address (2) and the no. of registers */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } send_msg(rsp, rsp_length); } int ModbusinoSlave::loop(uint16_t *tab_reg, uint16_t nb_reg) { int rc = 0; uint8_t req[_MODBUSINO_RTU_MAX_ADU_LENGTH]; if (Serial.available()) { rc = receive(req, _slave); if (rc > 0) { reply(tab_reg, nb_reg, req, rc, _slave); } } /* Returns a positive value if successful, 0 if a slave filtering has occured, -1 if an undefined error has occured, -2 for MODBUS_EXCEPTION_ILLEGAL_FUNCTION etc */ return rc; } <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file JSLocalConsole.cpp * @author Marek Kotewicz <marek@ethdev.com> * @date 2015 * Ethereum client. */ #include <iostream> #include <libweb3jsonrpc/WebThreeStubServer.h> #include "JSLocalConsole.h" #include "JSV8Connector.h" using namespace std; using namespace dev; using namespace dev::eth; JSLocalConsole::JSLocalConsole() { m_jsonrpcConnector.reset(new JSV8Connector(m_engine)); // m_jsonrpcServer.reset(new WebThreeStubServer(*m_jsonrpcConnector.get(), _web3, _accounts, vector<KeyPair>())); } <commit_msg>removed unused commented line<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file JSLocalConsole.cpp * @author Marek Kotewicz <marek@ethdev.com> * @date 2015 * Ethereum client. */ #include <iostream> #include <libweb3jsonrpc/WebThreeStubServer.h> #include "JSLocalConsole.h" #include "JSV8Connector.h" using namespace std; using namespace dev; using namespace dev::eth; JSLocalConsole::JSLocalConsole() { m_jsonrpcConnector.reset(new JSV8Connector(m_engine)); } <|endoftext|>
<commit_before>/* ModbusIP.cpp - Source for Modbus IP Library Copyright (C) 2015 Andr Sarmento Barbosa */ #include "ModbusIP.h" ModbusIP::ModbusIP():_server(MODBUSIP_PORT) { } bool ModbusIP::config(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet) { Ethernet.begin(mac, ip); _server.begin(); return true; } void ModbusIP::proc() { EthernetClient client = _server.available(); if (client) { if (client.connected()) { int i = 0; while (client.available()){ _MBAP[i] = client.read(); i++; if (i==7) break; //MBAP length has 7 bytes size } _len = _MBAP[4] << 8 | _MBAP[5]; _len--; // Do not count with last byte from MBAP if (_MBAP[2] !=0 | _MBAP[3] !=0) return; //Not a MODBUSIP packet if (_len > MODBUSIP_MAXFRAME) return; //Length is over MODBUSIP_MAXFRAME _frame = (byte*) malloc(_len); i = 0; while (client.available()){ _frame[i] = client.read(); i++; if (i==_len) break; } if (this->receivePDU(_frame) && _reply != MB_REPLY_OFF) { //MBAP _MBAP[4] = _len >> 8; _MBAP[5] = _len | 0x00FF; for (i = 0 ; i < 7 ; i++) { client.write(_MBAP[i]); } //PDU Frame for (i = 0 ; i < _len ; i++) { client.write(_frame[i]); } } free(_frame); _len = 0; client.stop(); } } } <commit_msg>Overloaded config types. receivePDU to void.<commit_after>/* ModbusIP.cpp - Source for Modbus IP Library Copyright (C) 2015 Andr Sarmento Barbosa */ #include "ModbusIP.h" ModbusIP::ModbusIP():_server(MODBUSIP_PORT) { _server.begin(); } void ModbusIP::config(uint8_t *mac) { Ethernet.begin(mac); } void ModbusIP::config(uint8_t *mac, IPAddress ip) { Ethernet.begin(mac, ip); } void ModbusIP::config(uint8_t *mac, IPAddress ip, IPAddress dns) { Ethernet.begin(mac, ip, dns); } void ModbusIP::config(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway) { Ethernet.begin(mac, ip, dns, gateway); } void ModbusIP::config(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet) { Ethernet.begin(mac, ip, dns, gateway, subnet); } void ModbusIP::task() { EthernetClient client = _server.available(); if (client) { if (client.connected()) { int i = 0; while (client.available()){ _MBAP[i] = client.read(); i++; if (i==7) break; //MBAP length has 7 bytes size } _len = _MBAP[4] << 8 | _MBAP[5]; _len--; // Do not count with last byte from MBAP if (_MBAP[2] !=0 | _MBAP[3] !=0) return; //Not a MODBUSIP packet if (_len > MODBUSIP_MAXFRAME) return; //Length is over MODBUSIP_MAXFRAME _frame = (byte*) malloc(_len); i = 0; while (client.available()){ _frame[i] = client.read(); i++; if (i==_len) break; } this->receivePDU(_frame); if (_reply != MB_REPLY_OFF) { //MBAP _MBAP[4] = _len >> 8; _MBAP[5] = _len | 0x00FF; for (i = 0 ; i < 7 ; i++) { client.write(_MBAP[i]); } //PDU Frame for (i = 0 ; i < _len ; i++) { client.write(_frame[i]); } } free(_frame); _len = 0; client.stop(); } } } <|endoftext|>
<commit_before>#pragma once //=========================================================================// /*! @file @brief RX24T グループ・DOC 定義 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017, 2022 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=========================================================================// #include "common/device.hpp" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief データ演算回路(DOC) @param[in] base ベース・アドレス @param[in] per ペリフェラル型 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral per> struct doc_t { static constexpr auto PERIPHERAL = per; ///< ペリフェラル型 //-----------------------------------------------------------------// /*! @brief DOC コントロールレジスタ(DOCR) @param[in] ofs オフセット */ //-----------------------------------------------------------------// template <uint32_t ofs> struct docr_t : public rw8_t<ofs> { typedef rw8_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 2> OMS; bit_rw_t <io_, bitpos::B2> DCSEL; bit_rw_t <io_, bitpos::B4> DOPCIE; bit_rw_t <io_, bitpos::B5> DOPCF; bit_rw_t <io_, bitpos::B6> DOPCFCL; }; typedef docr_t<base + 0x00> DOCR_; static DOCR_ DOCR; //-----------------------------------------------------------------// /*! @brief DOC データインプットレジスタ(DODIR) */ //-----------------------------------------------------------------// typedef rw16_t<base + 0x02> DODIR_; static DODIR_ DODIR; //-----------------------------------------------------------------// /*! @brief DOC データセッティングレジスタ(DODSR) */ //-----------------------------------------------------------------// typedef rw16_t<base + 0x04> DODSR_; static DODSR_ DODSR; }; template <uint32_t base, peripheral per> typename doc_t<base, per>::DOCR_ doc_t<base, per>::DOCR; template <uint32_t base, peripheral per> typename doc_t<base, per>::DODIR_ doc_t<base, per>::DODIR; template <uint32_t base, peripheral per> typename doc_t<base, per>::DODSR_ doc_t<base, per>::DODSR; #if defined(SIG_RX24T) //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief データ演算回路(DOC) @param[in] base ベース・アドレス @param[in] vec 割り込みベクター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral per, ICU::VECTOR vec> struct doc_norm_t : public doc_t<base, per> { static constexpr auto I_VEC = vec; ///< 割り込みベクター }; typedef doc_norm_t<0x0008'B080, peripheral::DOC, ICU::VECTOR::DOPCF> DOC; #endif #if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) || defined(SIG_RX66T) || defined(SIG_RX72T) //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief データ演算回路(DOC) @param[in] base ベース・アドレス @param[in] vec 割り込みベクター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral per, ICU::VECTOR_BL0 vec> struct doc_gbl0_t : public doc_t<base, per> { static constexpr auto I_VEC = vec; ///< 割り込みベクター }; typedef doc_gbl0_t<0x0008'B080, peripheral::DOC, ICU::VECTOR_BL0::DOPCI> DOC; #endif } <commit_msg>Update: Add RX63T<commit_after>#pragma once //=========================================================================// /*! @file @brief RX600 グループ・DOC 定義 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017, 2022 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=========================================================================// #include "common/device.hpp" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief データ演算回路(DOC) @param[in] base ベース・アドレス @param[in] per ペリフェラル型 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral per> struct doc_t { static constexpr auto PERIPHERAL = per; ///< ペリフェラル型 //-----------------------------------------------------------------// /*! @brief DOC コントロールレジスタ(DOCR) @param[in] ofs オフセット */ //-----------------------------------------------------------------// template <uint32_t ofs> struct docr_t : public rw8_t<ofs> { typedef rw8_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 2> OMS; bit_rw_t <io_, bitpos::B2> DCSEL; bit_rw_t <io_, bitpos::B4> DOPCIE; bit_rw_t <io_, bitpos::B5> DOPCF; bit_rw_t <io_, bitpos::B6> DOPCFCL; }; typedef docr_t<base + 0x00> DOCR_; static DOCR_ DOCR; //-----------------------------------------------------------------// /*! @brief DOC データインプットレジスタ(DODIR) */ //-----------------------------------------------------------------// typedef rw16_t<base + 0x02> DODIR_; static DODIR_ DODIR; //-----------------------------------------------------------------// /*! @brief DOC データセッティングレジスタ(DODSR) */ //-----------------------------------------------------------------// typedef rw16_t<base + 0x04> DODSR_; static DODSR_ DODSR; }; template <uint32_t base, peripheral per> typename doc_t<base, per>::DOCR_ doc_t<base, per>::DOCR; template <uint32_t base, peripheral per> typename doc_t<base, per>::DODIR_ doc_t<base, per>::DODIR; template <uint32_t base, peripheral per> typename doc_t<base, per>::DODSR_ doc_t<base, per>::DODSR; #if defined(SIG_RX63T) || defined(SIG_RX24T) //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief データ演算回路(DOC) @param[in] base ベース・アドレス @param[in] vec 割り込みベクター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral per, ICU::VECTOR vec> struct doc_norm_t : public doc_t<base, per> { static constexpr auto I_VEC = vec; ///< 割り込みベクター }; typedef doc_norm_t<0x0008'B080, peripheral::DOC, ICU::VECTOR::DOPCF> DOC; #endif #if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) || defined(SIG_RX66T) || defined(SIG_RX72T) //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief データ演算回路(DOC) @param[in] base ベース・アドレス @param[in] vec 割り込みベクター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral per, ICU::VECTOR_BL0 vec> struct doc_gbl0_t : public doc_t<base, per> { static constexpr auto I_VEC = vec; ///< 割り込みベクター }; typedef doc_gbl0_t<0x0008'B080, peripheral::DOC, ICU::VECTOR_BL0::DOPCI> DOC; #endif } <|endoftext|>
<commit_before>/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // #define VERBOSE_DEBUG #define LOG_TAG "Minikin" #include <cutils/log.h> #include "MinikinInternal.h" #include <minikin/CmapCoverage.h> #include <minikin/FontCollection.h> using std::vector; namespace android { template <typename T> static inline T max(T a, T b) { return a>b ? a : b; } uint32_t FontCollection::sNextId = 0; FontCollection::FontCollection(const vector<FontFamily*>& typefaces) : mMaxChar(0) { AutoMutex _l(gMinikinLock); mId = sNextId++; vector<uint32_t> lastChar; size_t nTypefaces = typefaces.size(); #ifdef VERBOSE_DEBUG ALOGD("nTypefaces = %d\n", nTypefaces); #endif const FontStyle defaultStyle; for (size_t i = 0; i < nTypefaces; i++) { FontFamily* family = typefaces[i]; MinikinFont* typeface = family->getClosestMatch(defaultStyle).font; if (typeface == NULL) { ALOGE("FontCollection: closest match was null"); // TODO: we shouldn't hit this, as there should be more robust // checks upstream to prevent empty/invalid FontFamily objects continue; } family->RefLocked(); FontInstance dummy; mInstances.push_back(dummy); // emplace_back would be better FontInstance* instance = &mInstances.back(); instance->mFamily = family; instance->mCoverage = new SparseBitSet; #ifdef VERBOSE_DEBUG ALOGD("closest match = %p, family size = %d\n", typeface, family->getNumFonts()); #endif const uint32_t cmapTag = MinikinFont::MakeTag('c', 'm', 'a', 'p'); size_t cmapSize = 0; bool ok = typeface->GetTable(cmapTag, NULL, &cmapSize); UniquePtr<uint8_t[]> cmapData(new uint8_t[cmapSize]); ok = typeface->GetTable(cmapTag, cmapData.get(), &cmapSize); CmapCoverage::getCoverage(*instance->mCoverage, cmapData.get(), cmapSize); #ifdef VERBOSE_DEBUG ALOGD("font coverage length=%d, first ch=%x\n", instance->mCoverage->length(), instance->mCoverage->nextSetBit(0)); #endif mMaxChar = max(mMaxChar, instance->mCoverage->length()); lastChar.push_back(instance->mCoverage->nextSetBit(0)); } nTypefaces = mInstances.size(); size_t nPages = (mMaxChar + kPageMask) >> kLogCharsPerPage; size_t offset = 0; for (size_t i = 0; i < nPages; i++) { Range dummy; mRanges.push_back(dummy); Range* range = &mRanges.back(); #ifdef VERBOSE_DEBUG ALOGD("i=%d: range start = %d\n", i, offset); #endif range->start = offset; for (size_t j = 0; j < nTypefaces; j++) { if (lastChar[j] < (i + 1) << kLogCharsPerPage) { const FontInstance* instance = &mInstances[j]; mInstanceVec.push_back(instance); offset++; uint32_t nextChar = instance->mCoverage->nextSetBit((i + 1) << kLogCharsPerPage); #ifdef VERBOSE_DEBUG ALOGD("nextChar = %d (j = %d)\n", nextChar, j); #endif lastChar[j] = nextChar; } } range->end = offset; } } FontCollection::~FontCollection() { for (size_t i = 0; i < mInstances.size(); i++) { delete mInstances[i].mCoverage; mInstances[i].mFamily->UnrefLocked(); } } // Implement heuristic for choosing best-match font. Here are the rules: // 1. If first font in the collection has the character, it wins. // 2. If a font matches both language and script, it gets a score of 4. // 3. If a font matches just language, it gets a score of 2. // 4. Matching the "compact" or "elegant" variant adds one to the score. // 5. Highest score wins, with ties resolved to the first font. const FontCollection::FontInstance* FontCollection::getInstanceForChar(uint32_t ch, FontLanguage lang, int variant) const { if (ch >= mMaxChar) { return NULL; } const Range& range = mRanges[ch >> kLogCharsPerPage]; #ifdef VERBOSE_DEBUG ALOGD("querying range %d:%d\n", range.start, range.end); #endif const FontInstance* bestInstance = NULL; int bestScore = -1; for (size_t i = range.start; i < range.end; i++) { const FontInstance* instance = mInstanceVec[i]; if (instance->mCoverage->get(ch)) { FontFamily* family = instance->mFamily; // First font family in collection always matches if (mInstances[0].mFamily == family) { return instance; } int score = lang.match(family->lang()) * 2; if (variant != 0 && variant == family->variant()) { score++; } if (score > bestScore) { bestScore = score; bestInstance = instance; } } } return bestInstance; } const uint32_t NBSP = 0xa0; const uint32_t ZWJ = 0x200c; const uint32_t ZWNJ = 0x200d; // Characters where we want to continue using existing font run instead of // recomputing the best match in the fallback list. static const uint32_t stickyWhitelist[] = { '!', ',', '.', ':', ';', '?', NBSP, ZWJ, ZWNJ }; static bool isStickyWhitelisted(uint32_t c) { for (size_t i = 0; i < sizeof(stickyWhitelist) / sizeof(stickyWhitelist[0]); i++) { if (stickyWhitelist[i] == c) return true; } return false; } void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style, vector<Run>* result) const { FontLanguage lang = style.getLanguage(); int variant = style.getVariant(); const FontInstance* lastInstance = NULL; Run* run = NULL; int nShorts; for (size_t i = 0; i < string_size; i += nShorts) { nShorts = 1; uint32_t ch = string[i]; // sigh, decode UTF-16 by hand here if ((ch & 0xfc00) == 0xd800) { if ((i + 1) < string_size) { ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff); nShorts = 2; } } // Continue using existing font as long as it has coverage and is whitelisted if (lastInstance == NULL || !(isStickyWhitelisted(ch) && lastInstance->mCoverage->get(ch))) { const FontInstance* instance = getInstanceForChar(ch, lang, variant); if (i == 0 || instance != lastInstance) { Run dummy; result->push_back(dummy); run = &result->back(); if (instance == NULL) { run->fakedFont.font = NULL; } else { run->fakedFont = instance->mFamily->getClosestMatch(style); } lastInstance = instance; run->start = i; } } run->end = i + nShorts; } } MinikinFont* FontCollection::baseFont(FontStyle style) { return baseFontFaked(style).font; } FakedFont FontCollection::baseFontFaked(FontStyle style) { if (mInstances.empty()) { return FakedFont(); } return mInstances[0].mFamily->getClosestMatch(style); } uint32_t FontCollection::getId() const { return mId; } } // namespace android <commit_msg>Assign non-coverage font runs to base font<commit_after>/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // #define VERBOSE_DEBUG #define LOG_TAG "Minikin" #include <cutils/log.h> #include "MinikinInternal.h" #include <minikin/CmapCoverage.h> #include <minikin/FontCollection.h> using std::vector; namespace android { template <typename T> static inline T max(T a, T b) { return a>b ? a : b; } uint32_t FontCollection::sNextId = 0; FontCollection::FontCollection(const vector<FontFamily*>& typefaces) : mMaxChar(0) { AutoMutex _l(gMinikinLock); mId = sNextId++; vector<uint32_t> lastChar; size_t nTypefaces = typefaces.size(); #ifdef VERBOSE_DEBUG ALOGD("nTypefaces = %d\n", nTypefaces); #endif const FontStyle defaultStyle; for (size_t i = 0; i < nTypefaces; i++) { FontFamily* family = typefaces[i]; MinikinFont* typeface = family->getClosestMatch(defaultStyle).font; if (typeface == NULL) { continue; } family->RefLocked(); FontInstance dummy; mInstances.push_back(dummy); // emplace_back would be better FontInstance* instance = &mInstances.back(); instance->mFamily = family; instance->mCoverage = new SparseBitSet; #ifdef VERBOSE_DEBUG ALOGD("closest match = %p, family size = %d\n", typeface, family->getNumFonts()); #endif const uint32_t cmapTag = MinikinFont::MakeTag('c', 'm', 'a', 'p'); size_t cmapSize = 0; bool ok = typeface->GetTable(cmapTag, NULL, &cmapSize); UniquePtr<uint8_t[]> cmapData(new uint8_t[cmapSize]); ok = typeface->GetTable(cmapTag, cmapData.get(), &cmapSize); CmapCoverage::getCoverage(*instance->mCoverage, cmapData.get(), cmapSize); #ifdef VERBOSE_DEBUG ALOGD("font coverage length=%d, first ch=%x\n", instance->mCoverage->length(), instance->mCoverage->nextSetBit(0)); #endif mMaxChar = max(mMaxChar, instance->mCoverage->length()); lastChar.push_back(instance->mCoverage->nextSetBit(0)); } nTypefaces = mInstances.size(); LOG_ALWAYS_FATAL_IF(nTypefaces == 0, "Font collection must have at least one valid typeface"); size_t nPages = (mMaxChar + kPageMask) >> kLogCharsPerPage; size_t offset = 0; for (size_t i = 0; i < nPages; i++) { Range dummy; mRanges.push_back(dummy); Range* range = &mRanges.back(); #ifdef VERBOSE_DEBUG ALOGD("i=%d: range start = %d\n", i, offset); #endif range->start = offset; for (size_t j = 0; j < nTypefaces; j++) { if (lastChar[j] < (i + 1) << kLogCharsPerPage) { const FontInstance* instance = &mInstances[j]; mInstanceVec.push_back(instance); offset++; uint32_t nextChar = instance->mCoverage->nextSetBit((i + 1) << kLogCharsPerPage); #ifdef VERBOSE_DEBUG ALOGD("nextChar = %d (j = %d)\n", nextChar, j); #endif lastChar[j] = nextChar; } } range->end = offset; } } FontCollection::~FontCollection() { for (size_t i = 0; i < mInstances.size(); i++) { delete mInstances[i].mCoverage; mInstances[i].mFamily->UnrefLocked(); } } // Implement heuristic for choosing best-match font. Here are the rules: // 1. If first font in the collection has the character, it wins. // 2. If a font matches both language and script, it gets a score of 4. // 3. If a font matches just language, it gets a score of 2. // 4. Matching the "compact" or "elegant" variant adds one to the score. // 5. Highest score wins, with ties resolved to the first font. const FontCollection::FontInstance* FontCollection::getInstanceForChar(uint32_t ch, FontLanguage lang, int variant) const { if (ch >= mMaxChar) { return NULL; } const Range& range = mRanges[ch >> kLogCharsPerPage]; #ifdef VERBOSE_DEBUG ALOGD("querying range %d:%d\n", range.start, range.end); #endif const FontInstance* bestInstance = NULL; int bestScore = -1; for (size_t i = range.start; i < range.end; i++) { const FontInstance* instance = mInstanceVec[i]; if (instance->mCoverage->get(ch)) { FontFamily* family = instance->mFamily; // First font family in collection always matches if (mInstances[0].mFamily == family) { return instance; } int score = lang.match(family->lang()) * 2; if (variant != 0 && variant == family->variant()) { score++; } if (score > bestScore) { bestScore = score; bestInstance = instance; } } } if (bestInstance == NULL) { bestInstance = &mInstances[0]; } return bestInstance; } const uint32_t NBSP = 0xa0; const uint32_t ZWJ = 0x200c; const uint32_t ZWNJ = 0x200d; // Characters where we want to continue using existing font run instead of // recomputing the best match in the fallback list. static const uint32_t stickyWhitelist[] = { '!', ',', '.', ':', ';', '?', NBSP, ZWJ, ZWNJ }; static bool isStickyWhitelisted(uint32_t c) { for (size_t i = 0; i < sizeof(stickyWhitelist) / sizeof(stickyWhitelist[0]); i++) { if (stickyWhitelist[i] == c) return true; } return false; } void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style, vector<Run>* result) const { FontLanguage lang = style.getLanguage(); int variant = style.getVariant(); const FontInstance* lastInstance = NULL; Run* run = NULL; int nShorts; for (size_t i = 0; i < string_size; i += nShorts) { nShorts = 1; uint32_t ch = string[i]; // sigh, decode UTF-16 by hand here if ((ch & 0xfc00) == 0xd800) { if ((i + 1) < string_size) { ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff); nShorts = 2; } } // Continue using existing font as long as it has coverage and is whitelisted if (lastInstance == NULL || !(isStickyWhitelisted(ch) && lastInstance->mCoverage->get(ch))) { const FontInstance* instance = getInstanceForChar(ch, lang, variant); if (i == 0 || instance != lastInstance) { Run dummy; result->push_back(dummy); run = &result->back(); if (instance == NULL) { run->fakedFont.font = NULL; } else { run->fakedFont = instance->mFamily->getClosestMatch(style); } lastInstance = instance; run->start = i; } } run->end = i + nShorts; } } MinikinFont* FontCollection::baseFont(FontStyle style) { return baseFontFaked(style).font; } FakedFont FontCollection::baseFontFaked(FontStyle style) { if (mInstances.empty()) { return FakedFont(); } return mInstances[0].mFamily->getClosestMatch(style); } uint32_t FontCollection::getId() const { return mId; } } // namespace android <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include <caf/all.hpp> #include "vast/concept/printable/std/chrono.hpp" #include "vast/concept/printable/to_string.hpp" #include "vast/concept/printable/vast/bitmap.hpp" #include "vast/concept/printable/vast/event.hpp" #include "vast/concept/printable/vast/expression.hpp" #include "vast/concept/printable/vast/uuid.hpp" #include "vast/detail/assert.hpp" #include "vast/detail/fill_status_map.hpp" #include "vast/event.hpp" #include "vast/expression_visitors.hpp" #include "vast/logger.hpp" #include "vast/table_slice.hpp" #include "vast/to_events.hpp" #include "vast/system/archive.hpp" #include "vast/system/atoms.hpp" #include "vast/system/exporter.hpp" #include "vast/detail/assert.hpp" using namespace std::chrono; using namespace std::string_literals; using namespace caf; namespace vast { namespace system { namespace { void ship_results(stateful_actor<exporter_state>* self) { VAST_TRACE(""); if (self->state.results.empty() || self->state.query.requested == 0) { return; } VAST_DEBUG(self, "relays", self->state.results.size(), "events"); message msg; if (self->state.results.size() <= self->state.query.requested) { self->state.query.requested -= self->state.results.size(); self->state.query.shipped += self->state.results.size(); msg = make_message(std::move(self->state.results)); self->state.results = {}; } else { std::vector<event> remainder; remainder.reserve(self->state.results.size() - self->state.query.requested); auto begin = self->state.results.begin() + self->state.query.requested; auto end = self->state.results.end(); std::move(begin, end, std::back_inserter(remainder)); self->state.results.resize(self->state.query.requested); msg = make_message(std::move(self->state.results)); self->state.results = std::move(remainder); self->state.query.shipped += self->state.query.requested; self->state.query.requested = 0; } self->send(self->state.sink, msg); } void report_statistics(stateful_actor<exporter_state>* self) { auto& st = self->state; timespan runtime = steady_clock::now() - st.start; st.query.runtime = runtime; VAST_INFO(self, "shipped", st.query.shipped, "results out of", st.query.processed, "candidates in", vast::to_string(runtime)); self->send(st.sink, st.id, st.query); if (st.accountant) { auto hits = rank(st.hits); auto processed = st.query.processed; auto shipped = st.query.shipped; auto results = shipped + st.results.size(); auto selectivity = double(results) / processed; auto msg = report{{"exporter.hits", hits}, {"exporter.processed", processed}, {"exporter.results", results}, {"exporter.shipped", shipped}, {"exporter.selectivity", selectivity}, {"exporter.runtime", runtime}}; self->send(st.accountant, msg); } } void shutdown(stateful_actor<exporter_state>* self, caf::error err) { VAST_DEBUG(self, "initiates shutdown with error", self->system().render(err)); self->send_exit(self, std::move(err)); } void shutdown(stateful_actor<exporter_state>* self) { if (has_continuous_option(self->state.options)) return; VAST_DEBUG(self, "initiates shutdown"); self->send_exit(self, exit_reason::normal); } void request_more_hits(stateful_actor<exporter_state>* self) { const auto& st = self->state; if (!has_historical_option(st.options)) return; auto waiting_for_hits = st.query.received == st.query.scheduled; auto need_more_results = st.query.requested > 0; auto have_no_inflight_requests = st.query.lookups_issued == st.query.lookups_complete; // If we're (1) no longer waiting for index hits, (2) still need more // results, and (3) have no inflight requests to the archive, we ask // the index for more hits. if (!waiting_for_hits && need_more_results && have_no_inflight_requests) { auto remaining = st.query.expected - st.query.received; VAST_ASSERT(remaining > 0); // TODO: Figure out right number of partitions to ask for. For now, we // bound the number by an arbitrary constant. auto n = std::min(remaining, size_t{2}); VAST_DEBUG(self, "asks index to process", n, "more partitions"); self->send(st.index, st.id, n); } } } // namespace <anonymous> caf::settings exporter_state::status() { caf::settings result; put(result, "hits", rank(hits)); put(result, "start", caf::deep_to_string(start)); put(result, "id", to_string(id)); put(result, "expression", to_string(expr)); return result; } behavior exporter(stateful_actor<exporter_state>* self, expression expr, query_options options) { auto eu = self->system().dummy_execution_unit(); self->state.sink = actor_pool::make(eu, actor_pool::broadcast()); if (auto a = self->system().registry().get(accountant_atom::value)) { self->state.accountant = actor_cast<accountant_type>(a); self->send(self->state.accountant, announce_atom::value, self->name()); } self->state.options = options; self->state.expr = std::move(expr); if (has_continuous_option(options)) VAST_DEBUG(self, "has continuous query option"); self->set_exit_handler( [=](const exit_msg& msg) { VAST_DEBUG(self, "received exit from", msg.source, "with reason:", msg.reason); self->send<message_priority::high>(self->state.index, self->state.id, 0); self->send(self->state.sink, sys_atom::value, delete_atom::value); self->send_exit(self->state.sink, msg.reason); self->quit(msg.reason); if (msg.reason != exit_reason::kill) report_statistics(self); } ); self->set_down_handler( [=](const down_msg& msg) { VAST_DEBUG(self, "received DOWN from", msg.source); if (has_continuous_option(self->state.options) && (msg.source == self->state.archive || msg.source == self->state.index)) report_statistics(self); } ); auto finished = [&](const query_status& qs) -> bool { return qs.received == qs.expected && qs.lookups_issued == qs.lookups_complete; }; auto handle_batch = [=](std::vector<event> candidates) { auto& st = self->state; VAST_DEBUG(self, "got batch of", candidates.size(), "events"); auto sender = self->current_sender(); for (auto& candidate : candidates) { auto& checker = st.checkers[candidate.type()]; // Construct a candidate checker if we don't have one for this type. if (caf::holds_alternative<caf::none_t>(checker)) { auto x = tailor(st.expr, candidate.type()); if (!x) { VAST_ERROR(self, "failed to tailor expression:", self->system().render(x.error())); ship_results(self); self->send_exit(self, exit_reason::normal); return; } checker = std::move(*x); VAST_DEBUG(self, "tailored AST to", candidate.type() << ':', checker); } // Perform candidate check and keep event as result on success. if (caf::visit(event_evaluator{candidate}, checker)) st.results.push_back(std::move(candidate)); else VAST_DEBUG(self, "ignores false positive:", candidate); } st.query.processed += candidates.size(); ship_results(self); }; return { // The INDEX (or the EVALUATOR, to be more precise) sends us a series of // `ids` in response to an expression (query), terminated by 'done'. [=](ids& hits) -> caf::result<void> { auto& st = self->state; // Skip results that arrive before we got our lookup handle from the // INDEX actor. if (st.query.expected == 0) return caf::skip; // Add `hits` to the total result set and update all stats. timespan runtime = steady_clock::now() - st.start; st.query.runtime = runtime; auto count = rank(hits); if (st.accountant) { auto r = report{}; if (st.hits.empty()) r.push_back({"exporter.hits.first", runtime}); r.push_back({"exporter.hits.arrived", runtime}); r.push_back({"exporter.hits.count", count}); self->send(st.accountant, r); } if (count == 0) { VAST_WARNING(self, "got empty hits"); } else { VAST_DEBUG(self, "got", count, "index hits in [", (select(hits, 1)), ',', (select(hits, -1) + 1), ')'); st.hits |= hits; VAST_DEBUG(self, "forwards hits to archive"); // FIXME: restrict according to configured limit. ++st.query.lookups_issued; self->send(st.archive, std::move(hits)); } return caf::unit; }, [=](table_slice_ptr slice) { handle_batch(to_events(*slice, self->state.hits)); }, [=](done_atom) { // Figure out if we're done by bumping the counter for `received` and // check whether it reaches `expected`. auto& st = self->state; timespan runtime = steady_clock::now() - st.start; st.query.runtime = runtime; st.query.received += st.query.scheduled; if (st.query.received < st.query.expected) { VAST_DEBUG(self, "received", st.query.received, '/', st.query.expected, "ID sets"); request_more_hits(self); } else { VAST_DEBUG(self, "received all", st.query.expected, "ID set(s) in", vast::to_string(runtime)); if (st.accountant) self->send(st.accountant, "exporter.hits.runtime", runtime); if (finished(st.query)) shutdown(self); } }, [=](done_atom, const caf::error& err) { auto& st = self->state; auto sender = self->current_sender(); if (sender == st.archive) { if (err) VAST_DEBUG(self, "received error from archive:", self->system().render(err)); ++st.query.lookups_complete; } if (finished(st.query)) shutdown(self); }, [=](extract_atom) { VAST_DEBUG(self, "got request to extract all events"); if (self->state.query.requested == max_events) { VAST_WARNING(self, "ignores extract request, already getting all"); return; } self->state.query.requested = max_events; ship_results(self); request_more_hits(self); }, [=](extract_atom, uint64_t requested) { if (self->state.query.requested == max_events) { VAST_WARNING(self, "ignores extract request, already getting all"); return; } auto n = std::min(max_events - requested, requested); self->state.query.requested += n; VAST_DEBUG(self, "got request to extract", n, "new events in addition to", self->state.query.requested, "pending results"); ship_results(self); request_more_hits(self); }, [=](status_atom) { auto result = self->state.status(); detail::fill_status_map(result, self); return result; }, [=](const archive_type& archive) { VAST_DEBUG(self, "registers archive", archive); self->state.archive = archive; if (has_continuous_option(self->state.options)) self->monitor(archive); // Register self at the archive if (has_historical_option(self->state.options)) self->send(archive, exporter_atom::value, self); }, [=](index_atom, const actor& index) { VAST_DEBUG(self, "registers index", index); self->state.index = index; if (has_continuous_option(self->state.options)) self->monitor(index); }, [=](sink_atom, const actor& sink) { VAST_DEBUG(self, "registers sink", sink); self->send(self->state.sink, sys_atom::value, put_atom::value, sink); self->monitor(self->state.sink); }, [=](importer_atom, const std::vector<actor>& importers) { // Register for events at running IMPORTERs. if (has_continuous_option(self->state.options)) for (auto& x : importers) self->send(x, exporter_atom::value, self); }, [=](run_atom) { VAST_INFO(self, "executes query", self->state.expr); self->state.start = steady_clock::now(); if (!has_historical_option(self->state.options)) return; self->request(self->state.index, infinite, self->state.expr).then( [=](const uuid& lookup, uint32_t partitions, uint32_t scheduled) { VAST_DEBUG(self, "got lookup handle", lookup << ", scheduled", scheduled << '/' << partitions, "partitions"); self->state.id = lookup; if (partitions > 0) { self->state.query.expected = partitions; self->state.query.scheduled = scheduled; } else { shutdown(self); } }, [=](const error& e) { shutdown(self, e); } ); }, [=](caf::stream<table_slice_ptr> in) { return self->make_sink( in, [](caf::unit_t&) { // nop }, [=](caf::unit_t&, const table_slice_ptr& slice) { // TODO: port to new table slice API auto candidates = to_events(*slice); handle_batch(std::move(candidates)); }, [=](caf::unit_t&, const error& err) { VAST_IGNORE_UNUSED(err); VAST_ERROR(self, "got error during streaming: ", err); } ); }, }; } } // namespace system } // namespace vast <commit_msg>Polish EXPORTER logging output<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include <caf/all.hpp> #include "vast/concept/printable/std/chrono.hpp" #include "vast/concept/printable/to_string.hpp" #include "vast/concept/printable/vast/bitmap.hpp" #include "vast/concept/printable/vast/event.hpp" #include "vast/concept/printable/vast/expression.hpp" #include "vast/concept/printable/vast/uuid.hpp" #include "vast/detail/assert.hpp" #include "vast/detail/fill_status_map.hpp" #include "vast/event.hpp" #include "vast/expression_visitors.hpp" #include "vast/logger.hpp" #include "vast/table_slice.hpp" #include "vast/to_events.hpp" #include "vast/system/archive.hpp" #include "vast/system/atoms.hpp" #include "vast/system/exporter.hpp" #include "vast/detail/assert.hpp" using namespace std::chrono; using namespace std::string_literals; using namespace caf; namespace vast { namespace system { namespace { void ship_results(stateful_actor<exporter_state>* self) { VAST_TRACE(""); if (self->state.results.empty() || self->state.query.requested == 0) { return; } VAST_DEBUG(self, "relays", self->state.results.size(), "events"); message msg; if (self->state.results.size() <= self->state.query.requested) { self->state.query.requested -= self->state.results.size(); self->state.query.shipped += self->state.results.size(); msg = make_message(std::move(self->state.results)); self->state.results = {}; } else { std::vector<event> remainder; remainder.reserve(self->state.results.size() - self->state.query.requested); auto begin = self->state.results.begin() + self->state.query.requested; auto end = self->state.results.end(); std::move(begin, end, std::back_inserter(remainder)); self->state.results.resize(self->state.query.requested); msg = make_message(std::move(self->state.results)); self->state.results = std::move(remainder); self->state.query.shipped += self->state.query.requested; self->state.query.requested = 0; } self->send(self->state.sink, msg); } void report_statistics(stateful_actor<exporter_state>* self) { auto& st = self->state; timespan runtime = steady_clock::now() - st.start; st.query.runtime = runtime; VAST_INFO(self, "processed", st.query.processed, "candidates in", vast::to_string(runtime), "and shipped", st.query.shipped, "results"); self->send(st.sink, st.id, st.query); if (st.accountant) { auto hits = rank(st.hits); auto processed = st.query.processed; auto shipped = st.query.shipped; auto results = shipped + st.results.size(); auto selectivity = double(results) / processed; auto msg = report{{"exporter.hits", hits}, {"exporter.processed", processed}, {"exporter.results", results}, {"exporter.shipped", shipped}, {"exporter.selectivity", selectivity}, {"exporter.runtime", runtime}}; self->send(st.accountant, msg); } } void shutdown(stateful_actor<exporter_state>* self, caf::error err) { VAST_DEBUG(self, "initiates shutdown with error", self->system().render(err)); self->send_exit(self, std::move(err)); } void shutdown(stateful_actor<exporter_state>* self) { if (has_continuous_option(self->state.options)) return; VAST_DEBUG(self, "initiates shutdown"); self->send_exit(self, exit_reason::normal); } void request_more_hits(stateful_actor<exporter_state>* self) { const auto& st = self->state; if (!has_historical_option(st.options)) return; auto waiting_for_hits = st.query.received == st.query.scheduled; auto need_more_results = st.query.requested > 0; auto have_no_inflight_requests = st.query.lookups_issued == st.query.lookups_complete; // If we're (1) no longer waiting for index hits, (2) still need more // results, and (3) have no inflight requests to the archive, we ask // the index for more hits. if (!waiting_for_hits && need_more_results && have_no_inflight_requests) { auto remaining = st.query.expected - st.query.received; VAST_ASSERT(remaining > 0); // TODO: Figure out right number of partitions to ask for. For now, we // bound the number by an arbitrary constant. auto n = std::min(remaining, size_t{2}); VAST_DEBUG(self, "asks index to process", n, "more partitions"); self->send(st.index, st.id, n); } } } // namespace <anonymous> caf::settings exporter_state::status() { caf::settings result; put(result, "hits", rank(hits)); put(result, "start", caf::deep_to_string(start)); put(result, "id", to_string(id)); put(result, "expression", to_string(expr)); return result; } behavior exporter(stateful_actor<exporter_state>* self, expression expr, query_options options) { auto eu = self->system().dummy_execution_unit(); self->state.sink = actor_pool::make(eu, actor_pool::broadcast()); if (auto a = self->system().registry().get(accountant_atom::value)) { self->state.accountant = actor_cast<accountant_type>(a); self->send(self->state.accountant, announce_atom::value, self->name()); } self->state.options = options; self->state.expr = std::move(expr); if (has_continuous_option(options)) VAST_DEBUG(self, "has continuous query option"); self->set_exit_handler( [=](const exit_msg& msg) { VAST_DEBUG(self, "received exit from", msg.source, "with reason:", msg.reason); self->send<message_priority::high>(self->state.index, self->state.id, 0); self->send(self->state.sink, sys_atom::value, delete_atom::value); self->send_exit(self->state.sink, msg.reason); self->quit(msg.reason); if (msg.reason != exit_reason::kill) report_statistics(self); } ); self->set_down_handler( [=](const down_msg& msg) { VAST_DEBUG(self, "received DOWN from", msg.source); if (has_continuous_option(self->state.options) && (msg.source == self->state.archive || msg.source == self->state.index)) report_statistics(self); } ); auto finished = [&](const query_status& qs) -> bool { return qs.received == qs.expected && qs.lookups_issued == qs.lookups_complete; }; auto handle_batch = [=](std::vector<event> candidates) { auto& st = self->state; VAST_DEBUG(self, "got batch of", candidates.size(), "events"); auto sender = self->current_sender(); for (auto& candidate : candidates) { auto& checker = st.checkers[candidate.type()]; // Construct a candidate checker if we don't have one for this type. if (caf::holds_alternative<caf::none_t>(checker)) { auto x = tailor(st.expr, candidate.type()); if (!x) { VAST_ERROR(self, "failed to tailor expression:", self->system().render(x.error())); ship_results(self); self->send_exit(self, exit_reason::normal); return; } checker = std::move(*x); VAST_DEBUG(self, "tailored AST to", candidate.type() << ':', checker); } // Perform candidate check and keep event as result on success. if (caf::visit(event_evaluator{candidate}, checker)) st.results.push_back(std::move(candidate)); else VAST_DEBUG(self, "ignores false positive:", candidate); } st.query.processed += candidates.size(); ship_results(self); }; return { // The INDEX (or the EVALUATOR, to be more precise) sends us a series of // `ids` in response to an expression (query), terminated by 'done'. [=](ids& hits) -> caf::result<void> { auto& st = self->state; // Skip results that arrive before we got our lookup handle from the // INDEX actor. if (st.query.expected == 0) return caf::skip; // Add `hits` to the total result set and update all stats. timespan runtime = steady_clock::now() - st.start; st.query.runtime = runtime; auto count = rank(hits); if (st.accountant) { auto r = report{}; if (st.hits.empty()) r.push_back({"exporter.hits.first", runtime}); r.push_back({"exporter.hits.arrived", runtime}); r.push_back({"exporter.hits.count", count}); self->send(st.accountant, r); } if (count == 0) { VAST_WARNING(self, "got empty hits"); } else { VAST_DEBUG(self, "got", count, "index hits in [", (select(hits, 1)), ',', (select(hits, -1) + 1), ')'); st.hits |= hits; VAST_DEBUG(self, "forwards hits to archive"); // FIXME: restrict according to configured limit. ++st.query.lookups_issued; self->send(st.archive, std::move(hits)); } return caf::unit; }, [=](table_slice_ptr slice) { handle_batch(to_events(*slice, self->state.hits)); }, [=](done_atom) { // Figure out if we're done by bumping the counter for `received` and // check whether it reaches `expected`. auto& st = self->state; timespan runtime = steady_clock::now() - st.start; st.query.runtime = runtime; st.query.received += st.query.scheduled; if (st.query.received < st.query.expected) { VAST_DEBUG(self, "received", st.query.received, '/', st.query.expected, "ID sets"); request_more_hits(self); } else { VAST_DEBUG(self, "received all", st.query.expected, "ID set(s) in", vast::to_string(runtime)); if (st.accountant) self->send(st.accountant, "exporter.hits.runtime", runtime); if (finished(st.query)) shutdown(self); } }, [=](done_atom, const caf::error& err) { auto& st = self->state; auto sender = self->current_sender(); if (sender == st.archive) { if (err) VAST_DEBUG(self, "received error from archive:", self->system().render(err)); ++st.query.lookups_complete; } if (finished(st.query)) shutdown(self); }, [=](extract_atom) { VAST_DEBUG(self, "got request to extract all events"); if (self->state.query.requested == max_events) { VAST_WARNING(self, "ignores extract request, already getting all"); return; } self->state.query.requested = max_events; ship_results(self); request_more_hits(self); }, [=](extract_atom, uint64_t requested) { if (self->state.query.requested == max_events) { VAST_WARNING(self, "ignores extract request, already getting all"); return; } auto n = std::min(max_events - requested, requested); self->state.query.requested += n; VAST_DEBUG(self, "got request to extract", n, "new events in addition to", self->state.query.requested, "pending results"); ship_results(self); request_more_hits(self); }, [=](status_atom) { auto result = self->state.status(); detail::fill_status_map(result, self); return result; }, [=](const archive_type& archive) { VAST_DEBUG(self, "registers archive", archive); self->state.archive = archive; if (has_continuous_option(self->state.options)) self->monitor(archive); // Register self at the archive if (has_historical_option(self->state.options)) self->send(archive, exporter_atom::value, self); }, [=](index_atom, const actor& index) { VAST_DEBUG(self, "registers index", index); self->state.index = index; if (has_continuous_option(self->state.options)) self->monitor(index); }, [=](sink_atom, const actor& sink) { VAST_DEBUG(self, "registers sink", sink); self->send(self->state.sink, sys_atom::value, put_atom::value, sink); self->monitor(self->state.sink); }, [=](importer_atom, const std::vector<actor>& importers) { // Register for events at running IMPORTERs. if (has_continuous_option(self->state.options)) for (auto& x : importers) self->send(x, exporter_atom::value, self); }, [=](run_atom) { VAST_INFO(self, "executes query:", self->state.expr); self->state.start = steady_clock::now(); if (!has_historical_option(self->state.options)) return; self->request(self->state.index, infinite, self->state.expr).then( [=](const uuid& lookup, uint32_t partitions, uint32_t scheduled) { VAST_DEBUG(self, "got lookup handle", lookup << ", scheduled", scheduled << '/' << partitions, "partitions"); self->state.id = lookup; if (partitions > 0) { self->state.query.expected = partitions; self->state.query.scheduled = scheduled; } else { shutdown(self); } }, [=](const error& e) { shutdown(self, e); } ); }, [=](caf::stream<table_slice_ptr> in) { return self->make_sink( in, [](caf::unit_t&) { // nop }, [=](caf::unit_t&, const table_slice_ptr& slice) { // TODO: port to new table slice API auto candidates = to_events(*slice); handle_batch(std::move(candidates)); }, [=](caf::unit_t&, const error& err) { VAST_IGNORE_UNUSED(err); VAST_ERROR(self, "got error during streaming: ", err); } ); }, }; } } // namespace system } // namespace vast <|endoftext|>
<commit_before>#include "Scheduler.h" #include <cstdio> using namespace std; using namespace boost; void Scheduler::addConnection(Connection *c) { printf("addConnection: source [ %p idx %d ] -> sink [ %p idx %d]\n", c->m_sourceBlock, c->m_sourceIndex, c->m_sinkBlock, c->m_sinkIndex); vertex_t vert_source, vert_sink; bool found_source = false, found_sink = false; /* see if the source or sink vertex (or both) is already in the graph */ auto v_it = vertices(m_graph); for (auto it = v_it.first; it != v_it.second; ++it) { vertex_t v = *it; if (m_graph[v] == c->m_sourceBlock) { printf("- source block %p is already in the graph.\n", c->m_sourceBlock); vert_source = v; found_source = true; } if (m_graph[v] == c->m_sinkBlock) { printf("- sink block %p is already in the graph.\n", c->m_sinkBlock); vert_sink = v; found_sink = true; } if (found_source && found_sink) break; } /* if source and/or sink were not found, add new vertex(es) to the graph */ if (!found_source) { printf("- source block %p is not in the graph; creating.\n", c->m_sourceBlock); vert_source = add_vertex(m_graph); m_graph[vert_source] = c->m_sourceBlock; } if (!found_sink) { printf("- sink block %p is not in the graph; creating.\n", c->m_sinkBlock); vert_sink = add_vertex(m_graph); m_graph[vert_sink] = c->m_sinkBlock; } edge_t edge; bool found_edge = false; /* see if the edge is already in the graph */ auto e_it = edges(m_graph); for (auto it = e_it.first; it != e_it.second; ++it) { edge_t e = *it; pair<int, int> indices = m_graph[e]; vertex_t v1 = source(e, m_graph); vertex_t v2 = target(e, m_graph); if (m_graph[v1] == c->m_sourceBlock && m_graph[v2] == c->m_sinkBlock && indices.first == c->m_sourceIndex && indices.second == c->m_sinkIndex) { printf("- edge is already in the graph!\n"); edge = e; found_edge = true; break; } } /* if edge was not found, add new edge to the graph */ if (!found_edge) { printf("- edge does not exist in the graph; creating.\n"); bool b; tie(edge, b) = add_edge(vert_source, vert_sink, m_graph); m_graph[edge] = pair<int, int>(c->m_sourceIndex, c->m_sinkIndex); /* bool b is supposed to be set false if the graph is configured to * disallow parallel edges (see documentation for add_edge); * currently this is not how our graph is set up. * if this can be set, then we don't need to hunt for duplicate edges */ } else { /* probably want to throw an exception here instead of this nonsense */ printf("- refusing to add a duplicate edge\n"); } dumpGraph(); m_needCheck = true; } void Scheduler::checkGraph(void) { printf("checkGraph: checking graph validity\n"); int errors = 0; /* ensure that no input is connected to more than one output * (no two edges should have the same sink block AND sink index) */ auto e_it = edges(m_graph); for (auto it1 = e_it.first; it1 != e_it.second; ++it1) { edge_t e1 = *it1; Block *sinkBlock1 = m_graph[target(e1, m_graph)]; int sinkIndex1 = m_graph[e1].second; for (auto it2 = e_it.first; it2 != e_it.second; ++it2) { if (it1 == it2) continue; edge_t e2 = *it2; Block *sinkBlock2 = m_graph[target(e2, m_graph)]; int sinkIndex2 = m_graph[e2].second; if (sinkBlock1 == sinkBlock2 && sinkIndex1 == sinkIndex2) { printf("- sink [ %p idx %d ] has more than one source " "connected!\n", sinkBlock1, sinkIndex1); ++errors; } } } printf("- %d errors\n", errors); if (errors != 0) { throw new runtime_error("Graph validation failed"); } m_needCheck = false; } void Scheduler::dumpGraph(void) { printf("\n====================== m_graph summary ======================\n"); printf("%lu vertices\n", num_vertices(m_graph)); auto v_it = vertices(m_graph); for (auto it = v_it.first; it != v_it.second; ++it) { vertex_t v = *it; printf(" + vert: %p\n", m_graph[v]); } printf("\n%lu edges\n", num_edges(m_graph)); auto e_it = edges(m_graph); for (auto it = e_it.first; it != e_it.second; ++it) { edge_t e = *it; std::pair<int, int> indices = m_graph[e]; vertex_t v1 = source(e, m_graph); vertex_t v2 = target(e, m_graph); printf(" + edge: [ %p idx %d ] -> [ %p idx %d ]\n", m_graph[v1], indices.first, m_graph[v2], indices.second); } printf("=============================================================\n\n"); } void Scheduler::run(void) { if (m_needCheck) { checkGraph(); } #if 0 /* Call work on all blocks */ for (boost::tie(i, end) = vertices(m_graph); i != end; ++i) { printf("run: calling work on %p\n", *i); (*i)->work(); } /* Move samples from source blocks to sink blocks */ graph_traits < adjacency_list <> >::vertex_iterator i, end; for (boost::tie(i, end) = vertices(m_graph); i != end; ++i) { while (!(*i)->outputEmpty()) { int sample = (*i)->popOutput(); /* Iterate over all sinks attached to this block */ graph_traits < adjacency_list <> >::adjacency_iterator ai, a_end; for (boost::tie(ai, a_end) = adjacent_vertices(*i, m_graph); ai != a_end; ++ai) { printf(""); (*ai)->pushInput(sample); } } } #endif } <commit_msg>checkGraph: remove erroneous 'new' in throw statement<commit_after>#include "Scheduler.h" #include <cstdio> using namespace std; using namespace boost; void Scheduler::addConnection(Connection *c) { printf("addConnection: source [ %p idx %d ] -> sink [ %p idx %d]\n", c->m_sourceBlock, c->m_sourceIndex, c->m_sinkBlock, c->m_sinkIndex); vertex_t vert_source, vert_sink; bool found_source = false, found_sink = false; /* see if the source or sink vertex (or both) is already in the graph */ auto v_it = vertices(m_graph); for (auto it = v_it.first; it != v_it.second; ++it) { vertex_t v = *it; if (m_graph[v] == c->m_sourceBlock) { printf("- source block %p is already in the graph.\n", c->m_sourceBlock); vert_source = v; found_source = true; } if (m_graph[v] == c->m_sinkBlock) { printf("- sink block %p is already in the graph.\n", c->m_sinkBlock); vert_sink = v; found_sink = true; } if (found_source && found_sink) break; } /* if source and/or sink were not found, add new vertex(es) to the graph */ if (!found_source) { printf("- source block %p is not in the graph; creating.\n", c->m_sourceBlock); vert_source = add_vertex(m_graph); m_graph[vert_source] = c->m_sourceBlock; } if (!found_sink) { printf("- sink block %p is not in the graph; creating.\n", c->m_sinkBlock); vert_sink = add_vertex(m_graph); m_graph[vert_sink] = c->m_sinkBlock; } edge_t edge; bool found_edge = false; /* see if the edge is already in the graph */ auto e_it = edges(m_graph); for (auto it = e_it.first; it != e_it.second; ++it) { edge_t e = *it; pair<int, int> indices = m_graph[e]; vertex_t v1 = source(e, m_graph); vertex_t v2 = target(e, m_graph); if (m_graph[v1] == c->m_sourceBlock && m_graph[v2] == c->m_sinkBlock && indices.first == c->m_sourceIndex && indices.second == c->m_sinkIndex) { printf("- edge is already in the graph!\n"); edge = e; found_edge = true; break; } } /* if edge was not found, add new edge to the graph */ if (!found_edge) { printf("- edge does not exist in the graph; creating.\n"); bool b; tie(edge, b) = add_edge(vert_source, vert_sink, m_graph); m_graph[edge] = pair<int, int>(c->m_sourceIndex, c->m_sinkIndex); /* bool b is supposed to be set false if the graph is configured to * disallow parallel edges (see documentation for add_edge); * currently this is not how our graph is set up. * if this can be set, then we don't need to hunt for duplicate edges */ } else { /* probably want to throw an exception here instead of this nonsense */ printf("- refusing to add a duplicate edge\n"); } dumpGraph(); m_needCheck = true; } void Scheduler::checkGraph(void) { printf("checkGraph: checking graph validity\n"); int errors = 0; /* ensure that no input is connected to more than one output * (no two edges should have the same sink block AND sink index) */ auto e_it = edges(m_graph); for (auto it1 = e_it.first; it1 != e_it.second; ++it1) { edge_t e1 = *it1; Block *sinkBlock1 = m_graph[target(e1, m_graph)]; int sinkIndex1 = m_graph[e1].second; for (auto it2 = e_it.first; it2 != e_it.second; ++it2) { if (it1 == it2) continue; edge_t e2 = *it2; Block *sinkBlock2 = m_graph[target(e2, m_graph)]; int sinkIndex2 = m_graph[e2].second; if (sinkBlock1 == sinkBlock2 && sinkIndex1 == sinkIndex2) { printf("- sink [ %p idx %d ] has more than one source " "connected!\n", sinkBlock1, sinkIndex1); ++errors; } } } printf("- %d errors\n", errors); if (errors != 0) { throw runtime_error("Graph validation failed"); } m_needCheck = false; } void Scheduler::dumpGraph(void) { printf("\n====================== m_graph summary ======================\n"); printf("%lu vertices\n", num_vertices(m_graph)); auto v_it = vertices(m_graph); for (auto it = v_it.first; it != v_it.second; ++it) { vertex_t v = *it; printf(" + vert: %p\n", m_graph[v]); } printf("\n%lu edges\n", num_edges(m_graph)); auto e_it = edges(m_graph); for (auto it = e_it.first; it != e_it.second; ++it) { edge_t e = *it; std::pair<int, int> indices = m_graph[e]; vertex_t v1 = source(e, m_graph); vertex_t v2 = target(e, m_graph); printf(" + edge: [ %p idx %d ] -> [ %p idx %d ]\n", m_graph[v1], indices.first, m_graph[v2], indices.second); } printf("=============================================================\n\n"); } void Scheduler::run(void) { if (m_needCheck) { checkGraph(); } #if 0 /* Call work on all blocks */ for (boost::tie(i, end) = vertices(m_graph); i != end; ++i) { printf("run: calling work on %p\n", *i); (*i)->work(); } /* Move samples from source blocks to sink blocks */ graph_traits < adjacency_list <> >::vertex_iterator i, end; for (boost::tie(i, end) = vertices(m_graph); i != end; ++i) { while (!(*i)->outputEmpty()) { int sample = (*i)->popOutput(); /* Iterate over all sinks attached to this block */ graph_traits < adjacency_list <> >::adjacency_iterator ai, a_end; for (boost::tie(ai, a_end) = adjacent_vertices(*i, m_graph); ai != a_end; ++ai) { printf(""); (*ai)->pushInput(sample); } } } #endif } <|endoftext|>
<commit_before>/* * Copyright (C) 2015, Nils Moehrle * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the LICENSE.txt file for details. */ #include <set> #include <map> #include <util/file_system.h> #include <mve/image_tools.h> #include <mve/image_io.h> #include "texture_atlas.h" TextureAtlas::TextureAtlas(unsigned int size) : size(size), padding(size >> 7), finalized(false) { bin = RectangularBin::create(size, size); image = mve::ByteImage::create(size, size, 3); validity_mask = mve::ByteImage::create(size, size, 1); } /** * Copies the src image into the dest image at the given position, * optionally adding a border. * @warning asserts that the given src image fits into the given dest image. */ void copy_into(mve::ByteImage::ConstPtr src, int x, int y, mve::ByteImage::Ptr dest, int border = 0) { assert(x >= 0 && x + src->width() + 2 * border <= dest->width()); assert(y >= 0 && y + src->height() + 2 * border <= dest->height()); for (int i = 0; i < src->width() + 2 * border; ++i) { for(int j = 0; j < src->height() + 2 * border; j++) { int sx = i - border; int sy = j - border; if (sx < 0 || sx >= src->width() || sy < 0 || sy >= src->height()) continue; for (int c = 0; c < src->channels(); ++c) { dest->at(x + i, y + j, c) = src->at(sx, sy, c); } } } } typedef std::vector<std::pair<int, int> > PixelVector; typedef std::set<std::pair<int, int> > PixelSet; bool TextureAtlas::insert(TexturePatch::ConstPtr texture_patch) { if (finalized) { throw util::Exception("No insertion possible, TextureAtlas already finalized"); } assert(bin != NULL); assert(validity_mask != NULL); int const width = texture_patch->get_width() + 2 * padding; int const height = texture_patch->get_height() + 2 * padding; Rect<int> rect(0, 0, width, height); if (!bin->insert(&rect)) return false; /* Update texture atlas and its validity mask. */ mve::ByteImage::Ptr patch_image = mve::image::float_to_byte_image( texture_patch->get_image(), 0.0f, 1.0f); mve::image::gamma_correct(patch_image, 1.0f / 2.2f); copy_into(patch_image, rect.min_x, rect.min_y, image, padding); mve::ByteImage::ConstPtr patch_validity_mask = texture_patch->get_validity_mask(); copy_into(patch_validity_mask, rect.min_x, rect.min_y, validity_mask, padding); TexturePatch::Faces const & patch_faces = texture_patch->get_faces(); TexturePatch::Texcoords const & patch_texcoords = texture_patch->get_texcoords(); /* Calculate the offset of the texture patches' relative texture coordinates */ math::Vec2f offset = math::Vec2f(rect.min_x + padding, rect.min_y + padding); faces.insert(faces.end(), patch_faces.begin(), patch_faces.end()); /* Calculate the final textcoords of the faces. */ for (std::size_t i = 0; i < patch_faces.size(); ++i) { for (int j = 0; j < 3; ++j) { math::Vec2f rel_texcoord(patch_texcoords[i * 3 + j]); math::Vec2f texcoord = rel_texcoord + offset; texcoord[0] = texcoord[0] / this->size; texcoord[1] = texcoord[1] / this->size; texcoords.push_back(texcoord); } } return true; } void TextureAtlas::apply_edge_padding(void) { assert(image != NULL); assert(validity_mask != NULL); const int width = image->width(); const int height = image->height(); math::Matrix<float, 3, 3> gauss; gauss[0] = 1.0f; gauss[1] = 2.0f; gauss[2] = 1.0f; gauss[3] = 2.0f; gauss[4] = 4.0f; gauss[5] = 2.0f; gauss[6] = 1.0f; gauss[7] = 2.0f; gauss[8] = 1.0f; gauss /= 16.0f; /* Calculate the set of invalid pixels at the border of texture patches. */ PixelSet invalid_border_pixels; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { if (validity_mask->at(x, y, 0) == 255) continue; /* Check the direct neighbourhood of all invalid pixels. */ for (int j = -1; j <= 1; ++j) { for (int i = -1; i <= 1; ++i) { int nx = x + i; int ny = y + j; /* If the invalid pixel has a valid neighbour: */ if (0 <= nx && nx < width && 0 <= ny && ny < height && validity_mask->at(nx, ny, 0) == 255) { /* Add the pixel to the set of invalid border pixels. */ invalid_border_pixels.insert(std::pair<int, int>(x, y)); } } } } } mve::ByteImage::Ptr new_validity_mask = validity_mask->duplicate(); /* Iteratively dilate border pixels until padding constants are reached. */ for (unsigned int n = 0; n <= padding; ++n) { PixelVector new_valid_pixels; PixelSet::iterator it = invalid_border_pixels.begin(); for (;it != invalid_border_pixels.end(); it++) { int x = it->first; int y = it->second; bool now_valid = false; /* Calculate new pixel value. */ for (int c = 0; c < 3; ++c) { float norm = 0.0f; float value = 0.0f; for (int j = -1; j <= 1; ++j) { for (int i = -1; i <= 1; ++i) { int nx = x + i; int ny = y + j; if (0 <= nx && nx < width && 0 <= ny && ny < height && new_validity_mask->at(nx, ny, 0) == 255) { float w = gauss[(j + 1) * 3 + (i + 1)]; norm += w; value += (image->at(nx, ny, c) / 255.0f) * w; } } } if (norm == 0.0f) continue; now_valid = true; image->at(x, y, c) = (value / norm) * 255.0f; } if (now_valid) { new_valid_pixels.push_back(*it); } } invalid_border_pixels.clear(); /* Mark the new valid pixels valid in the validity mask. */ for (std::size_t i = 0; i < new_valid_pixels.size(); ++i) { int x = new_valid_pixels[i].first; int y = new_valid_pixels[i].second; new_validity_mask->at(x, y, 0) = 255; } /* Calculate the set of invalid pixels at the border of the valid area. */ for (std::size_t i = 0; i < new_valid_pixels.size(); ++i) { int x = new_valid_pixels[i].first; int y = new_valid_pixels[i].second; for (int j = -1; j <= 1; ++j) { for (int i = -1; i <= 1; ++i) { int nx = x + i; int ny = y + j; if (0 <= nx && nx < width && 0 <= ny && ny < height && new_validity_mask->at(nx, ny, 0) == 0) { invalid_border_pixels.insert(std::pair<int, int>(nx, ny)); } } } } } } struct VectorCompare { bool operator()(math::Vec2f const & lhs, math::Vec2f const & rhs) { return lhs[0] < rhs[0] || (lhs[0] == rhs[0] && lhs[1] < rhs[1]); } }; typedef std::map<math::Vec2f, std::size_t, VectorCompare> TexcoordMap; void TextureAtlas::merge_texcoords() { Texcoords tmp; tmp.swap(this->texcoords); TexcoordMap texcoord_map; for (math::Vec2f const & texcoord : tmp) { TexcoordMap::iterator iter = texcoord_map.find(texcoord); if (iter == texcoord_map.end()) { std::size_t texcoord_id = this->texcoords.size(); texcoord_map[texcoord] = texcoord_id; this->texcoords.push_back(texcoord); this->texcoord_ids.push_back(texcoord_id); } else { this->texcoord_ids.push_back(iter->second); } } } void TextureAtlas::finalize() { if (finalized) { throw util::Exception("TextureAtlas already finalized"); } this->bin.reset(); this->apply_edge_padding(); this->validity_mask.reset(); this->merge_texcoords(); this->finalized = true; } <commit_msg>Qualify VectorCompare::operator() as const<commit_after>/* * Copyright (C) 2015, Nils Moehrle * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the LICENSE.txt file for details. */ #include <set> #include <map> #include <util/file_system.h> #include <mve/image_tools.h> #include <mve/image_io.h> #include "texture_atlas.h" TextureAtlas::TextureAtlas(unsigned int size) : size(size), padding(size >> 7), finalized(false) { bin = RectangularBin::create(size, size); image = mve::ByteImage::create(size, size, 3); validity_mask = mve::ByteImage::create(size, size, 1); } /** * Copies the src image into the dest image at the given position, * optionally adding a border. * @warning asserts that the given src image fits into the given dest image. */ void copy_into(mve::ByteImage::ConstPtr src, int x, int y, mve::ByteImage::Ptr dest, int border = 0) { assert(x >= 0 && x + src->width() + 2 * border <= dest->width()); assert(y >= 0 && y + src->height() + 2 * border <= dest->height()); for (int i = 0; i < src->width() + 2 * border; ++i) { for(int j = 0; j < src->height() + 2 * border; j++) { int sx = i - border; int sy = j - border; if (sx < 0 || sx >= src->width() || sy < 0 || sy >= src->height()) continue; for (int c = 0; c < src->channels(); ++c) { dest->at(x + i, y + j, c) = src->at(sx, sy, c); } } } } typedef std::vector<std::pair<int, int> > PixelVector; typedef std::set<std::pair<int, int> > PixelSet; bool TextureAtlas::insert(TexturePatch::ConstPtr texture_patch) { if (finalized) { throw util::Exception("No insertion possible, TextureAtlas already finalized"); } assert(bin != NULL); assert(validity_mask != NULL); int const width = texture_patch->get_width() + 2 * padding; int const height = texture_patch->get_height() + 2 * padding; Rect<int> rect(0, 0, width, height); if (!bin->insert(&rect)) return false; /* Update texture atlas and its validity mask. */ mve::ByteImage::Ptr patch_image = mve::image::float_to_byte_image( texture_patch->get_image(), 0.0f, 1.0f); mve::image::gamma_correct(patch_image, 1.0f / 2.2f); copy_into(patch_image, rect.min_x, rect.min_y, image, padding); mve::ByteImage::ConstPtr patch_validity_mask = texture_patch->get_validity_mask(); copy_into(patch_validity_mask, rect.min_x, rect.min_y, validity_mask, padding); TexturePatch::Faces const & patch_faces = texture_patch->get_faces(); TexturePatch::Texcoords const & patch_texcoords = texture_patch->get_texcoords(); /* Calculate the offset of the texture patches' relative texture coordinates */ math::Vec2f offset = math::Vec2f(rect.min_x + padding, rect.min_y + padding); faces.insert(faces.end(), patch_faces.begin(), patch_faces.end()); /* Calculate the final textcoords of the faces. */ for (std::size_t i = 0; i < patch_faces.size(); ++i) { for (int j = 0; j < 3; ++j) { math::Vec2f rel_texcoord(patch_texcoords[i * 3 + j]); math::Vec2f texcoord = rel_texcoord + offset; texcoord[0] = texcoord[0] / this->size; texcoord[1] = texcoord[1] / this->size; texcoords.push_back(texcoord); } } return true; } void TextureAtlas::apply_edge_padding(void) { assert(image != NULL); assert(validity_mask != NULL); const int width = image->width(); const int height = image->height(); math::Matrix<float, 3, 3> gauss; gauss[0] = 1.0f; gauss[1] = 2.0f; gauss[2] = 1.0f; gauss[3] = 2.0f; gauss[4] = 4.0f; gauss[5] = 2.0f; gauss[6] = 1.0f; gauss[7] = 2.0f; gauss[8] = 1.0f; gauss /= 16.0f; /* Calculate the set of invalid pixels at the border of texture patches. */ PixelSet invalid_border_pixels; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { if (validity_mask->at(x, y, 0) == 255) continue; /* Check the direct neighbourhood of all invalid pixels. */ for (int j = -1; j <= 1; ++j) { for (int i = -1; i <= 1; ++i) { int nx = x + i; int ny = y + j; /* If the invalid pixel has a valid neighbour: */ if (0 <= nx && nx < width && 0 <= ny && ny < height && validity_mask->at(nx, ny, 0) == 255) { /* Add the pixel to the set of invalid border pixels. */ invalid_border_pixels.insert(std::pair<int, int>(x, y)); } } } } } mve::ByteImage::Ptr new_validity_mask = validity_mask->duplicate(); /* Iteratively dilate border pixels until padding constants are reached. */ for (unsigned int n = 0; n <= padding; ++n) { PixelVector new_valid_pixels; PixelSet::iterator it = invalid_border_pixels.begin(); for (;it != invalid_border_pixels.end(); it++) { int x = it->first; int y = it->second; bool now_valid = false; /* Calculate new pixel value. */ for (int c = 0; c < 3; ++c) { float norm = 0.0f; float value = 0.0f; for (int j = -1; j <= 1; ++j) { for (int i = -1; i <= 1; ++i) { int nx = x + i; int ny = y + j; if (0 <= nx && nx < width && 0 <= ny && ny < height && new_validity_mask->at(nx, ny, 0) == 255) { float w = gauss[(j + 1) * 3 + (i + 1)]; norm += w; value += (image->at(nx, ny, c) / 255.0f) * w; } } } if (norm == 0.0f) continue; now_valid = true; image->at(x, y, c) = (value / norm) * 255.0f; } if (now_valid) { new_valid_pixels.push_back(*it); } } invalid_border_pixels.clear(); /* Mark the new valid pixels valid in the validity mask. */ for (std::size_t i = 0; i < new_valid_pixels.size(); ++i) { int x = new_valid_pixels[i].first; int y = new_valid_pixels[i].second; new_validity_mask->at(x, y, 0) = 255; } /* Calculate the set of invalid pixels at the border of the valid area. */ for (std::size_t i = 0; i < new_valid_pixels.size(); ++i) { int x = new_valid_pixels[i].first; int y = new_valid_pixels[i].second; for (int j = -1; j <= 1; ++j) { for (int i = -1; i <= 1; ++i) { int nx = x + i; int ny = y + j; if (0 <= nx && nx < width && 0 <= ny && ny < height && new_validity_mask->at(nx, ny, 0) == 0) { invalid_border_pixels.insert(std::pair<int, int>(nx, ny)); } } } } } } struct VectorCompare { bool operator()(math::Vec2f const & lhs, math::Vec2f const & rhs) const { return lhs[0] < rhs[0] || (lhs[0] == rhs[0] && lhs[1] < rhs[1]); } }; typedef std::map<math::Vec2f, std::size_t, VectorCompare> TexcoordMap; void TextureAtlas::merge_texcoords() { Texcoords tmp; tmp.swap(this->texcoords); TexcoordMap texcoord_map; for (math::Vec2f const & texcoord : tmp) { TexcoordMap::iterator iter = texcoord_map.find(texcoord); if (iter == texcoord_map.end()) { std::size_t texcoord_id = this->texcoords.size(); texcoord_map[texcoord] = texcoord_id; this->texcoords.push_back(texcoord); this->texcoord_ids.push_back(texcoord_id); } else { this->texcoord_ids.push_back(iter->second); } } } void TextureAtlas::finalize() { if (finalized) { throw util::Exception("TextureAtlas already finalized"); } this->bin.reset(); this->apply_edge_padding(); this->validity_mask.reset(); this->merge_texcoords(); this->finalized = true; } <|endoftext|>
<commit_before>#include <XdmfArray.h> #include <XdmfHDF.h> #include <mpi.h> /// Simple memory buffer implementation that keeps track of it's stream pointer. class Buffer { private: std::size_t m_size; char* m_data; char* m_put; char* m_tell; public: Buffer( std::size_t size ) : m_size( size ), m_data( new char[size] ), m_put( m_data ), m_tell( m_data ) {} ~Buffer() { delete [] m_data; } /// put a single value into the buffer template< typename T > void put( const T& t ) { std::size_t size = sizeof( T ); memcpy( m_put, &t, size ); m_put += size; } /// copy a contiguous block into the buffer void put( void* data, std::size_t size ) { memcpy( m_put, data, size ); m_put += size; } /// Copy a single value into the buffer. template< typename T > T tell() { std::size_t size = sizeof( T ); T tmp; memcpy( &tmp, m_tell, size ); m_tell += size; return tmp; } /// copy a contiguous block of data from the buffer to an already allocated /// location void tell( void* out, std::size_t size ) { memcpy( out, m_tell, size ); m_tell += size; } std::size_t size() const { return m_size; } char* pointer() { return m_data; } void reset() { m_put = m_data; m_tell = m_data; } }; /// Callback implements parallel IO by communicating to rank 0 in MPI_COMM_WORLD. class CommunicationCallback : public XdmfOpenCallback, public XdmfWriteCallback, public XdmfCloseCallback, public XdmfReadCallback { private: int mCommRank; int mCommSize; public: CommunicationCallback() { MPI_Comm_size( MPI_COMM_WORLD, &mCommSize ); MPI_Comm_rank( MPI_COMM_WORLD, &mCommRank ); } XdmfInt32 DoOpen( XdmfHeavyData* ds, XdmfConstString name, XdmfConstString access ) { if ( mCommRank == 0 ) { return ds->DoOpen( name, access ); } else { return XDMF_SUCCESS; } } XdmfInt32 DoClose( XdmfHeavyData* ds ) { if ( mCommRank == 0 ) { return ds->DoClose(); } else { return XDMF_SUCCESS; } } XdmfInt32 DoWrite( XdmfHeavyData* ds, XdmfArray* array ) { // this is a really bad implementation that assumes rank 0 has the same data // size as everyone else, but we're really just going for a simple // example here. The real coalescing implementation will require a few more // classes to handle buffering the data cleanly and robustly. XdmfInt64 start[1], stride[1], count[1]; XdmfInt32 slab_rank = ds->GetHyperSlab( start, stride, count ); std::size_t slab_info_size = sizeof( XdmfInt32 ) // slab rank + slab_rank * sizeof( XdmfInt64 ) * 3; // start, stride, and count Buffer buf( slab_info_size + array->GetCoreLength() ); if ( mCommRank != 0 ) { // copy local data to the buffer for sending buf.put( slab_rank ); for ( int i = 0; i < slab_rank; ++i ) { buf.put( start[i] ); buf.put( stride[i] ); buf.put( count[i] ); } buf.put( array->GetDataPointer(), array->GetCoreLength() ); MPI_Send( buf.pointer(), buf.size(), MPI_BYTE, 0, 0, MPI_COMM_WORLD ); } else { // first, it's easy to write my own data ds->DoWrite( array ); int processes_received = 1; // I've written local data while ( processes_received < mCommSize ) { MPI_Recv( buf.pointer(), buf.size(), MPI_BYTE, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, 0 ); processes_received++; // pull the information from the buffer buf.reset(); slab_rank = buf.tell< XdmfInt32 >(); for( int i = 0; i < slab_rank; ++i ) { start[i] = buf.tell< XdmfInt64 >(); stride[i] = buf.tell< XdmfInt64 >(); count[i] = buf.tell< XdmfInt64 >(); } ds->SelectHyperSlab( start, stride, count ); XdmfArray* recv = new XdmfArray; recv->CopyShape( array ); buf.tell( recv->GetDataPointer(), recv->GetCoreLength() ); ds->DoWrite( recv ); delete recv; } } return XDMF_SUCCESS; } XdmfArray* DoRead( XdmfHeavyData* ds, XdmfArray* array ) { if ( mCommRank == 0 ) { return ds->DoRead( array ); } else { return NULL; } } }; char const * const kDatasetName = "FILE:TestFile.h5:/XdmfHDFMPI"; int main( int argc, char* argv[] ) { MPI_Init( &argc, &argv ); int rank; MPI_Comm_rank( MPI_COMM_WORLD, &rank ); XdmfHDF* H5 = new XdmfHDF(); CommunicationCallback* cb = new CommunicationCallback; H5->setOpenCallback( cb ); H5->setWriteCallback( cb ); H5->setCloseCallback(cb ); XdmfArray* MyData = new XdmfArray(); MyData->SetNumberType( XDMF_FLOAT32_TYPE ); MyData->SetNumberOfElements( 25 ); MyData->Generate( rank * 25, rank*25 + 24 ); H5->CopyType( MyData ); XdmfInt64 dims[1], start[1], stride[1], count[1]; dims[0] = 100; H5->SetShape( 1, dims ); start[0] = rank * 25; stride[0] = 1; count[0] = 25; H5->SelectHyperSlab( start, stride, count ); H5->Open( kDatasetName, "w" ); H5->Write( MyData ); H5->Close(); bool failure = false; XdmfHDF* H5In = new XdmfHDF(); H5In->setReadCallback( cb ); H5In->setOpenCallback( cb ); H5In->Open( kDatasetName, "r" ); XdmfArray* result = H5In->Read(); if ( result ) { for ( size_t i = 0; i < 100; ++i ) { float value = result->GetValueAsFloat32( i ); std::cout << i << " " << value << std::endl; failure = ( value != i ); } } MPI_Finalize(); delete H5; delete cb; delete MyData; delete H5In; delete result; if ( failure ) { return -1; } else { return 0; } }; <commit_msg>fix compilation error for mpich<commit_after>#include <mpi.h> #include <XdmfArray.h> #include <XdmfHDF.h> /// Simple memory buffer implementation that keeps track of it's stream pointer. class Buffer { private: std::size_t m_size; char* m_data; char* m_put; char* m_tell; public: Buffer( std::size_t size ) : m_size( size ), m_data( new char[size] ), m_put( m_data ), m_tell( m_data ) {} ~Buffer() { delete [] m_data; } /// put a single value into the buffer template< typename T > void put( const T& t ) { std::size_t size = sizeof( T ); memcpy( m_put, &t, size ); m_put += size; } /// copy a contiguous block into the buffer void put( void* data, std::size_t size ) { memcpy( m_put, data, size ); m_put += size; } /// Copy a single value into the buffer. template< typename T > T tell() { std::size_t tsize = sizeof( T ); T tmp; memcpy( &tmp, m_tell, tsize ); m_tell += tsize; return tmp; } /// copy a contiguous block of data from the buffer to an already allocated /// location void tell( void* out, std::size_t size ) { memcpy( out, m_tell, size ); m_tell += size; } std::size_t size() const { return m_size; } char* pointer() { return m_data; } void reset() { m_put = m_data; m_tell = m_data; } }; /// Callback implements parallel IO by communicating to rank 0 in MPI_COMM_WORLD. class CommunicationCallback : public XdmfOpenCallback, public XdmfWriteCallback, public XdmfCloseCallback, public XdmfReadCallback { private: int mCommRank; int mCommSize; public: CommunicationCallback() { MPI_Comm_size( MPI_COMM_WORLD, &mCommSize ); MPI_Comm_rank( MPI_COMM_WORLD, &mCommRank ); } XdmfInt32 DoOpen( XdmfHeavyData* ds, XdmfConstString name, XdmfConstString access ) { if ( mCommRank == 0 ) { return ds->DoOpen( name, access ); } else { return XDMF_SUCCESS; } } XdmfInt32 DoClose( XdmfHeavyData* ds ) { if ( mCommRank == 0 ) { return ds->DoClose(); } else { return XDMF_SUCCESS; } } XdmfInt32 DoWrite( XdmfHeavyData* ds, XdmfArray* array ) { // this is a really bad implementation that assumes rank 0 has the same data // size as everyone else, but we're really just going for a simple // example here. The real coalescing implementation will require a few more // classes to handle buffering the data cleanly and robustly. XdmfInt64 start[1], stride[1], count[1]; XdmfInt32 slab_rank = ds->GetHyperSlab( start, stride, count ); std::size_t slab_info_size = sizeof( XdmfInt32 ) // slab rank + slab_rank * sizeof( XdmfInt64 ) * 3; // start, stride, and count Buffer buf( slab_info_size + array->GetCoreLength() ); if ( mCommRank != 0 ) { // copy local data to the buffer for sending buf.put( slab_rank ); for ( int i = 0; i < slab_rank; ++i ) { buf.put( start[i] ); buf.put( stride[i] ); buf.put( count[i] ); } buf.put( array->GetDataPointer(), array->GetCoreLength() ); MPI_Send( buf.pointer(), buf.size(), MPI_BYTE, 0, 0, MPI_COMM_WORLD ); } else { // first, it's easy to write my own data ds->DoWrite( array ); int processes_received = 1; // I've written local data while ( processes_received < mCommSize ) { MPI_Recv( buf.pointer(), buf.size(), MPI_BYTE, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, 0 ); processes_received++; // pull the information from the buffer buf.reset(); slab_rank = buf.tell< XdmfInt32 >(); for( int i = 0; i < slab_rank; ++i ) { start[i] = buf.tell< XdmfInt64 >(); stride[i] = buf.tell< XdmfInt64 >(); count[i] = buf.tell< XdmfInt64 >(); } ds->SelectHyperSlab( start, stride, count ); XdmfArray* recv = new XdmfArray; recv->CopyShape( array ); buf.tell( recv->GetDataPointer(), recv->GetCoreLength() ); ds->DoWrite( recv ); delete recv; } } return XDMF_SUCCESS; } XdmfArray* DoRead( XdmfHeavyData* ds, XdmfArray* array ) { if ( mCommRank == 0 ) { return ds->DoRead( array ); } else { return NULL; } } }; char const * const kDatasetName = "FILE:TestFile.h5:/XdmfHDFMPI"; int main( int argc, char* argv[] ) { MPI_Init( &argc, &argv ); int rank; MPI_Comm_rank( MPI_COMM_WORLD, &rank ); XdmfHDF* H5 = new XdmfHDF(); CommunicationCallback* cb = new CommunicationCallback; H5->setOpenCallback( cb ); H5->setWriteCallback( cb ); H5->setCloseCallback(cb ); XdmfArray* MyData = new XdmfArray(); MyData->SetNumberType( XDMF_FLOAT32_TYPE ); MyData->SetNumberOfElements( 25 ); MyData->Generate( rank * 25, rank*25 + 24 ); H5->CopyType( MyData ); XdmfInt64 dims[1], start[1], stride[1], count[1]; dims[0] = 100; H5->SetShape( 1, dims ); start[0] = rank * 25; stride[0] = 1; count[0] = 25; H5->SelectHyperSlab( start, stride, count ); H5->Open( kDatasetName, "w" ); H5->Write( MyData ); H5->Close(); bool failure = false; XdmfHDF* H5In = new XdmfHDF(); H5In->setReadCallback( cb ); H5In->setOpenCallback( cb ); H5In->Open( kDatasetName, "r" ); XdmfArray* result = H5In->Read(); if ( result ) { for ( size_t i = 0; i < 100; ++i ) { float value = result->GetValueAsFloat32( i ); std::cout << i << " " << value << std::endl; failure = ( value != i ); } } MPI_Finalize(); delete H5; delete cb; delete MyData; delete H5In; delete result; if ( failure ) { return -1; } else { return 0; } }; <|endoftext|>
<commit_before>#include "bf/generator.h" #include <fstream> int main(int argc, char **argv) { bf::generator bfg; // Helper function to read ascii int from the input auto read_int = [&bfg](bf::var &var) { auto input = bfg.new_var("input"); auto ascii_zero = bfg.new_var("ascii_zero", '0'); input->read_input(); bfg.while_begin(*input); { auto cmp_res = bfg.new_var("cmp_res"); cmp_res->copy(*input); cmp_res->greater_equal(*ascii_zero); bfg.if_begin(*cmp_res); { // Add input to variable var.multiply(10); input->subtract('0'); // ascii to int var.add(*input); // Read next char input->read_input(); } bfg.if_end(*cmp_res); auto not_res = bfg.new_var("not_res"); not_res->bool_not(*cmp_res); bfg.if_begin(*not_res); { // End input cols input->set(0); } bfg.if_end(*not_res); } bfg.while_end(*input); }; // Read input auto cols = bfg.new_var("cols"); auto rows = bfg.new_var("rows"); bfg.print("Cols? "); read_int(*cols); bfg.print("Rows? "); read_int(*rows); bfg.print("\n"); // ------------------------------------------------------------------------ // Adjacent underscores in the current row auto underscores = bfg.new_var("underscores", 1); // For each row // for (i = row; i > 0; --i) auto i = bfg.new_var("i"); i->copy(*rows); bfg.while_begin(*i); { // Just print an X for the first column bfg.print("X"); // Column position, count < underscores -> print "_" auto count = bfg.new_var("count"); // For each col but the first // for (j = cols - 1; j > 0; --j) auto j = bfg.new_var("j"); j->copy(*cols); j->decrement(); bfg.while_begin(*j); { // If count < underscores auto cmp_res = bfg.new_var("cmp_res"); cmp_res->copy(*count); cmp_res->lower_than(*underscores); bfg.if_begin(*cmp_res); { // Print "_" and ++count bfg.print("_"); count->increment(); } bfg.if_end(*cmp_res); // Else (count >= underscores) auto not_res = bfg.new_var("not_res"); not_res->bool_not(*cmp_res); bfg.if_begin(*not_res); { // Print "X" and reset count bfg.print("X"); count->set(0); } bfg.if_end(*not_res); j->decrement(); } bfg.while_end(*j); bfg.print("\n"); // More underscores in the next row underscores->increment(); i->decrement(); } bfg.while_end(*i); // Print to file std::ofstream out("Ueb3Aufg2.bf"); out << bfg; //auto minimal_code = bfg.minimal_code(); //out << minimal_code; return 0; } <commit_msg>Renamed some variables.<commit_after>#include "bf/generator.h" #include <fstream> int main(int argc, char **argv) { bf::generator bfg; // Helper function to read ascii int from the input auto read_int = [&bfg](bf::var &var) { auto input = bfg.new_var("input"); auto ascii_zero = bfg.new_var("ascii_zero", '0'); input->read_input(); bfg.while_begin(*input); { auto is_number = bfg.new_var("is_number"); is_number->copy(*input); is_number->greater_equal(*ascii_zero); bfg.if_begin(*is_number); { // Add input to variable var.multiply(10); input->subtract('0'); // ascii to int var.add(*input); // Read next char input->read_input(); } bfg.if_end(*is_number); auto no_number = bfg.new_var("no_number"); no_number->bool_not(*is_number); bfg.if_begin(*no_number); { // End input cols input->set(0); } bfg.if_end(*no_number); } bfg.while_end(*input); }; // Read input auto cols = bfg.new_var("cols"); auto rows = bfg.new_var("rows"); bfg.print("Cols? "); read_int(*cols); bfg.print("Rows? "); read_int(*rows); bfg.print("\n"); // ------------------------------------------------------------------------ // Adjacent underscores in the current row auto underscores = bfg.new_var("underscores", 1); // For each row // for (i = row; i > 0; --i) auto i = bfg.new_var("i"); i->copy(*rows); bfg.while_begin(*i); { // Just print an X for the first column bfg.print("X"); // Column position, count < underscores -> print "_" auto count = bfg.new_var("count"); // For each col but the first // for (j = cols - 1; j > 0; --j) auto j = bfg.new_var("j"); j->copy(*cols); j->decrement(); bfg.while_begin(*j); { // If count < underscores auto cmp_res = bfg.new_var("cmp_res"); cmp_res->copy(*count); cmp_res->lower_than(*underscores); bfg.if_begin(*cmp_res); { // Print "_" and ++count bfg.print("_"); count->increment(); } bfg.if_end(*cmp_res); // Else (count >= underscores) auto not_res = bfg.new_var("not_res"); not_res->bool_not(*cmp_res); bfg.if_begin(*not_res); { // Print "X" and reset count bfg.print("X"); count->set(0); } bfg.if_end(*not_res); j->decrement(); } bfg.while_end(*j); bfg.print("\n"); // More underscores in the next row underscores->increment(); i->decrement(); } bfg.while_end(*i); // Print to file std::ofstream out("Ueb3Aufg2.bf"); out << bfg; //auto minimal_code = bfg.minimal_code(); //out << minimal_code; return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2016, Ford Motor Company * 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 Ford Motor Company 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. */ #include "application_manager/commands/hmi/sdl_activate_app_request.h" #include "application_manager/state_controller.h" #include "application_manager/message_helper.h" namespace application_manager { namespace commands { SDLActivateAppRequest::SDLActivateAppRequest( const MessageSharedPtr& message, ApplicationManager& application_manager) : RequestFromHMI(message, application_manager) {} SDLActivateAppRequest::~SDLActivateAppRequest() {} void SDLActivateAppRequest::Run() { LOG4CXX_AUTO_TRACE(logger_); using namespace hmi_apis::FunctionID; using namespace hmi_apis::Common_Result; const uint32_t application_id = app_id(); ApplicationConstSharedPtr app = application_manager_.application(application_id); if (!app) { LOG4CXX_ERROR( logger_, "Can't find application within regular apps: " << application_id); return; } DevicesApps devices_apps = FindAllAppOnParticularDevice(app->device()); if (!devices_apps.first && devices_apps.second.empty()) { LOG4CXX_ERROR(logger_, "Can't find regular foreground app with the same " "connection id:" << app->device()); SendResponse(false, correlation_id(), SDL_ActivateApp, NO_APPS_REGISTERED); return; } if (!app->IsRegistered()) { if (devices_apps.first) { MessageHelper::SendLaunchApp(devices_apps.first->app_id(), app->SchemaUrl(), app->PackageName(), application_manager_); } else { std::vector<ApplicationSharedPtr>::const_iterator it = devices_apps.second.begin(); for (; it != devices_apps.second.end(); ++it) { MessageHelper::SendLaunchApp((*it)->app_id(), app->SchemaUrl(), app->PackageName(), application_manager_); } } subscribe_on_event(BasicCommunication_OnAppRegistered); } else { if (devices_apps.first) { MessageHelper::SendLaunchApp(devices_apps.first->app_id(), app->SchemaUrl(), app->PackageName(), application_manager_); } else { const uint32_t application_id = app_id(); application_manager_.GetPolicyHandler().OnActivateApp(application_id, correlation_id()); } } } void SDLActivateAppRequest::onTimeOut() { using namespace hmi_apis::FunctionID; using namespace hmi_apis::Common_Result; using namespace application_manager; unsubscribe_from_event(BasicCommunication_OnAppRegistered); SendResponse( false, correlation_id(), SDL_ActivateApp, APPLICATION_NOT_REGISTERED); } void SDLActivateAppRequest::on_event(const event_engine::Event& event) { using namespace hmi_apis::FunctionID; if (event.id() != BasicCommunication_OnAppRegistered) { return; } unsubscribe_from_event(BasicCommunication_OnAppRegistered); // Have to use HMI app id from event, since HMI app id from original request // message will be changed after app, initially requested for launch via // SDL.ActivateApp, will be registered const uint32_t hmi_application_id = hmi_app_id(event.smart_object()); ApplicationSharedPtr app = application_manager_.application_by_hmi_app(hmi_application_id); if (!app) { LOG4CXX_ERROR( logger_, "Application not found by HMI app id: " << hmi_application_id); return; } application_manager_.GetPolicyHandler().OnActivateApp(app->app_id(), correlation_id()); } uint32_t SDLActivateAppRequest::app_id() const { if ((*message_).keyExists(strings::msg_params)) { if ((*message_)[strings::msg_params].keyExists(strings::app_id)) { return (*message_)[strings::msg_params][strings::app_id].asUInt(); } } LOG4CXX_DEBUG(logger_, "app_id section is absent in the message."); return 0; } uint32_t SDLActivateAppRequest::hmi_app_id( const smart_objects::SmartObject& so) const { if (so.keyExists(strings::params)) { if (so[strings::msg_params].keyExists(strings::application)) { if (so[strings::msg_params][strings::application].keyExists( strings::app_id)) { return so[strings::msg_params][strings::application][strings::app_id] .asUInt(); } } } LOG4CXX_DEBUG(logger_, "Can't find app_id section is absent in the message."); return 0; } DevicesApps SDLActivateAppRequest::FindAllAppOnParticularDevice( const connection_handler::DeviceHandle handle) { DevicesApps apps; const ApplicationSet app_list = application_manager_.applications().GetData(); ApplicationSetIt it = app_list.begin(); ApplicationSetIt it_end = app_list.end(); for (; it != it_end; ++it) { if (handle == (*it)->device()) { if ((*it)->is_foreground()) { apps.first = *it; } apps.second.push_back(*it); } } return apps; } } // namespace commands } // namespace application_manager <commit_msg>Fixes LAUNCH_APP flow<commit_after>/* * Copyright (c) 2016, Ford Motor Company * 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 Ford Motor Company 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. */ #include "application_manager/commands/hmi/sdl_activate_app_request.h" #include "application_manager/state_controller.h" #include "application_manager/message_helper.h" namespace application_manager { namespace commands { SDLActivateAppRequest::SDLActivateAppRequest( const MessageSharedPtr& message, ApplicationManager& application_manager) : RequestFromHMI(message, application_manager) {} SDLActivateAppRequest::~SDLActivateAppRequest() {} void SDLActivateAppRequest::Run() { LOG4CXX_AUTO_TRACE(logger_); using namespace hmi_apis::FunctionID; using namespace hmi_apis::Common_Result; const uint32_t application_id = app_id(); ApplicationConstSharedPtr app = application_manager_.application(application_id); if (!app) { LOG4CXX_ERROR( logger_, "Can't find application within regular apps: " << application_id); // Here is the hack - in fact SDL gets hmi_app_id in appID field and // replaces it with connection_key only for normally registered apps, but // for apps_to_be_registered (waiting) it keeps original value (hmi_app_id) // so method does lookup for hmi_app_id app = application_manager_.app_to_be_registered(application_id); if (!app) { LOG4CXX_WARN( logger_, "Can't find application within waiting apps: " << application_id); return; } } if (app->IsRegistered()) { application_manager_.GetPolicyHandler().OnActivateApp(application_id, correlation_id()); return; } DevicesApps devices_apps = FindAllAppOnParticularDevice(app->device()); if (!devices_apps.first && devices_apps.second.empty()) { LOG4CXX_ERROR(logger_, "Can't find regular foreground app with the same " "connection id:" << app->device()); SendResponse(false, correlation_id(), SDL_ActivateApp, NO_APPS_REGISTERED); return; } if (devices_apps.first) { MessageHelper::SendLaunchApp(devices_apps.first->app_id(), app->SchemaUrl(), app->PackageName(), application_manager_); } else { std::vector<ApplicationSharedPtr>::const_iterator it = devices_apps.second.begin(); for (; it != devices_apps.second.end(); ++it) { MessageHelper::SendLaunchApp((*it)->app_id(), app->SchemaUrl(), app->PackageName(), application_manager_); } subscribe_on_event(BasicCommunication_OnAppRegistered); return; } } void SDLActivateAppRequest::onTimeOut() { using namespace hmi_apis::FunctionID; using namespace hmi_apis::Common_Result; using namespace application_manager; unsubscribe_from_event(BasicCommunication_OnAppRegistered); SendResponse( false, correlation_id(), SDL_ActivateApp, APPLICATION_NOT_REGISTERED); } void SDLActivateAppRequest::on_event(const event_engine::Event& event) { using namespace hmi_apis::FunctionID; if (event.id() != BasicCommunication_OnAppRegistered) { return; } unsubscribe_from_event(BasicCommunication_OnAppRegistered); // Have to use HMI app id from event, since HMI app id from original request // message will be changed after app, initially requested for launch via // SDL.ActivateApp, will be registered const uint32_t hmi_application_id = hmi_app_id(event.smart_object()); ApplicationSharedPtr app = application_manager_.application_by_hmi_app(hmi_application_id); if (!app) { LOG4CXX_ERROR( logger_, "Application not found by HMI app id: " << hmi_application_id); return; } application_manager_.GetPolicyHandler().OnActivateApp(app->app_id(), correlation_id()); } uint32_t SDLActivateAppRequest::app_id() const { if ((*message_).keyExists(strings::msg_params)) { if ((*message_)[strings::msg_params].keyExists(strings::app_id)) { return (*message_)[strings::msg_params][strings::app_id].asUInt(); } } LOG4CXX_DEBUG(logger_, "app_id section is absent in the message."); return 0; } uint32_t SDLActivateAppRequest::hmi_app_id( const smart_objects::SmartObject& so) const { if (so.keyExists(strings::params)) { if (so[strings::msg_params].keyExists(strings::application)) { if (so[strings::msg_params][strings::application].keyExists( strings::app_id)) { return so[strings::msg_params][strings::application][strings::app_id] .asUInt(); } } } LOG4CXX_DEBUG(logger_, "Can't find app_id section is absent in the message."); return 0; } DevicesApps SDLActivateAppRequest::FindAllAppOnParticularDevice( const connection_handler::DeviceHandle handle) { DevicesApps apps; const ApplicationSet app_list = application_manager_.applications().GetData(); ApplicationSetIt it = app_list.begin(); ApplicationSetIt it_end = app_list.end(); for (; it != it_end; ++it) { if (handle == (*it)->device()) { if ((*it)->is_foreground()) { apps.first = *it; } apps.second.push_back(*it); } } return apps; } } // namespace commands } // namespace application_manager <|endoftext|>
<commit_before>#if defined(_MSC_VER) #include "stdafx.h" #endif #include "UnitTests.h" #include "NULLC/nullc.h" #include "NULLC/nullc_debug.h" // Check that remote debug module compiles correctly #if defined(_MSC_VER) #include "NULLC/nullc_remote.h" #endif #include "NULLC/ParseClass.h" #include "NULLC/includes/file.h" #include "NULLC/includes/math.h" #include "NULLC/includes/vector.h" #include "NULLC/includes/random.h" #include "NULLC/includes/dynamic.h" #include "NULLC/includes/gc.h" #include "NULLC/includes/time.h" #include "NULLC/includes/canvas.h" #include "NULLC/includes/window.h" #include "NULLC/includes/io.h" #include "NULLC/includes/pugi.h" #include "tests/TestBase.h" #include "tests/TestSpeed.h" #include "tests/TestCompileFail.h" #include "tests/TestParseFail.h" #include "tests/TestInterface.h" #pragma warning(disable: 4127) FILE *allocLog = NULL; void* testAlloc(size_t size) { if(!allocLog) allocLog = fopen("testAlloc.txt", "wb"); static size_t overall = 0; static int allocs = 0; overall += size; allocs++; fprintf(allocLog, "%d Alloc of %u bytes (Total %u)\r\n", allocs, (unsigned int)size, (unsigned int)overall); fflush(allocLog); return malloc(size); } void testDealloc(void* ptr) { free(ptr); } nullres CompileFile(const char* fileName) { char content[64 * 1024]; FILE *euler = fopen(fileName, "rb"); fseek(euler, 0, SEEK_END); unsigned int textSize = ftell(euler); assert(textSize < 64 * 1024); fseek(euler, 0, SEEK_SET); fread(content, 1, textSize, euler); content[textSize] = 0; fclose(euler); return nullcCompile(content); } void RunTests(bool verbose) { Tests::messageVerbose = verbose; // Extra tests // Safe sprintf test { testsCount[3]++; char buf[8]; char *pos = buf + SafeSprintf(buf, 8, "this "); pos += SafeSprintf(pos, 8 - int(pos - buf), "string is too long"); if(memcmp(buf, "this st", 8) != 0) printf("Safe sprintf test failed: string is incorrect\n"); else if(pos != buf + 8) printf("Safe sprintf test failed: iterator is incorrect\n"); else testsPassed[3]++; } /* unsigned int tStart = clock(); for(unsigned int i = 0; i < 10000; i++) { nullcInit("Modules\\"); nullcTerminate(); } printf("Finished in %d\r\n", clock() - tStart); */ // Init NULLC nullcInit(MODULE_PATH); //nullcInitCustomAlloc(testAlloc, testDealloc, "Modules\\"); //nullcSetFileReadHandler(TestFileLoad); nullcInitTypeinfoModule(); nullcInitFileModule(); nullcInitMathModule(); nullcInitVectorModule(); nullcInitRandomModule(); nullcInitDynamicModule(); nullcInitGCModule(); nullcInitIOModule(); nullcInitCanvasModule(); #if defined(_MSC_VER) nullcInitWindowModule(); #endif /* //SpeedTestFile("test_document.nc"); //SpeedTestFile("shapes.nc"); //SpeedTestFile("raytrace.nc"); //SpeedTestFile("blob.nc"); return;*/ RunInterfaceTests(); #ifdef NULLC_ENABLE_C_TRANSLATION nullres bRes = CompileFile("Modules/std/math.nc"); assert(bRes); nullcTranslateToC("NULLC\\translation\\std_math.cpp", "__init_std_math_nc"); bRes = CompileFile("Modules/std/typeinfo.nc"); assert(bRes); nullcTranslateToC("NULLC\\translation\\std_typeinfo.cpp", "__init_std_typeinfo_nc"); bRes = CompileFile("Modules/std/file.nc"); assert(bRes); nullcTranslateToC("NULLC\\translation\\std_file.cpp", "__init_std_file_nc"); bRes = CompileFile("Modules/std/vector.nc"); assert(bRes); nullcTranslateToC("NULLC\\translation\\std_vector.cpp", "__init_std_vector_nc"); bRes = nullcCompile("import std.math; float4 a; a.x = 2;"); assert(bRes); nullcTranslateToC("test_a.cpp", "__init_test_a_nc"); bRes = nullcCompile("char[] arr2 = \" world\";{ int r = 5; }"); assert(bRes); nullcTranslateToC("test_importhide.cpp", "__init_test_importhide_nc"); bRes = nullcCompile("int func(int a, b = 6){ return a * b; }"); assert(bRes); nullcTranslateToC("test_defargs.cpp", "__init_test_defargs_nc"); bRes = nullcCompile("int func(int a, b = 6){ return a * b; } int func(int d, c, a, b = 4){ return d * c + a + b; }"); assert(bRes); nullcTranslateToC("test_defargs2.cpp", "__init_test_defargs2_nc"); bRes = nullcCompile("class Test{ int func(int a, b = 6){ return a * b; } }"); assert(bRes); nullcTranslateToC("test_defargs3.cpp", "__init_test_defargs3_nc"); bRes = nullcCompile("class Test{ int func(int a, b = 6); }"); assert(bRes); nullcTranslateToC("test_defargs4.cpp", "__init_test_defargs4_nc"); bRes = nullcCompile("int foo(int x, char[] a = \"xx\", int y = 0){return x + a[0] + a[1];}"); assert(bRes); nullcTranslateToC("test_defargs5.cpp", "__init_test_defargs5_nc"); bRes = nullcCompile("int x = 5; int foo(auto ref a = &x){return int(a);}"); assert(bRes); nullcTranslateToC("test_defargs6.cpp", "__init_test_defargs6_nc"); bRes = nullcCompile("int CheckAlignment(auto ref ptr, int alignment);"); assert(bRes); nullcTranslateToC("test_alignment.cpp", "__init_test_alignment_nc"); bRes = CompileFile("Modules/std/list.nc"); assert(bRes); nullcTranslateToC("NULLC\\translation\\std_list.cpp", "__init_std_list_nc"); bRes = CompileFile("Modules/std/range.nc"); assert(bRes); nullcTranslateToC("NULLC\\translation\\std_range.cpp", "__init_std_range_nc"); bRes = CompileFile("Modules/std/gc.nc"); assert(bRes); nullcTranslateToC("NULLC\\translation\\std_gc.cpp", "__init_std_gc_nc"); bRes = CompileFile("Modules/std/dynamic.nc"); assert(bRes); nullcTranslateToC("NULLC\\translation\\std_dynamic.cpp", "__init_std_dynamic_nc"); bRes = CompileFile("Modules/std/io.nc"); assert(bRes); nullcTranslateToC("NULLC\\translation\\std_io.cpp", "__init_std_io_nc"); #endif RunCompileFailTests(); RunParseFailTests(); TestQueue queue; queue.RunTests(); // Conclusion printf("VM passed %d of %d tests\r\n", testsPassed[0], testsCount[0]); #ifdef NULLC_BUILD_X86_JIT printf("X86 passed %d of %d tests\r\n", testsPassed[1], testsCount[1]); #else testsPassed[1] = 0; testsCount[1] = 0; #endif #ifdef NULLC_LLVM_SUPPORT printf("LLVM passed %d of %d tests\r\n", testsPassed[2], testsCount[2]); #else testsPassed[2] = 0; testsCount[2] = 0; #endif printf("Failure tests: passed %d of %d tests\r\n", testsPassed[TEST_FAILURE_INDEX], testsCount[TEST_FAILURE_INDEX]); printf("Extra tests: passed %d of %d tests\r\n", testsPassed[TEST_EXTRA_INDEX], testsCount[TEST_EXTRA_INDEX]); #ifdef NULLC_ENABLE_C_TRANSLATION printf("Translation tests: passed %d of %d tests\r\n", testsPassed[TEST_TRANSLATION_INDEX], testsCount[TEST_TRANSLATION_INDEX]); #endif unsigned allTests = 0; unsigned allPassed = 0; for(unsigned i = 0; i < 6; i++) { allTests += testsCount[i]; allPassed += testsPassed[i]; } printf("Passed %d of %d tests\r\n", allPassed, allTests); printf("Compilation time: %f\r\n", Tests::timeCompile); printf("Get listing time: %f\r\n", Tests::timeGetListing); printf("Get bytecode time: %f\r\n", Tests::timeGetBytecode); printf("Clean time: %f\r\n", Tests::timeClean); printf("Link time: %f\r\n", Tests::timeLinkCode); printf("Run time: %f\r\n", Tests::timeRun); RunSpeedTests(); // Terminate NULLC nullcTerminate(); } <commit_msg>tests: standard library and test module translation to C now report a text error instead of assertion if compilation failed.<commit_after>#if defined(_MSC_VER) #include "stdafx.h" #endif #include "UnitTests.h" #include "NULLC/nullc.h" #include "NULLC/nullc_debug.h" // Check that remote debug module compiles correctly #if defined(_MSC_VER) #include "NULLC/nullc_remote.h" #endif #include "NULLC/ParseClass.h" #include "NULLC/includes/file.h" #include "NULLC/includes/math.h" #include "NULLC/includes/vector.h" #include "NULLC/includes/random.h" #include "NULLC/includes/dynamic.h" #include "NULLC/includes/gc.h" #include "NULLC/includes/time.h" #include "NULLC/includes/canvas.h" #include "NULLC/includes/window.h" #include "NULLC/includes/io.h" #include "NULLC/includes/pugi.h" #include "tests/TestBase.h" #include "tests/TestSpeed.h" #include "tests/TestCompileFail.h" #include "tests/TestParseFail.h" #include "tests/TestInterface.h" #pragma warning(disable: 4127) FILE *allocLog = NULL; void* testAlloc(size_t size) { if(!allocLog) allocLog = fopen("testAlloc.txt", "wb"); static size_t overall = 0; static int allocs = 0; overall += size; allocs++; fprintf(allocLog, "%d Alloc of %u bytes (Total %u)\r\n", allocs, (unsigned int)size, (unsigned int)overall); fflush(allocLog); return malloc(size); } void testDealloc(void* ptr) { free(ptr); } nullres CompileFile(const char* fileName) { char content[64 * 1024]; FILE *euler = fopen(fileName, "rb"); fseek(euler, 0, SEEK_END); unsigned int textSize = ftell(euler); assert(textSize < 64 * 1024); fseek(euler, 0, SEEK_SET); fread(content, 1, textSize, euler); content[textSize] = 0; fclose(euler); return nullcCompile(content); } void RunTests(bool verbose) { Tests::messageVerbose = verbose; // Extra tests // Safe sprintf test { testsCount[3]++; char buf[8]; char *pos = buf + SafeSprintf(buf, 8, "this "); pos += SafeSprintf(pos, 8 - int(pos - buf), "string is too long"); if(memcmp(buf, "this st", 8) != 0) printf("Safe sprintf test failed: string is incorrect\n"); else if(pos != buf + 8) printf("Safe sprintf test failed: iterator is incorrect\n"); else testsPassed[3]++; } /* unsigned int tStart = clock(); for(unsigned int i = 0; i < 10000; i++) { nullcInit("Modules\\"); nullcTerminate(); } printf("Finished in %d\r\n", clock() - tStart); */ // Init NULLC nullcInit(MODULE_PATH); //nullcInitCustomAlloc(testAlloc, testDealloc, "Modules\\"); //nullcSetFileReadHandler(TestFileLoad); nullcInitTypeinfoModule(); nullcInitFileModule(); nullcInitMathModule(); nullcInitVectorModule(); nullcInitRandomModule(); nullcInitDynamicModule(); nullcInitGCModule(); nullcInitIOModule(); nullcInitCanvasModule(); #if defined(_MSC_VER) nullcInitWindowModule(); #endif /* //SpeedTestFile("test_document.nc"); //SpeedTestFile("shapes.nc"); //SpeedTestFile("raytrace.nc"); //SpeedTestFile("blob.nc"); return;*/ RunInterfaceTests(); #ifdef NULLC_ENABLE_C_TRANSLATION if(!CompileFile("Modules/std/math.nc")) printf("ERROR: failed to compile std.math for translation\n"); nullcTranslateToC("NULLC\\translation\\std_math.cpp", "__init_std_math_nc"); if(!CompileFile("Modules/std/typeinfo.nc")) printf("ERROR: failed to compile std.typeinfo for translation\n"); nullcTranslateToC("NULLC\\translation\\std_typeinfo.cpp", "__init_std_typeinfo_nc"); if(!CompileFile("Modules/std/file.nc")) printf("ERROR: failed to compile std.file for translation\n"); nullcTranslateToC("NULLC\\translation\\std_file.cpp", "__init_std_file_nc"); if(!CompileFile("Modules/std/vector.nc")) printf("ERROR: failed to compile std.vector for translation\n"); nullcTranslateToC("NULLC\\translation\\std_vector.cpp", "__init_std_vector_nc"); if(!nullcCompile("import std.math; float4 a; a.x = 2;")) printf("ERROR: failed to compile test_a for translation\n"); nullcTranslateToC("test_a.cpp", "__init_test_a_nc"); if(!nullcCompile("char[] arr2 = \" world\";{ int r = 5; }")) printf("ERROR: failed to compile test_importhide for translation\n"); nullcTranslateToC("test_importhide.cpp", "__init_test_importhide_nc"); if(!nullcCompile("int func(int a, b = 6){ return a * b; }")) printf("ERROR: failed to compile test_defargs for translation\n"); nullcTranslateToC("test_defargs.cpp", "__init_test_defargs_nc"); if(!nullcCompile("int func(int a, b = 6){ return a * b; } int func(int d, c, a, b = 4){ return d * c + a + b; }")) printf("ERROR: failed to compile test_defargs2 for translation\n"); nullcTranslateToC("test_defargs2.cpp", "__init_test_defargs2_nc"); if(!nullcCompile("class Test{ int func(int a, b = 6){ return a * b; } }")) printf("ERROR: failed to compile test_defargs3 for translation\n"); nullcTranslateToC("test_defargs3.cpp", "__init_test_defargs3_nc"); if(!nullcCompile("class Test{ int func(int a, b = 6); }")) printf("ERROR: failed to compile test_defargs4 for translation\n"); nullcTranslateToC("test_defargs4.cpp", "__init_test_defargs4_nc"); if(!nullcCompile("int foo(int x, char[] a = \"xx\", int y = 0){return x + a[0] + a[1];}")) printf("ERROR: failed to compile test_defargs5 for translation\n"); nullcTranslateToC("test_defargs5.cpp", "__init_test_defargs5_nc"); if(!nullcCompile("int x = 5; int foo(auto ref a = &x){return int(a);}")) printf("ERROR: failed to compile test_defargs6 for translation\n"); nullcTranslateToC("test_defargs6.cpp", "__init_test_defargs6_nc"); if(!nullcCompile("int CheckAlignment(auto ref ptr, int alignment);")) printf("ERROR: failed to compile test_alignment for translation\n"); nullcTranslateToC("test_alignment.cpp", "__init_test_alignment_nc"); if(!CompileFile("Modules/std/list.nc")) printf("ERROR: failed to compile std.list for translation\n"); nullcTranslateToC("NULLC\\translation\\std_list.cpp", "__init_std_list_nc"); if(!CompileFile("Modules/std/range.nc")) printf("ERROR: failed to compile std.range for translation\n"); nullcTranslateToC("NULLC\\translation\\std_range.cpp", "__init_std_range_nc"); if(!CompileFile("Modules/std/gc.nc")) printf("ERROR: failed to compile std.gc for translation\n"); nullcTranslateToC("NULLC\\translation\\std_gc.cpp", "__init_std_gc_nc"); if(!CompileFile("Modules/std/dynamic.nc")) printf("ERROR: failed to compile std.dynamic for translation\n"); nullcTranslateToC("NULLC\\translation\\std_dynamic.cpp", "__init_std_dynamic_nc"); if(!CompileFile("Modules/std/io.nc")) printf("ERROR: failed to compile std.io for translation\n"); nullcTranslateToC("NULLC\\translation\\std_io.cpp", "__init_std_io_nc"); #endif RunCompileFailTests(); RunParseFailTests(); TestQueue queue; queue.RunTests(); // Conclusion printf("VM passed %d of %d tests\r\n", testsPassed[0], testsCount[0]); #ifdef NULLC_BUILD_X86_JIT printf("X86 passed %d of %d tests\r\n", testsPassed[1], testsCount[1]); #else testsPassed[1] = 0; testsCount[1] = 0; #endif #ifdef NULLC_LLVM_SUPPORT printf("LLVM passed %d of %d tests\r\n", testsPassed[2], testsCount[2]); #else testsPassed[2] = 0; testsCount[2] = 0; #endif printf("Failure tests: passed %d of %d tests\r\n", testsPassed[TEST_FAILURE_INDEX], testsCount[TEST_FAILURE_INDEX]); printf("Extra tests: passed %d of %d tests\r\n", testsPassed[TEST_EXTRA_INDEX], testsCount[TEST_EXTRA_INDEX]); #ifdef NULLC_ENABLE_C_TRANSLATION printf("Translation tests: passed %d of %d tests\r\n", testsPassed[TEST_TRANSLATION_INDEX], testsCount[TEST_TRANSLATION_INDEX]); #endif unsigned allTests = 0; unsigned allPassed = 0; for(unsigned i = 0; i < 6; i++) { allTests += testsCount[i]; allPassed += testsPassed[i]; } printf("Passed %d of %d tests\r\n", allPassed, allTests); printf("Compilation time: %f\r\n", Tests::timeCompile); printf("Get listing time: %f\r\n", Tests::timeGetListing); printf("Get bytecode time: %f\r\n", Tests::timeGetBytecode); printf("Clean time: %f\r\n", Tests::timeClean); printf("Link time: %f\r\n", Tests::timeLinkCode); printf("Run time: %f\r\n", Tests::timeRun); RunSpeedTests(); // Terminate NULLC nullcTerminate(); } <|endoftext|>
<commit_before>//============================================================================= // ■ main.cpp //----------------------------------------------------------------------------- // VMGS的主程序。 //============================================================================= #include "VMGS.hpp" namespace VM76 { Shaders* shader_textured = NULL; Shaders* shader_basic = NULL; Res::Texture* tile_texture = NULL; Cube* block_pointer; TiledMap* map; Axis* axe; Object* obj = new Object(); int map_count = 0; void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { #define PRESS(n) key == n && action == GLFW_PRESS if (PRESS(GLFW_KEY_A)) obj->move(glm::vec3(-0.5, 0.0, 0.0)); if (PRESS(GLFW_KEY_D)) obj->move(glm::vec3(0.5, 0.0, 0.0)); if (PRESS(GLFW_KEY_W)) obj->move(glm::vec3(0.0, 0.0, -0.5)); if (PRESS(GLFW_KEY_S)) obj->move(glm::vec3(0.0, 0.0, 0.5)); if (PRESS(GLFW_KEY_UP)) obj->move(glm::vec3(0.0, 0.5, 0.0)); if (PRESS(GLFW_KEY_DOWN)) obj->move(glm::vec3(0.0, -0.5, 0.0)); if (PRESS(GLFW_KEY_SPACE)) { map->tiles[map->calcTileIndex(obj->pos * 2.0f)].tid = 2; map->bake_tiles(); } #undef PRESS } void loop() { for (;;) { ::main_draw_start(); update_control(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); shader_textured->use(); // Setup uniforms shader_textured->set_float("brightness", VMDE->state.brightness); shader_textured->ProjectionView(projection, view); map->render(); // Setup uniforms shader_basic->use(); shader_textured->ProjectionView(projection, view); block_pointer->mat[0] = obj->transform(); block_pointer->update_instance(1); block_pointer->render(); axe->render(); ::main_draw_end(); if (VMDE->done) break; } } void init_textures() { shader_textured->set_texture("colortex0", tile_texture, 0); } void start_game() { // 先设好事件回调然后再启动引擎,最大地避免段错误 on_terminate = terminate; ::init_engine(860, 540, "VM / 76"); init_control(); tile_texture = new Res::Texture("../Media/terrain.png"); shader_textured = Shaders::CreateFromFile("../Media/shaders/gbuffers_textured.vsh", "../Media/shaders/gbuffers_textured.fsh"); shader_basic = Shaders::CreateFromFile("../Media/shaders/gbuffers_basic.vsh", "../Media/shaders/gbuffers_basic.fsh"); projection = glm::perspective(1.3f, float(VMDE->width) / float(VMDE->height), 0.1f, 1000.0f); view = glm::lookAt(glm::vec3(0.0, 2.6, 0.0), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0)); // GL settings initialize glFrontFace(GL_CCW); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glDepthRange(0.0f, 1.0f); glClearDepth(1.0f); glDepthMask(GL_TRUE); init_textures(); block_pointer = new Cube(1); axe = new Axis(); map = new TiledMap(16, 16, 16); block_pointer->obj->data.mat_c = 1; glfwSetKeyCallback(window, key_callback); loop(); } void terminate() { log("starting to terminate"); terminate_engine(); VMDE_Dispose(tile_texture); VMDE_Dispose(block_pointer); VMDE_Dispose(map); log("terminated successfully"); } } int main() { log("Hello! This is VM76. Nice to meet you!"); VM76::start_game(); } <commit_msg>放置方块声效<commit_after>//============================================================================= // ■ main.cpp //----------------------------------------------------------------------------- // VMGS的主程序。 //============================================================================= #include "VMGS.hpp" namespace VM76 { Shaders* shader_textured = NULL; Shaders* shader_basic = NULL; Res::Texture* tile_texture = NULL; Cube* block_pointer; TiledMap* map; Axis* axe; Object* obj = new Object(); int map_count = 0; void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { #define PRESS(n) key == n && action == GLFW_PRESS if (PRESS(GLFW_KEY_A)) obj->move(glm::vec3(-0.5, 0.0, 0.0)); if (PRESS(GLFW_KEY_D)) obj->move(glm::vec3(0.5, 0.0, 0.0)); if (PRESS(GLFW_KEY_W)) obj->move(glm::vec3(0.0, 0.0, -0.5)); if (PRESS(GLFW_KEY_S)) obj->move(glm::vec3(0.0, 0.0, 0.5)); if (PRESS(GLFW_KEY_UP)) obj->move(glm::vec3(0.0, 0.5, 0.0)); if (PRESS(GLFW_KEY_DOWN)) obj->move(glm::vec3(0.0, -0.5, 0.0)); if (PRESS(GLFW_KEY_SPACE)) { Audio::play_sound("../Media/soft-ping.ogg", false); map->tiles[map->calcTileIndex(obj->pos * 2.0f)].tid = 2; map->bake_tiles(); } #undef PRESS } void loop() { for (;;) { ::main_draw_start(); update_control(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); shader_textured->use(); // Setup uniforms shader_textured->set_float("brightness", VMDE->state.brightness); shader_textured->ProjectionView(projection, view); map->render(); // Setup uniforms shader_basic->use(); shader_textured->ProjectionView(projection, view); block_pointer->mat[0] = obj->transform(); block_pointer->update_instance(1); block_pointer->render(); axe->render(); ::main_draw_end(); if (VMDE->done) break; } } void init_textures() { shader_textured->set_texture("colortex0", tile_texture, 0); } void start_game() { // 先设好事件回调然后再启动引擎,最大地避免段错误 on_terminate = terminate; ::init_engine(860, 540, "VM / 76"); init_control(); tile_texture = new Res::Texture("../Media/terrain.png"); shader_textured = Shaders::CreateFromFile("../Media/shaders/gbuffers_textured.vsh", "../Media/shaders/gbuffers_textured.fsh"); shader_basic = Shaders::CreateFromFile("../Media/shaders/gbuffers_basic.vsh", "../Media/shaders/gbuffers_basic.fsh"); projection = glm::perspective(1.3f, float(VMDE->width) / float(VMDE->height), 0.1f, 1000.0f); view = glm::lookAt(glm::vec3(0.0, 2.6, 0.0), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0)); // GL settings initialize glFrontFace(GL_CCW); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glDepthRange(0.0f, 1.0f); glClearDepth(1.0f); glDepthMask(GL_TRUE); init_textures(); block_pointer = new Cube(1); axe = new Axis(); map = new TiledMap(16, 16, 16); block_pointer->obj->data.mat_c = 1; glfwSetKeyCallback(window, key_callback); loop(); } void terminate() { log("starting to terminate"); terminate_engine(); VMDE_Dispose(tile_texture); VMDE_Dispose(block_pointer); VMDE_Dispose(map); log("terminated successfully"); } } int main() { log("Hello! This is VM76. Nice to meet you!"); VM76::start_game(); } <|endoftext|>
<commit_before>/* * Copyright 2014 The Imaging Source Europe GmbH * * 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 "properties.h" #include "utils.h" #include <iostream> #include <iomanip> #include <memory> #include <gst/gst.h> #include "tcamprop.h" #include "tcam.h" #include "general.h" using namespace tcam; static const size_t name_width = 40; void print_properties (const std::string& serial) { GstElement* source = gst_element_factory_make("tcamsrc", "source"); if (!source) { std::cerr << "Unable to create source element." << std::endl; return; } if (!is_valid_device_serial(source, serial)) { std::cerr << "Device with given serial does not exist." << std::endl; return; } std::string str; GValue val = {}; g_value_init(&val, G_TYPE_STRING); g_value_set_static_string(&val, serial.c_str()); g_object_set_property(G_OBJECT(source), "serial", &val); GSList* names = tcam_prop_get_tcam_property_names(TCAM_PROP(source)); for (unsigned int i = 0; i < g_slist_length(names); ++i) { char* name = (char*)g_slist_nth(names, i)->data; GValue value = {}; GValue min = {}; GValue max = {}; GValue default_value = {}; GValue step_size = {}; GValue type = {}; GValue flags = {}; GValue category = {}; GValue group = {}; gboolean ret = tcam_prop_get_tcam_property(TCAM_PROP(source), name, &value, &min, &max, &default_value, &step_size, &type, &flags, &category, &group); if (!ret) { printf("Could not query property '%s'\n", name); continue; } std::cout << std::left; const char* t = g_value_get_string(&type); if (strcmp(t, "integer") == 0) { std::cout << std::setw(name_width) << name << "(int)"<< std::right << " min=" << g_value_get_int(&min) << " max=" << g_value_get_int(&max) << " step=" << g_value_get_int(&step_size) << " default=" << g_value_get_int(&default_value) << " value=" << g_value_get_int(&default_value) << " category=" << g_value_get_string(&category) << " group=" << g_value_get_string(&group) << std::endl; } else if (strcmp(t, "double") == 0) { std::cout << std::setw(name_width) << name << "(double)"<< std::right << " min=" << g_value_get_double(&min) << " max=" << g_value_get_double(&max) << " step=" << g_value_get_double(&step_size) << " default=" << g_value_get_double(&default_value) << " value=" << g_value_get_double(&value) << " category=" << g_value_get_string(&category) << " group=" << g_value_get_string(&group) << std::endl; } else if (strcmp(t, "string") == 0) { printf("%s(string) value: %s default: %s grouping %s %s\n", name, g_value_get_string(&value), g_value_get_string(&default_value), g_value_get_string(&category), g_value_get_string(&group)); } else if (strcmp(t, "enum") == 0) { GSList* entries = tcam_prop_get_tcam_menu_entries(TCAM_PROP(source), name); if (entries == NULL) { printf("%s returned no enumeration values.\n", name); continue; } std::cout << std::setw(name_width) << name << "(enum) " << " default="<< std::setw(6) << g_value_get_string(&default_value) << " category=" << g_value_get_string(&category) << " group=" << g_value_get_string(&group) << "\n\t\t\t\t\t\tvalue=" << g_value_get_string(&value) << std::endl; for (unsigned int x = 0; x < g_slist_length(entries); ++x) { printf("\t\t\t\t\t\t\t %s\n", (const char*)g_slist_nth(entries, x)->data); } } else if (strcmp(t, "boolean") == 0) { std::cout << std::setw(name_width) << name << "(bool)" << " default="; if (g_value_get_boolean(&default_value)) { std::cout << "true"; } else { std::cout << "false"; } std::cout << " value="; if (g_value_get_boolean(&value)) { std::cout << "true"; } else { std::cout << "false"; } std::cout << " category=" << g_value_get_string(&category) << " group=" << g_value_get_string(&group) << std::endl; } else if (strcmp(t, "button") == 0) { std::cout << std::setw(name_width) << name << "(button)" << " category=" << g_value_get_string(&category) << " group=" << g_value_get_string(&group) << std::endl; } else { printf("Property '%s' has type '%s' .\n", name, t); } } g_slist_free(names); gst_object_unref(source); } void print_state_json (const std::string& serial) { GstElement* source = gst_element_factory_make("tcamsrc", "source"); if (!source) { std::cerr << "Unable to create source element." << std::endl; return; } if (!is_valid_device_serial(source, serial)) { std::cerr << "Device with given serial does not exist." << std::endl; return; } GValue val = {}; g_value_init(&val, G_TYPE_STRING); g_value_set_static_string(&val, serial.c_str()); g_object_set_property(G_OBJECT(source), "serial", &val); gst_element_set_state(source, GST_STATE_READY); const char* state_str = nullptr; g_object_get(G_OBJECT(source), "state", &state_str, NULL); std::cout << state_str << std::endl; gst_element_set_state(source, GST_STATE_NULL); gst_object_unref(source); } void load_state_json_string (const std::string& serial, const std::string& json_str) { GstElement* source = gst_element_factory_make("tcamsrc", "source"); if (!source) { std::cerr << "Unable to create source element." << std::endl; return; } if (!is_valid_device_serial(source, serial)) { std::cerr << "Device with given serial does not exist." << std::endl; return; } GValue val = {}; g_value_init(&val, G_TYPE_STRING); g_value_set_static_string(&val, serial.c_str()); g_object_set_property(G_OBJECT(source), "serial", &val); gst_element_set_state(source, GST_STATE_READY); g_object_set(G_OBJECT(source), "state", json_str.c_str(), NULL); gst_element_set_state(source, GST_STATE_NULL); gst_object_unref(source); } <commit_msg>tcam-ctrl: Fix int value display<commit_after>/* * Copyright 2014 The Imaging Source Europe GmbH * * 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 "properties.h" #include "utils.h" #include <iostream> #include <iomanip> #include <memory> #include <gst/gst.h> #include "tcamprop.h" #include "tcam.h" #include "general.h" using namespace tcam; static const size_t name_width = 40; void print_properties (const std::string& serial) { GstElement* source = gst_element_factory_make("tcamsrc", "source"); if (!source) { std::cerr << "Unable to create source element." << std::endl; return; } if (!is_valid_device_serial(source, serial)) { std::cerr << "Device with given serial does not exist." << std::endl; return; } std::string str; GValue val = {}; g_value_init(&val, G_TYPE_STRING); g_value_set_static_string(&val, serial.c_str()); g_object_set_property(G_OBJECT(source), "serial", &val); GSList* names = tcam_prop_get_tcam_property_names(TCAM_PROP(source)); for (unsigned int i = 0; i < g_slist_length(names); ++i) { char* name = (char*)g_slist_nth(names, i)->data; GValue value = {}; GValue min = {}; GValue max = {}; GValue default_value = {}; GValue step_size = {}; GValue type = {}; GValue flags = {}; GValue category = {}; GValue group = {}; gboolean ret = tcam_prop_get_tcam_property(TCAM_PROP(source), name, &value, &min, &max, &default_value, &step_size, &type, &flags, &category, &group); if (!ret) { printf("Could not query property '%s'\n", name); continue; } std::cout << std::left; const char* t = g_value_get_string(&type); if (strcmp(t, "integer") == 0) { std::cout << std::setw(name_width) << name << "(int)"<< std::right << " min=" << g_value_get_int(&min) << " max=" << g_value_get_int(&max) << " step=" << g_value_get_int(&step_size) << " default=" << g_value_get_int(&default_value) << " value=" << g_value_get_int(&value) << " category=" << g_value_get_string(&category) << " group=" << g_value_get_string(&group) << std::endl; } else if (strcmp(t, "double") == 0) { std::cout << std::setw(name_width) << name << "(double)"<< std::right << " min=" << g_value_get_double(&min) << " max=" << g_value_get_double(&max) << " step=" << g_value_get_double(&step_size) << " default=" << g_value_get_double(&default_value) << " value=" << g_value_get_double(&value) << " category=" << g_value_get_string(&category) << " group=" << g_value_get_string(&group) << std::endl; } else if (strcmp(t, "string") == 0) { printf("%s(string) value: %s default: %s grouping %s %s\n", name, g_value_get_string(&value), g_value_get_string(&default_value), g_value_get_string(&category), g_value_get_string(&group)); } else if (strcmp(t, "enum") == 0) { GSList* entries = tcam_prop_get_tcam_menu_entries(TCAM_PROP(source), name); if (entries == NULL) { printf("%s returned no enumeration values.\n", name); continue; } std::cout << std::setw(name_width) << name << "(enum) " << " default="<< std::setw(6) << g_value_get_string(&default_value) << " category=" << g_value_get_string(&category) << " group=" << g_value_get_string(&group) << "\n\t\t\t\t\t\tvalue=" << g_value_get_string(&value) << std::endl; for (unsigned int x = 0; x < g_slist_length(entries); ++x) { printf("\t\t\t\t\t\t\t %s\n", (const char*)g_slist_nth(entries, x)->data); } } else if (strcmp(t, "boolean") == 0) { std::cout << std::setw(name_width) << name << "(bool)" << " default="; if (g_value_get_boolean(&default_value)) { std::cout << "true"; } else { std::cout << "false"; } std::cout << " value="; if (g_value_get_boolean(&value)) { std::cout << "true"; } else { std::cout << "false"; } std::cout << " category=" << g_value_get_string(&category) << " group=" << g_value_get_string(&group) << std::endl; } else if (strcmp(t, "button") == 0) { std::cout << std::setw(name_width) << name << "(button)" << " category=" << g_value_get_string(&category) << " group=" << g_value_get_string(&group) << std::endl; } else { printf("Property '%s' has type '%s' .\n", name, t); } } g_slist_free(names); gst_object_unref(source); } void print_state_json (const std::string& serial) { GstElement* source = gst_element_factory_make("tcamsrc", "source"); if (!source) { std::cerr << "Unable to create source element." << std::endl; return; } if (!is_valid_device_serial(source, serial)) { std::cerr << "Device with given serial does not exist." << std::endl; return; } GValue val = {}; g_value_init(&val, G_TYPE_STRING); g_value_set_static_string(&val, serial.c_str()); g_object_set_property(G_OBJECT(source), "serial", &val); gst_element_set_state(source, GST_STATE_READY); const char* state_str = nullptr; g_object_get(G_OBJECT(source), "state", &state_str, NULL); std::cout << state_str << std::endl; gst_element_set_state(source, GST_STATE_NULL); gst_object_unref(source); } void load_state_json_string (const std::string& serial, const std::string& json_str) { GstElement* source = gst_element_factory_make("tcamsrc", "source"); if (!source) { std::cerr << "Unable to create source element." << std::endl; return; } if (!is_valid_device_serial(source, serial)) { std::cerr << "Device with given serial does not exist." << std::endl; return; } GValue val = {}; g_value_init(&val, G_TYPE_STRING); g_value_set_static_string(&val, serial.c_str()); g_object_set_property(G_OBJECT(source), "serial", &val); gst_element_set_state(source, GST_STATE_READY); g_object_set(G_OBJECT(source), "state", json_str.c_str(), NULL); gst_element_set_state(source, GST_STATE_NULL); gst_object_unref(source); } <|endoftext|>
<commit_before>/* * MIT License * * Copyright (c) 2017 Kevin Kirchner * * 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 libelfpp.cpp * \brief Main source file for \p libelfpp * \author Kevin Kirchner * \date 2017 * \copyright MIT LICENSE * * This source file is the main source file for \p libelfpp and implements the * library's public interface. */ #include "libelfpp/libelfpp.h" #include "private_impl.h" #include <cstring> #include <iostream> namespace libelfpp { // Implementation of constructor ELFFile::ELFFile(const std::string& filename) : Filename(filename) { std::ifstream Input(filename); if (!Input.good()) { throw std::runtime_error("File does not exist!"); } unsigned char e_ident[EI_NIDENT]; Input.seekg(0); Input.read(reinterpret_cast<char*>(&e_ident), sizeof(e_ident)); // check if file is ELF file if (Input.gcount() != sizeof(e_ident) || std::memcmp(e_ident, ELFMAG, std::strlen(ELFMAG)) != 0) { throw std::runtime_error("Invalid magic number!"); } switch (e_ident[EI_CLASS]) { case ELFCLASS32: Is64Bit = false; break; case ELFCLASS64: Is64Bit = true; break; default: throw std::runtime_error("Invalid ELF file class!"); } switch (e_ident[EI_DATA]) { case ELFDATA2LSB: IsLittleEndian = true; break; case ELFDATA2MSB: IsLittleEndian = false; break; default: throw std::runtime_error("Invalid ELF encoding!"); } Converter = std::make_shared<EndianessConverter>(IsLittleEndian); if (Is64Bit) { FileHeader = std::make_shared<ELFHeaderImpl<Elf64_Ehdr>>(Converter, IsLittleEndian, Input); } else { FileHeader = std::make_shared<ELFHeaderImpl<Elf32_Ehdr>>(Converter, IsLittleEndian, Input); } loadSegmentsFromFile(Input); loadSectionsFromFile(Input); Input.close(); } // Loads all segmetns from the file stream Elf64_Half ELFFile::loadSegmentsFromFile(std::ifstream& stream) { Elf64_Half entrySize = FileHeader->getProgramHeaderSize(); Elf64_Half segmentNumber = FileHeader->getProgramHeaderNumber(); Elf64_Off offset = FileHeader->getProgramHeaderOffset(); for (Elf64_Half iter = 0; iter < segmentNumber; ++iter) { std::shared_ptr<Segment> Seg; Elf64_Off baseOff, endOff, vBaseAddr, vEndAddr; if (Is64Bit) { Seg = std::make_shared<SegmentImpl<Elf64_Phdr>>(Converter); } else { Seg = std::make_shared<SegmentImpl<Elf32_Phdr>>(Converter); } Seg->loadSegment(stream, (std::streamoff) offset + iter * entrySize); Seg->setIndex(iter); Segments.push_back(Seg); // add associated sections baseOff = Seg->getOffset(); endOff = baseOff + Seg->getFileSize(); vBaseAddr = Seg->getVirtualAddress(); vEndAddr = vBaseAddr + Seg->getMemorySize(); for (const auto& Section : Sections) { if (Section->getFlags() & SHF_ALLOC) { if (vBaseAddr <= Section->getAddress() && Section->getAddress() + Section->getSize() <= vEndAddr) { Seg->addSectionIndex(Section->getIndex()); } } else { if (baseOff <= Section->getOffset() && Section->getOffset() + Section->getSize() <= endOff) { Seg->addSectionIndex(Section->getIndex()); } } } } return segmentNumber; } // Loads all sections from the file stream Elf64_Half ELFFile::loadSectionsFromFile(std::ifstream& stream) { Elf64_Half entrySize = FileHeader->getSectionHeaderSize(); Elf64_Half sectionNumber = FileHeader->getSectionHeaderNumber(); Elf64_Off offset = FileHeader->getSectionHeaderOffset(); for (Elf64_Half iter = 0; iter < sectionNumber; ++iter) { std::shared_ptr<Section> Sec; if (Is64Bit) { Sec = std::make_shared<SectionImpl<Elf64_Shdr>>(Converter); } else { Sec = std::make_shared<SectionImpl<Elf32_Shdr>>(Converter); } Sec->loadSection(stream, (std::streamoff) offset + iter * entrySize); Sec->setIndex(iter); Sections.push_back(Sec); if (Sec->getType() == SHT_DYNAMIC) { if (FileHeader->is64Bit()) { DynamicSec = DynamicSectionImpl<Elf64_Shdr, Elf64_Dyn>::fromSection(Sec); } else { DynamicSec = DynamicSectionImpl<Elf32_Shdr, Elf32_Dyn>::fromSection(Sec); } } } // get primary string section Elf64_Half StringIndex = FileHeader->getSectionHeaderStringTableIndex(); if (StringIndex != SHN_UNDEF) { if (FileHeader->is64Bit()) { StrSection = StringSectionImpl<Elf64_Shdr>::fromSection(Sections[StringIndex]); } else { StrSection = StringSectionImpl<Elf32_Shdr>::fromSection(Sections[StringIndex]); } for (const auto& Sec : Sections) { Sec->setName(StrSection->getString(Sec->getNameStringOffset())); // get symbol sections in this loop, so we do not need to loop again if (Sec->getType() == SHT_DYNSYM || Sec->getType() == SHT_SYMTAB) { std::shared_ptr<SymbolSection> Sym; std::shared_ptr<StringSection> Str; if (FileHeader->is64Bit()) { Str = StringSectionImpl<Elf64_Shdr>::fromSection(Sections[Sec->getLink()]); Sym = SymbolSectionImpl<Elf64_Shdr, Elf64_Sym>::fromSection(Sec, Str); } else { } if (Sym) SymbolSections.push_back(Sym); } if (Sec->getType() == SHT_REL || Sec->getType() == SHT_RELA) { std::shared_ptr<RelocationSection> Reloc; std::shared_ptr<StringSection> Str; std::shared_ptr<SymbolSection> Sym; if (FileHeader->is64Bit()) { Str = StringSectionImpl<Elf64_Shdr>::fromSection(Sections[Sections[Sec->getLink()]->getLink()]); Sym = SymbolSectionImpl<Elf64_Shdr, Elf64_Sym>::fromSection(Sections[Sec->getLink()], Str); Reloc = RelocationSectionImpl<Elf64_Shdr>::fromSection(Sec, Sym, true); } else { Str = StringSectionImpl<Elf32_Shdr>::fromSection(Sections[Sections[Sec->getLink()]->getLink()]); Sym = SymbolSectionImpl<Elf32_Shdr, Elf32_Sym>::fromSection(Sections[Sec->getLink()], Str); Reloc = RelocationSectionImpl<Elf32_Shdr>::fromSection(Sec, Sym, true); } if (Reloc) RelocSections.push_back(Reloc); } } DynamicSec->setName(StrSection->getString(DynamicSec->getNameStringOffset())); StrSection->setName(StrSection->getString(StrSection->getNameStringOffset())); } return sectionNumber; } // return needed libraries const std::vector<std::string> ELFFile::getNeededLibraries() const { std::shared_ptr<StringSection> StrSec; try { if (FileHeader->is64Bit()) { StrSec = std::make_shared<StringSectionImpl<Elf64_Shdr> >(*dynamic_cast<SectionImpl< Elf64_Shdr> *>(sections().at(DynamicSec->getLink()).get())); } else { StrSec = std::make_shared<StringSectionImpl<Elf32_Shdr> >(*dynamic_cast<SectionImpl< Elf32_Shdr> *>(sections().at(DynamicSec->getLink()).get())); } } catch (const std::out_of_range&) { return {}; } if (!StrSec) return {}; std::vector<std::string> result; for (const auto& entry : DynamicSec->getAllEntries()) { if (entry.tag == DT_NEEDED) { result.push_back(StrSec->getString(static_cast<Elf64_Word>(entry.value))); } } return result; } } // end of namespace libelfpp<commit_msg>Fix missing creation of symbol sections in 32 Bit ELF files.<commit_after>/* * MIT License * * Copyright (c) 2017 Kevin Kirchner * * 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 libelfpp.cpp * \brief Main source file for \p libelfpp * \author Kevin Kirchner * \date 2017 * \copyright MIT LICENSE * * This source file is the main source file for \p libelfpp and implements the * library's public interface. */ #include "libelfpp/libelfpp.h" #include "private_impl.h" #include <cstring> #include <iostream> namespace libelfpp { // Implementation of constructor ELFFile::ELFFile(const std::string& filename) : Filename(filename) { std::ifstream Input(filename); if (!Input.good()) { throw std::runtime_error("File does not exist!"); } unsigned char e_ident[EI_NIDENT]; Input.seekg(0); Input.read(reinterpret_cast<char*>(&e_ident), sizeof(e_ident)); // check if file is ELF file if (Input.gcount() != sizeof(e_ident) || std::memcmp(e_ident, ELFMAG, std::strlen(ELFMAG)) != 0) { throw std::runtime_error("Invalid magic number!"); } switch (e_ident[EI_CLASS]) { case ELFCLASS32: Is64Bit = false; break; case ELFCLASS64: Is64Bit = true; break; default: throw std::runtime_error("Invalid ELF file class!"); } switch (e_ident[EI_DATA]) { case ELFDATA2LSB: IsLittleEndian = true; break; case ELFDATA2MSB: IsLittleEndian = false; break; default: throw std::runtime_error("Invalid ELF encoding!"); } Converter = std::make_shared<EndianessConverter>(IsLittleEndian); if (Is64Bit) { FileHeader = std::make_shared<ELFHeaderImpl<Elf64_Ehdr>>(Converter, IsLittleEndian, Input); } else { FileHeader = std::make_shared<ELFHeaderImpl<Elf32_Ehdr>>(Converter, IsLittleEndian, Input); } loadSegmentsFromFile(Input); loadSectionsFromFile(Input); Input.close(); } // Loads all segmetns from the file stream Elf64_Half ELFFile::loadSegmentsFromFile(std::ifstream& stream) { Elf64_Half entrySize = FileHeader->getProgramHeaderSize(); Elf64_Half segmentNumber = FileHeader->getProgramHeaderNumber(); Elf64_Off offset = FileHeader->getProgramHeaderOffset(); for (Elf64_Half iter = 0; iter < segmentNumber; ++iter) { std::shared_ptr<Segment> Seg; Elf64_Off baseOff, endOff, vBaseAddr, vEndAddr; if (Is64Bit) { Seg = std::make_shared<SegmentImpl<Elf64_Phdr>>(Converter); } else { Seg = std::make_shared<SegmentImpl<Elf32_Phdr>>(Converter); } Seg->loadSegment(stream, (std::streamoff) offset + iter * entrySize); Seg->setIndex(iter); Segments.push_back(Seg); // add associated sections baseOff = Seg->getOffset(); endOff = baseOff + Seg->getFileSize(); vBaseAddr = Seg->getVirtualAddress(); vEndAddr = vBaseAddr + Seg->getMemorySize(); for (const auto& Section : Sections) { if (Section->getFlags() & SHF_ALLOC) { if (vBaseAddr <= Section->getAddress() && Section->getAddress() + Section->getSize() <= vEndAddr) { Seg->addSectionIndex(Section->getIndex()); } } else { if (baseOff <= Section->getOffset() && Section->getOffset() + Section->getSize() <= endOff) { Seg->addSectionIndex(Section->getIndex()); } } } } return segmentNumber; } // Loads all sections from the file stream Elf64_Half ELFFile::loadSectionsFromFile(std::ifstream& stream) { Elf64_Half entrySize = FileHeader->getSectionHeaderSize(); Elf64_Half sectionNumber = FileHeader->getSectionHeaderNumber(); Elf64_Off offset = FileHeader->getSectionHeaderOffset(); for (Elf64_Half iter = 0; iter < sectionNumber; ++iter) { std::shared_ptr<Section> Sec; if (Is64Bit) { Sec = std::make_shared<SectionImpl<Elf64_Shdr>>(Converter); } else { Sec = std::make_shared<SectionImpl<Elf32_Shdr>>(Converter); } Sec->loadSection(stream, (std::streamoff) offset + iter * entrySize); Sec->setIndex(iter); Sections.push_back(Sec); if (Sec->getType() == SHT_DYNAMIC) { if (FileHeader->is64Bit()) { DynamicSec = DynamicSectionImpl<Elf64_Shdr, Elf64_Dyn>::fromSection(Sec); } else { DynamicSec = DynamicSectionImpl<Elf32_Shdr, Elf32_Dyn>::fromSection(Sec); } } } // get primary string section Elf64_Half StringIndex = FileHeader->getSectionHeaderStringTableIndex(); if (StringIndex != SHN_UNDEF) { if (FileHeader->is64Bit()) { StrSection = StringSectionImpl<Elf64_Shdr>::fromSection(Sections[StringIndex]); } else { StrSection = StringSectionImpl<Elf32_Shdr>::fromSection(Sections[StringIndex]); } for (const auto& Sec : Sections) { Sec->setName(StrSection->getString(Sec->getNameStringOffset())); // get symbol sections in this loop, so we do not need to loop again if (Sec->getType() == SHT_DYNSYM || Sec->getType() == SHT_SYMTAB) { std::shared_ptr<SymbolSection> Sym; std::shared_ptr<StringSection> Str; if (FileHeader->is64Bit()) { Str = StringSectionImpl<Elf64_Shdr>::fromSection(Sections[Sec->getLink()]); Sym = SymbolSectionImpl<Elf64_Shdr, Elf64_Sym>::fromSection(Sec, Str); } else { Str = StringSectionImpl<Elf32_Shdr>::fromSection(Sections[Sec->getLink()]); Sym = SymbolSectionImpl<Elf32_Shdr, Elf32_Sym>::fromSection(Sec, Str); } if (Sym) SymbolSections.push_back(Sym); } if (Sec->getType() == SHT_REL || Sec->getType() == SHT_RELA) { std::shared_ptr<RelocationSection> Reloc; std::shared_ptr<StringSection> Str; std::shared_ptr<SymbolSection> Sym; if (FileHeader->is64Bit()) { Str = StringSectionImpl<Elf64_Shdr>::fromSection(Sections[Sections[Sec->getLink()]->getLink()]); Sym = SymbolSectionImpl<Elf64_Shdr, Elf64_Sym>::fromSection(Sections[Sec->getLink()], Str); Reloc = RelocationSectionImpl<Elf64_Shdr>::fromSection(Sec, Sym, true); } else { Str = StringSectionImpl<Elf32_Shdr>::fromSection(Sections[Sections[Sec->getLink()]->getLink()]); Sym = SymbolSectionImpl<Elf32_Shdr, Elf32_Sym>::fromSection(Sections[Sec->getLink()], Str); Reloc = RelocationSectionImpl<Elf32_Shdr>::fromSection(Sec, Sym, false); } if (Reloc) RelocSections.push_back(Reloc); } } DynamicSec->setName(StrSection->getString(DynamicSec->getNameStringOffset())); StrSection->setName(StrSection->getString(StrSection->getNameStringOffset())); } return sectionNumber; } // return needed libraries const std::vector<std::string> ELFFile::getNeededLibraries() const { std::shared_ptr<StringSection> StrSec; try { if (FileHeader->is64Bit()) { StrSec = std::make_shared<StringSectionImpl<Elf64_Shdr> >(*dynamic_cast<SectionImpl< Elf64_Shdr> *>(sections().at(DynamicSec->getLink()).get())); } else { StrSec = std::make_shared<StringSectionImpl<Elf32_Shdr> >(*dynamic_cast<SectionImpl< Elf32_Shdr> *>(sections().at(DynamicSec->getLink()).get())); } } catch (const std::out_of_range&) { return {}; } if (!StrSec) return {}; std::vector<std::string> result; for (const auto& entry : DynamicSec->getAllEntries()) { if (entry.tag == DT_NEEDED) { result.push_back(StrSec->getString(static_cast<Elf64_Word>(entry.value))); } } return result; } } // end of namespace libelfpp<|endoftext|>
<commit_before>#include "../headers/geom.h" #include "../headers/util.h" #include "stdio.h" namespace geos { const double maximumPreciseValue=9007199254740992.0; //double PrecisionModel::makePrecise(double val){ // //return rint(val); // return ((val >= 0.0) ? floor(val+0.5) : - floor(-val+0.5)); // /* // * Other options: // * - Math.floor(a + 0.5d); // * - Math.floor(a); // * - (val >= 0.0) ? Math.floor(val) : - Math.floor(-val); // */ //} /** * Rounds an numeric value to the PrecisionModel grid. */ double PrecisionModel::makePrecise(double val) { double v=val*scale; if (val>=0.0) v=floor(v+0.5); else v=-floor(-v+0.5); return v/scale; } /** * Rounds a Coordinate to the PrecisionModel grid. */ void PrecisionModel::makePrecise(Coordinate *coord) { if (modelType==FLOATING) return; coord->x=makePrecise(coord->x); coord->y=makePrecise(coord->y); } PrecisionModel::PrecisionModel(){ modelType=FLOATING; scale=0.0; offsetX=0.0; offsetY=0.0; } /** * Creates a <code>PrecisionModel</code> that specifies Fixed precision. * Fixed-precision coordinates are represented as precise internal coordinates, * which are rounded to the grid defined by the scale factor. * *@param scale amount by which to multiply a coordinate after subtracting * the offset, to obtain a precise coordinate *@param offsetX not used. *@param offsetY not used. * * @deprecated */ PrecisionModel::PrecisionModel(double newScale, double newOffsetX, double newOffsetY) { modelType = FIXED; setScale(newScale); offsetX = newOffsetX; offsetY = newOffsetY; } /** * Creates a <code>PrecisionModel</code> that specifies Fixed precision. * Fixed-precision coordinates are represented as precise internal coordinates, * which are rounded to the grid defined by the scale factor. * *@param scale amount by which to multiply a coordinate after subtracting * the offset, to obtain a precise coordinate */ PrecisionModel::PrecisionModel(double newScale) { modelType=FIXED; setScale(scale); offsetX=0; offsetY=0; } PrecisionModel::PrecisionModel(const PrecisionModel &pm) { modelType = pm.modelType; scale = pm.scale; offsetX = pm.offsetX; offsetY = pm.offsetY; } bool PrecisionModel::isFloating(){ return modelType == FLOATING; } /** * Returns the multiplying factor used to obtain a precise coordinate. * This method is private because PrecisionModel is intended to * be an immutable (value) type. * *@return the amount by which to multiply a coordinate after subtracting * the offset */ double PrecisionModel::getScale(){ return scale; } /** * Sets the multiplying factor used to obtain a precise coordinate. * This method is private because PrecisionModel is intended to * be an immutable (value) type. * */ void PrecisionModel::setScale(double newScale) { scale=fabs(newScale); } double PrecisionModel::getOffsetX(){ return offsetX; } double PrecisionModel::getOffsetY() { return offsetY; } void PrecisionModel::toInternal (Coordinate& external, Coordinate* internal) { if (isFloating()) { internal->x = external.x; internal->y = external.y; } else { internal->x=makePrecise(external.x); internal->y=makePrecise(external.y); } internal->z = external.z; } Coordinate* PrecisionModel::toInternal(Coordinate& external) { Coordinate* internal=new Coordinate(); toInternal(external, internal); return internal; } Coordinate* PrecisionModel::toExternal(Coordinate& internal) { Coordinate* external=new Coordinate(); toExternal(internal, external); return external; } void PrecisionModel::toExternal(Coordinate& internal, Coordinate* external) { external->x = internal.x; external->y = internal.y; } string PrecisionModel::toString() { string result(""); char buffer[255]; if (isFloating()) { result="Floating"; } else { sprintf(buffer,"Fixed (Scale=%g, Offset X=%g, Offset Y=%g)",scale,offsetX,offsetY); result.append(buffer); result.append(""); } return result; } PrecisionModel::~PrecisionModel(){} bool operator==(PrecisionModel a, PrecisionModel b) { return a.isFloating() == b.isFloating() && a.getOffsetX() == b.getOffsetX() && a.getOffsetY() == b.getOffsetY() && a.getScale() == b.getScale(); } /** * Compares this {@link PrecisionModel} object with the specified object for order. * A PrecisionModel is greater than another if it provides greater precision. * *@param o the <code>PrecisionModel</code> with which this <code>PrecisionModel</code> * is being compared *@return a negative integer, zero, or a positive integer as this <code>PrecisionModel</code> * is less than, equal to, or greater than the specified <code>PrecisionModel</code> */ int PrecisionModel::compareTo(void* o) { PrecisionModel *other=(PrecisionModel*) o; if (modelType==FLOATING && other->modelType==FLOATING) return 0; if (modelType==FLOATING && other->modelType!=FLOATING) return 1; if (modelType!=FLOATING && other->modelType==FLOATING) return -1; if (modelType==FIXED && other->modelType==FIXED) { if (scale>other->scale) return 1; else if (scale<other->scale) return -1; else return 0; } Assert::shouldNeverReachHere("Unknown Precision Model type encountered"); return 0; } } <commit_msg>Throw an exception if scale is 0. Added Log entry.<commit_after>/* * $Log$ * Revision 1.13 2003/10/09 10:10:05 strk * Throw an exception if scale is 0. Added Log entry. * */ #include "../headers/geom.h" #include "../headers/util.h" #include "stdio.h" namespace geos { const double maximumPreciseValue=9007199254740992.0; //double PrecisionModel::makePrecise(double val){ // //return rint(val); // return ((val >= 0.0) ? floor(val+0.5) : - floor(-val+0.5)); // /* // * Other options: // * - Math.floor(a + 0.5d); // * - Math.floor(a); // * - (val >= 0.0) ? Math.floor(val) : - Math.floor(-val); // */ //} /** * Rounds an numeric value to the PrecisionModel grid. */ double PrecisionModel::makePrecise(double val) { double v=val*scale; if (val>=0.0) v=floor(v+0.5); else v=-floor(-v+0.5); return v/scale; } /** * Rounds a Coordinate to the PrecisionModel grid. */ void PrecisionModel::makePrecise(Coordinate *coord) { if (modelType==FLOATING) return; coord->x=makePrecise(coord->x); coord->y=makePrecise(coord->y); } PrecisionModel::PrecisionModel(){ modelType=FLOATING; scale=0.0; offsetX=0.0; offsetY=0.0; } /** * Creates a <code>PrecisionModel</code> that specifies Fixed precision. * Fixed-precision coordinates are represented as precise internal coordinates, * which are rounded to the grid defined by the scale factor. * *@param scale amount by which to multiply a coordinate after subtracting * the offset, to obtain a precise coordinate *@param offsetX not used. *@param offsetY not used. * * @deprecated */ PrecisionModel::PrecisionModel(double newScale, double newOffsetX, double newOffsetY) { if ( newScale == 0 ) throw new IllegalArgumentException("PrecisionModel scale cannot be 0"); modelType = FIXED; setScale(newScale); offsetX = newOffsetX; offsetY = newOffsetY; } /** * Creates a <code>PrecisionModel</code> that specifies Fixed precision. * Fixed-precision coordinates are represented as precise internal coordinates, * which are rounded to the grid defined by the scale factor. * *@param scale amount by which to multiply a coordinate after subtracting * the offset, to obtain a precise coordinate */ PrecisionModel::PrecisionModel(double newScale) { modelType=FIXED; setScale(scale); offsetX=0; offsetY=0; } PrecisionModel::PrecisionModel(const PrecisionModel &pm) { modelType = pm.modelType; scale = pm.scale; offsetX = pm.offsetX; offsetY = pm.offsetY; } bool PrecisionModel::isFloating(){ return modelType == FLOATING; } /** * Returns the multiplying factor used to obtain a precise coordinate. * This method is private because PrecisionModel is intended to * be an immutable (value) type. * *@return the amount by which to multiply a coordinate after subtracting * the offset */ double PrecisionModel::getScale(){ return scale; } /** * Sets the multiplying factor used to obtain a precise coordinate. * This method is private because PrecisionModel is intended to * be an immutable (value) type. * */ void PrecisionModel::setScale(double newScale) { scale=fabs(newScale); } double PrecisionModel::getOffsetX(){ return offsetX; } double PrecisionModel::getOffsetY() { return offsetY; } void PrecisionModel::toInternal (Coordinate& external, Coordinate* internal) { if (isFloating()) { internal->x = external.x; internal->y = external.y; } else { internal->x=makePrecise(external.x); internal->y=makePrecise(external.y); } internal->z = external.z; } Coordinate* PrecisionModel::toInternal(Coordinate& external) { Coordinate* internal=new Coordinate(); toInternal(external, internal); return internal; } Coordinate* PrecisionModel::toExternal(Coordinate& internal) { Coordinate* external=new Coordinate(); toExternal(internal, external); return external; } void PrecisionModel::toExternal(Coordinate& internal, Coordinate* external) { external->x = internal.x; external->y = internal.y; } string PrecisionModel::toString() { string result(""); char buffer[255]; if (isFloating()) { result="Floating"; } else { sprintf(buffer,"Fixed (Scale=%g, Offset X=%g, Offset Y=%g)",scale,offsetX,offsetY); result.append(buffer); result.append(""); } return result; } PrecisionModel::~PrecisionModel(){} bool operator==(PrecisionModel a, PrecisionModel b) { return a.isFloating() == b.isFloating() && a.getOffsetX() == b.getOffsetX() && a.getOffsetY() == b.getOffsetY() && a.getScale() == b.getScale(); } /** * Compares this {@link PrecisionModel} object with the specified object for order. * A PrecisionModel is greater than another if it provides greater precision. * *@param o the <code>PrecisionModel</code> with which this <code>PrecisionModel</code> * is being compared *@return a negative integer, zero, or a positive integer as this <code>PrecisionModel</code> * is less than, equal to, or greater than the specified <code>PrecisionModel</code> */ int PrecisionModel::compareTo(void* o) { PrecisionModel *other=(PrecisionModel*) o; if (modelType==FLOATING && other->modelType==FLOATING) return 0; if (modelType==FLOATING && other->modelType!=FLOATING) return 1; if (modelType!=FLOATING && other->modelType==FLOATING) return -1; if (modelType==FIXED && other->modelType==FIXED) { if (scale>other->scale) return 1; else if (scale<other->scale) return -1; else return 0; } Assert::shouldNeverReachHere("Unknown Precision Model type encountered"); return 0; } } <|endoftext|>
<commit_before>/** * Copyright (C) 2011 Trever Fischer <tdfischer@fedoraproject.org> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * 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 Lesser 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. * */ #include "logmodel.h" #include "refreshjob.h" #include "DataModel/subject.h" #include <QtGui/QFileIconProvider> #include <QtCore/QDebug> #include <QtCore/QUrl> #include <QtCore/QDir> #include <QtCore/QCryptographicHash> namespace QZeitgeist { LogModel::LogModel(QObject *parent) : QAbstractItemModel(parent) , m_monitor(0) , m_iconMode(URIIcons) { m_log = new QZeitgeist::Log(this); m_storageState = QZeitgeist::Log::Any; m_range = QZeitgeist::DataModel::TimeRange::always(); m_eventTemplates << QZeitgeist::DataModel::Event(); m_type = QZeitgeist::Log::MostRecentSubjects; m_pool = new QThreadPool(this); } LogModel::~LogModel() { } void LogModel::setIconMode(IconMode mode) { m_iconMode = mode; emit dataChanged(index(0), index(rowCount())); } void LogModel::diffEvents(const QZeitgeist::DataModel::EventList &events) { //TODO: Implement dyanmic programming for a proper diff algorithm. //This probably depends on the datamodel objects not being QObjects. QZeitgeist::DataModel::EventList newEvents = events; QZeitgeist::DataModel::EventList::iterator currentIt = m_events.begin(); QZeitgeist::DataModel::EventList::iterator newIt = newEvents.begin(); int currentRow = 0; while(currentIt != m_events.end() && newIt != newEvents.end()) { if (newIt->id() == currentIt->id()) { newIt++; currentIt++; currentRow++; } else if (newIt->timestamp() >= currentIt->timestamp()) { beginInsertRows(QModelIndex(), currentRow, currentRow); currentIt = m_events.insert(currentIt, *newIt); endInsertRows(); newIt = newEvents.erase(newIt); currentIt++; currentRow++; } else if (newIt->timestamp() < currentIt->timestamp()) { beginRemoveRows(QModelIndex(), currentRow, currentRow); currentIt = m_events.erase(currentIt); endRemoveRows(); } } if (newIt != newEvents.end()) { beginInsertRows(QModelIndex(), currentRow, currentRow+newEvents.size()-1); while(newIt != newEvents.end()) { currentIt = m_events.insert(currentIt, *newIt); currentRow++; currentIt++; newIt++; } endInsertRows(); } if (currentIt != m_events.end()) { beginRemoveRows(QModelIndex(), currentRow, m_events.size()-1); while(currentIt != m_events.end()) { currentIt = m_events.erase(currentIt); } endRemoveRows(); } } void LogModel::refresh() { RefreshJob *refreshJob = new RefreshJob(m_range, m_eventTemplates, m_storageState, 10000, m_type, m_log, this); connect(refreshJob, SIGNAL(done(QZeitgeist::DataModel::EventList)), this, SLOT(refreshDone(QZeitgeist::DataModel::EventList))); m_pool->start(refreshJob); if (m_monitor) m_log->removeMonitor(m_monitor); m_monitor = m_log->installMonitor(m_range, m_eventTemplates); connect(m_monitor, SIGNAL(eventsInserted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventList)), this, SLOT(eventsInserted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventList))); connect(m_monitor, SIGNAL(eventsDeleted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventIdList&)), this, SLOT(eventsDeleted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventIdList))); } void LogModel::eventsInserted(const QZeitgeist::DataModel::TimeRange &range, const QZeitgeist::DataModel::EventList &events) { QZeitgeist::DataModel::EventList oldEvents = m_events; foreach(const QZeitgeist::DataModel::Event &evt, events) { oldEvents << evt; } diffEvents(oldEvents); } void LogModel::eventsDeleted(const QZeitgeist::DataModel::TimeRange &range, const QZeitgeist::DataModel::EventIdList &events) { QZeitgeist::DataModel::EventList oldEvents = m_events; foreach(int id, events) { foreach(const QZeitgeist::DataModel::Event &evt, oldEvents) { if (evt.id() == id) oldEvents.removeOne(evt); } } diffEvents(oldEvents); } void LogModel::refreshDone(const QZeitgeist::DataModel::EventList &results) { diffEvents(results); } int LogModel::rowCount(const QModelIndex &idx) const { if (idx.isValid()) return 0; return m_events.size(); } int LogModel::columnCount(const QModelIndex &idx) const { if (idx.isValid()) return 0; return 1; } QModelIndex LogModel::parent(const QModelIndex &idx) const { Q_UNUSED(idx); return QModelIndex(); } QVariant LogModel::data(const QModelIndex &idx, int role) const { if (idx.isValid() && idx.row() >= 0 && idx.row() < rowCount() && idx.column() == 0) { QZeitgeist::DataModel::Event event = m_events[idx.row()]; switch(role) { case Qt::DisplayRole: return event.subjects()[0].text(); case Qt::DecorationRole: return iconForEvent(event); case EventRole: return QVariant::fromValue<QZeitgeist::DataModel::Event>(event); case TimeRole: return event.timestamp(); case IDRole: return event.id(); case URLRole: return event.subjects()[0].uri(); case MimeRole: return event.subjects()[0].mimeType(); case ActorRole: return event.actor(); case ThumbnailRole: return thumbnailForEvent(event); default: return QVariant(); } } return QVariant(); } QPixmap LogModel::thumbnailForEvent(const QZeitgeist::DataModel::Event &event) const { //FIXME: Implement caching QString url(event.subjects()[0].uri()); QDir thumbDir(QString("%1/.thumbnails/large/").arg(QDir::homePath())); QString snapshotName = QString("%1.png").arg(QString(QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5).toHex())); if (thumbDir.exists(snapshotName)) { return QPixmap(thumbDir.absoluteFilePath(snapshotName), "JPEG"); } return QPixmap(); } QIcon LogModel::iconForActor(const QString &actor) const { QString desktopFile = QUrl(actor).authority().section('.', 0, 0); return QIcon::fromTheme(desktopFile); } QIcon LogModel::iconForEvent(const QZeitgeist::DataModel::Event &event) const { QFileIconProvider icons; QIcon ret = iconForActor(event.actor()); if (m_iconMode == ActorIcons) return ret; foreach(QZeitgeist::DataModel::Subject subject, event.subjects()) { QUrl url = subject.uri(); if (url.scheme() == "file") { QFileInfo info(url.path()); ret = icons.icon(info); if (!ret.isNull()) break; } } if (ret.isNull()) ret = iconForActor(event.actor()); } QModelIndex LogModel::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid() && row >= 0 && row < rowCount() && column == 0) return createIndex(row, column); return QModelIndex(); } void LogModel::setRange(const QZeitgeist::DataModel::TimeRange &range) { m_range = range; refresh(); } Qt::ItemFlags LogModel::flags(const QModelIndex &index) const { if (index.isValid() && index.row() >= 0 && index.row() < rowCount() && index.column() == 0) return Qt::ItemIsEnabled | Qt::ItemIsSelectable; return 0; } QStringList LogModel::eventIconOverlays(const QZeitgeist::DataModel::Event &event) const { QStringList overlays; QZeitgeist::DataModel::Subject subject = event.subjects()[0]; /*switch(subject.interpretation()) { case QZeitgeist::Interpretation::Subject::NFOAudio: overlays << "applications-m }*/ QString mime = subject.mimeType(); overlays << mime.replace('/', '-'); return overlays; } QZeitgeist::DataModel::TimeRange LogModel::range() const { return m_range; } void LogModel::setResultType(QZeitgeist::Log::ResultType type) { m_type = type; refresh(); } QZeitgeist::Log::ResultType LogModel::resultType() const { return m_type; } void LogModel::setEventTemplates(const QZeitgeist::DataModel::EventList &templates) { m_eventTemplates = templates; refresh(); } DataModel::EventList LogModel::eventTemplates() const { return m_eventTemplates; } } // namespace QZeitgeist #include "logmodel.moc" <commit_msg>build++<commit_after>/** * Copyright (C) 2011 Trever Fischer <tdfischer@fedoraproject.org> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * 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 Lesser 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. * */ #include "logmodel.h" #include "refreshjob.h" #include "DataModel/subject.h" #include <QtGui/QFileIconProvider> #include <QtCore/QDebug> #include <QtCore/QUrl> #include <QtCore/QDir> #include <QtCore/QCryptographicHash> namespace QZeitgeist { LogModel::LogModel(QObject *parent) : QAbstractItemModel(parent) , m_monitor(0) , m_iconMode(URIIcons) { m_log = new QZeitgeist::Log(this); m_storageState = QZeitgeist::Log::Any; m_range = QZeitgeist::DataModel::TimeRange::always(); m_eventTemplates << QZeitgeist::DataModel::Event(); m_type = QZeitgeist::Log::MostRecentSubjects; m_pool = new QThreadPool(this); } LogModel::~LogModel() { } void LogModel::setIconMode(IconMode mode) { m_iconMode = mode; emit dataChanged(index(0, 0), index(rowCount(), 0)); } void LogModel::diffEvents(const QZeitgeist::DataModel::EventList &events) { //TODO: Implement dyanmic programming for a proper diff algorithm. //This probably depends on the datamodel objects not being QObjects. QZeitgeist::DataModel::EventList newEvents = events; QZeitgeist::DataModel::EventList::iterator currentIt = m_events.begin(); QZeitgeist::DataModel::EventList::iterator newIt = newEvents.begin(); int currentRow = 0; while(currentIt != m_events.end() && newIt != newEvents.end()) { if (newIt->id() == currentIt->id()) { newIt++; currentIt++; currentRow++; } else if (newIt->timestamp() >= currentIt->timestamp()) { beginInsertRows(QModelIndex(), currentRow, currentRow); currentIt = m_events.insert(currentIt, *newIt); endInsertRows(); newIt = newEvents.erase(newIt); currentIt++; currentRow++; } else if (newIt->timestamp() < currentIt->timestamp()) { beginRemoveRows(QModelIndex(), currentRow, currentRow); currentIt = m_events.erase(currentIt); endRemoveRows(); } } if (newIt != newEvents.end()) { beginInsertRows(QModelIndex(), currentRow, currentRow+newEvents.size()-1); while(newIt != newEvents.end()) { currentIt = m_events.insert(currentIt, *newIt); currentRow++; currentIt++; newIt++; } endInsertRows(); } if (currentIt != m_events.end()) { beginRemoveRows(QModelIndex(), currentRow, m_events.size()-1); while(currentIt != m_events.end()) { currentIt = m_events.erase(currentIt); } endRemoveRows(); } } void LogModel::refresh() { RefreshJob *refreshJob = new RefreshJob(m_range, m_eventTemplates, m_storageState, 10000, m_type, m_log, this); connect(refreshJob, SIGNAL(done(QZeitgeist::DataModel::EventList)), this, SLOT(refreshDone(QZeitgeist::DataModel::EventList))); m_pool->start(refreshJob); if (m_monitor) m_log->removeMonitor(m_monitor); m_monitor = m_log->installMonitor(m_range, m_eventTemplates); connect(m_monitor, SIGNAL(eventsInserted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventList)), this, SLOT(eventsInserted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventList))); connect(m_monitor, SIGNAL(eventsDeleted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventIdList&)), this, SLOT(eventsDeleted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventIdList))); } void LogModel::eventsInserted(const QZeitgeist::DataModel::TimeRange &range, const QZeitgeist::DataModel::EventList &events) { QZeitgeist::DataModel::EventList oldEvents = m_events; foreach(const QZeitgeist::DataModel::Event &evt, events) { oldEvents << evt; } diffEvents(oldEvents); } void LogModel::eventsDeleted(const QZeitgeist::DataModel::TimeRange &range, const QZeitgeist::DataModel::EventIdList &events) { QZeitgeist::DataModel::EventList oldEvents = m_events; foreach(int id, events) { foreach(const QZeitgeist::DataModel::Event &evt, oldEvents) { if (evt.id() == id) oldEvents.removeOne(evt); } } diffEvents(oldEvents); } void LogModel::refreshDone(const QZeitgeist::DataModel::EventList &results) { diffEvents(results); } int LogModel::rowCount(const QModelIndex &idx) const { if (idx.isValid()) return 0; return m_events.size(); } int LogModel::columnCount(const QModelIndex &idx) const { if (idx.isValid()) return 0; return 1; } QModelIndex LogModel::parent(const QModelIndex &idx) const { Q_UNUSED(idx); return QModelIndex(); } QVariant LogModel::data(const QModelIndex &idx, int role) const { if (idx.isValid() && idx.row() >= 0 && idx.row() < rowCount() && idx.column() == 0) { QZeitgeist::DataModel::Event event = m_events[idx.row()]; switch(role) { case Qt::DisplayRole: return event.subjects()[0].text(); case Qt::DecorationRole: return iconForEvent(event); case EventRole: return QVariant::fromValue<QZeitgeist::DataModel::Event>(event); case TimeRole: return event.timestamp(); case IDRole: return event.id(); case URLRole: return event.subjects()[0].uri(); case MimeRole: return event.subjects()[0].mimeType(); case ActorRole: return event.actor(); case ThumbnailRole: return thumbnailForEvent(event); default: return QVariant(); } } return QVariant(); } QPixmap LogModel::thumbnailForEvent(const QZeitgeist::DataModel::Event &event) const { //FIXME: Implement caching QString url(event.subjects()[0].uri()); QDir thumbDir(QString("%1/.thumbnails/large/").arg(QDir::homePath())); QString snapshotName = QString("%1.png").arg(QString(QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5).toHex())); if (thumbDir.exists(snapshotName)) { return QPixmap(thumbDir.absoluteFilePath(snapshotName), "JPEG"); } return QPixmap(); } QIcon LogModel::iconForActor(const QString &actor) const { QString desktopFile = QUrl(actor).authority().section('.', 0, 0); return QIcon::fromTheme(desktopFile); } QIcon LogModel::iconForEvent(const QZeitgeist::DataModel::Event &event) const { QFileIconProvider icons; QIcon ret = iconForActor(event.actor()); if (m_iconMode == ActorIcons) return ret; foreach(QZeitgeist::DataModel::Subject subject, event.subjects()) { QUrl url = subject.uri(); if (url.scheme() == "file") { QFileInfo info(url.path()); ret = icons.icon(info); if (!ret.isNull()) break; } } if (ret.isNull()) ret = iconForActor(event.actor()); } QModelIndex LogModel::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid() && row >= 0 && row < rowCount() && column == 0) return createIndex(row, column); return QModelIndex(); } void LogModel::setRange(const QZeitgeist::DataModel::TimeRange &range) { m_range = range; refresh(); } Qt::ItemFlags LogModel::flags(const QModelIndex &index) const { if (index.isValid() && index.row() >= 0 && index.row() < rowCount() && index.column() == 0) return Qt::ItemIsEnabled | Qt::ItemIsSelectable; return 0; } QStringList LogModel::eventIconOverlays(const QZeitgeist::DataModel::Event &event) const { QStringList overlays; QZeitgeist::DataModel::Subject subject = event.subjects()[0]; /*switch(subject.interpretation()) { case QZeitgeist::Interpretation::Subject::NFOAudio: overlays << "applications-m }*/ QString mime = subject.mimeType(); overlays << mime.replace('/', '-'); return overlays; } QZeitgeist::DataModel::TimeRange LogModel::range() const { return m_range; } void LogModel::setResultType(QZeitgeist::Log::ResultType type) { m_type = type; refresh(); } QZeitgeist::Log::ResultType LogModel::resultType() const { return m_type; } void LogModel::setEventTemplates(const QZeitgeist::DataModel::EventList &templates) { m_eventTemplates = templates; refresh(); } DataModel::EventList LogModel::eventTemplates() const { return m_eventTemplates; } } // namespace QZeitgeist #include "logmodel.moc" <|endoftext|>
<commit_before>// // Created by Gerard Canal <gcanal@iri.upc.edu> on 11/10/18. // #include <rosplan_knowledge_msgs/GetAttributeService.h> #include "rosplan_planning_system/PlanDispatch/PlanDispatcher.h" namespace KCL_rosplan { PlanDispatcher::PlanDispatcher(ros::NodeHandle& nh): as_(nh, "dispatch_plan_action", false) { node_handle = &nh; kb_ = "knowledge_base"; node_handle->getParam("knowledge_base", kb_); std::stringstream ss; ss << "/" << kb_ << "/query_state"; queryKnowledgeClient = node_handle->serviceClient<rosplan_knowledge_msgs::KnowledgeQueryService>(ss.str()); ss.str(""); ss << "/" << kb_ << "/domain/operator_details"; queryDomainClient = node_handle->serviceClient<rosplan_knowledge_msgs::GetDomainOperatorDetailsService>(ss.str()); ss.str(""); ss << "/" << kb_ << "/state/goals"; get_goals = node_handle->serviceClient<rosplan_knowledge_msgs::GetAttributeService>(ss.str()); ss.str(""); // Register actionlib callbacks as_.registerGoalCallback(boost::bind(&KCL_rosplan::PlanDispatcher::dispatchPlanActionlib, this)); as_.registerPreemptCallback(boost::bind(&KCL_rosplan::PlanDispatcher::cancelDispatch, this)); as_.start(); // Start the action // start the plan parsing services service1 = nh.advertiseService("dispatch_plan", &KCL_rosplan::PlanDispatcher::dispatchPlanService, this); service2 = nh.advertiseService("cancel_dispatch", &KCL_rosplan::PlanDispatcher::cancelDispatchService, this); dispatching = false; // Action topics action_dispatch_topic = "action_dispatch"; action_feedback_topic = "action_feedback"; nh.getParam("action_dispatch_topic", action_dispatch_topic); nh.getParam("action_feedback_topic", action_feedback_topic); action_dispatch_publisher = node_handle->advertise<rosplan_dispatch_msgs::ActionDispatch>(action_dispatch_topic, 1, true); action_feedback_publisher = node_handle->advertise<rosplan_dispatch_msgs::ActionFeedback>(action_feedback_topic, 1, true); } void PlanDispatcher::publishFeedback(const rosplan_dispatch_msgs::ActionFeedback &fb) { if (as_.isActive()) { // Action server is the one dispatching rosplan_dispatch_msgs::NonBlockingDispatchFeedback afeedback; afeedback.feedback = fb; as_.publishFeedback(afeedback); } // Publish feedback in topic anyway... action_feedback_publisher.publish(fb); } bool PlanDispatcher::cancelDispatch() { if (as_.isNewGoalAvailable()) { // Preempt caused by sending of new goal, ignore it //ROS_WARN("KCL: (%s) Got a new dispatch request but a plan is already being dispatched!", ros::this_node::getName().c_str()); // Don't cancel a goal as it is being preempted because of a new goal sent return false; } ROS_INFO("KCL: (%s) Cancel plan command received.", ros::this_node::getName().c_str()); if (as_.isActive()) as_.setPreempted(); plan_cancelled = true; return true; } bool PlanDispatcher::cancelDispatchService(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) { return cancelDispatch(); } /*--------------------*/ /* Dispatch interface */ /*--------------------*/ /** * plan dispatch service method (1) * dispatches plan as a service * @returns True iff every action was dispatched and returned success. */ bool PlanDispatcher::dispatchPlanService(rosplan_dispatch_msgs::DispatchService::Request &req, rosplan_dispatch_msgs::DispatchService::Response &res) { if (dispatching) return false; dispatching = true; bool success = dispatchPlan(mission_start_time,ros::WallTime::now().toSec()); dispatching = false; reset(); res.success = success; res.goal_achieved = goalAchieved(); return true; } /** * plan dispatch action method (2) * dispatches plan as a service * @returns True iff every action was dispatched and returned success. */ void PlanDispatcher::dispatchPlanActionlib() { if (as_.isActive() or dispatching) { ROS_WARN("KCL: (%s) Got a new dispatch request but a plan is already being dispatched! It will be ignored", ros::this_node::getName().c_str()); } else { as_.acceptNewGoal(); dispatching = true; bool success = dispatchPlan(mission_start_time, ros::WallTime::now().toSec()); dispatching = false; reset(); rosplan_dispatch_msgs::NonBlockingDispatchResult res; res.success = success; res.goal_achieved = goalAchieved(); as_.setSucceeded(res); } } void PlanDispatcher::reset() { replan_requested = false; dispatch_paused = false; plan_cancelled = false; action_received.clear(); action_completed.clear(); plan_received = false; dispatching = false; } /** * Returns true of the actions preconditions are true in the current state. Calls the Knowledge Base. */ bool PlanDispatcher::checkPreconditions(rosplan_dispatch_msgs::ActionDispatch msg) { // get domain opertor details rosplan_knowledge_msgs::GetDomainOperatorDetailsService srv; srv.request.name = msg.name; if(!queryDomainClient.call(srv)) { ROS_ERROR("KCL: (%s) could not call Knowledge Base for operator details, %s", ros::this_node::getName().c_str(), msg.name.c_str()); return false; } // setup service call rosplan_knowledge_msgs::DomainOperator op = srv.response.op; rosplan_knowledge_msgs::KnowledgeQueryService querySrv; // iterate through conditions std::vector<rosplan_knowledge_msgs::DomainFormula>::iterator cit = op.at_start_simple_condition.begin(); for(; cit!=op.at_start_simple_condition.end(); cit++) { // create condition rosplan_knowledge_msgs::KnowledgeItem condition; condition.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::FACT; condition.attribute_name = cit->name; // populate parameters for(int i=0; i<cit->typed_parameters.size(); i++) { // set parameter label to predicate label diagnostic_msgs::KeyValue param; param.key = cit->typed_parameters[i].key; // search for correct operator parameter value for(int j=0; j<msg.parameters.size() && j<op.formula.typed_parameters.size(); j++) { if(op.formula.typed_parameters[j].key == cit->typed_parameters[i].key) { param.value = msg.parameters[j].value; } } condition.values.push_back(param); } querySrv.request.knowledge.push_back(condition); } // check conditions in knowledge base if (queryKnowledgeClient.call(querySrv)) { if(!querySrv.response.all_true) { std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator kit; for(kit=querySrv.response.false_knowledge.begin(); kit != querySrv.response.false_knowledge.end(); kit++) ROS_INFO("KCL: (%s) Precondition not achieved: %s", ros::this_node::getName().c_str(), kit->attribute_name.c_str()); } return querySrv.response.all_true; } else { ROS_ERROR("KCL: (%s) Failed to call service query_state", ros::this_node::getName().c_str()); } } bool PlanDispatcher::goalAchieved() { rosplan_knowledge_msgs::GetAttributeService goal; if (not get_goals.call(goal)) { ROS_ERROR("KCL: (%s) Failed to call service get_goals", ros::this_node::getName().c_str()); return false; } if (goal.response.attributes.empty()) return false; rosplan_knowledge_msgs::KnowledgeQueryService querySrv; querySrv.request.knowledge = goal.response.attributes; if (not queryKnowledgeClient.call(querySrv)) { ROS_ERROR("KCL: (%s) Failed to call service query_state", ros::this_node::getName().c_str()); return false; } return querySrv.response.all_true; } }<commit_msg>Fixed goal check when empty goal<commit_after>// // Created by Gerard Canal <gcanal@iri.upc.edu> on 11/10/18. // #include <rosplan_knowledge_msgs/GetAttributeService.h> #include "rosplan_planning_system/PlanDispatch/PlanDispatcher.h" namespace KCL_rosplan { PlanDispatcher::PlanDispatcher(ros::NodeHandle& nh): as_(nh, "dispatch_plan_action", false) { node_handle = &nh; kb_ = "knowledge_base"; node_handle->getParam("knowledge_base", kb_); std::stringstream ss; ss << "/" << kb_ << "/query_state"; queryKnowledgeClient = node_handle->serviceClient<rosplan_knowledge_msgs::KnowledgeQueryService>(ss.str()); ss.str(""); ss << "/" << kb_ << "/domain/operator_details"; queryDomainClient = node_handle->serviceClient<rosplan_knowledge_msgs::GetDomainOperatorDetailsService>(ss.str()); ss.str(""); ss << "/" << kb_ << "/state/goals"; get_goals = node_handle->serviceClient<rosplan_knowledge_msgs::GetAttributeService>(ss.str()); ss.str(""); // Register actionlib callbacks as_.registerGoalCallback(boost::bind(&KCL_rosplan::PlanDispatcher::dispatchPlanActionlib, this)); as_.registerPreemptCallback(boost::bind(&KCL_rosplan::PlanDispatcher::cancelDispatch, this)); as_.start(); // Start the action // start the plan parsing services service1 = nh.advertiseService("dispatch_plan", &KCL_rosplan::PlanDispatcher::dispatchPlanService, this); service2 = nh.advertiseService("cancel_dispatch", &KCL_rosplan::PlanDispatcher::cancelDispatchService, this); dispatching = false; // Action topics action_dispatch_topic = "action_dispatch"; action_feedback_topic = "action_feedback"; nh.getParam("action_dispatch_topic", action_dispatch_topic); nh.getParam("action_feedback_topic", action_feedback_topic); action_dispatch_publisher = node_handle->advertise<rosplan_dispatch_msgs::ActionDispatch>(action_dispatch_topic, 1, true); action_feedback_publisher = node_handle->advertise<rosplan_dispatch_msgs::ActionFeedback>(action_feedback_topic, 1, true); } void PlanDispatcher::publishFeedback(const rosplan_dispatch_msgs::ActionFeedback &fb) { if (as_.isActive()) { // Action server is the one dispatching rosplan_dispatch_msgs::NonBlockingDispatchFeedback afeedback; afeedback.feedback = fb; as_.publishFeedback(afeedback); } // Publish feedback in topic anyway... action_feedback_publisher.publish(fb); } bool PlanDispatcher::cancelDispatch() { if (as_.isNewGoalAvailable()) { // Preempt caused by sending of new goal, ignore it //ROS_WARN("KCL: (%s) Got a new dispatch request but a plan is already being dispatched!", ros::this_node::getName().c_str()); // Don't cancel a goal as it is being preempted because of a new goal sent return false; } ROS_INFO("KCL: (%s) Cancel plan command received.", ros::this_node::getName().c_str()); if (as_.isActive()) as_.setPreempted(); plan_cancelled = true; return true; } bool PlanDispatcher::cancelDispatchService(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) { return cancelDispatch(); } /*--------------------*/ /* Dispatch interface */ /*--------------------*/ /** * plan dispatch service method (1) * dispatches plan as a service * @returns True iff every action was dispatched and returned success. */ bool PlanDispatcher::dispatchPlanService(rosplan_dispatch_msgs::DispatchService::Request &req, rosplan_dispatch_msgs::DispatchService::Response &res) { if (dispatching) return false; dispatching = true; bool success = dispatchPlan(mission_start_time,ros::WallTime::now().toSec()); dispatching = false; reset(); res.success = success; res.goal_achieved = goalAchieved(); return true; } /** * plan dispatch action method (2) * dispatches plan as a service * @returns True iff every action was dispatched and returned success. */ void PlanDispatcher::dispatchPlanActionlib() { if (as_.isActive() or dispatching) { ROS_WARN("KCL: (%s) Got a new dispatch request but a plan is already being dispatched! It will be ignored", ros::this_node::getName().c_str()); } else { as_.acceptNewGoal(); dispatching = true; bool success = dispatchPlan(mission_start_time, ros::WallTime::now().toSec()); dispatching = false; reset(); rosplan_dispatch_msgs::NonBlockingDispatchResult res; res.success = success; res.goal_achieved = goalAchieved(); as_.setSucceeded(res); } } void PlanDispatcher::reset() { replan_requested = false; dispatch_paused = false; plan_cancelled = false; action_received.clear(); action_completed.clear(); plan_received = false; dispatching = false; } /** * Returns true of the actions preconditions are true in the current state. Calls the Knowledge Base. */ bool PlanDispatcher::checkPreconditions(rosplan_dispatch_msgs::ActionDispatch msg) { // get domain opertor details rosplan_knowledge_msgs::GetDomainOperatorDetailsService srv; srv.request.name = msg.name; if(!queryDomainClient.call(srv)) { ROS_ERROR("KCL: (%s) could not call Knowledge Base for operator details, %s", ros::this_node::getName().c_str(), msg.name.c_str()); return false; } // setup service call rosplan_knowledge_msgs::DomainOperator op = srv.response.op; rosplan_knowledge_msgs::KnowledgeQueryService querySrv; // iterate through conditions std::vector<rosplan_knowledge_msgs::DomainFormula>::iterator cit = op.at_start_simple_condition.begin(); for(; cit!=op.at_start_simple_condition.end(); cit++) { // create condition rosplan_knowledge_msgs::KnowledgeItem condition; condition.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::FACT; condition.attribute_name = cit->name; // populate parameters for(int i=0; i<cit->typed_parameters.size(); i++) { // set parameter label to predicate label diagnostic_msgs::KeyValue param; param.key = cit->typed_parameters[i].key; // search for correct operator parameter value for(int j=0; j<msg.parameters.size() && j<op.formula.typed_parameters.size(); j++) { if(op.formula.typed_parameters[j].key == cit->typed_parameters[i].key) { param.value = msg.parameters[j].value; } } condition.values.push_back(param); } querySrv.request.knowledge.push_back(condition); } // check conditions in knowledge base if (queryKnowledgeClient.call(querySrv)) { if(!querySrv.response.all_true) { std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator kit; for(kit=querySrv.response.false_knowledge.begin(); kit != querySrv.response.false_knowledge.end(); kit++) ROS_INFO("KCL: (%s) Precondition not achieved: %s", ros::this_node::getName().c_str(), kit->attribute_name.c_str()); } return querySrv.response.all_true; } else { ROS_ERROR("KCL: (%s) Failed to call service query_state", ros::this_node::getName().c_str()); } } bool PlanDispatcher::goalAchieved() { rosplan_knowledge_msgs::GetAttributeService goal; if (not get_goals.call(goal)) { ROS_ERROR("KCL: (%s) Failed to call service get_goals", ros::this_node::getName().c_str()); return false; } if (goal.response.attributes.empty()) return true; rosplan_knowledge_msgs::KnowledgeQueryService querySrv; querySrv.request.knowledge = goal.response.attributes; if (not queryKnowledgeClient.call(querySrv)) { ROS_ERROR("KCL: (%s) Failed to call service query_state", ros::this_node::getName().c_str()); return false; } return querySrv.response.all_true; } }<|endoftext|>
<commit_before>/* Copyright 2019 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/lite/delegates/gpu/gl/compiler/shader_codegen.h" #include <algorithm> #include "absl/strings/str_cat.h" #include "tensorflow/lite/delegates/gpu/common/status.h" #include "tensorflow/lite/delegates/gpu/gl/compiler/preprocessor.h" #include "tensorflow/lite/delegates/gpu/gl/compiler/variable_accessor.h" #include "tensorflow/lite/delegates/gpu/gl/variable.h" namespace tflite { namespace gpu { namespace gl { ShaderCodegen::ShaderCodegen(const CompilationOptions& options, const GpuInfo& gpu_info) : options_(options), gpu_type_(gpu_info.type) {} Status ShaderCodegen::Build(CompiledNodeAttributes attr, ShaderCode* shader_code) const { VariableAccessor variable_accessor(options_.inline_parameters); ObjectAccessor objects(gpu_type_ == GpuType::MALI, options_.sampler_textures, &variable_accessor); auto add_object = [&](const std::string& name, Object&& object) { if (!objects.AddObject(name, std::forward<Object>(object))) { return InternalError("There is an object with the same name"); } return OkStatus(); }; auto add_uniform_parameter = [&](Variable&& param) { if (!variable_accessor.AddUniformParameter(std::forward<Variable>(param))) { return InternalError("There is a parameter with the same name"); } return OkStatus(); }; for (auto&& param : attr.code.parameters) { RETURN_IF_ERROR(add_uniform_parameter(std::move(param))); } for (auto&& object : attr.code.objects) { RETURN_IF_ERROR(add_object(object.first, std::move(object.second))); } int index = 0; for (auto&& input : attr.inputs) { RETURN_IF_ERROR( add_object(absl::StrCat("input_data_", index++), std::move(input))); } index = 0; for (auto&& output : attr.outputs) { RETURN_IF_ERROR( add_object(absl::StrCat("output_data_", index++), std::move(output))); } // TODO(akulik): workload params need to go away and be replaced with // output_data_0_w RETURN_IF_ERROR(add_uniform_parameter( {"workload_x", static_cast<int32_t>(attr.code.workload.x)})); RETURN_IF_ERROR(add_uniform_parameter( {"workload_y", static_cast<int32_t>(attr.code.workload.y)})); RETURN_IF_ERROR(add_uniform_parameter( {"workload_z", static_cast<int32_t>(attr.code.workload.z)})); std::string source_code = R"( ivec3 gid = ivec3(gl_GlobalInvocationID.xyz); if (gid.x >= $workload_x$ || gid.y >= $workload_y$ || gid.z >= $workload_z$) { return; } )"; switch (attr.code.input) { case IOStructure::ONLY_DEFINITIONS: for (int i = 0; i < attr.inputs.size(); ++i) { absl::StrAppend(&source_code, " highp vec4 value_", i, " = vec4(0);\n"); } break; case IOStructure::AUTO: { for (int i = 0; i < attr.inputs.size(); ++i) { absl::StrAppend(&source_code, " highp vec4 value_", i, " = $input_data_", i, "[gid.x, gid.y, gid.z]$;\n"); } break; } } source_code.append(attr.code.source_code); if (attr.code.output == IOStructure::AUTO) { for (int i = 0; i < attr.outputs.size(); ++i) { absl::StrAppend(&source_code, " $output_data_", i, "[gid.x, gid.y, gid.z] = value_", i, "$;\n"); } } // At this point main function is already generated. Now we need to process // object and parameter accessors. // process objects first. Object accessor may introduce new uniform // parameters that need to be rewritten in the subsequent pass. { TextPreprocessor preprocessor('$', /*keep_unknown_rewrites=*/true); preprocessor.AddRewrite(&objects); RETURN_IF_ERROR(preprocessor.Rewrite(source_code, &source_code)); } { TextPreprocessor preprocessor('$', /*keep_unknown_rewrites=*/false); preprocessor.AddRewrite(&variable_accessor); RETURN_IF_ERROR(preprocessor.Rewrite(source_code, &source_code)); } if (options_.inline_parameters) { source_code = absl::StrCat(variable_accessor.GetConstDeclarations(), source_code); } std::string declarations = absl::StrCat( objects.GetFunctionsDeclarations(), "\n", objects.GetObjectDeclarations(), "\n", variable_accessor.GetUniformParameterDeclarations()); *shader_code = ShaderCode( variable_accessor.GetUniformParameters(), objects.GetObjects(), attr.code.workload, attr.code.workgroup, absl::StrCat("layout(std430) buffer;\nprecision ", options_.allow_precision_loss ? "mediump" : "highp", " float;\n", declarations, "\nvoid main() {\n", source_code, "\n}"), attr.node_indices); return OkStatus(); } } // namespace gl } // namespace gpu } // namespace tflite <commit_msg>TFLite GPU OpenGL: Reflect shared variables to shader code generation.<commit_after>/* Copyright 2019 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/lite/delegates/gpu/gl/compiler/shader_codegen.h" #include <algorithm> #include "absl/strings/str_cat.h" #include "tensorflow/lite/delegates/gpu/common/status.h" #include "tensorflow/lite/delegates/gpu/gl/compiler/preprocessor.h" #include "tensorflow/lite/delegates/gpu/gl/compiler/variable_accessor.h" #include "tensorflow/lite/delegates/gpu/gl/variable.h" namespace tflite { namespace gpu { namespace gl { ShaderCodegen::ShaderCodegen(const CompilationOptions& options, const GpuInfo& gpu_info) : options_(options), gpu_type_(gpu_info.type) {} Status ShaderCodegen::Build(CompiledNodeAttributes attr, ShaderCode* shader_code) const { VariableAccessor variable_accessor(options_.inline_parameters); ObjectAccessor object_accessor(gpu_type_ == GpuType::MALI, options_.sampler_textures, &variable_accessor); const auto add_object = [&](const std::string& name, Object&& object) { if (!object_accessor.AddObject(name, std::forward<Object>(object))) { return AlreadyExistsError(absl::StrCat("Object \"", name, "\"")); } return OkStatus(); }; const auto add_uniform_parameter = [&](Variable&& variable) { const std::string name = variable.name; if (!variable_accessor.AddUniformParameter(std::move(variable))) { return AlreadyExistsError( absl::StrCat("Uniform parameter \"", name, "\"")); } return OkStatus(); }; for (auto&& object : attr.code.objects) { RETURN_IF_ERROR(add_object(object.first, std::move(object.second))); } for (auto&& variable : attr.code.shared_variables) { const std::string name = variable.name; if (!variable_accessor.AddSharedVariable(std::move(variable))) { return AlreadyExistsError(absl::StrCat("Shared variable \"", name, "\"")); } } for (auto&& variable : attr.code.parameters) { RETURN_IF_ERROR(add_uniform_parameter(std::move(variable))); } int index = 0; for (auto&& input : attr.inputs) { RETURN_IF_ERROR( add_object(absl::StrCat("input_data_", index++), std::move(input))); } index = 0; for (auto&& output : attr.outputs) { RETURN_IF_ERROR( add_object(absl::StrCat("output_data_", index++), std::move(output))); } // TODO(akulik): workload params need to go away and be replaced with // output_data_0_w RETURN_IF_ERROR(add_uniform_parameter( {"workload_x", static_cast<int32_t>(attr.code.workload.x)})); RETURN_IF_ERROR(add_uniform_parameter( {"workload_y", static_cast<int32_t>(attr.code.workload.y)})); RETURN_IF_ERROR(add_uniform_parameter( {"workload_z", static_cast<int32_t>(attr.code.workload.z)})); std::string main_source_code = R"( ivec3 gid = ivec3(gl_GlobalInvocationID.xyz); if (gid.x >= $workload_x$ || gid.y >= $workload_y$ || gid.z >= $workload_z$) { return; } )"; switch (attr.code.input) { case IOStructure::ONLY_DEFINITIONS: for (int i = 0; i < attr.inputs.size(); ++i) { absl::StrAppend(&main_source_code, " highp vec4 value_", i, " = vec4(0);\n"); } break; case IOStructure::AUTO: { for (int i = 0; i < attr.inputs.size(); ++i) { absl::StrAppend(&main_source_code, " highp vec4 value_", i, " = $input_data_", i, "[gid.x, gid.y, gid.z]$;\n"); } break; } } main_source_code.append(attr.code.source_code); if (attr.code.output == IOStructure::AUTO) { for (int i = 0; i < attr.outputs.size(); ++i) { absl::StrAppend(&main_source_code, " $output_data_", i, "[gid.x, gid.y, gid.z] = value_", i, "$;\n"); } } // At this point main function is already generated. Now we need to process // object and variable accessors. // process objects first. Object accessor may introduce new uniform // parameters that need to be rewritten in the subsequent pass. { TextPreprocessor preprocessor('$', /*keep_unknown_rewrites=*/true); preprocessor.AddRewrite(&object_accessor); RETURN_IF_ERROR(preprocessor.Rewrite(main_source_code, &main_source_code)); } { TextPreprocessor preprocessor('$', /*keep_unknown_rewrites=*/false); preprocessor.AddRewrite(&variable_accessor); RETURN_IF_ERROR(preprocessor.Rewrite(main_source_code, &main_source_code)); } if (options_.inline_parameters) { main_source_code = absl::StrCat(variable_accessor.GetConstDeclarations(), main_source_code); } // partial_source_code is only missing the following which is added later: // #version 310 es // layout(local_size_x = ..., local_size_y = ..., local_size_z = ...) in; const char* precision = options_.allow_precision_loss ? "mediump" : "highp"; const std::string partial_source_code = absl::StrCat( "layout(std430) buffer;\n", // "precision ", precision, " float;\n", // object_accessor.GetFunctionsDeclarations(), "\n", // object_accessor.GetObjectDeclarations(), "\n", // variable_accessor.GetSharedVariableDeclarations(), "\n", // variable_accessor.GetUniformParameterDeclarations(), "\n", // "void main() {\n", // main_source_code, // "}"); *shader_code = ShaderCode(variable_accessor.GetUniformParameters(), object_accessor.GetObjects(), attr.code.workload, attr.code.workgroup, partial_source_code, attr.node_indices); return OkStatus(); } } // namespace gl } // namespace gpu } // namespace tflite <|endoftext|>
<commit_before>/** * \file * \brief FpuSignalTestCase class implementation for ARMv7-M (Cortex-M3 / Cortex-M4) * * \author Copyright (C) 2015-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "ARMv7-M-FpuSignalTestCase.hpp" #include "distortos/chip/CMSIS-proxy.h" #if __FPU_PRESENT == 1 && __FPU_USED == 1 #include "checkFpuRegisters.hpp" #include "setFpuRegisters.hpp" #include "distortos/DynamicThread.hpp" #include "distortos/StaticSoftwareTimer.hpp" #include "distortos/statistics.hpp" #include "distortos/ThisThread.hpp" #include "distortos/ThisThread-Signals.hpp" #endif // __FPU_PRESENT == 1 && __FPU_USED == 1 namespace distortos { namespace test { #if __FPU_PRESENT == 1 && __FPU_USED == 1 namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local types +---------------------------------------------------------------------------------------------------------------------*/ /// values used in single test stage struct Stage { /// value written to all FPU registers in main thread, don't use FPU in main thread if 0 uint32_t threadValue; /// value written to "lower" FPU registers in "sender" before queuing of signal, skip this step if 0 uint32_t senderValueBefore; /// value written to "lower" FPU registers in "sender" after queuing of signal, skip this step if 0 uint32_t senderValueAfter; /// signal value, written to "lower" FPU registers in handler, don't use FPU in handler if 0 int signalValue; }; /// description of single test phase struct Phase { /// type of "sender" function using Sender = int(Thread&, const Stage&); /// reference to "sender" function Sender& sender; /// expected number of context switches for single stage executed in this phase decltype(statistics::getContextSwitchCount()) contextSwitchCount; }; /*---------------------------------------------------------------------------------------------------------------------+ | local constants +---------------------------------------------------------------------------------------------------------------------*/ /// tested signal number constexpr uint8_t testSignalNumber {16}; /// size of stack for test thread, bytes constexpr size_t testThreadStackSize {512}; /*---------------------------------------------------------------------------------------------------------------------+ | local functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief Disables FPU context for current thread by clearing FPCA bit in CONTROL register. */ void disableFpuContext() { const auto control = __get_CONTROL(); __set_CONTROL(control & ~CONTROL_FPCA_Msk); } /** * \brief Signal handler * * Sets "lower" FPU registers (s0-s15 and FPSCR) using the value queued with signal, unless this value is 0. * * \param [in] signalInformation is a reference to received SignalInformation object */ void handler(const SignalInformation& signalInformation) { const auto value = signalInformation.getValue().sival_int; if (value == 0) return; setFpuRegisters(value, false); } /** * \brief Tests whether FPU context is active for current thread. * * \return true if FPU context is active for current thread (FPCA bit in CONTROL register is set), false otherwise */ bool isFpuContextActive() { const auto control = __get_CONTROL(); return (control & CONTROL_FPCA_Msk) != 0; } /** * \brief Test wrapper for Thread::queueSignal() that also modifies FPU registers. * * \param [in] thread is a reference to thread to which the signal will be queued * \param [in] stage is a reference to test stage * \param [in] full is the \a full argument passed to setFpuRegisters() * \param [in] sharedRet is a reference to int variable which will be written with 0 on success, error code otherwise */ void queueSignalWrapper(Thread& thread, const Stage& stage, const bool full, int& sharedRet) { if (stage.senderValueBefore != 0) // should FPU be used at the beginning of "sender"? setFpuRegisters(stage.senderValueBefore, full); sharedRet = thread.queueSignal(testSignalNumber, sigval{stage.signalValue}); if (stage.senderValueAfter != 0) // should FPU be used at th"sender""sender"? setFpuRegisters(stage.senderValueAfter, full); } /** * \brief Queues signal from interrupt (via software timer) to current thread. * * \param [in] thread is a reference to thread to which the signal will be queued * \param [in] stage is a reference to test stage * * \return 0 on success, error code otherwise: * - error codes returned by Thread::queueSignal(); */ int queueSignalFromInterrupt(Thread& thread, const Stage& stage) { int sharedRet {EINVAL}; auto softwareTimer = makeStaticSoftwareTimer(queueSignalWrapper, std::ref(thread), std::ref(stage), false, std::ref(sharedRet)); softwareTimer.start(TickClock::duration{}); while (softwareTimer.isRunning() == true); return sharedRet; } /** * \brief Queues signal from thread to non-current thread. * * \param [in] thread is a reference to thread to which the signal will be queued * \param [in] stage is a reference to test stage * * \return 0 on success, error code otherwise: * - error codes returned by Thread::queueSignal(); */ int queueSignalFromThread(Thread& thread, const Stage& stage) { constexpr decltype(FpuSignalTestCase::getTestCasePriority()) highPriority { FpuSignalTestCase::getTestCasePriority() + 1 }; int sharedRet {EINVAL}; auto testThread = makeAndStartDynamicThread({testThreadStackSize, highPriority}, queueSignalWrapper, std::ref(thread), std::ref(stage), true, std::ref(sharedRet)); testThread.join(); return sharedRet; } /*---------------------------------------------------------------------------------------------------------------------+ | local constants +---------------------------------------------------------------------------------------------------------------------*/ /// test phasese const Phase phases[] { {queueSignalFromInterrupt, 0}, {queueSignalFromThread, 2}, }; /// test stages const Stage stages[] { {0, 0, 0, 0}, // don't use FPU in all contexts {0, 0, 0, 0x0b39fa96}, // in handler {0, 0, 0x8606151d, 0}, // in "sender" (at the end) {0, 0, 0x8bdd3b5e, 0x7d21d1c6}, // in "sender" (at the end) and in handler {0, 0x2f884196, 0, 0}, // in "sender" (at the beginning) {0, 0x0b0bbc86, 0, 0x0e43811b}, // in "sender" (at the beginning) and in handler {0, 0xb72b2917, 0x8c27baa7, 0}, // in "sender" {0, 0xa83b80c2, 0xd2b7dd4d, 0x626ca399}, // in "sender" and in handler {0xb4e40525, 0, 0, 0}, // in main thread {0x772bdf91, 0, 0, 0x0bb325b7}, // in main thread and in handler {0x8a19625e, 0, 0x32378f7b, 0}, // in main thread and in "sender" (at the end) {0xd17a21db, 0, 0xaa807a91, 0x03caf264}, // in main thread, in "sender" (at the end) and in handler {0xe4b44073, 0xa88c0cf5, 0, 0}, // in main thread and in "sender" (at the beginning) {0xb94c722b, 0x5f8ca773, 0, 0x288301cf}, // in main thread, in "sender" (at the beginning) and in handler {0x347ecfc5, 0xcb4a3584, 0x5a8bf219, 0}, // in main thread and in "sender" {0x788ed92e, 0x4b0ddff9, 0x73776a21, 0x48fb1969}, // in all contexts }; } // namespace #endif // __FPU_PRESENT == 1 && __FPU_USED == 1 /*---------------------------------------------------------------------------------------------------------------------+ | protected functions +---------------------------------------------------------------------------------------------------------------------*/ bool FpuSignalTestCase::finalize() const { #if __FPU_PRESENT == 1 && __FPU_USED == 1 disableFpuContext(); #endif // __FPU_PRESENT == 1 && __FPU_USED == 1 return SignalsTestCaseCommon::finalize(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ bool FpuSignalTestCase::run_() const { #if __FPU_PRESENT == 1 && __FPU_USED == 1 const auto contextSwitchCount = statistics::getContextSwitchCount(); auto expectedContextSwitchCount = decltype(contextSwitchCount){}; { int ret; std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber, SignalAction{handler, SignalSet{SignalSet::empty}}); if (ret != 0) return false; } auto& currentThread = ThisThread::get(); for (auto& phase : phases) for (auto& stage : stages) { disableFpuContext(); decltype(setFpuRegisters({}, {})) fpscr {}; if (stage.threadValue != 0) // should FPU be used in main thread? fpscr = setFpuRegisters(stage.threadValue, true); if (phase.sender(currentThread, stage) != 0) return false; // FPU context may be active only if FPU was used in main thread if (isFpuContextActive() != (stage.threadValue != 0)) return false; if (stage.threadValue != 0) // was FPU used in main thread? if (checkFpuRegisters(stage.threadValue, fpscr) == false) return false; expectedContextSwitchCount += phase.contextSwitchCount; if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount) return false; } if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount) return false; return true; #else return true; #endif // __FPU_PRESENT == 1 && __FPU_USED == 1 } } // namespace test } // namespace distortos <commit_msg>test: include <cerrno> in ARMv7-M-FpuSignalTestCase.cpp<commit_after>/** * \file * \brief FpuSignalTestCase class implementation for ARMv7-M (Cortex-M3 / Cortex-M4) * * \author Copyright (C) 2015-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "ARMv7-M-FpuSignalTestCase.hpp" #include "distortos/chip/CMSIS-proxy.h" #if __FPU_PRESENT == 1 && __FPU_USED == 1 #include "checkFpuRegisters.hpp" #include "setFpuRegisters.hpp" #include "distortos/DynamicThread.hpp" #include "distortos/StaticSoftwareTimer.hpp" #include "distortos/statistics.hpp" #include "distortos/ThisThread.hpp" #include "distortos/ThisThread-Signals.hpp" #include <cerrno> #endif // __FPU_PRESENT == 1 && __FPU_USED == 1 namespace distortos { namespace test { #if __FPU_PRESENT == 1 && __FPU_USED == 1 namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local types +---------------------------------------------------------------------------------------------------------------------*/ /// values used in single test stage struct Stage { /// value written to all FPU registers in main thread, don't use FPU in main thread if 0 uint32_t threadValue; /// value written to "lower" FPU registers in "sender" before queuing of signal, skip this step if 0 uint32_t senderValueBefore; /// value written to "lower" FPU registers in "sender" after queuing of signal, skip this step if 0 uint32_t senderValueAfter; /// signal value, written to "lower" FPU registers in handler, don't use FPU in handler if 0 int signalValue; }; /// description of single test phase struct Phase { /// type of "sender" function using Sender = int(Thread&, const Stage&); /// reference to "sender" function Sender& sender; /// expected number of context switches for single stage executed in this phase decltype(statistics::getContextSwitchCount()) contextSwitchCount; }; /*---------------------------------------------------------------------------------------------------------------------+ | local constants +---------------------------------------------------------------------------------------------------------------------*/ /// tested signal number constexpr uint8_t testSignalNumber {16}; /// size of stack for test thread, bytes constexpr size_t testThreadStackSize {512}; /*---------------------------------------------------------------------------------------------------------------------+ | local functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief Disables FPU context for current thread by clearing FPCA bit in CONTROL register. */ void disableFpuContext() { const auto control = __get_CONTROL(); __set_CONTROL(control & ~CONTROL_FPCA_Msk); } /** * \brief Signal handler * * Sets "lower" FPU registers (s0-s15 and FPSCR) using the value queued with signal, unless this value is 0. * * \param [in] signalInformation is a reference to received SignalInformation object */ void handler(const SignalInformation& signalInformation) { const auto value = signalInformation.getValue().sival_int; if (value == 0) return; setFpuRegisters(value, false); } /** * \brief Tests whether FPU context is active for current thread. * * \return true if FPU context is active for current thread (FPCA bit in CONTROL register is set), false otherwise */ bool isFpuContextActive() { const auto control = __get_CONTROL(); return (control & CONTROL_FPCA_Msk) != 0; } /** * \brief Test wrapper for Thread::queueSignal() that also modifies FPU registers. * * \param [in] thread is a reference to thread to which the signal will be queued * \param [in] stage is a reference to test stage * \param [in] full is the \a full argument passed to setFpuRegisters() * \param [in] sharedRet is a reference to int variable which will be written with 0 on success, error code otherwise */ void queueSignalWrapper(Thread& thread, const Stage& stage, const bool full, int& sharedRet) { if (stage.senderValueBefore != 0) // should FPU be used at the beginning of "sender"? setFpuRegisters(stage.senderValueBefore, full); sharedRet = thread.queueSignal(testSignalNumber, sigval{stage.signalValue}); if (stage.senderValueAfter != 0) // should FPU be used at th"sender""sender"? setFpuRegisters(stage.senderValueAfter, full); } /** * \brief Queues signal from interrupt (via software timer) to current thread. * * \param [in] thread is a reference to thread to which the signal will be queued * \param [in] stage is a reference to test stage * * \return 0 on success, error code otherwise: * - error codes returned by Thread::queueSignal(); */ int queueSignalFromInterrupt(Thread& thread, const Stage& stage) { int sharedRet {EINVAL}; auto softwareTimer = makeStaticSoftwareTimer(queueSignalWrapper, std::ref(thread), std::ref(stage), false, std::ref(sharedRet)); softwareTimer.start(TickClock::duration{}); while (softwareTimer.isRunning() == true); return sharedRet; } /** * \brief Queues signal from thread to non-current thread. * * \param [in] thread is a reference to thread to which the signal will be queued * \param [in] stage is a reference to test stage * * \return 0 on success, error code otherwise: * - error codes returned by Thread::queueSignal(); */ int queueSignalFromThread(Thread& thread, const Stage& stage) { constexpr decltype(FpuSignalTestCase::getTestCasePriority()) highPriority { FpuSignalTestCase::getTestCasePriority() + 1 }; int sharedRet {EINVAL}; auto testThread = makeAndStartDynamicThread({testThreadStackSize, highPriority}, queueSignalWrapper, std::ref(thread), std::ref(stage), true, std::ref(sharedRet)); testThread.join(); return sharedRet; } /*---------------------------------------------------------------------------------------------------------------------+ | local constants +---------------------------------------------------------------------------------------------------------------------*/ /// test phasese const Phase phases[] { {queueSignalFromInterrupt, 0}, {queueSignalFromThread, 2}, }; /// test stages const Stage stages[] { {0, 0, 0, 0}, // don't use FPU in all contexts {0, 0, 0, 0x0b39fa96}, // in handler {0, 0, 0x8606151d, 0}, // in "sender" (at the end) {0, 0, 0x8bdd3b5e, 0x7d21d1c6}, // in "sender" (at the end) and in handler {0, 0x2f884196, 0, 0}, // in "sender" (at the beginning) {0, 0x0b0bbc86, 0, 0x0e43811b}, // in "sender" (at the beginning) and in handler {0, 0xb72b2917, 0x8c27baa7, 0}, // in "sender" {0, 0xa83b80c2, 0xd2b7dd4d, 0x626ca399}, // in "sender" and in handler {0xb4e40525, 0, 0, 0}, // in main thread {0x772bdf91, 0, 0, 0x0bb325b7}, // in main thread and in handler {0x8a19625e, 0, 0x32378f7b, 0}, // in main thread and in "sender" (at the end) {0xd17a21db, 0, 0xaa807a91, 0x03caf264}, // in main thread, in "sender" (at the end) and in handler {0xe4b44073, 0xa88c0cf5, 0, 0}, // in main thread and in "sender" (at the beginning) {0xb94c722b, 0x5f8ca773, 0, 0x288301cf}, // in main thread, in "sender" (at the beginning) and in handler {0x347ecfc5, 0xcb4a3584, 0x5a8bf219, 0}, // in main thread and in "sender" {0x788ed92e, 0x4b0ddff9, 0x73776a21, 0x48fb1969}, // in all contexts }; } // namespace #endif // __FPU_PRESENT == 1 && __FPU_USED == 1 /*---------------------------------------------------------------------------------------------------------------------+ | protected functions +---------------------------------------------------------------------------------------------------------------------*/ bool FpuSignalTestCase::finalize() const { #if __FPU_PRESENT == 1 && __FPU_USED == 1 disableFpuContext(); #endif // __FPU_PRESENT == 1 && __FPU_USED == 1 return SignalsTestCaseCommon::finalize(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ bool FpuSignalTestCase::run_() const { #if __FPU_PRESENT == 1 && __FPU_USED == 1 const auto contextSwitchCount = statistics::getContextSwitchCount(); auto expectedContextSwitchCount = decltype(contextSwitchCount){}; { int ret; std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber, SignalAction{handler, SignalSet{SignalSet::empty}}); if (ret != 0) return false; } auto& currentThread = ThisThread::get(); for (auto& phase : phases) for (auto& stage : stages) { disableFpuContext(); decltype(setFpuRegisters({}, {})) fpscr {}; if (stage.threadValue != 0) // should FPU be used in main thread? fpscr = setFpuRegisters(stage.threadValue, true); if (phase.sender(currentThread, stage) != 0) return false; // FPU context may be active only if FPU was used in main thread if (isFpuContextActive() != (stage.threadValue != 0)) return false; if (stage.threadValue != 0) // was FPU used in main thread? if (checkFpuRegisters(stage.threadValue, fpscr) == false) return false; expectedContextSwitchCount += phase.contextSwitchCount; if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount) return false; } if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount) return false; return true; #else return true; #endif // __FPU_PRESENT == 1 && __FPU_USED == 1 } } // namespace test } // namespace distortos <|endoftext|>
<commit_before>/* * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/pc/e2e/stats_based_network_quality_metrics_reporter.h" #include <cstdint> #include <map> #include <memory> #include <set> #include <string> #include <type_traits> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/scoped_refptr.h" #include "api/stats/rtc_stats.h" #include "api/stats/rtcstats_objects.h" #include "api/test/network_emulation/network_emulation_interfaces.h" #include "api/test/network_emulation_manager.h" #include "api/units/data_rate.h" #include "api/units/timestamp.h" #include "rtc_base/event.h" #include "rtc_base/ip_address.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/synchronization/mutex.h" #include "system_wrappers/include/field_trial.h" #include "test/testsupport/perf_test.h" namespace webrtc { namespace webrtc_pc_e2e { namespace { constexpr int kStatsWaitTimeoutMs = 1000; // Field trial which controls whether to report standard-compliant bytes // sent/received per stream. If enabled, padding and headers are not included // in bytes sent or received. constexpr char kUseStandardBytesStats[] = "WebRTC-UseStandardBytesStats"; std::unique_ptr<EmulatedNetworkStats> PopulateStats( std::vector<EmulatedEndpoint*> endpoints, NetworkEmulationManager* network_emulation) { rtc::Event stats_loaded; std::unique_ptr<EmulatedNetworkStats> stats; network_emulation->GetStats(endpoints, [&](std::unique_ptr<EmulatedNetworkStats> s) { stats = std::move(s); stats_loaded.Set(); }); bool stats_received = stats_loaded.Wait(kStatsWaitTimeoutMs); RTC_CHECK(stats_received); return stats; } std::map<rtc::IPAddress, std::string> PopulateIpToPeer( const std::map<std::string, std::vector<EmulatedEndpoint*>>& peer_endpoints) { std::map<rtc::IPAddress, std::string> out; for (const auto& entry : peer_endpoints) { for (const EmulatedEndpoint* const endpoint : entry.second) { out.emplace(endpoint->GetPeerLocalAddress(), entry.first); } } return out; } } // namespace StatsBasedNetworkQualityMetricsReporter::NetworkLayerStatsCollector:: NetworkLayerStatsCollector( std::map<std::string, std::vector<EmulatedEndpoint*>> peer_endpoints, NetworkEmulationManager* network_emulation) : peer_endpoints_(std::move(peer_endpoints)), ip_to_peer_(PopulateIpToPeer(peer_endpoints_)), network_emulation_(network_emulation) {} void StatsBasedNetworkQualityMetricsReporter::NetworkLayerStatsCollector:: Start() { // Check that network stats are clean before test execution. for (const auto& entry : peer_endpoints_) { std::unique_ptr<EmulatedNetworkStats> stats = PopulateStats(entry.second, network_emulation_); RTC_CHECK_EQ(stats->PacketsSent(), 0); RTC_CHECK_EQ(stats->PacketsReceived(), 0); } } std::map<std::string, StatsBasedNetworkQualityMetricsReporter::NetworkLayerStats> StatsBasedNetworkQualityMetricsReporter::NetworkLayerStatsCollector:: GetStats() { std::map<std::string, NetworkLayerStats> peer_to_stats; std::map<std::string, std::vector<std::string>> sender_to_receivers; for (const auto& entry : peer_endpoints_) { NetworkLayerStats stats; stats.stats = PopulateStats(entry.second, network_emulation_); const std::string& peer_name = entry.first; for (const auto& income_stats_entry : stats.stats->IncomingStatsPerSource()) { const rtc::IPAddress& source_ip = income_stats_entry.first; auto it = ip_to_peer_.find(source_ip); if (it == ip_to_peer_.end()) { // Source IP is unknown for this collector, so will be skipped. continue; } sender_to_receivers[it->second].push_back(peer_name); } peer_to_stats.emplace(peer_name, std::move(stats)); } for (auto& entry : peer_to_stats) { const std::vector<std::string>& receivers = sender_to_receivers[entry.first]; entry.second.receivers = std::set<std::string>(receivers.begin(), receivers.end()); } return peer_to_stats; } void StatsBasedNetworkQualityMetricsReporter::Start( absl::string_view test_case_name, const TrackIdStreamInfoMap* reporter_helper) { test_case_name_ = std::string(test_case_name); collector_.Start(); start_time_ = clock_->CurrentTime(); } void StatsBasedNetworkQualityMetricsReporter::OnStatsReports( absl::string_view pc_label, const rtc::scoped_refptr<const RTCStatsReport>& report) { PCStats cur_stats; auto inbound_stats = report->GetStatsOfType<RTCInboundRTPStreamStats>(); for (const auto& stat : inbound_stats) { cur_stats.payload_received += DataSize::Bytes(stat->bytes_received.ValueOrDefault(0ul) + stat->header_bytes_received.ValueOrDefault(0ul)); } auto outbound_stats = report->GetStatsOfType<RTCOutboundRTPStreamStats>(); for (const auto& stat : outbound_stats) { cur_stats.payload_sent += DataSize::Bytes(stat->bytes_sent.ValueOrDefault(0ul) + stat->header_bytes_sent.ValueOrDefault(0ul)); } auto candidate_pairs_stats = report->GetStatsOfType<RTCTransportStats>(); for (const auto& stat : candidate_pairs_stats) { cur_stats.total_received += DataSize::Bytes(stat->bytes_received.ValueOrDefault(0ul)); cur_stats.total_sent += DataSize::Bytes(stat->bytes_sent.ValueOrDefault(0ul)); cur_stats.packets_received += stat->packets_received.ValueOrDefault(0ul); cur_stats.packets_sent += stat->packets_sent.ValueOrDefault(0ul); } MutexLock lock(&mutex_); pc_stats_[std::string(pc_label)] = cur_stats; } void StatsBasedNetworkQualityMetricsReporter::StopAndReportResults() { Timestamp end_time = clock_->CurrentTime(); if (!webrtc::field_trial::IsEnabled(kUseStandardBytesStats)) { RTC_LOG(LS_ERROR) << "Non-standard GetStats; \"payload\" counts include RTP headers"; } std::map<std::string, NetworkLayerStats> stats = collector_.GetStats(); for (const auto& entry : stats) { LogNetworkLayerStats(entry.first, entry.second); } MutexLock lock(&mutex_); for (const auto& pair : pc_stats_) { auto it = stats.find(pair.first); RTC_CHECK(it != stats.end()) << "Peer name used for PeerConnection stats collection and peer name " "used for endpoints naming doesn't match. No endpoints found for " "peer " << pair.first; const NetworkLayerStats& network_layer_stats = it->second; int64_t total_packets_received = 0; bool found = false; for (const auto& dest_peer : network_layer_stats.receivers) { auto pc_stats_it = pc_stats_.find(dest_peer); if (pc_stats_it == pc_stats_.end()) { continue; } found = true; total_packets_received += pc_stats_it->second.packets_received; } int64_t packet_loss = -1; if (found) { packet_loss = pair.second.packets_sent - total_packets_received; } ReportStats(pair.first, pair.second, network_layer_stats, packet_loss, end_time); } } void StatsBasedNetworkQualityMetricsReporter::ReportStats( const std::string& pc_label, const PCStats& pc_stats, const NetworkLayerStats& network_layer_stats, int64_t packet_loss, const Timestamp& end_time) { ReportResult("bytes_dropped", pc_label, network_layer_stats.stats->BytesDropped().bytes(), "sizeInBytes"); ReportResult("packets_dropped", pc_label, network_layer_stats.stats->PacketsDropped(), "unitless"); ReportResult("payload_bytes_received", pc_label, pc_stats.payload_received.bytes(), "sizeInBytes"); ReportResult("payload_bytes_sent", pc_label, pc_stats.payload_sent.bytes(), "sizeInBytes"); ReportResult("bytes_sent", pc_label, pc_stats.total_sent.bytes(), "sizeInBytes"); ReportResult("packets_sent", pc_label, pc_stats.packets_sent, "unitless"); ReportResult("average_send_rate", pc_label, (pc_stats.total_sent / (end_time - start_time_)).bytes_per_sec(), "bytesPerSecond"); ReportResult("bytes_received", pc_label, pc_stats.total_received.bytes(), "sizeInBytes"); ReportResult("packets_received", pc_label, pc_stats.packets_received, "unitless"); ReportResult( "average_receive_rate", pc_label, (pc_stats.total_received / (end_time - start_time_)).bytes_per_sec(), "bytesPerSecond"); ReportResult("sent_packets_loss", pc_label, packet_loss, "unitless"); } void StatsBasedNetworkQualityMetricsReporter::ReportResult( const std::string& metric_name, const std::string& network_label, const double value, const std::string& unit) const { test::PrintResult(metric_name, /*modifier=*/"", GetTestCaseName(network_label), value, unit, /*important=*/false); } void StatsBasedNetworkQualityMetricsReporter::ReportResult( const std::string& metric_name, const std::string& network_label, const SamplesStatsCounter& value, const std::string& unit) const { test::PrintResult(metric_name, /*modifier=*/"", GetTestCaseName(network_label), value, unit, /*important=*/false); } std::string StatsBasedNetworkQualityMetricsReporter::GetTestCaseName( absl::string_view network_label) const { rtc::StringBuilder builder; builder << test_case_name_ << "/" << network_label.data(); return builder.str(); } void StatsBasedNetworkQualityMetricsReporter::LogNetworkLayerStats( const std::string& peer_name, const NetworkLayerStats& stats) const { DataRate average_send_rate = stats.stats->PacketsSent() >= 2 ? stats.stats->AverageSendRate() : DataRate::Zero(); DataRate average_receive_rate = stats.stats->PacketsReceived() >= 2 ? stats.stats->AverageReceiveRate() : DataRate::Zero(); rtc::StringBuilder log; log << "Raw network layer statistic for [" << peer_name << "]:\n" << "Local IPs:\n"; std::vector<rtc::IPAddress> local_ips = stats.stats->LocalAddresses(); for (size_t i = 0; i < local_ips.size(); ++i) { log << " " << local_ips[i].ToString() << "\n"; } if (!stats.stats->SentPacketsSizeCounter().IsEmpty()) { ReportResult("sent_packets_size", peer_name, stats.stats->SentPacketsSizeCounter(), "sizeInBytes"); } if (!stats.stats->ReceivedPacketsSizeCounter().IsEmpty()) { ReportResult("received_packets_size", peer_name, stats.stats->ReceivedPacketsSizeCounter(), "sizeInBytes"); } if (!stats.stats->DroppedPacketsSizeCounter().IsEmpty()) { ReportResult("dropped_packets_size", peer_name, stats.stats->DroppedPacketsSizeCounter(), "sizeInBytes"); } log << "Send statistic:\n" << " packets: " << stats.stats->PacketsSent() << " bytes: " << stats.stats->BytesSent().bytes() << " avg_rate (bytes/sec): " << average_send_rate.bytes_per_sec() << " avg_rate (bps): " << average_send_rate.bps() << "\n" << "Send statistic per destination:\n"; for (const auto& entry : stats.stats->OutgoingStatsPerDestination()) { DataRate source_average_send_rate = entry.second->PacketsSent() >= 2 ? entry.second->AverageSendRate() : DataRate::Zero(); log << "(" << entry.first.ToString() << "):\n" << " packets: " << entry.second->PacketsSent() << " bytes: " << entry.second->BytesSent().bytes() << " avg_rate (bytes/sec): " << source_average_send_rate.bytes_per_sec() << " avg_rate (bps): " << source_average_send_rate.bps() << "\n"; if (!entry.second->SentPacketsSizeCounter().IsEmpty()) { ReportResult("sent_packets_size", peer_name + "/" + entry.first.ToString(), stats.stats->SentPacketsSizeCounter(), "sizeInBytes"); } } log << "Receive statistic:\n" << " packets: " << stats.stats->PacketsReceived() << " bytes: " << stats.stats->BytesReceived().bytes() << " avg_rate (bytes/sec): " << average_receive_rate.bytes_per_sec() << " avg_rate (bps): " << average_receive_rate.bps() << "\n" << "Receive statistic per source:\n"; for (const auto& entry : stats.stats->IncomingStatsPerSource()) { DataRate source_average_receive_rate = entry.second->PacketsReceived() >= 2 ? entry.second->AverageReceiveRate() : DataRate::Zero(); log << "(" << entry.first.ToString() << "):\n" << " packets: " << entry.second->PacketsReceived() << " bytes: " << entry.second->BytesReceived().bytes() << " avg_rate (bytes/sec): " << source_average_receive_rate.bytes_per_sec() << " avg_rate (bps): " << source_average_receive_rate.bps() << "\n"; if (!entry.second->ReceivedPacketsSizeCounter().IsEmpty()) { ReportResult("received_packets_size", peer_name + "/" + entry.first.ToString(), stats.stats->ReceivedPacketsSizeCounter(), "sizeInBytes"); } if (!entry.second->DroppedPacketsSizeCounter().IsEmpty()) { ReportResult("dropped_packets_size", peer_name + "/" + entry.first.ToString(), stats.stats->DroppedPacketsSizeCounter(), "sizeInBytes"); } } RTC_LOG(INFO) << log.str(); } } // namespace webrtc_pc_e2e } // namespace webrtc <commit_msg>Report sent_packets_queue_wait_time_us in PC level framework network debug mode<commit_after>/* * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/pc/e2e/stats_based_network_quality_metrics_reporter.h" #include <cstdint> #include <map> #include <memory> #include <set> #include <string> #include <type_traits> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/scoped_refptr.h" #include "api/stats/rtc_stats.h" #include "api/stats/rtcstats_objects.h" #include "api/test/network_emulation/network_emulation_interfaces.h" #include "api/test/network_emulation_manager.h" #include "api/units/data_rate.h" #include "api/units/timestamp.h" #include "rtc_base/event.h" #include "rtc_base/ip_address.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/synchronization/mutex.h" #include "system_wrappers/include/field_trial.h" #include "test/testsupport/perf_test.h" namespace webrtc { namespace webrtc_pc_e2e { namespace { constexpr int kStatsWaitTimeoutMs = 1000; // Field trial which controls whether to report standard-compliant bytes // sent/received per stream. If enabled, padding and headers are not included // in bytes sent or received. constexpr char kUseStandardBytesStats[] = "WebRTC-UseStandardBytesStats"; std::unique_ptr<EmulatedNetworkStats> PopulateStats( std::vector<EmulatedEndpoint*> endpoints, NetworkEmulationManager* network_emulation) { rtc::Event stats_loaded; std::unique_ptr<EmulatedNetworkStats> stats; network_emulation->GetStats(endpoints, [&](std::unique_ptr<EmulatedNetworkStats> s) { stats = std::move(s); stats_loaded.Set(); }); bool stats_received = stats_loaded.Wait(kStatsWaitTimeoutMs); RTC_CHECK(stats_received); return stats; } std::map<rtc::IPAddress, std::string> PopulateIpToPeer( const std::map<std::string, std::vector<EmulatedEndpoint*>>& peer_endpoints) { std::map<rtc::IPAddress, std::string> out; for (const auto& entry : peer_endpoints) { for (const EmulatedEndpoint* const endpoint : entry.second) { out.emplace(endpoint->GetPeerLocalAddress(), entry.first); } } return out; } } // namespace StatsBasedNetworkQualityMetricsReporter::NetworkLayerStatsCollector:: NetworkLayerStatsCollector( std::map<std::string, std::vector<EmulatedEndpoint*>> peer_endpoints, NetworkEmulationManager* network_emulation) : peer_endpoints_(std::move(peer_endpoints)), ip_to_peer_(PopulateIpToPeer(peer_endpoints_)), network_emulation_(network_emulation) {} void StatsBasedNetworkQualityMetricsReporter::NetworkLayerStatsCollector:: Start() { // Check that network stats are clean before test execution. for (const auto& entry : peer_endpoints_) { std::unique_ptr<EmulatedNetworkStats> stats = PopulateStats(entry.second, network_emulation_); RTC_CHECK_EQ(stats->PacketsSent(), 0); RTC_CHECK_EQ(stats->PacketsReceived(), 0); } } std::map<std::string, StatsBasedNetworkQualityMetricsReporter::NetworkLayerStats> StatsBasedNetworkQualityMetricsReporter::NetworkLayerStatsCollector:: GetStats() { std::map<std::string, NetworkLayerStats> peer_to_stats; std::map<std::string, std::vector<std::string>> sender_to_receivers; for (const auto& entry : peer_endpoints_) { NetworkLayerStats stats; stats.stats = PopulateStats(entry.second, network_emulation_); const std::string& peer_name = entry.first; for (const auto& income_stats_entry : stats.stats->IncomingStatsPerSource()) { const rtc::IPAddress& source_ip = income_stats_entry.first; auto it = ip_to_peer_.find(source_ip); if (it == ip_to_peer_.end()) { // Source IP is unknown for this collector, so will be skipped. continue; } sender_to_receivers[it->second].push_back(peer_name); } peer_to_stats.emplace(peer_name, std::move(stats)); } for (auto& entry : peer_to_stats) { const std::vector<std::string>& receivers = sender_to_receivers[entry.first]; entry.second.receivers = std::set<std::string>(receivers.begin(), receivers.end()); } return peer_to_stats; } void StatsBasedNetworkQualityMetricsReporter::Start( absl::string_view test_case_name, const TrackIdStreamInfoMap* reporter_helper) { test_case_name_ = std::string(test_case_name); collector_.Start(); start_time_ = clock_->CurrentTime(); } void StatsBasedNetworkQualityMetricsReporter::OnStatsReports( absl::string_view pc_label, const rtc::scoped_refptr<const RTCStatsReport>& report) { PCStats cur_stats; auto inbound_stats = report->GetStatsOfType<RTCInboundRTPStreamStats>(); for (const auto& stat : inbound_stats) { cur_stats.payload_received += DataSize::Bytes(stat->bytes_received.ValueOrDefault(0ul) + stat->header_bytes_received.ValueOrDefault(0ul)); } auto outbound_stats = report->GetStatsOfType<RTCOutboundRTPStreamStats>(); for (const auto& stat : outbound_stats) { cur_stats.payload_sent += DataSize::Bytes(stat->bytes_sent.ValueOrDefault(0ul) + stat->header_bytes_sent.ValueOrDefault(0ul)); } auto candidate_pairs_stats = report->GetStatsOfType<RTCTransportStats>(); for (const auto& stat : candidate_pairs_stats) { cur_stats.total_received += DataSize::Bytes(stat->bytes_received.ValueOrDefault(0ul)); cur_stats.total_sent += DataSize::Bytes(stat->bytes_sent.ValueOrDefault(0ul)); cur_stats.packets_received += stat->packets_received.ValueOrDefault(0ul); cur_stats.packets_sent += stat->packets_sent.ValueOrDefault(0ul); } MutexLock lock(&mutex_); pc_stats_[std::string(pc_label)] = cur_stats; } void StatsBasedNetworkQualityMetricsReporter::StopAndReportResults() { Timestamp end_time = clock_->CurrentTime(); if (!webrtc::field_trial::IsEnabled(kUseStandardBytesStats)) { RTC_LOG(LS_ERROR) << "Non-standard GetStats; \"payload\" counts include RTP headers"; } std::map<std::string, NetworkLayerStats> stats = collector_.GetStats(); for (const auto& entry : stats) { LogNetworkLayerStats(entry.first, entry.second); } MutexLock lock(&mutex_); for (const auto& pair : pc_stats_) { auto it = stats.find(pair.first); RTC_CHECK(it != stats.end()) << "Peer name used for PeerConnection stats collection and peer name " "used for endpoints naming doesn't match. No endpoints found for " "peer " << pair.first; const NetworkLayerStats& network_layer_stats = it->second; int64_t total_packets_received = 0; bool found = false; for (const auto& dest_peer : network_layer_stats.receivers) { auto pc_stats_it = pc_stats_.find(dest_peer); if (pc_stats_it == pc_stats_.end()) { continue; } found = true; total_packets_received += pc_stats_it->second.packets_received; } int64_t packet_loss = -1; if (found) { packet_loss = pair.second.packets_sent - total_packets_received; } ReportStats(pair.first, pair.second, network_layer_stats, packet_loss, end_time); } } void StatsBasedNetworkQualityMetricsReporter::ReportStats( const std::string& pc_label, const PCStats& pc_stats, const NetworkLayerStats& network_layer_stats, int64_t packet_loss, const Timestamp& end_time) { ReportResult("bytes_dropped", pc_label, network_layer_stats.stats->BytesDropped().bytes(), "sizeInBytes"); ReportResult("packets_dropped", pc_label, network_layer_stats.stats->PacketsDropped(), "unitless"); ReportResult("payload_bytes_received", pc_label, pc_stats.payload_received.bytes(), "sizeInBytes"); ReportResult("payload_bytes_sent", pc_label, pc_stats.payload_sent.bytes(), "sizeInBytes"); ReportResult("bytes_sent", pc_label, pc_stats.total_sent.bytes(), "sizeInBytes"); ReportResult("packets_sent", pc_label, pc_stats.packets_sent, "unitless"); ReportResult("average_send_rate", pc_label, (pc_stats.total_sent / (end_time - start_time_)).bytes_per_sec(), "bytesPerSecond"); ReportResult("bytes_received", pc_label, pc_stats.total_received.bytes(), "sizeInBytes"); ReportResult("packets_received", pc_label, pc_stats.packets_received, "unitless"); ReportResult( "average_receive_rate", pc_label, (pc_stats.total_received / (end_time - start_time_)).bytes_per_sec(), "bytesPerSecond"); ReportResult("sent_packets_loss", pc_label, packet_loss, "unitless"); } void StatsBasedNetworkQualityMetricsReporter::ReportResult( const std::string& metric_name, const std::string& network_label, const double value, const std::string& unit) const { test::PrintResult(metric_name, /*modifier=*/"", GetTestCaseName(network_label), value, unit, /*important=*/false); } void StatsBasedNetworkQualityMetricsReporter::ReportResult( const std::string& metric_name, const std::string& network_label, const SamplesStatsCounter& value, const std::string& unit) const { test::PrintResult(metric_name, /*modifier=*/"", GetTestCaseName(network_label), value, unit, /*important=*/false); } std::string StatsBasedNetworkQualityMetricsReporter::GetTestCaseName( absl::string_view network_label) const { rtc::StringBuilder builder; builder << test_case_name_ << "/" << network_label.data(); return builder.str(); } void StatsBasedNetworkQualityMetricsReporter::LogNetworkLayerStats( const std::string& peer_name, const NetworkLayerStats& stats) const { DataRate average_send_rate = stats.stats->PacketsSent() >= 2 ? stats.stats->AverageSendRate() : DataRate::Zero(); DataRate average_receive_rate = stats.stats->PacketsReceived() >= 2 ? stats.stats->AverageReceiveRate() : DataRate::Zero(); rtc::StringBuilder log; log << "Raw network layer statistic for [" << peer_name << "]:\n" << "Local IPs:\n"; std::vector<rtc::IPAddress> local_ips = stats.stats->LocalAddresses(); for (size_t i = 0; i < local_ips.size(); ++i) { log << " " << local_ips[i].ToString() << "\n"; } if (!stats.stats->SentPacketsSizeCounter().IsEmpty()) { ReportResult("sent_packets_size", peer_name, stats.stats->SentPacketsSizeCounter(), "sizeInBytes"); } if (!stats.stats->ReceivedPacketsSizeCounter().IsEmpty()) { ReportResult("received_packets_size", peer_name, stats.stats->ReceivedPacketsSizeCounter(), "sizeInBytes"); } if (!stats.stats->DroppedPacketsSizeCounter().IsEmpty()) { ReportResult("dropped_packets_size", peer_name, stats.stats->DroppedPacketsSizeCounter(), "sizeInBytes"); } if (!stats.stats->SentPacketsQueueWaitTimeUs().IsEmpty()) { ReportResult("sent_packets_queue_wait_time_us", peer_name, stats.stats->SentPacketsQueueWaitTimeUs(), "unitless"); } log << "Send statistic:\n" << " packets: " << stats.stats->PacketsSent() << " bytes: " << stats.stats->BytesSent().bytes() << " avg_rate (bytes/sec): " << average_send_rate.bytes_per_sec() << " avg_rate (bps): " << average_send_rate.bps() << "\n" << "Send statistic per destination:\n"; for (const auto& entry : stats.stats->OutgoingStatsPerDestination()) { DataRate source_average_send_rate = entry.second->PacketsSent() >= 2 ? entry.second->AverageSendRate() : DataRate::Zero(); log << "(" << entry.first.ToString() << "):\n" << " packets: " << entry.second->PacketsSent() << " bytes: " << entry.second->BytesSent().bytes() << " avg_rate (bytes/sec): " << source_average_send_rate.bytes_per_sec() << " avg_rate (bps): " << source_average_send_rate.bps() << "\n"; if (!entry.second->SentPacketsSizeCounter().IsEmpty()) { ReportResult("sent_packets_size", peer_name + "/" + entry.first.ToString(), stats.stats->SentPacketsSizeCounter(), "sizeInBytes"); } } log << "Receive statistic:\n" << " packets: " << stats.stats->PacketsReceived() << " bytes: " << stats.stats->BytesReceived().bytes() << " avg_rate (bytes/sec): " << average_receive_rate.bytes_per_sec() << " avg_rate (bps): " << average_receive_rate.bps() << "\n" << "Receive statistic per source:\n"; for (const auto& entry : stats.stats->IncomingStatsPerSource()) { DataRate source_average_receive_rate = entry.second->PacketsReceived() >= 2 ? entry.second->AverageReceiveRate() : DataRate::Zero(); log << "(" << entry.first.ToString() << "):\n" << " packets: " << entry.second->PacketsReceived() << " bytes: " << entry.second->BytesReceived().bytes() << " avg_rate (bytes/sec): " << source_average_receive_rate.bytes_per_sec() << " avg_rate (bps): " << source_average_receive_rate.bps() << "\n"; if (!entry.second->ReceivedPacketsSizeCounter().IsEmpty()) { ReportResult("received_packets_size", peer_name + "/" + entry.first.ToString(), stats.stats->ReceivedPacketsSizeCounter(), "sizeInBytes"); } if (!entry.second->DroppedPacketsSizeCounter().IsEmpty()) { ReportResult("dropped_packets_size", peer_name + "/" + entry.first.ToString(), stats.stats->DroppedPacketsSizeCounter(), "sizeInBytes"); } } RTC_LOG(INFO) << log.str(); } } // namespace webrtc_pc_e2e } // namespace webrtc <|endoftext|>
<commit_before>#include "density.h" namespace sirius { void Density::generate_valence_density_it(K_set& ks__) { Timer t("sirius::Density::generate_valence_density_it", ctx_.comm()); /* add k-point contribution */ for (int ikloc = 0; ikloc < (int)ks__.spl_num_kpoints().local_size(); ikloc++) { int ik = ks__.spl_num_kpoints(ikloc); auto kp = ks__[ik]; occupied_bands_descriptor occupied_bands; if (ctx_.fft(0)->parallel()) { occupied_bands = kp->get_occupied_bands_list(kp->blacs_grid().comm_col()); } else { occupied_bands = kp->get_occupied_bands_list(kp->blacs_grid_slice().comm_col()); } if (!parameters_.full_potential() && kp->num_ranks() > 1) { linalg<CPU>::gemr2d(kp->wf_size(), occupied_bands.num_occupied_bands(), kp->fv_states(), 0, 0, kp->spinor_wave_functions(0), 0, 0, kp->blacs_grid().context()); } if (ctx_.fft(0)->parallel()) { add_k_point_contribution_it_pfft(ks__[ik], occupied_bands); } else { add_k_point_contribution_it(ks__[ik], occupied_bands); } } /* reduce arrays; assume that each rank did it's own fraction of the density */ if (ctx_.fft(0)->parallel()) { ctx_.mpi_grid().communicator(1 << _dim_k_ | 1 << _dim_col_).allreduce(&rho_->f_it(0), ctx_.fft(0)->local_size()); } else { ctx_.comm().allreduce(&rho_->f_it(0), ctx_.fft(0)->size()); for (int j = 0; j < parameters_.num_mag_dims(); j++) ctx_.comm().allreduce(&magnetization_[j]->f_it(0), ctx_.fft(0)->size()); } } }; <commit_msg>check one more timer<commit_after>#include "density.h" namespace sirius { void Density::generate_valence_density_it(K_set& ks__) { Timer t("sirius::Density::generate_valence_density_it", ctx_.comm()); /* add k-point contribution */ for (int ikloc = 0; ikloc < (int)ks__.spl_num_kpoints().local_size(); ikloc++) { int ik = ks__.spl_num_kpoints(ikloc); auto kp = ks__[ik]; occupied_bands_descriptor occupied_bands; if (ctx_.fft(0)->parallel()) { occupied_bands = kp->get_occupied_bands_list(kp->blacs_grid().comm_col()); } else { occupied_bands = kp->get_occupied_bands_list(kp->blacs_grid_slice().comm_col()); } if (!parameters_.full_potential() && kp->num_ranks() > 1) { double t0 = -Utils::current_time(); linalg<CPU>::gemr2d(kp->wf_size(), occupied_bands.num_occupied_bands(), kp->fv_states(), 0, 0, kp->spinor_wave_functions(0), 0, 0, kp->blacs_grid().context()); t0 += Utils::current_time(); printf("gemr2d time: %.4f\n", t0); } if (ctx_.fft(0)->parallel()) { add_k_point_contribution_it_pfft(ks__[ik], occupied_bands); } else { add_k_point_contribution_it(ks__[ik], occupied_bands); } } double t0 = -Utils::current_time(); /* reduce arrays; assume that each rank did it's own fraction of the density */ if (ctx_.fft(0)->parallel()) { ctx_.mpi_grid().communicator(1 << _dim_k_ | 1 << _dim_col_).allreduce(&rho_->f_it(0), ctx_.fft(0)->local_size()); } else { ctx_.comm().allreduce(&rho_->f_it(0), ctx_.fft(0)->size()); for (int j = 0; j < parameters_.num_mag_dims(); j++) ctx_.comm().allreduce(&magnetization_[j]->f_it(0), ctx_.fft(0)->size()); } t0 += Utils::current_time(); printf("reduction time: %.4f\n", t0); } }; <|endoftext|>
<commit_before>/// /// @file pi_deleglise_rivat3.cpp /// @brief Implementation of the Deleglise-Rivat prime counting /// algorithm. This implementation is identical to /// pi_deleglise_rivat2(x) but uses 128-bit integers. /// /// This implementation is based on the paper: /// Tomás Oliveira e Silva, Computing pi(x): the combinatorial /// method, Revista do DETUA, vol. 4, no. 6, March 2006, /// pp. 759-768. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PiTable.hpp> #include <FactorTable.hpp> #include <primecount.hpp> #include <primecount-internal.hpp> #include <BitSieve.hpp> #include <generate.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <int128.hpp> #include <S1.hpp> #include <tos_counters.hpp> #include <stdint.h> #include <algorithm> #include <vector> using namespace std; using namespace primecount; namespace { /// Cross-off the multiples of prime in the sieve array. /// For each element that is unmarked the first time update /// the special counters tree data structure. /// template <typename T> void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, BitSieve& sieve, T& counters) { int64_t segment_size = sieve.size(); int64_t k = next_multiple; for (; k < high; k += prime * 2) { if (sieve[k - low]) { sieve.unset(k - low); cnt_update(counters, k - low, segment_size); } } next_multiple = k; } /// Calculate the contribution of the trivial leaves. /// template <typename P> int128_t S2_trivial(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, vector<P>& primes) { int64_t pi_y = pi(y); int64_t pi_sqrtz = pi(min(isqrt(z), y)); int128_t S2_result = 0; // Find all trivial leaves: n = primes[b] * primes[l] // which satisfy phi(x / n), b - 1) = 1 for (int64_t b = max(c, pi_sqrtz + 1); b < pi_y; b++) { uint128_t prime = primes[b]; uint64_t xn = (uint64_t) max(x / (prime * prime), prime); S2_result += pi_y - pi(xn); } return S2_result; } /// Calculate the contribution of the trivial leaves, the clustered /// easy leaves and the sparse easy leaves. /// template <typename P> int128_t S2_easy(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, vector<P>& primes) { int64_t pi_sqrty = pi(isqrt(y)); int64_t pi_x13 = pi(iroot<3>(x)); int128_t S2_result = 0; for (int64_t b = max(c, pi_sqrty) + 1; b <= pi_x13; b++) { int128_t prime128 = primes[b]; int64_t prime = primes[b]; int64_t min_trivial_leaf = min(x / (prime128 * prime), y); int64_t min_clustered_easy_leaf = isqrt(x / prime); int64_t min_sparse_easy_leaf = z / prime; int64_t min_hard_leaf = max(y / prime, prime); min_sparse_easy_leaf = max(min_sparse_easy_leaf, min_hard_leaf); min_clustered_easy_leaf = max(min_clustered_easy_leaf, min_hard_leaf); int64_t l = pi(min_trivial_leaf); // Find all clustered easy leaves: // x / n <= y and phi(x / n, b - 1) == phi(x / m, b - 1) // where phi(x / n, b - 1) = pi(x / n) - b + 2 while (primes[l] > min_clustered_easy_leaf) { int128_t n = prime128 * primes[l]; int64_t xn = (int64_t) (x / n); int64_t phi_xn = pi(xn) - b + 2; int128_t m = prime128 * primes[b + phi_xn - 1]; int64_t xm = max((int64_t) (x / m), min_clustered_easy_leaf); int64_t l2 = pi(xm); int128_t phi_factor = l - l2; S2_result += phi_xn * phi_factor; l = l2; } // Find all sparse easy leaves: // x / n <= y and phi(x / n, b - 1) = pi(x / n) - b + 2 for (; primes[l] > min_sparse_easy_leaf; l--) { int128_t n = prime128 * primes[l]; int64_t xn = (int64_t) (x / n); S2_result += pi(xn) - b + 2; } } return S2_result; } /// Calculate the contribution of the special leaves which require /// a sieve (in order to reduce the memory usage). /// template <typename P, typename F> int128_t S2_sieve(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, vector<P>& primes, FactorTable<F>& factors) { int64_t limit = z + 1; int64_t segment_size = next_power_of_2(isqrt(limit)); int64_t pi_sqrty = pi(isqrt(y)); int64_t pi_sqrtz = pi(min(isqrt(z), y)); int128_t S2_result = 0; BitSieve sieve(segment_size); vector<int32_t> counters(segment_size); vector<int64_t> next(primes.begin(), primes.end()); vector<int64_t> phi(primes.size(), 0); // Segmented sieve of Eratosthenes for (int64_t low = 1; low < limit; low += segment_size) { // Current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t b = 2; sieve.fill(low, high); // phi(y, b) nodes with b <= c do not contribute to S2, so we // simply sieve out the multiples of the first c primes for (; b <= c; b++) { int64_t k = next[b]; for (int64_t prime = primes[b]; k < high; k += prime * 2) sieve.unset(k - low); next[b] = k; } // Initialize special tree data structure from sieve cnt_finit(sieve, counters, segment_size); // For c + 1 <= b <= pi_sqrty // Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m] // which satisfy: low <= (x / n) < high for (; b <= pi_sqrty; b++) { int128_t prime128 = primes[b]; int64_t prime = primes[b]; int64_t min_m = max(min(x / (prime128 * high), y), y / prime); int64_t max_m = min(x / (prime128 * low), y); if (prime >= max_m) goto next_segment; factors.to_index(&min_m); factors.to_index(&max_m); for (int64_t m = max_m; m > min_m; m--) { if (prime < factors.lpf(m)) { int64_t n = prime * factors.get_number(m); int64_t count = cnt_query(counters, (x / n) - low); int64_t phi_xn = phi[b] + count; S2_result -= factors.mu(m) * phi_xn; } } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } // For pi_sqrty <= b <= pi_sqrtz // Find all hard special leaves: n = primes[b] * primes[l] // which satisfy: low <= (x / n) < high for (; b <= pi_sqrtz; b++) { int128_t prime128 = primes[b]; int64_t prime = primes[b]; int64_t l = pi(min(min(x / (prime128 * low), y), z / prime)); int64_t min_hard_leaf = max3(min(x / (prime128 * high), y), y / prime, prime); if (prime >= primes[l]) goto next_segment; for (; primes[l] > min_hard_leaf; l--) { int64_t n = prime * primes[l]; int64_t xn = x / n; int64_t count = cnt_query(counters, xn - low); int64_t phi_xn = phi[b] + count; S2_result += phi_xn; } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } next_segment:; } return S2_result; } /// Calculate the contribution of the special leaves. /// @pre y > 0 && c > 1 /// template <typename P, typename F> int128_t S2(uint128_t x, int64_t y, int64_t z, int64_t c, vector<P>& primes, FactorTable<F>& factors) { int128_t S2_total = 0; PiTable pi(y); S2_total += S2_trivial(x, y, z, c, pi, primes); S2_total += S2_easy(x, y, z, c, pi, primes); S2_total += S2_sieve(x, y, z, c, pi, primes, factors); return S2_total; } /// alpha is a tuning factor which should grow like (log(x))^3 /// for the Deleglise-Rivat prime counting algorithm. /// double compute_alpha(uint128_t x) { double d = (double) x; double alpha = log(d) * log(d) * log(d) / 1200; return in_between(1, alpha, iroot<6>(x)); } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat3(int128_t x) { if (x < 2) return 0; if (x > to_maxint(primecount::max())) throw primecount_error("pi(x): x must be <= " + max()); double alpha = compute_alpha(x); int64_t y = (int64_t) (alpha * iroot<3>(x)); int64_t z = (int64_t) (x / y); int64_t pi_y; int64_t c; int128_t p2 = P2(x, y, 1); int128_t s1, s2; if (y <= FactorTable<uint16_t>::max()) { // if y < 2^32 we can use 32-bit primes and a 16-bit FactorTable // which uses ~ (y / 2) bytes of memory vector<uint32_t> primes = generate_primes<uint32_t>(y); FactorTable<uint16_t> factors(y); pi_y = primes.size() - 1; c = min(pi_y, PhiTiny::max_a()); s1 = S1(x, y, c, primes[c], factors, 1); s2 = S2(x, y, z, c, primes, factors); } else { // if y >= 2^32 we need to use 64-bit primes and a 32-bit // FactorTable which uses ~ y bytes of memory vector<int64_t> primes = generate_primes<int64_t>(y); FactorTable<uint32_t> factors(y); pi_y = primes.size() - 1; c = min(pi_y, PhiTiny::max_a()); s1 = S1(x, y, c, primes[c], factors, 1); s2 = S2(x, y, z, c, primes, factors); } int128_t phi = s1 + s2; int128_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace primecount <commit_msg>Update pi_deleglise_rivat3.cpp<commit_after>/// /// @file pi_deleglise_rivat3.cpp /// @brief Implementation of the Deleglise-Rivat prime counting /// algorithm. This implementation is identical to /// pi_deleglise_rivat2(x) but uses 128-bit integers. /// /// This implementation is based on the paper: /// Tomás Oliveira e Silva, Computing pi(x): the combinatorial /// method, Revista do DETUA, vol. 4, no. 6, March 2006, /// pp. 759-768. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PiTable.hpp> #include <FactorTable.hpp> #include <primecount.hpp> #include <primecount-internal.hpp> #include <BitSieve.hpp> #include <generate.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <int128.hpp> #include <S1.hpp> #include <tos_counters.hpp> #include <stdint.h> #include <algorithm> #include <vector> using namespace std; using namespace primecount; namespace { /// Cross-off the multiples of prime in the sieve array. /// For each element that is unmarked the first time update /// the special counters tree data structure. /// template <typename T> void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, BitSieve& sieve, T& counters) { int64_t segment_size = sieve.size(); int64_t k = next_multiple; for (; k < high; k += prime * 2) { if (sieve[k - low]) { sieve.unset(k - low); cnt_update(counters, k - low, segment_size); } } next_multiple = k; } /// Calculate the contribution of the trivial leaves. /// template <typename P> int128_t S2_trivial(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, vector<P>& primes) { int64_t pi_y = pi(y); int64_t pi_sqrtz = pi(min(isqrt(z), y)); int128_t S2_result = 0; // Find all trivial leaves: n = primes[b] * primes[l] // which satisfy phi(x / n), b - 1) = 1 for (int64_t b = max(c, pi_sqrtz + 1); b < pi_y; b++) { uint128_t prime = primes[b]; uint64_t xn = (uint64_t) max(x / (prime * prime), prime); S2_result += pi_y - pi(xn); } return S2_result; } /// Calculate the contribution of the clustered easy /// leaves and the sparse easy leaves. /// template <typename P> int128_t S2_easy(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, vector<P>& primes) { int64_t pi_sqrty = pi(isqrt(y)); int64_t pi_x13 = pi(iroot<3>(x)); int128_t S2_result = 0; for (int64_t b = max(c, pi_sqrty) + 1; b <= pi_x13; b++) { int128_t prime128 = primes[b]; int64_t prime = primes[b]; int64_t min_trivial_leaf = min(x / (prime128 * prime), y); int64_t min_clustered_easy_leaf = isqrt(x / prime); int64_t min_sparse_easy_leaf = z / prime; int64_t min_hard_leaf = max(y / prime, prime); min_sparse_easy_leaf = max(min_sparse_easy_leaf, min_hard_leaf); min_clustered_easy_leaf = max(min_clustered_easy_leaf, min_hard_leaf); int64_t l = pi(min_trivial_leaf); // Find all clustered easy leaves: // x / n <= y and phi(x / n, b - 1) == phi(x / m, b - 1) // where phi(x / n, b - 1) = pi(x / n) - b + 2 while (primes[l] > min_clustered_easy_leaf) { int128_t n = prime128 * primes[l]; int64_t xn = (int64_t) (x / n); int64_t phi_xn = pi(xn) - b + 2; int128_t m = prime128 * primes[b + phi_xn - 1]; int64_t xm = max((int64_t) (x / m), min_clustered_easy_leaf); int64_t l2 = pi(xm); int128_t phi_factor = l - l2; S2_result += phi_xn * phi_factor; l = l2; } // Find all sparse easy leaves: // x / n <= y and phi(x / n, b - 1) = pi(x / n) - b + 2 for (; primes[l] > min_sparse_easy_leaf; l--) { int128_t n = prime128 * primes[l]; int64_t xn = (int64_t) (x / n); S2_result += pi(xn) - b + 2; } } return S2_result; } /// Calculate the contribution of the special leaves which require /// a sieve (in order to reduce the memory usage). /// template <typename P, typename F> int128_t S2_sieve(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, vector<P>& primes, FactorTable<F>& factors) { int64_t limit = z + 1; int64_t segment_size = next_power_of_2(isqrt(limit)); int64_t pi_sqrty = pi(isqrt(y)); int64_t pi_sqrtz = pi(min(isqrt(z), y)); int128_t S2_result = 0; BitSieve sieve(segment_size); vector<int32_t> counters(segment_size); vector<int64_t> next(primes.begin(), primes.end()); vector<int64_t> phi(primes.size(), 0); // Segmented sieve of Eratosthenes for (int64_t low = 1; low < limit; low += segment_size) { // Current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t b = 2; sieve.fill(low, high); // phi(y, b) nodes with b <= c do not contribute to S2, so we // simply sieve out the multiples of the first c primes for (; b <= c; b++) { int64_t k = next[b]; for (int64_t prime = primes[b]; k < high; k += prime * 2) sieve.unset(k - low); next[b] = k; } // Initialize special tree data structure from sieve cnt_finit(sieve, counters, segment_size); // For c + 1 <= b <= pi_sqrty // Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m] // which satisfy: low <= (x / n) < high for (; b <= pi_sqrty; b++) { int128_t prime128 = primes[b]; int64_t prime = primes[b]; int64_t min_m = max(min(x / (prime128 * high), y), y / prime); int64_t max_m = min(x / (prime128 * low), y); if (prime >= max_m) goto next_segment; factors.to_index(&min_m); factors.to_index(&max_m); for (int64_t m = max_m; m > min_m; m--) { if (prime < factors.lpf(m)) { int64_t n = prime * factors.get_number(m); int64_t count = cnt_query(counters, (x / n) - low); int64_t phi_xn = phi[b] + count; S2_result -= factors.mu(m) * phi_xn; } } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } // For pi_sqrty <= b <= pi_sqrtz // Find all hard special leaves: n = primes[b] * primes[l] // which satisfy: low <= (x / n) < high for (; b <= pi_sqrtz; b++) { int128_t prime128 = primes[b]; int64_t prime = primes[b]; int64_t l = pi(min(min(x / (prime128 * low), y), z / prime)); int64_t min_hard_leaf = max3(min(x / (prime128 * high), y), y / prime, prime); if (prime >= primes[l]) goto next_segment; for (; primes[l] > min_hard_leaf; l--) { int64_t n = prime * primes[l]; int64_t xn = x / n; int64_t count = cnt_query(counters, xn - low); int64_t phi_xn = phi[b] + count; S2_result += phi_xn; } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } next_segment:; } return S2_result; } /// Calculate the contribution of the special leaves. /// @pre y > 0 && c > 1 /// template <typename P, typename F> int128_t S2(uint128_t x, int64_t y, int64_t z, int64_t c, vector<P>& primes, FactorTable<F>& factors) { int128_t S2_total = 0; PiTable pi(y); S2_total += S2_trivial(x, y, z, c, pi, primes); S2_total += S2_easy(x, y, z, c, pi, primes); S2_total += S2_sieve(x, y, z, c, pi, primes, factors); return S2_total; } /// alpha is a tuning factor which should grow like (log(x))^3 /// for the Deleglise-Rivat prime counting algorithm. /// double compute_alpha(uint128_t x) { double d = (double) x; double alpha = log(d) * log(d) * log(d) / 1200; return in_between(1, alpha, iroot<6>(x)); } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat3(int128_t x) { if (x < 2) return 0; if (x > to_maxint(primecount::max())) throw primecount_error("pi(x): x must be <= " + max()); double alpha = compute_alpha(x); int64_t y = (int64_t) (alpha * iroot<3>(x)); int64_t z = (int64_t) (x / y); int64_t pi_y; int64_t c; int128_t p2 = P2(x, y, 1); int128_t s1, s2; if (y <= FactorTable<uint16_t>::max()) { // if y < 2^32 we can use 32-bit primes and a 16-bit FactorTable // which uses ~ (y / 2) bytes of memory vector<uint32_t> primes = generate_primes<uint32_t>(y); FactorTable<uint16_t> factors(y); pi_y = primes.size() - 1; c = min(pi_y, PhiTiny::max_a()); s1 = S1(x, y, c, primes[c], factors, 1); s2 = S2(x, y, z, c, primes, factors); } else { // if y >= 2^32 we need to use 64-bit primes and a 32-bit // FactorTable which uses ~ y bytes of memory vector<int64_t> primes = generate_primes<int64_t>(y); FactorTable<uint32_t> factors(y); pi_y = primes.size() - 1; c = min(pi_y, PhiTiny::max_a()); s1 = S1(x, y, c, primes[c], factors, 1); s2 = S2(x, y, z, c, primes, factors); } int128_t phi = s1 + s2; int128_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace primecount <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/ompl_interface/detail/state_validity_checker.h> #include <moveit/ompl_interface/model_based_planning_context.h> #include <moveit/profiler/profiler.h> #include <ros/ros.h> ompl_interface::StateValidityChecker::StateValidityChecker(const ModelBasedPlanningContext *pc) : ompl::base::StateValidityChecker(pc->getOMPLSimpleSetup().getSpaceInformation()), planning_context_(pc), group_name_(pc->getJointModelGroupName()), tss_(pc->getCompleteInitialRobotState()), verbose_(false) { specs_.clearanceComputationType = ompl::base::StateValidityCheckerSpecs::APPROXIMATE; specs_.hasValidDirectionComputation = false; collision_request_with_distance_.distance = true; collision_request_with_cost_.cost = true; collision_request_simple_.group_name = planning_context_->getJointModelGroupName(); collision_request_with_distance_.group_name = planning_context_->getJointModelGroupName(); collision_request_with_cost_.group_name = planning_context_->getJointModelGroupName(); collision_request_simple_verbose_ = collision_request_simple_; collision_request_simple_verbose_.verbose = true; collision_request_with_distance_verbose_ = collision_request_with_distance_; collision_request_with_distance_verbose_.verbose = true; } void ompl_interface::StateValidityChecker::setVerbose(bool flag) { verbose_ = flag; } bool ompl_interface::StateValidityChecker::isValid(const ompl::base::State *state, bool verbose) const { // moveit::Profiler::ScopedBlock sblock("isValid"); return planning_context_->useStateValidityCache() ? isValidWithCache(state, verbose) : isValidWithoutCache(state, verbose); } bool ompl_interface::StateValidityChecker::isValid(const ompl::base::State *state, double &dist, bool verbose) const { // moveit::Profiler::ScopedBlock sblock("isValid"); return planning_context_->useStateValidityCache() ? isValidWithCache(state, dist, verbose) : isValidWithoutCache(state, dist, verbose); } double ompl_interface::StateValidityChecker::cost(const ompl::base::State *state) const { static std::vector<double> prev_joint_values; static bool first_time = true; static boost::thread::id thread_id = boost::this_thread::get_id(); // Check that we are still on same thread if( thread_id != boost::this_thread::get_id() ) ROS_ERROR_STREAM("Multiple threads are not implemented here..."); // Get current robot state robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); // Cost double cost = 0.0; std::vector<double> new_joint_values; // get joint state values kstate->getStateValues(new_joint_values); // calculate cost for (std::size_t i = 0; i < new_joint_values.size(); ++i) { double value = 0; // Check if first time if (first_time) { first_time = false; prev_joint_values.resize(new_joint_values.size()); } else { // get abs of difference in each joint value value = fabs(prev_joint_values[i] - new_joint_values[i]); } cost += value; // copy new value to old vector prev_joint_values[i] = new_joint_values[i]; } return cost; /* robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); collision_detection::CollisionResult res; planning_context_->getPlanningScene()->checkCollision(collision_request_with_cost_, res, *kstate); double c = 0.0; for (std::set<collision_detection::CostSource>::const_iterator it = res.cost_sources.begin() ; it != res.cost_sources.end() ; ++it) c += it->cost * it->getVolume(); return c; */ } double ompl_interface::StateValidityChecker::clearance(const ompl::base::State *state) const { robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); collision_detection::CollisionResult res; planning_context_->getPlanningScene()->checkCollision(collision_request_with_distance_, res, *kstate); return res.collision ? 0.0 : (res.distance < 0.0 ? std::numeric_limits<double>::infinity() : res.distance); } bool ompl_interface::StateValidityChecker::isValidWithoutCache(const ompl::base::State *state, bool verbose) const { if (!si_->satisfiesBounds(state)) { if (verbose) logInform("State outside bounds"); return false; } robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); // check path constraints const kinematic_constraints::KinematicConstraintSetPtr &kset = planning_context_->getPathConstraints(); if (kset && !kset->decide(*kstate, verbose).satisfied) return false; // check feasibility if (!planning_context_->getPlanningScene()->isStateFeasible(*kstate, verbose)) return false; // check collision avoidance collision_detection::CollisionResult res; planning_context_->getPlanningScene()->checkCollision(verbose ? collision_request_simple_verbose_ : collision_request_simple_, res, *kstate); return res.collision == false; } bool ompl_interface::StateValidityChecker::isValidWithoutCache(const ompl::base::State *state, double &dist, bool verbose) const { if (!si_->satisfiesBounds(state)) { if (verbose) logInform("State outside bounds"); return false; } robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); // check path constraints const kinematic_constraints::KinematicConstraintSetPtr &kset = planning_context_->getPathConstraints(); if (kset) { kinematic_constraints::ConstraintEvaluationResult cer = kset->decide(*kstate, verbose); if (!cer.satisfied) { dist = cer.distance; return false; } } // check feasibility if (!planning_context_->getPlanningScene()->isStateFeasible(*kstate, verbose)) { dist = 0.0; return false; } // check collision avoidance collision_detection::CollisionResult res; planning_context_->getPlanningScene()->checkCollision(verbose ? collision_request_with_distance_verbose_ : collision_request_with_distance_, res, *kstate); dist = res.distance; return res.collision == false; } bool ompl_interface::StateValidityChecker::isValidWithCache(const ompl::base::State *state, bool verbose) const { if (state->as<ModelBasedStateSpace::StateType>()->isValidityKnown()) return state->as<ModelBasedStateSpace::StateType>()->isMarkedValid(); if (!si_->satisfiesBounds(state)) { if (verbose) logInform("State outside bounds"); const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markInvalid(); return false; } robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); // check path constraints const kinematic_constraints::KinematicConstraintSetPtr &kset = planning_context_->getPathConstraints(); if (kset && !kset->decide(*kstate, verbose).satisfied) { const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markInvalid(); return false; } // check feasibility if (!planning_context_->getPlanningScene()->isStateFeasible(*kstate, verbose)) { const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markInvalid(); return false; } // check collision avoidance collision_detection::CollisionResult res; planning_context_->getPlanningScene()->checkCollision(verbose ? collision_request_simple_verbose_ : collision_request_simple_, res, *kstate); if (res.collision == false) { const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markValid(); return true; } else { const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markInvalid(); return false; } } bool ompl_interface::StateValidityChecker::isValidWithCache(const ompl::base::State *state, double &dist, bool verbose) const { if (state->as<ModelBasedStateSpace::StateType>()->isValidityKnown() && state->as<ModelBasedStateSpace::StateType>()->isGoalDistanceKnown()) { dist = state->as<ModelBasedStateSpace::StateType>()->distance; return state->as<ModelBasedStateSpace::StateType>()->isMarkedValid(); } if (!si_->satisfiesBounds(state)) { if (verbose) logInform("State outside bounds"); const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markInvalid(0.0); return false; } robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); // check path constraints const kinematic_constraints::KinematicConstraintSetPtr &kset = planning_context_->getPathConstraints(); if (kset) { kinematic_constraints::ConstraintEvaluationResult cer = kset->decide(*kstate, verbose); if (!cer.satisfied) { dist = cer.distance; const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markInvalid(dist); return false; } } // check feasibility if (!planning_context_->getPlanningScene()->isStateFeasible(*kstate, verbose)) { dist = 0.0; return false; } // check collision avoidance collision_detection::CollisionResult res; planning_context_->getPlanningScene()->checkCollision(verbose ? collision_request_with_distance_verbose_ : collision_request_with_distance_, res, *kstate); dist = res.distance; return res.collision == false; } <commit_msg>Removed formatting changes<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/ompl_interface/detail/state_validity_checker.h> #include <moveit/ompl_interface/model_based_planning_context.h> #include <moveit/profiler/profiler.h> #include <ros/ros.h> ompl_interface::StateValidityChecker::StateValidityChecker(const ModelBasedPlanningContext *pc) : ompl::base::StateValidityChecker(pc->getOMPLSimpleSetup().getSpaceInformation()), planning_context_(pc), group_name_(pc->getJointModelGroupName()), tss_(pc->getCompleteInitialRobotState()), verbose_(false) { specs_.clearanceComputationType = ompl::base::StateValidityCheckerSpecs::APPROXIMATE; specs_.hasValidDirectionComputation = false; collision_request_with_distance_.distance = true; collision_request_with_cost_.cost = true; collision_request_simple_.group_name = planning_context_->getJointModelGroupName(); collision_request_with_distance_.group_name = planning_context_->getJointModelGroupName(); collision_request_with_cost_.group_name = planning_context_->getJointModelGroupName(); collision_request_simple_verbose_ = collision_request_simple_; collision_request_simple_verbose_.verbose = true; collision_request_with_distance_verbose_ = collision_request_with_distance_; collision_request_with_distance_verbose_.verbose = true; } void ompl_interface::StateValidityChecker::setVerbose(bool flag) { verbose_ = flag; } bool ompl_interface::StateValidityChecker::isValid(const ompl::base::State *state, bool verbose) const { // moveit::Profiler::ScopedBlock sblock("isValid"); return planning_context_->useStateValidityCache() ? isValidWithCache(state, verbose) : isValidWithoutCache(state, verbose); } bool ompl_interface::StateValidityChecker::isValid(const ompl::base::State *state, double &dist, bool verbose) const { // moveit::Profiler::ScopedBlock sblock("isValid"); return planning_context_->useStateValidityCache() ? isValidWithCache(state, dist, verbose) : isValidWithoutCache(state, dist, verbose); } double ompl_interface::StateValidityChecker::cost(const ompl::base::State *state) const { bool useCollisionDistanceCost = false; // TODO - set this somewhere else double cost = 0.0; if( useCollisionDistanceCost ) // proximity to collisions cost { robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); collision_detection::CollisionResult res; planning_context_->getPlanningScene()->checkCollision(collision_request_with_cost_, res, *kstate); for (std::set<collision_detection::CostSource>::const_iterator it = res.cost_sources.begin() ; it != res.cost_sources.end() ; ++it) cost += it->cost * it->getVolume(); } else // use distance between joints cost { static std::vector<double> prev_joint_values; static bool first_time = true; static boost::thread::id thread_id = boost::this_thread::get_id(); // Check that we are still on same thread if( thread_id != boost::this_thread::get_id() ) ROS_ERROR_STREAM("Multiple threads are not implemented here..."); // Get current robot state robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); std::vector<double> new_joint_values; // get joint state values kstate->getStateValues(new_joint_values); // calculate cost for (std::size_t i = 0; i < new_joint_values.size(); ++i) { double value = 0; // Check if first time if (first_time) { first_time = false; prev_joint_values.resize(new_joint_values.size()); } else { // get abs of difference in each joint value value = fabs(prev_joint_values[i] - new_joint_values[i]); } cost += value; // copy new value to old vector prev_joint_values[i] = new_joint_values[i]; } } return cost; } double ompl_interface::StateValidityChecker::clearance(const ompl::base::State *state) const { robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); collision_detection::CollisionResult res; planning_context_->getPlanningScene()->checkCollision(collision_request_with_distance_, res, *kstate); return res.collision ? 0.0 : (res.distance < 0.0 ? std::numeric_limits<double>::infinity() : res.distance); } bool ompl_interface::StateValidityChecker::isValidWithoutCache(const ompl::base::State *state, bool verbose) const { if (!si_->satisfiesBounds(state)) { if (verbose) logInform("State outside bounds"); return false; } robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); // check path constraints const kinematic_constraints::KinematicConstraintSetPtr &kset = planning_context_->getPathConstraints(); if (kset && !kset->decide(*kstate, verbose).satisfied) return false; // check feasibility if (!planning_context_->getPlanningScene()->isStateFeasible(*kstate, verbose)) return false; // check collision avoidance collision_detection::CollisionResult res; planning_context_->getPlanningScene()->checkCollision(verbose ? collision_request_simple_verbose_ : collision_request_simple_, res, *kstate); return res.collision == false; } bool ompl_interface::StateValidityChecker::isValidWithoutCache(const ompl::base::State *state, double &dist, bool verbose) const { if (!si_->satisfiesBounds(state)) { if (verbose) logInform("State outside bounds"); return false; } robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); // check path constraints const kinematic_constraints::KinematicConstraintSetPtr &kset = planning_context_->getPathConstraints(); if (kset) { kinematic_constraints::ConstraintEvaluationResult cer = kset->decide(*kstate, verbose); if (!cer.satisfied) { dist = cer.distance; return false; } } // check feasibility if (!planning_context_->getPlanningScene()->isStateFeasible(*kstate, verbose)) { dist = 0.0; return false; } // check collision avoidance collision_detection::CollisionResult res; planning_context_->getPlanningScene()->checkCollision(verbose ? collision_request_with_distance_verbose_ : collision_request_with_distance_, res, *kstate); dist = res.distance; return res.collision == false; } bool ompl_interface::StateValidityChecker::isValidWithCache(const ompl::base::State *state, bool verbose) const { if (state->as<ModelBasedStateSpace::StateType>()->isValidityKnown()) return state->as<ModelBasedStateSpace::StateType>()->isMarkedValid(); if (!si_->satisfiesBounds(state)) { if (verbose) logInform("State outside bounds"); const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markInvalid(); return false; } robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); // check path constraints const kinematic_constraints::KinematicConstraintSetPtr &kset = planning_context_->getPathConstraints(); if (kset && !kset->decide(*kstate, verbose).satisfied) { const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markInvalid(); return false; } // check feasibility if (!planning_context_->getPlanningScene()->isStateFeasible(*kstate, verbose)) { const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markInvalid(); return false; } // check collision avoidance collision_detection::CollisionResult res; planning_context_->getPlanningScene()->checkCollision(verbose ? collision_request_simple_verbose_ : collision_request_simple_, res, *kstate); if (res.collision == false) { const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markValid(); return true; } else { const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markInvalid(); return false; } } bool ompl_interface::StateValidityChecker::isValidWithCache(const ompl::base::State *state, double &dist, bool verbose) const { if (state->as<ModelBasedStateSpace::StateType>()->isValidityKnown() && state->as<ModelBasedStateSpace::StateType>()->isGoalDistanceKnown()) { dist = state->as<ModelBasedStateSpace::StateType>()->distance; return state->as<ModelBasedStateSpace::StateType>()->isMarkedValid(); } if (!si_->satisfiesBounds(state)) { if (verbose) logInform("State outside bounds"); const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markInvalid(0.0); return false; } robot_state::RobotState *kstate = tss_.getStateStorage(); planning_context_->getOMPLStateSpace()->copyToRobotState(*kstate, state); // check path constraints const kinematic_constraints::KinematicConstraintSetPtr &kset = planning_context_->getPathConstraints(); if (kset) { kinematic_constraints::ConstraintEvaluationResult cer = kset->decide(*kstate, verbose); if (!cer.satisfied) { dist = cer.distance; const_cast<ob::State*>(state)->as<ModelBasedStateSpace::StateType>()->markInvalid(dist); return false; } } // check feasibility if (!planning_context_->getPlanningScene()->isStateFeasible(*kstate, verbose)) { dist = 0.0; return false; } // check collision avoidance collision_detection::CollisionResult res; planning_context_->getPlanningScene()->checkCollision(verbose ? collision_request_with_distance_verbose_ : collision_request_with_distance_, res, *kstate); dist = res.distance; return res.collision == false; } <|endoftext|>
<commit_before>#include "Controller.h" #include <iostream> #include <chrono> typedef std::chrono::high_resolution_clock Clock; typedef std::chrono::duration<double, std::milli> millisec_t; Controller::Controller() : m_ballPosOptiTrack(0, 0), m_ballVelOptiTrack(0, 0), m_initialized(false) { sigmaRef = 0.0; psiRef = 0.0; JRigidInv << 0, 0, 0, 0; xip(0) = 0.0; xip(1) = 0.0; qpRef = JRigidInv*xip; psipRef = qpRef(0); sigmapRef = qpRef(1); setReferenceEnergy(0.0); //H = 1 / 2 * pow(0.0, 2) + g*sin(beta)*0.0; //Href = getReferenceEnergy(); //Htilde = H - Href; //reflection gain of mirror law 0.075, // restoring of the energy href 0.01 //this->setGains(0.075, 0.1, 0.05, 0.05); /* Following set of gains seems to work alright this->setGains(0.05, 0.001, 0.1, 0.05) // also k1 = 1e-4 */ double k0 = 0.285; double k1 = 0.593; double k00 = 0.718; double k01 = 0.155; // For heavier puck this->setDefaultGains(k0, k1, k00, k01); this->setGains(k0, k1, k00, k01); } Controller::~Controller() { delete m_serialComm; } int Controller::initialize(OptiTrack* optiTrackPointer) { if (m_initialized) { printf("Controller already initialized. Exiting"); } m_optiTrackPointer = optiTrackPointer; //ToDo: check if pointer was initilaized try { m_serialComm = new SerialCommunicator(); } catch(...) { // catch any serial errors! printf("COM Port not open!"); return 1; } // create a motor object std::cout << "Controller Init, Thread :: ID = " << std::this_thread::get_id() << std::endl; int motorSetPosition = 0; //std::cout << "In Main Thread : Before Thread Start motorSetPosition = " << motorSetPosition << std::endl; // ToDo: get a handle on that thread m_initialized = true; // Start the Thread! std::thread threadObj(&Controller::controlArmThread, this); if (threadObj.joinable()) { //threadObj.join(); //std::cout << "Joined Thread " << std::endl; std::cout << "Detaching Control Arm Thread " << std::endl; threadObj.detach(); } } void Controller::getDefaultGains(double* gainReflection, double* gainEnergy, double* gainHoriz, double* gainHorizDer) { std::lock_guard<std::mutex> guard(m_mutexGains); *gainReflection = kappa0Default; *gainEnergy = kappa1Default; *gainHoriz = kappa00Default; *gainHorizDer = kappa01Default; } void Controller::setDefaultGains(const double& gainReflection, const double& gainEnergy, const double& gainHoriz, const double& gainHorizDer) { std::lock_guard<std::mutex> guard(m_mutexGains); kappa0Default = gainReflection; kappa1Default = gainEnergy; kappa00Default = gainHoriz; kappa01Default = gainHorizDer; } void Controller::getGains(double* gainReflection, double* gainEnergy, double* gainHoriz, double* gainHorizDer) { std::lock_guard<std::mutex> guard(m_mutexGains); *gainReflection = kappa0; *gainEnergy = kappa1; *gainHoriz = kappa00; *gainHorizDer = kappa01; } void Controller::setGains(const double& gainReflection, const double& gainEnergy, const double& gainHoriz, const double& gainHorizDer) { std::lock_guard<std::mutex> guard(m_mutexGains); kappa0 = gainReflection; kappa1 = gainEnergy; kappa00 = gainHoriz; kappa01 = gainHorizDer; } double Controller::getReferenceEnergy() { return Href; } void Controller::setReferenceEnergy(double referenceEnergy) { Href = referenceEnergy; } double Controller::computeVerticalEnergy() { return 1 / 2 * pow(zp, 2) + g*sin(beta)*z; } void Controller::computeSigmaRef() { ballDistanceSquaredFromHinge = pow(ox - x, 2) + pow(oz - z, 2); sigmaRef = sqrt(-pow(r + rz, 2) + ballDistanceSquaredFromHinge) - rx; } void Controller::updateReferencePosition() { /* Old calculation psiRef = atan2(-(oz - z)*sigmaRef + r*(ox - x), (ox - x)*sigmaRef - r*(oz - z)) - M_PI; psiRef = remainder(-psiRef, (2 * M_PI)); */ //psiRef = atan2( (r+rz)*(ox - x) + (sigmaRef+rx)*(oz-z), (sigmaRef+rx)*(ox-x) - (r+rz)*(oz-z) ); psiRef = atan2((r + rz)*(ox - x) + (sigmaRef + rx)*(oz - z), (sigmaRef + rx)*(ox - x) - (r + rz)*(oz - z)); } void Controller::updateReferenceVelocity() { computeJacobianInverse(); Vector2d xip(xp, zp); Vector2d refVel = JRigidInv*xip; psipRef = refVel(0); sigmapRef = refVel(1); } void Controller::computeJacobianInverse() { /*Old Jinv JRigidInv(0, 0) = (r*(x - ox) + (z - oz)*sigmaRef) / ballDistanceSquaredFromHinge / sigmaRef; JRigidInv(0, 1) = (r*(z - oz) + (ox - x)*sigmaRef) / ballDistanceSquaredFromHinge / sigmaRef; JRigidInv(1, 0) = (ox - x) / sigmaRef; JRigidInv(1, 1) = (oz - z) / sigmaRef; */ JRigidInv(0, 0) = ((r + rz)*(ox - x) + (sigmaRef + rx)*(oz - z)) / ballDistanceSquaredFromHinge / (sigmaRef + rx); JRigidInv(0, 1) = ((r + rz)*(oz - z) - (sigmaRef + rx)*(ox - x)) / ballDistanceSquaredFromHinge / (sigmaRef + rx); JRigidInv(1, 0) = -(ox - x) / (sigmaRef + rx); JRigidInv(1, 1) = -(oz - z) / (sigmaRef + rx); } double Controller::computeDesiredPaddlePosition() { // control vertically H = computeVerticalEnergy(); //Htilde = H - Href; Htilde = Href - H; computeSigmaRef(); updateReferencePosition(); updateReferenceVelocity(); // Control horizontally double rhoBar = rubberLength / 4; //in the rubber frame double rhoRef = sigmaRef*cos(psiRef); double rhopRef = sigmapRef*cos(psiRef) - sigmaRef*psipRef*sin(psiRef); std::lock_guard<std::mutex> guard(m_mutexGains); return -(kappa0 + kappa1*Htilde)*psiRef - ( kappa00*(rhoRef - rhoBar) + kappa01*rhopRef); } double Controller::computeDesiredPaddleVelocity() { return -m_positionGain * (m_currentPaddlePositionRad - m_desiredPaddlePositionRad); } void Controller::controlArmThread() { //double gaink0, gaink1, gaink00, gaink01; while (true) { // Ensure it was initialized! if (!m_initialized) { printf("please init() controller!"); return; } // printf("I'm in the controller thread.\n"); // Velocity of Motor from Mbed m_motorVelMeasRadS = this->m_serialComm->readMotorRadPerSec(); //Position of Paddle as set by OptiTrack m_currentPaddlePositionRad = m_optiTrackPointer->getPaddlePosition(); //Position and Velocity of Puck Vector2d ballPos = m_optiTrackPointer->getBallPosition(); x = ballPos(0); z = ballPos(1); Vector2d ballVel = m_optiTrackPointer->getBallVelocity(); xp = ballVel(0); zp = ballVel(1); m_desiredPaddlePositionRad = this->computeDesiredPaddlePosition(); m_desiredPaddleVelocityRad = this->computeDesiredPaddleVelocity(); this->m_serialComm->sendMotorRadPerSec((float)m_desiredPaddleVelocityRad); m_controlThreadCounter++; std::this_thread::sleep_for(std::chrono::milliseconds(LOOP_PERIOD_MS)); if (m_debug) { if (m_controlThreadCounter % LOOPCOUNTS_INT == 0) { printf("sigRef= %3.2f, psiRef= %3.2f, psiDes= %3.2f, psipDes= %3.2f\n", sigmaRef, psiRef, m_desiredPaddlePositionRad, m_desiredPaddleVelocityRad); //printf("H = %3.2f, \t Href = %3.2f \t Htilde = %3.2f \t \n", H, Href, Htilde); } /*if (m_controlThreadCounter % LOOPCOUNTS_INT == 150) { this->getGains(&gaink0, &gaink1, &gaink00, &gaink01); printf("k0 = %4.3f, k1 = %4.3f, k00 = %4.3f, k01 = %4.3f\n", gaink0, gaink1, gaink00, gaink01); }*/ } //double incline = computeIncline(); //printf("The inline is %3.2f degrees.\n", incline); } } double sgn(double d) { double eps = 1e-16; return d<-eps ? -1 : d>eps; } //double Controller::computeIncline() //{ // Vector2d ballPos = m_optiTrackPointer->getBallPosition(); // z = ballPos(1); // // while (abs(z) > 0.25) { // m_optiTrackPointer->getBallPosition(); // z = ballPos(1); // printf("z-coordinate is = %3.2f\n", z); // } // // auto t1 = Clock::now(); // while (abs(z) < 0.25) { // m_optiTrackPointer->getBallPosition(); // z = ballPos(1); // } // auto t2 = Clock::now(); // // millisec_t clkDuration(std::chrono::duration_cast<millisec_t>(t2 - t1)); // // double deltat= clkDuration.count();; // double deltaz = 0.5; // double incline = ( asin((-2 * deltaz) / g / deltat / deltat) ) * 180 / M_PI; // // return incline; //} <commit_msg>Went above 30 degree inclination with this.<commit_after>#include "Controller.h" #include <iostream> #include <chrono> typedef std::chrono::high_resolution_clock Clock; typedef std::chrono::duration<double, std::milli> millisec_t; Controller::Controller() : m_ballPosOptiTrack(0, 0), m_ballVelOptiTrack(0, 0), m_initialized(false) { sigmaRef = 0.0; psiRef = 0.0; JRigidInv << 0, 0, 0, 0; xip(0) = 0.0; xip(1) = 0.0; qpRef = JRigidInv*xip; psipRef = qpRef(0); sigmapRef = qpRef(1); setReferenceEnergy(0.0); //reflection gain of mirror law 0.075, // restoring of the energy href 0.01 //this->setGains(0.075, 0.1, 0.05, 0.05); /* Following set of gains seems to work alright this->setGains(0.05, 0.001, 0.1, 0.05) // also k1 = 1e-4 */ // These are for inclination, beta = 15.6 degrees. /*double k0 = 0.285; double k1 = 0.593; double k00 = 0.718; double k01 = 0.155;*/ // For heavier puck // Increase inclination to, beta = ~33 degrees double k0 = 0.315; double k1 = 0.593; double k00 = 0.869; double k01 = 0.170; this->setDefaultGains(k0, k1, k00, k01); this->setGains(k0, k1, k00, k01); } Controller::~Controller() { delete m_serialComm; } int Controller::initialize(OptiTrack* optiTrackPointer) { if (m_initialized) { printf("Controller already initialized. Exiting"); } m_optiTrackPointer = optiTrackPointer; //ToDo: check if pointer was initilaized try { m_serialComm = new SerialCommunicator(); } catch(...) { // catch any serial errors! printf("COM Port not open!"); return 1; } // create a motor object std::cout << "Controller Init, Thread :: ID = " << std::this_thread::get_id() << std::endl; int motorSetPosition = 0; //std::cout << "In Main Thread : Before Thread Start motorSetPosition = " << motorSetPosition << std::endl; // ToDo: get a handle on that thread m_initialized = true; // Start the Thread! std::thread threadObj(&Controller::controlArmThread, this); if (threadObj.joinable()) { //threadObj.join(); //std::cout << "Joined Thread " << std::endl; std::cout << "Detaching Control Arm Thread " << std::endl; threadObj.detach(); } } void Controller::getDefaultGains(double* gainReflection, double* gainEnergy, double* gainHoriz, double* gainHorizDer) { std::lock_guard<std::mutex> guard(m_mutexGains); *gainReflection = kappa0Default; *gainEnergy = kappa1Default; *gainHoriz = kappa00Default; *gainHorizDer = kappa01Default; } void Controller::setDefaultGains(const double& gainReflection, const double& gainEnergy, const double& gainHoriz, const double& gainHorizDer) { std::lock_guard<std::mutex> guard(m_mutexGains); kappa0Default = gainReflection; kappa1Default = gainEnergy; kappa00Default = gainHoriz; kappa01Default = gainHorizDer; } void Controller::getGains(double* gainReflection, double* gainEnergy, double* gainHoriz, double* gainHorizDer) { std::lock_guard<std::mutex> guard(m_mutexGains); *gainReflection = kappa0; *gainEnergy = kappa1; *gainHoriz = kappa00; *gainHorizDer = kappa01; } void Controller::setGains(const double& gainReflection, const double& gainEnergy, const double& gainHoriz, const double& gainHorizDer) { std::lock_guard<std::mutex> guard(m_mutexGains); kappa0 = gainReflection; kappa1 = gainEnergy; kappa00 = gainHoriz; kappa01 = gainHorizDer; } double Controller::getReferenceEnergy() { return Href; } void Controller::setReferenceEnergy(double referenceEnergy) { Href = referenceEnergy; } double Controller::computeVerticalEnergy() { return 1 / 2 * pow(zp, 2) + g*sin(beta)*z; } void Controller::computeSigmaRef() { ballDistanceSquaredFromHinge = pow(ox - x, 2) + pow(oz - z, 2); sigmaRef = sqrt(-pow(r + rz, 2) + ballDistanceSquaredFromHinge) - rx; } void Controller::updateReferencePosition() { /* Old calculation psiRef = atan2(-(oz - z)*sigmaRef + r*(ox - x), (ox - x)*sigmaRef - r*(oz - z)) - M_PI; psiRef = remainder(-psiRef, (2 * M_PI)); */ //psiRef = atan2( (r+rz)*(ox - x) + (sigmaRef+rx)*(oz-z), (sigmaRef+rx)*(ox-x) - (r+rz)*(oz-z) ); psiRef = atan2((r + rz)*(ox - x) + (sigmaRef + rx)*(oz - z), (sigmaRef + rx)*(ox - x) - (r + rz)*(oz - z)); } void Controller::updateReferenceVelocity() { computeJacobianInverse(); Vector2d xip(xp, zp); Vector2d refVel = JRigidInv*xip; psipRef = refVel(0); sigmapRef = refVel(1); } void Controller::computeJacobianInverse() { /*Old Jinv JRigidInv(0, 0) = (r*(x - ox) + (z - oz)*sigmaRef) / ballDistanceSquaredFromHinge / sigmaRef; JRigidInv(0, 1) = (r*(z - oz) + (ox - x)*sigmaRef) / ballDistanceSquaredFromHinge / sigmaRef; JRigidInv(1, 0) = (ox - x) / sigmaRef; JRigidInv(1, 1) = (oz - z) / sigmaRef; */ JRigidInv(0, 0) = ((r + rz)*(ox - x) + (sigmaRef + rx)*(oz - z)) / ballDistanceSquaredFromHinge / (sigmaRef + rx); JRigidInv(0, 1) = ((r + rz)*(oz - z) - (sigmaRef + rx)*(ox - x)) / ballDistanceSquaredFromHinge / (sigmaRef + rx); JRigidInv(1, 0) = -(ox - x) / (sigmaRef + rx); JRigidInv(1, 1) = -(oz - z) / (sigmaRef + rx); } double Controller::computeDesiredPaddlePosition() { // control vertically H = computeVerticalEnergy(); //Htilde = H - Href; Htilde = Href - H; computeSigmaRef(); updateReferencePosition(); updateReferenceVelocity(); // Control horizontally double rhoBar = rubberLength / 4; //in the rubber frame double rhoRef = sigmaRef*cos(psiRef); double rhopRef = sigmapRef*cos(psiRef) - sigmaRef*psipRef*sin(psiRef); std::lock_guard<std::mutex> guard(m_mutexGains); return -(kappa0 + kappa1*Htilde)*psiRef - ( kappa00*(rhoRef - rhoBar) + kappa01*rhopRef); } double Controller::computeDesiredPaddleVelocity() { return -m_positionGain * (m_currentPaddlePositionRad - m_desiredPaddlePositionRad); } void Controller::controlArmThread() { //double gaink0, gaink1, gaink00, gaink01; while (true) { // Ensure it was initialized! if (!m_initialized) { printf("please init() controller!"); return; } // printf("I'm in the controller thread.\n"); // Velocity of Motor from Mbed m_motorVelMeasRadS = this->m_serialComm->readMotorRadPerSec(); //Position of Paddle as set by OptiTrack m_currentPaddlePositionRad = m_optiTrackPointer->getPaddlePosition(); //Position and Velocity of Puck Vector2d ballPos = m_optiTrackPointer->getBallPosition(); x = ballPos(0); z = ballPos(1); Vector2d ballVel = m_optiTrackPointer->getBallVelocity(); xp = ballVel(0); zp = ballVel(1); m_desiredPaddlePositionRad = this->computeDesiredPaddlePosition(); m_desiredPaddleVelocityRad = this->computeDesiredPaddleVelocity(); this->m_serialComm->sendMotorRadPerSec((float)m_desiredPaddleVelocityRad); m_controlThreadCounter++; std::this_thread::sleep_for(std::chrono::milliseconds(LOOP_PERIOD_MS)); if (m_debug) { if (m_controlThreadCounter % LOOPCOUNTS_INT == 0) { printf("sigRef= %3.2f, psiRef= %3.2f, psiDes= %3.2f, psipDes= %3.2f\n", sigmaRef, psiRef, m_desiredPaddlePositionRad, m_desiredPaddleVelocityRad); //printf("H = %3.2f, \t Href = %3.2f \t Htilde = %3.2f \t \n", H, Href, Htilde); } /*if (m_controlThreadCounter % LOOPCOUNTS_INT == 150) { this->getGains(&gaink0, &gaink1, &gaink00, &gaink01); printf("k0 = %4.3f, k1 = %4.3f, k00 = %4.3f, k01 = %4.3f\n", gaink0, gaink1, gaink00, gaink01); }*/ } //double incline = computeIncline(); //printf("The inline is %3.2f degrees.\n", incline); } } double sgn(double d) { double eps = 1e-16; return d<-eps ? -1 : d>eps; } //double Controller::computeIncline() //{ // Vector2d ballPos = m_optiTrackPointer->getBallPosition(); // z = ballPos(1); // // while (abs(z) > 0.25) { // m_optiTrackPointer->getBallPosition(); // z = ballPos(1); // printf("z-coordinate is = %3.2f\n", z); // } // // auto t1 = Clock::now(); // while (abs(z) < 0.25) { // m_optiTrackPointer->getBallPosition(); // z = ballPos(1); // } // auto t2 = Clock::now(); // // millisec_t clkDuration(std::chrono::duration_cast<millisec_t>(t2 - t1)); // // double deltat= clkDuration.count();; // double deltaz = 0.5; // double incline = ( asin((-2 * deltaz) / g / deltat / deltat) ) * 180 / M_PI; // // return incline; //} <|endoftext|>
<commit_before>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*- * * Quadra, an action puzzle game * Copyright (C) 1998-2000 Ludus Design * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <string.h> #include "input.h" #include "cursor.h" #include "listbox.h" RCSID("$Id$") Zone_listbox::Zone_listbox(Inter* in, Bitmap *fond, Font *f, int *pval, int px, int py, int pw, int ph): Zone_watch_int(in, pval, px, py, pw, ph) { if(fond) back = new Bitmap((*fond)[py+1]+px+1, pw-2, ph-2, fond->realwidth); else back = NULL; screen = Video_bitmap::New(px+1, py+1, pw-2, ph-2); font2 = f; zup = new Zone_listup(this); zdown = new Zone_listdown(this); for(int i=y+18; i<y+h-18-f->height(); i+=f->height()) { list.add(new Zone_listtext(this, i)); } first_item = 0; if(val) select(*val); } Zone_listbox::~Zone_listbox() { empty(); while(list.size()) { delete list.last(); list.removelast(); } delete zdown; delete zup; if(back) delete back; delete screen; } void Zone_listbox::draw() { screen->setmem(); if(back) back->draw(screen, 0, 0); video->vb->hline(y, x, w, 210); video->vb->hline(y+h-1, x, w, 210); video->vb->vline(x, y, h, 210); video->vb->vline(x+w-1, y, h, 210); //video->vb->hline(y+20, x, w, 210); //video->vb->hline(y+h-1-20, x, w, 210); } void Zone_listbox::dirt() { if(dirty != 2) { Zone_watch_int::dirt(); zup->dirt(); zdown->dirt(); for(int i=0; i<list.size(); i++) list[i]->dirt(); } } void Zone_listbox::enable() { Zone_watch_int::enable(); zup->enable(); zdown->enable(); for(int i=0; i<list.size(); i++) list[i]->enable(); } void Zone_listbox::disable() { Zone_watch_int::disable(); zup->disable(); zdown->disable(); for(int i=0; i<list.size(); i++) list[i]->disable(); } void Zone_listbox::init_sort() { sort_list.clear(); } void Zone_listbox::add_sort(Listable *l) { sort_list.add(l); } void Zone_listbox::end_sort() { qsort((void *) &sort_list[0], sort_list.size(), sizeof(sort_list[0]), compare_sort); for(int i=0; i<sort_list.size(); i++) add_item(sort_list[i]); sort_list.clear(); } int Zone_listbox::compare_sort(const void *arg1, const void *arg2) { char *s1 = (*(Listable **) arg1)->list_name; char *s2 = (*(Listable **) arg2)->list_name; return strcasecmp(s1, s2); } void Zone_listbox::add_item(Listable *e) { elements.add(e); sync_list(); } void Zone_listbox::replace_item(int i, Listable *e) { delete elements[i]; elements.replace(i, e); sync_list(); } void Zone_listbox::remove_item(Listable *e) { int i; for(i=0; i<elements.size(); i++) if(elements[i]==e) break; if(i==elements.size()) return; if(get_selected()==e) unselect(); delete elements[i]; elements.remove(i); sync_list(); } void Zone_listbox::remove_item(int i) { delete elements[i]; elements.remove(i); sync_list(); } Listable *Zone_listbox::get_selected() { if(!val || *val == -1) return NULL; else return elements[*val]; } void Zone_listbox::process() { Zone_watch_int::process(); if(input) { if(cursor->x > x && cursor->x < x+w && cursor->y > y && cursor->y < y+h) { int z = input->mouse.dz; if(z > 0) zup->clicked(0); if(z < 0) zdown->clicked(0); } } } int Zone_listbox::search(Listable *source) { for(int i=0; i<elements.size(); i++) if(elements[i]->is_equal(source)) return i; return -1; } bool Zone_listbox::in_listbox(const Zone *z) { for(int i=0; i<list.size(); i++) if(list[i] == z) return true; return false; } void Zone_listbox::sync_list() { for(int i=0; i<list.size(); i++) { Font *f = inter->font; list[i]->kb_focusable = false; if(i+first_item >= elements.size()) { list[i]->set_text(""); } else { if(val) list[i]->kb_focusable = true; Listable *li = elements[i+first_item]; list[i]->set_text(li->list_name); if(li->font) f = li->font; } list[i]->set_font(f); } if(val) select(*val); dirt(); } void Zone_listbox::empty() { while(elements.size()) { delete elements.last(); elements.removelast(); } } void Zone_listbox::clear() { empty(); first_item = 0; if(val) *val = -1; sync_list(); } void Zone_listbox::unselect() { if(!val) return; if(*val >= first_item && *val < first_item+list.size()) { Font *f = inter->font; if(elements[*val]->font) f = elements[*val]->font; list[*val-first_item]->set_font(f); } *val = -1; } void Zone_listbox::select(int q) { if(!val) return; *val = q; if(*val >= first_item && *val < first_item+list.size()) { list[*val-first_item]->set_font(font2); } } Zone_listupdown::Zone_listupdown(Zone_listbox *par, const char *s, int py): Zone_text_select(par->inter, par->font2, s, par->x, py, par->w) { parent = par; leaved(); kb_focusable = true; } void Zone_listupdown::waiting() { Zone_text_select::waiting(); if(input->mouse.button[0] & PRESSED) { count--; if(count < 0) { clicked(0); count = 5; } } } void Zone_listupdown::leaved() { Zone_text_select::leaved(); count = 40; } void Zone_listupdown::dirt() { Zone_text_select::dirt(); parent->dirt(); } Zone_listup::Zone_listup(Zone_listbox *par): Zone_listupdown(par, "3", par->y) { } void Zone_listup::clicked(int quel) { if(parent->first_item > 0) { parent->first_item--; parent->sync_list(); parent->clicked(quel); } } Zone_listdown::Zone_listdown(Zone_listbox *par): Zone_listupdown(par, "4", par->y+par->h-18) { } void Zone_listdown::clicked(int quel) { if(parent->first_item < parent->elements.size() - parent->list.size()) { parent->first_item++; parent->sync_list(); parent->clicked(quel); } } Listable::Listable(const char *s, Font *f) { strcpy(list_name, s); font = f; } bool Listable::is_equal(Listable *source) { return !strcmp(list_name, source->list_name); } Zone_listtext::Zone_listtext(Zone_listbox *par, int i): Zone_text(par->inter, "", par->x+2, i, par->w-4) { parent = par; quel = par->list.size(); high = false; } void Zone_listtext::clicked(int quel) { //Watch out! Param 'quel' is mouse button; this->quel is... // hmmm... something else... Ask Remz parent->unselect(); if(this->quel < parent->elements.size()) { parent->select(this->quel + parent->first_item); //inter->clicked = parent; // eww! parent->clicked(quel); } } void Zone_listtext::draw() { parent->screen->setmem(); font->draw(st, parent->screen, text_x-parent->x, y-parent->y); if(high) { if(!kb_focusable) high=false; else video->vb->box(x, y, w, h, 255); } } void Zone_listtext::dirt() { Zone_text::dirt(); parent->dirt(); } void Zone_listtext::entered() { Zone_text::entered(); if(parent->val && kb_focusable) { /* kb_focusable also indicates that this zone_listtext currently contains something */ high=true; dirt(); } } void Zone_listtext::leaved() { Zone_text::leaved(); if(parent->val && kb_focusable) { /* kb_focusable also indicates that this zone_listtext currently contains something */ high=false; dirt(); } } <commit_msg>Attempt at a fix for the crash in Demo Central.<commit_after>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*- * * Quadra, an action puzzle game * Copyright (C) 1998-2000 Ludus Design * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <string.h> #include "input.h" #include "cursor.h" #include "listbox.h" RCSID("$Id$") Zone_listbox::Zone_listbox(Inter* in, Bitmap *fond, Font *f, int *pval, int px, int py, int pw, int ph): Zone_watch_int(in, pval, px, py, pw, ph) { if(fond) back = new Bitmap((*fond)[py+1]+px+1, pw-2, ph-2, fond->realwidth); else back = NULL; screen = Video_bitmap::New(px+1, py+1, pw-2, ph-2); font2 = f; zup = new Zone_listup(this); zdown = new Zone_listdown(this); for(int i=y+18; i<y+h-18-f->height(); i+=f->height()) { list.add(new Zone_listtext(this, i)); } first_item = 0; if(val) select(*val); } Zone_listbox::~Zone_listbox() { empty(); while(list.size()) { delete list.last(); list.removelast(); } delete zdown; delete zup; if(back) delete back; delete screen; } void Zone_listbox::draw() { screen->setmem(); if(back) back->draw(screen, 0, 0); video->vb->hline(y, x, w, 210); video->vb->hline(y+h-1, x, w, 210); video->vb->vline(x, y, h, 210); video->vb->vline(x+w-1, y, h, 210); //video->vb->hline(y+20, x, w, 210); //video->vb->hline(y+h-1-20, x, w, 210); } void Zone_listbox::dirt() { if(dirty != 2) { Zone_watch_int::dirt(); zup->dirt(); zdown->dirt(); for(int i=0; i<list.size(); i++) list[i]->dirt(); } } void Zone_listbox::enable() { Zone_watch_int::enable(); zup->enable(); zdown->enable(); for(int i=0; i<list.size(); i++) list[i]->enable(); } void Zone_listbox::disable() { Zone_watch_int::disable(); zup->disable(); zdown->disable(); for(int i=0; i<list.size(); i++) list[i]->disable(); } void Zone_listbox::init_sort() { sort_list.clear(); } void Zone_listbox::add_sort(Listable *l) { sort_list.add(l); } void Zone_listbox::end_sort() { if (sort_list.size() == 0) return; qsort((void *) &sort_list[0], sort_list.size(), sizeof(sort_list[0]), compare_sort); for (int i = 0; i < sort_list.size(); ++i) add_item(sort_list[i]); sort_list.clear(); } int Zone_listbox::compare_sort(const void *arg1, const void *arg2) { char *s1 = (*(Listable **) arg1)->list_name; char *s2 = (*(Listable **) arg2)->list_name; return strcasecmp(s1, s2); } void Zone_listbox::add_item(Listable *e) { elements.add(e); sync_list(); } void Zone_listbox::replace_item(int i, Listable *e) { delete elements[i]; elements.replace(i, e); sync_list(); } void Zone_listbox::remove_item(Listable *e) { int i; for(i=0; i<elements.size(); i++) if(elements[i]==e) break; if(i==elements.size()) return; if(get_selected()==e) unselect(); delete elements[i]; elements.remove(i); sync_list(); } void Zone_listbox::remove_item(int i) { delete elements[i]; elements.remove(i); sync_list(); } Listable *Zone_listbox::get_selected() { if(!val || *val == -1) return NULL; else return elements[*val]; } void Zone_listbox::process() { Zone_watch_int::process(); if(input) { if(cursor->x > x && cursor->x < x+w && cursor->y > y && cursor->y < y+h) { int z = input->mouse.dz; if(z > 0) zup->clicked(0); if(z < 0) zdown->clicked(0); } } } int Zone_listbox::search(Listable *source) { for(int i=0; i<elements.size(); i++) if(elements[i]->is_equal(source)) return i; return -1; } bool Zone_listbox::in_listbox(const Zone *z) { for(int i=0; i<list.size(); i++) if(list[i] == z) return true; return false; } void Zone_listbox::sync_list() { for(int i=0; i<list.size(); i++) { Font *f = inter->font; list[i]->kb_focusable = false; if(i+first_item >= elements.size()) { list[i]->set_text(""); } else { if(val) list[i]->kb_focusable = true; Listable *li = elements[i+first_item]; list[i]->set_text(li->list_name); if(li->font) f = li->font; } list[i]->set_font(f); } if(val) select(*val); dirt(); } void Zone_listbox::empty() { while(elements.size()) { delete elements.last(); elements.removelast(); } } void Zone_listbox::clear() { empty(); first_item = 0; if(val) *val = -1; sync_list(); } void Zone_listbox::unselect() { if(!val) return; if(*val >= first_item && *val < first_item+list.size()) { Font *f = inter->font; if(elements[*val]->font) f = elements[*val]->font; list[*val-first_item]->set_font(f); } *val = -1; } void Zone_listbox::select(int q) { if(!val) return; *val = q; if(*val >= first_item && *val < first_item+list.size()) { list[*val-first_item]->set_font(font2); } } Zone_listupdown::Zone_listupdown(Zone_listbox *par, const char *s, int py): Zone_text_select(par->inter, par->font2, s, par->x, py, par->w) { parent = par; leaved(); kb_focusable = true; } void Zone_listupdown::waiting() { Zone_text_select::waiting(); if(input->mouse.button[0] & PRESSED) { count--; if(count < 0) { clicked(0); count = 5; } } } void Zone_listupdown::leaved() { Zone_text_select::leaved(); count = 40; } void Zone_listupdown::dirt() { Zone_text_select::dirt(); parent->dirt(); } Zone_listup::Zone_listup(Zone_listbox *par): Zone_listupdown(par, "3", par->y) { } void Zone_listup::clicked(int quel) { if(parent->first_item > 0) { parent->first_item--; parent->sync_list(); parent->clicked(quel); } } Zone_listdown::Zone_listdown(Zone_listbox *par): Zone_listupdown(par, "4", par->y+par->h-18) { } void Zone_listdown::clicked(int quel) { if(parent->first_item < parent->elements.size() - parent->list.size()) { parent->first_item++; parent->sync_list(); parent->clicked(quel); } } Listable::Listable(const char *s, Font *f) { strcpy(list_name, s); font = f; } bool Listable::is_equal(Listable *source) { return !strcmp(list_name, source->list_name); } Zone_listtext::Zone_listtext(Zone_listbox *par, int i): Zone_text(par->inter, "", par->x+2, i, par->w-4) { parent = par; quel = par->list.size(); high = false; } void Zone_listtext::clicked(int quel) { //Watch out! Param 'quel' is mouse button; this->quel is... // hmmm... something else... Ask Remz parent->unselect(); if(this->quel < parent->elements.size()) { parent->select(this->quel + parent->first_item); //inter->clicked = parent; // eww! parent->clicked(quel); } } void Zone_listtext::draw() { parent->screen->setmem(); font->draw(st, parent->screen, text_x-parent->x, y-parent->y); if(high) { if(!kb_focusable) high=false; else video->vb->box(x, y, w, h, 255); } } void Zone_listtext::dirt() { Zone_text::dirt(); parent->dirt(); } void Zone_listtext::entered() { Zone_text::entered(); if(parent->val && kb_focusable) { /* kb_focusable also indicates that this zone_listtext currently contains something */ high=true; dirt(); } } void Zone_listtext::leaved() { Zone_text::leaved(); if(parent->val && kb_focusable) { /* kb_focusable also indicates that this zone_listtext currently contains something */ high=false; dirt(); } } <|endoftext|>