text
stringlengths
54
60.6k
<commit_before>/* This file is part of Ingen. * Copyright (C) 2007 Dave Robillard <http://drobilla.net> * * Ingen 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. * * Ingen 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 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cassert> #include <raul/Atom.hpp> #include "interface/EngineInterface.hpp" #include "client/PatchModel.hpp" #include "client/NodeModel.hpp" #include "App.hpp" #include "NodeModule.hpp" #include "PatchCanvas.hpp" #include "Port.hpp" #include "GladeFactory.hpp" #include "RenameWindow.hpp" #include "PatchWindow.hpp" #include "WindowFactory.hpp" #include "SubpatchModule.hpp" #include "NodeControlWindow.hpp" namespace Ingen { namespace GUI { NodeModule::NodeModule(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node) : FlowCanvas::Module(canvas, node->path().name()) , _node(node) , _gui(NULL) , _gui_item(NULL) { assert(_node); Glib::RefPtr<Gnome::Glade::Xml> xml = GladeFactory::new_glade_reference(); xml->get_widget_derived("object_menu", _menu); _menu->init(node); set_menu(_menu); node->signal_new_port.connect(sigc::bind(sigc::mem_fun(this, &NodeModule::add_port), true)); node->signal_removed_port.connect(sigc::mem_fun(this, &NodeModule::remove_port)); node->signal_metadata.connect(sigc::mem_fun(this, &NodeModule::set_metadata)); node->signal_polyphonic.connect(sigc::mem_fun(this, &NodeModule::set_stacked_border)); node->signal_renamed.connect(sigc::mem_fun(this, &NodeModule::rename)); _menu->signal_embed_gui.connect(sigc::mem_fun(this, &NodeModule::embed_gui)); set_stacked_border(node->polyphonic()); } NodeModule::~NodeModule() { NodeControlWindow* win = App::instance().window_factory()->control_window(_node); if (win) { // Should remove from window factory via signal delete win; } } boost::shared_ptr<NodeModule> NodeModule::create(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node) { boost::shared_ptr<NodeModule> ret; SharedPtr<PatchModel> patch = PtrCast<PatchModel>(node); if (patch) ret = boost::shared_ptr<NodeModule>(new SubpatchModule(canvas, patch)); else ret = boost::shared_ptr<NodeModule>(new NodeModule(canvas, node)); for (MetadataMap::const_iterator m = node->metadata().begin(); m != node->metadata().end(); ++m) ret->set_metadata(m->first, m->second); for (PortModelList::const_iterator p = node->ports().begin(); p != node->ports().end(); ++p) ret->add_port(*p, false); ret->resize(); return ret; } void NodeModule::embed_gui(bool embed) { if (embed) { GtkWidget* c_widget = NULL; if (!_gui_item) { cerr << "Embedding LV2 GUI" << endl; // FIXME: leaks? SLV2UIInstance ui = _node->plugin()->ui(App::instance().engine().get(), _node.get()); if (ui) { cerr << "Found UI" << endl; c_widget = (GtkWidget*)slv2_ui_instance_get_widget(ui); _gui = Glib::wrap(c_widget); assert(_gui); const double y = 4 + _canvas_title.property_text_height(); _gui_item = new Gnome::Canvas::Widget(/**_canvas.lock()->root()*/*this, 2.0, y, *_gui); } } if (_gui_item) { assert(_gui); cerr << "Created canvas item" << endl; _gui->show(); _gui->show_all(); _gui_item->show(); GtkRequisition r; gtk_widget_size_request(c_widget, &r); cerr << "Size request: " << r.width << "x" << r.height << endl; _width = max(_width, (double)r.width); _height = max(_height, (double)r.height); _gui_item->property_width() = _width - 2; _gui_item->property_height() = _height; _gui_item->raise_to_top(); _ports_y_offset = _height + 2; set_width(_width); } else { cerr << "*** Failed to create canvas item" << endl; } } else { if (_gui_item) _gui_item->hide(); _ports_y_offset = 0; } resize(); } void NodeModule::rename() { set_name(_node->path().name()); } void NodeModule::add_port(SharedPtr<PortModel> port, bool resize_to_fit) { Module::add_port(boost::shared_ptr<Port>(new Port( PtrCast<NodeModule>(shared_from_this()), port))); if (resize_to_fit) resize(); } void NodeModule::remove_port(SharedPtr<PortModel> port) { SharedPtr<FlowCanvas::Port> p = Module::remove_port(port->path().name()); p.reset(); } void NodeModule::show_control_window() { #ifdef HAVE_SLV2 if (_node->plugin()->type() == PluginModel::LV2) { // FIXME: check type SLV2UIInstance ui = _node->plugin()->ui(App::instance().engine().get(), _node.get()); if (ui) { cerr << "Showing LV2 GUI" << endl; // FIXME: leak GtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(ui); Gtk::Widget* widget = Glib::wrap(c_widget); Gtk::Window* win = new Gtk::Window(); win->add(*widget); widget->show_all(); win->show_all(); win->present(); widget->show_all(); win->show_all(); } else { cerr << "No LV2 GUI, showing builtin controls" << endl; App::instance().window_factory()->present_controls(_node); } } else { App::instance().window_factory()->present_controls(_node); } #else App::instance().window_factory()->present_controls(_node); #endif } void NodeModule::store_location() { const float x = static_cast<float>(property_x()); const float y = static_cast<float>(property_y()); const Atom& existing_x = _node->get_metadata("ingenuity:canvas-x"); const Atom& existing_y = _node->get_metadata("ingenuity:canvas-y"); if (existing_x.type() != Atom::FLOAT || existing_y.type() != Atom::FLOAT || existing_x.get_float() != x || existing_y.get_float() != y) { App::instance().engine()->set_metadata(_node->path(), "ingenuity:canvas-x", Atom(x)); App::instance().engine()->set_metadata(_node->path(), "ingenuity:canvas-y", Atom(y)); } } void NodeModule::set_metadata(const string& key, const Atom& value) { if (key == "ingenuity:canvas-x" && value.type() == Atom::FLOAT) move_to(value.get_float(), property_y()); else if (key == "ingenuity:canvas-y" && value.type() == Atom::FLOAT) move_to(property_x(), value.get_float()); } } // namespace GUI } // namespace Ingen <commit_msg>LV2 GUI embedding w/ proper sizing.<commit_after>/* This file is part of Ingen. * Copyright (C) 2007 Dave Robillard <http://drobilla.net> * * Ingen 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. * * Ingen 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 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cassert> #include <raul/Atom.hpp> #include "interface/EngineInterface.hpp" #include "client/PatchModel.hpp" #include "client/NodeModel.hpp" #include "App.hpp" #include "NodeModule.hpp" #include "PatchCanvas.hpp" #include "Port.hpp" #include "GladeFactory.hpp" #include "RenameWindow.hpp" #include "PatchWindow.hpp" #include "WindowFactory.hpp" #include "SubpatchModule.hpp" #include "NodeControlWindow.hpp" namespace Ingen { namespace GUI { NodeModule::NodeModule(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node) : FlowCanvas::Module(canvas, node->path().name()) , _node(node) , _gui(NULL) , _gui_item(NULL) { assert(_node); Glib::RefPtr<Gnome::Glade::Xml> xml = GladeFactory::new_glade_reference(); xml->get_widget_derived("object_menu", _menu); _menu->init(node); set_menu(_menu); node->signal_new_port.connect(sigc::bind(sigc::mem_fun(this, &NodeModule::add_port), true)); node->signal_removed_port.connect(sigc::mem_fun(this, &NodeModule::remove_port)); node->signal_metadata.connect(sigc::mem_fun(this, &NodeModule::set_metadata)); node->signal_polyphonic.connect(sigc::mem_fun(this, &NodeModule::set_stacked_border)); node->signal_renamed.connect(sigc::mem_fun(this, &NodeModule::rename)); _menu->signal_embed_gui.connect(sigc::mem_fun(this, &NodeModule::embed_gui)); set_stacked_border(node->polyphonic()); } NodeModule::~NodeModule() { NodeControlWindow* win = App::instance().window_factory()->control_window(_node); if (win) { // Should remove from window factory via signal delete win; } } boost::shared_ptr<NodeModule> NodeModule::create(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node) { boost::shared_ptr<NodeModule> ret; SharedPtr<PatchModel> patch = PtrCast<PatchModel>(node); if (patch) ret = boost::shared_ptr<NodeModule>(new SubpatchModule(canvas, patch)); else ret = boost::shared_ptr<NodeModule>(new NodeModule(canvas, node)); for (MetadataMap::const_iterator m = node->metadata().begin(); m != node->metadata().end(); ++m) ret->set_metadata(m->first, m->second); for (PortModelList::const_iterator p = node->ports().begin(); p != node->ports().end(); ++p) ret->add_port(*p, false); ret->resize(); return ret; } void NodeModule::embed_gui(bool embed) { if (embed) { // FIXME: leaks? GtkWidget* c_widget = NULL; Gtk::EventBox* container = NULL; if (!_gui_item) { cerr << "Embedding LV2 GUI" << endl; SLV2UIInstance ui = _node->plugin()->ui(App::instance().engine().get(), _node.get()); if (ui) { cerr << "Found UI" << endl; c_widget = (GtkWidget*)slv2_ui_instance_get_widget(ui); _gui = Glib::wrap(c_widget); assert(_gui); /* Kludge, show in window to get size */ container = new Gtk::EventBox(); container->add(*_gui); container->show_all(); const double y = 4 + _canvas_title.property_text_height(); _gui_item = new Gnome::Canvas::Widget(*this, 2.0, y, *container); } } if (_gui_item) { assert(_gui); cerr << "Created canvas item" << endl; _gui->show(); _gui->show_all(); _gui_item->show(); GtkRequisition r; gtk_widget_size_request(c_widget, &r); cerr << "Size request: " << r.width << "x" << r.height << endl; if (r.width + 4 > _width) set_width(r.width + 4); _height = max(_height, (double)r.height); _gui_item->property_width() = _width - 4; _gui_item->property_height() = r.height; _gui_item->raise_to_top(); _ports_y_offset = r.height + 2; } else { cerr << "*** Failed to create canvas item" << endl; } } else { if (_gui_item) _gui_item->hide(); _ports_y_offset = 0; } resize(); } void NodeModule::rename() { set_name(_node->path().name()); } void NodeModule::add_port(SharedPtr<PortModel> port, bool resize_to_fit) { Module::add_port(boost::shared_ptr<Port>(new Port( PtrCast<NodeModule>(shared_from_this()), port))); if (resize_to_fit) resize(); } void NodeModule::remove_port(SharedPtr<PortModel> port) { SharedPtr<FlowCanvas::Port> p = Module::remove_port(port->path().name()); p.reset(); } void NodeModule::show_control_window() { #ifdef HAVE_SLV2 if (_node->plugin()->type() == PluginModel::LV2) { // FIXME: check type SLV2UIInstance ui = _node->plugin()->ui(App::instance().engine().get(), _node.get()); if (ui) { cerr << "Showing LV2 GUI" << endl; // FIXME: leak GtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(ui); Gtk::Widget* widget = Glib::wrap(c_widget); Gtk::Window* win = new Gtk::Window(); win->add(*widget); widget->show_all(); win->present(); } else { cerr << "No LV2 GUI, showing builtin controls" << endl; App::instance().window_factory()->present_controls(_node); } } else { App::instance().window_factory()->present_controls(_node); } #else App::instance().window_factory()->present_controls(_node); #endif } void NodeModule::store_location() { const float x = static_cast<float>(property_x()); const float y = static_cast<float>(property_y()); const Atom& existing_x = _node->get_metadata("ingenuity:canvas-x"); const Atom& existing_y = _node->get_metadata("ingenuity:canvas-y"); if (existing_x.type() != Atom::FLOAT || existing_y.type() != Atom::FLOAT || existing_x.get_float() != x || existing_y.get_float() != y) { App::instance().engine()->set_metadata(_node->path(), "ingenuity:canvas-x", Atom(x)); App::instance().engine()->set_metadata(_node->path(), "ingenuity:canvas-y", Atom(y)); } } void NodeModule::set_metadata(const string& key, const Atom& value) { if (key == "ingenuity:canvas-x" && value.type() == Atom::FLOAT) move_to(value.get_float(), property_y()); else if (key == "ingenuity:canvas-y" && value.type() == Atom::FLOAT) move_to(property_x(), value.get_float()); } } // namespace GUI } // namespace Ingen <|endoftext|>
<commit_before>// Ignore unused parameter warnings coming from cppuint headers #include <libmesh/ignore_warnings.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <libmesh/restore_warnings.h> #include <libmesh/equation_systems.h> #include <libmesh/mesh.h> #include <libmesh/mesh_generation.h> #include "test_comm.h" using namespace libMesh; class EquationSystemsTest : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE( EquationSystemsTest ); CPPUNIT_TEST( testConstruction ); CPPUNIT_TEST( testAddSystem ); CPPUNIT_TEST( testInit ); CPPUNIT_TEST( testPostInitAddSystem ); CPPUNIT_TEST_SUITE_END(); private: public: void setUp() {} void tearDown() {} void testConstruction() { Mesh mesh(*TestCommWorld); EquationSystems es(mesh); } void testAddSystem() { Mesh mesh(*TestCommWorld); EquationSystems es(mesh); /*System &sys = */es.add_system<System> ("SimpleSystem"); } void testInit() { Mesh mesh(*TestCommWorld); EquationSystems es(mesh); /*System &sys = */es.add_system<System> ("SimpleSystem"); MeshTools::Generation::build_point(mesh); es.init(); } void testPostInitAddSystem() { Mesh mesh(*TestCommWorld); MeshTools::Generation::build_point(mesh); EquationSystems es(mesh); /*System &sys1 = */es.add_system<System> ("SimpleSystem"); es.init(); /*System &sys2 = */es.add_system<System> ("SecondSystem"); es.reinit(); } void testPostInitAddRealSystem() { Mesh mesh(*TestCommWorld); MeshTools::Generation::build_point(mesh); EquationSystems es(mesh); System &sys1 = es.add_system<System> ("SimpleSystem"); sys1.add_variable("u1", FIRST); es.init(); System &sys2 = es.add_system<System> ("SecondSystem"); sys2.add_variable("u2", FIRST); es.reinit(); } }; CPPUNIT_TEST_SUITE_REGISTRATION( EquationSystemsTest ); <commit_msg>Add test for ES::reinit() with newly added Elem<commit_after>// Ignore unused parameter warnings coming from cppuint headers #include <libmesh/ignore_warnings.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <libmesh/restore_warnings.h> #include <libmesh/equation_systems.h> #include <libmesh/mesh.h> #include <libmesh/mesh_generation.h> #include "test_comm.h" using namespace libMesh; class EquationSystemsTest : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE( EquationSystemsTest ); CPPUNIT_TEST( testConstruction ); CPPUNIT_TEST( testAddSystem ); CPPUNIT_TEST( testInit ); CPPUNIT_TEST( testPostInitAddSystem ); CPPUNIT_TEST( testPostInitAddElem ); CPPUNIT_TEST_SUITE_END(); private: public: void setUp() {} void tearDown() {} void testConstruction() { Mesh mesh(*TestCommWorld); EquationSystems es(mesh); } void testAddSystem() { Mesh mesh(*TestCommWorld); EquationSystems es(mesh); /*System &sys = */es.add_system<System> ("SimpleSystem"); } void testInit() { Mesh mesh(*TestCommWorld); EquationSystems es(mesh); /*System &sys = */es.add_system<System> ("SimpleSystem"); MeshTools::Generation::build_point(mesh); es.init(); } void testPostInitAddSystem() { Mesh mesh(*TestCommWorld); MeshTools::Generation::build_point(mesh); EquationSystems es(mesh); /*System &sys1 = */es.add_system<System> ("SimpleSystem"); es.init(); /*System &sys2 = */es.add_system<System> ("SecondSystem"); es.reinit(); } void testPostInitAddRealSystem() { Mesh mesh(*TestCommWorld); MeshTools::Generation::build_point(mesh); EquationSystems es(mesh); System &sys1 = es.add_system<System> ("SimpleSystem"); sys1.add_variable("u1", FIRST); es.init(); System &sys2 = es.add_system<System> ("SecondSystem"); sys2.add_variable("u2", FIRST); es.reinit(); } void testPostInitAddElem() { Mesh mesh(*TestCommWorld); EquationSystems es(mesh); System &sys = es.add_system<System> ("SimpleSystem"); sys.add_variable("u", FIRST); MeshTools::Generation::build_line (mesh, 10, 0., 1., EDGE2); es.init(); Elem* e = Elem::build(EDGE2).release(); e->set_id(mesh.max_elem_id()); e->processor_id() = 0; e->set_node(0) = mesh.node_ptr(2); e->set_node(1) = mesh.node_ptr(8); mesh.add_elem(e); mesh.prepare_for_use(); es.reinit(); } }; CPPUNIT_TEST_SUITE_REGISTRATION( EquationSystemsTest ); <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <random> #include <simulated_annealing.hpp> struct City{ float x; float y; }; float distance(const City& c1, const City& c2) { return std::hypot(c2.x - c1.x, c2.y - c1.y); } using Trajectory = std::vector<City>; std::ostream& operator<<(std::ostream& o, const Trajectory& t) { for (auto& c : t) o << "[" << c.x << ", " << c.y << "], "; return o; } struct Generator{ Trajectory operator()(const Trajectory& t, const SimulatedAnnealing& sa) const { Trajectory t2 = t; std::shuffle(begin(t2), end(t2), std::default_random_engine{}); return t2; } }; struct Energy{ float operator()(const Trajectory& t) const { std::vector<float> distances; for (int i = 1; i < t.size(); ++i) distances.push_back(distance(t[i-1], t[i])); return std::accumulate(begin(distances), end(distances), 0.0); } }; int main() { Energy energy; Generator generator; // City clermont_ferrand{0, 0}; //center of the universe // City madrid{-10, -100}; // City new_york{-1000, 20}; // City shanghai{+5000, -100}; // Trajectory trajectory{clermont_ferrand, madrid, new_york, shanghai}; // City c0 {0.0, 0.0}; // City c1 {1.0, 0.0}; // City c2 {2.0, 0.0}; // City c3 {3.0, 0.0}; // City c4 {4.0, 0.0}; // City c5 {5.0, 0.0}; // City c6 {6.0, 0.0}; // City c7 {7.0, 0.0}; // City c8 {8.0, 0.0}; // City c9 {9.0, 0.0}; // City c10 {10.0, 0.0}; // City c11 {11.0, 0.0}; // City c12 {12.0, 0.0}; // City c13 {13.0, 0.0}; // City c14 {14.0, 0.0}; // City c15 {15.0, 0.0}; // Trajectory trajectory{c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15}; City c0 { 200.0, 800.0}; City c1 {3600.0, 2300.0}; City c2 {3100.0, 3300.0}; City c3 {4700.0, 5750.0}; City c4 {5400.0, 5750.0}; City c5 {5608.0, 7103.0}; City c6 {4493.0, 7102.0}; City c7 {3600.0, 6950.0}; Trajectory trajectory{c0, c1, c2, c3, c4, c5, c6, c7}; std::cout << "Optimal trajectory: " << trajectory << std::endl; std::cout << "Optimal distance: " << energy(trajectory) << std::endl; SimulatedAnnealing sim( 1e3 // start temp , 1e-1 // stop temp , int(1e4) // max it , energy(trajectory) // energy min ); std::shuffle(begin(trajectory), end(trajectory), std::default_random_engine{}); std::cout << "Initial trajectory: " << trajectory << std::endl; sim(energy, trajectory, generator); std::cout << "Final trajectory: " << trajectory << std::endl; return 0; } <commit_msg>[traveling_salesman] fixed warning<commit_after>#include <iostream> #include <algorithm> #include <random> #include <simulated_annealing.hpp> struct City{ float x; float y; }; float distance(const City& c1, const City& c2) { return std::hypot(c2.x - c1.x, c2.y - c1.y); } using Trajectory = std::vector<City>; std::ostream& operator<<(std::ostream& o, const Trajectory& t) { for (auto& c : t) o << "[" << c.x << ", " << c.y << "], "; return o; } struct Generator{ Trajectory operator()(const Trajectory& t, const SimulatedAnnealing& sa) const { Trajectory t2 = t; std::shuffle(begin(t2), end(t2), std::default_random_engine{}); return t2; } }; struct Energy{ float operator()(const Trajectory& t) const { std::vector<float> distances; for (int i = 1; i < t.size(); ++i) distances.push_back(distance(t[i-1], t[i])); return std::accumulate(begin(distances), end(distances), 0.0); } }; int main() { Energy energy; Generator generator; City c0 { 200.0, 800.0}; City c1 {3600.0, 2300.0}; City c2 {3100.0, 3300.0}; City c3 {4700.0, 5750.0}; City c4 {5400.0, 5750.0}; City c5 {5608.0, 7103.0}; City c6 {4493.0, 7102.0}; City c7 {3600.0, 6950.0}; Trajectory trajectory{c0, c1, c2, c3, c4, c5, c6, c7}; std::cout << "Optimal trajectory: " << trajectory << std::endl; std::cout << "Optimal distance: " << energy(trajectory) << std::endl; SimulatedAnnealing sim(1e3, // start temp 1e-1, // stop temp int(1e4), // max it energy(trajectory)); // energy min std::shuffle(begin(trajectory), end(trajectory), std::default_random_engine{}); std::cout << "Initial trajectory: " << trajectory << std::endl; sim(energy, trajectory, generator); std::cout << "Final trajectory: " << trajectory << std::endl; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_UTILS_DESIGN_PATTERN_CREATION_HPP #define IOX_UTILS_DESIGN_PATTERN_CREATION_HPP #include "iceoryx_utils/cxx/expected.hpp" namespace DesignPattern { template <typename DerivedClass, typename ErrorType> class Creation { public: using CreationPattern_t = Creation<DerivedClass, ErrorType>; using result_t = iox::cxx::expected<DerivedClass, ErrorType>; using errorType_t = ErrorType; template <typename... Targs> static result_t create(Targs&&... args) noexcept { return verify(DerivedClass(std::forward<Targs>(args)...)); } static result_t verify(DerivedClass&& newObject) noexcept { if (!newObject.m_isInitialized) { return iox::cxx::error<ErrorType>(newObject.m_errorValue); } return iox::cxx::success<DerivedClass>(std::move(newObject)); } template <typename... Targs> static iox::cxx::expected<ErrorType> placementCreate(void* const memory, Targs&&... args) noexcept { auto newClass = static_cast<DerivedClass*>(memory); new (newClass) DerivedClass(std::forward<Targs>(args)...); if (!newClass->m_isInitialized) { ErrorType errorValue = newClass->m_errorValue; newClass->~DerivedClass(); return iox::cxx::error<ErrorType>(errorValue); } return iox::cxx::success<>(); } Creation() noexcept = default; Creation(Creation&& rhs) noexcept { *this = std::move(rhs); } Creation& operator=(Creation&& rhs) noexcept { if (this != &rhs) { m_isInitialized = rhs.m_isInitialized; m_errorValue = rhs.m_errorValue; rhs.m_isInitialized = false; } return *this; } Creation(const Creation& rhs) noexcept = default; Creation& operator=(const Creation& rhs) noexcept = default; bool isInitialized() const noexcept { return m_isInitialized; } protected: bool m_isInitialized{false}; ErrorType m_errorValue; }; } // namespace DesignPattern #endif // IOX_UTILS_DESIGN_PATTERN_CREATION_HPP <commit_msg>iox-#542 moved error value as well<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_UTILS_DESIGN_PATTERN_CREATION_HPP #define IOX_UTILS_DESIGN_PATTERN_CREATION_HPP #include "iceoryx_utils/cxx/expected.hpp" namespace DesignPattern { template <typename DerivedClass, typename ErrorType> class Creation { public: using CreationPattern_t = Creation<DerivedClass, ErrorType>; using result_t = iox::cxx::expected<DerivedClass, ErrorType>; using errorType_t = ErrorType; template <typename... Targs> static result_t create(Targs&&... args) noexcept { return verify(DerivedClass(std::forward<Targs>(args)...)); } static result_t verify(DerivedClass&& newObject) noexcept { if (!newObject.m_isInitialized) { return iox::cxx::error<ErrorType>(newObject.m_errorValue); } return iox::cxx::success<DerivedClass>(std::move(newObject)); } template <typename... Targs> static iox::cxx::expected<ErrorType> placementCreate(void* const memory, Targs&&... args) noexcept { auto newClass = static_cast<DerivedClass*>(memory); new (newClass) DerivedClass(std::forward<Targs>(args)...); if (!newClass->m_isInitialized) { ErrorType errorValue = newClass->m_errorValue; newClass->~DerivedClass(); return iox::cxx::error<ErrorType>(errorValue); } return iox::cxx::success<>(); } Creation() noexcept = default; Creation(Creation&& rhs) noexcept { *this = std::move(rhs); } Creation& operator=(Creation&& rhs) noexcept { if (this != &rhs) { m_isInitialized = rhs.m_isInitialized; m_errorValue = std::move(rhs.m_errorValue); rhs.m_isInitialized = false; } return *this; } Creation(const Creation& rhs) noexcept = default; Creation& operator=(const Creation& rhs) noexcept = default; bool isInitialized() const noexcept { return m_isInitialized; } protected: bool m_isInitialized{false}; ErrorType m_errorValue; }; } // namespace DesignPattern #endif // IOX_UTILS_DESIGN_PATTERN_CREATION_HPP <|endoftext|>
<commit_before>/** * **************************************************************************** * Copyright (c) 2017, Robert Lukierski. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holder 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. * * **************************************************************************** * Transform feedback. * **************************************************************************** */ #ifndef VISIONCORE_WRAPGL_TRANSFORM_FEEDBACK_IMPL_HPP #define VISIONCORE_WRAPGL_TRANSFORM_FEEDBACK_IMPL_HPP inline vc::wrapgl::TransformFeedback::TransformFeedback() : tbid(0) { create(); } inline vc::wrapgl::TransformFeedback::~TransformFeedback() { destroy(); } inline void vc::wrapgl::TransformFeedback::create() { destroy(); glGenTransformFeedbacks(1, &tbid); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::destroy() { if(tbid != 0) { glDeleteTransformFeedbacks(1, &tbid); WRAPGL_CHECK_ERROR(); tbid = 0; } } inline bool vc::wrapgl::TransformFeedback::isValid() const { return tbid != 0; } inline void vc::wrapgl::TransformFeedback::bind() const { glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, tbid); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::unbind() const { glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, tbid); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::draw(GLenum mode) const { glDrawTransformFeedback(mode, tbid); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::draw(GLenum mode, GLsizei instcnt) const { glDrawTransformFeedbackInstanced(mode, tbid, instcnt); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::begin(GLenum primode) { glBeginTransformFeedback(primode); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::end() { glEndTransformFeedback(); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::pause() { glPauseTransformFeedback(); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::resume() { glPauseTransformFeedback(); WRAPGL_CHECK_ERROR(); } inline GLuint vc::wrapgl::TransformFeedback::id() const { return tbid; } #endif // VISIONCORE_WRAPGL_TRANSFORM_FEEDBACK_IMPL_HPP <commit_msg>Minor bug<commit_after>/** * **************************************************************************** * Copyright (c) 2017, Robert Lukierski. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holder 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. * * **************************************************************************** * Transform feedback. * **************************************************************************** */ #ifndef VISIONCORE_WRAPGL_TRANSFORM_FEEDBACK_IMPL_HPP #define VISIONCORE_WRAPGL_TRANSFORM_FEEDBACK_IMPL_HPP inline vc::wrapgl::TransformFeedback::TransformFeedback() : tbid(0) { create(); } inline vc::wrapgl::TransformFeedback::~TransformFeedback() { destroy(); } inline void vc::wrapgl::TransformFeedback::create() { destroy(); glGenTransformFeedbacks(1, &tbid); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::destroy() { if(tbid != 0) { glDeleteTransformFeedbacks(1, &tbid); WRAPGL_CHECK_ERROR(); tbid = 0; } } inline bool vc::wrapgl::TransformFeedback::isValid() const { return tbid != 0; } inline void vc::wrapgl::TransformFeedback::bind() const { glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, tbid); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::unbind() const { glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::draw(GLenum mode) const { glDrawTransformFeedback(mode, tbid); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::draw(GLenum mode, GLsizei instcnt) const { glDrawTransformFeedbackInstanced(mode, tbid, instcnt); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::begin(GLenum primode) { glBeginTransformFeedback(primode); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::end() { glEndTransformFeedback(); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::pause() { glPauseTransformFeedback(); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::TransformFeedback::resume() { glPauseTransformFeedback(); WRAPGL_CHECK_ERROR(); } inline GLuint vc::wrapgl::TransformFeedback::id() const { return tbid; } #endif // VISIONCORE_WRAPGL_TRANSFORM_FEEDBACK_IMPL_HPP <|endoftext|>
<commit_before> // // This file is part of Easylogging++ samples // el::Loggable sample // // Revision 1.0 // @author mkhan3189 // #include "easylogging++.h" _INITIALIZE_EASYLOGGINGPP class MyClass : public el::Loggable { public: MyClass(const char* name) : m_name(name) {} friend std::ostream& operator<<(std::ostream& os, const MyClass& myclass) { os << myclass.m_name; return os; } private: const char* m_name; }; int main(void) { MyClass c("c"); MyClass c2("c2"); LOG(INFO) << c << " " << c2; return 0; } <commit_msg>minor sample update<commit_after> // // This file is part of Easylogging++ samples // el::Loggable sample // // Revision 1.0 // @author mkhan3189 // #include "easylogging++.h" _INITIALIZE_EASYLOGGINGPP class MyClass : public el::Loggable { public: MyClass(const char* name) : m_name(name) {} friend std::ostream& operator<<(std::ostream& os, const MyClass& myclass) { os << myclass.m_name; return os; } private: const char* m_name; }; int main(void) { MyClass c("c"); MyClass c2("c2"); LOG(INFO) << "I am " << c << "; and I am " << c2; return 0; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 1998-2010 by authors (see AUTHORS.txt ) * * * * This file is part of LuxRays. * * * * LuxRays 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. * * * * LuxRays 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/>. * * * * LuxRays website: http://www.luxrender.net * ***************************************************************************/ #include <cstdio> #include <cstdlib> #include "smalllux.h" #include "mainwindow.h" #include "luxmarkapp.h" static void PrintCmdLineHelp(const QString &cmd) { cerr << "Usage: " << cmd.toAscii().data() << " [options]" << endl << " --help <display this help and exit>" << endl << " --scene=<LUXBALL_HDR|SALA|ROOM>" << endl; } int main(int argc, char **argv) { LuxMarkApp app(argc, argv); // Get the arguments into a list bool exit = false; QStringList argsList = app.arguments(); QRegExp argHelp("--help"); QRegExp argScene("--scene=(LUXBALL_HDR|SALA|ROOM)"); LuxMarkAppMode mode = BENCHMARK_OCL_GPU; const char *scnName = SCENE_SALA; for (int i = 1; i < argsList.size(); ++i) { if (argHelp.indexIn(argsList.at(i)) != -1 ) { PrintCmdLineHelp(argsList.at(0)); exit = true; break; } else if (argScene.indexIn(argsList.at(i)) != -1 ) { QString scene = argScene.cap(1); if (scene.compare("LUXBALL_HDR", Qt::CaseInsensitive) == 0) scnName = SCENE_LUXBALL_HDR; else if (scene.compare("SALA", Qt::CaseInsensitive) == 0) scnName = SCENE_SALA; else if (scene.compare("ROOM", Qt::CaseInsensitive) == 0) scnName = SCENE_ROOM; else { cerr << "Unknown scene name: " << argScene.cap(1).toAscii().data() << endl; PrintCmdLineHelp(argsList.at(0)); exit = true; break; } } else { cerr << "Unknown argument: " << argsList.at(i).toAscii().data() << endl; PrintCmdLineHelp(argsList.at(0)); exit = true; break; } } if (exit) return EXIT_SUCCESS; else { app.Init(mode, scnName); // Force C locale setlocale(LC_NUMERIC,"C"); if (app.mainWin != NULL) return app.exec(); else return EXIT_FAILURE; } } <commit_msg>LuxMark: added command line option --mode=<BENCHMARK_OCL_GPU|BENCHMARK_OCL_CPUGPU|BENCHMARK_OCL_CPU|INTERACTIVE|PAUSE><commit_after>/*************************************************************************** * Copyright (C) 1998-2010 by authors (see AUTHORS.txt ) * * * * This file is part of LuxRays. * * * * LuxRays 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. * * * * LuxRays 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/>. * * * * LuxRays website: http://www.luxrender.net * ***************************************************************************/ #include <cstdio> #include <cstdlib> #include "smalllux.h" #include "mainwindow.h" #include "luxmarkapp.h" static void PrintCmdLineHelp(const QString &cmd) { cerr << "Usage: " << cmd.toAscii().data() << " [options]" << endl << " --help <display this help and exit>" << endl << " --scene=<LUXBALL_HDR|SALA|ROOM>" << endl << " --mode=<BENCHMARK_OCL_GPU|BENCHMARK_OCL_CPUGPU|BENCHMARK_OCL_CPU|INTERACTIVE|PAUSE>" << endl; } int main(int argc, char **argv) { LuxMarkApp app(argc, argv); // Get the arguments into a list bool exit = false; QStringList argsList = app.arguments(); QRegExp argHelp("--help"); QRegExp argScene("--scene=(LUXBALL_HDR|SALA|ROOM)"); QRegExp argMode("--mode=(BENCHMARK_OCL_GPU|BENCHMARK_OCL_CPUGPU|BENCHMARK_OCL_CPU|INTERACTIVE|PAUSE)"); LuxMarkAppMode mode = BENCHMARK_OCL_GPU; const char *scnName = SCENE_SALA; for (int i = 1; i < argsList.size(); ++i) { if (argHelp.indexIn(argsList.at(i)) != -1 ) { PrintCmdLineHelp(argsList.at(0)); exit = true; break; } else if (argScene.indexIn(argsList.at(i)) != -1 ) { QString scene = argScene.cap(1); if (scene.compare("LUXBALL_HDR", Qt::CaseInsensitive) == 0) scnName = SCENE_LUXBALL_HDR; else if (scene.compare("SALA", Qt::CaseInsensitive) == 0) scnName = SCENE_SALA; else if (scene.compare("ROOM", Qt::CaseInsensitive) == 0) scnName = SCENE_ROOM; else { cerr << "Unknown scene name: " << argScene.cap(1).toAscii().data() << endl; PrintCmdLineHelp(argsList.at(0)); exit = true; break; } } else if (argMode.indexIn(argsList.at(i)) != -1 ) { QString scene = argMode.cap(1); if (scene.compare("BENCHMARK_OCL_GPU", Qt::CaseInsensitive) == 0) mode = BENCHMARK_OCL_GPU; else if (scene.compare("BENCHMARK_OCL_CPUGPU", Qt::CaseInsensitive) == 0) mode = BENCHMARK_OCL_CPUGPU; else if (scene.compare("BENCHMARK_OCL_CPU", Qt::CaseInsensitive) == 0) mode = BENCHMARK_OCL_CPU; else if (scene.compare("INTERACTIVE", Qt::CaseInsensitive) == 0) mode = INTERACTIVE; else if (scene.compare("PAUSE", Qt::CaseInsensitive) == 0) mode = PAUSE; else { cerr << "Unknown mode name: " << argMode.cap(1).toAscii().data() << endl; PrintCmdLineHelp(argsList.at(0)); exit = true; break; } } else { cerr << "Unknown argument: " << argsList.at(i).toAscii().data() << endl; PrintCmdLineHelp(argsList.at(0)); exit = true; break; } } if (exit) return EXIT_SUCCESS; else { app.Init(mode, scnName); // Force C locale setlocale(LC_NUMERIC,"C"); if (app.mainWin != NULL) return app.exec(); else return EXIT_FAILURE; } } <|endoftext|>
<commit_before>#pragma once #include <eosio/chain/webassembly/common.hpp> #include <eosio/chain/webassembly/runtime_interface.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/apply_context.hpp> #include <softfloat_types.h> //eos-vm includes #include <eosio/wasm_backend/backend.hpp> // eosio specific specializations namespace eosio { namespace wasm_backend { template <> struct reduce_type<chain::name> { typedef uint64_t type; }; template <typename S, typename T, typename Backend> constexpr auto get_value(Backend& backend, T&& val) -> std::enable_if_t<std::is_same_v<i64_const_t, T> && std::is_same_v<chain::name, std::decay_t<S>>, S> { return {(uint64_t)val.data.ui}; } // we can clean these up if we go with custom vms template <typename T> struct reduce_type<eosio::chain::array_ptr<T>> { typedef uint32_t type; }; template <typename S, typename T, typename Backend> constexpr auto get_value(Backend& backend, T&& val) -> std::enable_if_t<std::is_same_v<i32_const_t, T> && std::is_same_v< eosio::chain::array_ptr<typename S::type>, S> && !std::is_lvalue_reference_v<S> && !std::is_pointer_v<S>, S> { return eosio::chain::array_ptr<typename S::type>((typename S::type*)(backend.get_wasm_allocator()->template get_base_ptr<uint8_t>()+val.data.ui)); } template <> struct reduce_type<eosio::chain::null_terminated_ptr> { typedef uint32_t type; }; template <typename S, typename T, typename Backend> constexpr auto get_value(Backend& backend, T&& val) -> std::enable_if_t<std::is_same_v<i32_const_t, T> && std::is_same_v< eosio::chain::null_terminated_ptr, S> && !std::is_lvalue_reference_v<S> && !std::is_pointer_v<S>, S> { return eosio::chain::null_terminated_ptr((char*)(backend.get_wasm_allocator()->template get_base_ptr<uint8_t>()+val.data.ui)); } }} // ns eosio::wasm_backend namespace eosio { namespace chain { namespace webassembly { namespace eos_vm_runtime { using namespace fc; using namespace eosio::wasm_backend; using namespace eosio::chain::webassembly::common; class eos_vm_runtime : public eosio::chain::wasm_runtime_interface { public: eos_vm_runtime(); std::unique_ptr<wasm_instantiated_module_interface> instantiate_module(const char* code_bytes, size_t code_size, std::vector<uint8_t>) override; void immediately_exit_currently_running_module() override { _bkend->immediate_exit(); } private: backend<apply_context>* _bkend; // non owning pointer to allow for immediate exit }; } } } }// eosio::chain::webassembly::wabt_runtime #define __EOS_VM_INTRINSIC_NAME(LBL, SUF) LBL##SUF #define _EOS_VM_INTRINSIC_NAME(LBL, SUF) __INTRINSIC_NAME(LBL, SUF) #define _REGISTER_EOS_VM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\ eosio::wasm_backend::registered_function<CLS, &CLS::METHOD, eosio::wasm_backend::backend<CLS>> _EOS_VM_INTRINSIC_NAME(__eos_vm_intrinsic_fn, __COUNTER__){MOD, NAME}; <commit_msg>solved issue with linking<commit_after>#pragma once #include <eosio/chain/webassembly/common.hpp> #include <eosio/chain/webassembly/runtime_interface.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/apply_context.hpp> #include <softfloat_types.h> //eos-vm includes #include <eosio/wasm_backend/backend.hpp> // eosio specific specializations namespace eosio { namespace wasm_backend { template <> struct reduce_type<chain::name> { typedef uint64_t type; }; template <typename S, typename T, typename Backend> constexpr auto get_value(Backend& backend, T&& val) -> std::enable_if_t<std::is_same_v<i64_const_t, T> && std::is_same_v<chain::name, std::decay_t<S>>, S> { return {(uint64_t)val.data.ui}; } // we can clean these up if we go with custom vms template <typename T> struct reduce_type<eosio::chain::array_ptr<T>> { typedef uint32_t type; }; template <typename S, typename T, typename Backend> constexpr auto get_value(Backend& backend, T&& val) -> std::enable_if_t<std::is_same_v<i32_const_t, T> && std::is_same_v< eosio::chain::array_ptr<typename S::type>, S> && !std::is_lvalue_reference_v<S> && !std::is_pointer_v<S>, S> { return eosio::chain::array_ptr<typename S::type>((typename S::type*)(backend.get_wasm_allocator()->template get_base_ptr<uint8_t>()+val.data.ui)); } template <> struct reduce_type<eosio::chain::null_terminated_ptr> { typedef uint32_t type; }; template <typename S, typename T, typename Backend> constexpr auto get_value(Backend& backend, T&& val) -> std::enable_if_t<std::is_same_v<i32_const_t, T> && std::is_same_v< eosio::chain::null_terminated_ptr, S> && !std::is_lvalue_reference_v<S> && !std::is_pointer_v<S>, S> { return eosio::chain::null_terminated_ptr((char*)(backend.get_wasm_allocator()->template get_base_ptr<uint8_t>()+val.data.ui)); } }} // ns eosio::wasm_backend namespace eosio { namespace chain { namespace webassembly { namespace eos_vm_runtime { using namespace fc; using namespace eosio::wasm_backend; using namespace eosio::chain::webassembly::common; class eos_vm_runtime : public eosio::chain::wasm_runtime_interface { public: eos_vm_runtime(); std::unique_ptr<wasm_instantiated_module_interface> instantiate_module(const char* code_bytes, size_t code_size, std::vector<uint8_t>) override; void immediately_exit_currently_running_module() override { _bkend->immediate_exit(); } private: backend<apply_context>* _bkend; // non owning pointer to allow for immediate exit }; } } } }// eosio::chain::webassembly::wabt_runtime #define __EOS_VM_INTRINSIC_NAME(LBL, SUF) LBL##SUF #define _EOS_VM_INTRINSIC_NAME(LBL, SUF) __INTRINSIC_NAME(LBL, SUF) #define _REGISTER_EOS_VM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG) \ eosio::wasm_backend::registered_function<eosio::chain::apply_context, CLS, &CLS::METHOD, eosio::wasm_backend::backend<eosio::chain::apply_context>> _EOS_VM_INTRINSIC_NAME(__eos_vm_intrinsic_fn, __COUNTER__)(std::string(MOD), std::string(NAME)); <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * Copyright (c) 2012, hiDOF, 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. *********************************************************************/ #include <effort_controllers/joint_position_controller.h> #include <angles/angles.h> #include <pluginlib/class_list_macros.h> namespace effort_controllers { JointPositionController::JointPositionController() : loop_count_(0) {} JointPositionController::~JointPositionController() { sub_command_.shutdown(); } bool JointPositionController::init(hardware_interface::EffortJointInterface *robot, const std::string &joint_name, const control_toolbox::Pid &pid) { joint_ = robot->getHandle(joint_name); pid_controller_ = pid; // get urdf info about joint urdf::Model urdf; if (!urdf.initParam("robot_description")){ ROS_ERROR("Failed to parse urdf file"); return false; } joint_urdf_ = urdf.getJoint(joint_name); if (!joint_urdf_){ ROS_ERROR("Could not find joint '%s' in urdf", joint_name.c_str()); return false; } return true; } bool JointPositionController::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n) { std::string joint_name; if (!n.getParam("joint", joint_name)) { ROS_ERROR("No joint given (namespace: %s)", n.getNamespace().c_str()); return false; } control_toolbox::Pid pid; if (!pid.init(ros::NodeHandle(n, "pid"))) return false; controller_state_publisher_.reset( new realtime_tools::RealtimePublisher<controllers_msgs::JointControllerState>(n, "state", 1)); sub_command_ = n.subscribe<std_msgs::Float64>("command", 1, &JointPositionController::setCommandCB, this); return init(robot, joint_name, pid); } void JointPositionController::setGains(const double &p, const double &i, const double &d, const double &i_max, const double &i_min) { pid_controller_.setGains(p,i,d,i_max,i_min); } void JointPositionController::getGains(double &p, double &i, double &d, double &i_max, double &i_min) { pid_controller_.getGains(p,i,d,i_max,i_min); } std::string JointPositionController::getJointName() { return joint_.getName(); } // Set the joint position command void JointPositionController::setCommand(double cmd) { // the writeFromNonRT can be used in RT, if you have the guarantee that // * no non-rt thread is calling the same function (we're not subscribing to ros callbacks) // * there is only one single rt thread command_.writeFromNonRT(cmd); } void JointPositionController::starting(const ros::Time& time) { command_.initRT(joint_.getPosition()); pid_controller_.reset(); } void JointPositionController::update(const ros::Time& time, const ros::Duration& period) { double command = *(command_.readFromRT()); double error; if (joint_urdf_->type == urdf::Joint::REVOLUTE) { angles::shortest_angular_distance_with_limits(command, joint_.getPosition(), joint_urdf_->limits->lower, joint_urdf_->limits->upper, error); } else if (joint_urdf_->type == urdf::Joint::CONTINUOUS) { error = angles::shortest_angular_distance(command, joint_.getPosition()); } else //prismatic { error = command - joint_.getPosition(); } // Set the PID error and compute the PID command with nonuniform // time step size. This also allows the user to pass in a precomputed derivative error. double commanded_effort = pid_controller_.computeCommand(error, joint_.getVelocity(), period); // assuming desired velocity is 0 joint_.setCommand(commanded_effort); // publish state if (loop_count_ % 10 == 0) { if(controller_state_publisher_ && controller_state_publisher_->trylock()) { controller_state_publisher_->msg_.header.stamp = time; controller_state_publisher_->msg_.set_point = command; controller_state_publisher_->msg_.process_value = joint_.getPosition(); controller_state_publisher_->msg_.process_value_dot = joint_.getVelocity(); controller_state_publisher_->msg_.error = error; controller_state_publisher_->msg_.time_step = period.toSec(); controller_state_publisher_->msg_.command = commanded_effort; double dummy; getGains(controller_state_publisher_->msg_.p, controller_state_publisher_->msg_.i, controller_state_publisher_->msg_.d, controller_state_publisher_->msg_.i_clamp, dummy); controller_state_publisher_->unlockAndPublish(); } } loop_count_++; } void JointPositionController::setCommandCB(const std_msgs::Float64ConstPtr& msg) { setCommand(msg->data); } } // namespace PLUGINLIB_EXPORT_CLASS( effort_controllers::JointPositionController, controller_interface::ControllerBase) <commit_msg>Fixing position effort controller pid command args<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * Copyright (c) 2012, hiDOF, 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. *********************************************************************/ #include <effort_controllers/joint_position_controller.h> #include <angles/angles.h> #include <pluginlib/class_list_macros.h> namespace effort_controllers { JointPositionController::JointPositionController() : loop_count_(0) {} JointPositionController::~JointPositionController() { sub_command_.shutdown(); } bool JointPositionController::init(hardware_interface::EffortJointInterface *robot, const std::string &joint_name, const control_toolbox::Pid &pid) { joint_ = robot->getHandle(joint_name); pid_controller_ = pid; // get urdf info about joint urdf::Model urdf; if (!urdf.initParam("robot_description")){ ROS_ERROR("Failed to parse urdf file"); return false; } joint_urdf_ = urdf.getJoint(joint_name); if (!joint_urdf_){ ROS_ERROR("Could not find joint '%s' in urdf", joint_name.c_str()); return false; } return true; } bool JointPositionController::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n) { std::string joint_name; if (!n.getParam("joint", joint_name)) { ROS_ERROR("No joint given (namespace: %s)", n.getNamespace().c_str()); return false; } control_toolbox::Pid pid; if (!pid.init(ros::NodeHandle(n, "pid"))) return false; controller_state_publisher_.reset( new realtime_tools::RealtimePublisher<controllers_msgs::JointControllerState>(n, "state", 1)); sub_command_ = n.subscribe<std_msgs::Float64>("command", 1, &JointPositionController::setCommandCB, this); return init(robot, joint_name, pid); } void JointPositionController::setGains(const double &p, const double &i, const double &d, const double &i_max, const double &i_min) { pid_controller_.setGains(p,i,d,i_max,i_min); } void JointPositionController::getGains(double &p, double &i, double &d, double &i_max, double &i_min) { pid_controller_.getGains(p,i,d,i_max,i_min); } std::string JointPositionController::getJointName() { return joint_.getName(); } // Set the joint position command void JointPositionController::setCommand(double cmd) { // the writeFromNonRT can be used in RT, if you have the guarantee that // * no non-rt thread is calling the same function (we're not subscribing to ros callbacks) // * there is only one single rt thread command_.writeFromNonRT(cmd); } void JointPositionController::starting(const ros::Time& time) { command_.initRT(joint_.getPosition()); pid_controller_.reset(); } void JointPositionController::update(const ros::Time& time, const ros::Duration& period) { double command = *(command_.readFromRT()); double error, vel_error; // Compute position error if (joint_urdf_->type == urdf::Joint::REVOLUTE) { angles::shortest_angular_distance_with_limits(command, joint_.getPosition(), joint_urdf_->limits->lower, joint_urdf_->limits->upper, error); } else if (joint_urdf_->type == urdf::Joint::CONTINUOUS) { error = angles::shortest_angular_distance(command, joint_.getPosition()); } else //prismatic { error = command - joint_.getPosition(); } // Compute velocity error assuming desired velocity is 0 vel_error = 0.0 - joint_.getVelocity(); // Set the PID error and compute the PID command with nonuniform // time step size. This also allows the user to pass in a precomputed derivative error. double commanded_effort = pid_controller_.computeCommand(error, vel_error, period); joint_.setCommand(commanded_effort); // publish state if (loop_count_ % 10 == 0) { if(controller_state_publisher_ && controller_state_publisher_->trylock()) { controller_state_publisher_->msg_.header.stamp = time; controller_state_publisher_->msg_.set_point = command; controller_state_publisher_->msg_.process_value = joint_.getPosition(); controller_state_publisher_->msg_.process_value_dot = joint_.getVelocity(); controller_state_publisher_->msg_.error = error; controller_state_publisher_->msg_.time_step = period.toSec(); controller_state_publisher_->msg_.command = commanded_effort; double dummy; getGains(controller_state_publisher_->msg_.p, controller_state_publisher_->msg_.i, controller_state_publisher_->msg_.d, controller_state_publisher_->msg_.i_clamp, dummy); controller_state_publisher_->unlockAndPublish(); } } loop_count_++; } void JointPositionController::setCommandCB(const std_msgs::Float64ConstPtr& msg) { setCommand(msg->data); } } // namespace PLUGINLIB_EXPORT_CLASS( effort_controllers::JointPositionController, controller_interface::ControllerBase) <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: graphicnameaccess.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:49:39 $ * * 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 __FRAMEWORK_UICONFIGURATION_GRAPHICNAMEACCESS_HXX_ #include <uiconfiguration/graphicnameaccess.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #include <comphelper/sequence.hxx> using namespace ::com::sun::star; namespace framework { GraphicNameAccess::GraphicNameAccess() { } GraphicNameAccess::~GraphicNameAccess() { } void GraphicNameAccess::addElement( const rtl::OUString& rName, const uno::Reference< graphic::XGraphic >& rElement ) { m_aNameToElementMap.insert( NameGraphicHashMap::value_type( rName, rElement )); } sal_uInt32 GraphicNameAccess::size() const { return m_aNameToElementMap.size(); } // XNameAccess uno::Any SAL_CALL GraphicNameAccess::getByName( const ::rtl::OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.find( aName ); if ( pIter != m_aNameToElementMap.end() ) return uno::makeAny( pIter->second ); else throw container::NoSuchElementException(); } uno::Sequence< ::rtl::OUString > SAL_CALL GraphicNameAccess::getElementNames() throw(::com::sun::star::uno::RuntimeException) { if ( m_aSeq.getLength() == 0 ) { uno::Sequence< rtl::OUString > aSeq( m_aNameToElementMap.size() ); NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.begin(); sal_Int32 i( 0); while ( pIter != m_aNameToElementMap.end()) { aSeq[i++] = pIter->first; ++pIter; } m_aSeq = aSeq; } return m_aSeq; } sal_Bool SAL_CALL GraphicNameAccess::hasByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException) { NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.find( aName ); return ( pIter != m_aNameToElementMap.end() ); } // XElementAccess sal_Bool SAL_CALL GraphicNameAccess::hasElements() throw( uno::RuntimeException ) { return ( m_aNameToElementMap.size() > 0 ); } uno::Type SAL_CALL GraphicNameAccess::getElementType() throw( uno::RuntimeException ) { return ::getCppuType( (const uno::Reference< graphic::XGraphic > *)NULL ); } } // namespace framework <commit_msg>INTEGRATION: CWS pchfix02 (1.3.202); FILE MERGED 2006/09/01 17:29:23 kaib 1.3.202.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: graphicnameaccess.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-16 14:15:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_framework.hxx" #ifndef __FRAMEWORK_UICONFIGURATION_GRAPHICNAMEACCESS_HXX_ #include <uiconfiguration/graphicnameaccess.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #include <comphelper/sequence.hxx> using namespace ::com::sun::star; namespace framework { GraphicNameAccess::GraphicNameAccess() { } GraphicNameAccess::~GraphicNameAccess() { } void GraphicNameAccess::addElement( const rtl::OUString& rName, const uno::Reference< graphic::XGraphic >& rElement ) { m_aNameToElementMap.insert( NameGraphicHashMap::value_type( rName, rElement )); } sal_uInt32 GraphicNameAccess::size() const { return m_aNameToElementMap.size(); } // XNameAccess uno::Any SAL_CALL GraphicNameAccess::getByName( const ::rtl::OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.find( aName ); if ( pIter != m_aNameToElementMap.end() ) return uno::makeAny( pIter->second ); else throw container::NoSuchElementException(); } uno::Sequence< ::rtl::OUString > SAL_CALL GraphicNameAccess::getElementNames() throw(::com::sun::star::uno::RuntimeException) { if ( m_aSeq.getLength() == 0 ) { uno::Sequence< rtl::OUString > aSeq( m_aNameToElementMap.size() ); NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.begin(); sal_Int32 i( 0); while ( pIter != m_aNameToElementMap.end()) { aSeq[i++] = pIter->first; ++pIter; } m_aSeq = aSeq; } return m_aSeq; } sal_Bool SAL_CALL GraphicNameAccess::hasByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException) { NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.find( aName ); return ( pIter != m_aNameToElementMap.end() ); } // XElementAccess sal_Bool SAL_CALL GraphicNameAccess::hasElements() throw( uno::RuntimeException ) { return ( m_aNameToElementMap.size() > 0 ); } uno::Type SAL_CALL GraphicNameAccess::getElementType() throw( uno::RuntimeException ) { return ::getCppuType( (const uno::Reference< graphic::XGraphic > *)NULL ); } } // namespace framework <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlExport.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-07-13 15:22:19 $ * * 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 DBA_XMLEXPORT_HXX #define DBA_XMLEXPORT_HXX #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_ #include <com/sun/star/document/XFilter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_ #include <com/sun/star/document/XImporter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_ #include <com/sun/star/document/XExporter.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE5_HXX_ #include <cppuhelper/implbase5.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_ #include <com/sun/star/io/XActiveDataSource.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _UNOTOOLS_TEMPFILE_HXX #include <unotools/tempfile.hxx> #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif #ifndef _UNTOOLS_UCBSTREAMHELPER_HXX #include <unotools/ucbstreamhelper.hxx> #endif #ifndef _XMLOFF_XMLEXP_HXX #include <xmloff/xmlexp.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XColumnsSupplier.hpp> #endif #include <memory> namespace dbaxml { using namespace ::rtl; using namespace ::xmloff::token; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::document; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::text; using namespace ::com::sun::star::io; using namespace ::com::sun::star::xml::sax; // ------------- // - ODBExport - // ------------- #define PROGRESS_BAR_STEP 20 class ODBExport : public SvXMLExport { typedef ::std::pair< ::rtl::OUString ,::rtl::OUString> TStringPair; typedef struct { ::rtl::OUString sText; ::rtl::OUString sField; ::rtl::OUString sDecimal; ::rtl::OUString sThousand; } TDelimiter; typedef ::std::map< Reference<XPropertySet> ,::rtl::OUString > TPropertyStyleMap; ::std::auto_ptr< TStringPair > m_aAutoIncrement; ::std::auto_ptr< TDelimiter > m_aDelimiter; ::std::vector< Any> m_aDataSourceSettings; TPropertyStyleMap m_aAutoStyleNames; ::rtl::OUString m_sCharSet; Any m_aPreviewMode; UniReference < SvXMLExportPropertyMapper> m_xExportHelper; UniReference < SvXMLExportPropertyMapper> m_xColumnExportHelper; mutable UniReference < XMLPropertySetMapper > m_xTableStylesPropertySetMapper; mutable UniReference < XMLPropertySetMapper > m_xColumnStylesPropertySetMapper; Reference<XPropertySet> m_xDataSource; sal_Bool m_bAllreadyFilled; void exportDataSource(); void exportLogin(); void exportSequence(const Sequence< ::rtl::OUString>& _aValue ,::xmloff::token::XMLTokenEnum _eTokenFilter ,::xmloff::token::XMLTokenEnum _eTokenType); void exportDelimiter(); void exportAutoIncrement(); void exportCharSet(); void exportDataSourceSettings(); void exportForms(); void exportReports(); void exportQueries(sal_Bool _bExportContext); void exportTables(sal_Bool _bExportContext); void exportStyleName(XPropertySet* _xProp,SvXMLAttributeList& _rAtt); void exportCollection(const Reference< XNameAccess >& _xCollection ,enum ::xmloff::token::XMLTokenEnum _eComponents ,enum ::xmloff::token::XMLTokenEnum _eSubComponents ,sal_Bool _bExportContext ,const ::comphelper::mem_fun1_t<ODBExport,XPropertySet* >& _aMemFunc); void exportComponent(XPropertySet* _xProp); void exportQuery(XPropertySet* _xProp); void exportTable(XPropertySet* _xProp); void exportFilter(XPropertySet* _xProp ,const ::rtl::OUString& _sProp ,enum ::xmloff::token::XMLTokenEnum _eStatementType); void exportTableName(XPropertySet* _xProp,sal_Bool _bUpdate); void exportAutoStyle(XPropertySet* _xProp); void exportColumns(const Reference<XColumnsSupplier>& _xColSup); void collectComponentStyles(); ::rtl::OUString implConvertAny(const Any& _rValue); UniReference < XMLPropertySetMapper > GetTableStylesPropertySetMapper() const; private: ODBExport(); protected: virtual void _ExportStyles( BOOL bUsed ); virtual void _ExportAutoStyles(); virtual void _ExportContent(); virtual void _ExportMasterStyles(); virtual void _ExportFontDecls(); virtual sal_uInt32 exportDoc( enum ::xmloff::token::XMLTokenEnum eClass ); virtual SvXMLAutoStylePoolP* CreateAutoStylePool(); virtual void GetViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps); virtual void GetConfigurationSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps); virtual ~ODBExport(){}; public: ODBExport(const Reference< XMultiServiceFactory >& _rxMSF, sal_uInt16 nExportFlag = EXPORT_CONTENT | EXPORT_AUTOSTYLES | EXPORT_PRETTY|EXPORT_FONTDECLS); // XServiceInfo DECLARE_SERVICE_INFO_STATIC( ); UniReference < XMLPropertySetMapper > GetColumnStylesPropertySetMapper() const; // XExporter virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); inline Reference<XPropertySet> getDataSource() const { return m_xDataSource; } }; // ----------------------------------------------------------------------------- } // dbaxml // ----------------------------------------------------------------------------- #endif // DBA_XMLEXPORT_HXX <commit_msg>INTEGRATION: CWS dba30 (1.4.14); FILE MERGED 2006/07/19 12:29:24 fs 1.4.14.3: RESYNC: (1.5-1.6); FILE MERGED 2005/09/30 06:38:50 fs 1.4.14.2: RESYNC: (1.4-1.5); FILE MERGED 2005/04/06 07:18:40 fs 1.4.14.1: #i46768# also properly write and read empty properties from the DataSource's Info sequence<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlExport.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-08-15 10:48:21 $ * * 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 DBA_XMLEXPORT_HXX #define DBA_XMLEXPORT_HXX #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_ #include <com/sun/star/document/XFilter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_ #include <com/sun/star/document/XImporter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_ #include <com/sun/star/document/XExporter.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE5_HXX_ #include <cppuhelper/implbase5.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_ #include <com/sun/star/io/XActiveDataSource.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _UNOTOOLS_TEMPFILE_HXX #include <unotools/tempfile.hxx> #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif #ifndef _UNTOOLS_UCBSTREAMHELPER_HXX #include <unotools/ucbstreamhelper.hxx> #endif #ifndef _XMLOFF_XMLEXP_HXX #include <xmloff/xmlexp.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XColumnsSupplier.hpp> #endif #include <memory> namespace dbaxml { using namespace ::rtl; using namespace ::xmloff::token; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::document; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::text; using namespace ::com::sun::star::io; using namespace ::com::sun::star::xml::sax; // ------------- // - ODBExport - // ------------- #define PROGRESS_BAR_STEP 20 class ODBExport : public SvXMLExport { typedef ::std::pair< ::rtl::OUString ,::rtl::OUString> TStringPair; struct TDelimiter { ::rtl::OUString sText; ::rtl::OUString sField; ::rtl::OUString sDecimal; ::rtl::OUString sThousand; bool bUsed; TDelimiter() : bUsed( false ) { } }; typedef ::std::map< Reference<XPropertySet> ,::rtl::OUString > TPropertyStyleMap; ::std::auto_ptr< TStringPair > m_aAutoIncrement; ::std::auto_ptr< TDelimiter > m_aDelimiter; ::std::vector< Any> m_aDataSourceSettings; TPropertyStyleMap m_aAutoStyleNames; ::rtl::OUString m_sCharSet; UniReference < SvXMLExportPropertyMapper> m_xExportHelper; UniReference < SvXMLExportPropertyMapper> m_xColumnExportHelper; mutable UniReference < XMLPropertySetMapper > m_xTableStylesPropertySetMapper; mutable UniReference < XMLPropertySetMapper > m_xColumnStylesPropertySetMapper; Reference<XPropertySet> m_xDataSource; sal_Bool m_bAllreadyFilled; void exportDataSource(); void exportLogin(); void exportSequence(const Sequence< ::rtl::OUString>& _aValue ,::xmloff::token::XMLTokenEnum _eTokenFilter ,::xmloff::token::XMLTokenEnum _eTokenType); void exportDelimiter(); void exportAutoIncrement(); void exportCharSet(); void exportDataSourceSettings(); void exportForms(); void exportReports(); void exportQueries(sal_Bool _bExportContext); void exportTables(sal_Bool _bExportContext); void exportStyleName(XPropertySet* _xProp,SvXMLAttributeList& _rAtt); void exportCollection(const Reference< XNameAccess >& _xCollection ,enum ::xmloff::token::XMLTokenEnum _eComponents ,enum ::xmloff::token::XMLTokenEnum _eSubComponents ,sal_Bool _bExportContext ,const ::comphelper::mem_fun1_t<ODBExport,XPropertySet* >& _aMemFunc); void exportComponent(XPropertySet* _xProp); void exportQuery(XPropertySet* _xProp); void exportTable(XPropertySet* _xProp); void exportFilter(XPropertySet* _xProp ,const ::rtl::OUString& _sProp ,enum ::xmloff::token::XMLTokenEnum _eStatementType); void exportTableName(XPropertySet* _xProp,sal_Bool _bUpdate); void exportAutoStyle(XPropertySet* _xProp); void exportColumns(const Reference<XColumnsSupplier>& _xColSup); void collectComponentStyles(); ::rtl::OUString implConvertAny(const Any& _rValue); UniReference < XMLPropertySetMapper > GetTableStylesPropertySetMapper() const; private: ODBExport(); protected: virtual void _ExportStyles( BOOL bUsed ); virtual void _ExportAutoStyles(); virtual void _ExportContent(); virtual void _ExportMasterStyles(); virtual void _ExportFontDecls(); virtual sal_uInt32 exportDoc( enum ::xmloff::token::XMLTokenEnum eClass ); virtual SvXMLAutoStylePoolP* CreateAutoStylePool(); virtual void GetViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps); virtual void GetConfigurationSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps); virtual ~ODBExport(){}; public: ODBExport(const Reference< XMultiServiceFactory >& _rxMSF, sal_uInt16 nExportFlag = EXPORT_CONTENT | EXPORT_AUTOSTYLES | EXPORT_PRETTY|EXPORT_FONTDECLS); // XServiceInfo DECLARE_SERVICE_INFO_STATIC( ); UniReference < XMLPropertySetMapper > GetColumnStylesPropertySetMapper() const; // XExporter virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); inline Reference<XPropertySet> getDataSource() const { return m_xDataSource; } }; // ----------------------------------------------------------------------------- } // dbaxml // ----------------------------------------------------------------------------- #endif // DBA_XMLEXPORT_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: AppDetailView.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2005-01-21 17:07:10 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the License); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Ocke Janssen * * ************************************************************************/ #ifndef DBAUI_APPDETAILVIEW_HXX #define DBAUI_APPDETAILVIEW_HXX #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_ #include <com/sun/star/ucb/XContent.hpp> #endif #ifndef _SV_SPLIT_HXX #include <vcl/split.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX #include "IClipBoardTest.hxx" #endif #ifndef DBAUI_TITLE_WINDOW_HXX #include "AppTitleWindow.hxx" #endif #ifndef DBAUI_APPELEMENTTYPE_HXX #include "AppElementType.hxx" #endif #ifndef _SVTREEBOX_HXX #include <svtools/svtreebx.hxx> #endif #ifndef DBAUI_VERTSPLITVIEW_HXX #include "VertSplitView.hxx" #endif #include <vector> class SvLBoxEntry; namespace dbaui { class OApplicationController; class OAppBorderWindow; class OApplicationDetailView; class OAppDetailPageHelper; class OTasksWindow; class OCreationList : public SvTreeListBox { OTasksWindow* m_pTaskWindow; public: OCreationList(OTasksWindow* _pParent); // window overloads virtual void MouseMove( const MouseEvent& rMEvt ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void KeyInput( const KeyEvent& rKEvt ); }; typedef ::std::pair< ::rtl::OUString,USHORT> TResourcePair; typedef ::std::vector< ::std::pair<String, TResourcePair> > TResourceStruct; class OTasksWindow : public Window { ::std::vector< USHORT > m_aHelpTextIds; OCreationList m_aCreation; FixedText m_aDescription; FixedText m_aHelpText; FixedLine m_aFL; OApplicationDetailView* m_pDetailView; DECL_LINK( OnEntrySelectHdl, SvTreeListBox* ); public: OTasksWindow(Window* _pParent,OApplicationDetailView* _pDetailView); virtual ~OTasksWindow(); // window overloads virtual void Resize(); OApplicationDetailView* getDetailView() const { return m_pDetailView; } /** fills the Creation listbox with the necessary strings and images @param _rList The strings and the id of the images and help texts to add. */ void fillCreationNew( const TResourceStruct& _rList ); void Clear(); void setHelpText(USHORT _nId); }; //================================================================== class OApplicationDetailView : public OSplitterView , public IClipboardTest { Splitter m_aHorzSplitter; OTitleWindow m_aTasks; OTitleWindow m_aContainer; OAppBorderWindow* m_pBorderWin; // my parent OAppDetailPageHelper* m_pControlHelper; void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground ); protected: virtual void DataChanged(const DataChangedEvent& rDCEvt); public: OApplicationDetailView(OAppBorderWindow* _pParent); virtual ~OApplicationDetailView(); // window overloads // virtual void Resize(); virtual void GetFocus(); /** creates the tables page @param _xConnection The connection to get the table names */ void createTablesPage(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection); /** creates the page for the specific type. @param _eType The type which should be created. E_TABLE isn't allowed. @param _xContainer The container of the elements to be inserted. */ void createPage(ElementType _eType,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xContainer); inline OAppBorderWindow* getBorderWin() const { return m_pBorderWin;} sal_Bool isCutAllowed() ; sal_Bool isCopyAllowed() ; sal_Bool isPasteAllowed(); virtual sal_Bool hasChildPathFocus() { return HasChildPathFocus(); } void copy(); void cut(); void paste(); /** return the qualified name. @param _pEntry The entry of a table, or query, form, report to get the qualified name. If the entry is <NULL/>, the first selected is chosen. @param _xMetaData The meta data are used to create the table name, otherwise this may also be <NULL/> @return the qualified name */ ::rtl::OUString getQualifiedName(SvLBoxEntry* _pEntry ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData) const; /** returns if an entry is a leaf @param _pEntry The entry to check @return <TRUE/> if the entry is a leaf, otherwise <FALSE/> */ sal_Bool isLeaf(SvLBoxEntry* _pEntry) const; /** returns if one of the selected entries is a leaf @return <TRUE/> if the entry is a leaf, otherwise <FALSE/> */ sal_Bool isALeafSelected() const; /** select all entries in the detail page */ void selectAll(); /// returns <TRUE/> if it sorts ascending sal_Bool isSortUp() const; /// sort the entries in the detail page down void sortDown(); /// sort the entries in the detail page up void sortUp(); /// returns <TRUE/> when a detail page was filled sal_Bool isFilled() const; /// return the element of currently select entry ElementType getElementType() const; /** clears the detail pages. @param _bTaskAlso If <TRUE/> the task window will also be cleared. */ void clearPages(sal_Bool _bTaskAlso = sal_True); /// returns the count of entries sal_Int32 getElementCount(); /// returns the count of selected entries sal_Int32 getSelectionCount(); /** returns the element names which are selected @param _rNames The list will be filled. @param _xMetaData Will be used when the table list should be filled. */ void getSelectionElementNames(::std::vector< ::rtl::OUString>& _rNames ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData = NULL) const; /** adds a new object to the detail page. @param _eType The type where the entry shold be appended. @param _rName The name of the object to be inserted @param _rObject The object to add. @param _rxConn If we insert a table, the connection must be set. */ SvLBoxEntry* elementAdded(ElementType eType ,const ::rtl::OUString& _rName ,const ::com::sun::star::uno::Any& _rObject ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn = NULL); /** replaces a objects name with a new one @param _eType The type where the entry shold be appended. @param _rOldName The old name of the object to be replaced @param _rNewName The new name of the object to be replaced @param _rxConn If we insert a table, the connection must be set. */ void elementReplaced(ElementType eType ,const ::rtl::OUString& _rOldName ,const ::rtl::OUString& _rNewName ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn = NULL); /** removes an element from the detail page. @param _eType The type where the entry shold be appended. @param _rName The name of the element to be removed. @param _rxConn If we remove a table, the connection must be set. */ void elementRemoved(ElementType _eType ,const ::rtl::OUString& _rName ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn); /// returns the preview mode PreviewMode getPreviewMode(); /// <TRUE/> if the preview is enabled sal_Bool isPreviewEnabled(); /// switches the current preview void switchPreview(); /** switches to the given preview mode @param _eMode the mode to set for the preview */ void switchPreview(PreviewMode _eMode); /** shows the Preview of the content when it is enabled. @param _xContent The content which must support the "preview" command. */ void showPreview(const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >& _xContent); /** shows the Preview of a table or query @param _sDataSourceName the name of the data source @param _xConnection the connection which will be shared @param _sName the name of table or query @param _bTable <TRUE/> if it is a table, otherwise <FALSE/> @return void */ void showPreview( const ::rtl::OUString& _sDataSourceName, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection, const ::rtl::OUString& _sName, sal_Bool _bTable); SvLBoxEntry* getEntry( const Point& _aPoint ) const; /** a command entry was selected @param _sCommand The command to be executed. */ void onCreationClick( const ::rtl::OUString& _sCommand); /** disable the controls @param _bDisable if <TRUE/> then the controls will be disabled otherwise they will be enabled. */ void disableControls(sal_Bool _bDisable); }; } #endif // DBAUI_APPDETAILVIEW_HXX <commit_msg>INTEGRATION: CWS dba24 (1.6.4); FILE MERGED 2005/02/11 12:32:21 oj 1.6.4.2: #i42473# clear description as ell when changing to another categorie 2005/02/01 15:48:52 fs 1.6.4.1: #i41822# some more appealing layout for the task pane<commit_after>/************************************************************************* * * $RCSfile: AppDetailView.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: vg $ $Date: 2005-03-10 16:44:54 $ * * 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): Ocke Janssen * * ************************************************************************/ #ifndef DBAUI_APPDETAILVIEW_HXX #define DBAUI_APPDETAILVIEW_HXX #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_ #include <com/sun/star/ucb/XContent.hpp> #endif #ifndef _SV_SPLIT_HXX #include <vcl/split.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX #include "IClipBoardTest.hxx" #endif #ifndef DBAUI_TITLE_WINDOW_HXX #include "AppTitleWindow.hxx" #endif #ifndef DBAUI_APPELEMENTTYPE_HXX #include "AppElementType.hxx" #endif #ifndef _SVTREEBOX_HXX #include <svtools/svtreebx.hxx> #endif #ifndef DBAUI_VERTSPLITVIEW_HXX #include "VertSplitView.hxx" #endif #include <vector> class SvLBoxEntry; namespace dbaui { class OApplicationController; class OAppBorderWindow; class OApplicationDetailView; class OAppDetailPageHelper; class OTasksWindow; class OCreationList : public SvTreeListBox { OTasksWindow* m_pTaskWindow; // members related to drawing the currently hovered/selected entry SvLBoxEntry* m_pMouseDownEntry; SvLBoxEntry* m_pLastActiveEntry; Color m_aOriginalBackgroundColor; Font m_aOriginalFont; public: OCreationList(OTasksWindow* _pParent); // window overloads virtual void MouseMove( const MouseEvent& rMEvt ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void KeyInput( const KeyEvent& rKEvt ); virtual void Paint( const Rectangle& rRect ); virtual void StartDrag( sal_Int8 _nAction, const Point& _rPosPixel ); virtual void GetFocus(); virtual void LoseFocus(); void updateHelpText(); protected: virtual void PreparePaint( SvLBoxEntry* _pEntry ); virtual Rectangle GetFocusRect( SvLBoxEntry* _pEntry, long _nLine ); private: void onSelected( SvLBoxEntry* _pEntry ) const; /** sets a new current entry, and invalidates the old and the new one, if necessary @return <TRUE/> if and only if the "current entry" changed */ bool setCurrentEntryInvalidate( SvLBoxEntry* _pEntry ); }; typedef ::std::pair< ::rtl::OUString,USHORT> TResourcePair; typedef ::std::vector< ::std::pair<String, TResourcePair> > TResourceStruct; class OTasksWindow : public Window { ::std::vector< USHORT > m_aHelpTextIds; OCreationList m_aCreation; FixedText m_aDescription; FixedText m_aHelpText; FixedLine m_aFL; OApplicationDetailView* m_pDetailView; DECL_LINK( OnEntrySelectHdl, SvTreeListBox* ); public: OTasksWindow(Window* _pParent,OApplicationDetailView* _pDetailView); virtual ~OTasksWindow(); // window overloads virtual void Resize(); OApplicationDetailView* getDetailView() const { return m_pDetailView; } /** fills the Creation listbox with the necessary strings and images @param _rList The strings and the id of the images and help texts to add. */ void fillCreationNew( const TResourceStruct& _rList ); void Clear(); void setHelpText(USHORT _nId); }; //================================================================== class OApplicationDetailView : public OSplitterView , public IClipboardTest { Splitter m_aHorzSplitter; OTitleWindow m_aTasks; OTitleWindow m_aContainer; OAppBorderWindow* m_pBorderWin; // my parent OAppDetailPageHelper* m_pControlHelper; void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground ); protected: virtual void DataChanged(const DataChangedEvent& rDCEvt); public: OApplicationDetailView(OAppBorderWindow* _pParent); virtual ~OApplicationDetailView(); // window overloads // virtual void Resize(); virtual void GetFocus(); /** creates the tables page @param _xConnection The connection to get the table names */ void createTablesPage(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection); /** creates the page for the specific type. @param _eType The type which should be created. E_TABLE isn't allowed. @param _xContainer The container of the elements to be inserted. */ void createPage(ElementType _eType,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xContainer); inline OAppBorderWindow* getBorderWin() const { return m_pBorderWin;} sal_Bool isCutAllowed() ; sal_Bool isCopyAllowed() ; sal_Bool isPasteAllowed(); virtual sal_Bool hasChildPathFocus() { return HasChildPathFocus(); } void copy(); void cut(); void paste(); /** return the qualified name. @param _pEntry The entry of a table, or query, form, report to get the qualified name. If the entry is <NULL/>, the first selected is chosen. @param _xMetaData The meta data are used to create the table name, otherwise this may also be <NULL/> @return the qualified name */ ::rtl::OUString getQualifiedName(SvLBoxEntry* _pEntry ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData) const; /** returns if an entry is a leaf @param _pEntry The entry to check @return <TRUE/> if the entry is a leaf, otherwise <FALSE/> */ sal_Bool isLeaf(SvLBoxEntry* _pEntry) const; /** returns if one of the selected entries is a leaf @return <TRUE/> if the entry is a leaf, otherwise <FALSE/> */ sal_Bool isALeafSelected() const; /** select all entries in the detail page */ void selectAll(); /// returns <TRUE/> if it sorts ascending sal_Bool isSortUp() const; /// sort the entries in the detail page down void sortDown(); /// sort the entries in the detail page up void sortUp(); /// returns <TRUE/> when a detail page was filled sal_Bool isFilled() const; /// return the element of currently select entry ElementType getElementType() const; /** clears the detail pages. @param _bTaskAlso If <TRUE/> the task window will also be cleared. */ void clearPages(sal_Bool _bTaskAlso = sal_True); /// returns the count of entries sal_Int32 getElementCount(); /// returns the count of selected entries sal_Int32 getSelectionCount(); /** returns the element names which are selected @param _rNames The list will be filled. @param _xMetaData Will be used when the table list should be filled. */ void getSelectionElementNames(::std::vector< ::rtl::OUString>& _rNames ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData = NULL) const; /** adds a new object to the detail page. @param _eType The type where the entry shold be appended. @param _rName The name of the object to be inserted @param _rObject The object to add. @param _rxConn If we insert a table, the connection must be set. */ SvLBoxEntry* elementAdded(ElementType eType ,const ::rtl::OUString& _rName ,const ::com::sun::star::uno::Any& _rObject ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn = NULL); /** replaces a objects name with a new one @param _eType The type where the entry shold be appended. @param _rOldName The old name of the object to be replaced @param _rNewName The new name of the object to be replaced @param _rxConn If we insert a table, the connection must be set. */ void elementReplaced(ElementType eType ,const ::rtl::OUString& _rOldName ,const ::rtl::OUString& _rNewName ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn = NULL); /** removes an element from the detail page. @param _eType The type where the entry shold be appended. @param _rName The name of the element to be removed. @param _rxConn If we remove a table, the connection must be set. */ void elementRemoved(ElementType _eType ,const ::rtl::OUString& _rName ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn); /// returns the preview mode PreviewMode getPreviewMode(); /// <TRUE/> if the preview is enabled sal_Bool isPreviewEnabled(); /// switches the current preview void switchPreview(); /** switches to the given preview mode @param _eMode the mode to set for the preview */ void switchPreview(PreviewMode _eMode); /** shows the Preview of the content when it is enabled. @param _xContent The content which must support the "preview" command. */ void showPreview(const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >& _xContent); /** shows the Preview of a table or query @param _sDataSourceName the name of the data source @param _xConnection the connection which will be shared @param _sName the name of table or query @param _bTable <TRUE/> if it is a table, otherwise <FALSE/> @return void */ void showPreview( const ::rtl::OUString& _sDataSourceName, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection, const ::rtl::OUString& _sName, sal_Bool _bTable); SvLBoxEntry* getEntry( const Point& _aPoint ) const; /** a command entry was selected @param _sCommand The command to be executed. */ void onCreationClick( const ::rtl::OUString& _sCommand); /** disable the controls @param _bDisable if <TRUE/> then the controls will be disabled otherwise they will be enabled. */ void disableControls(sal_Bool _bDisable); }; } #endif // DBAUI_APPDETAILVIEW_HXX <|endoftext|>
<commit_before>#ifndef __ACTION_INTERSECT_HLS_H__ #define __ACTION_INTERSECT_HLS_H__ /* * Copyright 2016, 2017 International Business Machines * * 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 "hls_snap.H" #include "action_intersect.h" #define USE_HASH ////////////////////////////////////// // General ////////////////////////////////////// #define MAX_NB_OF_BYTES_READ (4 * 1024) // Size of each element // 6 = log2(64) // Just equal to BPERDW // Consider ap_uint<> width should be less than 1024 // So ELE_BYTES should <= 128. #define ELE_BYTES 64 typedef ap_uint<ELE_BYTES *8> ele_t; // Memcopy directions #define HOST2DDR 0 #define DDR2HOST 1 #define DDR2DDR 2 ////////////////////////////////////// //DDR Address map ////////////////////////////////////// // 0: Table1 (Configured from SW) //1GB: Table2 (Configured from SW) //2GB: Result (Configured from SW) //4GB: Hash table start address or sort place ////////////////////////////////////// // Sort Method ////////////////////////////////////// #ifdef USE_SORT #define NUM_SORT 64 #define NUM_ENGINES 8 #define ONE_BUF_SIZE NUM_SORT * ELE_BYTES #define DDR_SORT_SPACE (snapu64_t)4*1024*1024*1024 #else ////////////////////////////////////// // Hash Method ////////////////////////////////////// #ifdef USE_HASH #define HW_HT_ENTRY_NUM_EXP 22 #define HW_HT_ENTRY_NUM (1<<HW_HT_ENTRY_NUM_EXP) // A 512bit-width BRAM stays in local FPGA for "used" bits #define WIDTH_EXP 9 #define BRAM_WIDTH (1<<WIDTH_EXP) ap_uint<BRAM_WIDTH> hash_used[HW_HT_ENTRY_NUM/BRAM_WIDTH]; #define HASH_TABLE_ADDR (snapu64_t)4*1024*1024*1024 #endif #endif typedef struct { struct snap_addr src_tables_host0; /* input tables */ struct snap_addr src_tables_host1; /* input tables */ struct snap_addr src_tables_ddr0; /* input tables */ struct snap_addr src_tables_ddr1; /* input tables */ struct snap_addr result_table; /* output table */ uint32_t step; uint32_t method; } DATA; typedef struct { CONTROL Control; DATA Data; uint8_t padding[SNAP_HLS_JOBSIZE - sizeof(intersect_job_t)]; } action_reg; #endif /* __ACTION_INTERSECT_HLS_H__ */ <commit_msg>HLS adjust for hash method<commit_after>#ifndef __ACTION_INTERSECT_HLS_H__ #define __ACTION_INTERSECT_HLS_H__ /* * Copyright 2016, 2017 International Business Machines * * 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 "hls_snap.H" #include "action_intersect.h" #define USE_HASH ////////////////////////////////////// // General ////////////////////////////////////// #define MAX_NB_OF_BYTES_READ (4 * 1024) // Size of each element // 6 = log2(64) // Just equal to BPERDW // Consider ap_uint<> width should be less than 1024 // So ELE_BYTES should <= 128. #define ELE_BYTES 64 typedef ap_uint<ELE_BYTES *8> ele_t; // Memcopy directions #define HOST2DDR 0 #define DDR2HOST 1 #define DDR2DDR 2 ////////////////////////////////////// //DDR Address map ////////////////////////////////////// // 0: Table1 (Configured from SW) //1GB: Table2 (Configured from SW) //2GB: Result (Configured from SW) //4GB: Hash table start address or sort place ////////////////////////////////////// // Sort Method ////////////////////////////////////// #ifdef USE_SORT #define NUM_SORT 64 #define NUM_ENGINES 8 #define ONE_BUF_SIZE NUM_SORT * ELE_BYTES #define DDR_SORT_SPACE (snapu64_t)4*1024*1024*1024 #else ////////////////////////////////////// // Hash Method ////////////////////////////////////// #ifdef USE_HASH #define HW_HT_ENTRY_NUM_EXP 22 #define HW_HT_ENTRY_NUM (1<<HW_HT_ENTRY_NUM_EXP) // A 256bit-width BRAM stays in local FPGA for "used" bits #define WIDTH_EXP 8 #define BRAM_WIDTH (1<<WIDTH_EXP) ap_uint<BRAM_WIDTH> hash_used[HW_HT_ENTRY_NUM/BRAM_WIDTH]; #define HASH_TABLE_ADDR (snapu64_t)4*1024*1024*1024 #endif #endif typedef struct { struct snap_addr src_tables_host0; /* input tables */ struct snap_addr src_tables_host1; /* input tables */ struct snap_addr src_tables_ddr0; /* input tables */ struct snap_addr src_tables_ddr1; /* input tables */ struct snap_addr result_table; /* output table */ uint32_t step; uint32_t method; } DATA; typedef struct { CONTROL Control; DATA Data; uint8_t padding[SNAP_HLS_JOBSIZE - sizeof(intersect_job_t)]; } action_reg; #endif /* __ACTION_INTERSECT_HLS_H__ */ <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "hazelcast/client/config/ClientNetworkConfig.h" namespace hazelcast { namespace client { namespace config { ClientNetworkConfig::ClientNetworkConfig() : connectionTimeout(5000) { } #ifdef HZ_BUILD_WITH_SSL SSLConfig &ClientNetworkConfig::getSSLConfig() { return sslConfig; } ClientNetworkConfig &ClientNetworkConfig::setSSLConfig(const config::SSLConfig &sslConfig) { this->sslConfig = sslConfig; return *this; } int64_t ClientNetworkConfig::getConnectionTimeout() const { return connectionTimeout; } ClientNetworkConfig &ClientNetworkConfig::setConnectionTimeout(int64_t connectionTimeoutInMillis) { this->connectionTimeout = connectionTimeoutInMillis; return *this; } #endif // HZ_BUILD_WITH_SSL } } } <commit_msg>Corrected the network config cpp file so that the getConnectionTimeout and setConnectionTimeout are defined even when no ssl. (#241)<commit_after>/* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "hazelcast/client/config/ClientNetworkConfig.h" namespace hazelcast { namespace client { namespace config { ClientNetworkConfig::ClientNetworkConfig() : connectionTimeout(5000) { } #ifdef HZ_BUILD_WITH_SSL SSLConfig &ClientNetworkConfig::getSSLConfig() { return sslConfig; } ClientNetworkConfig &ClientNetworkConfig::setSSLConfig(const config::SSLConfig &sslConfig) { this->sslConfig = sslConfig; return *this; } #endif // HZ_BUILD_WITH_SSL int64_t ClientNetworkConfig::getConnectionTimeout() const { return connectionTimeout; } ClientNetworkConfig &ClientNetworkConfig::setConnectionTimeout(int64_t connectionTimeoutInMillis) { this->connectionTimeout = connectionTimeoutInMillis; return *this; } } } } <|endoftext|>
<commit_before>//@author A0114171W #include "stdafx.h" #include <CppUnitTest.h> #include <cstdio> #include <fstream> #include "../mocks.h" #include "internal/operations/erase_operation.h" #include "internal/operations/post_operation.h" #include "internal/operations/put_operation.h" #include "internal/internal_datastore.h" #include "internal/constants.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { using DataStore = You::DataStore::Internal::DataStore; /// Unit Test Class for \ref Internal::DataStore class TEST_CLASS(DataStoreTest) { public: TEST_METHOD_INITIALIZE(clearDataStoreState) { DataStore::get().document.reset(); std::remove("data.xml"); } TEST_METHOD_CLEANUP(cleanUpDataStoreState) { DataStore::get().document.reset(); std::remove("data.xml"); } /// Checks if DataStore::get() method adds a new transaction into /// the active transaction stack TEST_METHOD(beginTransactionAddsToTransactionStack) { DataStore& sut = DataStore::get(); Assert::IsTrue(sut.transactionStack.empty()); Transaction t(sut.begin()); Assert::AreEqual(1U, sut.transactionStack.size()); } /// Checks if post, put, and erase methods add \ref Internal::Operation /// objects into the active transaction's operationsQueue TEST_METHOD(pushedOperationsAddedToTransactionOperationsQueue) { DataStore& sut = DataStore::get(); Transaction t(sut.begin()); sut.post(Internal::TASKS_NODE, L"10", task1); Assert::AreEqual(1U, t->operationsQueue.size()); sut.put(Internal::TASKS_NODE, L"10", task2); Assert::AreEqual(2U, t->operationsQueue.size()); sut.erase(Internal::TASKS_NODE, L"10"); Assert::AreEqual(3U, t->operationsQueue.size()); } /// Checks if the document is only changed when a transaction is committed TEST_METHOD(commitChangesXmlDocumentTree) { DataStore& sut = DataStore::get(); Transaction t(sut.begin()); sut.post(Internal::TASKS_NODE, L"10", task1); // Note: To check if document is not changed after commit requires // 2 first_child()s because the first one retrieves the tasks node // while the second one is to check if the children of the tasks node // is empty // document must not change without commit Assert::IsTrue(sut.document.first_child().first_child().empty()); t.commit(); // document changes after commit Assert::IsFalse(sut.document.first_child().first_child().empty()); Transaction t2(sut.begin()); sut.erase(Internal::TASKS_NODE, L"10"); // document must not change without commit Assert::IsFalse(sut.document.first_child().first_child().empty()); t2.commit(); // document changes after commit Assert::IsTrue(sut.document.first_child().first_child().empty()); } /// Checks if rollback cleans up the transaction stack too TEST_METHOD(rollbackDeleteTransactionFromStack) { DataStore& sut = DataStore::get(); Transaction t(sut.begin()); Assert::AreEqual(1U, sut.transactionStack.size()); t.rollback(); Assert::AreEqual(0U, sut.transactionStack.size()); } /// Unit test to check if getAll behaves correctly when getting from the /// XML document tree TEST_METHOD(getAllFromTree) { DataStore& sut = DataStore::get(); // Create mock sut.document.append_child(L"tasks").append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); std::vector<KeyValuePairs> result = sut.getAll(L"tasks"); Assert::AreEqual(1U, result.size()); } /// Unit test to check if getAll behaves correctly when getting from /// file (scenario: during load) TEST_METHOD(getAllFromFile) { DataStore& sut = DataStore::get(); // Create mock sut.document.append_child(L"tasks").append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); sut.document.save_file(sut.FILE_PATH.c_str()); sut.document.reset(); std::vector<KeyValuePairs> result = sut.getAll(L"tasks"); Assert::AreEqual(1U, result.size()); } /// Checks if saving and loading works TEST_METHOD(saveAndLoadTheSameThing) { DataStore& sut = DataStore::get(); sut.document.append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); bool result = sut.saveData(); Assert::IsTrue(result); sut.document.reset(); sut.loadData(); std::wstring value = sut.document.child(L"task").child_value(); Assert::AreEqual(std::wstring(L"what"), value); } /// Unit test for \ref Internal::Transaction 's push operation TEST_METHOD(pushOperationToTransactionWithoutDataStore) { Internal::Transaction sut; std::unique_ptr<Internal::Operation> post = std::make_unique<Internal::PostOperation>(Internal::TASKS_NODE, L"0", task1); sut.push(std::move(post)); Assert::AreEqual(1U, sut.operationsQueue.size()); std::unique_ptr<Internal::Operation> put = std::make_unique<Internal::PutOperation>(Internal::TASKS_NODE, L"0", task1); sut.push(std::move(put)); Assert::AreEqual(2U, sut.operationsQueue.size()); std::unique_ptr<Internal::Operation> erase = std::make_unique<Internal::EraseOperation>(Internal::TASKS_NODE, L"0"); sut.push(std::move(erase)); Assert::AreEqual(3U, sut.operationsQueue.size()); sut.operationsQueue.clear(); } /// Unit test for \ref Internal::Transaction 's mergeOperationsQueue method TEST_METHOD(mergeOperationsQueueIsAppend) { boost::ptr_deque<Internal::Operation> q1; boost::ptr_deque<Internal::Operation> q2; std::unique_ptr<Internal::Operation> post = std::make_unique<Internal::PostOperation>(Internal::TASKS_NODE, L"0", task1); std::unique_ptr<Internal::Operation> erase = std::make_unique<Internal::EraseOperation>(Internal::TASKS_NODE, L"0"); q1.push_back(post.release()); q2.push_back(erase.release()); Internal::Transaction sut; sut.mergeOperationsQueue(q1); Assert::AreEqual(1U, sut.mergedOperationsQueue.size()); sut.mergeOperationsQueue(q2); Assert::AreEqual(2U, sut.mergedOperationsQueue.size()); pugi::xml_document mockDocument; // Check if the order of operation is correct bool result = sut.mergedOperationsQueue.front().run(mockDocument); Assert::IsTrue(result); result = sut.mergedOperationsQueue.back().run(mockDocument); Assert::IsTrue(result); } TEST_METHOD(wipeData) { DataStore::get().wipeData(); } }; } // namespace UnitTests } // namespace DataStore } // namespace You <commit_msg>Add tests for parse error<commit_after>//@author A0114171W #include "stdafx.h" #include <CppUnitTest.h> #include <cstdio> #include <fstream> #include "../mocks.h" #include "internal/operations/erase_operation.h" #include "internal/operations/post_operation.h" #include "internal/operations/put_operation.h" #include "internal/internal_datastore.h" #include "internal/constants.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { using DataStore = You::DataStore::Internal::DataStore; /// Unit Test Class for \ref Internal::DataStore class TEST_CLASS(DataStoreTest) { public: void createDummyDataXml() { std::ofstream ofs("data.xml"); ofs << "Lel I'm not even an xml"; } TEST_METHOD_INITIALIZE(clearDataStoreState) { DataStore::get().document.reset(); std::remove("data.xml"); } TEST_METHOD_CLEANUP(cleanUpDataStoreState) { DataStore::get().document.reset(); std::remove("data.xml"); } /// Checks if DataStore::get() method adds a new transaction into /// the active transaction stack TEST_METHOD(beginTransactionAddsToTransactionStack) { DataStore& sut = DataStore::get(); Assert::IsTrue(sut.transactionStack.empty()); Transaction t(sut.begin()); Assert::AreEqual(1U, sut.transactionStack.size()); } /// Checks if post, put, and erase methods add \ref Internal::Operation /// objects into the active transaction's operationsQueue TEST_METHOD(pushedOperationsAddedToTransactionOperationsQueue) { DataStore& sut = DataStore::get(); Transaction t(sut.begin()); sut.post(Internal::TASKS_NODE, L"10", task1); Assert::AreEqual(1U, t->operationsQueue.size()); sut.put(Internal::TASKS_NODE, L"10", task2); Assert::AreEqual(2U, t->operationsQueue.size()); sut.erase(Internal::TASKS_NODE, L"10"); Assert::AreEqual(3U, t->operationsQueue.size()); } /// Checks if the document is only changed when a transaction is committed TEST_METHOD(commitChangesXmlDocumentTree) { DataStore& sut = DataStore::get(); Transaction t(sut.begin()); sut.post(Internal::TASKS_NODE, L"10", task1); // Note: To check if document is not changed after commit requires // 2 first_child()s because the first one retrieves the tasks node // while the second one is to check if the children of the tasks node // is empty // document must not change without commit Assert::IsTrue(sut.document.first_child().first_child().empty()); t.commit(); // document changes after commit Assert::IsFalse(sut.document.first_child().first_child().empty()); Transaction t2(sut.begin()); sut.erase(Internal::TASKS_NODE, L"10"); // document must not change without commit Assert::IsFalse(sut.document.first_child().first_child().empty()); t2.commit(); // document changes after commit Assert::IsTrue(sut.document.first_child().first_child().empty()); } /// Checks if rollback cleans up the transaction stack too TEST_METHOD(rollbackDeleteTransactionFromStack) { DataStore& sut = DataStore::get(); Transaction t(sut.begin()); Assert::AreEqual(1U, sut.transactionStack.size()); t.rollback(); Assert::AreEqual(0U, sut.transactionStack.size()); } /// Unit test to check if getAll behaves correctly when getting from the /// XML document tree TEST_METHOD(getAllFromTree) { DataStore& sut = DataStore::get(); // Create mock sut.document.append_child(L"tasks").append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); std::vector<KeyValuePairs> result = sut.getAll(L"tasks"); Assert::AreEqual(1U, result.size()); } /// Unit test to check if getAll behaves correctly when getting from /// file (scenario: during load) TEST_METHOD(getAllFromFile) { DataStore& sut = DataStore::get(); // Create mock sut.document.append_child(L"tasks").append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); sut.document.save_file(sut.FILE_PATH.c_str()); sut.document.reset(); std::vector<KeyValuePairs> result = sut.getAll(L"tasks"); Assert::AreEqual(1U, result.size()); } /// Checks if saving and loading works TEST_METHOD(saveAndLoadTheSameThing) { DataStore& sut = DataStore::get(); sut.document.append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); bool result = sut.saveData(); Assert::IsTrue(result); sut.document.reset(); sut.loadData(); std::wstring value = sut.document.child(L"task").child_value(); Assert::AreEqual(std::wstring(L"what"), value); } /// Unit test for \ref Internal::Transaction 's push operation TEST_METHOD(pushOperationToTransactionWithoutDataStore) { Internal::Transaction sut; std::unique_ptr<Internal::Operation> post = std::make_unique<Internal::PostOperation>(Internal::TASKS_NODE, L"0", task1); sut.push(std::move(post)); Assert::AreEqual(1U, sut.operationsQueue.size()); std::unique_ptr<Internal::Operation> put = std::make_unique<Internal::PutOperation>(Internal::TASKS_NODE, L"0", task1); sut.push(std::move(put)); Assert::AreEqual(2U, sut.operationsQueue.size()); std::unique_ptr<Internal::Operation> erase = std::make_unique<Internal::EraseOperation>(Internal::TASKS_NODE, L"0"); sut.push(std::move(erase)); Assert::AreEqual(3U, sut.operationsQueue.size()); sut.operationsQueue.clear(); } /// Unit test for \ref Internal::Transaction 's mergeOperationsQueue method TEST_METHOD(mergeOperationsQueueIsAppend) { boost::ptr_deque<Internal::Operation> q1; boost::ptr_deque<Internal::Operation> q2; std::unique_ptr<Internal::Operation> post = std::make_unique<Internal::PostOperation>(Internal::TASKS_NODE, L"0", task1); std::unique_ptr<Internal::Operation> erase = std::make_unique<Internal::EraseOperation>(Internal::TASKS_NODE, L"0"); q1.push_back(post.release()); q2.push_back(erase.release()); Internal::Transaction sut; sut.mergeOperationsQueue(q1); Assert::AreEqual(1U, sut.mergedOperationsQueue.size()); sut.mergeOperationsQueue(q2); Assert::AreEqual(2U, sut.mergedOperationsQueue.size()); pugi::xml_document mockDocument; // Check if the order of operation is correct bool result = sut.mergedOperationsQueue.front().run(mockDocument); Assert::IsTrue(result); result = sut.mergedOperationsQueue.back().run(mockDocument); Assert::IsTrue(result); } TEST_METHOD(wipeData) { DataStore::get().wipeData(); } TEST_METHOD(firstLoadDoesNotThrowException) { std::remove("data.xml"); Internal::DataStore::get().loadData(); } TEST_METHOD(xmlParseErrorThrowsException) { createDummyDataXml(); auto fun = [] { Internal::DataStore::get().loadData(); }; Assert::ExpectException<char*>(fun); } }; } // namespace UnitTests } // namespace DataStore } // namespace You <|endoftext|>
<commit_before>/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <boost/algorithm/string/join.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <osquery/core.h> #include <osquery/filesystem.h> #include <osquery/logger.h> #include <osquery/tables.h> namespace fs = boost::filesystem; namespace pt = boost::property_tree; namespace osquery { namespace tables { const std::string kHomebrewRoot = "/usr/local/Cellar/"; std::vector<std::string> getHomebrewAppInfoPlistPaths() { std::vector<std::string> results; auto status = osquery::listDirectoriesInDirectory(kHomebrewRoot, results); if (!status.ok()) { TLOG << "Error listing " << kHomebrewRoot << ": " << status.toString(); } return results; } std::string getHomebrewNameFromInfoPlistPath(const std::string& path) { auto bits = osquery::split(path, "/"); return bits[bits.size() - 1]; } std::vector<std::string> getHomebrewVersionsFromInfoPlistPath( const std::string& path) { std::vector<std::string> results; std::vector<std::string> app_versions; auto status = osquery::listDirectoriesInDirectory(path, app_versions); if (status.ok()) { for (const auto& version : app_versions) { results.push_back(fs::path(version).filename().string()); } } else { TLOG << "Error listing " << path << ": " << status.toString(); } return results; } QueryData genHomebrewPackages(QueryContext& context) { QueryData results; for (const auto& path : getHomebrewAppInfoPlistPaths()) { auto versions = getHomebrewVersionsFromInfoPlistPath(path); auto name = getHomebrewNameFromInfoPlistPath(path); for (const auto& version : versions) { // Support a many to one version to package name. Row r; r["name"] = name; r["path"] = path; r["version"] = version; results.push_back(r); } } return results; } } } <commit_msg>Fix version reporting for homewbrew_packages. Fixes #1434<commit_after>/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <boost/algorithm/string/join.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <osquery/core.h> #include <osquery/filesystem.h> #include <osquery/logger.h> #include <osquery/tables.h> namespace fs = boost::filesystem; namespace pt = boost::property_tree; namespace osquery { namespace tables { const std::string kHomebrewRoot = "/usr/local/Cellar/"; std::vector<std::string> getHomebrewAppInfoPlistPaths() { std::vector<std::string> results; auto status = osquery::listDirectoriesInDirectory(kHomebrewRoot, results); if (!status.ok()) { TLOG << "Error listing " << kHomebrewRoot << ": " << status.toString(); } return results; } std::string getHomebrewNameFromInfoPlistPath(const std::string& path) { auto bits = osquery::split(path, "/"); return bits[bits.size() - 1]; } std::vector<std::string> getHomebrewVersionsFromInfoPlistPath( const std::string& path) { std::vector<std::string> results; std::vector<std::string> app_versions; auto status = osquery::listDirectoriesInDirectory(path, app_versions); if (status.ok()) { for (const auto& version : app_versions) { results.push_back(fs::path(version).parent_path().filename().string()); } } else { TLOG << "Error listing " << path << ": " << status.toString(); } return results; } QueryData genHomebrewPackages(QueryContext& context) { QueryData results; for (const auto& path : getHomebrewAppInfoPlistPaths()) { auto versions = getHomebrewVersionsFromInfoPlistPath(path); auto name = getHomebrewNameFromInfoPlistPath(path); for (const auto& version : versions) { // Support a many to one version to package name. Row r; r["name"] = name; r["path"] = path; r["version"] = version; results.push_back(r); } } return results; } } } <|endoftext|>
<commit_before>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include "TextureResourceD3D11.h" #include "RendererD3D11.h" #include "core/Engine.h" #include "utils/Log.h" namespace ouzel { namespace graphics { static DXGI_FORMAT getD3D11PixelFormat(PixelFormat pixelFormat) { switch (pixelFormat) { case PixelFormat::A8_UNORM: return DXGI_FORMAT_A8_UNORM; case PixelFormat::R8_UNORM: return DXGI_FORMAT_R8_UNORM; case PixelFormat::R8_SNORM: return DXGI_FORMAT_R8_SNORM; case PixelFormat::R8_UINT: return DXGI_FORMAT_R8_UINT; case PixelFormat::R8_SINT: return DXGI_FORMAT_R8_SINT; case PixelFormat::R16_UNORM: return DXGI_FORMAT_R16_UNORM; case PixelFormat::R16_SNORM: return DXGI_FORMAT_R16_SNORM; case PixelFormat::R16_UINT: return DXGI_FORMAT_R16_UINT; case PixelFormat::R16_SINT: return DXGI_FORMAT_R16_SINT; case PixelFormat::R16_FLOAT: return DXGI_FORMAT_R16_FLOAT; case PixelFormat::R32_UINT: return DXGI_FORMAT_R32_UINT; case PixelFormat::R32_SINT: return DXGI_FORMAT_R32_SINT; case PixelFormat::R32_FLOAT: return DXGI_FORMAT_R32_FLOAT; case PixelFormat::RG8_UNORM: return DXGI_FORMAT_R8G8_UNORM; case PixelFormat::RG8_SNORM: return DXGI_FORMAT_R8G8_SNORM; case PixelFormat::RG8_UINT: return DXGI_FORMAT_R8G8_UINT; case PixelFormat::RG8_SINT: return DXGI_FORMAT_R8G8_SINT; case PixelFormat::RGBA8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM; case PixelFormat::RGBA8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM; case PixelFormat::RGBA8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT; case PixelFormat::RGBA8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT; case PixelFormat::RGBA16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM; case PixelFormat::RGBA16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM; case PixelFormat::RGBA16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT; case PixelFormat::RGBA16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT; case PixelFormat::RGBA16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT; case PixelFormat::RGBA32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT; case PixelFormat::RGBA32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT; case PixelFormat::RGBA32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT; default: return DXGI_FORMAT_UNKNOWN; } } TextureResourceD3D11::TextureResourceD3D11() { } TextureResourceD3D11::~TextureResourceD3D11() { if (depthStencilTexture) { depthStencilTexture->Release(); } if (depthStencilView) { depthStencilView->Release(); } if (renderTargetView) { renderTargetView->Release(); } if (resourceView) { resourceView->Release(); } if (texture) { texture->Release(); } if (samplerState) { samplerState->Release(); } width = 0; height = 0; } bool TextureResourceD3D11::upload() { std::lock_guard<std::mutex> lock(uploadMutex); if (dirty) { RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer()); if (dirty & DIRTY_DATA) { if (size.v[0] > 0 && size.v[1] > 0) { if (!texture || static_cast<UINT>(size.v[0]) != width || static_cast<UINT>(size.v[1]) != height) { if (texture) { texture->Release(); } if (resourceView) { resourceView->Release(); resourceView = nullptr; } width = static_cast<UINT>(size.v[0]); height = static_cast<UINT>(size.v[1]); DXGI_FORMAT d3d11PixelFormat = getD3D11PixelFormat(pixelFormat); if (d3d11PixelFormat == DXGI_FORMAT_UNKNOWN) { Log(Log::Level::ERR) << "Invalid pixel format"; return false; } D3D11_TEXTURE2D_DESC textureDesc; textureDesc.Width = width; textureDesc.Height = height; textureDesc.MipLevels = (levels.size() > 1) ? 0 : 1; textureDesc.ArraySize = 1; textureDesc.Format = d3d11PixelFormat; textureDesc.Usage = (dynamic && !renderTarget) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; textureDesc.CPUAccessFlags = (dynamic && !renderTarget) ? D3D11_CPU_ACCESS_WRITE : 0; textureDesc.SampleDesc.Count = sampleCount; textureDesc.SampleDesc.Quality = 0; textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0); textureDesc.MiscFlags = 0; HRESULT hr = rendererD3D11->getDevice()->CreateTexture2D(&textureDesc, nullptr, &texture); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 texture, error: " << hr; return false; } D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc; resourceViewDesc.Format = d3d11PixelFormat; resourceViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D; if (sampleCount == 1) { resourceViewDesc.Texture2D.MostDetailedMip = 0; resourceViewDesc.Texture2D.MipLevels = static_cast<UINT>(levels.size()); } hr = rendererD3D11->getDevice()->CreateShaderResourceView(texture, &resourceViewDesc, &resourceView); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 shader resource view, error: " << hr; return false; } if (renderTarget) { if (renderTargetView) { renderTargetView->Release(); } D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc; renderTargetViewDesc.Format = d3d11PixelFormat; renderTargetViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D; if (sampleCount == 1) { renderTargetViewDesc.Texture2D.MipSlice = 0; } hr = rendererD3D11->getDevice()->CreateRenderTargetView(texture, &renderTargetViewDesc, &renderTargetView); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 render target view, error: " << hr; return false; } } if (depth) { if (depthStencilTexture) { depthStencilTexture->Release(); } if (depthStencilView) { depthStencilView->Release(); depthStencilView = nullptr; } D3D11_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = width; depthStencilDesc.Height = height; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT; depthStencilDesc.SampleDesc.Count = sampleCount; depthStencilDesc.SampleDesc.Quality = 0; depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; hr = rendererD3D11->getDevice()->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencilTexture); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil texture, error: " << hr; return false; } hr = rendererD3D11->getDevice()->CreateDepthStencilView(depthStencilTexture, nullptr, &depthStencilView); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil view, error: " << hr; return false; } } } if (dynamic) { for (size_t level = 0; level < levels.size(); ++level) { if (!levels[level].data.empty()) { D3D11_MAPPED_SUBRESOURCE mappedSubresource; mappedSubresource.pData = 0; mappedSubresource.RowPitch = 0; mappedSubresource.DepthPitch = 0; HRESULT hr = rendererD3D11->getContext()->Map(texture, static_cast<UINT>(level), (level == 0) ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE, 0, &mappedSubresource); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to map Direct3D 11 texture, error: " << hr; return false; } uint8_t* target = reinterpret_cast<uint8_t*>(mappedSubresource.pData); for (UINT row = 0; row < height; ++row) { std::copy(levels[level].data.begin() + row * levels[level].pitch, levels[level].data.begin() + (row + 1) * levels[level].pitch, target); target += mappedSubresource.RowPitch; } rendererD3D11->getContext()->Unmap(texture, static_cast<UINT>(level)); } } } else { for (size_t level = 0; level < levels.size(); ++level) { if (!levels[level].data.empty()) { rendererD3D11->getContext()->UpdateSubresource(texture, static_cast<UINT>(level), nullptr, levels[level].data.data(), static_cast<UINT>(levels[level].pitch), 0); } } } } } if (dirty & DIRTY_PARAMETERS) { clearFrameBufferView = clearColorBuffer; clearDepthBufferView = clearDepthBuffer; frameBufferClearColor[0] = clearColor.normR(); frameBufferClearColor[1] = clearColor.normG(); frameBufferClearColor[2] = clearColor.normB(); frameBufferClearColor[3] = clearColor.normA(); if (samplerState) samplerState->Release(); RendererD3D11::SamplerStateDesc samplerDesc; samplerDesc.filter = (filter == Texture::Filter::DEFAULT) ? rendererD3D11->getTextureFilter() : filter; samplerDesc.addressX = addressX; samplerDesc.addressY = addressY; samplerDesc.maxAnisotropy = (maxAnisotropy == 0) ? rendererD3D11->getMaxAnisotropy() : maxAnisotropy; samplerState = rendererD3D11->getSamplerState(samplerDesc); if (!samplerState) { Log(Log::Level::ERR) << "Failed to get D3D11 sampler state"; return false; } samplerState->AddRef(); } dirty = 0; } return true; } } // namespace graphics } // namespace ouzel <commit_msg>If the pitches are equal copy the whole buffer<commit_after>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include "TextureResourceD3D11.h" #include "RendererD3D11.h" #include "core/Engine.h" #include "utils/Log.h" namespace ouzel { namespace graphics { static DXGI_FORMAT getD3D11PixelFormat(PixelFormat pixelFormat) { switch (pixelFormat) { case PixelFormat::A8_UNORM: return DXGI_FORMAT_A8_UNORM; case PixelFormat::R8_UNORM: return DXGI_FORMAT_R8_UNORM; case PixelFormat::R8_SNORM: return DXGI_FORMAT_R8_SNORM; case PixelFormat::R8_UINT: return DXGI_FORMAT_R8_UINT; case PixelFormat::R8_SINT: return DXGI_FORMAT_R8_SINT; case PixelFormat::R16_UNORM: return DXGI_FORMAT_R16_UNORM; case PixelFormat::R16_SNORM: return DXGI_FORMAT_R16_SNORM; case PixelFormat::R16_UINT: return DXGI_FORMAT_R16_UINT; case PixelFormat::R16_SINT: return DXGI_FORMAT_R16_SINT; case PixelFormat::R16_FLOAT: return DXGI_FORMAT_R16_FLOAT; case PixelFormat::R32_UINT: return DXGI_FORMAT_R32_UINT; case PixelFormat::R32_SINT: return DXGI_FORMAT_R32_SINT; case PixelFormat::R32_FLOAT: return DXGI_FORMAT_R32_FLOAT; case PixelFormat::RG8_UNORM: return DXGI_FORMAT_R8G8_UNORM; case PixelFormat::RG8_SNORM: return DXGI_FORMAT_R8G8_SNORM; case PixelFormat::RG8_UINT: return DXGI_FORMAT_R8G8_UINT; case PixelFormat::RG8_SINT: return DXGI_FORMAT_R8G8_SINT; case PixelFormat::RGBA8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM; case PixelFormat::RGBA8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM; case PixelFormat::RGBA8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT; case PixelFormat::RGBA8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT; case PixelFormat::RGBA16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM; case PixelFormat::RGBA16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM; case PixelFormat::RGBA16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT; case PixelFormat::RGBA16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT; case PixelFormat::RGBA16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT; case PixelFormat::RGBA32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT; case PixelFormat::RGBA32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT; case PixelFormat::RGBA32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT; default: return DXGI_FORMAT_UNKNOWN; } } TextureResourceD3D11::TextureResourceD3D11() { } TextureResourceD3D11::~TextureResourceD3D11() { if (depthStencilTexture) { depthStencilTexture->Release(); } if (depthStencilView) { depthStencilView->Release(); } if (renderTargetView) { renderTargetView->Release(); } if (resourceView) { resourceView->Release(); } if (texture) { texture->Release(); } if (samplerState) { samplerState->Release(); } width = 0; height = 0; } bool TextureResourceD3D11::upload() { std::lock_guard<std::mutex> lock(uploadMutex); if (dirty) { RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer()); if (dirty & DIRTY_DATA) { if (size.v[0] > 0 && size.v[1] > 0) { if (!texture || static_cast<UINT>(size.v[0]) != width || static_cast<UINT>(size.v[1]) != height) { if (texture) { texture->Release(); } if (resourceView) { resourceView->Release(); resourceView = nullptr; } width = static_cast<UINT>(size.v[0]); height = static_cast<UINT>(size.v[1]); DXGI_FORMAT d3d11PixelFormat = getD3D11PixelFormat(pixelFormat); if (d3d11PixelFormat == DXGI_FORMAT_UNKNOWN) { Log(Log::Level::ERR) << "Invalid pixel format"; return false; } D3D11_TEXTURE2D_DESC textureDesc; textureDesc.Width = width; textureDesc.Height = height; textureDesc.MipLevels = (levels.size() > 1) ? 0 : 1; textureDesc.ArraySize = 1; textureDesc.Format = d3d11PixelFormat; textureDesc.Usage = (dynamic && !renderTarget) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; textureDesc.CPUAccessFlags = (dynamic && !renderTarget) ? D3D11_CPU_ACCESS_WRITE : 0; textureDesc.SampleDesc.Count = sampleCount; textureDesc.SampleDesc.Quality = 0; textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0); textureDesc.MiscFlags = 0; HRESULT hr = rendererD3D11->getDevice()->CreateTexture2D(&textureDesc, nullptr, &texture); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 texture, error: " << hr; return false; } D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc; resourceViewDesc.Format = d3d11PixelFormat; resourceViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D; if (sampleCount == 1) { resourceViewDesc.Texture2D.MostDetailedMip = 0; resourceViewDesc.Texture2D.MipLevels = static_cast<UINT>(levels.size()); } hr = rendererD3D11->getDevice()->CreateShaderResourceView(texture, &resourceViewDesc, &resourceView); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 shader resource view, error: " << hr; return false; } if (renderTarget) { if (renderTargetView) { renderTargetView->Release(); } D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc; renderTargetViewDesc.Format = d3d11PixelFormat; renderTargetViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D; if (sampleCount == 1) { renderTargetViewDesc.Texture2D.MipSlice = 0; } hr = rendererD3D11->getDevice()->CreateRenderTargetView(texture, &renderTargetViewDesc, &renderTargetView); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 render target view, error: " << hr; return false; } } if (depth) { if (depthStencilTexture) { depthStencilTexture->Release(); } if (depthStencilView) { depthStencilView->Release(); depthStencilView = nullptr; } D3D11_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = width; depthStencilDesc.Height = height; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT; depthStencilDesc.SampleDesc.Count = sampleCount; depthStencilDesc.SampleDesc.Quality = 0; depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; hr = rendererD3D11->getDevice()->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencilTexture); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil texture, error: " << hr; return false; } hr = rendererD3D11->getDevice()->CreateDepthStencilView(depthStencilTexture, nullptr, &depthStencilView); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil view, error: " << hr; return false; } } } if (dynamic) { for (size_t level = 0; level < levels.size(); ++level) { if (!levels[level].data.empty()) { D3D11_MAPPED_SUBRESOURCE mappedSubresource; mappedSubresource.pData = 0; mappedSubresource.RowPitch = 0; mappedSubresource.DepthPitch = 0; HRESULT hr = rendererD3D11->getContext()->Map(texture, static_cast<UINT>(level), (level == 0) ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE, 0, &mappedSubresource); if (FAILED(hr)) { Log(Log::Level::ERR) << "Failed to map Direct3D 11 texture, error: " << hr; return false; } uint8_t* target = reinterpret_cast<uint8_t*>(mappedSubresource.pData); if (mappedSubresource.RowPitch == levels[level].pitch) { std::copy(levels[level].data.begin(), levels[level].data.end(), target); } else { for (UINT row = 0; row < height; ++row) { std::copy(levels[level].data.begin() + row * levels[level].pitch, levels[level].data.begin() + (row + 1) * levels[level].pitch, target); target += mappedSubresource.RowPitch; } rendererD3D11->getContext()->Unmap(texture, static_cast<UINT>(level)); } } } } else { for (size_t level = 0; level < levels.size(); ++level) { if (!levels[level].data.empty()) { rendererD3D11->getContext()->UpdateSubresource(texture, static_cast<UINT>(level), nullptr, levels[level].data.data(), static_cast<UINT>(levels[level].pitch), 0); } } } } } if (dirty & DIRTY_PARAMETERS) { clearFrameBufferView = clearColorBuffer; clearDepthBufferView = clearDepthBuffer; frameBufferClearColor[0] = clearColor.normR(); frameBufferClearColor[1] = clearColor.normG(); frameBufferClearColor[2] = clearColor.normB(); frameBufferClearColor[3] = clearColor.normA(); if (samplerState) samplerState->Release(); RendererD3D11::SamplerStateDesc samplerDesc; samplerDesc.filter = (filter == Texture::Filter::DEFAULT) ? rendererD3D11->getTextureFilter() : filter; samplerDesc.addressX = addressX; samplerDesc.addressY = addressY; samplerDesc.maxAnisotropy = (maxAnisotropy == 0) ? rendererD3D11->getMaxAnisotropy() : maxAnisotropy; samplerState = rendererD3D11->getSamplerState(samplerDesc); if (!samplerState) { Log(Log::Level::ERR) << "Failed to get D3D11 sampler state"; return false; } samplerState->AddRef(); } dirty = 0; } return true; } } // namespace graphics } // namespace ouzel <|endoftext|>
<commit_before>#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Render.h" #include "j1Window.h" #include "j1Map.h" #include "j1Colliders.h" #include "j1Scene.h" #include "j1Scene2.h" #include "j1Player.h" j1Scene::j1Scene() : j1Module() { name.create("scene"); } // Destructor j1Scene::~j1Scene() {} // Called before render is available bool j1Scene::Awake(pugi::xml_node& config) { LOG("Loading Scene"); bool ret = true; return ret; } // Called before the first frame bool j1Scene::Start() { App->map->Load("test.tmx"); App->audio->PlayMusic("audio/music/map1_music.ogg"); //Colliders //App->colliders->AddCollider({ 0,415,10000,10 }, COLLIDER_FLOOR); App->map->Draw_Colliders(); return true; } // Called each loop iteration bool j1Scene::PreUpdate() { return true; } // Called each loop iteration bool j1Scene::Update(float dt) { if(App->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN) App->SaveGame(); if(App->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN) App->LoadGame(); if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN) { active = false; App->scene2->active = true; CleanUp(); App->scene2->Start(); App->player->position.y = 215; } if (App->player->position.x >= App->player->win_width/2 && App->player->position.x <= 15000)//App->player->win_width) { App->render->camera.x =- App->player->position.x + App->player->win_width / 2; } //App->render->Blit(img, 0, 0); App->map->Draw(); // TODO 7: Set the window title like // "Map:%dx%d Tiles:%dx%d Tilesets:%d" p2SString title("Map:%dx%d Tiles:%dx%d Tilesets:%d Player.x=%i Player.y=%i CameraPosition.x=%i CameraPosition.y=%i Acceleration=%d X=%d Y=%d", App->map->data.width, App->map->data.height, App->map->data.tile_width, App->map->data.tile_height, App->map->data.tilesets.count(), App->player->position.x, App->player->position.y, App->render->camera.x, App->render->camera.y, App->player->acceleration, App->player->position.x,App->player->position.y); App->win->SetTitle(title.GetString()); return true; } // Called each loop iteration bool j1Scene::PostUpdate() { bool ret = true; if(App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false; return ret; } // Called before quitting bool j1Scene::CleanUp() { LOG("Freeing scene"); App->map->CleanUp(); App->colliders->CleanUp(); return true; } <commit_msg>player x reload<commit_after>#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Render.h" #include "j1Window.h" #include "j1Map.h" #include "j1Colliders.h" #include "j1Scene.h" #include "j1Scene2.h" #include "j1Player.h" j1Scene::j1Scene() : j1Module() { name.create("scene"); } // Destructor j1Scene::~j1Scene() {} // Called before render is available bool j1Scene::Awake(pugi::xml_node& config) { LOG("Loading Scene"); bool ret = true; return ret; } // Called before the first frame bool j1Scene::Start() { App->map->Load("untitled.tmx"); App->audio->PlayMusic("audio/music/map1_music.ogg"); //Colliders //App->colliders->AddCollider({ 0,415,10000,10 }, COLLIDER_FLOOR); App->map->Draw_Colliders(); return true; } // Called each loop iteration bool j1Scene::PreUpdate() { return true; } // Called each loop iteration bool j1Scene::Update(float dt) { if(App->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN) App->SaveGame(); if(App->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN) App->LoadGame(); if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN) { active = false; App->scene2->active = true; CleanUp(); App->scene2->Start(); App->player->position.y = 215; App->player->position.x = 60; } if (App->player->position.x >= App->player->win_width/2 && App->player->position.x <= 15000)//App->player->win_width) { App->render->camera.x =- App->player->position.x + App->player->win_width / 2; } //App->render->Blit(img, 0, 0); App->map->Draw(); // TODO 7: Set the window title like // "Map:%dx%d Tiles:%dx%d Tilesets:%d" p2SString title("Map:%dx%d Tiles:%dx%d Tilesets:%d Player.x=%i Player.y=%i CameraPosition.x=%i CameraPosition.y=%i Acceleration=%d X=%d Y=%d", App->map->data.width, App->map->data.height, App->map->data.tile_width, App->map->data.tile_height, App->map->data.tilesets.count(), App->player->position.x, App->player->position.y, App->render->camera.x, App->render->camera.y, App->player->acceleration, App->player->position.x,App->player->position.y); App->win->SetTitle(title.GetString()); return true; } // Called each loop iteration bool j1Scene::PostUpdate() { bool ret = true; if(App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false; return ret; } // Called before quitting bool j1Scene::CleanUp() { LOG("Freeing scene"); App->map->CleanUp(); App->colliders->CleanUp(); return true; } <|endoftext|>
<commit_before>// Copyright (c) 2009 - Decho Corp. #include "mordor/common/pch.h" #include "oauth.h" #include "mordor/common/streams/memory.h" #include "mordor/common/streams/transfer.h" void HTTP::OAuth::authorize(Request &nextRequest) { if (m_params.find("oauth_token_secret") == m_params.end() || m_params.find("oauth_token") == m_params.end()) { getRequestToken(); getAccessToken(m_authDg(m_params)); } AuthParams &authorization = nextRequest.request.authorization; authorization.scheme = "OAuth"; URI::QueryString params = signRequest(nextRequest.requestLine.uri, nextRequest.requestLine.method); authorization.parameters.clear(); authorization.parameters.insert(params.begin(), params.end()); } void HTTP::OAuth::getRequestToken() { ASSERT(m_requestTokenMethod == HTTP::GET || m_requestTokenMethod == HTTP::POST); URI::QueryString qs; qs.insert(std::make_pair("oauth_consumer_key", m_consumerKey)); qs.insert(std::make_pair("oauth_version", "1.0")); qs.insert(std::make_pair("oauth_callback", "oob")); nonceAndTimestamp(qs); sign(m_requestTokenUri, m_requestTokenMethod, qs); HTTP::Request requestHeaders; requestHeaders.requestLine.method = m_requestTokenMethod; requestHeaders.requestLine.uri = m_requestTokenUri; std::string body; if (m_requestTokenMethod == HTTP::GET) { // Add parameters that are part of the request token URI URI::QueryString qsFromUri = m_requestTokenUri.queryString(); qs.insert(qsFromUri.begin(), qsFromUri.end()); requestHeaders.requestLine.uri.query(qs); } else { body = qs.toString(); requestHeaders.entity.contentType.type = "application"; requestHeaders.entity.contentType.subtype = "x-www-form-urlencoded"; requestHeaders.entity.contentLength = body.size(); } HTTP::ClientRequest::ptr request = m_connDg(m_requestTokenUri)->request(requestHeaders); if (!body.empty()) { request->requestStream()->write(body.c_str(), body.size()); request->requestStream()->close(); } if (request->response().status.status != HTTP::OK) { request->cancel(); throw HTTP::InvalidResponseException("", request->response()); } MemoryStream responseStream; transferStream(request->responseStream(), responseStream); std::string response; response.resize(responseStream.buffer().readAvailable()); responseStream.buffer().copyOut(&response[0], responseStream.buffer().readAvailable()); m_params = response; URI::QueryString::iterator it = m_params.find("oauth_token"); if (it == m_params.end()) throw HTTP::InvalidResponseException("Missing oauth_token in response", request->response()); ++it; if (it != m_params.end() && stricmp(it->first.c_str(), "oauth_token") == 0) throw HTTP::InvalidResponseException("Duplicate oauth_token in response", request->response()); it = m_params.find("oauth_token_secret"); if (it == m_params.end()) throw HTTP::InvalidResponseException("Missing oauth_token_secret in response", request->response()); ++it; if (it != m_params.end() && stricmp(it->first.c_str(), "oauth_token_secret") == 0) throw HTTP::InvalidResponseException("Duplicate oauth_token_secret in response", request->response()); } void HTTP::OAuth::getAccessToken(const std::string &verifier) { ASSERT(m_accessTokenMethod == HTTP::GET || m_accessTokenMethod == HTTP::POST); URI::QueryString qs; qs.insert(std::make_pair("oauth_consumer_key", m_consumerKey)); qs.insert(*m_params.find("oauth_token")); qs.insert(std::make_pair("oauth_verifier", verifier)); qs.insert(std::make_pair("oauth_version", "1.0")); nonceAndTimestamp(qs); sign(m_accessTokenUri, m_accessTokenMethod, qs); HTTP::Request requestHeaders; requestHeaders.requestLine.method = m_accessTokenMethod; requestHeaders.requestLine.uri = m_accessTokenUri; std::string body; if (m_accessTokenMethod == HTTP::GET) { // Add parameters that are part of the request token URI URI::QueryString qsFromUri = m_accessTokenUri.queryString(); qs.insert(qsFromUri.begin(), qsFromUri.end()); requestHeaders.requestLine.uri.query(qs); } else { body = qs.toString(); requestHeaders.entity.contentType.type = "application"; requestHeaders.entity.contentType.subtype = "x-www-form-urlencoded"; requestHeaders.entity.contentLength = body.size(); } HTTP::ClientRequest::ptr request = m_connDg(m_accessTokenUri)->request(requestHeaders); if (!body.empty()) { request->requestStream()->write(body.c_str(), body.size()); request->requestStream()->close(); } if (request->response().status.status != HTTP::OK) { request->cancel(); throw HTTP::InvalidResponseException("", request->response()); } MemoryStream responseStream; transferStream(request->responseStream(), responseStream); std::string response; response.resize(responseStream.buffer().readAvailable()); responseStream.buffer().copyOut(&response[0], responseStream.buffer().readAvailable()); m_params = response; URI::QueryString::iterator it = m_params.find("oauth_token"); if (it == m_params.end()) throw HTTP::InvalidResponseException("Missing oauth_token in response", request->response()); ++it; if (it != m_params.end() && stricmp(it->first.c_str(), "oauth_token") == 0) throw HTTP::InvalidResponseException("Duplicate oauth_token in response", request->response()); it = m_params.find("oauth_token_secret"); if (it == m_params.end()) throw HTTP::InvalidResponseException("Missing oauth_token_secret in response", request->response()); ++it; if (it != m_params.end() && stricmp(it->first.c_str(), "oauth_token_secret") == 0) throw HTTP::InvalidResponseException("Duplicate oauth_token_secret in response", request->response()); } URI::QueryString HTTP::OAuth::signRequest(const URI &uri, Method method) { URI::QueryString result; result.insert(std::make_pair("oauth_consumer_key", m_consumerKey)); result.insert(*m_params.find("oauth_token")); result.insert(std::make_pair("oauth_version", "1.0")); nonceAndTimestamp(result); sign(uri, method, result); return result; } void HTTP::OAuth::nonceAndTimestamp(URI::QueryString &params) { // TODO: fill in with better data params.insert(std::make_pair("oauth_timestamp", "123")); params.insert(std::make_pair("oauth_nonce", "abc")); } void HTTP::OAuth::sign(URI uri, Method method, URI::QueryString &params) { std::string signatureMethod; URI::QueryString::iterator it = params.find("oauth_signature_method"); if (it == params.end()) { params.insert(std::make_pair("oauth_signature_method", "PLAINTEXT")); signatureMethod = "PLAINTEXT"; } else { signatureMethod = it->second; } it = params.find("oauth_signature"); if (it != params.end()) params.erase(it); std::ostringstream os; uri.queryDefined(false); uri.fragmentDefined(false); uri.normalize(); os << method << '&' << uri; URI::QueryString combined = params; it = combined.find("realm"); if (it != combined.end()) combined.erase(it); // TODO: POST params of application/x-www-form-urlencoded if (uri.queryDefined()) { URI::QueryString queryParams = uri.queryString(); combined.insert(queryParams.begin(), queryParams.end()); } // TODO: ordering of duplicate keys std::string signatureBaseString = combined.toString(); std::string secrets = URI::encode(m_consumerSecret, URI::QUERYSTRING); secrets.append(1, '&'); secrets.append(URI::encode(m_params.find("oauth_token_secret")->second, URI::QUERYSTRING)); if (stricmp(signatureMethod.c_str(), "HMAC-SHA1") == 0) { params.insert(std::make_pair("oauth_signature", hmacSha1(signatureBaseString, secrets))); } else if (stricmp(signatureMethod.c_str(), "PLAINTEXT") == 0) { params.insert(std::make_pair("oauth_signature", secrets)); } else { NOTREACHED(); } } <commit_msg>Use actual nonce and timestamps. Follow the spec for formation of the signature base string.<commit_after>// Copyright (c) 2009 - Decho Corp. #include "mordor/common/pch.h" #include "oauth.h" #include "mordor/common/streams/memory.h" #include "mordor/common/streams/transfer.h" void HTTP::OAuth::authorize(Request &nextRequest) { if (m_params.find("oauth_token_secret") == m_params.end() || m_params.find("oauth_token") == m_params.end()) { getRequestToken(); getAccessToken(m_authDg(m_params)); } AuthParams &authorization = nextRequest.request.authorization; authorization.scheme = "OAuth"; URI::QueryString params = signRequest(nextRequest.requestLine.uri, nextRequest.requestLine.method); authorization.parameters.clear(); authorization.parameters.insert(params.begin(), params.end()); } void HTTP::OAuth::getRequestToken() { ASSERT(m_requestTokenMethod == HTTP::GET || m_requestTokenMethod == HTTP::POST); URI::QueryString qs; qs.insert(std::make_pair("oauth_consumer_key", m_consumerKey)); qs.insert(std::make_pair("oauth_version", "1.0")); qs.insert(std::make_pair("oauth_callback", "oob")); nonceAndTimestamp(qs); sign(m_requestTokenUri, m_requestTokenMethod, qs); HTTP::Request requestHeaders; requestHeaders.requestLine.method = m_requestTokenMethod; requestHeaders.requestLine.uri = m_requestTokenUri; std::string body; if (m_requestTokenMethod == HTTP::GET) { // Add parameters that are part of the request token URI URI::QueryString qsFromUri = m_requestTokenUri.queryString(); qs.insert(qsFromUri.begin(), qsFromUri.end()); requestHeaders.requestLine.uri.query(qs); } else { body = qs.toString(); requestHeaders.entity.contentType.type = "application"; requestHeaders.entity.contentType.subtype = "x-www-form-urlencoded"; requestHeaders.entity.contentLength = body.size(); } HTTP::ClientRequest::ptr request = m_connDg(m_requestTokenUri)->request(requestHeaders); if (!body.empty()) { request->requestStream()->write(body.c_str(), body.size()); request->requestStream()->close(); } if (request->response().status.status != HTTP::OK) { request->cancel(); throw HTTP::InvalidResponseException("", request->response()); } MemoryStream responseStream; transferStream(request->responseStream(), responseStream); std::string response; response.resize(responseStream.buffer().readAvailable()); responseStream.buffer().copyOut(&response[0], responseStream.buffer().readAvailable()); m_params = response; URI::QueryString::iterator it = m_params.find("oauth_token"); if (it == m_params.end()) throw HTTP::InvalidResponseException("Missing oauth_token in response", request->response()); ++it; if (it != m_params.end() && stricmp(it->first.c_str(), "oauth_token") == 0) throw HTTP::InvalidResponseException("Duplicate oauth_token in response", request->response()); it = m_params.find("oauth_token_secret"); if (it == m_params.end()) throw HTTP::InvalidResponseException("Missing oauth_token_secret in response", request->response()); ++it; if (it != m_params.end() && stricmp(it->first.c_str(), "oauth_token_secret") == 0) throw HTTP::InvalidResponseException("Duplicate oauth_token_secret in response", request->response()); } void HTTP::OAuth::getAccessToken(const std::string &verifier) { ASSERT(m_accessTokenMethod == HTTP::GET || m_accessTokenMethod == HTTP::POST); URI::QueryString qs; qs.insert(std::make_pair("oauth_consumer_key", m_consumerKey)); qs.insert(*m_params.find("oauth_token")); qs.insert(std::make_pair("oauth_verifier", verifier)); qs.insert(std::make_pair("oauth_version", "1.0")); nonceAndTimestamp(qs); sign(m_accessTokenUri, m_accessTokenMethod, qs); HTTP::Request requestHeaders; requestHeaders.requestLine.method = m_accessTokenMethod; requestHeaders.requestLine.uri = m_accessTokenUri; std::string body; if (m_accessTokenMethod == HTTP::GET) { // Add parameters that are part of the request token URI URI::QueryString qsFromUri = m_accessTokenUri.queryString(); qs.insert(qsFromUri.begin(), qsFromUri.end()); requestHeaders.requestLine.uri.query(qs); } else { body = qs.toString(); requestHeaders.entity.contentType.type = "application"; requestHeaders.entity.contentType.subtype = "x-www-form-urlencoded"; requestHeaders.entity.contentLength = body.size(); } HTTP::ClientRequest::ptr request = m_connDg(m_accessTokenUri)->request(requestHeaders); if (!body.empty()) { request->requestStream()->write(body.c_str(), body.size()); request->requestStream()->close(); } if (request->response().status.status != HTTP::OK) { request->cancel(); throw HTTP::InvalidResponseException("", request->response()); } MemoryStream responseStream; transferStream(request->responseStream(), responseStream); std::string response; response.resize(responseStream.buffer().readAvailable()); responseStream.buffer().copyOut(&response[0], responseStream.buffer().readAvailable()); m_params = response; URI::QueryString::iterator it = m_params.find("oauth_token"); if (it == m_params.end()) throw HTTP::InvalidResponseException("Missing oauth_token in response", request->response()); ++it; if (it != m_params.end() && stricmp(it->first.c_str(), "oauth_token") == 0) throw HTTP::InvalidResponseException("Duplicate oauth_token in response", request->response()); it = m_params.find("oauth_token_secret"); if (it == m_params.end()) throw HTTP::InvalidResponseException("Missing oauth_token_secret in response", request->response()); ++it; if (it != m_params.end() && stricmp(it->first.c_str(), "oauth_token_secret") == 0) throw HTTP::InvalidResponseException("Duplicate oauth_token_secret in response", request->response()); } URI::QueryString HTTP::OAuth::signRequest(const URI &uri, Method method) { URI::QueryString result; result.insert(std::make_pair("oauth_consumer_key", m_consumerKey)); result.insert(*m_params.find("oauth_token")); result.insert(std::make_pair("oauth_version", "1.0")); nonceAndTimestamp(result); sign(uri, method, result); return result; } void HTTP::OAuth::nonceAndTimestamp(URI::QueryString &params) { static boost::posix_time::ptime start(boost::gregorian::date(1970, 1, 1)); static const char *allowedChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::ostringstream os; boost::posix_time::ptime now = boost::posix_time::second_clock::universal_time(); boost::posix_time::time_duration duration = now - start; os << duration.total_seconds(); std::string nonce; nonce.resize(40); for (size_t i = 0; i < 40; ++i) { nonce[i] = allowedChars[rand() % 36]; } params.insert(std::make_pair("oauth_timestamp", os.str())); params.insert(std::make_pair("oauth_nonce", nonce)); } void HTTP::OAuth::sign(URI uri, Method method, URI::QueryString &params) { std::string signatureMethod; URI::QueryString::iterator it = params.find("oauth_signature_method"); if (it == params.end()) { params.insert(std::make_pair("oauth_signature_method", "PLAINTEXT")); signatureMethod = "PLAINTEXT"; } else { signatureMethod = it->second; } it = params.find("oauth_signature"); if (it != params.end()) params.erase(it); std::ostringstream os; uri.queryDefined(false); uri.fragmentDefined(false); uri.normalize(); os << method << '&' << uri; std::map<std::string, std::multiset<std::string> > combined; std::map<std::string, std::multiset<std::string> >::iterator combinedIt; for (it = params.begin(); it != params.end(); ++it) if (stricmp(it->first.c_str(), "realm") != 0) combined[it->first].insert(it->second); // TODO: POST params of application/x-www-form-urlencoded if (uri.queryDefined()) { URI::QueryString queryParams = uri.queryString(); for (it = queryParams.begin(); it != queryParams.end(); ++it) combined[it->first].insert(it->second); } for (combinedIt = combined.begin(); combinedIt != combined.end(); ++combinedIt) { for (std::multiset<std::string>::iterator it2 = combinedIt->second.begin(); it2 != combinedIt->second.end(); ++it2) { os << '&' << URI::encode(combinedIt->first, URI::QUERYSTRING) << '=' << URI::encode(*it2, URI::QUERYSTRING); } } std::string signatureBaseString = os.str(); std::string secrets = URI::encode(m_consumerSecret, URI::QUERYSTRING); secrets.append(1, '&'); secrets.append(URI::encode(m_params.find("oauth_token_secret")->second, URI::QUERYSTRING)); if (stricmp(signatureMethod.c_str(), "HMAC-SHA1") == 0) { params.insert(std::make_pair("oauth_signature", hmacSha1(signatureBaseString, secrets))); } else if (stricmp(signatureMethod.c_str(), "PLAINTEXT") == 0) { params.insert(std::make_pair("oauth_signature", secrets)); } else { NOTREACHED(); } } <|endoftext|>
<commit_before>//////////////////////////////// -*- C++ -*- ///////////////////////////// // // FILE NAME // ParticleAttributesFactory.cc // // AUTHOR // A. Shishlo // // CREATED // 07/16/2005 // // DESCRIPTION // A factory class for particle attributes classes. // Usually it will be used from a Bunch class instance. // /////////////////////////////////////////////////////////////////////////// #include "ParticleAttributesFactory.hh" #include "ParticleMacroSize.hh" #include "WaveFunctionAmplitudes.hh" #include "AtomPopulations.hh" #include "pq_coordinates.hh" #include "part_time.hh" #include "Evolution.hh" #include "LostParticleAttributes.hh" ParticleAttributesFactory::ParticleAttributesFactory() { } ParticleAttributesFactory::~ParticleAttributesFactory() { } ParticleAttributes* ParticleAttributesFactory::getParticleAttributesInstance( const string name, std::map<std::string,double> params_dict, Bunch* bunch) { //for MPI --- start int rank_MPI = 0; int size_MPI = 1; int iMPIini = 0; MPI_Comm MPI_COMM_Local = bunch->getMPI_Comm_Local()->comm; ORBIT_MPI_Initialized(&iMPIini); if(iMPIini > 0){ ORBIT_MPI_Comm_size(MPI_COMM_Local, &size_MPI); ORBIT_MPI_Comm_rank(MPI_COMM_Local, &rank_MPI); } //for MPI --- stop ParticleAttributes* part_atrs = NULL; if(name == "empty"){ part_atrs = new ParticleAttributes(bunch,0); } if(name == "macrosize"){ part_atrs = new ParticleMacroSize(bunch); } if(name == "LostParticleAttributes"){ part_atrs = new LostParticleAttributes(bunch); } if(name == "Amplitudes"){ if(params_dict.size() == 0){ cout<<"dictionary Amplitudes(dict) should be defined "<<"\n"; } else { if(params_dict.count("size") == 1){ part_atrs = new WaveFunctionAmplitudes(bunch,(int) params_dict["size"]); } else { if(rank_MPI == 0){ std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl; std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl; std::cerr << "MPI size="<< size_MPI << std::endl; std::cerr << "MPI rank="<< rank_MPI << std::endl; std::cerr << "attr. name:"<< name << std::endl; std::cerr << "There is no <size> specification in the dict. "<< std::endl; } ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop."); } } } if(name == "Populations"){ if(params_dict.size() == 0){ cout<<"dictionary AtomPopulations(dict) should be defined "<<"\n"; } else { if(params_dict.count("size") == 1){ part_atrs = new AtomPopulations(bunch,(int) params_dict["size"]); } else { if(rank_MPI == 0){ std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl; std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl; std::cerr << "MPI size="<< size_MPI << std::endl; std::cerr << "MPI rank="<< rank_MPI << std::endl; std::cerr << "attr. name:"<< name << std::endl; std::cerr << "There is no <size> specification in the dict. "<< std::endl; } ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop."); } } } if(name == "pq_coords"){ if(params_dict.size() == 0){ cout<<"dictionary pq_coords(dict) should be defined "<<"\n"; } else { if(params_dict.count("size") == 1){ part_atrs = new pq_coordinates(bunch,(int) params_dict["size"]); } else { if(rank_MPI == 0){ std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl; std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl; std::cerr << "MPI size="<< size_MPI << std::endl; std::cerr << "MPI rank="<< rank_MPI << std::endl; std::cerr << "attr. name:"<< name << std::endl; std::cerr << "There is no <size> specification in the dict. "<< std::endl; } ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop."); } } } if(name == "part_time"){ if(params_dict.size() == 0){ cout<<"dictionary prf_time(dict) should be defined "<<"\n"; } else { if(params_dict.count("size") == 1){ part_atrs = new part_time(bunch, (int)params_dict["size"]); } else { if(rank_MPI == 0){ std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl; std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl; std::cerr << "MPI size="<< size_MPI << std::endl; std::cerr << "MPI rank="<< rank_MPI << std::endl; std::cerr << "attr. name:"<< name << std::endl; std::cerr << "There is no <size> specification in the dict. "<< std::endl; } ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop."); } } } if(name == "Evolution"){ if(params_dict.size() == 0){ cout<<"dictionary Evolution(dict) should be defined "<<"\n"; } else { if(params_dict.count("size") == 1){ part_atrs = new Evolution(bunch, (int) params_dict["size"]); } else { if(rank_MPI == 0){ std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl; std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl; std::cerr << "MPI size="<< size_MPI << std::endl; std::cerr << "MPI rank="<< rank_MPI << std::endl; std::cerr << "attr. name:"<< name << std::endl; std::cerr << "There is no <size> specification in the dict. "<< std::endl; } ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop."); } } } if(part_atrs == NULL) { if(rank_MPI == 0){ std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(const string name, Bunch* bunch)"<< std::endl; std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl; std::cerr << "MPI size="<< size_MPI << std::endl; std::cerr << "MPI rank="<< rank_MPI << std::endl; std::cerr << "There is not a particle attirubutes class with such name in the Factory."<< std::endl; std::cerr << "attr. name:"<< name << std::endl; } ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop."); return part_atrs; } //copy the particle attributes dictionary part_atrs->parameterDict = params_dict; part_atrs->parameterDict["size"] = part_atrs->getAttSize(); return part_atrs; } void ParticleAttributesFactory::getParticleAttributesNames(std::vector<string>& names){ names.clear(); names.push_back("macrosize"); names.push_back("Amplitudes"); names.push_back("Populations"); names.push_back("pq_coords"); names.push_back("part_time"); names.push_back("Evolution"); names.push_back("LostParticleAttributes"); } <commit_msg>Added tune attributes.<commit_after>//////////////////////////////// -*- C++ -*- ///////////////////////////// // // FILE NAME // ParticleAttributesFactory.cc // // AUTHOR // A. Shishlo // // CREATED // 07/16/2005 // // DESCRIPTION // A factory class for particle attributes classes. // Usually it will be used from a Bunch class instance. // /////////////////////////////////////////////////////////////////////////// #include "ParticleAttributesFactory.hh" #include "ParticleMacroSize.hh" #include "WaveFunctionAmplitudes.hh" #include "AtomPopulations.hh" #include "pq_coordinates.hh" #include "part_time.hh" #include "Evolution.hh" #include "LostParticleAttributes.hh" #include "ParticlePhaseAttributes.hh" ParticleAttributesFactory::ParticleAttributesFactory() { } ParticleAttributesFactory::~ParticleAttributesFactory() { } ParticleAttributes* ParticleAttributesFactory::getParticleAttributesInstance( const string name, std::map<std::string,double> params_dict, Bunch* bunch) { //for MPI --- start int rank_MPI = 0; int size_MPI = 1; int iMPIini = 0; MPI_Comm MPI_COMM_Local = bunch->getMPI_Comm_Local()->comm; ORBIT_MPI_Initialized(&iMPIini); if(iMPIini > 0){ ORBIT_MPI_Comm_size(MPI_COMM_Local, &size_MPI); ORBIT_MPI_Comm_rank(MPI_COMM_Local, &rank_MPI); } //for MPI --- stop ParticleAttributes* part_atrs = NULL; if(name == "empty"){ part_atrs = new ParticleAttributes(bunch,0); } if(name == "macrosize"){ part_atrs = new ParticleMacroSize(bunch); } if(name == "LostParticleAttributes"){ part_atrs = new LostParticleAttributes(bunch); } if(name == "ParticlePhaseAttributes"){ part_atrs = new ParticlePhaseAttributes(bunch); } if(name == "Amplitudes"){ if(params_dict.size() == 0){ cout<<"dictionary Amplitudes(dict) should be defined "<<"\n"; } else { if(params_dict.count("size") == 1){ part_atrs = new WaveFunctionAmplitudes(bunch,(int) params_dict["size"]); } else { if(rank_MPI == 0){ std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl; std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl; std::cerr << "MPI size="<< size_MPI << std::endl; std::cerr << "MPI rank="<< rank_MPI << std::endl; std::cerr << "attr. name:"<< name << std::endl; std::cerr << "There is no <size> specification in the dict. "<< std::endl; } ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop."); } } } if(name == "Populations"){ if(params_dict.size() == 0){ cout<<"dictionary AtomPopulations(dict) should be defined "<<"\n"; } else { if(params_dict.count("size") == 1){ part_atrs = new AtomPopulations(bunch,(int) params_dict["size"]); } else { if(rank_MPI == 0){ std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl; std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl; std::cerr << "MPI size="<< size_MPI << std::endl; std::cerr << "MPI rank="<< rank_MPI << std::endl; std::cerr << "attr. name:"<< name << std::endl; std::cerr << "There is no <size> specification in the dict. "<< std::endl; } ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop."); } } } if(name == "pq_coords"){ if(params_dict.size() == 0){ cout<<"dictionary pq_coords(dict) should be defined "<<"\n"; } else { if(params_dict.count("size") == 1){ part_atrs = new pq_coordinates(bunch,(int) params_dict["size"]); } else { if(rank_MPI == 0){ std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl; std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl; std::cerr << "MPI size="<< size_MPI << std::endl; std::cerr << "MPI rank="<< rank_MPI << std::endl; std::cerr << "attr. name:"<< name << std::endl; std::cerr << "There is no <size> specification in the dict. "<< std::endl; } ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop."); } } } if(name == "part_time"){ if(params_dict.size() == 0){ cout<<"dictionary prf_time(dict) should be defined "<<"\n"; } else { if(params_dict.count("size") == 1){ part_atrs = new part_time(bunch, (int)params_dict["size"]); } else { if(rank_MPI == 0){ std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl; std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl; std::cerr << "MPI size="<< size_MPI << std::endl; std::cerr << "MPI rank="<< rank_MPI << std::endl; std::cerr << "attr. name:"<< name << std::endl; std::cerr << "There is no <size> specification in the dict. "<< std::endl; } ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop."); } } } if(name == "Evolution"){ if(params_dict.size() == 0){ cout<<"dictionary Evolution(dict) should be defined "<<"\n"; } else { if(params_dict.count("size") == 1){ part_atrs = new Evolution(bunch, (int) params_dict["size"]); } else { if(rank_MPI == 0){ std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(name,dict)"<< std::endl; std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl; std::cerr << "MPI size="<< size_MPI << std::endl; std::cerr << "MPI rank="<< rank_MPI << std::endl; std::cerr << "attr. name:"<< name << std::endl; std::cerr << "There is no <size> specification in the dict. "<< std::endl; } ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop."); } } } if(part_atrs == NULL) { if(rank_MPI == 0){ std::cerr << "ParticleAttributesFactory::getParticleAttributesInstance(const string name, Bunch* bunch)"<< std::endl; std::cerr << "MPI Communicator="<< MPI_COMM_Local << std::endl; std::cerr << "MPI size="<< size_MPI << std::endl; std::cerr << "MPI rank="<< rank_MPI << std::endl; std::cerr << "There is not a particle attirubutes class with such name in the Factory."<< std::endl; std::cerr << "attr. name:"<< name << std::endl; } ORBIT_MPI_Finalize("ParticleAttributesFactory::getParticleAttributesInstance. Stop."); return part_atrs; } //copy the particle attributes dictionary part_atrs->parameterDict = params_dict; part_atrs->parameterDict["size"] = part_atrs->getAttSize(); return part_atrs; } void ParticleAttributesFactory::getParticleAttributesNames(std::vector<string>& names){ names.clear(); names.push_back("macrosize"); names.push_back("Amplitudes"); names.push_back("Populations"); names.push_back("pq_coords"); names.push_back("part_time"); names.push_back("Evolution"); names.push_back("LostParticleAttributes"); names.push_back("ParticlePhaseAttributes"); } <|endoftext|>
<commit_before>// // Configurable.h // Clock Signal // // Created by Thomas Harte on 17/11/2017. // Copyright Β© 2017 Thomas Harte. All rights reserved. // #ifndef Configurable_h #define Configurable_h #include <map> #include <string> #include <vector> namespace Configurable { /*! The Option class hierarchy provides a way for components, machines, etc, to provide a named list of typed options to which they can respond. */ struct Option { std::string long_name; std::string short_name; virtual ~Option() {} Option(const std::string &long_name, const std::string &short_name) : long_name(long_name), short_name(short_name) {} }; struct BooleanOption: public Option { BooleanOption(const std::string &long_name, const std::string &short_name) : Option(long_name, short_name) {} }; struct ListOption: public Option { std::vector<std::string> options; ListOption(const std::string &long_name, const std::string &short_name, const std::vector<std::string> &options) : Option(long_name, short_name), options(options) {} }; /*! Selections are responses to Options. */ struct Selection { virtual ~Selection() {} }; struct BooleanSelection: public Selection { bool value; BooleanSelection(bool value) : value(value) {} }; struct ListSelection: public Selection { std::string value; ListSelection(const std::string value) : value(value) {} }; using SelectionSet = std::map<std::string, std::unique_ptr<Selection>>; /*! A Configuratble provides the options that it responds to and allows selections to be set. */ struct Device { virtual std::vector<std::unique_ptr<Option>> get_options() = 0; virtual void set_selections(const SelectionSet &selection_by_option) = 0; virtual SelectionSet get_accurate_selections() = 0; virtual SelectionSet get_user_friendly_selections() = 0; }; template <typename T> T *selection(const Configurable::SelectionSet &selections_by_option, const std::string &name) { auto selection = selections_by_option.find(name); if(selection == selections_by_option.end()) return nullptr; return dynamic_cast<T *>(selection->second.get()); } } #endif /* Configurable_h */ <commit_msg>Adds missing #include.<commit_after>// // Configurable.h // Clock Signal // // Created by Thomas Harte on 17/11/2017. // Copyright Β© 2017 Thomas Harte. All rights reserved. // #ifndef Configurable_h #define Configurable_h #include <map> #include <memory> #include <string> #include <vector> namespace Configurable { /*! The Option class hierarchy provides a way for components, machines, etc, to provide a named list of typed options to which they can respond. */ struct Option { std::string long_name; std::string short_name; virtual ~Option() {} Option(const std::string &long_name, const std::string &short_name) : long_name(long_name), short_name(short_name) {} }; struct BooleanOption: public Option { BooleanOption(const std::string &long_name, const std::string &short_name) : Option(long_name, short_name) {} }; struct ListOption: public Option { std::vector<std::string> options; ListOption(const std::string &long_name, const std::string &short_name, const std::vector<std::string> &options) : Option(long_name, short_name), options(options) {} }; /*! Selections are responses to Options. */ struct Selection { virtual ~Selection() {} }; struct BooleanSelection: public Selection { bool value; BooleanSelection(bool value) : value(value) {} }; struct ListSelection: public Selection { std::string value; ListSelection(const std::string value) : value(value) {} }; using SelectionSet = std::map<std::string, std::unique_ptr<Selection>>; /*! A Configuratble provides the options that it responds to and allows selections to be set. */ struct Device { virtual std::vector<std::unique_ptr<Option>> get_options() = 0; virtual void set_selections(const SelectionSet &selection_by_option) = 0; virtual SelectionSet get_accurate_selections() = 0; virtual SelectionSet get_user_friendly_selections() = 0; }; template <typename T> T *selection(const Configurable::SelectionSet &selections_by_option, const std::string &name) { auto selection = selections_by_option.find(name); if(selection == selections_by_option.end()) return nullptr; return dynamic_cast<T *>(selection->second.get()); } } #endif /* Configurable_h */ <|endoftext|>
<commit_before>/* * Global PRNG * (C) 2008-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/libstate.h> #include <botan/mutex.h> #if defined(BOTAN_HAS_RANDPOOL) #include <botan/randpool.h> #endif #if defined(BOTAN_HAS_HMAC_RNG) #include <botan/hmac_rng.h> #endif #if defined(BOTAN_HAS_X931_RNG) #include <botan/x931_rng.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_HIGH_RESOLUTION_TIMER) #include <botan/internal/hres_timer.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_DEV_RANDOM) #include <botan/internal/dev_random.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_EGD) #include <botan/internal/es_egd.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_UNIX) #include <botan/internal/es_unix.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_BEOS) #include <botan/internal/es_beos.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_CAPI) #include <botan/internal/es_capi.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_WIN32) #include <botan/internal/es_win32.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_FTW) #include <botan/internal/es_ftw.h> #endif namespace Botan { namespace { /** * Add any known entropy sources to this RNG */ void add_entropy_sources(RandomNumberGenerator* rng) { #if defined(BOTAN_HAS_ENTROPY_SRC_HIGH_RESOLUTION_TIMER) rng->add_entropy_source(new High_Resolution_Timestamp); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_DEV_RANDOM) rng->add_entropy_source( new Device_EntropySource( split_on("/dev/urandom:/dev/random:/dev/srandom", ':') ) ); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_EGD) rng->add_entropy_source( new EGD_EntropySource(split_on("/var/run/egd-pool:/dev/egd-pool", ':')) ); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_CAPI) rng->add_entropy_source(new Win32_CAPI_EntropySource); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_FTW) rng->add_entropy_source(new FTW_EntropySource("/proc")); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_WIN32) rng->add_entropy_source(new Win32_EntropySource); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_BEOS) rng->add_entropy_source(new BeOS_EntropySource); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_UNIX) rng->add_entropy_source( new Unix_EntropySource(split_on("/bin:/sbin:/usr/bin:/usr/sbin", ':')) ); #endif } class Serialized_PRNG : public RandomNumberGenerator { public: void randomize(byte out[], u32bit len) { Mutex_Holder lock(mutex); rng->randomize(out, len); } bool is_seeded() const { Mutex_Holder lock(mutex); return rng->is_seeded(); } void clear() { Mutex_Holder lock(mutex); rng->clear(); } std::string name() const { Mutex_Holder lock(mutex); return rng->name(); } void reseed(u32bit poll_bits) { Mutex_Holder lock(mutex); rng->reseed(poll_bits); } void add_entropy_source(EntropySource* es) { Mutex_Holder lock(mutex); rng->add_entropy_source(es); } void add_entropy(const byte in[], u32bit len) { Mutex_Holder lock(mutex); rng->add_entropy(in, len); } // We do not own the mutex; Library_State does Serialized_PRNG(RandomNumberGenerator* r, Mutex* m) : mutex(m), rng(r) {} ~Serialized_PRNG() { delete rng; } private: Mutex* mutex; RandomNumberGenerator* rng; }; } RandomNumberGenerator* Library_State::make_global_rng(Algorithm_Factory& af, Mutex* mutex) { RandomNumberGenerator* rng = 0; #if defined(BOTAN_HAS_HMAC_RNG) rng = new HMAC_RNG(af.make_mac("HMAC(SHA-512)"), af.make_mac("HMAC(SHA-256)")); #elif defined(BOTAN_HAS_RANDPOOL) rng = new Randpool(af.make_block_cipher("AES-256"), af.make_mac("HMAC(SHA-256)")); #endif if(!rng) throw Internal_Error("No usable RNG found enabled in build"); /* If X9.31 is available, use it to wrap the other RNG as a failsafe */ #if defined(BOTAN_HAS_X931_RNG) rng = new ANSI_X931_RNG(af.make_block_cipher("AES-256"), rng); #endif add_entropy_sources(rng); rng->reseed(256); return new Serialized_PRNG(rng, mutex); } } <commit_msg>mutex.h is internal - had been picking up system installed version<commit_after>/* * Global PRNG * (C) 2008-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/libstate.h> #include <botan/internal/mutex.h> #if defined(BOTAN_HAS_RANDPOOL) #include <botan/randpool.h> #endif #if defined(BOTAN_HAS_HMAC_RNG) #include <botan/hmac_rng.h> #endif #if defined(BOTAN_HAS_X931_RNG) #include <botan/x931_rng.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_HIGH_RESOLUTION_TIMER) #include <botan/internal/hres_timer.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_DEV_RANDOM) #include <botan/internal/dev_random.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_EGD) #include <botan/internal/es_egd.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_UNIX) #include <botan/internal/es_unix.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_BEOS) #include <botan/internal/es_beos.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_CAPI) #include <botan/internal/es_capi.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_WIN32) #include <botan/internal/es_win32.h> #endif #if defined(BOTAN_HAS_ENTROPY_SRC_FTW) #include <botan/internal/es_ftw.h> #endif namespace Botan { namespace { /** * Add any known entropy sources to this RNG */ void add_entropy_sources(RandomNumberGenerator* rng) { #if defined(BOTAN_HAS_ENTROPY_SRC_HIGH_RESOLUTION_TIMER) rng->add_entropy_source(new High_Resolution_Timestamp); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_DEV_RANDOM) rng->add_entropy_source( new Device_EntropySource( split_on("/dev/urandom:/dev/random:/dev/srandom", ':') ) ); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_EGD) rng->add_entropy_source( new EGD_EntropySource(split_on("/var/run/egd-pool:/dev/egd-pool", ':')) ); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_CAPI) rng->add_entropy_source(new Win32_CAPI_EntropySource); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_FTW) rng->add_entropy_source(new FTW_EntropySource("/proc")); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_WIN32) rng->add_entropy_source(new Win32_EntropySource); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_BEOS) rng->add_entropy_source(new BeOS_EntropySource); #endif #if defined(BOTAN_HAS_ENTROPY_SRC_UNIX) rng->add_entropy_source( new Unix_EntropySource(split_on("/bin:/sbin:/usr/bin:/usr/sbin", ':')) ); #endif } class Serialized_PRNG : public RandomNumberGenerator { public: void randomize(byte out[], u32bit len) { Mutex_Holder lock(mutex); rng->randomize(out, len); } bool is_seeded() const { Mutex_Holder lock(mutex); return rng->is_seeded(); } void clear() { Mutex_Holder lock(mutex); rng->clear(); } std::string name() const { Mutex_Holder lock(mutex); return rng->name(); } void reseed(u32bit poll_bits) { Mutex_Holder lock(mutex); rng->reseed(poll_bits); } void add_entropy_source(EntropySource* es) { Mutex_Holder lock(mutex); rng->add_entropy_source(es); } void add_entropy(const byte in[], u32bit len) { Mutex_Holder lock(mutex); rng->add_entropy(in, len); } // We do not own the mutex; Library_State does Serialized_PRNG(RandomNumberGenerator* r, Mutex* m) : mutex(m), rng(r) {} ~Serialized_PRNG() { delete rng; } private: Mutex* mutex; RandomNumberGenerator* rng; }; } RandomNumberGenerator* Library_State::make_global_rng(Algorithm_Factory& af, Mutex* mutex) { RandomNumberGenerator* rng = 0; #if defined(BOTAN_HAS_HMAC_RNG) rng = new HMAC_RNG(af.make_mac("HMAC(SHA-512)"), af.make_mac("HMAC(SHA-256)")); #elif defined(BOTAN_HAS_RANDPOOL) rng = new Randpool(af.make_block_cipher("AES-256"), af.make_mac("HMAC(SHA-256)")); #endif if(!rng) throw Internal_Error("No usable RNG found enabled in build"); /* If X9.31 is available, use it to wrap the other RNG as a failsafe */ #if defined(BOTAN_HAS_X931_RNG) rng = new ANSI_X931_RNG(af.make_block_cipher("AES-256"), rng); #endif add_entropy_sources(rng); rng->reseed(256); return new Serialized_PRNG(rng, mutex); } } <|endoftext|>
<commit_before>/* * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org) * * 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 <votca/xtp/kmccalculator.h> #include <votca/xtp/gnode.h> #include <votca/tools/constants.h> #include <boost/format.hpp> #include <votca/ctp/topology.h> #include <locale> using namespace std; namespace votca { namespace xtp { KMCCalculator::KMCCalculator(){}; void KMCCalculator::LoadGraph(ctp::Topology *top) { std::vector< ctp::Segment* >& seg = top->Segments(); if(seg.size()<1){ throw std::runtime_error("Your sql file contains no segments!"); } for (unsigned i = 0; i < seg.size(); i++) { GNode *newNode = new GNode(); newNode->ReadfromSegment(seg[i], _carriertype); if (tools::wildcmp(_injection_name.c_str(), seg[i]->getName().c_str())) { newNode->injectable = true; } else { newNode->injectable = false; } _nodes.push_back(newNode); } ctp::QMNBList &nblist = top->NBList(); if(nblist.size()<1){ throw std::runtime_error("Your sql file contains no pairs!"); } for (ctp::QMNBList::iterator it = nblist.begin(); it < nblist.end(); ++it) { _nodes[(*it)->Seg1()->getId()-1]->AddEventfromQmPair(*it, _carriertype); _nodes[(*it)->Seg2()->getId()-1]->AddEventfromQmPair(*it, _carriertype); } unsigned events=0; unsigned max=std::numeric_limits<unsigned>::min(); unsigned min=std::numeric_limits<unsigned>::max(); minlength=std::numeric_limits<double>::max(); double maxlength=0; for(const auto& node:_nodes){ unsigned size=node->events.size(); for( const auto& event:node->events){ if(event.decayevent){continue;} double dist=abs(event.dr); if(dist>maxlength){ maxlength=dist; } else if(dist<minlength){ minlength=dist; } } events+=size; if(size==0){ cout<<"Node "<<node->id<<" has 0 jumps"<<endl; } else if(size<min){ min=size; } else if(size>max){ max=size; } } double avg=double(events)/double(_nodes.size()); double deviation=0.0; for(const auto& node:_nodes){ double size=node->events.size(); deviation+=(size-avg)*(size-avg); } deviation=std::sqrt(deviation/double(_nodes.size())); cout<<"Nblist has "<<nblist.size()<<" pairs. Nodes contain "<<events<<" jump events"<<endl; cout<<"with avg="<<avg<<" std="<<deviation<<" max="<<max<<" min="<<min<<endl; cout<<"Minimum jumpdistance ="<<minlength<<" nm Maximum distance ="<<maxlength<<" nm"<<endl; cout<<"Grouping into "<<lengthdistribution<<" boxes"<<endl; lengthresolution=(1.00001*maxlength-minlength)/double(lengthdistribution); cout<<"Resolution is "<<lengthresolution<<" nm"<<endl; _jumplengthdistro=std::vector<long unsigned>(lengthdistribution,0); _jumplengthdistro_weighted=std::vector<double>(lengthdistribution,0); cout << "spatial density: " << _numberofcharges / top->BoxVolume() << " nm^-3" << endl; for (unsigned int i = 0; i < _nodes.size(); i++) { _nodes[i]->InitEscapeRate(); _nodes[i]->MakeHuffTree(); } return; } void KMCCalculator::ResetForbiddenlist(std::vector<int> &forbiddenid) { forbiddenid.clear(); return; } void KMCCalculator::AddtoForbiddenlist(int id, std::vector<int> &forbiddenid) { forbiddenid.push_back(id); return; } bool KMCCalculator::CheckForbidden(int id,const std::vector<int> &forbiddenlist) { bool forbidden = false; for (unsigned int i = 0; i < forbiddenlist.size(); i++) { if (id == forbiddenlist[i]) { forbidden = true; break; } } return forbidden; } bool KMCCalculator::CheckSurrounded(GNode* node,const std::vector<int> & forbiddendests) { bool surrounded = true; for (unsigned i = 0; i < node->events.size(); i++) { bool thisevent_possible = true; for (unsigned int j = 0; j < forbiddendests.size(); j++) { if (node->events[i].destination == forbiddendests[j]) { thisevent_possible = false; break; } } if (thisevent_possible == true) { surrounded = false; break; } } return surrounded; } std::string KMCCalculator::CarrierInttoLongString(int carriertype){ std::string name=""; if (carriertype==-1){ name="electron"; } else if(carriertype==1){ name="hole"; } else if(carriertype==2){ name="singlet"; } else if(carriertype==3){ name="triplet"; } else{ throw runtime_error((boost::format("Carriertype %i not known") % carriertype).str()); } return name; } std::string KMCCalculator::CarrierInttoShortString(int carriertype){ std::string name=""; if (carriertype==-1){ name="e"; } else if(carriertype==1){ name="h"; } else if(carriertype==2){ name="s"; } else if(carriertype==3){ name="t"; } else{ throw runtime_error((boost::format("Carriertype %i not known") % carriertype).str()); } return name; } int KMCCalculator::StringtoCarriertype(std::string name){ char firstcharacter=std::tolower(name.at(0), std::locale()); int carriertype=0; if (firstcharacter=='e'){ carriertype=-1; } else if(firstcharacter=='h'){ carriertype=1; } else if(firstcharacter=='s'){ carriertype=2; } else if(firstcharacter=='t'){ carriertype=3; } else{ throw runtime_error((boost::format("Carriername %s not known") % name).str()); } return carriertype; } void KMCCalculator::RandomlyCreateCharges(){ cout << "looking for injectable nodes..." << endl; for (unsigned int i = 0; i < _numberofcharges; i++) { Chargecarrier *newCharge = new Chargecarrier; newCharge->id = i; RandomlyAssignCarriertoSite(newCharge); cout << "starting position for charge " << i + 1 << ": segment " << newCharge->getCurrentNodeId()+1 << endl; _carriers.push_back(newCharge); } return; } void KMCCalculator::RandomlyAssignCarriertoSite(Chargecarrier* Charge){ int nodeId_guess=-1; do{ nodeId_guess=_RandomVariable.rand_uniform_int(_nodes.size()); } while (_nodes[nodeId_guess]->occupied || _nodes[nodeId_guess]->injectable==false ); // maybe already occupied? or maybe not injectable? if (Charge->hasNode()){ Charge->jumpfromCurrentNodetoNode(_nodes[nodeId_guess]); } else{ Charge->settoNote(_nodes[nodeId_guess]); } return; } void KMCCalculator::InitialRates() { cout << endl << "Calculating initial Marcus rates." << endl; cout << " Temperature T = " << _temperature << " K." << endl; cout << " carriertype: " << CarrierInttoLongString(_carriertype) << endl; unsigned numberofsites = _nodes.size(); cout << " Rates for " << numberofsites << " sites are computed." << endl; double charge=0.0; if (_carriertype == -1) { charge = -1.0; } else if (_carriertype == 1) { charge = 1.0; } cout<<"electric field ="<<_field<<" V/nm"<<endl; double maxreldiff = 0; double maxrate=0; double minrate=std::numeric_limits<double>::max(); int totalnumberofrates = 0; for (unsigned int i = 0; i < numberofsites; i++) { unsigned numberofneighbours = _nodes[i]->events.size(); for (unsigned int j = 0; j < numberofneighbours; j++) { if(_nodes[i]->events[j].decayevent){ //if event is a decay event there is no point in calculating its rate, because it already has that from the reading in. continue; } double destindex = _nodes[i]->events[j].destination; double reorg = _nodes[i]->reorg_intorig + _nodes[destindex]->reorg_intdest + _nodes[i]->events[j].reorg_out; if(std::abs(reorg)<1e-12){ throw std::runtime_error("Reorganisation energy for a pair is extremly close to zero,\n" " you probably forgot to import reorganisation energies into your sql file."); } double dG_Field =0.0; if(charge!=0.0){ dG_Field=charge * (_nodes[i]->events[j].dr*_field); } double dG_Site = _nodes[destindex]->siteenergy - _nodes[i]->siteenergy; double dG=dG_Site-dG_Field; double J2 = _nodes[i]->events[j].Jeff2; double rate = 2 * tools::conv::Pi / tools::conv::hbar * J2 / sqrt(4 * tools::conv::Pi * reorg * tools::conv::kB * _temperature) * exp(-(dG + reorg)*(dG + reorg) / (4 * reorg * tools::conv::kB * _temperature)); // calculate relative difference compared to values in the table double reldiff = (_nodes[i]->events[j].rate - rate) / _nodes[i]->events[j].rate; if (reldiff > maxreldiff) { maxreldiff = reldiff; } reldiff = (_nodes[i]->events[j].rate - rate) / rate; if (reldiff > maxreldiff) { maxreldiff = reldiff; } // set rates to calculated values _nodes[i]->events[j].rate = rate; _nodes[i]->events[j].initialrate = rate; if(rate>maxrate){ maxrate=rate; } else if(rate<minrate){ minrate=rate; } totalnumberofrates++; } } // Initialise escape rates for (auto* node:_nodes) { node->InitEscapeRate(); node->MakeHuffTree(); } cout << " " << totalnumberofrates << " rates have been calculated." << endl; cout<< " Largest rate="<<maxrate<<" 1/s Smallest rate="<<minrate<<" 1/s"<<endl; if (maxreldiff < 0.01) { cout << " Good agreement with rates in the state file. Maximal relative difference: " << maxreldiff * 100 << " %" << endl; } else { cout << " WARNING: Rates differ from those in the state file up to " << maxreldiff * 100 << " %." << " If the rates in the state file are calculated for a different temperature/field or if they are not Marcus rates, this is fine. Otherwise something might be wrong here." << endl; } return; } double KMCCalculator::Promotetime(double cumulated_rate){ double dt = 0; double rand_u = 1 - _RandomVariable.rand_uniform(); while (rand_u == 0) { cout << "WARNING: encountered 0 as a random variable! New try." << endl; rand_u = 1 - _RandomVariable.rand_uniform(); } dt = -1 / cumulated_rate * log(rand_u); return dt; } GLink* KMCCalculator::ChooseHoppingDest(GNode* node){ double u = 1 - _RandomVariable.rand_uniform(); return node->findHoppingDestination(u); } Chargecarrier* KMCCalculator::ChooseAffectedCarrier(double cumulated_rate){ if(_carriers.size()==1){ return _carriers[0]; } Chargecarrier* carrier=NULL; double u = 1 - _RandomVariable.rand_uniform(); for (unsigned int i = 0; i < _numberofcharges; i++) { u -= _carriers[i]->getCurrentEscapeRate() / cumulated_rate; if (u <= 0 || i==_numberofcharges-1) { carrier = _carriers[i]; break;} } return carrier; } void KMCCalculator::AddtoJumplengthdistro(const GLink* event,double dt){ if(dolengthdistributon){ double dist=abs(event->dr)-minlength; int index=int(dist/lengthresolution); _jumplengthdistro[index]++; _jumplengthdistro_weighted[index]+=dt; } return; } void KMCCalculator::PrintJumplengthdistro(){ if(dolengthdistributon){ long unsigned noofjumps=0; double weightedintegral=0; for(unsigned i=0;i<_jumplengthdistro.size();++i){ noofjumps+=_jumplengthdistro[i]; weightedintegral+=_jumplengthdistro_weighted[i]; } double noofjumps_double=double(noofjumps); cout<<"Total number of jumps: "<<noofjumps<<endl; cout<<" distance[nm] | # of jumps | # of jumps [%] | .w. by dist [nm] | w. by timestep [%]"<<endl; cout<<"------------------------------------------------------------------------------------"<<endl; for(unsigned i=0;i<_jumplengthdistro.size();++i){ double dist=lengthresolution*(i+0.5)+minlength; double percent=_jumplengthdistro[i]/noofjumps_double; double rtimespercent=percent*dist; cout<<(boost::format(" %4.3f | %15d | %04.2f | %4.3e | %04.2f") % (dist) % (_jumplengthdistro[i]) % (percent*100) %(rtimespercent) % (_jumplengthdistro_weighted[i]/weightedintegral*100)).str()<<endl; } cout<<"------------------------------------------------------------------------------------"<<endl; } return; } } } <commit_msg>Update kmccalculator.cc<commit_after>/* * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org) * * 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 <votca/xtp/kmccalculator.h> #include <votca/xtp/gnode.h> #include <votca/tools/constants.h> #include <boost/format.hpp> #include <votca/ctp/topology.h> #include <locale> using namespace std; namespace votca { namespace xtp { KMCCalculator::KMCCalculator(){}; void KMCCalculator::LoadGraph(ctp::Topology *top) { std::vector< ctp::Segment* >& seg = top->Segments(); if(seg.size()<1){ throw std::runtime_error("Your sql file contains no segments!"); } for (unsigned i = 0; i < seg.size(); i++) { GNode *newNode = new GNode(); newNode->ReadfromSegment(seg[i], _carriertype); if (tools::wildcmp(_injection_name.c_str(), seg[i]->getName().c_str())) { newNode->injectable = true; } else { newNode->injectable = false; } _nodes.push_back(newNode); } ctp::QMNBList &nblist = top->NBList(); if(nblist.size()<1){ throw std::runtime_error("Your sql file contains no pairs!"); } for (ctp::QMNBList::iterator it = nblist.begin(); it < nblist.end(); ++it) { _nodes[(*it)->Seg1()->getId()-1]->AddEventfromQmPair(*it, _carriertype); _nodes[(*it)->Seg2()->getId()-1]->AddEventfromQmPair(*it, _carriertype); } unsigned events=0; unsigned max=std::numeric_limits<unsigned>::min(); unsigned min=std::numeric_limits<unsigned>::max(); minlength=std::numeric_limits<double>::max(); double maxlength=0; for(const auto& node:_nodes){ unsigned size=node->events.size(); for( const auto& event:node->events){ if(event.decayevent){continue;} double dist=abs(event.dr); if(dist>maxlength){ maxlength=dist; } else if(dist<minlength){ minlength=dist; } } events+=size; if(size==0){ cout<<"Node "<<node->id<<" has 0 jumps"<<endl; } else if(size<min){ min=size; } else if(size>max){ max=size; } } double avg=double(events)/double(_nodes.size()); double deviation=0.0; for(const auto& node:_nodes){ double size=node->events.size(); deviation+=(size-avg)*(size-avg); } deviation=std::sqrt(deviation/double(_nodes.size())); cout<<"Nblist has "<<nblist.size()<<" pairs. Nodes contain "<<events<<" jump events"<<endl; cout<<"with avg="<<avg<<" std="<<deviation<<" max="<<max<<" min="<<min<<endl; cout<<"Minimum jumpdistance ="<<minlength<<" nm Maximum distance ="<<maxlength<<" nm"<<endl; cout<<"Grouping into "<<lengthdistribution<<" boxes"<<endl; lengthresolution=(1.00001*maxlength-minlength)/double(lengthdistribution); cout<<"Resolution is "<<lengthresolution<<" nm"<<endl; _jumplengthdistro=std::vector<long unsigned>(lengthdistribution,0); _jumplengthdistro_weighted=std::vector<double>(lengthdistribution,0); cout << "spatial density: " << _numberofcharges / top->BoxVolume() << " nm^-3" << endl; for (unsigned int i = 0; i < _nodes.size(); i++) { _nodes[i]->InitEscapeRate(); _nodes[i]->MakeHuffTree(); } return; } void KMCCalculator::ResetForbiddenlist(std::vector<int> &forbiddenid) { forbiddenid.clear(); return; } void KMCCalculator::AddtoForbiddenlist(int id, std::vector<int> &forbiddenid) { forbiddenid.push_back(id); return; } bool KMCCalculator::CheckForbidden(int id,const std::vector<int> &forbiddenlist) { // cout << "forbidden list has " << forbiddenlist.size() << " entries" << endl; bool forbidden = false; for (unsigned int i = 0; i < forbiddenlist.size(); i++) { if (id == forbiddenlist[i]) { forbidden = true; //cout << "ID " << id << " has been found as element " << i << " (" << forbiddenlist[i]<< ") in the forbidden list." << endl; break; } } return forbidden; } bool KMCCalculator::CheckSurrounded(GNode* node,const std::vector<int> & forbiddendests) { bool surrounded = true; for (unsigned i = 0; i < node->events.size(); i++) { bool thisevent_possible = true; for (unsigned int j = 0; j < forbiddendests.size(); j++) { if (node->events[i].destination == forbiddendests[j]) { thisevent_possible = false; break; } } if (thisevent_possible == true) { surrounded = false; break; } } return surrounded; } std::string KMCCalculator::CarrierInttoLongString(int carriertype){ std::string name=""; if (carriertype==-1){ name="electron"; } else if(carriertype==1){ name="hole"; } else if(carriertype==2){ name="singlet"; } else if(carriertype==3){ name="triplet"; } else{ throw runtime_error((boost::format("Carriertype %i not known") % carriertype).str()); } return name; } std::string KMCCalculator::CarrierInttoShortString(int carriertype){ std::string name=""; if (carriertype==-1){ name="e"; } else if(carriertype==1){ name="h"; } else if(carriertype==2){ name="s"; } else if(carriertype==3){ name="t"; } else{ throw runtime_error((boost::format("Carriertype %i not known") % carriertype).str()); } return name; } int KMCCalculator::StringtoCarriertype(std::string name){ char firstcharacter=std::tolower(name.at(0), std::locale()); int carriertype=0; if (firstcharacter=='e'){ carriertype=-1; } else if(firstcharacter=='h'){ carriertype=1; } else if(firstcharacter=='s'){ carriertype=2; } else if(firstcharacter=='t'){ carriertype=3; } else{ throw runtime_error((boost::format("Carriername %s not known") % name).str()); } return carriertype; } void KMCCalculator::RandomlyCreateCharges(){ cout << "looking for injectable nodes..." << endl; for (unsigned int i = 0; i < _numberofcharges; i++) { Chargecarrier *newCharge = new Chargecarrier; newCharge->id = i; RandomlyAssignCarriertoSite(newCharge); cout << "starting position for charge " << i + 1 << ": segment " << newCharge->getCurrentNodeId()+1 << endl; _carriers.push_back(newCharge); } return; } void KMCCalculator::RandomlyAssignCarriertoSite(Chargecarrier* Charge){ int nodeId_guess=-1; do{ nodeId_guess=_RandomVariable.rand_uniform_int(_nodes.size()); } while (_nodes[nodeId_guess]->occupied || _nodes[nodeId_guess]->injectable==false ); // maybe already occupied? or maybe not injectable? if (Charge->hasNode()){ Charge->jumpfromCurrentNodetoNode(_nodes[nodeId_guess]); } else{ Charge->settoNote(_nodes[nodeId_guess]); } return; } void KMCCalculator::InitialRates() { cout << endl << "Calculating initial Marcus rates." << endl; cout << " Temperature T = " << _temperature << " K." << endl; cout << " carriertype: " << CarrierInttoLongString(_carriertype) << endl; unsigned numberofsites = _nodes.size(); cout << " Rates for " << numberofsites << " sites are computed." << endl; double charge=0.0; if (_carriertype == -1) { charge = -1.0; } else if (_carriertype == 1) { charge = 1.0; } cout<<"electric field ="<<_field<<" V/nm"<<endl; double maxreldiff = 0; double maxrate=0; double minrate=std::numeric_limits<double>::max(); int totalnumberofrates = 0; for (unsigned int i = 0; i < numberofsites; i++) { unsigned numberofneighbours = _nodes[i]->events.size(); for (unsigned int j = 0; j < numberofneighbours; j++) { if(_nodes[i]->events[j].decayevent){ //if event is a decay event there is no point in calculating its rate, because it already has that from the reading in. continue; } double destindex = _nodes[i]->events[j].destination; double reorg = _nodes[i]->reorg_intorig + _nodes[destindex]->reorg_intdest + _nodes[i]->events[j].reorg_out; if(std::abs(reorg)<1e-12){ throw std::runtime_error("Reorganisation energy for a pair is extremly close to zero,\n" " you probably forgot to import reorganisation energies into your sql file."); } double dG_Field =0.0; if(charge!=0.0){ dG_Field=charge * (_nodes[i]->events[j].dr*_field); } double dG_Site = _nodes[destindex]->siteenergy - _nodes[i]->siteenergy; double dG=dG_Site-dG_Field; double J2 = _nodes[i]->events[j].Jeff2; double rate = 2 * tools::conv::Pi / tools::conv::hbar * J2 / sqrt(4 * tools::conv::Pi * reorg * tools::conv::kB * _temperature) * exp(-(dG + reorg)*(dG + reorg) / (4 * reorg * tools::conv::kB * _temperature)); // calculate relative difference compared to values in the table double reldiff = (_nodes[i]->events[j].rate - rate) / _nodes[i]->events[j].rate; if (reldiff > maxreldiff) { maxreldiff = reldiff; } reldiff = (_nodes[i]->events[j].rate - rate) / rate; if (reldiff > maxreldiff) { maxreldiff = reldiff; } // set rates to calculated values _nodes[i]->events[j].rate = rate; _nodes[i]->events[j].initialrate = rate; if(rate>maxrate){ maxrate=rate; } else if(rate<minrate){ minrate=rate; } totalnumberofrates++; } } // Initialise escape rates for (auto* node:_nodes) { node->InitEscapeRate(); node->MakeHuffTree(); } cout << " " << totalnumberofrates << " rates have been calculated." << endl; cout<< " Largest rate="<<maxrate<<" 1/s Smallest rate="<<minrate<<" 1/s"<<endl; if (maxreldiff < 0.01) { cout << " Good agreement with rates in the state file. Maximal relative difference: " << maxreldiff * 100 << " %" << endl; } else { cout << " WARNING: Rates differ from those in the state file up to " << maxreldiff * 100 << " %." << " If the rates in the state file are calculated for a different temperature/field or if they are not Marcus rates, this is fine. Otherwise something might be wrong here." << endl; } return; } double KMCCalculator::Promotetime(double cumulated_rate){ double dt = 0; double rand_u = 1 - _RandomVariable.rand_uniform(); while (rand_u == 0) { cout << "WARNING: encountered 0 as a random variable! New try." << endl; rand_u = 1 - _RandomVariable.rand_uniform(); } dt = -1 / cumulated_rate * log(rand_u); return dt; } GLink* KMCCalculator::ChooseHoppingDest(GNode* node){ double u = 1 - _RandomVariable.rand_uniform(); return node->findHoppingDestination(u); } Chargecarrier* KMCCalculator::ChooseAffectedCarrier(double cumulated_rate){ if(_carriers.size()==1){ return _carriers[0]; } Chargecarrier* carrier=NULL; double u = 1 - _RandomVariable.rand_uniform(); for (unsigned int i = 0; i < _numberofcharges; i++) { u -= _carriers[i]->getCurrentEscapeRate() / cumulated_rate; if (u <= 0 || i==_numberofcharges-1) { carrier = _carriers[i]; break;} } return carrier; } void KMCCalculator::AddtoJumplengthdistro(const GLink* event,double dt){ if(dolengthdistributon){ double dist=abs(event->dr)-minlength; int index=int(dist/lengthresolution); _jumplengthdistro[index]++; _jumplengthdistro_weighted[index]+=dt; } return; } void KMCCalculator::PrintJumplengthdistro(){ if(dolengthdistributon){ long unsigned noofjumps=0; double weightedintegral=0; for(unsigned i=0;i<_jumplengthdistro.size();++i){ noofjumps+=_jumplengthdistro[i]; weightedintegral+=_jumplengthdistro_weighted[i]; } double noofjumps_double=double(noofjumps); cout<<"Total number of jumps: "<<noofjumps<<endl; cout<<" distance[nm] | # of jumps | # of jumps [%] | .w. by dist [nm] | w. by timestep [%]"<<endl; cout<<"------------------------------------------------------------------------------------"<<endl; for(unsigned i=0;i<_jumplengthdistro.size();++i){ double dist=lengthresolution*(i+0.5)+minlength; double percent=_jumplengthdistro[i]/noofjumps_double; double rtimespercent=percent*dist; cout<<(boost::format(" %4.3f | %15d | %04.2f | %4.3e | %04.2f") % (dist) % (_jumplengthdistro[i]) % (percent*100) %(rtimespercent) % (_jumplengthdistro_weighted[i]/weightedintegral*100)).str()<<endl; } cout<<"------------------------------------------------------------------------------------"<<endl; } return; } } } <|endoftext|>
<commit_before>#include <iostream> using namespace std; int main() { cout << "Hola mundo" << endl; }<commit_msg>Ahora pregunta el nombre.<commit_after>#include <iostream> #include <string> using namespace std; int main() { string nombre; cout << "ΒΏComo te llamas? " << endl; cin >> nombre; cout << "Hola " << nombre << endl; }<|endoftext|>
<commit_before><commit_msg>Missing include<commit_after><|endoftext|>
<commit_before>#include "flDisplayObjectContainer.h" namespace fl2d { //============================================================== // Constructor / Destructor //============================================================== //-------------------------------------------------------------- flDisplayObjectContainer::flDisplayObjectContainer() { _typeID = FL_TYPE_DISPLAY_OBJECT_CONTAINER; _target = this; name("flDisplayObjectContainer"); _mouseChildren = true; //_tabChildren = false; } //-------------------------------------------------------------- flDisplayObjectContainer::~flDisplayObjectContainer() { _target = NULL; children.clear(); _mouseChildren = false; //_tabChildren = false; } //============================================================== // Setup / Update / Draw //============================================================== //-------------------------------------------------------------- void flDisplayObjectContainer::update() { // float tempLeft = _rect->left(); // float tempRight = _rect->right(); // float tempTop = _rect->top(); // float tempBottom = _rect->bottom(); // // _rect->_setToPoint(0, 0); // int i; int l; // flDisplayObject* child; // // l = children.size(); // for(i = 0; i < l; i++) { // child = children[i]; // float n1 = child->x(); // float n2 = child->y(); // _rect->__expandTo(n1, n2); // _rect->__expandTo(n1 + child->width(), n2 + child->height()); // } // _rect->__expandTo(tempLeft, tempTop); // _rect->__expandTo(tempRight, tempBottom); flDisplayObject::update(); } //-------------------------------------------------------------- void flDisplayObjectContainer::draw(bool applyMatrix) { if(!visible() && applyMatrix) return; // save off current state of blend enabled GLboolean blendEnabled; glGetBooleanv(GL_BLEND, &blendEnabled); // save off current state of src / dst blend functions GLint blendSrc; GLint blendDst; glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrc); glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDst); ofEnableAlphaBlending(); GLboolean preLighting = glIsEnabled(GL_LIGHTING); GLboolean preDepthTest = glIsEnabled(GL_DEPTH_TEST); GLboolean preLineSmooth = glIsEnabled(GL_LINE_SMOOTH); GLboolean preMultiSample = glIsEnabled(GL_MULTISAMPLE); ofDisableLighting(); glDisable(GL_DEPTH_TEST); if(_enabledSmoothing) { ofEnableSmoothing(); } else { ofDisableSmoothing(); } if(_enabledAntiAliasing) { ofEnableAntiAliasing(); } else { ofDisableAntiAliasing(); } //------------------------------------------ //-- matrix transform. // bool bIdentity = true; // bIdentity = matrix().isIdentity(); // bIdentity = false; if(applyMatrix){ // glPushMatrix(); ofPushMatrix(); // glMultMatrixf(matrix().getPtr()); ofMultMatrix(_transform.matrix().getPtr()); } ofPushStyle(); // ofSetColor(255, 255, 255, 255 * _compoundAlpha); _draw(); for(int i = 0; i < children.size(); i++) { flDisplayObject* child; child = children[i]; //child->drawOnFrame(); child->draw(); } ofPopStyle(); if(applyMatrix){ // glPopMatrix(); ofPopMatrix(); } //------------------------------------------ if(preMultiSample == GL_TRUE) { ofEnableAntiAliasing(); } else { ofDisableAntiAliasing(); } if(preLineSmooth == GL_TRUE) { ofEnableSmoothing(); } else { ofDisableSmoothing(); } if(preDepthTest == GL_TRUE) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } if(preLighting == GL_TRUE) { ofEnableLighting(); } else { ofDisableLighting(); } // restore saved state of blend enabled and blend functions if (blendEnabled) { glEnable(GL_BLEND); } else { glDisable(GL_BLEND); } glBlendFunc(blendSrc, blendDst); } //============================================================== // Public Method //============================================================== //-------------------------------------------------------------- bool flDisplayObjectContainer::mouseChildren() { return _mouseChildren; } void flDisplayObjectContainer::mouseChildren(bool value) { _mouseChildren = value; } //-------------------------------------------------------------- int flDisplayObjectContainer::numChildren() { return children.size(); } //-------------------------------------------------------------- bool flDisplayObjectContainer::contains(flDisplayObject* child) { for(int i = 0; i < children.size(); i++) { if(children[i] == child) return true; } return false; } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::stage() { return _stage; } void flDisplayObjectContainer::stage(flDisplayObject* value) { //cout << "[flDisplayObjectContainer]stage(" << value << ")" << name() << endl; //΁valueL΁ if(!_stage && value) { _stage = value; flEvent* event = new flEvent(flEvent::ADDED_TO_STAGE); // event->target(_target); dispatchEvent(event); } //L΁valueL΁ if(_stage && !value) { _stage = value; flEvent* event = new flEvent(flEvent::REMOVED_FROM_STAGE); // event->target(_target); dispatchEvent(event); } for(int i = 0; i < children.size(); i++) { flDisplayObject* displayObject = children[i]; displayObject->stage(_stage); } } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::addChild(flDisplayObject* child) { // cout << "[flDisplayObjectContainer]addChild((" << child->name() << ")" << endl; //if(child == NULL) throw "TypeError: Error #2007: child null ρ˜"; if(child->parent()){ ((flDisplayObjectContainer*)(child->parent()))->removeChild(child); } children.push_back(child); child->stage(this->_stage); child->parent(this); child->level(this->level()+1); _updateRect(); return child; } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::addChild(flDisplayObject* child, int x, int y) { // cout << "[flDisplayObjectContainer]addChild(" << child->name() << ", " << x << ", " << y << ")" << endl; //if(child == NULL) throw "TypeError: Error #2007: child null ρ˜"; if(child->parent()){ ((flDisplayObjectContainer*)(child->parent()))->removeChild(child); } children.push_back(child); child->x(x); child->y(y); child->stage(this->_stage); child->parent(this); child->level(this->level()+1); _updateRect(); return child; } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::addChildAt(flDisplayObject* child, int index) { //if(child == NULL) throw "TypeError: Error #2007: child null ρ˜"; if(index < 0 || index > children.size() - 1) return NULL; if(child->parent()) { ((flDisplayObjectContainer*)(child->parent()))->removeChild(child); } children.insert(children.begin() + index, child); child->stage(this->_stage); child->parent(this); child->level(this->level() + 1); _updateRect(); return child; } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::removeChild(flDisplayObject* child) { //if(child == NULL) throw "TypeError: Error #2007: child null ρ˜"; //children()̉ӏ̓t@N^OΖ‚ΕŠOɏo_ for(int i = 0; i < children.size(); i++){ if(children[i] == child){ child->stage(NULL); child->parent(NULL); child->level(-1); children.erase(children.begin() + i); _updateRect(); return child; } } throw "flDisplayObjectContainer::removeChild\n"; } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::removeChildAt(int index) { //children()̉ӏ̓t@N^OΖ‚ΕŠOɏo_ if(index < 0 || index > children.size() - 1) return NULL; flDisplayObject* child; child = children[index]; child->stage(NULL); child->parent(NULL); child->level(-1); children.erase(children.begin() + index); _updateRect(); return child; } //-------------------------------------------------------------- void flDisplayObjectContainer::removeAllChildren() { int i = 0; int t = children.size(); flDisplayObject* child; for(i; i < t; i++){ child = children[i]; child->stage(NULL); child->parent(NULL); child->level(-1); children.erase(children.begin() + i); --i; --t; } _updateRect(); } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::getChildAt(int index) { if(index < 0 || index > children.size() - 1) return NULL; return children[index]; } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::getChildByName(string name) { for(int i = 0; i < children.size(); i++){ if(children[i]->name() == name) return children[i]; } return NULL; } //-------------------------------------------------------------- int flDisplayObjectContainer::getChildIndex(flDisplayObject* child) { for(int i = 0; i < children.size(); i++){ if(children[i] == child) return i; } return -1; } //-------------------------------------------------------------- vector<flDisplayObject*> flDisplayObjectContainer::getObjectsUnderPoint(ofPoint point) { // TODO return children; } //-------------------------------------------------------------- void flDisplayObjectContainer::setChildIndex(flDisplayObject* child, int index) { if(index < 0 || index > children.size() - 1) return; for(int i = 0; i < children.size(); i++){ if(children[i] == child){ children.erase(children.begin() + i); children.insert(children.begin() + index, child); return; } } } //-------------------------------------------------------------- void flDisplayObjectContainer::swapChildren(flDisplayObject* child1, flDisplayObject* child2) { int index1 = getChildIndex(child1); int index2 = getChildIndex(child2); if(index1 == -1 || index2 == -1) return; for(int i = 0; i < children.size(); i++){ if(children[i] == child1 || children[i] == child2) { children.erase(children.begin() + i--); } } if(index1 < index2){ children.insert(children.begin() + index1, child2); children.insert(children.begin() + index2, child1); } else { children.insert(children.begin() + index2, child1); children.insert(children.begin() + index1, child2); } } //-------------------------------------------------------------- void flDisplayObjectContainer::swapChildrenAt(int index1, int index2) { if(index1 == index2) return; flDisplayObject* child1 = getChildAt(index1); flDisplayObject* child2 = getChildAt(index2); if(child1 == NULL || child2 == NULL) return; if(index2 > index1){ children.erase(children.begin() + index2); children.erase(children.begin() + index1); } else { children.erase(children.begin() + index1); children.erase(children.begin() + index2); } if(index1 < index2){ children.insert(children.begin() + index1, child2); children.insert(children.begin() + index2, child1); } else { children.insert(children.begin() + index2, child1); children.insert(children.begin() + index1, child2); } } //============================================================== // Protected / Private Method //============================================================== //-------------------------------------------------------------- void flDisplayObjectContainer::_updateRect() { // _hitAreaRect->__setNull(); _rect->__setZero(); int i; int l; l = children.size(); for(i = 0; i < l; i++) { flDisplayObject* child = children[i]; //=========================================== Matrix. //This the code is moved here from flStage._updateChildrenOne(). //transform child matrix by world matrix. flMatrix worldMatrix; worldMatrix = transform().concatenatedMatrix(); worldMatrix.concat(child->transform().matrix()); child->__updateTransform(worldMatrix); if(!child->visible()) continue; flRectangle childRect = child->__getRect(this); _rect->__expandTo(childRect.left(), childRect.top()); _rect->__expandTo(childRect.right(), childRect.bottom()); } _realWidth = _rect->width(); _realHeight = _rect->height(); if(_realWidth != 0.0 && !isnan(_targetWidth)) scaleX(_targetWidth / _realWidth); if(_realHeight != 0.0 && !isnan(_targetHeight)) scaleY(_targetHeight / _realHeight); // if(!isnan(_targetWidth)) scaleX(_targetWidth / _realWidth); // if(!isnan(_targetHeight)) scaleY(_targetHeight / _realHeight); // if(_targetWidth != -9999.0) scaleX(_targetWidth / _realWidth); // if(_targetHeight != -9999.0) scaleY(_targetHeight / _realHeight); } //-------------------------------------------------------------- bool flDisplayObjectContainer::_hasChildren(flDisplayObject* displayObject) { bool b; b = false; b = b || (displayObject->typeID() == FL_TYPE_DISPLAY_OBJECT_CONTAINER); b = b || (displayObject->typeID() == FL_TYPE_SPRITE); b = b || (displayObject->typeID() == FL_TYPE_MOVIE_CLIP); b = b || (displayObject->typeID() == FL_TYPE_UIBASE); return b; } } <commit_msg>no message<commit_after>#include "flDisplayObjectContainer.h" namespace fl2d { //============================================================== // Constructor / Destructor //============================================================== //-------------------------------------------------------------- flDisplayObjectContainer::flDisplayObjectContainer() { _typeID = FL_TYPE_DISPLAY_OBJECT_CONTAINER; _target = this; name("flDisplayObjectContainer"); _mouseChildren = true; //_tabChildren = false; } //-------------------------------------------------------------- flDisplayObjectContainer::~flDisplayObjectContainer() { _target = NULL; children.clear(); _mouseChildren = false; //_tabChildren = false; } //============================================================== // Setup / Update / Draw //============================================================== //-------------------------------------------------------------- void flDisplayObjectContainer::update() { // float tempLeft = _rect->left(); // float tempRight = _rect->right(); // float tempTop = _rect->top(); // float tempBottom = _rect->bottom(); // // _rect->_setToPoint(0, 0); // int i; int l; // flDisplayObject* child; // // l = children.size(); // for(i = 0; i < l; i++) { // child = children[i]; // float n1 = child->x(); // float n2 = child->y(); // _rect->__expandTo(n1, n2); // _rect->__expandTo(n1 + child->width(), n2 + child->height()); // } // _rect->__expandTo(tempLeft, tempTop); // _rect->__expandTo(tempRight, tempBottom); flDisplayObject::update(); } //-------------------------------------------------------------- void flDisplayObjectContainer::draw(bool applyMatrix) { if(!visible() && applyMatrix) return; // save off current state of blend enabled GLboolean blendEnabled; glGetBooleanv(GL_BLEND, &blendEnabled); // save off current state of src / dst blend functions GLint blendSrc; GLint blendDst; glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrc); glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDst); ofEnableAlphaBlending(); GLboolean preLighting = glIsEnabled(GL_LIGHTING); GLboolean preDepthTest = glIsEnabled(GL_DEPTH_TEST); GLboolean preLineSmooth = glIsEnabled(GL_LINE_SMOOTH); GLboolean preMultiSample = glIsEnabled(GL_MULTISAMPLE); ofDisableLighting(); glDisable(GL_DEPTH_TEST); if(_enabledSmoothing) { ofEnableSmoothing(); } else { ofDisableSmoothing(); } if(_enabledAntiAliasing) { ofEnableAntiAliasing(); } else { ofDisableAntiAliasing(); } //------------------------------------------ //-- matrix transform. // bool bIdentity = true; // bIdentity = matrix().isIdentity(); // bIdentity = false; if(applyMatrix){ // glPushMatrix(); ofPushMatrix(); // glMultMatrixf(matrix().getPtr()); ofMultMatrix(_transform.matrix().getPtr()); } ofPushStyle(); // ofSetColor(255, 255, 255, 255 * _compoundAlpha); _draw(); for(int i = 0; i < children.size(); i++) { flDisplayObject* child; child = children[i]; //child->drawOnFrame(); child->draw(); } ofPopStyle(); if(applyMatrix){ // glPopMatrix(); ofPopMatrix(); } //------------------------------------------ if(preMultiSample == GL_TRUE) { ofEnableAntiAliasing(); } else { ofDisableAntiAliasing(); } if(preLineSmooth == GL_TRUE) { ofEnableSmoothing(); } else { ofDisableSmoothing(); } if(preDepthTest == GL_TRUE) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } if(preLighting == GL_TRUE) { ofEnableLighting(); } else { ofDisableLighting(); } // restore saved state of blend enabled and blend functions if (blendEnabled) { glEnable(GL_BLEND); } else { glDisable(GL_BLEND); } glBlendFunc(blendSrc, blendDst); } //============================================================== // Public Method //============================================================== //-------------------------------------------------------------- bool flDisplayObjectContainer::mouseChildren() { return _mouseChildren; } void flDisplayObjectContainer::mouseChildren(bool value) { _mouseChildren = value; } //-------------------------------------------------------------- int flDisplayObjectContainer::numChildren() { return children.size(); } //-------------------------------------------------------------- bool flDisplayObjectContainer::contains(flDisplayObject* child) { for(int i = 0; i < children.size(); i++) { if(children[i] == child) return true; } return false; } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::stage() { return _stage; } void flDisplayObjectContainer::stage(flDisplayObject* value) { //cout << "[flDisplayObjectContainer]stage(" << value << ")" << name() << endl; //΁valueL΁ if(!_stage && value) { _stage = value; flEvent* event = new flEvent(flEvent::ADDED_TO_STAGE); // event->target(_target); dispatchEvent(event); } //L΁valueL΁ if(_stage && !value) { _stage = value; flEvent* event = new flEvent(flEvent::REMOVED_FROM_STAGE); // event->target(_target); dispatchEvent(event); } for(int i = 0; i < children.size(); i++) { flDisplayObject* displayObject = children[i]; displayObject->stage(_stage); } } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::addChild(flDisplayObject* child) { // cout << "[flDisplayObjectContainer]addChild((" << child->name() << ")" << endl; //if(child == NULL) throw "TypeError: Error #2007: child null ρ˜"; if(child->parent()){ ((flDisplayObjectContainer*)(child->parent()))->removeChild(child); } children.push_back(child); child->stage(this->_stage); child->parent(this); child->level(this->level()+1); _updateRect(); return child; } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::addChild(flDisplayObject* child, int x, int y) { // cout << "[flDisplayObjectContainer]addChild(" << child->name() << ", " << x << ", " << y << ")" << endl; //if(child == NULL) throw "TypeError: Error #2007: child null ρ˜"; if(child->parent()){ ((flDisplayObjectContainer*)(child->parent()))->removeChild(child); } children.push_back(child); child->x(x); child->y(y); child->stage(this->_stage); child->parent(this); child->level(this->level()+1); _updateRect(); return child; } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::addChildAt(flDisplayObject* child, int index) { //if(child == NULL) throw "TypeError: Error #2007: child null ρ˜"; if(index < 0 || index > children.size() - 1) return NULL; if(child->parent()) { ((flDisplayObjectContainer*)(child->parent()))->removeChild(child); } children.insert(children.begin() + index, child); child->stage(this->_stage); child->parent(this); child->level(this->level() + 1); _updateRect(); return child; } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::removeChild(flDisplayObject* child) { //if(child == NULL) throw "TypeError: Error #2007: child null ρ˜"; //children.size()̉ӏ̓t@N^OΖ‚ΕŠOɏo_ for(int i = 0; i < children.size(); i++){ if(children[i] == child){ child->stage(NULL); child->parent(NULL); child->level(-1); children.erase(children.begin() + i); _updateRect(); return child; } } throw "flDisplayObjectContainer::removeChild\n"; } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::removeChildAt(int index) { //children.size()̉ӏ̓t@N^OΖ‚ΕŠOɏo_ if(index < 0 || index > children.size() - 1) return NULL; flDisplayObject* child; child = children[index]; child->stage(NULL); child->parent(NULL); child->level(-1); children.erase(children.begin() + index); _updateRect(); return child; } //-------------------------------------------------------------- void flDisplayObjectContainer::removeAllChildren() { int i = 0; int t = children.size(); flDisplayObject* child; for(i; i < t; i++){ child = children[i]; child->stage(NULL); child->parent(NULL); child->level(-1); children.erase(children.begin() + i); --i; --t; } _updateRect(); } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::getChildAt(int index) { if(index < 0 || index > children.size() - 1) return NULL; return children[index]; } //-------------------------------------------------------------- flDisplayObject* flDisplayObjectContainer::getChildByName(string name) { for(int i = 0; i < children.size(); i++){ if(children[i]->name() == name) return children[i]; } return NULL; } //-------------------------------------------------------------- int flDisplayObjectContainer::getChildIndex(flDisplayObject* child) { for(int i = 0; i < children.size(); i++){ if(children[i] == child) return i; } return -1; } //-------------------------------------------------------------- vector<flDisplayObject*> flDisplayObjectContainer::getObjectsUnderPoint(ofPoint point) { // TODO return children; } //-------------------------------------------------------------- void flDisplayObjectContainer::setChildIndex(flDisplayObject* child, int index) { if(index < 0 || index > children.size() - 1) return; for(int i = 0; i < children.size(); i++){ if(children[i] == child){ children.erase(children.begin() + i); children.insert(children.begin() + index, child); return; } } } //-------------------------------------------------------------- void flDisplayObjectContainer::swapChildren(flDisplayObject* child1, flDisplayObject* child2) { int index1 = getChildIndex(child1); int index2 = getChildIndex(child2); if(index1 == -1 || index2 == -1) return; for(int i = 0; i < children.size(); i++){ if(children[i] == child1 || children[i] == child2) { children.erase(children.begin() + i--); } } if(index1 < index2){ children.insert(children.begin() + index1, child2); children.insert(children.begin() + index2, child1); } else { children.insert(children.begin() + index2, child1); children.insert(children.begin() + index1, child2); } } //-------------------------------------------------------------- void flDisplayObjectContainer::swapChildrenAt(int index1, int index2) { if(index1 == index2) return; flDisplayObject* child1 = getChildAt(index1); flDisplayObject* child2 = getChildAt(index2); if(child1 == NULL || child2 == NULL) return; if(index2 > index1){ children.erase(children.begin() + index2); children.erase(children.begin() + index1); } else { children.erase(children.begin() + index1); children.erase(children.begin() + index2); } if(index1 < index2){ children.insert(children.begin() + index1, child2); children.insert(children.begin() + index2, child1); } else { children.insert(children.begin() + index2, child1); children.insert(children.begin() + index1, child2); } } //============================================================== // Protected / Private Method //============================================================== //-------------------------------------------------------------- void flDisplayObjectContainer::_updateRect() { // _hitAreaRect->__setNull(); _rect->__setZero(); int i; int l; l = children.size(); for(i = 0; i < l; i++) { flDisplayObject* child = children[i]; //=========================================== Matrix. //This the code is moved here from flStage._updateChildrenOne(). //transform child matrix by world matrix. flMatrix worldMatrix; worldMatrix = transform().concatenatedMatrix(); worldMatrix.concat(child->transform().matrix()); child->__updateTransform(worldMatrix); if(!child->visible()) continue; flRectangle childRect = child->__getRect(this); _rect->__expandTo(childRect.left(), childRect.top()); _rect->__expandTo(childRect.right(), childRect.bottom()); } _realWidth = _rect->width(); _realHeight = _rect->height(); if(_realWidth != 0.0 && !isnan(_targetWidth)) scaleX(_targetWidth / _realWidth); if(_realHeight != 0.0 && !isnan(_targetHeight)) scaleY(_targetHeight / _realHeight); // if(!isnan(_targetWidth)) scaleX(_targetWidth / _realWidth); // if(!isnan(_targetHeight)) scaleY(_targetHeight / _realHeight); // if(_targetWidth != -9999.0) scaleX(_targetWidth / _realWidth); // if(_targetHeight != -9999.0) scaleY(_targetHeight / _realHeight); } //-------------------------------------------------------------- bool flDisplayObjectContainer::_hasChildren(flDisplayObject* displayObject) { bool b; b = false; b = b || (displayObject->typeID() == FL_TYPE_DISPLAY_OBJECT_CONTAINER); b = b || (displayObject->typeID() == FL_TYPE_SPRITE); b = b || (displayObject->typeID() == FL_TYPE_MOVIE_CLIP); b = b || (displayObject->typeID() == FL_TYPE_UIBASE); return b; } } <|endoftext|>
<commit_before>//(c) 2016 by Authors //This file is a part of ABruijn program. //Released under the BSD license (see LICENSE file) #include <chrono> #include <thread> #include "bubble_processor.h" namespace { size_t fileSize(const std::string& filename) { std::ifstream in(filename); in.ignore(std::numeric_limits<std::streamsize>::max()); return in.gcount(); } } BubbleProcessor::BubbleProcessor(const std::string& subsMatPath, const std::string& hopoMatrixPath): _subsMatrix(subsMatPath), _hopoMatrix(hopoMatrixPath), _generalPolisher(_subsMatrix), _homoPolisher(_subsMatrix, _hopoMatrix), _verbose(false) { } void BubbleProcessor::polishAll(const std::string& inBubbles, const std::string& outConsensus, int numThreads) { _cachedBubbles.clear(); _cachedBubbles.reserve(BUBBLES_CACHE); size_t fileLength = fileSize(inBubbles); _bubblesFile.open(inBubbles); if (!_bubblesFile.is_open()) { throw std::runtime_error("Error opening bubbles file"); } _progress.setFinalCount(fileLength); _consensusFile.open(outConsensus); if (!_consensusFile.is_open()) { throw std::runtime_error("Error opening consensus file"); } std::vector<std::thread> threads(numThreads); for (size_t i = 0; i < threads.size(); ++i) { threads[i] = std::thread(&BubbleProcessor::parallelWorker, this); } for (size_t i = 0; i < threads.size(); ++i) { threads[i].join(); } _progress.setDone(); } void BubbleProcessor::parallelWorker() { _stateMutex.lock(); while (true) { if (_cachedBubbles.empty()) { if(_bubblesFile.eof()) { _stateMutex.unlock(); return; } else { this->cacheBubbles(BUBBLES_CACHE); } } Bubble bubble = _cachedBubbles.back(); _cachedBubbles.pop_back(); _stateMutex.unlock(); _generalPolisher.polishBubble(bubble); _homoPolisher.polishBubble(bubble); _stateMutex.lock(); this->writeBubbles({bubble}); if (_verbose) this->writeLog({bubble}); } } void BubbleProcessor::writeBubbles(const std::vector<Bubble>& bubbles) { for (auto& bubble : bubbles) { _consensusFile << ">" << bubble.header << " " << bubble.position << " " << bubble.branches.size() << std::endl << bubble.candidate << std::endl; } } void BubbleProcessor::enableVerboseOutput(const std::string& filename) { _verbose = true; _logFile.open(filename); if (!_logFile.is_open()) { throw std::runtime_error("Error opening log file"); } } void BubbleProcessor::writeLog(const std::vector<Bubble>& bubbles) { std::vector<std::string> methods = {"None", "Insertion", "Substitution", "Deletion", "Homopolymer"}; for (auto& bubble : bubbles) { for (auto& stepInfo : bubble.polishSteps) { _logFile << std::fixed << std::setw(22) << std::left << "Consensus: " << std::right << stepInfo.sequence << std::endl << std::setw(22) << std::left << "Score: " << std::right << std::setprecision(2) << stepInfo.score << std::endl << std::setw(22) << std::left << "Last method applied: " << std::right << methods[stepInfo.methodUsed] << std::endl; if (stepInfo.methodUsed == StepDel) _logFile << "Char at pos: " << stepInfo.changedIndex << " was deleted. \n"; else if (stepInfo.methodUsed == StepSub) _logFile << "Char at pos " << stepInfo.changedIndex << " was substituted with " << "'" << stepInfo.changedLetter << "'.\n"; else if (stepInfo.methodUsed == StepIns) _logFile << "'"<< stepInfo.changedLetter << "'" << " was inserted at pos " << stepInfo.changedIndex << ".\n"; _logFile << std::endl; } _logFile << "-----------------\n"; } } void BubbleProcessor::cacheBubbles(int maxRead) { std::string buffer; std::string candidate; int readBubbles = 0; while (!_bubblesFile.eof() && readBubbles < maxRead) { std::getline(_bubblesFile, buffer); if (buffer.empty()) break; std::vector<std::string> elems = splitString(buffer, ' '); if (elems.size() < 3 || elems[0][0] != '>') { throw std::runtime_error("Error parsing bubbles file"); } std::getline(_bubblesFile, candidate); std::transform(candidate.begin(), candidate.end(), candidate.begin(), ::toupper); Bubble bubble; bubble.candidate = candidate; bubble.header = elems[0].substr(1, std::string::npos); bubble.position = std::stoi(elems[1]); int numOfReads = std::stoi(elems[2]); int count = 0; while (count < numOfReads) { if (buffer.empty()) break; std::getline(_bubblesFile, buffer); std::getline(_bubblesFile, buffer); std::transform(buffer.begin(), buffer.end(), buffer.begin(), ::toupper); bubble.branches.push_back(buffer); count++; } if (count != numOfReads) { throw std::runtime_error("Error parsing bubbles file"); } _cachedBubbles.push_back(std::move(bubble)); ++readBubbles; } int filePos = _bubblesFile.tellg(); if (filePos > 0) { _progress.setValue(filePos); } } <commit_msg>a fix for large bubbles progress bar<commit_after>//(c) 2016 by Authors //This file is a part of ABruijn program. //Released under the BSD license (see LICENSE file) #include <chrono> #include <thread> #include "bubble_processor.h" namespace { size_t fileSize(const std::string& filename) { std::ifstream in(filename); in.ignore(std::numeric_limits<std::streamsize>::max()); return in.gcount(); } } BubbleProcessor::BubbleProcessor(const std::string& subsMatPath, const std::string& hopoMatrixPath): _subsMatrix(subsMatPath), _hopoMatrix(hopoMatrixPath), _generalPolisher(_subsMatrix), _homoPolisher(_subsMatrix, _hopoMatrix), _verbose(false) { } void BubbleProcessor::polishAll(const std::string& inBubbles, const std::string& outConsensus, int numThreads) { _cachedBubbles.clear(); _cachedBubbles.reserve(BUBBLES_CACHE); size_t fileLength = fileSize(inBubbles); _bubblesFile.open(inBubbles); if (!_bubblesFile.is_open()) { throw std::runtime_error("Error opening bubbles file"); } _progress.setFinalCount(fileLength); _consensusFile.open(outConsensus); if (!_consensusFile.is_open()) { throw std::runtime_error("Error opening consensus file"); } std::vector<std::thread> threads(numThreads); for (size_t i = 0; i < threads.size(); ++i) { threads[i] = std::thread(&BubbleProcessor::parallelWorker, this); } for (size_t i = 0; i < threads.size(); ++i) { threads[i].join(); } _progress.setDone(); } void BubbleProcessor::parallelWorker() { _stateMutex.lock(); while (true) { if (_cachedBubbles.empty()) { if(_bubblesFile.eof()) { _stateMutex.unlock(); return; } else { this->cacheBubbles(BUBBLES_CACHE); } } Bubble bubble = _cachedBubbles.back(); _cachedBubbles.pop_back(); _stateMutex.unlock(); _generalPolisher.polishBubble(bubble); _homoPolisher.polishBubble(bubble); _stateMutex.lock(); this->writeBubbles({bubble}); if (_verbose) this->writeLog({bubble}); } } void BubbleProcessor::writeBubbles(const std::vector<Bubble>& bubbles) { for (auto& bubble : bubbles) { _consensusFile << ">" << bubble.header << " " << bubble.position << " " << bubble.branches.size() << std::endl << bubble.candidate << std::endl; } } void BubbleProcessor::enableVerboseOutput(const std::string& filename) { _verbose = true; _logFile.open(filename); if (!_logFile.is_open()) { throw std::runtime_error("Error opening log file"); } } void BubbleProcessor::writeLog(const std::vector<Bubble>& bubbles) { std::vector<std::string> methods = {"None", "Insertion", "Substitution", "Deletion", "Homopolymer"}; for (auto& bubble : bubbles) { for (auto& stepInfo : bubble.polishSteps) { _logFile << std::fixed << std::setw(22) << std::left << "Consensus: " << std::right << stepInfo.sequence << std::endl << std::setw(22) << std::left << "Score: " << std::right << std::setprecision(2) << stepInfo.score << std::endl << std::setw(22) << std::left << "Last method applied: " << std::right << methods[stepInfo.methodUsed] << std::endl; if (stepInfo.methodUsed == StepDel) _logFile << "Char at pos: " << stepInfo.changedIndex << " was deleted. \n"; else if (stepInfo.methodUsed == StepSub) _logFile << "Char at pos " << stepInfo.changedIndex << " was substituted with " << "'" << stepInfo.changedLetter << "'.\n"; else if (stepInfo.methodUsed == StepIns) _logFile << "'"<< stepInfo.changedLetter << "'" << " was inserted at pos " << stepInfo.changedIndex << ".\n"; _logFile << std::endl; } _logFile << "-----------------\n"; } } void BubbleProcessor::cacheBubbles(int maxRead) { std::string buffer; std::string candidate; int readBubbles = 0; while (!_bubblesFile.eof() && readBubbles < maxRead) { std::getline(_bubblesFile, buffer); if (buffer.empty()) break; std::vector<std::string> elems = splitString(buffer, ' '); if (elems.size() < 3 || elems[0][0] != '>') { throw std::runtime_error("Error parsing bubbles file"); } std::getline(_bubblesFile, candidate); std::transform(candidate.begin(), candidate.end(), candidate.begin(), ::toupper); Bubble bubble; bubble.candidate = candidate; bubble.header = elems[0].substr(1, std::string::npos); bubble.position = std::stoi(elems[1]); int numOfReads = std::stoi(elems[2]); int count = 0; while (count < numOfReads) { if (buffer.empty()) break; std::getline(_bubblesFile, buffer); std::getline(_bubblesFile, buffer); std::transform(buffer.begin(), buffer.end(), buffer.begin(), ::toupper); bubble.branches.push_back(buffer); count++; } if (count != numOfReads) { throw std::runtime_error("Error parsing bubbles file"); } _cachedBubbles.push_back(std::move(bubble)); ++readBubbles; } int64_t filePos = _bubblesFile.tellg(); if (filePos > 0) { _progress.setValue(filePos); } } <|endoftext|>
<commit_before>#include <string> #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <iterator> #include <tuple> #include <regex> #include <array> #include <valarray> #define all(v)begin(v),end(v) #define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n")) #define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i) #define fr(i,n)for(int i=0,i##e=n;i<i##e;++i) #define rf(i,n)for(int i=n-1;i>=0;--i) #define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1) #define sz(v)int(v.size()) #define sr(v)sort(all(v)) #define rs(v)sort(all(v),greater<int>()) #define rev(v)reverse(all(v)) #define eb emplace_back #define stst stringstream #define big numeric_limits<int>::max() #define g(t,i)get<i>(t) #define cb(v,w)copy(all(v),back_inserter(w)) #define uni(v)sort(all(v));v.erase(unique(all(v)),end(v)) #define vt(...)vector<tuple<__VA_ARGS__>> #define smx(a,b)a=max(a,b) #define smn(a,b)a=min(a,b) #define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q); #define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n); typedef long long ll; using namespace std; struct TheBestName { vector <string> sort(vector <string> names) { vt(int, string) v; auto sum = [](const string & s) { int r = 0; ei(a, s) r += a - 'A'; return r; }; ei(a, names) { v.eb(a == "JOHN" ? big : sum(a), a); } sr(v); ei(a, v) names[ai] = g(a,1); return names; } }; // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit-pf 2.3.0 #include <iostream> #include <string> #include <vector> #include <ctime> #include <cmath> using namespace std; bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, vector <string> p1) { cout << "Test " << testNum << ": [" << "{"; for (int i = 0; int(p0.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << "\"" << p0[i] << "\""; } cout << "}"; cout << "]" << endl; TheBestName *obj; vector <string> answer; obj = new TheBestName(); clock_t startTime = clock(); answer = obj->sort(p0); clock_t endTime = clock(); delete obj; bool res; res = true; cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl; if (hasAnswer) { cout << "Desired answer:" << endl; cout << "\t" << "{"; for (int i = 0; int(p1.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << "\"" << p1[i] << "\""; } cout << "}" << endl; } cout << "Your answer:" << endl; cout << "\t" << "{"; for (int i = 0; int(answer.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << "\"" << answer[i] << "\""; } cout << "}" << endl; if (hasAnswer) { if (answer.size() != p1.size()) { res = false; } else { for (int i = 0; int(answer.size()) > i; ++i) { if (answer[i] != p1[i]) { res = false; } } } } if (!res) { cout << "DOESN'T MATCH!!!!" << endl; } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) { cout << "FAIL the timeout" << endl; res = false; } else if (hasAnswer) { cout << "Match :-)" << endl; } else { cout << "OK, but is it right?" << endl; } cout << "" << endl; return res; } int main() { bool all_right; bool disabled; bool tests_disabled; all_right = true; tests_disabled = false; vector <string> p0; vector <string> p1; // ----- test 0 ----- disabled = false; p0 = {"JOHN","PETR","ACRUSH"}; p1 = {"JOHN","ACRUSH","PETR"}; all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right; tests_disabled = tests_disabled || disabled; // ------------------ // ----- test 1 ----- disabled = false; p0 = {"GLUK","MARGARITKA"}; p1 = {"MARGARITKA","GLUK"}; all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right; tests_disabled = tests_disabled || disabled; // ------------------ // ----- test 2 ----- disabled = false; p0 = {"JOHN","A","AA","AAA","JOHN","B","BB","BBB","JOHN","C","CC","CCC","JOHN"}; p1 = {"JOHN","JOHN","JOHN","JOHN","CCC","BBB","CC","BB","AAA","C","AA","B","A"}; all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right; tests_disabled = tests_disabled || disabled; // ------------------ // ----- test 3 ----- disabled = false; p0 = {"BATMAN","SUPERMAN","SPIDERMAN","TERMINATOR"}; p1 = {"TERMINATOR","SUPERMAN","SPIDERMAN","BATMAN"}; all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right; tests_disabled = tests_disabled || disabled; // ------------------ if (all_right) { if (tests_disabled) { cout << "You're a stud (but some test cases were disabled)!" << endl; } else { cout << "You're a stud (at least on given cases)!" << endl; } } else { cout << "Some of the test cases had errors." << endl; } return 0; } // END KAWIGIEDIT TESTING <commit_msg>TheBestName<commit_after>#include <string> #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <iterator> #include <tuple> #include <regex> #include <array> #include <valarray> #define all(v)begin(v),end(v) #define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n")) #define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i) #define fr(i,n)for(int i=0,i##e=n;i<i##e;++i) #define rf(i,n)for(int i=n-1;i>=0;--i) #define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1) #define sz(v)int(v.size()) #define sr(v)sort(all(v)) #define rs(v)sort(all(v),greater<int>()) #define rev(v)reverse(all(v)) #define eb emplace_back #define stst stringstream #define big numeric_limits<int>::max() #define g(t,i)get<i>(t) #define cb(v,w)copy(all(v),back_inserter(w)) #define uni(v)sort(all(v));v.erase(unique(all(v)),end(v)) #define vt(...)vector<tuple<__VA_ARGS__>> #define smx(a,b)a=max(a,b) #define smn(a,b)a=min(a,b) #define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q); #define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n); typedef long long ll; using namespace std; struct TheBestName { vector <string> sort(vector <string> names) { vector<pair<int, string>> v; auto sum = [](const string & s) { int r = 0; ei(a, s) r += a - 'A'; return r; }; ei(a, names) { v.eb(a == "JOHN" ? big : sum(a), a); } sr(v); ei(a, v) names[ai] = s.second; return names; } }; // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit-pf 2.3.0 #include <iostream> #include <string> #include <vector> #include <ctime> #include <cmath> using namespace std; bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, vector <string> p1) { cout << "Test " << testNum << ": [" << "{"; for (int i = 0; int(p0.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << "\"" << p0[i] << "\""; } cout << "}"; cout << "]" << endl; TheBestName *obj; vector <string> answer; obj = new TheBestName(); clock_t startTime = clock(); answer = obj->sort(p0); clock_t endTime = clock(); delete obj; bool res; res = true; cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl; if (hasAnswer) { cout << "Desired answer:" << endl; cout << "\t" << "{"; for (int i = 0; int(p1.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << "\"" << p1[i] << "\""; } cout << "}" << endl; } cout << "Your answer:" << endl; cout << "\t" << "{"; for (int i = 0; int(answer.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << "\"" << answer[i] << "\""; } cout << "}" << endl; if (hasAnswer) { if (answer.size() != p1.size()) { res = false; } else { for (int i = 0; int(answer.size()) > i; ++i) { if (answer[i] != p1[i]) { res = false; } } } } if (!res) { cout << "DOESN'T MATCH!!!!" << endl; } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) { cout << "FAIL the timeout" << endl; res = false; } else if (hasAnswer) { cout << "Match :-)" << endl; } else { cout << "OK, but is it right?" << endl; } cout << "" << endl; return res; } int main() { bool all_right; bool disabled; bool tests_disabled; all_right = true; tests_disabled = false; vector <string> p0; vector <string> p1; // ----- test 0 ----- disabled = false; p0 = {"JOHN","PETR","ACRUSH"}; p1 = {"JOHN","ACRUSH","PETR"}; all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right; tests_disabled = tests_disabled || disabled; // ------------------ // ----- test 1 ----- disabled = false; p0 = {"GLUK","MARGARITKA"}; p1 = {"MARGARITKA","GLUK"}; all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right; tests_disabled = tests_disabled || disabled; // ------------------ // ----- test 2 ----- disabled = false; p0 = {"JOHN","A","AA","AAA","JOHN","B","BB","BBB","JOHN","C","CC","CCC","JOHN"}; p1 = {"JOHN","JOHN","JOHN","JOHN","CCC","BBB","CC","BB","AAA","C","AA","B","A"}; all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right; tests_disabled = tests_disabled || disabled; // ------------------ // ----- test 3 ----- disabled = false; p0 = {"BATMAN","SUPERMAN","SPIDERMAN","TERMINATOR"}; p1 = {"TERMINATOR","SUPERMAN","SPIDERMAN","BATMAN"}; all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right; tests_disabled = tests_disabled || disabled; // ------------------ if (all_right) { if (tests_disabled) { cout << "You're a stud (but some test cases were disabled)!" << endl; } else { cout << "You're a stud (at least on given cases)!" << endl; } } else { cout << "Some of the test cases had errors." << endl; } return 0; } // END KAWIGIEDIT TESTING <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the Avogadro project. This source code is released under the 3-Clause BSD License, (see "LICENSE"). ******************************************************************************/ #include "label.h" #include <avogadro/core/elements.h> #include <avogadro/core/molecule.h> #include <avogadro/core/residue.h> #include <avogadro/qtgui/colorbutton.h> #include <avogadro/rendering/geometrynode.h> #include <avogadro/rendering/scene.h> #include <avogadro/rendering/textlabel3d.h> #include <QtCore/QSettings> #include <QtWidgets/QCheckBox> #include <QtWidgets/QComboBox> #include <QtWidgets/QDoubleSpinBox> #include <QtWidgets/QFormLayout> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> namespace Avogadro { namespace QtPlugins { using Avogadro::Rendering::TextLabel3D; using Core::Array; using Core::Atom; using Core::Elements; using Core::Molecule; using QtGui::PluginLayerManager; using Rendering::GeometryNode; using Rendering::GroupNode; using std::map; typedef Array<Molecule::BondType> NeighborListType; namespace { TextLabel3D* createLabel(const std::string& text, const Vector3f& pos, float radius, const Vector3ub& color) { Rendering::TextProperties tprop; tprop.setAlign(Rendering::TextProperties::HCenter, Rendering::TextProperties::VCenter); tprop.setFontFamily(Rendering::TextProperties::SansSerif); tprop.setColorRgb(color.data()); TextLabel3D* label = new TextLabel3D; label->setText(text); label->setRenderPass(Rendering::TranslucentPass); label->setTextProperties(tprop); label->setRadius(radius); label->setAnchor(pos); return label; } } // namespace struct LayerLabel : Core::LayerData { enum LabelOptions : char { None = 0x00, Index = 0x01, Name = 0x02, Custom = 0x04, Ordinal = 0x08 }; char atomOptions; char residueOptions; QWidget* widget; float radiusScalar; Vector3ub color; LayerLabel() { widget = nullptr; QSettings settings; atomOptions = char(settings.value("label/atomoptions", 0x02).toInt()); residueOptions = char(settings.value("label/residueoptions", 0x00).toInt()); radiusScalar = settings.value("label/radiusscalar", 0.5).toDouble(); QColor q_color = settings.value("label/color", QColor(Qt::white)).value<QColor>(); color[0] = static_cast<unsigned char>(q_color.red()); color[1] = static_cast<unsigned char>(q_color.green()); color[2] = static_cast<unsigned char>(q_color.blue()); } ~LayerLabel() { if (widget) widget->deleteLater(); } std::string serialize() override final { std::string aux = (const char*)atomOptions; std::string aux2 = (const char*)residueOptions; return aux + " " + aux2 + " " + std::to_string(radiusScalar) + " " + std::to_string(color[0]) + " " + std::to_string(color[1]) + " " + std::to_string(color[2]); } void deserialize(std::string text) override final { std::stringstream ss(text); std::string aux; ss >> aux; atomOptions = aux[0]; ss >> aux; residueOptions = aux[0]; ss >> aux; radiusScalar = std::stof(aux); ss >> aux; color[0] = std::stoi(aux); ss >> aux; color[1] = std::stoi(aux); ss >> aux; color[2] = std::stoi(aux); } void setupWidget(Label* slot) { if (!widget) { widget = new QWidget(qobject_cast<QWidget*>(slot->parent())); QVBoxLayout* v = new QVBoxLayout; QFormLayout* form = new QFormLayout; // color button QtGui::ColorButton* color = new QtGui::ColorButton; QObject::connect(color, SIGNAL(colorChanged(const QColor&)), slot, SLOT(setColor(const QColor&))); form->addRow(QObject::tr("Color:"), color); // radius scalar QDoubleSpinBox* spin = new QDoubleSpinBox; spin->setRange(0.0, 1.5); spin->setSingleStep(0.1); spin->setDecimals(1); spin->setValue(radiusScalar); QObject::connect(spin, SIGNAL(valueChanged(double)), slot, SLOT(setRadiusScalar(double))); form->addRow(QObject::tr("Distance from center:"), spin); QComboBox* atom = new QComboBox; atom->setObjectName("atom"); for (char i = 0x00; i < std::pow(2, 4); ++i) { if (i == 0) { atom->addItem(QObject::tr("None"), QVariant(LabelOptions::None)); } else { char val = 0x00; QStringList text; if (i & LabelOptions::Custom) { text << QObject::tr("Custom"); val = LabelOptions::Custom; } if (i & LabelOptions::Index) { text << ((text.size() == 0) ? QObject::tr("Index") : QObject::tr("In.")); val |= LabelOptions::Index; } if (i & LabelOptions::Name) { text << ((text.size() == 0) ? QObject::tr("Element") : QObject::tr("El.")); val |= LabelOptions::Name; } if (i & LabelOptions::Ordinal) { text << ((text.size() == 0) ? QObject::tr("Element & Ordinal") : QObject::tr("El.&Or.")); val |= LabelOptions::Ordinal; } QString join = QObject::tr(", "); atom->addItem(text.join(join), QVariant(val)); if (val == atomOptions) { atom->setCurrentText(text.join(join)); } } } QObject::connect(atom, SIGNAL(currentIndexChanged(int)), slot, SLOT(atomLabelType(int))); int index = atom->findData(int(atomOptions)); atom->model()->sort(0, Qt::AscendingOrder); form->addRow(QObject::tr("Atom Label:"), atom); QComboBox* residue = new QComboBox; residue->setObjectName("residue"); for (char i = 0x00; i < std::pow(2, 2); ++i) { if (i == 0) { residue->addItem(QObject::tr("None"), QVariant(LabelOptions::None)); } else { char val = 0x00; QStringList text; if (i & LabelOptions::Index) { text << QObject::tr("ID"); val |= LabelOptions::Index; } if (i & LabelOptions::Name) { text << QObject::tr("Name"); val |= LabelOptions::Name; } if (val != 0x00) { QString join = QObject::tr(" & "); residue->addItem(text.join(join), QVariant(val)); if (val == residueOptions) { residue->setCurrentText(text.join(join)); } } } } QObject::connect(residue, SIGNAL(currentIndexChanged(int)), slot, SLOT(residueLabelType(int))); index = residue->findData(int(residueOptions)); residue->model()->sort(0, Qt::AscendingOrder); form->addRow(QObject::tr("Residue Label:"), residue); v->addLayout(form); v->addStretch(1); widget->setLayout(v); } } }; Label::Label(QObject* parent_) : QtGui::ScenePlugin(parent_) { m_layerManager = PluginLayerManager(m_name); } Label::~Label() {} void Label::process(const Core::Molecule& molecule, Rendering::GroupNode& node) { m_layerManager.load<LayerLabel>(); for (size_t layer = 0; layer < m_layerManager.layerCount(); ++layer) { LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(layer); if (interface.residueOptions) { processResidue(molecule, node, layer); } if (interface.atomOptions) { processAtom(molecule, node, layer); } } } void Label::processResidue(const Core::Molecule& molecule, Rendering::GroupNode& node, size_t layer) { GeometryNode* geometry = new GeometryNode; node.addChild(geometry); for (const auto& residue : molecule.residues()) { Atom caAtom = residue.getAtomByName("CA"); if (!caAtom.isValid() || !m_layerManager.atomEnabled(layer, caAtom.index())) { continue; } auto name = residue.residueName(); const auto atoms = residue.residueAtoms(); Vector3f pos = Vector3f::Zero(); for (const auto& atom : atoms) { pos += atom.position3d().cast<float>(); } pos /= static_cast<float>(atoms.size()); float radius = 0.0f; for (const auto& atom : atoms) { unsigned char atomicNumber = atom.atomicNumber(); float auxR = static_cast<float>(Elements::radiusVDW(atomicNumber)); auxR += (atom.position3d().cast<float>() - pos).norm(); if (auxR > radius) { auxR = radius; } } auto& interface = m_layerManager.getSetting<LayerLabel>(layer); Vector3ub color = interface.color; std::string text = ""; if (interface.residueOptions & LayerLabel::LabelOptions::Index) { text = std::to_string(residue.residueId()); } if (interface.residueOptions & LayerLabel::LabelOptions::Name) { text += (text == "" ? "" : " / ") + name; } TextLabel3D* residueLabel = createLabel(text, pos, radius, color); geometry->addDrawable(residueLabel); } } void Label::processAtom(const Core::Molecule& molecule, Rendering::GroupNode& node, size_t layer) { GeometryNode* geometry = new GeometryNode; node.addChild(geometry); std::map<unsigned char, size_t> atomCount; for (Index i = 0; i < molecule.atomCount(); ++i) { Core::Atom atom = molecule.atom(i); unsigned char atomicNumber = atom.atomicNumber(); if (atomCount.find(atomicNumber) == atomCount.end()) { atomCount[atomicNumber] = 1; } else { ++atomCount[atomicNumber]; } if (!m_layerManager.atomEnabled(layer, i)) { continue; } LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(layer); std::string text = ""; if (interface.atomOptions & LayerLabel::LabelOptions::Custom) { text += (text == "" ? "" : " / ") + atom.label(); } if (interface.atomOptions & LayerLabel::LabelOptions::Index) { text += (text == "" ? "" : " / ") + std::to_string(atom.index()); } if (interface.atomOptions & LayerLabel::LabelOptions::Name) { text += (text == "" ? "" : " / ") + std::string(Elements::symbol(atomicNumber)); } if (interface.atomOptions & LayerLabel::LabelOptions::Ordinal) { text += (text == "" ? "" : " / ") + std::string(Elements::symbol(atomicNumber) + std::to_string(atomCount[atomicNumber])); } if (text != "") { const Vector3f pos(atom.position3d().cast<float>()); Vector3ub color = interface.color; float radius = static_cast<float>(Elements::radiusVDW(atomicNumber)) * interface.radiusScalar; TextLabel3D* atomLabel = createLabel(text, pos, radius, color); geometry->addDrawable(atomLabel); } } } void Label::setColor(const QColor& color) { LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(); interface.color[0] = static_cast<unsigned char>(color.red()); interface.color[1] = static_cast<unsigned char>(color.green()); interface.color[2] = static_cast<unsigned char>(color.blue()); emit drawablesChanged(); QSettings settings; settings.setValue("label/color", color); } void Label::atomLabelType(int index) { LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(); interface.atomOptions = char(setupWidget() ->findChildren<QComboBox*>("atom")[0] ->itemData(index) .toInt()); emit drawablesChanged(); } void Label::residueLabelType(int index) { LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(); interface.residueOptions = char(setupWidget() ->findChildren<QComboBox*>("residue")[0] ->itemData(index) .toInt()); emit drawablesChanged(); } void Label::setRadiusScalar(double radius) { LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(); interface.radiusScalar = float(radius); emit drawablesChanged(); QSettings settings; settings.setValue("label/radiusScalar", interface.radiusScalar); } QWidget* Label::setupWidget() { LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(); interface.setupWidget(this); return interface.widget; } } // namespace QtPlugins } // namespace Avogadro <commit_msg>remove extra label options<commit_after>/****************************************************************************** This source file is part of the Avogadro project. This source code is released under the 3-Clause BSD License, (see "LICENSE"). ******************************************************************************/ #include "label.h" #include <avogadro/core/elements.h> #include <avogadro/core/molecule.h> #include <avogadro/core/residue.h> #include <avogadro/qtgui/colorbutton.h> #include <avogadro/rendering/geometrynode.h> #include <avogadro/rendering/scene.h> #include <avogadro/rendering/textlabel3d.h> #include <QtCore/QSettings> #include <QtWidgets/QCheckBox> #include <QtWidgets/QComboBox> #include <QtWidgets/QDoubleSpinBox> #include <QtWidgets/QFormLayout> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> namespace Avogadro { namespace QtPlugins { using Avogadro::Rendering::TextLabel3D; using Core::Array; using Core::Atom; using Core::Elements; using Core::Molecule; using QtGui::PluginLayerManager; using Rendering::GeometryNode; using Rendering::GroupNode; using std::map; typedef Array<Molecule::BondType> NeighborListType; namespace { TextLabel3D* createLabel(const std::string& text, const Vector3f& pos, float radius, const Vector3ub& color) { Rendering::TextProperties tprop; tprop.setAlign(Rendering::TextProperties::HCenter, Rendering::TextProperties::VCenter); tprop.setFontFamily(Rendering::TextProperties::SansSerif); tprop.setColorRgb(color.data()); TextLabel3D* label = new TextLabel3D; label->setText(text); label->setRenderPass(Rendering::TranslucentPass); label->setTextProperties(tprop); label->setRadius(radius); label->setAnchor(pos); return label; } } // namespace struct LayerLabel : Core::LayerData { enum LabelOptions : char { None = 0x00, Index = 0x01, Name = 0x02, Custom = 0x04, Ordinal = 0x08 }; char atomOptions; char residueOptions; QWidget* widget; float radiusScalar; Vector3ub color; LayerLabel() { widget = nullptr; QSettings settings; atomOptions = char(settings.value("label/atomoptions", 0x02).toInt()); residueOptions = char(settings.value("label/residueoptions", 0x00).toInt()); radiusScalar = settings.value("label/radiusscalar", 0.5).toDouble(); QColor q_color = settings.value("label/color", QColor(Qt::white)).value<QColor>(); color[0] = static_cast<unsigned char>(q_color.red()); color[1] = static_cast<unsigned char>(q_color.green()); color[2] = static_cast<unsigned char>(q_color.blue()); } ~LayerLabel() { if (widget) widget->deleteLater(); } std::string serialize() override final { std::string aux = (const char*)atomOptions; std::string aux2 = (const char*)residueOptions; return aux + " " + aux2 + " " + std::to_string(radiusScalar) + " " + std::to_string(color[0]) + " " + std::to_string(color[1]) + " " + std::to_string(color[2]); } void deserialize(std::string text) override final { std::stringstream ss(text); std::string aux; ss >> aux; atomOptions = aux[0]; ss >> aux; residueOptions = aux[0]; ss >> aux; radiusScalar = std::stof(aux); ss >> aux; color[0] = std::stoi(aux); ss >> aux; color[1] = std::stoi(aux); ss >> aux; color[2] = std::stoi(aux); } void setupWidget(Label* slot) { if (!widget) { widget = new QWidget(qobject_cast<QWidget*>(slot->parent())); QVBoxLayout* v = new QVBoxLayout; QFormLayout* form = new QFormLayout; // color button QtGui::ColorButton* colorButton = new QtGui::ColorButton; QObject::connect(colorButton, SIGNAL(colorChanged(const QColor&)), slot, SLOT(setColor(const QColor&))); form->addRow(QObject::tr("Color:"), colorButton); // radius scalar QDoubleSpinBox* spin = new QDoubleSpinBox; spin->setRange(0.0, 1.5); spin->setSingleStep(0.1); spin->setDecimals(1); spin->setValue(radiusScalar); QObject::connect(spin, SIGNAL(valueChanged(double)), slot, SLOT(setRadiusScalar(double))); form->addRow(QObject::tr("Distance from center:"), spin); QComboBox* atom = new QComboBox; atom->setObjectName("atom"); char elements[] = { None, Index, Name, Custom, Ordinal }; for (unsigned char i = 0; i < 5; ++i) { char option = elements[i]; if (option == 0) { atom->addItem(QObject::tr("None"), QVariant(LabelOptions::None)); } else { char val = LabelOptions::None; QStringList text; if (option & LabelOptions::Custom) { text << QObject::tr("Custom"); val = LabelOptions::Custom; } if (option & LabelOptions::Index) { text << ((text.size() == 0) ? QObject::tr("Index") : QObject::tr("In.")); val |= LabelOptions::Index; } if (option & LabelOptions::Name) { text << ((text.size() == 0) ? QObject::tr("Element") : QObject::tr("El.")); val |= LabelOptions::Name; } if (option & LabelOptions::Ordinal) { text << ((text.size() == 0) ? QObject::tr("Element & Ordinal") : QObject::tr("El.&Or.")); val |= LabelOptions::Ordinal; } QString join = QObject::tr(", "); atom->addItem(text.join(join), QVariant(val)); if (val == atomOptions) { atom->setCurrentText(text.join(join)); } } } QObject::connect(atom, SIGNAL(currentIndexChanged(int)), slot, SLOT(atomLabelType(int))); int index = atom->findData(int(atomOptions)); atom->model()->sort(0, Qt::AscendingOrder); form->addRow(QObject::tr("Atom Label:"), atom); QComboBox* residue = new QComboBox; residue->setObjectName("residue"); for (char i = 0x00; i < std::pow(2, 2); ++i) { if (i == 0) { residue->addItem(QObject::tr("None"), QVariant(LabelOptions::None)); } else { char val = 0x00; QStringList text; if (i & LabelOptions::Index) { text << QObject::tr("ID"); val |= LabelOptions::Index; } if (i & LabelOptions::Name) { text << QObject::tr("Name"); val |= LabelOptions::Name; } if (val != 0x00) { QString join = QObject::tr(" & "); residue->addItem(text.join(join), QVariant(val)); if (val == residueOptions) { residue->setCurrentText(text.join(join)); } } } } QObject::connect(residue, SIGNAL(currentIndexChanged(int)), slot, SLOT(residueLabelType(int))); index = residue->findData(int(residueOptions)); residue->model()->sort(0, Qt::AscendingOrder); form->addRow(QObject::tr("Residue Label:"), residue); v->addLayout(form); v->addStretch(1); widget->setLayout(v); } } }; Label::Label(QObject* parent_) : QtGui::ScenePlugin(parent_) { m_layerManager = PluginLayerManager(m_name); } Label::~Label() {} void Label::process(const Core::Molecule& molecule, Rendering::GroupNode& node) { m_layerManager.load<LayerLabel>(); for (size_t layer = 0; layer < m_layerManager.layerCount(); ++layer) { LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(layer); if (interface.residueOptions) { processResidue(molecule, node, layer); } if (interface.atomOptions) { processAtom(molecule, node, layer); } } } void Label::processResidue(const Core::Molecule& molecule, Rendering::GroupNode& node, size_t layer) { GeometryNode* geometry = new GeometryNode; node.addChild(geometry); for (const auto& residue : molecule.residues()) { Atom caAtom = residue.getAtomByName("CA"); if (!caAtom.isValid() || !m_layerManager.atomEnabled(layer, caAtom.index())) { continue; } auto name = residue.residueName(); const auto atoms = residue.residueAtoms(); Vector3f pos = Vector3f::Zero(); for (const auto& atom : atoms) { pos += atom.position3d().cast<float>(); } pos /= static_cast<float>(atoms.size()); float radius = 0.0f; for (const auto& atom : atoms) { unsigned char atomicNumber = atom.atomicNumber(); float auxR = static_cast<float>(Elements::radiusVDW(atomicNumber)); auxR += (atom.position3d().cast<float>() - pos).norm(); if (auxR > radius) { auxR = radius; } } auto& interface = m_layerManager.getSetting<LayerLabel>(layer); Vector3ub color = interface.color; std::string text = ""; if (interface.residueOptions & LayerLabel::LabelOptions::Index) { text = std::to_string(residue.residueId()); } if (interface.residueOptions & LayerLabel::LabelOptions::Name) { text += (text == "" ? "" : " / ") + name; } TextLabel3D* residueLabel = createLabel(text, pos, radius, color); geometry->addDrawable(residueLabel); } } void Label::processAtom(const Core::Molecule& molecule, Rendering::GroupNode& node, size_t layer) { GeometryNode* geometry = new GeometryNode; node.addChild(geometry); std::map<unsigned char, size_t> atomCount; for (Index i = 0; i < molecule.atomCount(); ++i) { Core::Atom atom = molecule.atom(i); unsigned char atomicNumber = atom.atomicNumber(); if (atomCount.find(atomicNumber) == atomCount.end()) { atomCount[atomicNumber] = 1; } else { ++atomCount[atomicNumber]; } if (!m_layerManager.atomEnabled(layer, i)) { continue; } LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(layer); std::string text = ""; if (interface.atomOptions & LayerLabel::LabelOptions::Custom) { text += (text == "" ? "" : " / ") + atom.label(); } if (interface.atomOptions & LayerLabel::LabelOptions::Index) { text += (text == "" ? "" : " / ") + std::to_string(atom.index()); } if (interface.atomOptions & LayerLabel::LabelOptions::Name) { text += (text == "" ? "" : " / ") + std::string(Elements::symbol(atomicNumber)); } if (interface.atomOptions & LayerLabel::LabelOptions::Ordinal) { text += (text == "" ? "" : " / ") + std::string(Elements::symbol(atomicNumber) + std::to_string(atomCount[atomicNumber])); } if (text != "") { const Vector3f pos(atom.position3d().cast<float>()); Vector3ub color = interface.color; float radius = static_cast<float>(Elements::radiusVDW(atomicNumber)) * interface.radiusScalar; TextLabel3D* atomLabel = createLabel(text, pos, radius, color); geometry->addDrawable(atomLabel); } } } void Label::setColor(const QColor& color) { LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(); interface.color[0] = static_cast<unsigned char>(color.red()); interface.color[1] = static_cast<unsigned char>(color.green()); interface.color[2] = static_cast<unsigned char>(color.blue()); emit drawablesChanged(); QSettings settings; settings.setValue("label/color", color); } void Label::atomLabelType(int index) { LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(); interface.atomOptions = char(setupWidget() ->findChildren<QComboBox*>("atom")[0] ->itemData(index) .toInt()); emit drawablesChanged(); } void Label::residueLabelType(int index) { LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(); interface.residueOptions = char(setupWidget() ->findChildren<QComboBox*>("residue")[0] ->itemData(index) .toInt()); emit drawablesChanged(); } void Label::setRadiusScalar(double radius) { LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(); interface.radiusScalar = float(radius); emit drawablesChanged(); QSettings settings; settings.setValue("label/radiusScalar", interface.radiusScalar); } QWidget* Label::setupWidget() { LayerLabel& interface = m_layerManager.getSetting<LayerLabel>(); interface.setupWidget(this); return interface.widget; } } // namespace QtPlugins } // namespace Avogadro <|endoftext|>
<commit_before>/* * Copyright Copyright 2012, System Insights, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ref_counted.hpp" #include "dlib/threads.h" #include <libkern/OSAtomic.h> static dlib::rmutex sRefMutex; RefCounted::~RefCounted() { } void RefCounted::referTo() { #ifdef _WINDOWS InterlockedIncrement(&this->mRefCount); #else #ifdef MACOSX OSAtomicIncrement32Barrier(&(this->mRefCount)); #else dlib::auto_mutex lock(sRefMutex); mRefCount++; #endif #endif } void RefCounted::unrefer() { #ifdef _WINDOWS if (InterlockedDecrement(&this->mRefCount) <= 0) { delete this; } #else #ifdef MACOSX if (OSAtomicDecrement32Barrier(&(this->mRefCount)) <= 0) { delete this; } #else dlib::auto_mutex lock(sRefMutex); if (--mRefCount <= 0) { delete this; } #endif #endif } <commit_msg>Made windows interlocked increment cleaner like *nix version.<commit_after>/* * Copyright Copyright 2012, System Insights, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ref_counted.hpp" #include "dlib/threads.h" #include <libkern/OSAtomic.h> static dlib::rmutex sRefMutex; RefCounted::~RefCounted() { } void RefCounted::referTo() { #ifdef _WINDOWS InterlockedIncrement(&(this->mRefCount)); #else #ifdef MACOSX OSAtomicIncrement32Barrier(&(this->mRefCount)); #else dlib::auto_mutex lock(sRefMutex); mRefCount++; #endif #endif } void RefCounted::unrefer() { #ifdef _WINDOWS if (InterlockedDecrement(&(this->mRefCount)) <= 0) { delete this; } #else #ifdef MACOSX if (OSAtomicDecrement32Barrier(&(this->mRefCount)) <= 0) { delete this; } #else dlib::auto_mutex lock(sRefMutex); if (--mRefCount <= 0) { delete this; } #endif #endif } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ImplHelper.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: hr $ $Date: 2006-06-20 06:07:29 $ * * 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 * ************************************************************************/ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _IMPLHELPER_HXX_ #include "ImplHelper.hxx" #endif #ifndef _RTL_TENCINFO_H #include <rtl/tencinfo.h> #endif #ifndef _RTL_MEMORY_H_ #include <rtl/memory.h> #endif #include <memory> #if defined _MSC_VER #pragma warning(push,1) #endif #include <windows.h> #if defined _MSC_VER #pragma warning(pop) #endif //------------------------------------------------------------------------ // defines //------------------------------------------------------------------------ #define FORMATETC_EXACT_MATCH 1 #define FORMATETC_PARTIAL_MATCH -1 #define FORMATETC_NO_MATCH 0 //------------------------------------------------------------------------ // namespace directives //------------------------------------------------------------------------ using ::rtl::OUString; using ::rtl::OString; //------------------------------------------------------------------------ // returns a windows codepage appropriate to the // given mime charset parameter value //------------------------------------------------------------------------ sal_uInt32 SAL_CALL getWinCPFromMimeCharset( const OUString& charset ) { sal_uInt32 winCP = GetACP( ); if ( charset.getLength( ) ) { OString osCharset( charset.getStr( ), charset.getLength( ), RTL_TEXTENCODING_ASCII_US ); rtl_TextEncoding txtEnc = rtl_getTextEncodingFromMimeCharset( osCharset.getStr( ) ); sal_uInt32 winChrs = rtl_getBestWindowsCharsetFromTextEncoding( txtEnc ); CHARSETINFO chrsInf; sal_Bool bRet = TranslateCharsetInfo( (DWORD*)winChrs, &chrsInf, TCI_SRCCHARSET ) ? sal_True : sal_False; // if one of the above functions fails // we will return the current ANSI codepage // of this thread if ( bRet ) winCP = chrsInf.ciACP; } return winCP; } //-------------------------------------------------- // returns a windows codepage appropriate to the // given locale and locale type //-------------------------------------------------- OUString SAL_CALL getWinCPFromLocaleId( LCID lcid, LCTYPE lctype ) { OSL_ASSERT( IsValidLocale( lcid, LCID_SUPPORTED ) ); // we set an default value OUString winCP; // set an default value sal_Unicode wcstr[10]; if ( LOCALE_IDEFAULTCODEPAGE == lctype ) { _itow( GetOEMCP( ), wcstr, 10 ); winCP = OUString( wcstr, wcslen( wcstr ) ); } else if ( LOCALE_IDEFAULTANSICODEPAGE == lctype ) { _itow( GetACP( ), wcstr, 10 ); winCP = OUString( wcstr, wcslen( wcstr ) ); } else OSL_ASSERT( sal_False ); // we use the GetLocaleInfoA because don't want to provide // a unicode wrapper function for Win9x in sal/systools char buff[6]; sal_Int32 nResult = GetLocaleInfoA( lcid, lctype | LOCALE_USE_CP_ACP, buff, sizeof( buff ) ); OSL_ASSERT( nResult ); if ( nResult ) { sal_Int32 len = MultiByteToWideChar( CP_ACP, 0, buff, -1, NULL, 0 ); OSL_ASSERT( len > 0 ); std::auto_ptr< sal_Unicode > lpwchBuff( new sal_Unicode[len] ); if ( NULL != lpwchBuff.get( ) ) { len = MultiByteToWideChar( CP_ACP, 0, buff, -1, lpwchBuff.get( ), len ); winCP = OUString( lpwchBuff.get( ), (len - 1) ); } } return winCP; } //-------------------------------------------------- // returns a mime charset parameter value appropriate // to the given codepage, optional a prefix can be // given, e.g. "windows-" or "cp" //-------------------------------------------------- OUString SAL_CALL getMimeCharsetFromWinCP( sal_uInt32 cp, const OUString& aPrefix ) { return aPrefix + cptostr( cp ); } //-------------------------------------------------- // returns a mime charset parameter value appropriate // to the given locale id and locale type, optional a // prefix can be given, e.g. "windows-" or "cp" //-------------------------------------------------- OUString SAL_CALL getMimeCharsetFromLocaleId( LCID lcid, LCTYPE lctype, const OUString& aPrefix ) { OUString charset = getWinCPFromLocaleId( lcid, lctype ); return aPrefix + charset; } //------------------------------------------------------------------------ // IsOEMCP //------------------------------------------------------------------------ sal_Bool SAL_CALL IsOEMCP( sal_uInt32 codepage ) { OSL_ASSERT( IsValidCodePage( codepage ) ); sal_uInt32 arrOEMCP[] = { 437, 708, 709, 710, 720, 737, 775, 850, 852, 855, 857, 860, 861, 862, 863, 864, 865, 866, 869, 874, 932, 936, 949, 950, 1361 }; for ( sal_Int8 i = 0; i < ( sizeof( arrOEMCP )/sizeof( sal_uInt32 ) ); ++i ) if ( arrOEMCP[i] == codepage ) return sal_True; return sal_False; } //------------------------------------------------------------------------ // converts a codepage into its string representation //------------------------------------------------------------------------ OUString SAL_CALL cptostr( sal_uInt32 codepage ) { OSL_ASSERT( IsValidCodePage( codepage ) ); sal_Unicode cpStr[6]; _itow( codepage, cpStr, 10 ); return OUString( cpStr, wcslen( cpStr ) ); } //------------------------------------------------------------------------- // OleStdDeleteTargetDevice() // // Purpose: // // Parameters: // // Return Value: // SCODE - S_OK if successful //------------------------------------------------------------------------- void SAL_CALL DeleteTargetDevice( DVTARGETDEVICE* ptd ) { __try { CoTaskMemFree( ptd ); } __except( EXCEPTION_EXECUTE_HANDLER ) { OSL_ENSURE( sal_False, "Error DeleteTargetDevice" ); } } //------------------------------------------------------------------------- // OleStdCopyTargetDevice() // // Purpose: // duplicate a TARGETDEVICE struct. this function allocates memory for // the copy. the caller MUST free the allocated copy when done with it // using the standard allocator returned from CoGetMalloc. // (OleStdFree can be used to free the copy). // // Parameters: // ptdSrc pointer to source TARGETDEVICE // // Return Value: // pointer to allocated copy of ptdSrc // if ptdSrc==NULL then retuns NULL is returned. // if ptdSrc!=NULL and memory allocation fails, then NULL is returned //------------------------------------------------------------------------- DVTARGETDEVICE* SAL_CALL CopyTargetDevice( DVTARGETDEVICE* ptdSrc ) { DVTARGETDEVICE* ptdDest = NULL; __try { if ( NULL != ptdSrc ) { ptdDest = static_cast< DVTARGETDEVICE* >( CoTaskMemAlloc( ptdSrc->tdSize ) ); rtl_copyMemory( ptdDest, ptdSrc, static_cast< size_t >( ptdSrc->tdSize ) ); } } __except( EXCEPTION_EXECUTE_HANDLER ) { } return ptdDest; } //------------------------------------------------------------------------- // OleStdCopyFormatEtc() // // Purpose: // Copies the contents of a FORMATETC structure. this function takes // special care to copy correctly copying the pointer to the TARGETDEVICE // contained within the source FORMATETC structure. // if the source FORMATETC has a non-NULL TARGETDEVICE, then a copy // of the TARGETDEVICE will be allocated for the destination of the // FORMATETC (petcDest). // // NOTE: the caller MUST free the allocated copy of the TARGETDEVICE // within the destination FORMATETC when done with it // using the standard allocator returned from CoGetMalloc. // (OleStdFree can be used to free the copy). // // Parameters: // petcDest pointer to destination FORMATETC // petcSrc pointer to source FORMATETC // // Return Value: // returns TRUE if copy was successful; // retuns FALSE if not successful, e.g. one or both of the pointers // were invalid or the pointers were equal //------------------------------------------------------------------------- sal_Bool SAL_CALL CopyFormatEtc( LPFORMATETC petcDest, LPFORMATETC petcSrc ) { sal_Bool bRet = sal_False; __try { if ( petcDest == petcSrc ) __leave; petcDest->cfFormat = petcSrc->cfFormat; petcDest->ptd = NULL; if ( NULL != petcSrc->ptd ) petcDest->ptd = CopyTargetDevice(petcSrc->ptd); petcDest->dwAspect = petcSrc->dwAspect; petcDest->lindex = petcSrc->lindex; petcDest->tymed = petcSrc->tymed; bRet = sal_True; } __except( EXCEPTION_EXECUTE_HANDLER ) { OSL_ENSURE( sal_False, "Error CopyFormatEtc" ); } return bRet; } //------------------------------------------------------------------------- // returns: // 1 for exact match, // 0 for no match, // -1 for partial match (which is defined to mean the left is a subset // of the right: fewer aspects, null target device, fewer medium). //------------------------------------------------------------------------- sal_Int32 SAL_CALL CompareFormatEtc( const FORMATETC* pFetcLhs, const FORMATETC* pFetcRhs ) { sal_Int32 nMatch = FORMATETC_EXACT_MATCH; __try { if ( pFetcLhs == pFetcRhs ) __leave; if ( ( pFetcLhs->cfFormat != pFetcRhs->cfFormat ) || ( pFetcLhs->lindex != pFetcRhs->lindex ) || !CompareTargetDevice( pFetcLhs->ptd, pFetcRhs->ptd ) ) { nMatch = FORMATETC_NO_MATCH; __leave; } if ( pFetcLhs->dwAspect == pFetcRhs->dwAspect ) // same aspects; equal ; else if ( ( pFetcLhs->dwAspect & ~pFetcRhs->dwAspect ) != 0 ) { // left not subset of aspects of right; not equal nMatch = FORMATETC_NO_MATCH; __leave; } else // left subset of right nMatch = FORMATETC_PARTIAL_MATCH; if ( pFetcLhs->tymed == pFetcRhs->tymed ) // same medium flags; equal ; else if ( ( pFetcLhs->tymed & ~pFetcRhs->tymed ) != 0 ) { // left not subset of medium flags of right; not equal nMatch = FORMATETC_NO_MATCH; __leave; } else // left subset of right nMatch = FORMATETC_PARTIAL_MATCH; } __except( EXCEPTION_EXECUTE_HANDLER ) { OSL_ENSURE( sal_False, "Error CompareFormatEtc" ); nMatch = FORMATETC_NO_MATCH; } return nMatch; } //------------------------------------------------------------------------- // //------------------------------------------------------------------------- sal_Bool SAL_CALL CompareTargetDevice( DVTARGETDEVICE* ptdLeft, DVTARGETDEVICE* ptdRight ) { sal_Bool bRet = sal_False; __try { if ( ptdLeft == ptdRight ) { // same address of td; must be same (handles NULL case) bRet = sal_True; __leave; } // one ot the two is NULL if ( ( NULL == ptdRight ) || ( NULL == ptdLeft ) ) __leave; if ( ptdLeft->tdSize != ptdRight->tdSize ) __leave; if ( rtl_compareMemory( ptdLeft, ptdRight, ptdLeft->tdSize ) == 0 ) bRet = sal_True; } __except( EXCEPTION_EXECUTE_HANDLER ) { OSL_ENSURE( sal_False, "Error CompareTargetDevice" ); bRet = sal_False; } return bRet; } <commit_msg>INTEGRATION: CWS pchfix02 (1.15.14); FILE MERGED 2006/09/01 17:25:40 kaib 1.15.14.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ImplHelper.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: obo $ $Date: 2006-09-17 17:02:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dtrans.hxx" //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _IMPLHELPER_HXX_ #include "ImplHelper.hxx" #endif #ifndef _RTL_TENCINFO_H #include <rtl/tencinfo.h> #endif #ifndef _RTL_MEMORY_H_ #include <rtl/memory.h> #endif #include <memory> #if defined _MSC_VER #pragma warning(push,1) #endif #include <windows.h> #if defined _MSC_VER #pragma warning(pop) #endif //------------------------------------------------------------------------ // defines //------------------------------------------------------------------------ #define FORMATETC_EXACT_MATCH 1 #define FORMATETC_PARTIAL_MATCH -1 #define FORMATETC_NO_MATCH 0 //------------------------------------------------------------------------ // namespace directives //------------------------------------------------------------------------ using ::rtl::OUString; using ::rtl::OString; //------------------------------------------------------------------------ // returns a windows codepage appropriate to the // given mime charset parameter value //------------------------------------------------------------------------ sal_uInt32 SAL_CALL getWinCPFromMimeCharset( const OUString& charset ) { sal_uInt32 winCP = GetACP( ); if ( charset.getLength( ) ) { OString osCharset( charset.getStr( ), charset.getLength( ), RTL_TEXTENCODING_ASCII_US ); rtl_TextEncoding txtEnc = rtl_getTextEncodingFromMimeCharset( osCharset.getStr( ) ); sal_uInt32 winChrs = rtl_getBestWindowsCharsetFromTextEncoding( txtEnc ); CHARSETINFO chrsInf; sal_Bool bRet = TranslateCharsetInfo( (DWORD*)winChrs, &chrsInf, TCI_SRCCHARSET ) ? sal_True : sal_False; // if one of the above functions fails // we will return the current ANSI codepage // of this thread if ( bRet ) winCP = chrsInf.ciACP; } return winCP; } //-------------------------------------------------- // returns a windows codepage appropriate to the // given locale and locale type //-------------------------------------------------- OUString SAL_CALL getWinCPFromLocaleId( LCID lcid, LCTYPE lctype ) { OSL_ASSERT( IsValidLocale( lcid, LCID_SUPPORTED ) ); // we set an default value OUString winCP; // set an default value sal_Unicode wcstr[10]; if ( LOCALE_IDEFAULTCODEPAGE == lctype ) { _itow( GetOEMCP( ), wcstr, 10 ); winCP = OUString( wcstr, wcslen( wcstr ) ); } else if ( LOCALE_IDEFAULTANSICODEPAGE == lctype ) { _itow( GetACP( ), wcstr, 10 ); winCP = OUString( wcstr, wcslen( wcstr ) ); } else OSL_ASSERT( sal_False ); // we use the GetLocaleInfoA because don't want to provide // a unicode wrapper function for Win9x in sal/systools char buff[6]; sal_Int32 nResult = GetLocaleInfoA( lcid, lctype | LOCALE_USE_CP_ACP, buff, sizeof( buff ) ); OSL_ASSERT( nResult ); if ( nResult ) { sal_Int32 len = MultiByteToWideChar( CP_ACP, 0, buff, -1, NULL, 0 ); OSL_ASSERT( len > 0 ); std::auto_ptr< sal_Unicode > lpwchBuff( new sal_Unicode[len] ); if ( NULL != lpwchBuff.get( ) ) { len = MultiByteToWideChar( CP_ACP, 0, buff, -1, lpwchBuff.get( ), len ); winCP = OUString( lpwchBuff.get( ), (len - 1) ); } } return winCP; } //-------------------------------------------------- // returns a mime charset parameter value appropriate // to the given codepage, optional a prefix can be // given, e.g. "windows-" or "cp" //-------------------------------------------------- OUString SAL_CALL getMimeCharsetFromWinCP( sal_uInt32 cp, const OUString& aPrefix ) { return aPrefix + cptostr( cp ); } //-------------------------------------------------- // returns a mime charset parameter value appropriate // to the given locale id and locale type, optional a // prefix can be given, e.g. "windows-" or "cp" //-------------------------------------------------- OUString SAL_CALL getMimeCharsetFromLocaleId( LCID lcid, LCTYPE lctype, const OUString& aPrefix ) { OUString charset = getWinCPFromLocaleId( lcid, lctype ); return aPrefix + charset; } //------------------------------------------------------------------------ // IsOEMCP //------------------------------------------------------------------------ sal_Bool SAL_CALL IsOEMCP( sal_uInt32 codepage ) { OSL_ASSERT( IsValidCodePage( codepage ) ); sal_uInt32 arrOEMCP[] = { 437, 708, 709, 710, 720, 737, 775, 850, 852, 855, 857, 860, 861, 862, 863, 864, 865, 866, 869, 874, 932, 936, 949, 950, 1361 }; for ( sal_Int8 i = 0; i < ( sizeof( arrOEMCP )/sizeof( sal_uInt32 ) ); ++i ) if ( arrOEMCP[i] == codepage ) return sal_True; return sal_False; } //------------------------------------------------------------------------ // converts a codepage into its string representation //------------------------------------------------------------------------ OUString SAL_CALL cptostr( sal_uInt32 codepage ) { OSL_ASSERT( IsValidCodePage( codepage ) ); sal_Unicode cpStr[6]; _itow( codepage, cpStr, 10 ); return OUString( cpStr, wcslen( cpStr ) ); } //------------------------------------------------------------------------- // OleStdDeleteTargetDevice() // // Purpose: // // Parameters: // // Return Value: // SCODE - S_OK if successful //------------------------------------------------------------------------- void SAL_CALL DeleteTargetDevice( DVTARGETDEVICE* ptd ) { __try { CoTaskMemFree( ptd ); } __except( EXCEPTION_EXECUTE_HANDLER ) { OSL_ENSURE( sal_False, "Error DeleteTargetDevice" ); } } //------------------------------------------------------------------------- // OleStdCopyTargetDevice() // // Purpose: // duplicate a TARGETDEVICE struct. this function allocates memory for // the copy. the caller MUST free the allocated copy when done with it // using the standard allocator returned from CoGetMalloc. // (OleStdFree can be used to free the copy). // // Parameters: // ptdSrc pointer to source TARGETDEVICE // // Return Value: // pointer to allocated copy of ptdSrc // if ptdSrc==NULL then retuns NULL is returned. // if ptdSrc!=NULL and memory allocation fails, then NULL is returned //------------------------------------------------------------------------- DVTARGETDEVICE* SAL_CALL CopyTargetDevice( DVTARGETDEVICE* ptdSrc ) { DVTARGETDEVICE* ptdDest = NULL; __try { if ( NULL != ptdSrc ) { ptdDest = static_cast< DVTARGETDEVICE* >( CoTaskMemAlloc( ptdSrc->tdSize ) ); rtl_copyMemory( ptdDest, ptdSrc, static_cast< size_t >( ptdSrc->tdSize ) ); } } __except( EXCEPTION_EXECUTE_HANDLER ) { } return ptdDest; } //------------------------------------------------------------------------- // OleStdCopyFormatEtc() // // Purpose: // Copies the contents of a FORMATETC structure. this function takes // special care to copy correctly copying the pointer to the TARGETDEVICE // contained within the source FORMATETC structure. // if the source FORMATETC has a non-NULL TARGETDEVICE, then a copy // of the TARGETDEVICE will be allocated for the destination of the // FORMATETC (petcDest). // // NOTE: the caller MUST free the allocated copy of the TARGETDEVICE // within the destination FORMATETC when done with it // using the standard allocator returned from CoGetMalloc. // (OleStdFree can be used to free the copy). // // Parameters: // petcDest pointer to destination FORMATETC // petcSrc pointer to source FORMATETC // // Return Value: // returns TRUE if copy was successful; // retuns FALSE if not successful, e.g. one or both of the pointers // were invalid or the pointers were equal //------------------------------------------------------------------------- sal_Bool SAL_CALL CopyFormatEtc( LPFORMATETC petcDest, LPFORMATETC petcSrc ) { sal_Bool bRet = sal_False; __try { if ( petcDest == petcSrc ) __leave; petcDest->cfFormat = petcSrc->cfFormat; petcDest->ptd = NULL; if ( NULL != petcSrc->ptd ) petcDest->ptd = CopyTargetDevice(petcSrc->ptd); petcDest->dwAspect = petcSrc->dwAspect; petcDest->lindex = petcSrc->lindex; petcDest->tymed = petcSrc->tymed; bRet = sal_True; } __except( EXCEPTION_EXECUTE_HANDLER ) { OSL_ENSURE( sal_False, "Error CopyFormatEtc" ); } return bRet; } //------------------------------------------------------------------------- // returns: // 1 for exact match, // 0 for no match, // -1 for partial match (which is defined to mean the left is a subset // of the right: fewer aspects, null target device, fewer medium). //------------------------------------------------------------------------- sal_Int32 SAL_CALL CompareFormatEtc( const FORMATETC* pFetcLhs, const FORMATETC* pFetcRhs ) { sal_Int32 nMatch = FORMATETC_EXACT_MATCH; __try { if ( pFetcLhs == pFetcRhs ) __leave; if ( ( pFetcLhs->cfFormat != pFetcRhs->cfFormat ) || ( pFetcLhs->lindex != pFetcRhs->lindex ) || !CompareTargetDevice( pFetcLhs->ptd, pFetcRhs->ptd ) ) { nMatch = FORMATETC_NO_MATCH; __leave; } if ( pFetcLhs->dwAspect == pFetcRhs->dwAspect ) // same aspects; equal ; else if ( ( pFetcLhs->dwAspect & ~pFetcRhs->dwAspect ) != 0 ) { // left not subset of aspects of right; not equal nMatch = FORMATETC_NO_MATCH; __leave; } else // left subset of right nMatch = FORMATETC_PARTIAL_MATCH; if ( pFetcLhs->tymed == pFetcRhs->tymed ) // same medium flags; equal ; else if ( ( pFetcLhs->tymed & ~pFetcRhs->tymed ) != 0 ) { // left not subset of medium flags of right; not equal nMatch = FORMATETC_NO_MATCH; __leave; } else // left subset of right nMatch = FORMATETC_PARTIAL_MATCH; } __except( EXCEPTION_EXECUTE_HANDLER ) { OSL_ENSURE( sal_False, "Error CompareFormatEtc" ); nMatch = FORMATETC_NO_MATCH; } return nMatch; } //------------------------------------------------------------------------- // //------------------------------------------------------------------------- sal_Bool SAL_CALL CompareTargetDevice( DVTARGETDEVICE* ptdLeft, DVTARGETDEVICE* ptdRight ) { sal_Bool bRet = sal_False; __try { if ( ptdLeft == ptdRight ) { // same address of td; must be same (handles NULL case) bRet = sal_True; __leave; } // one ot the two is NULL if ( ( NULL == ptdRight ) || ( NULL == ptdLeft ) ) __leave; if ( ptdLeft->tdSize != ptdRight->tdSize ) __leave; if ( rtl_compareMemory( ptdLeft, ptdRight, ptdLeft->tdSize ) == 0 ) bRet = sal_True; } __except( EXCEPTION_EXECUTE_HANDLER ) { OSL_ENSURE( sal_False, "Error CompareTargetDevice" ); bRet = sal_False; } return bRet; } <|endoftext|>
<commit_before>#include <config.h> #include "grid_creation.hh" #include <dune/stuff/common/ranges.hh> #include <dune/stuff/grid/structuredgridfactory.hh> #include <dune/stuff/grid/information.hh> std::pair<std::shared_ptr<Dune::Multiscale::CommonTraits::GridType>, std::shared_ptr<Dune::Multiscale::CommonTraits::GridType>> Dune::Multiscale::make_grids() { const int dim_world = CommonTraits::GridType::dimensionworld; typedef FieldVector<typename CommonTraits::GridType::ctype, dim_world> CoordType; CoordType lowerLeft(0.0); CoordType upperRight(1.0); const auto coarse_cells = DSC_CONFIG_GET("global.macro_cells_per_dim", 8); array<unsigned int, dim_world> elements; for (const auto i : DSC::valueRange(dim_world)) elements[i] = coarse_cells; auto coarse_gridptr = StructuredGridFactory<CommonTraits::GridType>::createCubeGrid(lowerLeft, upperRight, elements, overCoarse); for (const auto i : DSC::valueRange(dim_world)) { elements[i] = coarse_cells * DSC_CONFIG_GET("global.micro_cells_per_macrocell_dim", 8); } auto fine_gridptr = StructuredGridFactory<CommonTraits::GridType>::createCubeGrid(lowerLeft, upperRight, elements); return {coarse_gridptr, fine_gridptr}; } <commit_msg>[gridCreation] compute necessary number of overlap layers for coarse grid<commit_after>#include <config.h> #include "grid_creation.hh" #include <dune/stuff/common/ranges.hh> #include <dune/stuff/grid/structuredgridfactory.hh> #include <dune/stuff/grid/information.hh> std::pair<std::shared_ptr<Dune::Multiscale::CommonTraits::GridType>, std::shared_ptr<Dune::Multiscale::CommonTraits::GridType>> Dune::Multiscale::make_grids() { const int dim_world = CommonTraits::GridType::dimensionworld; typedef FieldVector<typename CommonTraits::GridType::ctype, dim_world> CoordType; CoordType lowerLeft(0.0); CoordType upperRight(1.0); const auto oversamplingLayers = DSC_CONFIG_GET("msfem.oversampling_layers", 0); const auto microPerMacro = DSC_CONFIG_GET("msfem.micro_cells_per_macrocell_dim", 8); const int overlapLayers = std::ceil(double(oversamplingLayers)/double(microPerMacro)); const auto coarse_cells = DSC_CONFIG_GET("global.macro_cells_per_dim", 8); array<unsigned int, dim_world> elements; array<unsigned int, dim_world> overCoarse; for (const auto i : DSC::valueRange(dim_world)) { elements[i] = coarse_cells; overCoarse[i] = overlapLayers; } auto coarse_gridptr = StructuredGridFactory<CommonTraits::GridType>::createCubeGrid(lowerLeft, upperRight, elements, overCoarse); for (const auto i : DSC::valueRange(dim_world)) { elements[i] = coarse_cells * DSC_CONFIG_GET("global.micro_cells_per_macrocell_dim", 8); } auto fine_gridptr = StructuredGridFactory<CommonTraits::GridType>::createCubeGrid(lowerLeft, upperRight, elements); return {coarse_gridptr, fine_gridptr}; } <|endoftext|>
<commit_before>// Ouzel by Elviss Strazdins #ifndef OUZEL_CORE_NATIVEWINDOWMACOS_HPP #define OUZEL_CORE_NATIVEWINDOWMACOS_HPP #include <CoreGraphics/CGGeometry.h> #include <CoreGraphics/CoreGraphics.h> #ifdef __OBJC__ # import <Cocoa/Cocoa.h> typedef NSWindow* NSWindowPtr; typedef NSView* NSViewPtr; typedef id<NSWindowDelegate> NSWindowDelegatePtr; typedef NSScreen* NSScreenPtr; #else # include <objc/NSObjCRuntime.h> typedef id NSWindowPtr; typedef id NSViewPtr; typedef id NSWindowDelegatePtr; typedef id NSScreenPtr; typedef std::uint32_t CGDirectDisplayID; #endif #include "../NativeWindow.hpp" #include "../../graphics/Graphics.hpp" namespace ouzel::core::macos { class NativeWindow final: public core::NativeWindow { public: NativeWindow(const math::Size<std::uint32_t, 2>& newSize, bool newResizable, bool newFullscreen, bool newExclusiveFullscreen, const std::string& newTitle, graphics::Driver graphicsDriver, bool newHighDpi); ~NativeWindow() override; void close(); void setSize(const math::Size<std::uint32_t, 2>& newSize); void setFullscreen(bool newFullscreen); void setTitle(const std::string& newTitle); void bringToFront(); void show(); void hide(); void minimize(); void maximize(); void restore(); void handleResize(); void handleClose(); void handleMinituarize(); void handleDeminituarize(); void handleFullscreenChange(bool newFullscreen); void handleScaleFactorChange(); void handleScreenChange(); void handleBecomeKeyChange(); void handleResignKeyChange(); auto getNativeWindow() const noexcept { return window; } auto getNativeView() const noexcept { return view; } auto getScreen() const noexcept { return screen; } auto getDisplayId() const noexcept { return displayId; } private: void executeCommand(const Command& command) final; NSWindowPtr window = nil; NSViewPtr view = nil; NSWindowDelegatePtr windowDelegate = nil; NSScreenPtr screen = nil; CGDirectDisplayID displayId = 0; NSUInteger windowStyleMask = 0; CGRect windowRect; }; } #endif // OUZEL_CORE_NATIVEWINDOWMACOS_HPP <commit_msg>Include only Driver.hpp<commit_after>// Ouzel by Elviss Strazdins #ifndef OUZEL_CORE_NATIVEWINDOWMACOS_HPP #define OUZEL_CORE_NATIVEWINDOWMACOS_HPP #include <CoreGraphics/CGGeometry.h> #include <CoreGraphics/CoreGraphics.h> #ifdef __OBJC__ # import <Cocoa/Cocoa.h> typedef NSWindow* NSWindowPtr; typedef NSView* NSViewPtr; typedef id<NSWindowDelegate> NSWindowDelegatePtr; typedef NSScreen* NSScreenPtr; #else # include <objc/NSObjCRuntime.h> typedef id NSWindowPtr; typedef id NSViewPtr; typedef id NSWindowDelegatePtr; typedef id NSScreenPtr; typedef std::uint32_t CGDirectDisplayID; #endif #include "../NativeWindow.hpp" #include "../../graphics/Driver.hpp" namespace ouzel::core::macos { class NativeWindow final: public core::NativeWindow { public: NativeWindow(const math::Size<std::uint32_t, 2>& newSize, bool newResizable, bool newFullscreen, bool newExclusiveFullscreen, const std::string& newTitle, graphics::Driver graphicsDriver, bool newHighDpi); ~NativeWindow() override; void close(); void setSize(const math::Size<std::uint32_t, 2>& newSize); void setFullscreen(bool newFullscreen); void setTitle(const std::string& newTitle); void bringToFront(); void show(); void hide(); void minimize(); void maximize(); void restore(); void handleResize(); void handleClose(); void handleMinituarize(); void handleDeminituarize(); void handleFullscreenChange(bool newFullscreen); void handleScaleFactorChange(); void handleScreenChange(); void handleBecomeKeyChange(); void handleResignKeyChange(); auto getNativeWindow() const noexcept { return window; } auto getNativeView() const noexcept { return view; } auto getScreen() const noexcept { return screen; } auto getDisplayId() const noexcept { return displayId; } private: void executeCommand(const Command& command) final; NSWindowPtr window = nil; NSViewPtr view = nil; NSWindowDelegatePtr windowDelegate = nil; NSScreenPtr screen = nil; CGDirectDisplayID displayId = 0; NSUInteger windowStyleMask = 0; CGRect windowRect; }; } #endif // OUZEL_CORE_NATIVEWINDOWMACOS_HPP <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkScatterPlotMatrix.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkScatterPlotMatrix.h" #include "vtkTable.h" #include "vtkFloatArray.h" #include "vtkIntArray.h" #include "vtkChartXY.h" #include "vtkPlot.h" #include "vtkAxis.h" #include "vtkStdString.h" #include "vtkStringArray.h" #include "vtkNew.h" #include "vtkMathUtilities.h" #include "vtkObjectFactory.h" class vtkScatterPlotMatrix::PIMPL { public: PIMPL() : VisibleColumnsModified(true), BigChart(NULL) { } ~PIMPL() { } vtkNew<vtkTable> Histogram; bool VisibleColumnsModified; vtkChart* BigChart; }; namespace { int NumberOfBins = 10; // This is just here for now - quick and dirty historgram calculations... bool PopulateHistograms(vtkTable *input, vtkTable *output, vtkStringArray *s) { // The output table will have the twice the number of columns, they will be // the x and y for input column. This is the bin centers, and the population. for (vtkIdType i = output->GetNumberOfColumns() - 1; i >= 0; --i) { output->RemoveColumn(i); } for (vtkIdType i = 0; i < s->GetNumberOfTuples(); ++i) { double minmax[2] = { 0.0, 0.0 }; vtkStdString name(s->GetValue(i)); vtkDataArray *in = vtkDataArray::SafeDownCast(input->GetColumnByName(name.c_str())); if (in) { // The bin values are the centers, extending +/- half an inc either side in->GetRange(minmax); if (minmax[0] == minmax[1]) { minmax[1] = minmax[0] + 1.0; } double inc = (minmax[1] - minmax[0]) / NumberOfBins; double halfInc = inc / 2.0; vtkNew<vtkFloatArray> extents; extents->SetName(vtkStdString(name + "_extents").c_str()); extents->SetNumberOfTuples(NumberOfBins); float *centers = static_cast<float *>(extents->GetVoidPointer(0)); for (int j = 0; j < NumberOfBins; ++j) { extents->SetValue(j, minmax[0] + j * inc); } vtkNew<vtkIntArray> populations; populations->SetName(vtkStdString(name + "_pops").c_str()); populations->SetNumberOfTuples(NumberOfBins); int *pops = static_cast<int *>(populations->GetVoidPointer(0)); for (int k = 0; k < NumberOfBins; ++k) { pops[k] = 0; } for (vtkIdType j = 0; j < in->GetNumberOfTuples(); ++j) { double v(0.0); in->GetTuple(j, &v); for (int k = 0; k < NumberOfBins; ++k) { if (vtkMathUtilities::FuzzyCompare(v, double(centers[k]), halfInc)) { ++pops[k]; break; } } } output->AddColumn(extents.GetPointer()); output->AddColumn(populations.GetPointer()); } } return true; } } vtkStandardNewMacro(vtkScatterPlotMatrix) vtkScatterPlotMatrix::vtkScatterPlotMatrix() { this->Private = new PIMPL; } vtkScatterPlotMatrix::~vtkScatterPlotMatrix() { delete this->Private; } void vtkScatterPlotMatrix::Update() { if (this->Private->VisibleColumnsModified) { // We need to handle layout changes due to modified visibility. // Build up our histograms data before updating the layout. PopulateHistograms(this->Input.GetPointer(), this->Private->Histogram.GetPointer(), this->VisibleColumns.GetPointer()); this->UpdateLayout(); this->Private->VisibleColumnsModified = false; } } bool vtkScatterPlotMatrix::Paint(vtkContext2D *painter) { this->Update(); return Superclass::Paint(painter); } bool vtkScatterPlotMatrix::SetActivePlot(const vtkVector2i &pos) { if (pos.X() + pos.Y() + 1 < this->Size.X() && pos.X() < this->Size.X() && pos.Y() < this->Size.Y()) { // The supplied index is valid (in the lower quadrant). this->ActivePlot = pos; if (this->Private->BigChart) { vtkPlot *plot = this->Private->BigChart->GetPlot(0); if (!plot) { plot = this->Private->BigChart->AddPlot(vtkChart::POINTS); vtkChartXY *xy = vtkChartXY::SafeDownCast(this->Private->BigChart); if (xy) { xy->SetPlotCorner(plot, 2); } } plot->SetInput(this->Input.GetPointer(), this->VisibleColumns->GetValue(pos.X()), this->VisibleColumns->GetValue(this->Size.X() - pos.Y() - 1)); } return true; } else { return false; } } vtkVector2i vtkScatterPlotMatrix::GetActivePlot() { return this->ActivePlot; } void vtkScatterPlotMatrix::SetInput(vtkTable *table) { if (this->Input != table) { // Set the input, then update the size of the scatter plot matrix, set // their inputs and all the other stuff needed. this->Input = table; this->Modified(); if (table == NULL) { this->SetSize(vtkVector2i(0, 0)); this->SetColumnVisibilityAll(true); return; } int n = static_cast<int>(this->Input->GetNumberOfColumns()); this->SetColumnVisibilityAll(true); this->SetSize(vtkVector2i(n, n)); } } void vtkScatterPlotMatrix::SetColumnVisibility(const vtkStdString &name, bool visible) { if (visible) { for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i) { if (this->VisibleColumns->GetValue(i) == name) { // Already there, nothing more needs to be done return; } } // Add the column to the end of the list this->VisibleColumns->InsertNextValue(name); this->Private->VisibleColumnsModified = true; this->SetSize(vtkVector2i(this->VisibleColumns->GetNumberOfTuples(), this->VisibleColumns->GetNumberOfTuples())); this->Modified(); } else { // Remove the value if present for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i) { if (this->VisibleColumns->GetValue(i) == name) { // Move all the later elements down by one, and reduce the size while (i < this->VisibleColumns->GetNumberOfTuples()-1) { this->VisibleColumns->SetValue(i, this->VisibleColumns->GetValue(i+1)); ++i; } this->VisibleColumns->SetNumberOfTuples( this->VisibleColumns->GetNumberOfTuples()-1); this->SetSize(vtkVector2i(this->VisibleColumns->GetNumberOfTuples(), this->VisibleColumns->GetNumberOfTuples())); this->Private->VisibleColumnsModified = true; this->Modified(); return; } } } } bool vtkScatterPlotMatrix::GetColumnVisibility(const vtkStdString &name) { for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i) { if (this->VisibleColumns->GetValue(i) == name) { return true; } } return false; } void vtkScatterPlotMatrix::SetColumnVisibilityAll(bool visible) { if (visible && this->Input) { vtkIdType n = this->Input->GetNumberOfColumns(); this->VisibleColumns->SetNumberOfTuples(n); for (vtkIdType i = 0; i < n; ++i) { this->VisibleColumns->SetValue(i, this->Input->GetColumnName(i)); } } else { this->SetSize(vtkVector2i(0, 0)); this->VisibleColumns->SetNumberOfTuples(0); } this->Private->VisibleColumnsModified = true; } vtkStringArray* vtkScatterPlotMatrix::GetVisibleColumns() { return this->VisibleColumns.GetPointer(); } void vtkScatterPlotMatrix::UpdateLayout() { // We want scatter plots on the lower-left triangle, then histograms along // the diagonal and a big plot in the top-right. The basic layout is, // // 0 H +++ // 1 S H +++ // 2 S S H // 3 S S S H // 0 1 2 3 // // Where the indices are those of the columns. The indices of the charts // originate in the bottom-left. int n = this->Size.X(); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { vtkVector2i pos(i, j); if (i + j + 1 < n) { // Lower-left triangle - scatter plots. vtkPlot *plot = this->GetChart(pos)->AddPlot(vtkChart::POINTS); plot->SetInput(this->Input.GetPointer(), i, n - j - 1); } else if (i == n - j - 1) { // We are on the diagonal - need a histogram plot. vtkPlot *plot = this->GetChart(pos)->AddPlot(vtkChart::BAR); vtkStdString name(this->VisibleColumns->GetValue(i)); plot->SetInput(this->Private->Histogram.GetPointer(), name + "_extents", name + "_pops"); vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::TOP); axis->SetTitle(name.c_str()); if (i != n - 1) { axis->SetBehavior(vtkAxis::FIXED); } // Set the plot corner to the top-right vtkChartXY *xy = vtkChartXY::SafeDownCast(this->GetChart(pos)); if (xy) { xy->SetPlotCorner(plot, 2); } } else if (i == static_cast<int>(n / 2.0) + n % 2 && i == j) { // This big plot in the top-right this->Private->BigChart = this->GetChart(pos); this->SetChartSpan(pos, vtkVector2i(n - i, n - j)); this->SetActivePlot(vtkVector2i(0, n - 2)); } // Only show bottom axis label for bottom plots if (j > 0) { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::BOTTOM); axis->SetTitle(""); axis->SetLabelsVisible(false); axis->SetBehavior(vtkAxis::FIXED); } else { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::BOTTOM); axis->SetTitle(this->VisibleColumns->GetValue(i)); this->AttachAxisRangeListener(axis); } // Only show the left axis labels for left-most plots if (i > 0) { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::LEFT); axis->SetTitle(""); axis->SetLabelsVisible(false); axis->SetBehavior(vtkAxis::FIXED); } else { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::LEFT); axis->SetTitle(this->VisibleColumns->GetValue(n - j - 1)); this->AttachAxisRangeListener(axis); } } } } void vtkScatterPlotMatrix::AttachAxisRangeListener(vtkAxis* axis) { axis->AddObserver(vtkChart::UpdateRange, this, &vtkScatterPlotMatrix::AxisRangeForwarderCallback); } void vtkScatterPlotMatrix::AxisRangeForwarderCallback(vtkObject*, unsigned long, void*) { // Only set on the end axes, and propagated to all other matching axes. double r[2]; int n = this->GetSize().X() - 1; for (int i = 0; i < n; ++i) { this->GetChart(vtkVector2i(i, 0))->GetAxis(vtkAxis::BOTTOM)->GetRange(r); for (int j = 1; j < n - i; ++j) { this->GetChart(vtkVector2i(i, j))->GetAxis(vtkAxis::BOTTOM)->SetRange(r); } this->GetChart(vtkVector2i(i, n-i))->GetAxis(vtkAxis::TOP)->SetRange(r); this->GetChart(vtkVector2i(0, i))->GetAxis(vtkAxis::LEFT)->GetRange(r); for (int j = 1; j < n - i; ++j) { this->GetChart(vtkVector2i(j, i))->GetAxis(vtkAxis::LEFT)->SetRange(r); } } } void vtkScatterPlotMatrix::PrintSelf(ostream &os, vtkIndent indent) { Superclass::PrintSelf(os, indent); } <commit_msg>Add check for empty table to vtkScatterPlotMatrix::SetInput()<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkScatterPlotMatrix.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkScatterPlotMatrix.h" #include "vtkTable.h" #include "vtkFloatArray.h" #include "vtkIntArray.h" #include "vtkChartXY.h" #include "vtkPlot.h" #include "vtkAxis.h" #include "vtkStdString.h" #include "vtkStringArray.h" #include "vtkNew.h" #include "vtkMathUtilities.h" #include "vtkObjectFactory.h" class vtkScatterPlotMatrix::PIMPL { public: PIMPL() : VisibleColumnsModified(true), BigChart(NULL) { } ~PIMPL() { } vtkNew<vtkTable> Histogram; bool VisibleColumnsModified; vtkChart* BigChart; }; namespace { int NumberOfBins = 10; // This is just here for now - quick and dirty historgram calculations... bool PopulateHistograms(vtkTable *input, vtkTable *output, vtkStringArray *s) { // The output table will have the twice the number of columns, they will be // the x and y for input column. This is the bin centers, and the population. for (vtkIdType i = output->GetNumberOfColumns() - 1; i >= 0; --i) { output->RemoveColumn(i); } for (vtkIdType i = 0; i < s->GetNumberOfTuples(); ++i) { double minmax[2] = { 0.0, 0.0 }; vtkStdString name(s->GetValue(i)); vtkDataArray *in = vtkDataArray::SafeDownCast(input->GetColumnByName(name.c_str())); if (in) { // The bin values are the centers, extending +/- half an inc either side in->GetRange(minmax); if (minmax[0] == minmax[1]) { minmax[1] = minmax[0] + 1.0; } double inc = (minmax[1] - minmax[0]) / NumberOfBins; double halfInc = inc / 2.0; vtkNew<vtkFloatArray> extents; extents->SetName(vtkStdString(name + "_extents").c_str()); extents->SetNumberOfTuples(NumberOfBins); float *centers = static_cast<float *>(extents->GetVoidPointer(0)); for (int j = 0; j < NumberOfBins; ++j) { extents->SetValue(j, minmax[0] + j * inc); } vtkNew<vtkIntArray> populations; populations->SetName(vtkStdString(name + "_pops").c_str()); populations->SetNumberOfTuples(NumberOfBins); int *pops = static_cast<int *>(populations->GetVoidPointer(0)); for (int k = 0; k < NumberOfBins; ++k) { pops[k] = 0; } for (vtkIdType j = 0; j < in->GetNumberOfTuples(); ++j) { double v(0.0); in->GetTuple(j, &v); for (int k = 0; k < NumberOfBins; ++k) { if (vtkMathUtilities::FuzzyCompare(v, double(centers[k]), halfInc)) { ++pops[k]; break; } } } output->AddColumn(extents.GetPointer()); output->AddColumn(populations.GetPointer()); } } return true; } } vtkStandardNewMacro(vtkScatterPlotMatrix) vtkScatterPlotMatrix::vtkScatterPlotMatrix() { this->Private = new PIMPL; } vtkScatterPlotMatrix::~vtkScatterPlotMatrix() { delete this->Private; } void vtkScatterPlotMatrix::Update() { if (this->Private->VisibleColumnsModified) { // We need to handle layout changes due to modified visibility. // Build up our histograms data before updating the layout. PopulateHistograms(this->Input.GetPointer(), this->Private->Histogram.GetPointer(), this->VisibleColumns.GetPointer()); this->UpdateLayout(); this->Private->VisibleColumnsModified = false; } } bool vtkScatterPlotMatrix::Paint(vtkContext2D *painter) { this->Update(); return Superclass::Paint(painter); } bool vtkScatterPlotMatrix::SetActivePlot(const vtkVector2i &pos) { if (pos.X() + pos.Y() + 1 < this->Size.X() && pos.X() < this->Size.X() && pos.Y() < this->Size.Y()) { // The supplied index is valid (in the lower quadrant). this->ActivePlot = pos; if (this->Private->BigChart) { vtkPlot *plot = this->Private->BigChart->GetPlot(0); if (!plot) { plot = this->Private->BigChart->AddPlot(vtkChart::POINTS); vtkChartXY *xy = vtkChartXY::SafeDownCast(this->Private->BigChart); if (xy) { xy->SetPlotCorner(plot, 2); } } plot->SetInput(this->Input.GetPointer(), this->VisibleColumns->GetValue(pos.X()), this->VisibleColumns->GetValue(this->Size.X() - pos.Y() - 1)); } return true; } else { return false; } } vtkVector2i vtkScatterPlotMatrix::GetActivePlot() { return this->ActivePlot; } void vtkScatterPlotMatrix::SetInput(vtkTable *table) { if(table && table->GetNumberOfRows() == 0) { // do nothing if the table is emtpy return; } if (this->Input != table) { // Set the input, then update the size of the scatter plot matrix, set // their inputs and all the other stuff needed. this->Input = table; this->Modified(); if (table == NULL) { this->SetSize(vtkVector2i(0, 0)); this->SetColumnVisibilityAll(true); return; } int n = static_cast<int>(this->Input->GetNumberOfColumns()); this->SetColumnVisibilityAll(true); this->SetSize(vtkVector2i(n, n)); } } void vtkScatterPlotMatrix::SetColumnVisibility(const vtkStdString &name, bool visible) { if (visible) { for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i) { if (this->VisibleColumns->GetValue(i) == name) { // Already there, nothing more needs to be done return; } } // Add the column to the end of the list this->VisibleColumns->InsertNextValue(name); this->Private->VisibleColumnsModified = true; this->SetSize(vtkVector2i(this->VisibleColumns->GetNumberOfTuples(), this->VisibleColumns->GetNumberOfTuples())); this->Modified(); } else { // Remove the value if present for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i) { if (this->VisibleColumns->GetValue(i) == name) { // Move all the later elements down by one, and reduce the size while (i < this->VisibleColumns->GetNumberOfTuples()-1) { this->VisibleColumns->SetValue(i, this->VisibleColumns->GetValue(i+1)); ++i; } this->VisibleColumns->SetNumberOfTuples( this->VisibleColumns->GetNumberOfTuples()-1); this->SetSize(vtkVector2i(this->VisibleColumns->GetNumberOfTuples(), this->VisibleColumns->GetNumberOfTuples())); this->Private->VisibleColumnsModified = true; this->Modified(); return; } } } } bool vtkScatterPlotMatrix::GetColumnVisibility(const vtkStdString &name) { for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i) { if (this->VisibleColumns->GetValue(i) == name) { return true; } } return false; } void vtkScatterPlotMatrix::SetColumnVisibilityAll(bool visible) { if (visible && this->Input) { vtkIdType n = this->Input->GetNumberOfColumns(); this->VisibleColumns->SetNumberOfTuples(n); for (vtkIdType i = 0; i < n; ++i) { this->VisibleColumns->SetValue(i, this->Input->GetColumnName(i)); } } else { this->SetSize(vtkVector2i(0, 0)); this->VisibleColumns->SetNumberOfTuples(0); } this->Private->VisibleColumnsModified = true; } vtkStringArray* vtkScatterPlotMatrix::GetVisibleColumns() { return this->VisibleColumns.GetPointer(); } void vtkScatterPlotMatrix::UpdateLayout() { // We want scatter plots on the lower-left triangle, then histograms along // the diagonal and a big plot in the top-right. The basic layout is, // // 0 H +++ // 1 S H +++ // 2 S S H // 3 S S S H // 0 1 2 3 // // Where the indices are those of the columns. The indices of the charts // originate in the bottom-left. int n = this->Size.X(); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { vtkVector2i pos(i, j); if (i + j + 1 < n) { // Lower-left triangle - scatter plots. vtkPlot *plot = this->GetChart(pos)->AddPlot(vtkChart::POINTS); plot->SetInput(this->Input.GetPointer(), i, n - j - 1); } else if (i == n - j - 1) { // We are on the diagonal - need a histogram plot. vtkPlot *plot = this->GetChart(pos)->AddPlot(vtkChart::BAR); vtkStdString name(this->VisibleColumns->GetValue(i)); plot->SetInput(this->Private->Histogram.GetPointer(), name + "_extents", name + "_pops"); vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::TOP); axis->SetTitle(name.c_str()); if (i != n - 1) { axis->SetBehavior(vtkAxis::FIXED); } // Set the plot corner to the top-right vtkChartXY *xy = vtkChartXY::SafeDownCast(this->GetChart(pos)); if (xy) { xy->SetPlotCorner(plot, 2); } } else if (i == static_cast<int>(n / 2.0) + n % 2 && i == j) { // This big plot in the top-right this->Private->BigChart = this->GetChart(pos); this->SetChartSpan(pos, vtkVector2i(n - i, n - j)); this->SetActivePlot(vtkVector2i(0, n - 2)); } // Only show bottom axis label for bottom plots if (j > 0) { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::BOTTOM); axis->SetTitle(""); axis->SetLabelsVisible(false); axis->SetBehavior(vtkAxis::FIXED); } else { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::BOTTOM); axis->SetTitle(this->VisibleColumns->GetValue(i)); this->AttachAxisRangeListener(axis); } // Only show the left axis labels for left-most plots if (i > 0) { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::LEFT); axis->SetTitle(""); axis->SetLabelsVisible(false); axis->SetBehavior(vtkAxis::FIXED); } else { vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::LEFT); axis->SetTitle(this->VisibleColumns->GetValue(n - j - 1)); this->AttachAxisRangeListener(axis); } } } } void vtkScatterPlotMatrix::AttachAxisRangeListener(vtkAxis* axis) { axis->AddObserver(vtkChart::UpdateRange, this, &vtkScatterPlotMatrix::AxisRangeForwarderCallback); } void vtkScatterPlotMatrix::AxisRangeForwarderCallback(vtkObject*, unsigned long, void*) { // Only set on the end axes, and propagated to all other matching axes. double r[2]; int n = this->GetSize().X() - 1; for (int i = 0; i < n; ++i) { this->GetChart(vtkVector2i(i, 0))->GetAxis(vtkAxis::BOTTOM)->GetRange(r); for (int j = 1; j < n - i; ++j) { this->GetChart(vtkVector2i(i, j))->GetAxis(vtkAxis::BOTTOM)->SetRange(r); } this->GetChart(vtkVector2i(i, n-i))->GetAxis(vtkAxis::TOP)->SetRange(r); this->GetChart(vtkVector2i(0, i))->GetAxis(vtkAxis::LEFT)->GetRange(r); for (int j = 1; j < n - i; ++j) { this->GetChart(vtkVector2i(j, i))->GetAxis(vtkAxis::LEFT)->SetRange(r); } } } void vtkScatterPlotMatrix::PrintSelf(ostream &os, vtkIndent indent) { Superclass::PrintSelf(os, indent); } <|endoftext|>
<commit_before>#pragma once #include "generator/feature_merger.hpp" #include "generator/generate_info.hpp" #include "generator/popular_places_section_builder.hpp" #include "search/utils.hpp" #include "indexer/classificator.hpp" #include "indexer/scales.hpp" #include "coding/pointd_to_pointu.hpp" #include "geometry/polygon.hpp" #include "geometry/region2d.hpp" #include "geometry/tree4d.hpp" #include "base/logging.hpp" #include <algorithm> #include <cstdint> #include <map> #include <sstream> #include <string> #include <vector> #include "defines.hpp" namespace { class WaterBoundaryChecker { uint32_t m_boundaryType; struct RegionTraits { m2::RectD const & LimitRect(m2::RegionD const & r) const { return r.GetRect(); } }; m4::Tree<m2::RegionD, RegionTraits> m_tree; size_t m_totalFeatures = 0; size_t m_totalBorders = 0; size_t m_skippedBorders = 0; size_t m_selectedPolygons = 0; public: WaterBoundaryChecker(feature::GenerateInfo const & info) { m_boundaryType = classif().GetTypeByPath({"boundary", "administrative"}); LoadWaterGeometry( info.GetIntermediateFileName(WORLD_COASTS_FILE_NAME, RAW_GEOM_FILE_EXTENSION)); } ~WaterBoundaryChecker() { LOG_SHORT(LINFO, ("Features checked:", m_totalFeatures, "borders checked:", m_totalBorders, "borders skipped:", m_skippedBorders, "selected polygons:", m_selectedPolygons)); } void LoadWaterGeometry(std::string const & rawGeometryFileName) { LOG_SHORT(LINFO, ("Loading water geometry:", rawGeometryFileName)); FileReader reader(rawGeometryFileName); ReaderSource<FileReader> file(reader); size_t total = 0; while (true) { uint64_t numGeometries = 0; file.Read(&numGeometries, sizeof(numGeometries)); if (numGeometries == 0) break; ++total; for (size_t i = 0; i < numGeometries; ++i) { uint64_t numPoints = 0; file.Read(&numPoints, sizeof(numPoints)); std::vector<m2::PointD> points(numPoints); file.Read(points.data(), sizeof(m2::PointD) * numPoints); m_tree.Add(m2::RegionD(move(points))); } } LOG_SHORT(LINFO, ("Load", total, "water geometries")); } bool IsBoundaries(FeatureBuilder1 const & fb) { ++m_totalFeatures; if (fb.FindType(m_boundaryType, 2) == ftype::GetEmptyValue()) return false; ++m_totalBorders; return true; } enum class ProcessState { Initial, Water, Earth }; void ProcessBoundary(FeatureBuilder1 const & boundary, std::vector<FeatureBuilder1> & parts) { auto const & line = boundary.GetGeometry().front(); double constexpr kExtension = 0.01; ProcessState state = ProcessState::Initial; FeatureBuilder1::PointSeq points; for (size_t i = 0; i < line.size(); ++i) { m2::PointD const & p = line[i]; m2::RectD r(p.x - kExtension, p.y - kExtension, p.x + kExtension, p.y + kExtension); size_t hits = 0; m_tree.ForEachInRect(r, [&](m2::RegionD const & rgn) { ++m_selectedPolygons; hits += rgn.Contains(p) ? 1 : 0; }); bool inWater = (hits & 0x01) == 1; switch (state) { case ProcessState::Initial: { if (inWater) { state = ProcessState::Water; } else { points.push_back(p); state = ProcessState::Earth; } break; } case ProcessState::Water: { if (inWater) { // do nothing } else { points.push_back(p); state = ProcessState::Earth; } break; } case ProcessState::Earth: { if (inWater) { if (points.size() > 1) { parts.push_back(boundary); parts.back().ResetGeometry(); for (auto const & pt : points) parts.back().AddPoint(pt); } points.clear(); state = ProcessState::Water; } else { points.push_back(p); } break; } } } if (points.size() > 1) { parts.push_back(boundary); parts.back().ResetGeometry(); for (auto const & pt : points) parts.back().AddPoint(pt); } if (parts.empty()) m_skippedBorders++; } }; } // namespace /// Process FeatureBuilder1 for world map. Main functions: /// - check for visibility in world map /// - merge linear features template <class FeatureOutT> class WorldMapGenerator { class EmitterImpl : public FeatureEmitterIFace { FeatureOutT m_output; std::map<uint32_t, size_t> m_mapTypes; public: explicit EmitterImpl(feature::GenerateInfo const & info) : m_output(info.GetTmpFileName(WORLD_FILE_NAME)) { LOG_SHORT(LINFO, ("Output World file:", info.GetTmpFileName(WORLD_FILE_NAME))); } ~EmitterImpl() override { Classificator const & c = classif(); std::stringstream ss; ss << std::endl; for (auto const & p : m_mapTypes) ss << c.GetReadableObjectName(p.first) << " : " << p.second << std::endl; LOG_SHORT(LINFO, ("World types:", ss.str())); } /// This function is called after merging linear features. void operator()(FeatureBuilder1 const & fb) override { // do additional check for suitable size of feature if (NeedPushToWorld(fb) && scales::IsGoodForLevel(scales::GetUpperWorldScale(), fb.GetLimitRect())) PushSure(fb); } void CalcStatistics(FeatureBuilder1 const & fb) { for (uint32_t type : fb.GetTypes()) ++m_mapTypes[type]; } bool NeedPushToWorld(FeatureBuilder1 const & fb) const { // GetMinFeatureDrawScale also checks suitable size for AREA features return (scales::GetUpperWorldScale() >= fb.GetMinFeatureDrawScale()); } void PushSure(FeatureBuilder1 const & fb) { m_output(fb); } }; EmitterImpl m_worldBucket; FeatureTypesProcessor m_typesCorrector; FeatureMergeProcessor m_merger; WaterBoundaryChecker m_boundaryChecker; generator::PopularPlaces m_popularPlaces; public: explicit WorldMapGenerator(feature::GenerateInfo const & info) : m_worldBucket(info), m_merger(POINT_COORD_BITS - (scales::GetUpperScale() - scales::GetUpperWorldScale()) / 2), m_boundaryChecker(info) { // Do not strip last types for given tags, // for example, do not cut 'admin_level' in 'boundary-administrative-XXX'. char const * arr1[][3] = {{"boundary", "administrative", "2"}, {"boundary", "administrative", "3"}, {"boundary", "administrative", "4"}}; for (size_t i = 0; i < ARRAY_SIZE(arr1); ++i) m_typesCorrector.SetDontNormalizeType(arr1[i]); char const * arr2[] = {"boundary", "administrative", "4", "state"}; m_typesCorrector.SetDontNormalizeType(arr2); if (!info.m_popularPlacesFilename.empty()) generator::LoadPopularPlaces(info.m_popularPlacesFilename, m_popularPlaces); else LOG(LWARNING, ("popular_places_data option not set. Popular atractions will not be added to World.mwm")); } void operator()(FeatureBuilder1 fb) { auto const isPopularAttraction = IsPopularAttraction(fb); if (!m_worldBucket.NeedPushToWorld(fb) && !isPopularAttraction) return; m_worldBucket.CalcStatistics(fb); if (!m_boundaryChecker.IsBoundaries(fb)) { // Save original feature iff it is a popular attraction before PushFeature(fb) modifies fb. auto originalFeature = isPopularAttraction ? fb : FeatureBuilder1(); if (PushFeature(fb) || !isPopularAttraction) return; // We push GEOM_POINT with all the same tags, names and center instead of GEOM_WAY/GEOM_AREA // because we do not need geometry for attractions (just search index and placepage data) // and want to avoid size checks applied to areas. if (originalFeature.GetGeomType() != feature::GEOM_POINT) originalFeature.SetCenter(originalFeature.GetGeometryCenter()); m_worldBucket.PushSure(originalFeature); return; } std::vector<FeatureBuilder1> boundaryParts; m_boundaryChecker.ProcessBoundary(fb, boundaryParts); for (auto & f : boundaryParts) PushFeature(f); } bool PushFeature(FeatureBuilder1 & fb) { switch (fb.GetGeomType()) { case feature::GEOM_LINE: { MergedFeatureBuilder1 * p = m_typesCorrector(fb); if (p) m_merger(p); return false; } case feature::GEOM_AREA: { // This constant is set according to size statistics. // Added approx 4Mb of data to the World.mwm auto const & geometry = fb.GetOuterGeometry(); if (GetPolygonArea(geometry.begin(), geometry.end()) < 0.01) return false; } default: break; } if (feature::PreprocessForWorldMap(fb)) { m_worldBucket.PushSure(fb); return true; } return false; } void DoMerge() { m_merger.DoMerge(m_worldBucket); } private: bool IsPopularAttraction(FeatureBuilder1 const & fb) const { if (fb.GetName().empty()) return false; auto const attractionTypes = search::GetCategoryTypes("attractions", "en", GetDefaultCategories()); ASSERT(is_sorted(attractionTypes.begin(), attractionTypes.end()), ()); auto const & featureTypes = fb.GetTypes(); if (!std::any_of(featureTypes.begin(), featureTypes.end(), [&attractionTypes](uint32_t t) { return binary_search(attractionTypes.begin(), attractionTypes.end(), t); })) { return false; } auto const it = m_popularPlaces.find(fb.GetMostGenericOsmId()); if (it == m_popularPlaces.end()) return false; // todo(@t.yan): adjust uint8_t const kPopularityThreshold = 40; if (it->second < kPopularityThreshold) return false; // todo(@t.yan): maybe check place has wikipedia link. return true; } }; template <class FeatureOut> class SimpleCountryMapGenerator { public: SimpleCountryMapGenerator(feature::GenerateInfo const & info) : m_bucket(info) {} void operator()(FeatureBuilder1 & fb) { m_bucket(fb); } FeatureOut & Parent() { return m_bucket; } private: FeatureOut m_bucket; }; template <class FeatureOut> class CountryMapGenerator : public SimpleCountryMapGenerator<FeatureOut> { public: CountryMapGenerator(feature::GenerateInfo const & info) : SimpleCountryMapGenerator<FeatureOut>(info) {} void operator()(FeatureBuilder1 fb) { if (feature::PreprocessForCountryMap(fb)) SimpleCountryMapGenerator<FeatureOut>::operator()(fb); } }; <commit_msg>[generator] Add international airports to World.mwm<commit_after>#pragma once #include "generator/feature_merger.hpp" #include "generator/generate_info.hpp" #include "generator/popular_places_section_builder.hpp" #include "search/utils.hpp" #include "indexer/classificator.hpp" #include "indexer/scales.hpp" #include "coding/pointd_to_pointu.hpp" #include "geometry/polygon.hpp" #include "geometry/region2d.hpp" #include "geometry/tree4d.hpp" #include "base/logging.hpp" #include <algorithm> #include <cstdint> #include <map> #include <sstream> #include <string> #include <vector> #include "defines.hpp" namespace { class WaterBoundaryChecker { uint32_t m_boundaryType; struct RegionTraits { m2::RectD const & LimitRect(m2::RegionD const & r) const { return r.GetRect(); } }; m4::Tree<m2::RegionD, RegionTraits> m_tree; size_t m_totalFeatures = 0; size_t m_totalBorders = 0; size_t m_skippedBorders = 0; size_t m_selectedPolygons = 0; public: WaterBoundaryChecker(feature::GenerateInfo const & info) { m_boundaryType = classif().GetTypeByPath({"boundary", "administrative"}); LoadWaterGeometry( info.GetIntermediateFileName(WORLD_COASTS_FILE_NAME, RAW_GEOM_FILE_EXTENSION)); } ~WaterBoundaryChecker() { LOG_SHORT(LINFO, ("Features checked:", m_totalFeatures, "borders checked:", m_totalBorders, "borders skipped:", m_skippedBorders, "selected polygons:", m_selectedPolygons)); } void LoadWaterGeometry(std::string const & rawGeometryFileName) { LOG_SHORT(LINFO, ("Loading water geometry:", rawGeometryFileName)); FileReader reader(rawGeometryFileName); ReaderSource<FileReader> file(reader); size_t total = 0; while (true) { uint64_t numGeometries = 0; file.Read(&numGeometries, sizeof(numGeometries)); if (numGeometries == 0) break; ++total; for (size_t i = 0; i < numGeometries; ++i) { uint64_t numPoints = 0; file.Read(&numPoints, sizeof(numPoints)); std::vector<m2::PointD> points(numPoints); file.Read(points.data(), sizeof(m2::PointD) * numPoints); m_tree.Add(m2::RegionD(move(points))); } } LOG_SHORT(LINFO, ("Load", total, "water geometries")); } bool IsBoundaries(FeatureBuilder1 const & fb) { ++m_totalFeatures; if (fb.FindType(m_boundaryType, 2) == ftype::GetEmptyValue()) return false; ++m_totalBorders; return true; } enum class ProcessState { Initial, Water, Earth }; void ProcessBoundary(FeatureBuilder1 const & boundary, std::vector<FeatureBuilder1> & parts) { auto const & line = boundary.GetGeometry().front(); double constexpr kExtension = 0.01; ProcessState state = ProcessState::Initial; FeatureBuilder1::PointSeq points; for (size_t i = 0; i < line.size(); ++i) { m2::PointD const & p = line[i]; m2::RectD r(p.x - kExtension, p.y - kExtension, p.x + kExtension, p.y + kExtension); size_t hits = 0; m_tree.ForEachInRect(r, [&](m2::RegionD const & rgn) { ++m_selectedPolygons; hits += rgn.Contains(p) ? 1 : 0; }); bool inWater = (hits & 0x01) == 1; switch (state) { case ProcessState::Initial: { if (inWater) { state = ProcessState::Water; } else { points.push_back(p); state = ProcessState::Earth; } break; } case ProcessState::Water: { if (inWater) { // do nothing } else { points.push_back(p); state = ProcessState::Earth; } break; } case ProcessState::Earth: { if (inWater) { if (points.size() > 1) { parts.push_back(boundary); parts.back().ResetGeometry(); for (auto const & pt : points) parts.back().AddPoint(pt); } points.clear(); state = ProcessState::Water; } else { points.push_back(p); } break; } } } if (points.size() > 1) { parts.push_back(boundary); parts.back().ResetGeometry(); for (auto const & pt : points) parts.back().AddPoint(pt); } if (parts.empty()) m_skippedBorders++; } }; } // namespace /// Process FeatureBuilder1 for world map. Main functions: /// - check for visibility in world map /// - merge linear features template <class FeatureOutT> class WorldMapGenerator { class EmitterImpl : public FeatureEmitterIFace { FeatureOutT m_output; std::map<uint32_t, size_t> m_mapTypes; public: explicit EmitterImpl(feature::GenerateInfo const & info) : m_output(info.GetTmpFileName(WORLD_FILE_NAME)) { LOG_SHORT(LINFO, ("Output World file:", info.GetTmpFileName(WORLD_FILE_NAME))); } ~EmitterImpl() override { Classificator const & c = classif(); std::stringstream ss; ss << std::endl; for (auto const & p : m_mapTypes) ss << c.GetReadableObjectName(p.first) << " : " << p.second << std::endl; LOG_SHORT(LINFO, ("World types:", ss.str())); } /// This function is called after merging linear features. void operator()(FeatureBuilder1 const & fb) override { // do additional check for suitable size of feature if (NeedPushToWorld(fb) && scales::IsGoodForLevel(scales::GetUpperWorldScale(), fb.GetLimitRect())) PushSure(fb); } void CalcStatistics(FeatureBuilder1 const & fb) { for (uint32_t type : fb.GetTypes()) ++m_mapTypes[type]; } bool NeedPushToWorld(FeatureBuilder1 const & fb) const { // GetMinFeatureDrawScale also checks suitable size for AREA features return (scales::GetUpperWorldScale() >= fb.GetMinFeatureDrawScale()); } void PushSure(FeatureBuilder1 const & fb) { m_output(fb); } }; EmitterImpl m_worldBucket; FeatureTypesProcessor m_typesCorrector; FeatureMergeProcessor m_merger; WaterBoundaryChecker m_boundaryChecker; generator::PopularPlaces m_popularPlaces; public: explicit WorldMapGenerator(feature::GenerateInfo const & info) : m_worldBucket(info), m_merger(POINT_COORD_BITS - (scales::GetUpperScale() - scales::GetUpperWorldScale()) / 2), m_boundaryChecker(info) { // Do not strip last types for given tags, // for example, do not cut 'admin_level' in 'boundary-administrative-XXX'. char const * arr1[][3] = {{"boundary", "administrative", "2"}, {"boundary", "administrative", "3"}, {"boundary", "administrative", "4"}}; for (size_t i = 0; i < ARRAY_SIZE(arr1); ++i) m_typesCorrector.SetDontNormalizeType(arr1[i]); char const * arr2[] = {"boundary", "administrative", "4", "state"}; m_typesCorrector.SetDontNormalizeType(arr2); if (!info.m_popularPlacesFilename.empty()) generator::LoadPopularPlaces(info.m_popularPlacesFilename, m_popularPlaces); else LOG(LWARNING, ("popular_places_data option not set. Popular atractions will not be added to World.mwm")); } void operator()(FeatureBuilder1 fb) { auto const isPopularAttraction = IsPopularAttraction(fb); auto const isInternationalAirport = fb.HasType(classif().GetTypeByPath({"aeroway", "aerodrome", "international"})); auto const forcePushToWorld = isPopularAttraction || isInternationalAirport; if (!m_worldBucket.NeedPushToWorld(fb) && !forcePushToWorld) return; m_worldBucket.CalcStatistics(fb); if (!m_boundaryChecker.IsBoundaries(fb)) { // Save original feature iff we need to force push it before PushFeature(fb) modifies fb. auto originalFeature = forcePushToWorld ? fb : FeatureBuilder1(); if (PushFeature(fb) || !forcePushToWorld) return; // We push GEOM_POINT with all the same tags, names and center instead of GEOM_WAY/GEOM_AREA // because we do not need geometry for invisible features (just search index and placepage // data) and want to avoid size checks applied to areas. if (originalFeature.GetGeomType() != feature::GEOM_POINT) originalFeature.SetCenter(originalFeature.GetGeometryCenter()); m_worldBucket.PushSure(originalFeature); return; } std::vector<FeatureBuilder1> boundaryParts; m_boundaryChecker.ProcessBoundary(fb, boundaryParts); for (auto & f : boundaryParts) PushFeature(f); } bool PushFeature(FeatureBuilder1 & fb) { switch (fb.GetGeomType()) { case feature::GEOM_LINE: { MergedFeatureBuilder1 * p = m_typesCorrector(fb); if (p) m_merger(p); return false; } case feature::GEOM_AREA: { // This constant is set according to size statistics. // Added approx 4Mb of data to the World.mwm auto const & geometry = fb.GetOuterGeometry(); if (GetPolygonArea(geometry.begin(), geometry.end()) < 0.01) return false; } default: break; } if (feature::PreprocessForWorldMap(fb)) { m_worldBucket.PushSure(fb); return true; } return false; } void DoMerge() { m_merger.DoMerge(m_worldBucket); } private: bool IsPopularAttraction(FeatureBuilder1 const & fb) const { if (fb.GetName().empty()) return false; auto const attractionTypes = search::GetCategoryTypes("attractions", "en", GetDefaultCategories()); ASSERT(is_sorted(attractionTypes.begin(), attractionTypes.end()), ()); auto const & featureTypes = fb.GetTypes(); if (!std::any_of(featureTypes.begin(), featureTypes.end(), [&attractionTypes](uint32_t t) { return binary_search(attractionTypes.begin(), attractionTypes.end(), t); })) { return false; } auto const it = m_popularPlaces.find(fb.GetMostGenericOsmId()); if (it == m_popularPlaces.end()) return false; // todo(@t.yan): adjust uint8_t const kPopularityThreshold = 40; if (it->second < kPopularityThreshold) return false; // todo(@t.yan): maybe check place has wikipedia link. return true; } }; template <class FeatureOut> class SimpleCountryMapGenerator { public: SimpleCountryMapGenerator(feature::GenerateInfo const & info) : m_bucket(info) {} void operator()(FeatureBuilder1 & fb) { m_bucket(fb); } FeatureOut & Parent() { return m_bucket; } private: FeatureOut m_bucket; }; template <class FeatureOut> class CountryMapGenerator : public SimpleCountryMapGenerator<FeatureOut> { public: CountryMapGenerator(feature::GenerateInfo const & info) : SimpleCountryMapGenerator<FeatureOut>(info) {} void operator()(FeatureBuilder1 fb) { if (feature::PreprocessForCountryMap(fb)) SimpleCountryMapGenerator<FeatureOut>::operator()(fb); } }; <|endoftext|>
<commit_before>/* Copyright (c) 2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/escape_string.hpp" // for from_hex #include "libtorrent/alert_types.hpp" #include "libtorrent/bencode.hpp" // for bencode() #include "libtorrent/kademlia/item.hpp" // for sign_mutable_item #include "libtorrent/ed25519.h" #include <boost/bind.hpp> #include <stdlib.h> using namespace libtorrent; #ifdef TORRENT_DISABLE_DHT int main(int argc, char* argv[]) { fprintf(stderr, "not built with DHT support\n"); return 1; } #else void usage() { fprintf(stderr, "USAGE:\ndht <command> <arg>\n\nCOMMANDS:\n" "get <hash> - retrieves and prints out the immutable\n" " item stored under hash.\n" "put <string> - puts the specified string as an immutable\n" " item onto the DHT. The resulting target hash\n" "gen-key <key-file> - generate ed25519 keypair and save it in\n" " the specified file\n" "mput <key-file> <string> - puts the specified string as a mutable\n" " object under the public key in key-file\n" "mget <public-key> - get a mutable object under the specified\n" " public key\n" ); exit(1); } std::auto_ptr<alert> wait_for_alert(session& s, int alert_type) { std::auto_ptr<alert> ret; bool found = false; while (!found) { s.wait_for_alert(seconds(5)); std::deque<alert*> alerts; s.pop_alerts(&alerts); for (std::deque<alert*>::iterator i = alerts.begin() , end(alerts.end()); i != end; ++i) { if ((*i)->type() != alert_type) { static int spinner = 0; static const char anim[] = {'-', '\\', '|', '/'}; printf("\r%c", anim[spinner]); fflush(stdout); spinner = (spinner + 1) & 3; //print some alerts? delete *i; continue; } ret = std::auto_ptr<alert>(*i); found = true; } } printf("\n"); return ret; } void put_string(entry& e, boost::array<char, 64>& sig, boost::uint64_t& seq , std::string const& salt, char const* public_key, char const* private_key , char const* str) { using libtorrent::dht::sign_mutable_item; e = std::string(str); std::vector<char> buf; bencode(std::back_inserter(buf), e); ++seq; sign_mutable_item(std::pair<char const*, int>(&buf[0], buf.size()) , std::pair<char const*, int>(&salt[0], salt.size()) , seq , public_key , private_key , sig.data()); } void bootstrap(session& s) { printf("bootstrapping\n"); wait_for_alert(s, dht_bootstrap_alert::alert_type); } int main(int argc, char* argv[]) { // skip pointer to self ++argv; --argc; if (argc < 1) usage(); if (strcmp(argv[0], "gen-key") == 0) { ++argv; --argc; if (argc < 1) usage(); unsigned char seed[32]; ed25519_create_seed(seed); FILE* f = fopen(argv[0], "wb+"); if (f == NULL) { fprintf(stderr, "failed to open file for writing \"%s\": (%d) %s\n" , argv[0], errno, strerror(errno)); return 1; } fwrite(seed, 1, 32, f); fclose(f); return 0; } session s; s.set_alert_mask(0xffffffff); s.add_dht_router(std::pair<std::string, int>("54.205.98.145", 10000)); FILE* f = fopen(".dht", "rb"); if (f != NULL) { fseek(f, 0, SEEK_END); int size = ftell(f); fseek(f, 0, SEEK_SET); if (size > 0) { std::vector<char> state; state.resize(size); fread(&state[0], 1, state.size(), f); lazy_entry e; error_code ec; lazy_bdecode(&state[0], &state[0] + state.size(), e, ec); if (ec) fprintf(stderr, "failed to parse .dht file: (%d) %s\n" , ec.value(), ec.message().c_str()); else s.load_state(e); } fclose(f); } if (strcmp(argv[0], "get") == 0) { ++argv; --argc; if (argc < 1) usage(); if (strlen(argv[0]) != 40) { fprintf(stderr, "the hash is expected to be 40 hex characters\n"); usage(); } sha1_hash target; bool ret = from_hex(argv[0], 40, (char*)&target[0]); if (!ret) { fprintf(stderr, "invalid hex encoding of target hash\n"); return 1; } bootstrap(s); s.dht_get_item(target); printf("GET %s\n", to_hex(target.to_string()).c_str()); std::auto_ptr<alert> a = wait_for_alert(s, dht_immutable_item_alert::alert_type); dht_immutable_item_alert* item = alert_cast<dht_immutable_item_alert>(a.get()); entry data; if (item) data.swap(item->item); printf("%s", data.to_string().c_str()); } else if (strcmp(argv[0], "put") == 0) { ++argv; --argc; if (argc < 1) usage(); entry data; data = std::string(argv[0]); bootstrap(s); sha1_hash target = s.dht_put_item(data); printf("PUT %s\n", to_hex(target.to_string()).c_str()); wait_for_alert(s, dht_put_alert::alert_type); } else if (strcmp(argv[0], "mput") == 0) { ++argv; --argc; if (argc < 1) usage(); FILE* f = fopen(argv[0], "rb+"); if (f == NULL) { fprintf(stderr, "failed to open file \"%s\": (%d) %s\n" , argv[0], errno, strerror(errno)); return 1; } unsigned char seed[32]; fread(seed, 1, 32, f); fclose(f); ++argv; --argc; if (argc < 1) usage(); boost::array<char, 32> public_key; boost::array<char, 64> private_key; ed25519_create_keypair((unsigned char*)public_key.data() , (unsigned char*)private_key.data(), seed); bootstrap(s); s.dht_put_item(public_key, boost::bind(&put_string, _1, _2, _3, _4 , public_key.data(), private_key.data(), argv[0])); printf("public key: %s\n", to_hex(std::string(public_key.data() , public_key.size())).c_str()); wait_for_alert(s, dht_put_alert::alert_type); } else if (strcmp(argv[0], "mget") == 0) { ++argv; --argc; if (argc < 1) usage(); int len = strlen(argv[0]); if (len != 64) { fprintf(stderr, "public key is expected to be 64 hex digits\n"); return 1; } boost::array<char, 32> public_key; bool ret = from_hex(argv[0], len, &public_key[0]); if (!ret) { fprintf(stderr, "invalid hex encoding of public key\n"); return 1; } bootstrap(s); s.dht_get_item(public_key); std::auto_ptr<alert> a = wait_for_alert(s, dht_mutable_item_alert::alert_type); dht_mutable_item_alert* item = alert_cast<dht_mutable_item_alert>(a.get()); entry data; if (item) data.swap(item->item); printf("%s", data.to_string().c_str()); } else { usage(); } entry e; s.save_state(e, session::save_dht_state); std::vector<char> state; bencode(std::back_inserter(state), e); f = fopen(".dht", "wb+"); if (f == NULL) { fprintf(stderr, "failed to open file .dht for writing"); return 1; } fwrite(&state[0], 1, state.size(), f); fclose(f); } #endif <commit_msg>fix typo<commit_after>/* Copyright (c) 2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/escape_string.hpp" // for from_hex #include "libtorrent/alert_types.hpp" #include "libtorrent/bencode.hpp" // for bencode() #include "libtorrent/kademlia/item.hpp" // for sign_mutable_item #include "libtorrent/ed25519.hpp" #include <boost/bind.hpp> #include <stdlib.h> using namespace libtorrent; #ifdef TORRENT_DISABLE_DHT int main(int argc, char* argv[]) { fprintf(stderr, "not built with DHT support\n"); return 1; } #else void usage() { fprintf(stderr, "USAGE:\ndht <command> <arg>\n\nCOMMANDS:\n" "get <hash> - retrieves and prints out the immutable\n" " item stored under hash.\n" "put <string> - puts the specified string as an immutable\n" " item onto the DHT. The resulting target hash\n" "gen-key <key-file> - generate ed25519 keypair and save it in\n" " the specified file\n" "mput <key-file> <string> - puts the specified string as a mutable\n" " object under the public key in key-file\n" "mget <public-key> - get a mutable object under the specified\n" " public key\n" ); exit(1); } std::auto_ptr<alert> wait_for_alert(session& s, int alert_type) { std::auto_ptr<alert> ret; bool found = false; while (!found) { s.wait_for_alert(seconds(5)); std::deque<alert*> alerts; s.pop_alerts(&alerts); for (std::deque<alert*>::iterator i = alerts.begin() , end(alerts.end()); i != end; ++i) { if ((*i)->type() != alert_type) { static int spinner = 0; static const char anim[] = {'-', '\\', '|', '/'}; printf("\r%c", anim[spinner]); fflush(stdout); spinner = (spinner + 1) & 3; //print some alerts? delete *i; continue; } ret = std::auto_ptr<alert>(*i); found = true; } } printf("\n"); return ret; } void put_string(entry& e, boost::array<char, 64>& sig, boost::uint64_t& seq , std::string const& salt, char const* public_key, char const* private_key , char const* str) { using libtorrent::dht::sign_mutable_item; e = std::string(str); std::vector<char> buf; bencode(std::back_inserter(buf), e); ++seq; sign_mutable_item(std::pair<char const*, int>(&buf[0], buf.size()) , std::pair<char const*, int>(&salt[0], salt.size()) , seq , public_key , private_key , sig.data()); } void bootstrap(session& s) { printf("bootstrapping\n"); wait_for_alert(s, dht_bootstrap_alert::alert_type); } int main(int argc, char* argv[]) { // skip pointer to self ++argv; --argc; if (argc < 1) usage(); if (strcmp(argv[0], "gen-key") == 0) { ++argv; --argc; if (argc < 1) usage(); unsigned char seed[32]; ed25519_create_seed(seed); FILE* f = fopen(argv[0], "wb+"); if (f == NULL) { fprintf(stderr, "failed to open file for writing \"%s\": (%d) %s\n" , argv[0], errno, strerror(errno)); return 1; } fwrite(seed, 1, 32, f); fclose(f); return 0; } session s; s.set_alert_mask(0xffffffff); s.add_dht_router(std::pair<std::string, int>("54.205.98.145", 10000)); FILE* f = fopen(".dht", "rb"); if (f != NULL) { fseek(f, 0, SEEK_END); int size = ftell(f); fseek(f, 0, SEEK_SET); if (size > 0) { std::vector<char> state; state.resize(size); fread(&state[0], 1, state.size(), f); lazy_entry e; error_code ec; lazy_bdecode(&state[0], &state[0] + state.size(), e, ec); if (ec) fprintf(stderr, "failed to parse .dht file: (%d) %s\n" , ec.value(), ec.message().c_str()); else s.load_state(e); } fclose(f); } if (strcmp(argv[0], "get") == 0) { ++argv; --argc; if (argc < 1) usage(); if (strlen(argv[0]) != 40) { fprintf(stderr, "the hash is expected to be 40 hex characters\n"); usage(); } sha1_hash target; bool ret = from_hex(argv[0], 40, (char*)&target[0]); if (!ret) { fprintf(stderr, "invalid hex encoding of target hash\n"); return 1; } bootstrap(s); s.dht_get_item(target); printf("GET %s\n", to_hex(target.to_string()).c_str()); std::auto_ptr<alert> a = wait_for_alert(s, dht_immutable_item_alert::alert_type); dht_immutable_item_alert* item = alert_cast<dht_immutable_item_alert>(a.get()); entry data; if (item) data.swap(item->item); printf("%s", data.to_string().c_str()); } else if (strcmp(argv[0], "put") == 0) { ++argv; --argc; if (argc < 1) usage(); entry data; data = std::string(argv[0]); bootstrap(s); sha1_hash target = s.dht_put_item(data); printf("PUT %s\n", to_hex(target.to_string()).c_str()); wait_for_alert(s, dht_put_alert::alert_type); } else if (strcmp(argv[0], "mput") == 0) { ++argv; --argc; if (argc < 1) usage(); FILE* f = fopen(argv[0], "rb+"); if (f == NULL) { fprintf(stderr, "failed to open file \"%s\": (%d) %s\n" , argv[0], errno, strerror(errno)); return 1; } unsigned char seed[32]; fread(seed, 1, 32, f); fclose(f); ++argv; --argc; if (argc < 1) usage(); boost::array<char, 32> public_key; boost::array<char, 64> private_key; ed25519_create_keypair((unsigned char*)public_key.data() , (unsigned char*)private_key.data(), seed); bootstrap(s); s.dht_put_item(public_key, boost::bind(&put_string, _1, _2, _3, _4 , public_key.data(), private_key.data(), argv[0])); printf("public key: %s\n", to_hex(std::string(public_key.data() , public_key.size())).c_str()); wait_for_alert(s, dht_put_alert::alert_type); } else if (strcmp(argv[0], "mget") == 0) { ++argv; --argc; if (argc < 1) usage(); int len = strlen(argv[0]); if (len != 64) { fprintf(stderr, "public key is expected to be 64 hex digits\n"); return 1; } boost::array<char, 32> public_key; bool ret = from_hex(argv[0], len, &public_key[0]); if (!ret) { fprintf(stderr, "invalid hex encoding of public key\n"); return 1; } bootstrap(s); s.dht_get_item(public_key); std::auto_ptr<alert> a = wait_for_alert(s, dht_mutable_item_alert::alert_type); dht_mutable_item_alert* item = alert_cast<dht_mutable_item_alert>(a.get()); entry data; if (item) data.swap(item->item); printf("%s", data.to_string().c_str()); } else { usage(); } entry e; s.save_state(e, session::save_dht_state); std::vector<char> state; bencode(std::back_inserter(state), e); f = fopen(".dht", "wb+"); if (f == NULL) { fprintf(stderr, "failed to open file .dht for writing"); return 1; } fwrite(&state[0], 1, state.size(), f); fclose(f); } #endif <|endoftext|>
<commit_before>#include <cmath> #include <network.h> namespace ESN { NetworkImpl::NetworkImpl( unsigned neuronCount ) : mPotential( neuronCount ) , mThreshold( neuronCount ) , mResistance( neuronCount ) , mTimeConstant( neuronCount ) , mOutputCurrent( neuronCount ) , mSpikeTime( neuronCount ) , mConnection( neuronCount ) , mConnectionWeight( neuronCount ) { for ( auto & connection : mConnection ) connection.resize( neuronCount ); for ( auto & connectionWeight : mConnectionWeight ) connectionWeight.resize( neuronCount ); } void NetworkImpl::Step( float step ) { for ( int i = 0, n = mPotential.size(); i < n; ++ i ) { float inputCurrent = 0.0f; for ( int j = 0, nj = mConnection[i].size(); j < nj; ++ j ) inputCurrent += mConnection[i][j] * mConnectionWeight[i][j]; float delta = step * ( inputCurrent * mResistance[i] - mPotential[i] ) / mTimeConstant[i]; mPotential[i] += delta; } for ( int i = 0, n = mPotential.size(); i < n; ++ i ) { if ( mPotential[i] > mThreshold[i] ) mSpikeTime[i] = 0.0f; mOutputCurrent[i] = mSpikeTime[i] * std::exp( 1 - mSpikeTime[i] ); mSpikeTime[i] += step; } } } // namespace ESN <commit_msg>esn : NetworkImpl : fixed calculation of input current<commit_after>#include <cmath> #include <network.h> namespace ESN { NetworkImpl::NetworkImpl( unsigned neuronCount ) : mPotential( neuronCount ) , mThreshold( neuronCount ) , mResistance( neuronCount ) , mTimeConstant( neuronCount ) , mOutputCurrent( neuronCount ) , mSpikeTime( neuronCount ) , mConnection( neuronCount ) , mConnectionWeight( neuronCount ) { for ( auto & connection : mConnection ) connection.resize( neuronCount ); for ( auto & connectionWeight : mConnectionWeight ) connectionWeight.resize( neuronCount ); } void NetworkImpl::Step( float step ) { for ( int i = 0, n = mPotential.size(); i < n; ++ i ) { float inputCurrent = 0.0f; for ( int j = 0, nj = mConnection[i].size(); j < nj; ++ j ) { int inputNeuron = mConnection[i][j]; inputCurrent += mOutputCurrent[ inputNeuron ] * mConnectionWeight[i][j]; } float delta = step * ( inputCurrent * mResistance[i] - mPotential[i] ) / mTimeConstant[i]; mPotential[i] += delta; } for ( int i = 0, n = mPotential.size(); i < n; ++ i ) { if ( mPotential[i] > mThreshold[i] ) mSpikeTime[i] = 0.0f; mOutputCurrent[i] = mSpikeTime[i] * std::exp( 1 - mSpikeTime[i] ); mSpikeTime[i] += step; } } } // namespace ESN <|endoftext|>
<commit_before>//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility provides a simple wrapper around the LLVM Execution Engines, // which allow the direct execution of LLVM programs through a Just-In-Time // compiler, or through an interpreter if no JIT is available for this platform. // //===----------------------------------------------------------------------===// #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Type.h" #include "llvm/ADT/Triple.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/CodeGen/LinkAllCodegenComponents.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/Interpreter.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/IRReader.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PluginLoader.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Process.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetSelect.h" #include <cerrno> #ifdef __CYGWIN__ #include <cygwin/version.h> #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007 #define DO_NOTHING_ATEXIT 1 #endif #endif using namespace llvm; namespace { cl::opt<std::string> InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-")); cl::list<std::string> InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); cl::opt<bool> ForceInterpreter("force-interpreter", cl::desc("Force interpretation: disable JIT"), cl::init(false)); cl::opt<bool> UseMCJIT( "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"), cl::init(false)); // Determine optimization level. cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " "(default = '-O2')"), cl::Prefix, cl::ZeroOrMore, cl::init(' ')); cl::opt<std::string> TargetTriple("mtriple", cl::desc("Override target triple for module")); cl::opt<std::string> MArch("march", cl::desc("Architecture to generate assembly for (see --version)")); cl::opt<std::string> MCPU("mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"), cl::value_desc("cpu-name"), cl::init("")); cl::list<std::string> MAttrs("mattr", cl::CommaSeparated, cl::desc("Target specific attributes (-mattr=help for details)"), cl::value_desc("a1,+a2,-a3,...")); cl::opt<std::string> EntryFunc("entry-function", cl::desc("Specify the entry function (default = 'main') " "of the executable"), cl::value_desc("function"), cl::init("main")); cl::opt<std::string> FakeArgv0("fake-argv0", cl::desc("Override the 'argv[0]' value passed into the executing" " program"), cl::value_desc("executable")); cl::opt<bool> DisableCoreFiles("disable-core-files", cl::Hidden, cl::desc("Disable emission of core files if possible")); cl::opt<bool> NoLazyCompilation("disable-lazy-compilation", cl::desc("Disable JIT lazy compilation"), cl::init(false)); cl::opt<Reloc::Model> RelocModel("relocation-model", cl::desc("Choose relocation model"), cl::init(Reloc::Default), cl::values( clEnumValN(Reloc::Default, "default", "Target default relocation model"), clEnumValN(Reloc::Static, "static", "Non-relocatable code"), clEnumValN(Reloc::PIC_, "pic", "Fully relocatable, position independent code"), clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", "Relocatable external references, non-relocatable code"), clEnumValEnd)); cl::opt<llvm::CodeModel::Model> CMModel("code-model", cl::desc("Choose code model"), cl::init(CodeModel::JITDefault), cl::values(clEnumValN(CodeModel::JITDefault, "default", "Target default JIT code model"), clEnumValN(CodeModel::Small, "small", "Small code model"), clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"), clEnumValN(CodeModel::Medium, "medium", "Medium code model"), clEnumValN(CodeModel::Large, "large", "Large code model"), clEnumValEnd)); } static ExecutionEngine *EE = 0; static void do_shutdown() { // Cygwin-1.5 invokes DLL's dtors before atexit handler. #ifndef DO_NOTHING_ATEXIT delete EE; llvm_shutdown(); #endif } //===----------------------------------------------------------------------===// // main Driver function // int main(int argc, char **argv, char * const *envp) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); LLVMContext &Context = getGlobalContext(); atexit(do_shutdown); // Call llvm_shutdown() on exit. // If we have a native target, initialize it to ensure it is linked in and // usable by the JIT. InitializeNativeTarget(); InitializeNativeTargetAsmPrinter(); cl::ParseCommandLineOptions(argc, argv, "llvm interpreter & dynamic compiler\n"); // If the user doesn't want core files, disable them. if (DisableCoreFiles) sys::Process::PreventCoreFiles(); // Load the bitcode... SMDiagnostic Err; Module *Mod = ParseIRFile(InputFile, Err, Context); if (!Mod) { Err.print(argv[0], errs()); return 1; } // If not jitting lazily, load the whole bitcode file eagerly too. std::string ErrorMsg; if (NoLazyCompilation) { if (Mod->MaterializeAllPermanently(&ErrorMsg)) { errs() << argv[0] << ": bitcode didn't read correctly.\n"; errs() << "Reason: " << ErrorMsg << "\n"; exit(1); } } EngineBuilder builder(Mod); builder.setMArch(MArch); builder.setMCPU(MCPU); builder.setMAttrs(MAttrs); builder.setRelocationModel(RelocModel); builder.setCodeModel(CMModel); builder.setErrorStr(&ErrorMsg); builder.setEngineKind(ForceInterpreter ? EngineKind::Interpreter : EngineKind::JIT); // If we are supposed to override the target triple, do so now. if (!TargetTriple.empty()) Mod->setTargetTriple(Triple::normalize(TargetTriple)); // Enable MCJIT, if desired. if (UseMCJIT) builder.setUseMCJIT(true); CodeGenOpt::Level OLvl = CodeGenOpt::Default; switch (OptLevel) { default: errs() << argv[0] << ": invalid optimization level.\n"; return 1; case ' ': break; case '0': OLvl = CodeGenOpt::None; break; case '1': OLvl = CodeGenOpt::Less; break; case '2': OLvl = CodeGenOpt::Default; break; case '3': OLvl = CodeGenOpt::Aggressive; break; } builder.setOptLevel(OLvl); EE = builder.create(); if (!EE) { if (!ErrorMsg.empty()) errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n"; else errs() << argv[0] << ": unknown error creating EE!\n"; exit(1); } EE->RegisterJITEventListener(createOProfileJITEventListener()); EE->DisableLazyCompilation(NoLazyCompilation); // If the user specifically requested an argv[0] to pass into the program, // do it now. if (!FakeArgv0.empty()) { InputFile = FakeArgv0; } else { // Otherwise, if there is a .bc suffix on the executable strip it off, it // might confuse the program. if (StringRef(InputFile).endswith(".bc")) InputFile.erase(InputFile.length() - 3); } // Add the module's name to the start of the vector of arguments to main(). InputArgv.insert(InputArgv.begin(), InputFile); // Call the main function from M as if its signature were: // int main (int argc, char **argv, const char **envp) // using the contents of Args to determine argc & argv, and the contents of // EnvVars to determine envp. // Function *EntryFn = Mod->getFunction(EntryFunc); if (!EntryFn) { errs() << '\'' << EntryFunc << "\' function not found in module.\n"; return -1; } // If the program doesn't explicitly call exit, we will need the Exit // function later on to make an explicit call, so get the function now. Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context), Type::getInt32Ty(Context), NULL); // Reset errno to zero on entry to main. errno = 0; // Run static constructors. EE->runStaticConstructorsDestructors(false); if (NoLazyCompilation) { for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) { Function *Fn = &*I; if (Fn != EntryFn && !Fn->isDeclaration()) EE->getPointerToFunction(Fn); } } // Run main. int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp); // Run static destructors. EE->runStaticConstructorsDestructors(true); // If the program didn't call exit explicitly, we should call it now. // This ensures that any atexit handlers get called correctly. if (Function *ExitF = dyn_cast<Function>(Exit)) { std::vector<GenericValue> Args; GenericValue ResultGV; ResultGV.IntVal = APInt(32, Result); Args.push_back(ResultGV); EE->runFunction(ExitF, Args); errs() << "ERROR: exit(" << Result << ") returned!\n"; abort(); } else { errs() << "ERROR: exit defined with wrong prototype!\n"; abort(); } } <commit_msg>lli should create a JIT memory manager.<commit_after>//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility provides a simple wrapper around the LLVM Execution Engines, // which allow the direct execution of LLVM programs through a Just-In-Time // compiler, or through an interpreter if no JIT is available for this platform. // //===----------------------------------------------------------------------===// #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Type.h" #include "llvm/ADT/Triple.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/CodeGen/LinkAllCodegenComponents.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/Interpreter.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/ExecutionEngine/JITMemoryManager.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/IRReader.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PluginLoader.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Process.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetSelect.h" #include <cerrno> #ifdef __CYGWIN__ #include <cygwin/version.h> #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007 #define DO_NOTHING_ATEXIT 1 #endif #endif using namespace llvm; namespace { cl::opt<std::string> InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-")); cl::list<std::string> InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); cl::opt<bool> ForceInterpreter("force-interpreter", cl::desc("Force interpretation: disable JIT"), cl::init(false)); cl::opt<bool> UseMCJIT( "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"), cl::init(false)); // Determine optimization level. cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " "(default = '-O2')"), cl::Prefix, cl::ZeroOrMore, cl::init(' ')); cl::opt<std::string> TargetTriple("mtriple", cl::desc("Override target triple for module")); cl::opt<std::string> MArch("march", cl::desc("Architecture to generate assembly for (see --version)")); cl::opt<std::string> MCPU("mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"), cl::value_desc("cpu-name"), cl::init("")); cl::list<std::string> MAttrs("mattr", cl::CommaSeparated, cl::desc("Target specific attributes (-mattr=help for details)"), cl::value_desc("a1,+a2,-a3,...")); cl::opt<std::string> EntryFunc("entry-function", cl::desc("Specify the entry function (default = 'main') " "of the executable"), cl::value_desc("function"), cl::init("main")); cl::opt<std::string> FakeArgv0("fake-argv0", cl::desc("Override the 'argv[0]' value passed into the executing" " program"), cl::value_desc("executable")); cl::opt<bool> DisableCoreFiles("disable-core-files", cl::Hidden, cl::desc("Disable emission of core files if possible")); cl::opt<bool> NoLazyCompilation("disable-lazy-compilation", cl::desc("Disable JIT lazy compilation"), cl::init(false)); cl::opt<Reloc::Model> RelocModel("relocation-model", cl::desc("Choose relocation model"), cl::init(Reloc::Default), cl::values( clEnumValN(Reloc::Default, "default", "Target default relocation model"), clEnumValN(Reloc::Static, "static", "Non-relocatable code"), clEnumValN(Reloc::PIC_, "pic", "Fully relocatable, position independent code"), clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", "Relocatable external references, non-relocatable code"), clEnumValEnd)); cl::opt<llvm::CodeModel::Model> CMModel("code-model", cl::desc("Choose code model"), cl::init(CodeModel::JITDefault), cl::values(clEnumValN(CodeModel::JITDefault, "default", "Target default JIT code model"), clEnumValN(CodeModel::Small, "small", "Small code model"), clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"), clEnumValN(CodeModel::Medium, "medium", "Medium code model"), clEnumValN(CodeModel::Large, "large", "Large code model"), clEnumValEnd)); } static ExecutionEngine *EE = 0; static void do_shutdown() { // Cygwin-1.5 invokes DLL's dtors before atexit handler. #ifndef DO_NOTHING_ATEXIT delete EE; llvm_shutdown(); #endif } //===----------------------------------------------------------------------===// // main Driver function // int main(int argc, char **argv, char * const *envp) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); LLVMContext &Context = getGlobalContext(); atexit(do_shutdown); // Call llvm_shutdown() on exit. // If we have a native target, initialize it to ensure it is linked in and // usable by the JIT. InitializeNativeTarget(); InitializeNativeTargetAsmPrinter(); cl::ParseCommandLineOptions(argc, argv, "llvm interpreter & dynamic compiler\n"); // If the user doesn't want core files, disable them. if (DisableCoreFiles) sys::Process::PreventCoreFiles(); // Load the bitcode... SMDiagnostic Err; Module *Mod = ParseIRFile(InputFile, Err, Context); if (!Mod) { Err.print(argv[0], errs()); return 1; } // If not jitting lazily, load the whole bitcode file eagerly too. std::string ErrorMsg; if (NoLazyCompilation) { if (Mod->MaterializeAllPermanently(&ErrorMsg)) { errs() << argv[0] << ": bitcode didn't read correctly.\n"; errs() << "Reason: " << ErrorMsg << "\n"; exit(1); } } JITMemoryManager *JMM = JITMemoryManager::CreateDefaultMemManager(); EngineBuilder builder(Mod); builder.setMArch(MArch); builder.setMCPU(MCPU); builder.setMAttrs(MAttrs); builder.setRelocationModel(RelocModel); builder.setCodeModel(CMModel); builder.setErrorStr(&ErrorMsg); builder.setJITMemoryManager(JMM); builder.setEngineKind(ForceInterpreter ? EngineKind::Interpreter : EngineKind::JIT); // If we are supposed to override the target triple, do so now. if (!TargetTriple.empty()) Mod->setTargetTriple(Triple::normalize(TargetTriple)); // Enable MCJIT, if desired. if (UseMCJIT) builder.setUseMCJIT(true); CodeGenOpt::Level OLvl = CodeGenOpt::Default; switch (OptLevel) { default: errs() << argv[0] << ": invalid optimization level.\n"; return 1; case ' ': break; case '0': OLvl = CodeGenOpt::None; break; case '1': OLvl = CodeGenOpt::Less; break; case '2': OLvl = CodeGenOpt::Default; break; case '3': OLvl = CodeGenOpt::Aggressive; break; } builder.setOptLevel(OLvl); EE = builder.create(); if (!EE) { if (!ErrorMsg.empty()) errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n"; else errs() << argv[0] << ": unknown error creating EE!\n"; exit(1); } EE->RegisterJITEventListener(createOProfileJITEventListener()); EE->DisableLazyCompilation(NoLazyCompilation); // If the user specifically requested an argv[0] to pass into the program, // do it now. if (!FakeArgv0.empty()) { InputFile = FakeArgv0; } else { // Otherwise, if there is a .bc suffix on the executable strip it off, it // might confuse the program. if (StringRef(InputFile).endswith(".bc")) InputFile.erase(InputFile.length() - 3); } // Add the module's name to the start of the vector of arguments to main(). InputArgv.insert(InputArgv.begin(), InputFile); // Call the main function from M as if its signature were: // int main (int argc, char **argv, const char **envp) // using the contents of Args to determine argc & argv, and the contents of // EnvVars to determine envp. // Function *EntryFn = Mod->getFunction(EntryFunc); if (!EntryFn) { errs() << '\'' << EntryFunc << "\' function not found in module.\n"; return -1; } // If the program doesn't explicitly call exit, we will need the Exit // function later on to make an explicit call, so get the function now. Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context), Type::getInt32Ty(Context), NULL); // Reset errno to zero on entry to main. errno = 0; // Run static constructors. EE->runStaticConstructorsDestructors(false); if (NoLazyCompilation) { for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) { Function *Fn = &*I; if (Fn != EntryFn && !Fn->isDeclaration()) EE->getPointerToFunction(Fn); } } // Run main. int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp); // Run static destructors. EE->runStaticConstructorsDestructors(true); // If the program didn't call exit explicitly, we should call it now. // This ensures that any atexit handlers get called correctly. if (Function *ExitF = dyn_cast<Function>(Exit)) { std::vector<GenericValue> Args; GenericValue ResultGV; ResultGV.IntVal = APInt(32, Result); Args.push_back(ResultGV); EE->runFunction(ExitF, Args); errs() << "ERROR: exit(" << Result << ") returned!\n"; abort(); } else { errs() << "ERROR: exit defined with wrong prototype!\n"; abort(); } } <|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 "mutex.h" #include "sandbox_impl.h" // This is a C++ implementation of trusted_thread.cc. Since it trusts // the contents of the stack, it is not secure. It is intended to be // a reference implementation. This code can be used as an aid to // understanding what the real trusted thread does, since this code // should be easier to read than assembly code. It can also be used // as a test bed for changes to the trusted thread. namespace playground { void die(const char *msg) { sys_write(2, msg, strlen(msg)); sys_exit_group(1); } #define TO_STRING_1(x) #x #define TO_STRING(x) TO_STRING_1(x) #define assert(expr) { \ if (!(expr)) die("assertion failed at " __FILE__ ":" TO_STRING(__LINE__) \ ": " #expr "\n"); } // Perform a syscall given an array of syscall arguments. extern "C" long DoSyscall(long regs[7]); asm( ".pushsection .text, \"ax\", @progbits\n" ".global DoSyscall\n" "DoSyscall:\n" #if defined(__x86_64__) "push %rdi\n" "push %rsi\n" "push %rdx\n" "push %r10\n" "push %r8\n" "push %r9\n" // Set up syscall arguments "mov 0x00(%rdi), %rax\n" // Skip 0x08 (%rdi): this comes last "mov 0x10(%rdi), %rsi\n" "mov 0x18(%rdi), %rdx\n" "mov 0x20(%rdi), %r10\n" "mov 0x28(%rdi), %r8\n" "mov 0x30(%rdi), %r9\n" "mov 0x08(%rdi), %rdi\n" "syscall\n" "pop %r9\n" "pop %r8\n" "pop %r10\n" "pop %rdx\n" "pop %rsi\n" "pop %rdi\n" "ret\n" #elif defined(__i386__) "push %ebx\n" "push %ecx\n" "push %edx\n" "push %esi\n" "push %edi\n" "push %ebp\n" "mov 4+24(%esp), %ecx\n" // Set up syscall arguments "mov 0x00(%ecx), %eax\n" "mov 0x04(%ecx), %ebx\n" // Skip 0x08 (%ecx): this comes last "mov 0x0c(%ecx), %edx\n" "mov 0x10(%ecx), %esi\n" "mov 0x14(%ecx), %edi\n" "mov 0x18(%ecx), %ebp\n" "mov 0x08(%ecx), %ecx\n" "int $0x80\n" "pop %ebp\n" "pop %edi\n" "pop %esi\n" "pop %edx\n" "pop %ecx\n" "pop %ebx\n" "ret\n" #else #error Unsupported target platform #endif ".popsection\n" ); void ReturnFromCloneSyscall(SecureMem::Args *secureMem) { // TODO(mseaborn): Call sigreturn() to unblock signals. #if defined(__x86_64__) // Get stack argument that was passed to clone(). void **stack = (void**) secureMem->rsi; // Account for the x86-64 red zone adjustment that our syscall // interceptor does when returning from the system call. stack = (void**) ((char*) stack - 128); *--stack = secureMem->ret; *--stack = secureMem->r15; *--stack = secureMem->r14; *--stack = secureMem->r13; *--stack = secureMem->r12; *--stack = secureMem->r11; *--stack = secureMem->r10; *--stack = secureMem->r9; *--stack = secureMem->r8; *--stack = secureMem->rdi; *--stack = secureMem->rsi; *--stack = secureMem->rdx; *--stack = secureMem->rcx; *--stack = secureMem->rbx; *--stack = secureMem->rbp; asm("mov %0, %%rsp\n" "pop %%rbp\n" "pop %%rbx\n" "pop %%rcx\n" "pop %%rdx\n" "pop %%rsi\n" "pop %%rdi\n" "pop %%r8\n" "pop %%r9\n" "pop %%r10\n" "pop %%r11\n" "pop %%r12\n" "pop %%r13\n" "pop %%r14\n" "pop %%r15\n" "mov $0, %%rax\n" "ret\n" : : "m"(stack)); #elif defined(__i386__) // Get stack argument that was passed to clone(). void **stack = (void**) secureMem->ecx; *--stack = secureMem->ret; *--stack = secureMem->ebp; *--stack = secureMem->edi; *--stack = secureMem->esi; *--stack = secureMem->edx; *--stack = secureMem->ecx; *--stack = secureMem->ebx; asm("mov %0, %%esp\n" "pop %%ebx\n" "pop %%ecx\n" "pop %%edx\n" "pop %%esi\n" "pop %%edi\n" "pop %%ebp\n" "mov $0, %%eax\n" "ret\n" : : "m"(stack)); #else #error Unsupported target platform #endif } void InitCustomTLS(void *addr) { Sandbox::SysCalls sys; #if defined(__x86_64__) int rc = sys.arch_prctl(ARCH_SET_GS, addr); assert(rc == 0); #elif defined(__i386__) struct user_desc u; u.entry_number = (typeof u.entry_number)-1; u.base_addr = (long) addr; u.limit = 0xfffff; u.seg_32bit = 1; u.contents = 0; u.read_exec_only = 0; u.limit_in_pages = 1; u.seg_not_present = 0; u.useable = 1; int rc = sys.set_thread_area(&u); assert(rc == 0); asm volatile("movw %w0, %%fs" : : "q"(8 * u.entry_number + 3)); #else #error Unsupported target platform #endif } void UnlockSyscallMutex() { Sandbox::SysCalls sys; // TODO(mseaborn): Use clone() to be the same as trusted_thread.cc. int pid = sys.fork(); assert(pid >= 0); if (pid == 0) { int rc = sys.mprotect(&Sandbox::syscall_mutex_, 0x1000, PROT_READ | PROT_WRITE); assert(rc == 0); Mutex::unlockMutex(&Sandbox::syscall_mutex_); sys._exit(0); } int status; int rc = sys.waitpid(pid, &status, 0); assert(rc == pid); assert(status == 0); } // Allocate a stack that is never freed. char *AllocateStack() { Sandbox::SysCalls sys; int stack_size = 0x1000; #if defined(__i386__) void *stack = sys.mmap2(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); #else void *stack = sys.mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); #endif assert(stack != MAP_FAILED); return (char *) stack + stack_size; } int HandleNewThread(void *arg) { SecureMem::Args *secureMem = (SecureMem::Args *) arg; CreateReferenceTrustedThread(secureMem->newSecureMem); ReturnFromCloneSyscall(secureMem); return 0; } struct ThreadArgs { SecureMem::Args *secureMem; int threadFd; }; int TrustedThread(void *arg) { struct ThreadArgs *args = (struct ThreadArgs *) arg; SecureMem::Args *secureMem = args->secureMem; int fd = args->threadFd; Sandbox::SysCalls sys; int sequence_no = 2; while (1) { long syscall_args[7]; memset(syscall_args, 0, sizeof(syscall_args)); int got = sys.read(fd, syscall_args, 4); assert(got == 4); long syscall_result; int sysnum = syscall_args[0]; if (sysnum == -1 || sysnum == -2) { // Syscall where the registers have been checked by the trusted // process, e.g. munmap() ranges must be OK. // Doesn't need extra memory region. assert(secureMem->sequence == sequence_no); sequence_no += 2; if (secureMem->syscallNum == __NR_exit) { int rc = sys.close(fd); assert(rc == 0); rc = sys.close(secureMem->threadFdPub); assert(rc == 0); } else if (secureMem->syscallNum == __NR_clone) { assert(sysnum == -2); // Note that HandleNewThread() does UnlockSyscallMutex() for us. #if defined(__x86_64__) long clone_flags = (long) secureMem->rdi; int *pid_ptr = (int *) secureMem->rdx; int *tid_ptr = (int *) secureMem->r10; void *tls_info = secureMem->r8; #elif defined(__i386__) long clone_flags = (long) secureMem->ebx; int *pid_ptr = (int *) secureMem->edx; void *tls_info = secureMem->esi; int *tid_ptr = (int *) secureMem->edi; #else #error Unsupported target platform #endif syscall_result = sys.clone(HandleNewThread, (void *) AllocateStack(), clone_flags, (void *) secureMem, pid_ptr, tls_info, tid_ptr); assert(syscall_result > 0); int sent = sys.write(fd, &syscall_result, sizeof(syscall_result)); assert(sent == sizeof(syscall_result)); continue; } memcpy(syscall_args, &secureMem->syscallNum, sizeof(syscall_args)); // We release the mutex before doing the syscall, because we // have now copied the arguments. if (sysnum == -2) UnlockSyscallMutex(); } else if (sysnum == -3) { // RDTSC request. Send back a dummy answer. int timestamp[2] = {0, 0}; int sent = sys.write(fd, (char *) timestamp, sizeof(timestamp)); assert(sent == 8); continue; } else { int rest_size = sizeof(syscall_args) - sizeof(long); got = sys.read(fd, &syscall_args[1], rest_size); assert(got == rest_size); } syscall_result = DoSyscall(syscall_args); int sent = sys.write(fd, &syscall_result, sizeof(syscall_result)); assert(sent == sizeof(syscall_result)); } } void CreateReferenceTrustedThread(SecureMem::Args *secureMem) { // We are in the nascent thread. Sandbox::SysCalls sys; int socks[2]; int rc = sys.socketpair(AF_UNIX, SOCK_STREAM, 0, socks); assert(rc == 0); int threadFdPub = socks[0]; int threadFd = socks[1]; // Create trusted thread. // We omit CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID. int flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM; // Assumes that the stack grows down. char *stack_top = AllocateStack() - sizeof(struct ThreadArgs); struct ThreadArgs *thread_args = (struct ThreadArgs *) stack_top; thread_args->threadFd = threadFd; thread_args->secureMem = secureMem; rc = sys.clone(TrustedThread, stack_top, flags, thread_args, NULL, NULL, NULL); assert(rc > 0); // Make the thread state pages usable. rc = sys.mprotect(secureMem, 0x1000, PROT_READ); assert(rc == 0); rc = sys.mprotect(((char *) secureMem) + 0x1000, 0x1000, PROT_READ | PROT_WRITE); assert(rc == 0); // Using cookie as the start is a little odd because other code in // syscall.c works around this when addressing from %fs. void *tls = (void*) &secureMem->cookie; InitCustomTLS(tls); UnlockSyscallMutex(); int tid = sys.gettid(); assert(tid > 0); // Send the socket FDs to the trusted process. // TODO(mseaborn): Don't duplicate this struct in trusted_process.cc struct { SecureMem::Args* self; int tid; int fdPub; } __attribute__((packed)) data; data.self = secureMem; data.tid = tid; data.fdPub = threadFdPub; bool ok = Sandbox::sendFd(Sandbox::cloneFdPub_, threadFdPub, threadFd, (void *) &data, sizeof(data)); assert(ok); // Wait for the trusted process to fill out the thread state for us. char byte_message; int got = sys.read(threadFdPub, &byte_message, 1); assert(got == 1); assert(byte_message == 0); // Switch to seccomp mode. rc = sys.prctl(PR_SET_SECCOMP, 1); assert(rc == 0); } } <commit_msg>Fix warning produced by gcc 4.4.1 (from Ubuntu Karmic)<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 "mutex.h" #include "sandbox_impl.h" // This is a C++ implementation of trusted_thread.cc. Since it trusts // the contents of the stack, it is not secure. It is intended to be // a reference implementation. This code can be used as an aid to // understanding what the real trusted thread does, since this code // should be easier to read than assembly code. It can also be used // as a test bed for changes to the trusted thread. namespace playground { void die(const char *msg) { sys_write(2, msg, strlen(msg)); sys_exit_group(1); } #define TO_STRING_1(x) #x #define TO_STRING(x) TO_STRING_1(x) #define assert(expr) { \ if (!(expr)) die("assertion failed at " __FILE__ ":" TO_STRING(__LINE__) \ ": " #expr "\n"); } // Perform a syscall given an array of syscall arguments. extern "C" long DoSyscall(long regs[7]); asm( ".pushsection .text, \"ax\", @progbits\n" ".global DoSyscall\n" "DoSyscall:\n" #if defined(__x86_64__) "push %rdi\n" "push %rsi\n" "push %rdx\n" "push %r10\n" "push %r8\n" "push %r9\n" // Set up syscall arguments "mov 0x00(%rdi), %rax\n" // Skip 0x08 (%rdi): this comes last "mov 0x10(%rdi), %rsi\n" "mov 0x18(%rdi), %rdx\n" "mov 0x20(%rdi), %r10\n" "mov 0x28(%rdi), %r8\n" "mov 0x30(%rdi), %r9\n" "mov 0x08(%rdi), %rdi\n" "syscall\n" "pop %r9\n" "pop %r8\n" "pop %r10\n" "pop %rdx\n" "pop %rsi\n" "pop %rdi\n" "ret\n" #elif defined(__i386__) "push %ebx\n" "push %ecx\n" "push %edx\n" "push %esi\n" "push %edi\n" "push %ebp\n" "mov 4+24(%esp), %ecx\n" // Set up syscall arguments "mov 0x00(%ecx), %eax\n" "mov 0x04(%ecx), %ebx\n" // Skip 0x08 (%ecx): this comes last "mov 0x0c(%ecx), %edx\n" "mov 0x10(%ecx), %esi\n" "mov 0x14(%ecx), %edi\n" "mov 0x18(%ecx), %ebp\n" "mov 0x08(%ecx), %ecx\n" "int $0x80\n" "pop %ebp\n" "pop %edi\n" "pop %esi\n" "pop %edx\n" "pop %ecx\n" "pop %ebx\n" "ret\n" #else #error Unsupported target platform #endif ".popsection\n" ); void ReturnFromCloneSyscall(SecureMem::Args *secureMem) { // TODO(mseaborn): Call sigreturn() to unblock signals. #if defined(__x86_64__) // Get stack argument that was passed to clone(). void **stack = (void**) secureMem->rsi; // Account for the x86-64 red zone adjustment that our syscall // interceptor does when returning from the system call. stack = (void**) ((char*) stack - 128); *--stack = secureMem->ret; *--stack = secureMem->r15; *--stack = secureMem->r14; *--stack = secureMem->r13; *--stack = secureMem->r12; *--stack = secureMem->r11; *--stack = secureMem->r10; *--stack = secureMem->r9; *--stack = secureMem->r8; *--stack = secureMem->rdi; *--stack = secureMem->rsi; *--stack = secureMem->rdx; *--stack = secureMem->rcx; *--stack = secureMem->rbx; *--stack = secureMem->rbp; asm("mov %0, %%rsp\n" "pop %%rbp\n" "pop %%rbx\n" "pop %%rcx\n" "pop %%rdx\n" "pop %%rsi\n" "pop %%rdi\n" "pop %%r8\n" "pop %%r9\n" "pop %%r10\n" "pop %%r11\n" "pop %%r12\n" "pop %%r13\n" "pop %%r14\n" "pop %%r15\n" "mov $0, %%rax\n" "ret\n" : : "m"(stack)); #elif defined(__i386__) // Get stack argument that was passed to clone(). void **stack = (void**) secureMem->ecx; *--stack = secureMem->ret; *--stack = secureMem->ebp; *--stack = secureMem->edi; *--stack = secureMem->esi; *--stack = secureMem->edx; *--stack = secureMem->ecx; *--stack = secureMem->ebx; asm("mov %0, %%esp\n" "pop %%ebx\n" "pop %%ecx\n" "pop %%edx\n" "pop %%esi\n" "pop %%edi\n" "pop %%ebp\n" "mov $0, %%eax\n" "ret\n" : : "m"(stack)); #else #error Unsupported target platform #endif } void InitCustomTLS(void *addr) { Sandbox::SysCalls sys; #if defined(__x86_64__) int rc = sys.arch_prctl(ARCH_SET_GS, addr); assert(rc == 0); #elif defined(__i386__) struct user_desc u; u.entry_number = (typeof u.entry_number)-1; u.base_addr = (long) addr; u.limit = 0xfffff; u.seg_32bit = 1; u.contents = 0; u.read_exec_only = 0; u.limit_in_pages = 1; u.seg_not_present = 0; u.useable = 1; int rc = sys.set_thread_area(&u); assert(rc == 0); asm volatile("movw %w0, %%fs" : : "q"(8 * u.entry_number + 3)); #else #error Unsupported target platform #endif } void UnlockSyscallMutex() { Sandbox::SysCalls sys; // TODO(mseaborn): Use clone() to be the same as trusted_thread.cc. int pid = sys.fork(); assert(pid >= 0); if (pid == 0) { int rc = sys.mprotect(&Sandbox::syscall_mutex_, 0x1000, PROT_READ | PROT_WRITE); assert(rc == 0); Mutex::unlockMutex(&Sandbox::syscall_mutex_); sys._exit(0); } int status; int rc = sys.waitpid(pid, &status, 0); assert(rc == pid); assert(status == 0); } // Allocate a stack that is never freed. char *AllocateStack() { Sandbox::SysCalls sys; int stack_size = 0x1000; #if defined(__i386__) void *stack = sys.mmap2(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); #else void *stack = sys.mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); #endif assert(stack != MAP_FAILED); return (char *) stack + stack_size; } int HandleNewThread(void *arg) { SecureMem::Args *secureMem = (SecureMem::Args *) arg; CreateReferenceTrustedThread(secureMem->newSecureMem); ReturnFromCloneSyscall(secureMem); return 0; } struct ThreadArgs { SecureMem::Args *secureMem; int threadFd; }; int TrustedThread(void *arg) { struct ThreadArgs *args = (struct ThreadArgs *) arg; SecureMem::Args *secureMem = args->secureMem; int fd = args->threadFd; Sandbox::SysCalls sys; int sequence_no = 2; while (1) { long syscall_args[7]; memset(syscall_args, 0, sizeof(syscall_args)); int got = sys.read(fd, syscall_args, 4); assert(got == 4); long syscall_result; int sysnum = syscall_args[0]; if (sysnum == -1 || sysnum == -2) { // Syscall where the registers have been checked by the trusted // process, e.g. munmap() ranges must be OK. // Doesn't need extra memory region. assert(secureMem->sequence == sequence_no); sequence_no += 2; if (secureMem->syscallNum == __NR_exit) { int rc = sys.close(fd); assert(rc == 0); rc = sys.close(secureMem->threadFdPub); assert(rc == 0); } else if (secureMem->syscallNum == __NR_clone) { assert(sysnum == -2); // Note that HandleNewThread() does UnlockSyscallMutex() for us. #if defined(__x86_64__) long clone_flags = (long) secureMem->rdi; int *pid_ptr = (int *) secureMem->rdx; int *tid_ptr = (int *) secureMem->r10; void *tls_info = secureMem->r8; #elif defined(__i386__) long clone_flags = (long) secureMem->ebx; int *pid_ptr = (int *) secureMem->edx; void *tls_info = secureMem->esi; int *tid_ptr = (int *) secureMem->edi; #else #error Unsupported target platform #endif syscall_result = sys.clone(HandleNewThread, (void *) AllocateStack(), clone_flags, (void *) secureMem, pid_ptr, tls_info, tid_ptr); assert(syscall_result > 0); int sent = sys.write(fd, &syscall_result, sizeof(syscall_result)); assert(sent == sizeof(syscall_result)); continue; } memcpy(syscall_args, &secureMem->syscallNum, sizeof(syscall_args)); // We release the mutex before doing the syscall, because we // have now copied the arguments. if (sysnum == -2) UnlockSyscallMutex(); } else if (sysnum == -3) { // RDTSC request. Send back a dummy answer. int timestamp[2] = {0, 0}; int sent = sys.write(fd, (char *) timestamp, sizeof(timestamp)); assert(sent == 8); continue; } else { int rest_size = sizeof(syscall_args) - sizeof(long); got = sys.read(fd, &syscall_args[1], rest_size); assert(got == rest_size); } syscall_result = DoSyscall(syscall_args); int sent = sys.write(fd, &syscall_result, sizeof(syscall_result)); assert(sent == sizeof(syscall_result)); } return 0; } void CreateReferenceTrustedThread(SecureMem::Args *secureMem) { // We are in the nascent thread. Sandbox::SysCalls sys; int socks[2]; int rc = sys.socketpair(AF_UNIX, SOCK_STREAM, 0, socks); assert(rc == 0); int threadFdPub = socks[0]; int threadFd = socks[1]; // Create trusted thread. // We omit CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID. int flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM; // Assumes that the stack grows down. char *stack_top = AllocateStack() - sizeof(struct ThreadArgs); struct ThreadArgs *thread_args = (struct ThreadArgs *) stack_top; thread_args->threadFd = threadFd; thread_args->secureMem = secureMem; rc = sys.clone(TrustedThread, stack_top, flags, thread_args, NULL, NULL, NULL); assert(rc > 0); // Make the thread state pages usable. rc = sys.mprotect(secureMem, 0x1000, PROT_READ); assert(rc == 0); rc = sys.mprotect(((char *) secureMem) + 0x1000, 0x1000, PROT_READ | PROT_WRITE); assert(rc == 0); // Using cookie as the start is a little odd because other code in // syscall.c works around this when addressing from %fs. void *tls = (void*) &secureMem->cookie; InitCustomTLS(tls); UnlockSyscallMutex(); int tid = sys.gettid(); assert(tid > 0); // Send the socket FDs to the trusted process. // TODO(mseaborn): Don't duplicate this struct in trusted_process.cc struct { SecureMem::Args* self; int tid; int fdPub; } __attribute__((packed)) data; data.self = secureMem; data.tid = tid; data.fdPub = threadFdPub; bool ok = Sandbox::sendFd(Sandbox::cloneFdPub_, threadFdPub, threadFd, (void *) &data, sizeof(data)); assert(ok); // Wait for the trusted process to fill out the thread state for us. char byte_message; int got = sys.read(threadFdPub, &byte_message, 1); assert(got == 1); assert(byte_message == 0); // Switch to seccomp mode. rc = sys.prctl(PR_SET_SECCOMP, 1); assert(rc == 0); } } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- Copyright (c) 2010 Tippett Studio All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <iostream> #include <vector> #include <SiteShotgun/SiteProject.h> namespace SiteSG { // ***************************************************************************** SiteProject::SiteProject(SG::Shotgun *sg, const xmlrpc_c::value &attrs) : SG::Project(sg, attrs) { m_classType = "SiteProject"; } // ***************************************************************************** SiteProject::SiteProject(const SiteProject &ref) : Project(ref.m_sg, *ref.m_attrs) { m_classType = "SiteProject"; } // ***************************************************************************** SiteProject::~SiteProject() { // Nothing } // ***************************************************************************** SG::List SiteProject::defaultReturnFields() { return Project::defaultReturnFields() .append("created_by"); } } // End namespace SiteSG <commit_msg>* Minor update on the namespace.<commit_after>/* ----------------------------------------------------------------------------- Copyright (c) 2010 Tippett Studio All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <iostream> #include <vector> #include <SiteShotgun/SiteProject.h> namespace SiteSG { // ***************************************************************************** SiteProject::SiteProject(SG::Shotgun *sg, const xmlrpc_c::value &attrs) : SG::Project(sg, attrs) { m_classType = "SiteProject"; } // ***************************************************************************** SiteProject::SiteProject(const SiteProject &ref) : SG::Project(ref.m_sg, *ref.m_attrs) { m_classType = "SiteProject"; } // ***************************************************************************** SiteProject::~SiteProject() { // Nothing } // ***************************************************************************** SG::List SiteProject::defaultReturnFields() { return SG::Project::defaultReturnFields() .append("created_by"); } } // End namespace SiteSG <|endoftext|>
<commit_before>/* * tt.xfade~ * External object for Max/MSP * * Example project for TTBlue * Copyright Β© 2005 by Timothy Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "ext.h" // Max Header #include "z_dsp.h" // MSP Header #include "ext_strings.h" // String Functions #include "commonsyms.h" // Common symbols used by the Max 4.5 API #include "ext_obex.h" // Max Object Extensions (attributes) Header #include "TTBlueAPI.h" // TTBlue Interfaces... #define MAX_NUM_CHANNELS 32 // Data Structure for this object typedef struct _fade{ t_pxobject x_obj; long attr_shape; long attr_mode; float attr_position; TTUInt16 numChannels; TTAudioObject* xfade; // crossfade object from the TTBlue library TTAudioSignal* audioIn1; TTAudioSignal* audioIn2; TTAudioSignal* audioInControl; TTAudioSignal* audioOut; } t_fade; // Prototypes for methods void *fade_new(t_symbol *s, long argc, t_atom *argv); // New Object Creation Method t_int *fade_perform1(t_int *w); // An MSP Perform (signal) Method t_int *fade_perform2(t_int *w); // An MSP Perform (signal) Method void fade_dsp(t_fade *x, t_signal **sp, short *count); // DSP Method void fade_assist(t_fade *x, void *b, long m, long a, char *s); // Assistance Method void fade_float(t_fade *x, double value ); // Float Method void fade_free(t_fade *x); t_max_err attr_set_position(t_fade *x, void *attr, long argc, t_atom *argv); t_max_err attr_set_shape(t_fade *x, void *attr, long argc, t_atom *argv); t_max_err attr_set_mode(t_fade *x, void *attr, long argc, t_atom *argv); t_int *fade_perform_stereo_1(t_int *w); t_int *fade_perform_stereo_2(t_int *w); // Globals static t_class *s_fade_class; /************************************************************************************/ // Main() Function int main(void) // main recieves a copy of the Max function macros table { long attrflags = 0; t_class *c; t_object *attr; TTBlueInit(); common_symbols_init(); // Define our class c = class_new("tt.xfade~",(method)fade_new, (method)fade_free, sizeof(t_fade), (method)0L, A_GIMME, 0); // Make methods accessible for our class: class_addmethod(c, (method)fade_float, "float", A_FLOAT, 0L); class_addmethod(c, (method)fade_dsp, "dsp", A_CANT, 0L); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT,0); class_addmethod(c, (method)fade_assist, "assist", A_CANT, 0L); // Add attributes to our class: attr = attr_offset_new("shape", _sym_long, attrflags, (method)0L,(method)attr_set_shape, calcoffset(t_fade, attr_shape)); class_addattr(c, attr); attr = attr_offset_new("mode", _sym_long, attrflags, (method)0L,(method)attr_set_mode, calcoffset(t_fade, attr_mode)); class_addattr(c, attr); attr = attr_offset_new("position", _sym_float32, attrflags, (method)0L,(method)attr_set_position, calcoffset(t_fade, attr_position)); class_addattr(c, attr); // Setup our class to work with MSP class_dspinit(c); // Finalize our class class_register(CLASS_BOX, c); s_fade_class = c; return 0; } /************************************************************************************/ // Object Life // Create void *fade_new(t_symbol *s, long argc, t_atom *argv) { long attrstart = attr_args_offset(argc, argv); // support normal arguments short i; t_fade *x = (t_fade *)object_alloc(s_fade_class); if(x){ object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x, NULL)); // dumpout x->numChannels = 1; if(attrstart && argv){ int argument = atom_getlong(argv); x->numChannels = TTClip(argument, 1, MAX_NUM_CHANNELS); } dsp_setup((t_pxobject *)x, (x->numChannels * 2) + 1); // Create Object and N Inlets (last argument) x->x_obj.z_misc = Z_NO_INPLACE; // ESSENTIAL! for(i=0; i< (x->numChannels); i++) outlet_new((t_pxobject *)x, "signal"); // Create a signal Outlet //x->xfade = new TTCrossfade(x->numChannels); // Constructors TTObjectInstantiate(TT("crossfade"), &x->xfade, x->numChannels); TTObjectInstantiate(kTTSym_audiosignal, &x->audioIn1, x->numChannels); TTObjectInstantiate(kTTSym_audiosignal, &x->audioIn2, x->numChannels); TTObjectInstantiate(kTTSym_audiosignal, &x->audioInControl, x->numChannels); TTObjectInstantiate(kTTSym_audiosignal, &x->audioOut, x->numChannels); x->xfade->setAttributeValue(TT("mode"), TT("lookup")); x->xfade->setAttributeValue(TT("shape"), TT("equalPower")); x->xfade->setAttributeValue(TT("position"), 0.5); attr_args_process(x, argc, argv); // handle attribute args } return (x); // Return the pointer } // Destroy void fade_free(t_fade *x) { dsp_free((t_pxobject *)x); // Always call dsp_free first in this routine TTObjectRelease(&x->xfade); TTObjectRelease(&x->audioIn1); TTObjectRelease(&x->audioIn2); TTObjectRelease(&x->audioInControl); TTObjectRelease(&x->audioOut); } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void fade_assist(t_fade *x, void *b, long msg, long arg, char *dst) { if(msg==1){ // Inlets if(arg < x->numChannels) strcpy(dst, "(signal) Input A"); else if(arg < x->numChannels*2) strcpy(dst, "(signal) Input B"); else strcpy(dst, "(float/signal) Crossfade Position"); } else if(msg==2){ // Outlets if(arg < x->numChannels) strcpy(dst, "(signal) Crossfaded between A and B"); else strcpy(dst, "dumpout"); } } // Float Method void fade_float(t_fade *x, double value) { x->attr_position = value; x->xfade->setAttributeValue(TT("position"), value); } // ATTRIBUTE: position t_max_err attr_set_position(t_fade *x, void *attr, long argc, t_atom *argv) { fade_float(x, atom_getfloat(argv)); return MAX_ERR_NONE; } // ATTRIBUTE: shape t_max_err attr_set_shape(t_fade *x, void *attr, long argc, t_atom *argv) { x->attr_shape = atom_getlong(argv); if(x->attr_shape == 0) x->xfade->setAttributeValue(TT("shape"), TT("equalPower")); else x->xfade->setAttributeValue(TT("shape"), TT("linear")); return MAX_ERR_NONE; } // ATTRIBUTE: mode t_max_err attr_set_mode(t_fade *x, void *attr, long argc, t_atom *argv) { x->attr_mode = atom_getlong(argv); if(x->attr_mode == 0) x->xfade->setAttributeValue(TT("mode"), TT("lookup")); else x->xfade->setAttributeValue(TT("mode"), TT("calculate")); return MAX_ERR_NONE; } // control rate fading t_int *fade_perform1(t_int *w) { t_fade *x = (t_fade *)(w[1]); short i, j; TTUInt8 numChannels = x->audioIn1->getNumChannels(); TTUInt16 vs = x->audioIn1->getVectorSize(); for(i=0; i<numChannels; i++){ j = (i*3) + 1; x->audioIn1->setVector(i, vs, (t_float *)(w[j+1])); x->audioIn2->setVector(i, vs, (t_float *)(w[j+2])); } x->xfade->process(*x->audioIn1, *x->audioIn2, *x->audioOut); for(i=0; i<numChannels; i++){ j = (i*3) + 1; x->audioOut->getVector(i, vs, (t_float *)(w[j+3])); } return w + ((numChannels*3)+2); } // signal rate fading t_int *fade_perform2(t_int *w) { t_fade *x = (t_fade *)(w[1]); short i, j; TTUInt8 numChannels = x->audioIn1->getNumChannels(); TTUInt16 vs = x->audioIn1->getVectorSize(); for(i=0; i<numChannels; i++){ j = (i*3) + 1; x->audioIn1->setVector(i, vs, (t_float *)(w[j+1])); x->audioIn2->setVector(i, vs, (t_float *)(w[j+2])); } object_attr_setfloat(x, _sym_position, *((t_float *)(w[(numChannels*3)+2]))); x->xfade->process(*x->audioIn1, *x->audioIn2, *x->audioOut); for(i=0; i<numChannels; i++){ j = (i*3) + 1; x->audioOut->getVector(i, vs, (t_float *)(w[j+3])); } return w + ((numChannels*3)+3); } // DSP Method void fade_dsp(t_fade *x, t_signal **sp, short *count) { short i, j, k, l=0; void **audioVectors = NULL; TTUInt8 numChannels = 0; TTUInt16 vs = 0; if(count[x->numChannels * 2]) // SIGNAL RATE CROSSFADE CONNECTED audioVectors = (void**)sysmem_newptr(sizeof(void*) * ((x->numChannels * 3) + 2)); else // CONTROL RATE CROSSFADE audioVectors = (void**)sysmem_newptr(sizeof(void*) * ((x->numChannels * 3) + 1)); audioVectors[l] = x; l++; // audioVectors[] passed to balance_perform() as {x, audioInL[0], audioInR[0], audioOut[0], audioInL[1], audioInR[1], audioOut[1],...} for(i=0; i < x->numChannels; i++){ j = x->numChannels + i; k = x->numChannels*2 + i + 1; // + 1 to account for the position input if(count[i] && count[j] && count[k]){ numChannels++; if(sp[i]->s_n > vs) vs = sp[i]->s_n; audioVectors[l] = sp[i]->s_vec; l++; audioVectors[l] = sp[j]->s_vec; l++; audioVectors[l] = sp[k]->s_vec; l++; } } if(count[x->numChannels * 2]){ // SIGNAL RATE CROSSFADE CONNECTED audioVectors[l] = sp[x->numChannels*2]->s_vec; l++; } x->audioIn1->setnumChannels(numChannels); x->audioIn2->setnumChannels(numChannels); x->audioOut->setnumChannels(numChannels); x->audioIn1->setvectorSize(vs); x->audioIn2->setvectorSize(vs); x->audioOut->setvectorSize(vs); //audioIn will be set in the perform method x->audioOut->alloc(); x->xfade->setAttributeValue(TT("sr"), sp[0]->s_sr); if(count[x->numChannels * 2]) // SIGNAL RATE CROSSFADE CONNECTED dsp_addv(fade_perform2, l, audioVectors); else dsp_addv(fade_perform1, l, audioVectors); sysmem_freeptr(audioVectors); } <commit_msg>The tt.xfade~ example for MSP now uses new Max 5 API for defining attributes, and includes enumerated names in the Max inspector.<commit_after>/* * tt.xfade~ * External object for Max/MSP * * Example project for TTBlue * Copyright Β© 2005 by Timothy Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "ext.h" // Max Header #include "z_dsp.h" // MSP Header #include "ext_strings.h" // String Functions #include "commonsyms.h" // Common symbols used by the Max 4.5 API #include "ext_obex.h" // Max Object Extensions (attributes) Header #include "TTBlueAPI.h" // TTBlue Interfaces... #define MAX_NUM_CHANNELS 32 // Data Structure for this object typedef struct _fade{ t_pxobject x_obj; long attr_shape; long attr_mode; float attr_position; TTUInt16 numChannels; TTAudioObject* xfade; // crossfade object from the TTBlue library TTAudioSignal* audioIn1; TTAudioSignal* audioIn2; TTAudioSignal* audioInControl; TTAudioSignal* audioOut; } t_fade; // Prototypes for methods void *fade_new(t_symbol *s, long argc, t_atom *argv); // New Object Creation Method t_int *fade_perform1(t_int *w); // An MSP Perform (signal) Method t_int *fade_perform2(t_int *w); // An MSP Perform (signal) Method void fade_dsp(t_fade *x, t_signal **sp, short *count); // DSP Method void fade_assist(t_fade *x, void *b, long m, long a, char *s); // Assistance Method void fade_float(t_fade *x, double value ); // Float Method void fade_free(t_fade *x); t_max_err attr_set_position(t_fade *x, void *attr, long argc, t_atom *argv); t_max_err attr_set_shape(t_fade *x, void *attr, long argc, t_atom *argv); t_max_err attr_set_mode(t_fade *x, void *attr, long argc, t_atom *argv); t_int *fade_perform_stereo_1(t_int *w); t_int *fade_perform_stereo_2(t_int *w); // Globals static t_class *s_fade_class; /************************************************************************************/ // Main() Function int main(void) // main recieves a copy of the Max function macros table { long attrflags = 0; t_class *c; t_object *attr; TTBlueInit(); common_symbols_init(); // Define our class c = class_new("tt.xfade~", (method)fade_new, (method)fade_free, sizeof(t_fade), (method)0L, A_GIMME, 0); // Make methods accessible for our class: class_addmethod(c, (method)fade_float, "float", A_FLOAT, 0L); class_addmethod(c, (method)fade_dsp, "dsp", A_CANT, 0L); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT,0); class_addmethod(c, (method)fade_assist, "assist", A_CANT, 0L); // Add attributes to our class: CLASS_ATTR_LONG(c, "shape", 0, t_fade, attr_shape); CLASS_ATTR_ACCESSORS(c, "shape", NULL, attr_set_shape); CLASS_ATTR_ENUMINDEX(c, "shape", 0, "EqualPower Linear"); CLASS_ATTR_LONG(c, "mode", 0, t_fade, attr_mode); CLASS_ATTR_ACCESSORS(c, "mode", NULL, attr_set_mode); CLASS_ATTR_ENUMINDEX(c, "mode", 0, "LookupTable Calculate"); CLASS_ATTR_FLOAT(c, "position", 0, t_fade, attr_position); CLASS_ATTR_ACCESSORS(c, "position", NULL, attr_set_position); // Setup our class to work with MSP class_dspinit(c); // Finalize our class class_register(CLASS_BOX, c); s_fade_class = c; return 0; } /************************************************************************************/ // Object Life // Create void *fade_new(t_symbol *s, long argc, t_atom *argv) { long attrstart = attr_args_offset(argc, argv); // support normal arguments short i; t_fade *x = (t_fade *)object_alloc(s_fade_class); if(x){ object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x, NULL)); // dumpout x->numChannels = 1; if(attrstart && argv){ int argument = atom_getlong(argv); x->numChannels = TTClip(argument, 1, MAX_NUM_CHANNELS); } dsp_setup((t_pxobject *)x, (x->numChannels * 2) + 1); // Create Object and N Inlets (last argument) x->x_obj.z_misc = Z_NO_INPLACE; // ESSENTIAL! for(i=0; i< (x->numChannels); i++) outlet_new((t_pxobject *)x, "signal"); // Create a signal Outlet //x->xfade = new TTCrossfade(x->numChannels); // Constructors TTObjectInstantiate(TT("crossfade"), &x->xfade, x->numChannels); TTObjectInstantiate(kTTSym_audiosignal, &x->audioIn1, x->numChannels); TTObjectInstantiate(kTTSym_audiosignal, &x->audioIn2, x->numChannels); TTObjectInstantiate(kTTSym_audiosignal, &x->audioInControl, x->numChannels); TTObjectInstantiate(kTTSym_audiosignal, &x->audioOut, x->numChannels); x->xfade->setAttributeValue(TT("mode"), TT("lookup")); x->xfade->setAttributeValue(TT("shape"), TT("equalPower")); x->xfade->setAttributeValue(TT("position"), 0.5); attr_args_process(x, argc, argv); // handle attribute args } return (x); // Return the pointer } // Destroy void fade_free(t_fade *x) { dsp_free((t_pxobject *)x); // Always call dsp_free first in this routine TTObjectRelease(&x->xfade); TTObjectRelease(&x->audioIn1); TTObjectRelease(&x->audioIn2); TTObjectRelease(&x->audioInControl); TTObjectRelease(&x->audioOut); } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void fade_assist(t_fade *x, void *b, long msg, long arg, char *dst) { if(msg==1){ // Inlets if(arg < x->numChannels) strcpy(dst, "(signal) Input A"); else if(arg < x->numChannels*2) strcpy(dst, "(signal) Input B"); else strcpy(dst, "(float/signal) Crossfade Position"); } else if(msg==2){ // Outlets if(arg < x->numChannels) strcpy(dst, "(signal) Crossfaded between A and B"); else strcpy(dst, "dumpout"); } } // Float Method void fade_float(t_fade *x, double value) { x->attr_position = value; x->xfade->setAttributeValue(TT("position"), value); } // ATTRIBUTE: position t_max_err attr_set_position(t_fade *x, void *attr, long argc, t_atom *argv) { fade_float(x, atom_getfloat(argv)); return MAX_ERR_NONE; } // ATTRIBUTE: shape t_max_err attr_set_shape(t_fade *x, void *attr, long argc, t_atom *argv) { x->attr_shape = atom_getlong(argv); if(x->attr_shape == 0) x->xfade->setAttributeValue(TT("shape"), TT("equalPower")); else x->xfade->setAttributeValue(TT("shape"), TT("linear")); return MAX_ERR_NONE; } // ATTRIBUTE: mode t_max_err attr_set_mode(t_fade *x, void *attr, long argc, t_atom *argv) { x->attr_mode = atom_getlong(argv); if(x->attr_mode == 0) x->xfade->setAttributeValue(TT("mode"), TT("lookup")); else x->xfade->setAttributeValue(TT("mode"), TT("calculate")); return MAX_ERR_NONE; } // control rate fading t_int *fade_perform1(t_int *w) { t_fade *x = (t_fade *)(w[1]); short i, j; TTUInt8 numChannels = x->audioIn1->getNumChannels(); TTUInt16 vs = x->audioIn1->getVectorSize(); for(i=0; i<numChannels; i++){ j = (i*3) + 1; x->audioIn1->setVector(i, vs, (t_float *)(w[j+1])); x->audioIn2->setVector(i, vs, (t_float *)(w[j+2])); } x->xfade->process(*x->audioIn1, *x->audioIn2, *x->audioOut); for(i=0; i<numChannels; i++){ j = (i*3) + 1; x->audioOut->getVector(i, vs, (t_float *)(w[j+3])); } return w + ((numChannels*3)+2); } // signal rate fading t_int *fade_perform2(t_int *w) { t_fade *x = (t_fade *)(w[1]); short i, j; TTUInt8 numChannels = x->audioIn1->getNumChannels(); TTUInt16 vs = x->audioIn1->getVectorSize(); for(i=0; i<numChannels; i++){ j = (i*3) + 1; x->audioIn1->setVector(i, vs, (t_float *)(w[j+1])); x->audioIn2->setVector(i, vs, (t_float *)(w[j+2])); } object_attr_setfloat(x, _sym_position, *((t_float *)(w[(numChannels*3)+2]))); x->xfade->process(*x->audioIn1, *x->audioIn2, *x->audioOut); for(i=0; i<numChannels; i++){ j = (i*3) + 1; x->audioOut->getVector(i, vs, (t_float *)(w[j+3])); } return w + ((numChannels*3)+3); } // DSP Method void fade_dsp(t_fade *x, t_signal **sp, short *count) { short i, j, k, l=0; void **audioVectors = NULL; TTUInt8 numChannels = 0; TTUInt16 vs = 0; if(count[x->numChannels * 2]) // SIGNAL RATE CROSSFADE CONNECTED audioVectors = (void**)sysmem_newptr(sizeof(void*) * ((x->numChannels * 3) + 2)); else // CONTROL RATE CROSSFADE audioVectors = (void**)sysmem_newptr(sizeof(void*) * ((x->numChannels * 3) + 1)); audioVectors[l] = x; l++; // audioVectors[] passed to balance_perform() as {x, audioInL[0], audioInR[0], audioOut[0], audioInL[1], audioInR[1], audioOut[1],...} for(i=0; i < x->numChannels; i++){ j = x->numChannels + i; k = x->numChannels*2 + i + 1; // + 1 to account for the position input if(count[i] && count[j] && count[k]){ numChannels++; if(sp[i]->s_n > vs) vs = sp[i]->s_n; audioVectors[l] = sp[i]->s_vec; l++; audioVectors[l] = sp[j]->s_vec; l++; audioVectors[l] = sp[k]->s_vec; l++; } } if(count[x->numChannels * 2]){ // SIGNAL RATE CROSSFADE CONNECTED audioVectors[l] = sp[x->numChannels*2]->s_vec; l++; } x->audioIn1->setnumChannels(numChannels); x->audioIn2->setnumChannels(numChannels); x->audioOut->setnumChannels(numChannels); x->audioIn1->setvectorSize(vs); x->audioIn2->setvectorSize(vs); x->audioOut->setvectorSize(vs); //audioIn will be set in the perform method x->audioOut->alloc(); x->xfade->setAttributeValue(TT("sr"), sp[0]->s_sr); if(count[x->numChannels * 2]) // SIGNAL RATE CROSSFADE CONNECTED dsp_addv(fade_perform2, l, audioVectors); else dsp_addv(fade_perform1, l, audioVectors); sysmem_freeptr(audioVectors); } <|endoftext|>
<commit_before>/* * RGraphicsPlotManipulator.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ // TODO: closure for manipulate substitute expression // TODO: validate that all controls have variables in the expression // TODO: if manipulator popup values and controls match exactly then // do nothing....this will take care of the flashing problem #include "RGraphicsPlotManipulator.hpp" #include <core/Error.hpp> #include <core/FilePath.hpp> #include <r/RExec.hpp> #include <r/RJson.hpp> using namespace core; namespace r { namespace session { namespace graphics { PlotManipulator::PlotManipulator() : sexp_() { } PlotManipulator::PlotManipulator(SEXP sexp) : sexp_(sexp) { } PlotManipulator::~PlotManipulator() { try { } catch(...) { } } Error PlotManipulator::save(const FilePath& filePath) const { // call manipulator save r::exec::RFunction manipSave(".rs.manipulator.save"); manipSave.addParam(sexp_.get()); manipSave.addParam(filePath.absolutePath()); return manipSave.call(); } Error PlotManipulator::load(const FilePath& filePath) { // call manipulator load r::exec::RFunction manipLoad(".rs.manipulator.load"); manipLoad.addParam(filePath.absolutePath()); SEXP manipSEXP; Error error = manipLoad.call(&manipSEXP); if (error) return error; // set it sexp_.set(manipSEXP); return Success(); } void PlotManipulator::asJson(core::json::Value* pValue) const { Error error = r::json::jsonValueFromObject(sexp_.get(), pValue); if (error) LOG_ERROR(error); } SEXP PlotManipulator::sexp() const { return sexp_.get(); } } // namespace graphics } // namespace session } // namesapce r <commit_msg>eliminate TODO comments<commit_after>/* * RGraphicsPlotManipulator.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "RGraphicsPlotManipulator.hpp" #include <core/Error.hpp> #include <core/FilePath.hpp> #include <r/RExec.hpp> #include <r/RJson.hpp> using namespace core; namespace r { namespace session { namespace graphics { PlotManipulator::PlotManipulator() : sexp_() { } PlotManipulator::PlotManipulator(SEXP sexp) : sexp_(sexp) { } PlotManipulator::~PlotManipulator() { try { } catch(...) { } } Error PlotManipulator::save(const FilePath& filePath) const { // call manipulator save r::exec::RFunction manipSave(".rs.manipulator.save"); manipSave.addParam(sexp_.get()); manipSave.addParam(filePath.absolutePath()); return manipSave.call(); } Error PlotManipulator::load(const FilePath& filePath) { // call manipulator load r::exec::RFunction manipLoad(".rs.manipulator.load"); manipLoad.addParam(filePath.absolutePath()); SEXP manipSEXP; Error error = manipLoad.call(&manipSEXP); if (error) return error; // set it sexp_.set(manipSEXP); return Success(); } void PlotManipulator::asJson(core::json::Value* pValue) const { Error error = r::json::jsonValueFromObject(sexp_.get(), pValue); if (error) LOG_ERROR(error); } SEXP PlotManipulator::sexp() const { return sexp_.get(); } } // namespace graphics } // namespace session } // namesapce r <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbCoordinateToName.h" #include "otbMacro.h" #ifdef OTB_USE_CURL #include "tinyxml.h" #include <curl/curl.h> #endif namespace otb { /** * Constructor */ CoordinateToName::CoordinateToName(): m_Lon(-1000.0), m_Lat(-1000.0), m_Multithread(false), m_IsValid(false) { m_PlaceName = ""; m_CountryName = ""; m_TempFileName = "out-SignayriUt1.xml"; m_Threader = itk::MultiThreader::New(); m_UpdateDistance = 0.01;//about 1km at equator } /** * PrintSelf */ void CoordinateToName ::PrintSelf(std::ostream& os, itk::Indent indent) const { this->Superclass::PrintSelf(os,indent); os << indent << " m_Lon " << m_Lon << std::endl; os << indent << " m_Lat " << m_Lat << std::endl; os << indent << " m_PlaceName " << m_PlaceName << std::endl; } bool CoordinateToName::Evaluate() { if (m_Multithread) { m_Threader->SpawnThread(ThreadFunction, this); } else { DoEvaluate(); } } ITK_THREAD_RETURN_TYPE CoordinateToName::ThreadFunction( void *arg ) { struct itk::MultiThreader::ThreadInfoStruct * pInfo = (itk::MultiThreader::ThreadInfoStruct *)(arg); CoordinateToName::Pointer lThis = (CoordinateToName*)(pInfo->UserData); lThis->DoEvaluate(); } void CoordinateToName::DoEvaluate() { std::ostringstream urlStream; urlStream << "http://ws.geonames.org/findNearbyPlaceName?lat="; urlStream << m_Lat; urlStream << "&lng="; urlStream << m_Lon; otbMsgDevMacro("CoordinateToName: retrieve url " << urlStream.str()); RetrieveXML(urlStream); std::string placeName = ""; std::string countryName = ""; ParseXMLGeonames(placeName, countryName); m_PlaceName = placeName; m_CountryName = countryName; m_IsValid = true; } void CoordinateToName::RetrieveXML(std::ostringstream& urlStream) const { #ifdef OTB_USE_CURL CURL *curl; CURLcode res; FILE* output_file = fopen(m_TempFileName.c_str(),"w"); curl = curl_easy_init(); char url[256]; strcpy(url,urlStream.str().data()); // std::cout << url << std::endl; if (curl) { std::vector<char> chunk; curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file); res = curl_easy_perform(curl); fclose(output_file); /* always cleanup */ curl_easy_cleanup(curl); } #endif } void CoordinateToName::ParseXMLGeonames(std::string& placeName, std::string& countryName) const { #ifdef OTB_USE_CURL TiXmlDocument doc( m_TempFileName.c_str() ); doc.LoadFile(); TiXmlHandle docHandle( &doc ); TiXmlElement* childName = docHandle.FirstChild( "geonames" ).FirstChild( "geoname" ). FirstChild( "name" ).Element(); if ( childName ) { placeName=childName->GetText(); } TiXmlElement* childCountryName = docHandle.FirstChild( "geonames" ).FirstChild( "geoname" ). FirstChild( "countryName" ).Element(); if ( childCountryName ) { countryName=childCountryName->GetText(); } remove(m_TempFileName.c_str()); #endif } } // namespace otb <commit_msg>WRG: add return to methods<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbCoordinateToName.h" #include "otbMacro.h" #ifdef OTB_USE_CURL #include "tinyxml.h" #include <curl/curl.h> #endif namespace otb { /** * Constructor */ CoordinateToName::CoordinateToName(): m_Lon(-1000.0), m_Lat(-1000.0), m_Multithread(false), m_IsValid(false) { m_PlaceName = ""; m_CountryName = ""; m_TempFileName = "out-SignayriUt1.xml"; m_Threader = itk::MultiThreader::New(); m_UpdateDistance = 0.01;//about 1km at equator } /** * PrintSelf */ void CoordinateToName ::PrintSelf(std::ostream& os, itk::Indent indent) const { this->Superclass::PrintSelf(os,indent); os << indent << " m_Lon " << m_Lon << std::endl; os << indent << " m_Lat " << m_Lat << std::endl; os << indent << " m_PlaceName " << m_PlaceName << std::endl; } bool CoordinateToName::Evaluate() { if (m_Multithread) { m_Threader->SpawnThread(ThreadFunction, this); } else { DoEvaluate(); } return true; } ITK_THREAD_RETURN_TYPE CoordinateToName::ThreadFunction( void *arg ) { struct itk::MultiThreader::ThreadInfoStruct * pInfo = (itk::MultiThreader::ThreadInfoStruct *)(arg); CoordinateToName::Pointer lThis = (CoordinateToName*)(pInfo->UserData); lThis->DoEvaluate(); return 0; } void CoordinateToName::DoEvaluate() { std::ostringstream urlStream; urlStream << "http://ws.geonames.org/findNearbyPlaceName?lat="; urlStream << m_Lat; urlStream << "&lng="; urlStream << m_Lon; otbMsgDevMacro("CoordinateToName: retrieve url " << urlStream.str()); RetrieveXML(urlStream); std::string placeName = ""; std::string countryName = ""; ParseXMLGeonames(placeName, countryName); m_PlaceName = placeName; m_CountryName = countryName; m_IsValid = true; } void CoordinateToName::RetrieveXML(std::ostringstream& urlStream) const { #ifdef OTB_USE_CURL CURL *curl; CURLcode res; FILE* output_file = fopen(m_TempFileName.c_str(),"w"); curl = curl_easy_init(); char url[256]; strcpy(url,urlStream.str().data()); // std::cout << url << std::endl; if (curl) { std::vector<char> chunk; curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file); res = curl_easy_perform(curl); fclose(output_file); /* always cleanup */ curl_easy_cleanup(curl); } #endif } void CoordinateToName::ParseXMLGeonames(std::string& placeName, std::string& countryName) const { #ifdef OTB_USE_CURL TiXmlDocument doc( m_TempFileName.c_str() ); doc.LoadFile(); TiXmlHandle docHandle( &doc ); TiXmlElement* childName = docHandle.FirstChild( "geonames" ).FirstChild( "geoname" ). FirstChild( "name" ).Element(); if ( childName ) { placeName=childName->GetText(); } TiXmlElement* childCountryName = docHandle.FirstChild( "geonames" ).FirstChild( "geoname" ). FirstChild( "countryName" ).Element(); if ( childCountryName ) { countryName=childCountryName->GetText(); } remove(m_TempFileName.c_str()); #endif } } // namespace otb <|endoftext|>
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "qlinear_global_average_pool.h" #include "core/util/math_cpuonly.h" #include "core/providers/common.h" #include "core/platform/threadpool.h" #include "core/util/math.h" #include "core/mlas/inc/mlas.h" #include <functional> using onnxruntime::concurrency::ThreadPool; namespace onnxruntime { namespace contrib { Status ComputeQLinearGlobalAvgPool( const uint8_t* x, float x_scale, uint8_t x_zero_point, uint8_t* y, float y_scale, uint8_t y_zero_point, int64_t N, int64_t C, int64_t image_size, bool channels_last, concurrency::ThreadPool* tp) { static constexpr int64_t kMiniChannelGroup = 64; if (!channels_last || C == 1) { auto worker = [=](std::ptrdiff_t first, std::ptrdiff_t last) { const uint8_t* input = (const uint8_t*)(x + (first * image_size)); uint8_t* output = (uint8_t*)(y + first); std::vector<int32_t> acc_buffer(MlasQLinearSafePaddingElementCount(sizeof(int32_t), last - first)); MlasQLinearGlobalAveragePoolNchw(input, x_scale, x_zero_point, output, y_scale, y_zero_point, last - first, image_size, acc_buffer.data()); }; concurrency::ThreadPool::TryParallelFor( tp, static_cast<std::ptrdiff_t>(N * C), {1.0 * image_size, 1.0, 8.0 * image_size}, worker); } else { if (N == 1) { int64_t channel_padded = (C + kMiniChannelGroup - 1) & (~(kMiniChannelGroup - 1)); int64_t channel_groups = channel_padded / kMiniChannelGroup; auto worker = [=](std::ptrdiff_t first, std::ptrdiff_t last) { std::vector<int32_t> acc_buffer(MlasQLinearSafePaddingElementCount(sizeof(int32_t), C)); std::vector<uint8_t> zero_buffer(MlasQLinearSafePaddingElementCount(sizeof(uint8_t), C), 0); const uint8_t* input = x + first * kMiniChannelGroup; uint8_t* output = y + first * kMiniChannelGroup; int64_t channel_count = (last == channel_groups) ? (C - first * kMiniChannelGroup) : ((last - first) * kMiniChannelGroup); MlasQLinearGlobalAveragePoolNhwc( input, x_scale, x_zero_point, output, y_scale, y_zero_point, N, image_size, C, channel_count, acc_buffer.data(), zero_buffer.data()); }; concurrency::ThreadPool::TryParallelFor( tp, static_cast<std::ptrdiff_t>(channel_groups), {1.0 * N * image_size * kMiniChannelGroup, 1.0 * N * kMiniChannelGroup, 8.0 * N * image_size * kMiniChannelGroup}, worker); } else { auto worker = [=](std::ptrdiff_t first, std::ptrdiff_t last) { const uint8_t* input = x + first * C * image_size; uint8_t* output = y + first * C; std::vector<int32_t> acc_buffer(MlasQLinearSafePaddingElementCount(sizeof(int32_t), C)); std::vector<uint8_t> zero_buffer(MlasQLinearSafePaddingElementCount(sizeof(uint8_t), C), 0); MlasQLinearGlobalAveragePoolNhwc( input, x_scale, x_zero_point, output, y_scale, y_zero_point, last - first, image_size, C, C, acc_buffer.data(), zero_buffer.data()); }; concurrency::ThreadPool::TryParallelFor( tp, static_cast<std::ptrdiff_t>(N), {1.0 * image_size * C, 1.0 * C, 8.0 *image_size * C}, worker); } } return Status::OK(); } Status QLinearGlobalAveragePool::Compute(OpKernelContext* context) const { const auto tensor_x_scale = context->Input<Tensor>(1); const auto tensor_x_zero_point = context->Input<Tensor>(2); const auto tensor_y_scale = context->Input<Tensor>(3); const auto tensor_y_zero_point = context->Input<Tensor>(4); ORT_ENFORCE(IsScalarOr1ElementVector(tensor_x_scale), "Input x_scale must be a scalar or 1D tensor of size 1"); ORT_ENFORCE(IsScalarOr1ElementVector(tensor_x_zero_point), "input x_zero_point must be a scalar or 1D tensor of size 1 if given"); ORT_ENFORCE(IsScalarOr1ElementVector(tensor_y_scale), "input y_scale must be a scalar or 1D tensor of size 1"); ORT_ENFORCE(IsScalarOr1ElementVector(tensor_y_zero_point), "input y_zero_point must be a scalar or 1D tensor of size 1 if given"); concurrency::ThreadPool* tp = context->GetOperatorThreadPool(); const auto& X = *context->Input<Tensor>(0); const auto& x_shape = X.Shape().GetDims(); ORT_RETURN_IF_NOT(x_shape.size() >= 3, "Input dimension cannot be less than 3."); const size_t spatial_dim_start = channels_last_ ? 1 : 2; const size_t spatial_dim_end = spatial_dim_start + (x_shape.size() - 2); int64_t N = x_shape[0]; int64_t C = (channels_last_ ? x_shape.back() : x_shape[1]); int64_t image_size = std::accumulate(x_shape.cbegin() + spatial_dim_start, x_shape.cbegin() + spatial_dim_end, 1LL, std::multiplies<int64_t>()); std::vector<int64_t> output_dims(x_shape); std::transform(x_shape.cbegin() + spatial_dim_start, x_shape.cbegin() + spatial_dim_end, output_dims.begin() + spatial_dim_start, [](const int64_t&) { return int64_t{1}; }); Tensor& Y = *context->Output(0, output_dims); const float x_scale = *(tensor_x_scale->Data<float>()); const float y_scale = *(tensor_y_scale->Data<float>()); auto dtype = X.GetElementType(); switch (dtype) { case ONNX_NAMESPACE::TensorProto_DataType_UINT8: return ComputeQLinearGlobalAvgPool(X.Data<uint8_t>(), x_scale, *(tensor_x_zero_point->Data<uint8_t>()), Y.MutableData<uint8_t>(), y_scale, *(tensor_y_zero_point->Data<uint8_t>()), N, C, image_size, channels_last_, tp); default: ORT_THROW("Unsupported 'dtype' value: ", dtype); } } ONNX_OPERATOR_KERNEL_EX(QLinearGlobalAveragePool, kMSDomain, 1, kCpuExecutionProvider, KernelDefBuilder(), QLinearGlobalAveragePool); } // namespace contrib } // namespace onnxruntime <commit_msg>disable inner parallel for global avg pool as normally they are small (#9487)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "qlinear_global_average_pool.h" #include "core/util/math_cpuonly.h" #include "core/providers/common.h" #include "core/platform/threadpool.h" #include "core/util/math.h" #include "core/mlas/inc/mlas.h" #include <functional> using onnxruntime::concurrency::ThreadPool; namespace onnxruntime { namespace contrib { Status ComputeQLinearGlobalAvgPool( const uint8_t* x, float x_scale, uint8_t x_zero_point, uint8_t* y, float y_scale, uint8_t y_zero_point, int64_t N, int64_t C, int64_t image_size, bool channels_last, concurrency::ThreadPool* tp) { if (!channels_last || C == 1) { auto worker = [=](std::ptrdiff_t first, std::ptrdiff_t last) { const uint8_t* input = (const uint8_t*)(x + (first * image_size)); uint8_t* output = (uint8_t*)(y + first); std::vector<int32_t> acc_buffer(MlasQLinearSafePaddingElementCount(sizeof(int32_t), last - first)); MlasQLinearGlobalAveragePoolNchw(input, x_scale, x_zero_point, output, y_scale, y_zero_point, last - first, image_size, acc_buffer.data()); }; concurrency::ThreadPool::TryParallelFor( tp, static_cast<std::ptrdiff_t>(N * C), {1.0 * image_size, 1.0, 8.0 * image_size}, worker); } else { auto worker = [=](std::ptrdiff_t first, std::ptrdiff_t last) { const uint8_t* input = x + first * C * image_size; uint8_t* output = y + first * C; std::vector<int32_t> acc_buffer(MlasQLinearSafePaddingElementCount(sizeof(int32_t), C)); std::vector<uint8_t> zero_buffer(MlasQLinearSafePaddingElementCount(sizeof(uint8_t), C), 0); MlasQLinearGlobalAveragePoolNhwc( input, x_scale, x_zero_point, output, y_scale, y_zero_point, last - first, image_size, C, C, acc_buffer.data(), zero_buffer.data()); }; concurrency::ThreadPool::TryParallelFor( tp, static_cast<std::ptrdiff_t>(N), {1.0 * image_size * C, 1.0 * C, 8.0 *image_size * C}, worker); } return Status::OK(); } Status QLinearGlobalAveragePool::Compute(OpKernelContext* context) const { const auto tensor_x_scale = context->Input<Tensor>(1); const auto tensor_x_zero_point = context->Input<Tensor>(2); const auto tensor_y_scale = context->Input<Tensor>(3); const auto tensor_y_zero_point = context->Input<Tensor>(4); ORT_ENFORCE(IsScalarOr1ElementVector(tensor_x_scale), "Input x_scale must be a scalar or 1D tensor of size 1"); ORT_ENFORCE(IsScalarOr1ElementVector(tensor_x_zero_point), "input x_zero_point must be a scalar or 1D tensor of size 1 if given"); ORT_ENFORCE(IsScalarOr1ElementVector(tensor_y_scale), "input y_scale must be a scalar or 1D tensor of size 1"); ORT_ENFORCE(IsScalarOr1ElementVector(tensor_y_zero_point), "input y_zero_point must be a scalar or 1D tensor of size 1 if given"); concurrency::ThreadPool* tp = context->GetOperatorThreadPool(); const auto& X = *context->Input<Tensor>(0); const auto& x_shape = X.Shape().GetDims(); ORT_RETURN_IF_NOT(x_shape.size() >= 3, "Input dimension cannot be less than 3."); const size_t spatial_dim_start = channels_last_ ? 1 : 2; const size_t spatial_dim_end = spatial_dim_start + (x_shape.size() - 2); int64_t N = x_shape[0]; int64_t C = (channels_last_ ? x_shape.back() : x_shape[1]); int64_t image_size = std::accumulate(x_shape.cbegin() + spatial_dim_start, x_shape.cbegin() + spatial_dim_end, 1LL, std::multiplies<int64_t>()); std::vector<int64_t> output_dims(x_shape); std::transform(x_shape.cbegin() + spatial_dim_start, x_shape.cbegin() + spatial_dim_end, output_dims.begin() + spatial_dim_start, [](const int64_t&) { return int64_t{1}; }); Tensor& Y = *context->Output(0, output_dims); const float x_scale = *(tensor_x_scale->Data<float>()); const float y_scale = *(tensor_y_scale->Data<float>()); auto dtype = X.GetElementType(); switch (dtype) { case ONNX_NAMESPACE::TensorProto_DataType_UINT8: return ComputeQLinearGlobalAvgPool(X.Data<uint8_t>(), x_scale, *(tensor_x_zero_point->Data<uint8_t>()), Y.MutableData<uint8_t>(), y_scale, *(tensor_y_zero_point->Data<uint8_t>()), N, C, image_size, channels_last_, tp); default: ORT_THROW("Unsupported 'dtype' value: ", dtype); } } ONNX_OPERATOR_KERNEL_EX(QLinearGlobalAveragePool, kMSDomain, 1, kCpuExecutionProvider, KernelDefBuilder(), QLinearGlobalAveragePool); } // namespace contrib } // namespace onnxruntime <|endoftext|>
<commit_before>/* * BackwardChainerPMCB.cc * * Copyright (C) 2014 Misgana Bayetta * Copyright (C) 2015 OpenCog Foundation * * Author: Misgana Bayetta <[email protected]> October 2014 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "BackwardChainerPMCB.h" using namespace opencog; BackwardChainerPMCB::BackwardChainerPMCB(AtomSpace * as) : InitiateSearchCB(as), DefaultPatternMatchCB(as), as_(as) // : Implicator(as), DefaultPatternMatchCB(as), AttentionalFocusCB(as), PLNImplicator(as), as_(as) { } BackwardChainerPMCB::~BackwardChainerPMCB() { } bool BackwardChainerPMCB::grounding(const std::map<Handle, Handle> &var_soln, const std::map<Handle, Handle> &pred_soln) { std::map<Handle, Handle> true_var_soln; // get rid of non-var mapping for (auto& p : var_soln) { if (p.first->getType() == VARIABLE_NODE) true_var_soln[p.first] = p.second; } // XXX TODO if a variable match to itself, reject? // store the variable solution var_solns_.push_back(true_var_soln); pred_solns_.push_back(pred_soln); return false; } std::vector<std::map<Handle, Handle>> BackwardChainerPMCB::get_var_list() { return var_solns_; } std::vector<std::map<Handle, Handle>> BackwardChainerPMCB::get_pred_list() { return pred_solns_; } <commit_msg>Correct variable checking in PMCB<commit_after>/* * BackwardChainerPMCB.cc * * Copyright (C) 2014 Misgana Bayetta * Copyright (C) 2015 OpenCog Foundation * * Author: Misgana Bayetta <[email protected]> October 2014 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "BackwardChainerPMCB.h" using namespace opencog; BackwardChainerPMCB::BackwardChainerPMCB(AtomSpace * as) : InitiateSearchCB(as), DefaultPatternMatchCB(as), as_(as) // : Implicator(as), DefaultPatternMatchCB(as), AttentionalFocusCB(as), PLNImplicator(as), as_(as) { } BackwardChainerPMCB::~BackwardChainerPMCB() { } bool BackwardChainerPMCB::grounding(const std::map<Handle, Handle> &var_soln, const std::map<Handle, Handle> &pred_soln) { std::map<Handle, Handle> true_var_soln; // get rid of non-var mapping for (auto& p : var_soln) { if (_variables->varset.count(p.first) == 1) true_var_soln[p.first] = p.second; } // XXX TODO if a variable match to itself, reject? if (true_var_soln.size() == 0) return false; // store the variable solution var_solns_.push_back(true_var_soln); pred_solns_.push_back(pred_soln); return false; } std::vector<std::map<Handle, Handle>> BackwardChainerPMCB::get_var_list() { return var_solns_; } std::vector<std::map<Handle, Handle>> BackwardChainerPMCB::get_pred_list() { return pred_solns_; } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, 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 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: E. Gil Jones */ #include <ros/ros.h> #include <chomp_motion_planner/chomp_planner.h> #include <chomp_motion_planner/chomp_trajectory.h> #include <chomp_motion_planner/chomp_optimizer.h> #include <moveit/robot_state/conversions.h> #include <moveit_msgs/MotionPlanRequest.h> namespace chomp { ChompPlanner::ChompPlanner() { } bool ChompPlanner::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, const moveit_msgs::MotionPlanRequest& req, const chomp::ChompParameters& params, moveit_msgs::MotionPlanDetailedResponse& res) const { if (!planning_scene) { ROS_ERROR_STREAM("No planning scene initialized."); return false; } ros::WallTime start_time = ros::WallTime::now(); ChompTrajectory trajectory(planning_scene->getRobotModel(), 3.0, .03, req.group_name); jointStateToArray(planning_scene->getRobotModel(), req.start_state.joint_state, req.group_name, trajectory.getTrajectoryPoint(0)); int goal_index = trajectory.getNumPoints() - 1; trajectory.getTrajectoryPoint(goal_index) = trajectory.getTrajectoryPoint(0); sensor_msgs::JointState js; for (unsigned int i = 0; i < req.goal_constraints[0].joint_constraints.size(); i++) { js.name.push_back(req.goal_constraints[0].joint_constraints[i].joint_name); js.position.push_back(req.goal_constraints[0].joint_constraints[i].position); ROS_INFO_STREAM("Setting joint " << req.goal_constraints[0].joint_constraints[i].joint_name << " to position " << req.goal_constraints[0].joint_constraints[i].position); } jointStateToArray(planning_scene->getRobotModel(), js, req.group_name, trajectory.getTrajectoryPoint(goal_index)); const moveit::core::JointModelGroup* model_group = planning_scene->getRobotModel()->getJointModelGroup(req.group_name); // fix the goal to move the shortest angular distance for wrap-around joints: for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++) { const moveit::core::JointModel* model = model_group->getActiveJointModels()[i]; const moveit::core::RevoluteJointModel* revolute_joint = dynamic_cast<const moveit::core::RevoluteJointModel*>(model); if (revolute_joint != NULL) { if (revolute_joint->isContinuous()) { double start = (trajectory)(0, i); double end = (trajectory)(goal_index, i); ROS_INFO_STREAM("Start is " << start << " end " << end << " short " << shortestAngularDistance(start, end)); (trajectory)(goal_index, i) = start + shortestAngularDistance(start, end); } } } // fill in an initial quintic spline trajectory trajectory.fillInMinJerk(); // optimize! moveit::core::RobotState start_state(planning_scene->getCurrentState()); moveit::core::robotStateMsgToRobotState(req.start_state, start_state); start_state.update(); ros::WallTime create_time = ros::WallTime::now(); ChompOptimizer optimizer(&trajectory, planning_scene, req.group_name, &params, start_state); if (!optimizer.isInitialized()) { ROS_WARN_STREAM("Could not initialize optimizer"); res.error_code.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED; return false; } ROS_INFO("Optimization took %f sec to create", (ros::WallTime::now() - create_time).toSec()); optimizer.optimize(); ROS_INFO("Optimization actually took %f sec to run", (ros::WallTime::now() - create_time).toSec()); create_time = ros::WallTime::now(); // assume that the trajectory is now optimized, fill in the output structure: ROS_INFO("Output trajectory has %d joints", trajectory.getNumJoints()); res.trajectory.resize(1); for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++) { res.trajectory[0].joint_trajectory.joint_names.push_back(model_group->getActiveJointModels()[i]->getName()); } res.trajectory[0].joint_trajectory.header = req.start_state.joint_state.header; // @TODO this is probably a hack // fill in the entire trajectory res.trajectory[0].joint_trajectory.points.resize(trajectory.getNumPoints()); for (int i = 0; i < trajectory.getNumPoints(); i++) { res.trajectory[0].joint_trajectory.points[i].positions.resize(trajectory.getNumJoints()); for (size_t j = 0; j < res.trajectory[0].joint_trajectory.points[i].positions.size(); j++) { res.trajectory[0].joint_trajectory.points[i].positions[j] = trajectory.getTrajectoryPoint(i)(j); if (i == trajectory.getNumPoints() - 1) { ROS_INFO_STREAM("Joint " << j << " " << res.trajectory[0].joint_trajectory.points[i].positions[j]); } } // Setting invalid timestamps. // Further filtering is required to set valid timestamps accounting for velocity and acceleration constraints. res.trajectory[0].joint_trajectory.points[i].time_from_start = ros::Duration(0.0); } ROS_INFO("Bottom took %f sec to create", (ros::WallTime::now() - create_time).toSec()); ROS_INFO("Serviced planning request in %f wall-seconds, trajectory duration is %f", (ros::WallTime::now() - start_time).toSec(), res.trajectory[0].joint_trajectory.points[goal_index].time_from_start.toSec()); res.error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS; res.processing_time.push_back((ros::WallTime::now() - start_time).toSec()); return true; } } <commit_msg>Fail without joint-space goal<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, 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 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: E. Gil Jones */ #include <ros/ros.h> #include <chomp_motion_planner/chomp_planner.h> #include <chomp_motion_planner/chomp_trajectory.h> #include <chomp_motion_planner/chomp_optimizer.h> #include <moveit/robot_state/conversions.h> #include <moveit_msgs/MotionPlanRequest.h> namespace chomp { ChompPlanner::ChompPlanner() { } bool ChompPlanner::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, const moveit_msgs::MotionPlanRequest& req, const chomp::ChompParameters& params, moveit_msgs::MotionPlanDetailedResponse& res) const { if (!planning_scene) { ROS_ERROR_STREAM("No planning scene initialized."); res.error_code.val = moveit_msgs::MoveItErrorCodes::FAILURE; return false; } ros::WallTime start_time = ros::WallTime::now(); ChompTrajectory trajectory(planning_scene->getRobotModel(), 3.0, .03, req.group_name); jointStateToArray(planning_scene->getRobotModel(), req.start_state.joint_state, req.group_name, trajectory.getTrajectoryPoint(0)); if(req.goal_constraints[0].joint_constraints.empty()) { ROS_ERROR_STREAM("CHOMP only supports joint-space goals"); res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS; return false; } int goal_index = trajectory.getNumPoints() - 1; trajectory.getTrajectoryPoint(goal_index) = trajectory.getTrajectoryPoint(0); sensor_msgs::JointState js; for (unsigned int i = 0; i < req.goal_constraints[0].joint_constraints.size(); i++) { js.name.push_back(req.goal_constraints[0].joint_constraints[i].joint_name); js.position.push_back(req.goal_constraints[0].joint_constraints[i].position); ROS_INFO_STREAM("Setting joint " << req.goal_constraints[0].joint_constraints[i].joint_name << " to position " << req.goal_constraints[0].joint_constraints[i].position); } jointStateToArray(planning_scene->getRobotModel(), js, req.group_name, trajectory.getTrajectoryPoint(goal_index)); const moveit::core::JointModelGroup* model_group = planning_scene->getRobotModel()->getJointModelGroup(req.group_name); // fix the goal to move the shortest angular distance for wrap-around joints: for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++) { const moveit::core::JointModel* model = model_group->getActiveJointModels()[i]; const moveit::core::RevoluteJointModel* revolute_joint = dynamic_cast<const moveit::core::RevoluteJointModel*>(model); if (revolute_joint != NULL) { if (revolute_joint->isContinuous()) { double start = (trajectory)(0, i); double end = (trajectory)(goal_index, i); ROS_INFO_STREAM("Start is " << start << " end " << end << " short " << shortestAngularDistance(start, end)); (trajectory)(goal_index, i) = start + shortestAngularDistance(start, end); } } } // fill in an initial quintic spline trajectory trajectory.fillInMinJerk(); // optimize! moveit::core::RobotState start_state(planning_scene->getCurrentState()); moveit::core::robotStateMsgToRobotState(req.start_state, start_state); start_state.update(); ros::WallTime create_time = ros::WallTime::now(); ChompOptimizer optimizer(&trajectory, planning_scene, req.group_name, &params, start_state); if (!optimizer.isInitialized()) { ROS_WARN_STREAM("Could not initialize optimizer"); res.error_code.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED; return false; } ROS_INFO("Optimization took %f sec to create", (ros::WallTime::now() - create_time).toSec()); optimizer.optimize(); ROS_INFO("Optimization actually took %f sec to run", (ros::WallTime::now() - create_time).toSec()); create_time = ros::WallTime::now(); // assume that the trajectory is now optimized, fill in the output structure: ROS_INFO("Output trajectory has %d joints", trajectory.getNumJoints()); res.trajectory.resize(1); for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++) { res.trajectory[0].joint_trajectory.joint_names.push_back(model_group->getActiveJointModels()[i]->getName()); } res.trajectory[0].joint_trajectory.header = req.start_state.joint_state.header; // @TODO this is probably a hack // fill in the entire trajectory res.trajectory[0].joint_trajectory.points.resize(trajectory.getNumPoints()); for (int i = 0; i < trajectory.getNumPoints(); i++) { res.trajectory[0].joint_trajectory.points[i].positions.resize(trajectory.getNumJoints()); for (size_t j = 0; j < res.trajectory[0].joint_trajectory.points[i].positions.size(); j++) { res.trajectory[0].joint_trajectory.points[i].positions[j] = trajectory.getTrajectoryPoint(i)(j); if (i == trajectory.getNumPoints() - 1) { ROS_INFO_STREAM("Joint " << j << " " << res.trajectory[0].joint_trajectory.points[i].positions[j]); } } // Setting invalid timestamps. // Further filtering is required to set valid timestamps accounting for velocity and acceleration constraints. res.trajectory[0].joint_trajectory.points[i].time_from_start = ros::Duration(0.0); } ROS_INFO("Bottom took %f sec to create", (ros::WallTime::now() - create_time).toSec()); ROS_INFO("Serviced planning request in %f wall-seconds, trajectory duration is %f", (ros::WallTime::now() - start_time).toSec(), res.trajectory[0].joint_trajectory.points[goal_index].time_from_start.toSec()); res.error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS; res.processing_time.push_back((ros::WallTime::now() - start_time).toSec()); return true; } } <|endoftext|>
<commit_before>//======================================================== // Hazi feladat keret. // A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // sorokon beluli reszben celszeru garazdalkodni, mert // a tobbit ugyis toroljuk. // A Hazi feladat csak ebben a fajlban lehet // Tilos: // - mast "beincludolni", illetve mas konyvtarat hasznalni // - faljmuveleteket vegezni //======================================================== #include <math.h> #include <stdlib.h> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) // MsWindows-on ez is kell #include <windows.h> #else // g++ nem fordit a stanard include-ok nelkul :-/ #include <string.h> #endif // Win32 platform #include <GL/gl.h> #include <GL/glu.h> // A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/ #include <GL/glut.h> #include <stdio.h> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Innentol modosithatod... //-------------------------------------------------------- // Nev: Vajna Miklos // Neptun: AYU9RZ //-------------------------------------------------------- #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) class Vector { public: float x, y, z; Vector(float x0, float y0, float z0) { x = x0; y = y0; z = z0; } Vector operator+(const Vector& v) { return Vector(x + v.x, y + v.y, z + v.z); } Vector operator*(float f) { return Vector(x * f, y * f, z * f); } }; class Matrix { public: float m[4][4]; void Clear() { memset(&m[0][0], 0, sizeof(m)); } void LoadIdentify() { Clear(); m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1; } Vector operator*(const Vector& v) { float Xh = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3]; float Yh = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3]; float Zh = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3]; float h = m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3]; return Vector(Xh/h, Yh/h, Zh/h); } float *GetArray() { return &m[0][0]; } }; enum { NOOP = 0, SCALE, ROTATE, SHIFT }; int trans_state = NOOP; enum { OPENGL = 0, MANUAL }; int matrix_state = MANUAL; // csak mert math.ht nemszabad ;-/ # define M_PI 3.14159265358979323846 const Vector* points[2][7]; Matrix* transs[4]; void onInitialization( ) { points[0][0] = new Vector(160, 20, 0); points[0][1] = new Vector(250, 80, 0); points[0][2] = new Vector(270, 20, 0); points[0][3] = new Vector(360, 80, 0); points[0][4] = new Vector(390, 20, 0); points[0][5] = new Vector(470, 80, 0); points[0][6] = new Vector(490, 20, 0); points[1][0] = new Vector(160, 120, 0); points[1][1] = new Vector(250, 180, 0); points[1][2] = new Vector(270, 120, 0); points[1][3] = new Vector(360, 180, 0); points[1][4] = new Vector(390, 120, 0); points[1][5] = new Vector(470, 180, 0); points[1][6] = new Vector(490, 120, 0); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * 0 0 0 1 */ transs[NOOP] = new Matrix(); transs[NOOP]->LoadIdentify(); /* * 0.5 0 0 0 * 0 0.5 0 0 * 0 0 0.5 0 * 0 0 0 1 */ transs[SCALE] = new Matrix(); transs[SCALE]->LoadIdentify(); transs[SCALE]->m[0][0] = 0.5; transs[SCALE]->m[1][1] = 0.5; transs[SCALE]->m[2][2] = 0.5; /* * cos sin 0 0 * -sin cos 0 0 * 0 0 1 0 * 0 0 0 1 */ float angle = M_PI/4; transs[ROTATE] = new Matrix(); transs[ROTATE]->LoadIdentify(); transs[ROTATE]->m[0][0] = cosf(angle); transs[ROTATE]->m[0][1] = -sinf(angle); transs[ROTATE]->m[1][0] = sinf(angle); transs[ROTATE]->m[1][1] = cosf(angle); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * px py pz 1 */ transs[SHIFT] = new Matrix(); transs[SHIFT]->LoadIdentify(); transs[SHIFT]->m[1][3] = 100; } void onDisplay( ) { glClearColor(0.1f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor4d(0.9f, 0.8f, 0.7f, 1.0f); glMatrixMode(GL_PROJECTION); if (matrix_state == MANUAL) { glLoadIdentity(); } else { glLoadMatrixf(transs[trans_state]->GetArray()); } gluOrtho2D(0., 600., 0., 600.); for (int i = 0; i < ARRAY_SIZE(points); i++) { glBegin(GL_LINE_STRIP); for (int j = 0; j < ARRAY_SIZE(points[i]); j++) { if (matrix_state == MANUAL) { Vector v = *transs[trans_state] * *points[i][j]; glVertex2d(v.x, v.y); } else { Vector v = *points[i][j]; glVertex2d(v.x, v.y); } } glEnd(); } // Buffercsere: rajzolas vege glFinish(); glutSwapBuffers(); } void onMouse(int button, int state, int x, int y) { // A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON // ill. a GLUT_DOWN / GLUT_UP makrokat hasznald. } void onIdle( ) { } void onKeyboard(unsigned char key, int x, int y) { if (key != 's' && key != 'S') return; if (key == 's') matrix_state = MANUAL; else matrix_state = OPENGL; trans_state = (trans_state + 1) % 4; onDisplay(); } // ...Idaig modosithatod //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(600, 600); glutInitWindowPosition(100, 100); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow("Grafika hazi feladat"); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); onInitialization(); glutDisplayFunc(onDisplay); glutMouseFunc(onMouse); glutIdleFunc(onIdle); glutKeyboardFunc(onKeyboard); glutMainLoop(); return 0; } <commit_msg>simplify, still buggy<commit_after>//======================================================== // Hazi feladat keret. // A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // sorokon beluli reszben celszeru garazdalkodni, mert // a tobbit ugyis toroljuk. // A Hazi feladat csak ebben a fajlban lehet // Tilos: // - mast "beincludolni", illetve mas konyvtarat hasznalni // - faljmuveleteket vegezni //======================================================== #include <math.h> #include <stdlib.h> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) // MsWindows-on ez is kell #include <windows.h> #else // g++ nem fordit a stanard include-ok nelkul :-/ #include <string.h> #endif // Win32 platform #include <GL/gl.h> #include <GL/glu.h> // A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/ #include <GL/glut.h> #include <stdio.h> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Innentol modosithatod... //-------------------------------------------------------- // Nev: Vajna Miklos // Neptun: AYU9RZ //-------------------------------------------------------- #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) class Vector { public: float x, y, z; Vector(float x0, float y0, float z0) { x = x0; y = y0; z = z0; } Vector operator+(const Vector& v) { return Vector(x + v.x, y + v.y, z + v.z); } Vector operator*(float f) { return Vector(x * f, y * f, z * f); } }; class Matrix { public: float m[16]; void Clear() { memset(&m[0], 0, sizeof(m)); } void LoadIdentify() { Clear(); m[0] = m[5] = m[10] = m[15] = 1; } Vector operator*(const Vector& v) { float Xh = m[0] * v.x + m[1] * v.y + m[2] * v.z + m[3]; float Yh = m[4] * v.x + m[5] * v.y + m[6] * v.z + m[7]; float Zh = m[8] * v.x + m[9] * v.y + m[10] * v.z + m[11]; float h = m[12] * v.x + m[13] * v.y + m[14] * v.z + m[15]; return Vector(Xh/h, Yh/h, Zh/h); } float *GetArray() { return &m[0]; } void Dump() { printf("%f\t%f\t%f\t%f\n", m[0], m[4], m[8], m[12]); printf("%f\t%f\t%f\t%f\n", m[1], m[5], m[9], m[13]); printf("%f\t%f\t%f\t%f\n", m[2], m[6], m[10], m[14]); printf("%f\t%f\t%f\t%f\n", m[3], m[7], m[11], m[15]); printf("--end--\n"); } }; enum { NOOP = 0, SCALE, ROTATE, SHIFT }; int trans_state = NOOP; enum { OPENGL = 0, MANUAL }; int matrix_state = MANUAL; // csak mert math.ht nemszabad ;-/ # define M_PI 3.14159265358979323846 const Vector* points[2][7]; Matrix* transs[4]; void onInitialization( ) { points[0][0] = new Vector(160, 20, 0); points[0][1] = new Vector(250, 80, 0); points[0][2] = new Vector(270, 20, 0); points[0][3] = new Vector(360, 80, 0); points[0][4] = new Vector(390, 20, 0); points[0][5] = new Vector(470, 80, 0); points[0][6] = new Vector(490, 20, 0); points[1][0] = new Vector(160, 120, 0); points[1][1] = new Vector(250, 180, 0); points[1][2] = new Vector(270, 120, 0); points[1][3] = new Vector(360, 180, 0); points[1][4] = new Vector(390, 120, 0); points[1][5] = new Vector(470, 180, 0); points[1][6] = new Vector(490, 120, 0); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * 0 0 0 1 */ transs[NOOP] = new Matrix(); transs[NOOP]->LoadIdentify(); transs[NOOP]->Dump(); /* * 0.5 0 0 0 * 0 0.5 0 0 * 0 0 0.5 0 * 0 0 0 1 */ transs[SCALE] = new Matrix(); transs[SCALE]->LoadIdentify(); transs[SCALE]->m[0] = 0.5; transs[SCALE]->m[5] = 0.5; transs[SCALE]->m[10] = 0.5; transs[SCALE]->Dump(); /* * cos sin 0 0 * -sin cos 0 0 * 0 0 1 0 * 0 0 0 1 */ float angle = M_PI/4; transs[ROTATE] = new Matrix(); transs[ROTATE]->LoadIdentify(); transs[ROTATE]->m[0] = cosf(angle); transs[ROTATE]->m[1] = -sinf(angle); transs[ROTATE]->m[4] = sinf(angle); transs[ROTATE]->m[5] = cosf(angle); transs[ROTATE]->Dump(); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * px py pz 1 */ transs[SHIFT] = new Matrix(); transs[SHIFT]->LoadIdentify(); transs[SHIFT]->m[7] = 100; transs[SHIFT]->Dump(); } void onDisplay( ) { glClearColor(0.1f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor4d(0.9f, 0.8f, 0.7f, 1.0f); glMatrixMode(GL_PROJECTION); if (matrix_state == MANUAL) { glLoadIdentity(); } else { glLoadMatrixf(transs[trans_state]->GetArray()); } gluOrtho2D(0., 600., 0., 600.); for (int i = 0; i < ARRAY_SIZE(points); i++) { glBegin(GL_LINE_STRIP); for (int j = 0; j < ARRAY_SIZE(points[i]); j++) { if (matrix_state == MANUAL) { Vector v = *transs[trans_state] * *points[i][j]; glVertex2d(v.x, v.y); } else { Vector v = *points[i][j]; glVertex2d(v.x, v.y); } } glEnd(); } // Buffercsere: rajzolas vege glFinish(); glutSwapBuffers(); } void onMouse(int button, int state, int x, int y) { // A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON // ill. a GLUT_DOWN / GLUT_UP makrokat hasznald. } void onIdle( ) { } void onKeyboard(unsigned char key, int x, int y) { if (key != 's' && key != 'S') return; if (key == 's') matrix_state = MANUAL; else matrix_state = OPENGL; trans_state = (trans_state + 1) % 4; onDisplay(); } // ...Idaig modosithatod //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(600, 600); glutInitWindowPosition(100, 100); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow("Grafika hazi feladat"); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); onInitialization(); glutDisplayFunc(onDisplay); glutMouseFunc(onMouse); glutIdleFunc(onIdle); glutKeyboardFunc(onKeyboard); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>/* * 17 - Check armstrong number / #include <iostream> using namespace std; int main() { int n,temp,r,result = 0; cin>>n; temp = n; while(temp) { r = temp%10; result += r*r*r; temp /= 10; } if(result == n) cout<<"Armstrong number"<<endl; else cout<<"not an Armstrong number"<<endl; return 0; } <commit_msg>Update Armstrong.cpp<commit_after>/* * 17 - Check armstrong number */ #include <iostream> using namespace std; int main() { int n,temp,r,result = 0; cin>>n; temp = n; while(temp) { r = temp%10; result += r*r*r; temp /= 10; } if(result == n) cout<<"Armstrong number"<<endl; else cout<<"not an Armstrong number"<<endl; return 0; } <|endoftext|>
<commit_before>#ifndef RAZORTASK_CPP #define RAZORTASK_CPP /** * @file razortask.cpp * @brief implements the class Razortask * @author Christopher "VdoP" Regali */ #include "razortask.h" #include "razorbartask.h" #include "razor.h" RazorPlugin* init(RazorBar* panel, QWidget* parent, const QString & name) { RazorTaskManager * ret = new RazorTaskManager(panel, parent, name); Q_ASSERT(ret); return ret; } /** * @brief constructor */ RazorTask::RazorTask(Window _id, int _screen) { client=_id; onScreen = _screen; hasIcon = false; qDebug() << "getting name"; title=Razor::getInstance().get_Xfitman()->getName(client); qDebug() << "getting icon"; if (Razor::getInstance().get_Xfitman()->getClientIcon(client,clientIcon)) hasIcon = true; qDebug() << "getting desktop"; desktop=Razor::getInstance().get_Xfitman()->getWindowDesktop(_id); qDebug() << "getting hidden"; hidden=Razor::getInstance().get_Xfitman()->isHidden(_id); } /** * @brief returns the task-title */ QString RazorTask::getTitle() { title = Razor::getInstance().get_Xfitman()->getName(client); return title; } /** * @brief raises the window */ void RazorTask::raiseMe() { Razor::getInstance().get_Xfitman()->raiseWindow(client); } /** * @brief requests Xfitman to toggle minimalize-flag for this tasks window! */ void RazorTask::toogleMin() { hidden = Razor::getInstance().get_Xfitman()->isHidden(client); qDebug() << "Razortask::toggleMin, hidden:" << hidden; Razor::getInstance().get_Xfitman()->setClientStateFlag(client,"net_wm_state_hidden",2); hidden = !hidden; qDebug() << "Razortask::toggleMin, hidden:" << hidden; if (!hidden) Razor::getInstance().get_Xfitman()->raiseWindow(client); } /** * @brief returns if the window has hiddenflag turned on */ bool RazorTask::isHidden() { hidden = Razor::getInstance().get_Xfitman()->isHidden(client); return hidden; } /** * @brief returns true if task has inputfocus */ bool RazorTask::isActive() { return (Razor::getInstance().get_Xfitman()->getActiveAppWindow()==client); } /** * @brief requests Xfitman to set the window to fullscreen (UNTESTED!) */ void RazorTask::setFullscreen() { //first remove hidden-flag so make us visible / unminimize Razor::getInstance().get_Xfitman()->setClientStateFlag(client,"net_wm_state_hidden",0); //then add the fullscreen-flag Razor::getInstance().get_Xfitman()->setClientStateFlag(client,"net_wm_state_fullscreen",1); } /** * @brief destructor */ RazorTask::~RazorTask() { } /** * @brief gets the client icon, if we have one! */ bool RazorTask::getIcon(QPixmap& _pixm) { qDebug() << "Has this client an Icon?" << hasIcon << title; if (hasIcon) _pixm = clientIcon; return hasIcon; } /** * @brief handles the X events and sets client - gui states */ bool RazorTaskManager::handleEvent(XEvent* _event) { //destroy or create windows? thats whats interesting.. we dont care about the rest! //so we just fetch "propertynotify" events if (_event->type == PropertyNotify) updateMap(); return false; } /** * @brief constructor */ RazorTaskManager::RazorTaskManager(RazorBar * panel, QWidget * parent, const QString & name) : RazorPlugin(panel, parent, name) { qDebug() << "Razortaskmanager init"; //now we setup our gui element gui = new RazorBarTask(this, panel); mainLayout()->addWidget(gui); //now we need an updated map for the clients running //updateMap(); qDebug() << "Razortaskmanager updateMap done"; //now we add our taskbar to the panel // it's aligned to left and it should occypy all free space // in the panel. // TODO: it doesn't work with sizeHints and with the stretch =1 too... // Razor::getInstance().get_gui()->addWidget(gui,_bar, 1, Qt::AlignLeft); qDebug() << "Razortaskmanager added widget"; //we need the events so we can process the tasks correctly Razor::getInstance().get_events()->registerCallback(this); qDebug() << "Razortaskmanager callback registered"; } /** * @brief updates our clientmap */ void RazorTaskManager::updateMap() { QList<Window>* tmp = Razor::getInstance().get_Xfitman()->getClientlist(); //first we need to get rid of tasks that got closed QMapIterator<Window,RazorTask*> iter(clientList); while (iter.hasNext()) { iter.next(); if (!tmp->contains(iter.key())) { // qDebug() << "DELTHIS!"; //get the pointer RazorTask* deltask = iter.value(); //remove the link from the list clientList.remove(iter.key()); //free the heap delete deltask; } } //now we got the window-ids and we got the count so we get through all of them for (int i = 0; i < tmp->count(); i++) { //add new clients to the list making new entries for the new windows if (!clientList.contains(tmp->at(i)) && Razor::getInstance().get_Xfitman()->acceptWindow(tmp->at(i))) { RazorTask* rtask = new RazorTask(tmp->at(i),Razor::getInstance().get_Xfitman()->getWindowDesktop(tmp->at(i))); qDebug() << "title: " <<rtask->getTitle(); clientList[tmp->at(i)]=rtask; } } delete tmp; //then update the stuff in our gui gui->updateTasks(&clientList); gui->updateFocus(); } int RazorTaskManager::widthForHeight(int h) { return gui->width(); } int RazorTaskManager::heightForWidth(int w) { return gui->height(); } RazorPlugin::RazorPluginSizing RazorTaskManager::sizePriority() { return RazorPlugin::Expanding; } /** * @brief destructor */ RazorTaskManager::~RazorTaskManager() { for (int i = 0; i < clientList.values().count(); i++) delete clientList.values().at(i); } #endif <commit_msg>forgotten refactored getClientList<commit_after>#ifndef RAZORTASK_CPP #define RAZORTASK_CPP /** * @file razortask.cpp * @brief implements the class Razortask * @author Christopher "VdoP" Regali */ #include "razortask.h" #include "razorbartask.h" #include "razor.h" RazorPlugin* init(RazorBar* panel, QWidget* parent, const QString & name) { RazorTaskManager * ret = new RazorTaskManager(panel, parent, name); Q_ASSERT(ret); return ret; } /** * @brief constructor */ RazorTask::RazorTask(Window _id, int _screen) { client=_id; onScreen = _screen; hasIcon = false; qDebug() << "getting name"; title=Razor::getInstance().get_Xfitman()->getName(client); qDebug() << "getting icon"; if (Razor::getInstance().get_Xfitman()->getClientIcon(client,clientIcon)) hasIcon = true; qDebug() << "getting desktop"; desktop=Razor::getInstance().get_Xfitman()->getWindowDesktop(_id); qDebug() << "getting hidden"; hidden=Razor::getInstance().get_Xfitman()->isHidden(_id); } /** * @brief returns the task-title */ QString RazorTask::getTitle() { title = Razor::getInstance().get_Xfitman()->getName(client); return title; } /** * @brief raises the window */ void RazorTask::raiseMe() { Razor::getInstance().get_Xfitman()->raiseWindow(client); } /** * @brief requests Xfitman to toggle minimalize-flag for this tasks window! */ void RazorTask::toogleMin() { hidden = Razor::getInstance().get_Xfitman()->isHidden(client); qDebug() << "Razortask::toggleMin, hidden:" << hidden; Razor::getInstance().get_Xfitman()->setClientStateFlag(client,"net_wm_state_hidden",2); hidden = !hidden; qDebug() << "Razortask::toggleMin, hidden:" << hidden; if (!hidden) Razor::getInstance().get_Xfitman()->raiseWindow(client); } /** * @brief returns if the window has hiddenflag turned on */ bool RazorTask::isHidden() { hidden = Razor::getInstance().get_Xfitman()->isHidden(client); return hidden; } /** * @brief returns true if task has inputfocus */ bool RazorTask::isActive() { return (Razor::getInstance().get_Xfitman()->getActiveAppWindow()==client); } /** * @brief requests Xfitman to set the window to fullscreen (UNTESTED!) */ void RazorTask::setFullscreen() { //first remove hidden-flag so make us visible / unminimize Razor::getInstance().get_Xfitman()->setClientStateFlag(client,"net_wm_state_hidden",0); //then add the fullscreen-flag Razor::getInstance().get_Xfitman()->setClientStateFlag(client,"net_wm_state_fullscreen",1); } /** * @brief destructor */ RazorTask::~RazorTask() { } /** * @brief gets the client icon, if we have one! */ bool RazorTask::getIcon(QPixmap& _pixm) { qDebug() << "Has this client an Icon?" << hasIcon << title; if (hasIcon) _pixm = clientIcon; return hasIcon; } /** * @brief handles the X events and sets client - gui states */ bool RazorTaskManager::handleEvent(XEvent* _event) { //destroy or create windows? thats whats interesting.. we dont care about the rest! //so we just fetch "propertynotify" events if (_event->type == PropertyNotify) updateMap(); return false; } /** * @brief constructor */ RazorTaskManager::RazorTaskManager(RazorBar * panel, QWidget * parent, const QString & name) : RazorPlugin(panel, parent, name) { qDebug() << "Razortaskmanager init"; //now we setup our gui element gui = new RazorBarTask(this, panel); mainLayout()->addWidget(gui); //now we need an updated map for the clients running //updateMap(); qDebug() << "Razortaskmanager updateMap done"; //now we add our taskbar to the panel // it's aligned to left and it should occypy all free space // in the panel. // TODO: it doesn't work with sizeHints and with the stretch =1 too... // Razor::getInstance().get_gui()->addWidget(gui,_bar, 1, Qt::AlignLeft); qDebug() << "Razortaskmanager added widget"; //we need the events so we can process the tasks correctly Razor::getInstance().get_events()->registerCallback(this); qDebug() << "Razortaskmanager callback registered"; } /** * @brief updates our clientmap */ void RazorTaskManager::updateMap() { QList<Window> tmp = Razor::getInstance().get_Xfitman()->getClientList(); //first we need to get rid of tasks that got closed QMapIterator<Window,RazorTask*> iter(clientList); while (iter.hasNext()) { iter.next(); if (!tmp.contains(iter.key())) { // qDebug() << "DELTHIS!"; //get the pointer RazorTask* deltask = iter.value(); //remove the link from the list clientList.remove(iter.key()); //free the heap delete deltask; } } //now we got the window-ids and we got the count so we get through all of them for (int i = 0; i < tmp.count(); i++) { //add new clients to the list making new entries for the new windows if (!clientList.contains(tmp.at(i)) && Razor::getInstance().get_Xfitman()->acceptWindow(tmp.at(i))) { RazorTask* rtask = new RazorTask(tmp.at(i),Razor::getInstance().get_Xfitman()->getWindowDesktop(tmp.at(i))); qDebug() << "title: " <<rtask->getTitle(); clientList[tmp.at(i)]=rtask; } } //then update the stuff in our gui gui->updateTasks(&clientList); gui->updateFocus(); } int RazorTaskManager::widthForHeight(int h) { return gui->width(); } int RazorTaskManager::heightForWidth(int w) { return gui->height(); } RazorPlugin::RazorPluginSizing RazorTaskManager::sizePriority() { return RazorPlugin::Expanding; } /** * @brief destructor */ RazorTaskManager::~RazorTaskManager() { for (int i = 0; i < clientList.values().count(); i++) delete clientList.values().at(i); } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <fcntl.h> #include <sys/ioctl.h> #include <unistd.h> #include <boost/make_shared.hpp> #include <gtest/gtest.h> #include <osquery/dispatcher.h> #include "osquery/events/kernel.h" namespace osquery { class KernelCommunicationTests : public testing::Test { void TearDown() override { Dispatcher::stopServices(); Dispatcher::joinServices(); } }; #ifdef KERNEL_TEST class KernelProducerRunnable : public InternalRunnable { public: explicit KernelProducerRunnable(unsigned int events_to_produce, unsigned int event_type) : events_to_produce_(events_to_produce), event_type_(event_type) {} virtual void start() { int fd = open(kKernelDevice.c_str(), O_RDWR); if (fd >= 0) { for (unsigned int i = 0; i < events_to_produce_; i++) { ioctl(fd, OSQUERY_IOCTL_TEST, &event_type_); } close(fd); } } private: unsigned int events_to_produce_; unsigned int event_type_; }; TEST_F(KernelCommunicationTests, test_communication) { unsigned int num_threads = 20; unsigned int events_per_thread = 100000; unsigned int drops = 0; unsigned int reads = 0; CQueue queue(kKernelDevice, 8 * (1 << 20)); auto& dispatcher = Dispatcher::instance(); for (unsigned int c = 0; c < num_threads; ++c) { dispatcher.addService( std::make_shared<KernelProducerRunnable>(events_per_thread, c % 2)); } osquery_event_t event; osquery::CQueue::event* event_buf = nullptr; unsigned int tasks = 0; do { tasks = dispatcher.serviceCount(); drops += queue.kernelSync(OSQUERY_OPTIONS_NO_BLOCK); unsigned int max_before_sync = 2000; while (max_before_sync > 0 && (event = queue.dequeue(&event_buf))) { switch (event) { case OSQUERY_TEST_EVENT_0: case OSQUERY_TEST_EVENT_1: reads++; break; default: throw std::runtime_error("Uh oh. Unknown event."); } max_before_sync--; } } while (tasks > 0); EXPECT_EQ(num_threads * events_per_thread, reads + drops); } #endif // KERNEL_TEST } <commit_msg>Allow the non-blocking kernel-test publisher to drop 5% (#2336)<commit_after>/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <fcntl.h> #include <sys/ioctl.h> #include <unistd.h> #include <boost/make_shared.hpp> #include <gtest/gtest.h> #include <osquery/dispatcher.h> #include "osquery/events/kernel.h" namespace osquery { class KernelCommunicationTests : public testing::Test { void TearDown() override { Dispatcher::stopServices(); Dispatcher::joinServices(); } }; #ifdef KERNEL_TEST class KernelProducerRunnable : public InternalRunnable { public: explicit KernelProducerRunnable(unsigned int events_to_produce, unsigned int event_type) : events_to_produce_(events_to_produce), event_type_(event_type) {} virtual void start() { int fd = open(kKernelDevice.c_str(), O_RDWR); if (fd >= 0) { for (unsigned int i = 0; i < events_to_produce_; i++) { ioctl(fd, OSQUERY_IOCTL_TEST, &event_type_); } close(fd); } } private: unsigned int events_to_produce_; unsigned int event_type_; }; TEST_F(KernelCommunicationTests, test_communication) { unsigned int num_threads = 20; unsigned int events_per_thread = 100000; unsigned int drops = 0; unsigned int reads = 0; CQueue queue(kKernelDevice, 8 * (1 << 20)); auto& dispatcher = Dispatcher::instance(); for (unsigned int c = 0; c < num_threads; ++c) { dispatcher.addService( std::make_shared<KernelProducerRunnable>(events_per_thread, c % 2)); } osquery_event_t event; osquery::CQueue::event* event_buf = nullptr; unsigned int tasks = 0; do { tasks = dispatcher.serviceCount(); drops += queue.kernelSync(OSQUERY_OPTIONS_NO_BLOCK); unsigned int max_before_sync = 2000; while (max_before_sync > 0 && (event = queue.dequeue(&event_buf))) { switch (event) { case OSQUERY_TEST_EVENT_0: case OSQUERY_TEST_EVENT_1: reads++; break; default: throw std::runtime_error("Uh oh. Unknown event."); } max_before_sync--; } } while (tasks > 0); auto total_events = reads + drops; auto expected_events = num_threads * events_per_thread; // Since the sync is opened non-blocking we allow a 5% drop rate. EXPECT_GT(total_events, expected_events * 0.95); EXPECT_LE(total_events, expected_events); } #endif // KERNEL_TEST } <|endoftext|>
<commit_before>#include <iostream> #include <cstring> #include <cmath> using namespace std; int main() { int n; cin>>n; bool (*a) = new bool[n+1]; memset(a,true,sizeof(bool)*(n+1)); for (int i = 2; i <= sqrt(n); i++) if (a[i]) for (int j = i; j*i <= n; j++) a[j*i] = false; int (*p) = new int[n];int countp = 0; for (int k = 2; k <= n; k++) if (a[k]) {p[countp] = k;countp++;} int countn = 0; for(int l = 0; l < countp; l++) if(p[l+1] - p[l] == 2) countn++; cout<<countn<<endl; delete [] a;delete [] p; } <commit_msg>Clean up.<commit_after>#include <iostream> #include <cstring> #include <cmath> using namespace std; int main() { int n; cin>>n; bool (*a) = new bool[n+1]; memset(a,true,sizeof(bool)*(n+1)); for (int i = 2; i <= sqrt(n); i++) if (a[i]) for(int j = i; j*i <= n; j++) a[j*i] = false; int first = 0;int last = 0;int countn = 0; for(int i = 2; i < n + 1; i++) { if(a[i]) { if(!first) first = i; else { if(last) first = last; last = i; if(last - first == 2) countn++; } } } cout<<countn<<endl; delete [] a; } <|endoftext|>
<commit_before>#include <iostream> #include <limits> #include <string> using namespace std; int main() { string answer,temp;int n,countn; cin>>answer>>n; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); countn = 0; for(;(getline(cin,temp)) && (temp != "#");) { countn++; if(countn < n) { if(temp == answer) { cout<<"Welcome in"<<endl; break; } else { cout<<"Wrong password: "<<temp<<endl; continue; } } else if(countn = n) { if(temp == answer) { cout<<"Welcome in"<<endl; break; } else { cout<<"Wrong password: "<<temp<<endl<<"Account locked"<<endl; break; } } else break; } } <commit_msg>Update 1067.cpp<commit_after>#include <iostream> #include <limits> #include <string> using namespace std; int main() { string answer,temp;int n,countn; cin>>answer>>n; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); countn = 0; for(;(getline(cin,temp)) && (temp != "#");) { countn++; if(countn < n) { if(temp == answer) { cout<<"Welcome in"<<endl; break; } else { cout<<"Wrong password: "<<temp<<endl; continue; } } else if(countn == n) { if(temp == answer) { cout<<"Welcome in"<<endl; break; } else { cout<<"Wrong password: "<<temp<<endl<<"Account locked"<<endl; break; } } else break; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: GradientRecursiveGaussianImageFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // This example illustrates the use of the \doxygen{GradientRecursiveGaussianImageFilter}. // // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter} // // Software Guide : EndLatex #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" // Software Guide : BeginLatex // // The first step required to use this filter is to include its header // file. // // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter!header} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkGradientRecursiveGaussianImageFilter.h" // Software Guide : EndCodeSnippet int main( int argc, char * argv[] ) { if( argc < 4 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImageFile outputVectorImageFile sigma" << std::endl; return 1; } // Software Guide : BeginLatex // // Types should be instantiated based on the pixels of the input and // output images. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef float InputPixelType; typedef float OutputComponentPixelType; typedef itk::CovariantVector< OutputComponentPixelType > OutputPixelType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // With them, the input and output image types can be instantiated. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::Image< InputPixelType, 3 > InputImageType; typedef itk::Image< OutputPixelType, 3 > OutputImageType; // Software Guide : EndCodeSnippet typedef itk::ImageFileReader< InputImageType > ReaderType; // Software Guide : BeginLatex // // The filter type is now instantiated using both the input image and the // output image types. // // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter!Instantiation} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::GradientRecursiveGaussianImageFilter< InputImageType, OutputImageType > FilterType; // Software Guide : EndCodeSnippet ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); // Software Guide : BeginLatex // // A filter object is created by invoking the \code{New()} method and // assigning the result to a \doxygen{SmartPointer}. // // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter!New()} // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter!Pointer} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet FilterType::Pointer filter = FilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The input image can be obtained from the output of another filter. Here, // an image reader is used as source. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetInput( reader->GetOutput() ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The standard deviation of the Gaussian smoothing kernel is now set. // // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter!SetSigma()} // \index{SetSigma()!itk::Gradient\-Recursive\-Gaussian\-Image\-Filter} // // Software Guide : EndLatex const double sigma = atof( argv[3] ); // Software Guide : BeginCodeSnippet filter->SetSigma( sigma ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finally the filter is executed by invoking the \code{Update()} method. // // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter!Update()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // If connected to other filters in a pipeline, this filter will // automatically update when any downstream filters are updated. For // example, we may connect this gradient magnitude filter to an image file // writer and then update the writer. // // Software Guide : EndLatex typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); // Software Guide : BeginCodeSnippet writer->SetInput( filter->GetOutput() ); writer->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // // // Software Guide : EndLatex return 0; } <commit_msg>FIX: Unused include for RescaleIntensityImageFilter was removed.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: GradientRecursiveGaussianImageFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // This example illustrates the use of the \doxygen{GradientRecursiveGaussianImageFilter}. // // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter} // // Software Guide : EndLatex #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" // Software Guide : BeginLatex // // The first step required to use this filter is to include its header // file. // // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter!header} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkGradientRecursiveGaussianImageFilter.h" // Software Guide : EndCodeSnippet int main( int argc, char * argv[] ) { if( argc < 4 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImageFile outputVectorImageFile sigma" << std::endl; return 1; } // Software Guide : BeginLatex // // Types should be instantiated based on the pixels of the input and // output images. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef float InputPixelType; typedef float OutputComponentPixelType; typedef itk::CovariantVector< OutputComponentPixelType > OutputPixelType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // With them, the input and output image types can be instantiated. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::Image< InputPixelType, 3 > InputImageType; typedef itk::Image< OutputPixelType, 3 > OutputImageType; // Software Guide : EndCodeSnippet typedef itk::ImageFileReader< InputImageType > ReaderType; // Software Guide : BeginLatex // // The filter type is now instantiated using both the input image and the // output image types. // // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter!Instantiation} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::GradientRecursiveGaussianImageFilter< InputImageType, OutputImageType > FilterType; // Software Guide : EndCodeSnippet ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); // Software Guide : BeginLatex // // A filter object is created by invoking the \code{New()} method and // assigning the result to a \doxygen{SmartPointer}. // // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter!New()} // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter!Pointer} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet FilterType::Pointer filter = FilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The input image can be obtained from the output of another filter. Here, // an image reader is used as source. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetInput( reader->GetOutput() ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The standard deviation of the Gaussian smoothing kernel is now set. // // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter!SetSigma()} // \index{SetSigma()!itk::Gradient\-Recursive\-Gaussian\-Image\-Filter} // // Software Guide : EndLatex const double sigma = atof( argv[3] ); // Software Guide : BeginCodeSnippet filter->SetSigma( sigma ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finally the filter is executed by invoking the \code{Update()} method. // // \index{itk::Gradient\-Recursive\-Gaussian\-Image\-Filter!Update()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // If connected to other filters in a pipeline, this filter will // automatically update when any downstream filters are updated. For // example, we may connect this gradient magnitude filter to an image file // writer and then update the writer. // // Software Guide : EndLatex typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); // Software Guide : BeginCodeSnippet writer->SetInput( filter->GetOutput() ); writer->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // // // Software Guide : EndLatex return 0; } <|endoftext|>
<commit_before>#include "behaviour_xsensfollowing.h" #include <QtGui> #include <Behaviour_XsensFollowing/xsensfollowingform.h> #include <Framework/Angles.h> Behaviour_XsensFollowing::Behaviour_XsensFollowing(QString id, Module_ThrusterControlLoop *tcl, Module_XsensMTi *xsens) : RobotBehaviour(id) { this->xsens = xsens; this->tcl = tcl; turnTimer.moveToThread(this); timer.moveToThread(this); this->setDefaultValue("timer",30); this->setDefaultValue("driveTime",10000); this->setDefaultValue("ffSpeed",0.3); this->setDefaultValue("kp",0.3); this->setDefaultValue("delta",0.3); } bool Behaviour_XsensFollowing::isActive() { return isEnabled(); } void Behaviour_XsensFollowing::init() { logger->info("Xsens Following init"); setEnabled(false); connect(this,SIGNAL(newAngularSpeed(float)),tcl,SLOT(setAngularSpeed(float))); connect(this,SIGNAL(newForwardSpeed(float)),tcl,SLOT(setForwardSpeed(float))); connect(&timer,SIGNAL(timeout()),this,SLOT(controlLoop())); connect(&turnTimer,SIGNAL(timeout()),this,SLOT(turnNinety())); connect(this, SIGNAL(enabled(bool)), this, SLOT(controlEnabledChanged(bool))); } void Behaviour_XsensFollowing::startBehaviour() { if (this->isEnabled() == true){ logger->info("Already enabled/started!"); return; } logger->info("Starting Xsens Following"); this->setEnabled(true); initialHeading = xsens->getHeading(); ctrAngle = initialHeading; emit dataChanged(this); timer.start(getSettingsValue("timer").toInt()); turnTimer.start(getSettingsValue("driveTime").toInt()); } void Behaviour_XsensFollowing::stop() { if(timer.isActive()){ timer.stop(); } if(turnTimer.isActive()){ turnTimer.stop(); } if (!isEnabled()) { return; } logger->info("Xsens follow stop"); this->setEnabled(false); setEnabled(false); emit newAngularSpeed(0.0); emit newForwardSpeed(0.0); logger->info("Stop Xsens Following"); emit finished(this,true); } void Behaviour_XsensFollowing::reset() { logger->info("Xsens follow reset"); if (this->isEnabled() == false){ logger->info("Not enabled!"); return; } timer.stop(); turnTimer.stop(); emit newAngularSpeed(0.0); emit newForwardSpeed(0.0); RobotModule::reset(); if(xsens->isEnabled()){ if(xsens->getHealthStatus().isHealthOk()){ initialHeading = xsens->getHeading(); ctrAngle = initialHeading; emit dataChanged(this); this->setHealthToOk(); timer.start(getSettingsValue("timer").toInt()); turnTimer.start(getSettingsValue("driveTime").toInt()); }else{ this->stopOnXsensError(); } }else{ this->stop(); } } void Behaviour_XsensFollowing::controlLoop() { if (this->isEnabled() == false){ logger->info("not enabled - controlloop"); this->stop(); return; } if(!xsens->isEnabled() || !xsens->getHealthStatus().isHealthOk()) { this->stopOnXsensError(); return; } float curHeading = xsens->getHeading(); float curDelta = fabs(ctrAngle - curHeading); float ctrAngleSpeed = 0.0; float faktor = 1.0; if(ctrAngle-curHeading < 0) faktor = -1.0; if(curDelta > getSettingsValue("delta").toFloat()) { ctrAngleSpeed = getSettingsValue("kp").toFloat()* faktor * curHeading / ctrAngle; } addData("angularSpeed",ctrAngleSpeed); addData("current heading",curHeading); addData("ctrAngle", ctrAngle); emit dataChanged(this); emit newAngularSpeed(ctrAngleSpeed); emit newForwardSpeed(getSettingsValue("ffSpeed").toFloat()); } void Behaviour_XsensFollowing::turnNinety() { if (this->isEnabled() == false){ logger->info("not enabled - 90"); this->stop(); return; } if(getSettingsValue("enableTurn").toBool() == true){ float newHeading = ctrAngle; if(getSettingsValue("turnClockwise").toBool() == true){ newHeading = newHeading + 90.0; ctrAngle = Angles::deg2deg(newHeading); } else { newHeading = newHeading - 90.0; ctrAngle = Angles::deg2deg(newHeading); } } } void Behaviour_XsensFollowing::refreshHeading() { //logger->debug("Xsens follow refresh heading"); if (this->isEnabled() == false){ logger->info("Not enabled!"); return; } if(xsens->isEnabled()){ this->dataLockerMutex.lock(); initialHeading = this->xsens->getHeading(); logger->debug( "initial heading set to %fΒ°", initialHeading ); addData("initial_heading", initialHeading); dataChanged( this ); this->dataLockerMutex.unlock(); } } void Behaviour_XsensFollowing::stopOnXsensError() { if (!isEnabled()) { return; } logger->info("Xsens follow stop error"); this->setEnabled(false); timer.stop(); turnTimer.stop(); setHealthToSick("xsens error"); setEnabled(false); emit newAngularSpeed(0.0); emit newForwardSpeed(0.0); emit finished(this,false); } QList<RobotModule*> Behaviour_XsensFollowing::getDependencies() { QList<RobotModule*> ret; ret.append(tcl); ret.append(xsens); return ret; } QWidget* Behaviour_XsensFollowing::createView(QWidget* parent) { return new XsensFollowingForm(parent, this); } void Behaviour_XsensFollowing::controlEnabledChanged(bool b){ if(b == false){ logger->info("No longer enabled!"); QTimer::singleShot(0, this, SLOT(stop())); } } <commit_msg>xsensfollow - use Angles^2<commit_after>#include "behaviour_xsensfollowing.h" #include <QtGui> #include <Behaviour_XsensFollowing/xsensfollowingform.h> #include <Framework/Angles.h> Behaviour_XsensFollowing::Behaviour_XsensFollowing(QString id, Module_ThrusterControlLoop *tcl, Module_XsensMTi *xsens) : RobotBehaviour(id) { this->xsens = xsens; this->tcl = tcl; turnTimer.moveToThread(this); timer.moveToThread(this); this->setDefaultValue("timer",30); this->setDefaultValue("driveTime",10000); this->setDefaultValue("ffSpeed",0.3); this->setDefaultValue("kp",0.3); this->setDefaultValue("delta",0.3); } bool Behaviour_XsensFollowing::isActive() { return isEnabled(); } void Behaviour_XsensFollowing::init() { logger->info("Xsens Following init"); setEnabled(false); connect(this,SIGNAL(newAngularSpeed(float)),tcl,SLOT(setAngularSpeed(float))); connect(this,SIGNAL(newForwardSpeed(float)),tcl,SLOT(setForwardSpeed(float))); connect(&timer,SIGNAL(timeout()),this,SLOT(controlLoop())); connect(&turnTimer,SIGNAL(timeout()),this,SLOT(turnNinety())); connect(this, SIGNAL(enabled(bool)), this, SLOT(controlEnabledChanged(bool))); } void Behaviour_XsensFollowing::startBehaviour() { if (this->isEnabled() == true){ logger->info("Already enabled/started!"); return; } logger->info("Starting Xsens Following"); this->setEnabled(true); initialHeading = xsens->getHeading(); ctrAngle = initialHeading; emit dataChanged(this); timer.start(getSettingsValue("timer").toInt()); turnTimer.start(getSettingsValue("driveTime").toInt()); } void Behaviour_XsensFollowing::stop() { if(timer.isActive()){ timer.stop(); } if(turnTimer.isActive()){ turnTimer.stop(); } if (!isEnabled()) { return; } logger->info("Xsens follow stop"); this->setEnabled(false); setEnabled(false); emit newAngularSpeed(0.0); emit newForwardSpeed(0.0); logger->info("Stop Xsens Following"); emit finished(this,true); } void Behaviour_XsensFollowing::reset() { logger->info("Xsens follow reset"); if (this->isEnabled() == false){ logger->info("Not enabled!"); return; } timer.stop(); turnTimer.stop(); emit newAngularSpeed(0.0); emit newForwardSpeed(0.0); RobotModule::reset(); if(xsens->isEnabled()){ if(xsens->getHealthStatus().isHealthOk()){ initialHeading = xsens->getHeading(); ctrAngle = initialHeading; emit dataChanged(this); this->setHealthToOk(); timer.start(getSettingsValue("timer").toInt()); turnTimer.start(getSettingsValue("driveTime").toInt()); }else{ this->stopOnXsensError(); } }else{ this->stop(); } } void Behaviour_XsensFollowing::controlLoop() { if (this->isEnabled() == false){ logger->info("not enabled - controlloop"); this->stop(); return; } if(!xsens->isEnabled() || !xsens->getHealthStatus().isHealthOk()) { this->stopOnXsensError(); return; } float curHeading = xsens->getHeading(); float curDelta = Angles::deg2deg(ctrAngle - curHeading); float ctrAngleSpeed = 0.0; float faktor = 1.0; if(ctrAngle-curHeading < 0) faktor = -1.0; if(curDelta > getSettingsValue("delta").toFloat()) { ctrAngleSpeed = getSettingsValue("kp").toFloat()* faktor * curHeading / ctrAngle; } addData("angularSpeed",ctrAngleSpeed); addData("current heading",curHeading); addData("ctrAngle", ctrAngle); emit dataChanged(this); emit newAngularSpeed(ctrAngleSpeed); emit newForwardSpeed(getSettingsValue("ffSpeed").toFloat()); } void Behaviour_XsensFollowing::turnNinety() { if (this->isEnabled() == false){ logger->info("not enabled - 90"); this->stop(); return; } if(getSettingsValue("enableTurn").toBool() == true){ float newHeading = ctrAngle; if(getSettingsValue("turnClockwise").toBool() == true){ newHeading = newHeading + 90.0; ctrAngle = Angles::deg2deg(newHeading); } else { newHeading = newHeading - 90.0; ctrAngle = Angles::deg2deg(newHeading); } } } void Behaviour_XsensFollowing::refreshHeading() { //logger->debug("Xsens follow refresh heading"); if (this->isEnabled() == false){ logger->info("Not enabled!"); return; } if(xsens->isEnabled()){ this->dataLockerMutex.lock(); initialHeading = this->xsens->getHeading(); logger->debug( "initial heading set to %fΒ°", initialHeading ); addData("initial_heading", initialHeading); dataChanged( this ); this->dataLockerMutex.unlock(); } } void Behaviour_XsensFollowing::stopOnXsensError() { if (!isEnabled()) { return; } logger->info("Xsens follow stop error"); this->setEnabled(false); timer.stop(); turnTimer.stop(); setHealthToSick("xsens error"); setEnabled(false); emit newAngularSpeed(0.0); emit newForwardSpeed(0.0); emit finished(this,false); } QList<RobotModule*> Behaviour_XsensFollowing::getDependencies() { QList<RobotModule*> ret; ret.append(tcl); ret.append(xsens); return ret; } QWidget* Behaviour_XsensFollowing::createView(QWidget* parent) { return new XsensFollowingForm(parent, this); } void Behaviour_XsensFollowing::controlEnabledChanged(bool b){ if(b == false){ logger->info("No longer enabled!"); QTimer::singleShot(0, this, SLOT(stop())); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestRandomPContingencyStatisticsMPI.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /* * Copyright 2009 Sandia Corporation. * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive * license for use of this work by or on behalf of the * U.S. Government. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that this Notice and any * statement of authorship are reproduced on all copies. */ // .SECTION Thanks // Thanks to Philippe Pebay for implementing this test. #include <mpi.h> #include <time.h> #include "vtkContingencyStatistics.h" #include "vtkPContingencyStatistics.h" #include "vtkIntArray.h" #include "vtkMath.h" #include "vtkMPIController.h" #include "vtkMultiBlockDataSet.h" #include "vtkStdString.h" #include "vtkTable.h" #include "vtkVariantArray.h" // For debugging purposes, output results of serial engines ran on each slice of the distributed data set #define PRINT_ALL_SERIAL_STATS 0 struct RandomSampleStatisticsArgs { int nVals; int* retVal; int ioRank; int argc; char** argv; }; // This will be called by all processes void RandomSampleStatistics( vtkMultiProcessController* controller, void* arg ) { // Get test parameters RandomSampleStatisticsArgs* args = reinterpret_cast<RandomSampleStatisticsArgs*>( arg ); *(args->retVal) = 0; // Get MPI communicator vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() ); // Get local rank int myRank = com->GetLocalProcessId(); // Seed random number generator vtkMath::RandomSeed( static_cast<int>( time( NULL ) ) * ( myRank + 1 ) ); // Generate an input table that contains samples of mutually independent discrete random variables int nVariables = 2; vtkIntArray* intArray[2]; vtkStdString columnNames[] = { "Uniform 0", "Uniform 1" }; vtkTable* inputData = vtkTable::New(); // Discrete uniform samples for ( int c = 0; c < nVariables; ++ c ) { intArray[c] = vtkIntArray::New(); intArray[c]->SetNumberOfComponents( 1 ); intArray[c]->SetName( columnNames[c] ); int x; for ( int r = 0; r < args->nVals; ++ r ) { x = static_cast<int>( floor( vtkMath::Random() * 10. ) ) + 5; intArray[c]->InsertNextValue( x ); } inputData->AddColumn( intArray[c] ); intArray[c]->Delete(); } // ************************** Contingency Statistics ************************** // Synchronize and start clock com->Barrier(); time_t t0; time ( &t0 ); // Instantiate a parallel contingency statistics engine and set its ports vtkPContingencyStatistics* pcs = vtkPContingencyStatistics::New(); pcs->SetInput( 0, inputData ); vtkTable* outputData = pcs->GetOutput( 0 ); vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( pcs->GetOutputDataObject( 1 ) ); // Select column pairs (uniform vs. uniform, normal vs. normal) pcs->AddColumnPair( columnNames[0], columnNames[1] ); // Test (in parallel) with Learn, Derive, and Assess options turned on pcs->SetLearn( true ); pcs->SetDerive( true ); pcs->SetAssess( true ); pcs->Update(); // Synchronize and stop clock com->Barrier(); time_t t1; time ( &t1 ); if ( com->GetLocalProcessId() == args->ioRank ) { cout << "\n## Completed parallel calculation of contingency statistics (with assessment):\n" << " \n" << " Wall time: " << difftime( t1, t0 ) << " sec.\n"; // for ( unsigned int b = 0; b < outputMetaDS->GetNumberOfBlocks(); ++ b ) for ( unsigned int b = 0; b < 2; ++ b ) { vtkTable* outputMeta = vtkTable::SafeDownCast( outputMetaDS->GetBlock( b ) ); outputMeta->Dump(); } } com->Barrier(); outputData->Dump(); // Clean up pcs->Delete(); } //---------------------------------------------------------------------------- int main( int argc, char** argv ) { // **************************** MPI Initialization *************************** vtkMPIController* controller = vtkMPIController::New(); controller->Initialize( &argc, &argv ); // If an MPI controller was not created, terminate in error. if ( ! controller->IsA( "vtkMPIController" ) ) { vtkGenericWarningMacro("Failed to initialize a MPI controller."); controller->Delete(); return 1; } vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() ); // ************************** Find an I/O node ******************************** int* ioPtr; int ioRank; int flag; MPI_Attr_get( MPI_COMM_WORLD, MPI_IO, &ioPtr, &flag ); if ( ( ! flag ) || ( *ioPtr == MPI_PROC_NULL ) ) { // Getting MPI attributes did not return any I/O node found. ioRank = MPI_PROC_NULL; vtkGenericWarningMacro("No MPI I/O nodes found."); // As no I/O node was found, we need an unambiguous way to report the problem. // This is the only case when a testValue of -1 will be returned controller->Finalize(); controller->Delete(); return -1; } else { if ( *ioPtr == MPI_ANY_SOURCE ) { // Anyone can do the I/O trick--just pick node 0. ioRank = 0; } else { // Only some nodes can do I/O. Make sure everyone agrees on the choice (min). com->AllReduce( ioPtr, &ioRank, 1, vtkCommunicator::MIN_OP ); } } // ************************** Initialize test ********************************* if ( com->GetLocalProcessId() == ioRank ) { cout << "\n# Houston, this is process " << ioRank << " speaking. I'll be the I/O node.\n"; } // Check how many processes have been made available int numProcs = controller->GetNumberOfProcesses(); if ( controller->GetLocalProcessId() == ioRank ) { cout << "\n# Running test with " << numProcs << " processes...\n"; } // Parameters for regression test. int testValue = 0; RandomSampleStatisticsArgs args; args.nVals = 20; args.retVal = &testValue; args.ioRank = ioRank; args.argc = argc; args.argv = argv; // Execute the function named "process" on both processes controller->SetSingleMethod( RandomSampleStatistics, &args ); controller->SingleMethodExecute(); // Clean up and exit if ( com->GetLocalProcessId() == ioRank ) { cout << "\n# Test completed.\n\n"; } controller->Finalize(); controller->Delete(); return testValue; } <commit_msg>ENH: by default, use a bigger sample and are a wider distribution<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestRandomPContingencyStatisticsMPI.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /* * Copyright 2009 Sandia Corporation. * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive * license for use of this work by or on behalf of the * U.S. Government. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that this Notice and any * statement of authorship are reproduced on all copies. */ // .SECTION Thanks // Thanks to Philippe Pebay for implementing this test. #include <mpi.h> #include <time.h> #include "vtkContingencyStatistics.h" #include "vtkPContingencyStatistics.h" #include "vtkIntArray.h" #include "vtkMath.h" #include "vtkMPIController.h" #include "vtkMultiBlockDataSet.h" #include "vtkStdString.h" #include "vtkTable.h" #include "vtkVariantArray.h" // For debugging purposes, output results of serial engines ran on each slice of the distributed data set #define PRINT_ALL_SERIAL_STATS 0 struct RandomSampleStatisticsArgs { int nVals; int* retVal; int ioRank; int argc; char** argv; }; // This will be called by all processes void RandomSampleStatistics( vtkMultiProcessController* controller, void* arg ) { // Get test parameters RandomSampleStatisticsArgs* args = reinterpret_cast<RandomSampleStatisticsArgs*>( arg ); *(args->retVal) = 0; // Get MPI communicator vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() ); // Get local rank int myRank = com->GetLocalProcessId(); // Seed random number generator vtkMath::RandomSeed( static_cast<int>( time( NULL ) ) * ( myRank + 1 ) ); // Generate an input table that contains samples of mutually independent discrete random variables int nVariables = 2; vtkIntArray* intArray[2]; vtkStdString columnNames[] = { "Uniform 0", "Uniform 1" }; vtkTable* inputData = vtkTable::New(); // Discrete uniform samples for ( int c = 0; c < nVariables; ++ c ) { intArray[c] = vtkIntArray::New(); intArray[c]->SetNumberOfComponents( 1 ); intArray[c]->SetName( columnNames[c] ); int x; for ( int r = 0; r < args->nVals; ++ r ) { x = static_cast<int>( floor( vtkMath::Random() * 100. ) ) + 5; intArray[c]->InsertNextValue( x ); } inputData->AddColumn( intArray[c] ); intArray[c]->Delete(); } // ************************** Contingency Statistics ************************** // Synchronize and start clock com->Barrier(); time_t t0; time ( &t0 ); // Instantiate a parallel contingency statistics engine and set its ports vtkPContingencyStatistics* pcs = vtkPContingencyStatistics::New(); pcs->SetInput( 0, inputData ); vtkTable* outputData = pcs->GetOutput( 0 ); vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( pcs->GetOutputDataObject( 1 ) ); // Select column pairs (uniform vs. uniform, normal vs. normal) pcs->AddColumnPair( columnNames[0], columnNames[1] ); // Test (in parallel) with Learn, Derive, and Assess options turned on pcs->SetLearn( true ); pcs->SetDerive( true ); pcs->SetAssess( true ); pcs->Update(); // Synchronize and stop clock com->Barrier(); time_t t1; time ( &t1 ); if ( com->GetLocalProcessId() == args->ioRank ) { cout << "\n## Completed parallel calculation of contingency statistics (with assessment):\n" << " \n" << " Wall time: " << difftime( t1, t0 ) << " sec.\n"; // for ( unsigned int b = 0; b < outputMetaDS->GetNumberOfBlocks(); ++ b ) for ( unsigned int b = 0; b < 1; ++ b ) { vtkTable* outputMeta = vtkTable::SafeDownCast( outputMetaDS->GetBlock( b ) ); outputMeta->Dump(); } } // Clean up pcs->Delete(); } //---------------------------------------------------------------------------- int main( int argc, char** argv ) { // **************************** MPI Initialization *************************** vtkMPIController* controller = vtkMPIController::New(); controller->Initialize( &argc, &argv ); // If an MPI controller was not created, terminate in error. if ( ! controller->IsA( "vtkMPIController" ) ) { vtkGenericWarningMacro("Failed to initialize a MPI controller."); controller->Delete(); return 1; } vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() ); // ************************** Find an I/O node ******************************** int* ioPtr; int ioRank; int flag; MPI_Attr_get( MPI_COMM_WORLD, MPI_IO, &ioPtr, &flag ); if ( ( ! flag ) || ( *ioPtr == MPI_PROC_NULL ) ) { // Getting MPI attributes did not return any I/O node found. ioRank = MPI_PROC_NULL; vtkGenericWarningMacro("No MPI I/O nodes found."); // As no I/O node was found, we need an unambiguous way to report the problem. // This is the only case when a testValue of -1 will be returned controller->Finalize(); controller->Delete(); return -1; } else { if ( *ioPtr == MPI_ANY_SOURCE ) { // Anyone can do the I/O trick--just pick node 0. ioRank = 0; } else { // Only some nodes can do I/O. Make sure everyone agrees on the choice (min). com->AllReduce( ioPtr, &ioRank, 1, vtkCommunicator::MIN_OP ); } } // ************************** Initialize test ********************************* if ( com->GetLocalProcessId() == ioRank ) { cout << "\n# Houston, this is process " << ioRank << " speaking. I'll be the I/O node.\n"; } // Check how many processes have been made available int numProcs = controller->GetNumberOfProcesses(); if ( controller->GetLocalProcessId() == ioRank ) { cout << "\n# Running test with " << numProcs << " processes...\n"; } // Parameters for regression test. int testValue = 0; RandomSampleStatisticsArgs args; args.nVals = 200000; args.retVal = &testValue; args.ioRank = ioRank; args.argc = argc; args.argv = argv; // Execute the function named "process" on both processes controller->SetSingleMethod( RandomSampleStatistics, &args ); controller->SingleMethodExecute(); // Clean up and exit if ( com->GetLocalProcessId() == ioRank ) { cout << "\n# Test completed.\n\n"; } controller->Finalize(); controller->Delete(); return testValue; } <|endoftext|>
<commit_before>#pragma once #include <cmath> #include <iostream> const uint8_t POSIT_ROUND_DOWN = 0; const uint8_t POSIT_ROUND_TO_NEAREST = 1; /* class posit represents arbitrary configuration posits and their arithmetic */ template<size_t nbits> class quire : std::bitset<nbits> { public: quire<nbits>() {} quire<nbits>(const quire& q) { *this = q; } // template parameters need names different from class template parameters (for gcc and clang) template<size_t nnbits> friend std::ostream& operator<< (std::ostream& ostr, const quire<nnbits>& p); template<size_t nnbits> friend std::istream& operator>> (std::istream& istr, quire<nnbits>& p); template<size_t nnbits> friend bool operator==(const quire<nnbits>& lhs, const quire<nnbits>& rhs); template<size_t nnbits> friend bool operator!=(const quire<nnbits>& lhs, const quire<nnbits>& rhs); template<size_t nnbitss> friend bool operator< (const quire<nnbits>>& lhs, const quire<nnbits>& rhs); template<size_t nnbits> friend bool operator> (const quire<nnbits>>& lhs, const quire<nnbits>& rhs); template<size_t nnbits> friend bool operator<=(const quire<nnbits>>& lhs, const quire<nnbits>& rhs); template<size_t nnbits> friend bool operator>=(const quire<nnbits>& lhs, const quire<nnbits>>& rhs); }; <commit_msg>edits<commit_after>#pragma once #include <cmath> #include <iostream> const uint8_t POSIT_ROUND_DOWN = 0; const uint8_t POSIT_ROUND_TO_NEAREST = 1; /* class posit represents arbitrary configuration posits and their arithmetic */ template<size_t nbits> class quire : std::bitset<nbits> { public: quire<nbits>() {} quire<nbits>(const quire& q) { *this = q; } // template parameters need names different from class template parameters (for gcc and clang) template<size_t nnbits> friend std::ostream& operator<< (std::ostream& ostr, const quire<nnbits>& p); template<size_t nnbits> friend std::istream& operator>> (std::istream& istr, quire<nnbits>& p); template<size_t nnbits> friend bool operator==(const quire<nnbits>& lhs, const quire<nnbits>& rhs); template<size_t nnbits> friend bool operator!=(const quire<nnbits>& lhs, const quire<nnbits>& rhs); template<size_t nnbitss> friend bool operator< (const quire<nnbits>& lhs, const quire<nnbits>& rhs); template<size_t nnbits> friend bool operator> (const quire<nnbits>& lhs, const quire<nnbits>& rhs); template<size_t nnbits> friend bool operator<=(const quire<nnbits>& lhs, const quire<nnbits>& rhs); template<size_t nnbits> friend bool operator>=(const quire<nnbits>& lhs, const quire<nnbits>& rhs); }; <|endoftext|>
<commit_before>#include "stdafx.h" #include "UIProgress.h" namespace DuiLib { CProgressUI::CProgressUI() : m_bHorizontal(true), m_nMin(0), m_nMax(100), m_nValue(0) { m_uTextStyle = DT_SINGLELINE | DT_CENTER; SetFixedHeight(12); } LPCTSTR CProgressUI::GetClass() const { return DUI_CTR_PROGRESS; } LPVOID CProgressUI::GetInterface(LPCTSTR pstrName) { if( _tcscmp(pstrName, DUI_CTR_PROGRESS) == 0 ) return static_cast<CProgressUI*>(this); return CLabelUI::GetInterface(pstrName); } bool CProgressUI::IsHorizontal() { return m_bHorizontal; } void CProgressUI::SetHorizontal(bool bHorizontal) { if( m_bHorizontal == bHorizontal ) return; m_bHorizontal = bHorizontal; Invalidate(); } int CProgressUI::GetMinValue() const { return m_nMin; } void CProgressUI::SetMinValue(int nMin) { m_nMin = nMin; Invalidate(); } int CProgressUI::GetMaxValue() const { return m_nMax; } void CProgressUI::SetMaxValue(int nMax) { m_nMax = nMax; Invalidate(); } int CProgressUI::GetValue() const { return m_nValue; } void CProgressUI::SetValue(int nValue) { m_nValue = nValue; if (m_nValue > m_nMax) m_nValue = m_nMax; if (m_nValue < m_nMin) m_nValue = m_nMin; Invalidate(); } CDuiString CProgressUI::GetForeImage() const { return m_diFore.sDrawString; } void CProgressUI::SetForeImage(LPCTSTR pStrImage) { if( m_diFore.sDrawString == pStrImage && m_diFore.pImageInfo != NULL ) return; m_diFore.Clear(); m_diFore.sDrawString = pStrImage; Invalidate(); } void CProgressUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue) { if( _tcscmp(pstrName, _T("foreimage")) == 0 ) SetForeImage(pstrValue); else if( _tcscmp(pstrName, _T("hor")) == 0 ) SetHorizontal(_tcscmp(pstrValue, _T("true")) == 0); else if( _tcscmp(pstrName, _T("min")) == 0 ) SetMinValue(_ttoi(pstrValue)); else if( _tcscmp(pstrName, _T("max")) == 0 ) SetMaxValue(_ttoi(pstrValue)); else if( _tcscmp(pstrName, _T("value")) == 0 ) SetValue(_ttoi(pstrValue)); else CLabelUI::SetAttribute(pstrName, pstrValue); } void CProgressUI::PaintStatusImage(HDC hDC) { if( m_nMax <= m_nMin ) m_nMax = m_nMin + 1; if( m_nValue > m_nMax ) m_nValue = m_nMax; if( m_nValue < m_nMin ) m_nValue = m_nMin; RECT rc = {0}; if( m_bHorizontal ) { rc.right = (m_nValue - m_nMin) * (m_rcItem.right - m_rcItem.left) / (m_nMax - m_nMin); rc.bottom = m_rcItem.bottom - m_rcItem.top; } else { rc.top = (m_rcItem.bottom - m_rcItem.top) * (m_nMax - m_nValue) / (m_nMax - m_nMin); rc.right = m_rcItem.right - m_rcItem.left; rc.bottom = m_rcItem.bottom - m_rcItem.top; } m_diFore.rcDestOffset = rc; if( DrawImage(hDC, m_diFore) ) return; } } <commit_msg>CProgressUIζŽ§δ»ΆοΌŒζ–‡ζœ¬εˆε§‹εŒ–εž‚η›΄ε±…δΈ­εΉΆδΈ”ε•θ‘Œ<commit_after>#include "stdafx.h" #include "UIProgress.h" namespace DuiLib { CProgressUI::CProgressUI() : m_bHorizontal(true), m_nMin(0), m_nMax(100), m_nValue(0) { m_uTextStyle = DT_SINGLELINE | DT_CENTER; SetFixedHeight(12); m_uTextStyle = DT_VCENTER|DT_SINGLELINE; } LPCTSTR CProgressUI::GetClass() const { return DUI_CTR_PROGRESS; } LPVOID CProgressUI::GetInterface(LPCTSTR pstrName) { if( _tcscmp(pstrName, DUI_CTR_PROGRESS) == 0 ) return static_cast<CProgressUI*>(this); return CLabelUI::GetInterface(pstrName); } bool CProgressUI::IsHorizontal() { return m_bHorizontal; } void CProgressUI::SetHorizontal(bool bHorizontal) { if( m_bHorizontal == bHorizontal ) return; m_bHorizontal = bHorizontal; Invalidate(); } int CProgressUI::GetMinValue() const { return m_nMin; } void CProgressUI::SetMinValue(int nMin) { m_nMin = nMin; Invalidate(); } int CProgressUI::GetMaxValue() const { return m_nMax; } void CProgressUI::SetMaxValue(int nMax) { m_nMax = nMax; Invalidate(); } int CProgressUI::GetValue() const { return m_nValue; } void CProgressUI::SetValue(int nValue) { m_nValue = nValue; if (m_nValue > m_nMax) m_nValue = m_nMax; if (m_nValue < m_nMin) m_nValue = m_nMin; Invalidate(); } CDuiString CProgressUI::GetForeImage() const { return m_diFore.sDrawString; } void CProgressUI::SetForeImage(LPCTSTR pStrImage) { if( m_diFore.sDrawString == pStrImage && m_diFore.pImageInfo != NULL ) return; m_diFore.Clear(); m_diFore.sDrawString = pStrImage; Invalidate(); } void CProgressUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue) { if( _tcscmp(pstrName, _T("foreimage")) == 0 ) SetForeImage(pstrValue); else if( _tcscmp(pstrName, _T("hor")) == 0 ) SetHorizontal(_tcscmp(pstrValue, _T("true")) == 0); else if( _tcscmp(pstrName, _T("min")) == 0 ) SetMinValue(_ttoi(pstrValue)); else if( _tcscmp(pstrName, _T("max")) == 0 ) SetMaxValue(_ttoi(pstrValue)); else if( _tcscmp(pstrName, _T("value")) == 0 ) SetValue(_ttoi(pstrValue)); else CLabelUI::SetAttribute(pstrName, pstrValue); } void CProgressUI::PaintStatusImage(HDC hDC) { if( m_nMax <= m_nMin ) m_nMax = m_nMin + 1; if( m_nValue > m_nMax ) m_nValue = m_nMax; if( m_nValue < m_nMin ) m_nValue = m_nMin; RECT rc = {0}; if( m_bHorizontal ) { rc.right = (m_nValue - m_nMin) * (m_rcItem.right - m_rcItem.left) / (m_nMax - m_nMin); rc.bottom = m_rcItem.bottom - m_rcItem.top; } else { rc.top = (m_rcItem.bottom - m_rcItem.top) * (m_nMax - m_nValue) / (m_nMax - m_nMin); rc.right = m_rcItem.right - m_rcItem.left; rc.bottom = m_rcItem.bottom - m_rcItem.top; } m_diFore.rcDestOffset = rc; if( DrawImage(hDC, m_diFore) ) return; } } <|endoftext|>
<commit_before>// $Id$ // Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007 /************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. * * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for * * full copyright notice. * **************************************************************************/ TString acorde_module_path(Int_t module); void acorde_raw() { AliEveEventManager::AssertGeometry(); AliRawReader * reader = AliEveEventManager::AssertRawReader(); AliACORDERawStream * stream = new AliACORDERawStream(reader); stream->Reset(); stream->Next(); UInt_t dy[4]; dy[0] = stream->GetWord(0); dy[1] = stream->GetWord(1); dy[2] = stream->GetWord(2); dy[3] = stream->GetWord(3); printf ("ACORDE event 0x%08x 0x%08x 0x%08x 0x%08x\n", dy[0], dy[1], dy[2], dy[3]); TEveElementList* acorde = new TEveElementList("ACORDE Raw"); gEve->AddElement(acorde); for (Int_t module=0; module < 60; ++module) { TString path = acorde_module_path(module); // printf("%2d - %s\n", i, path.Data()); if ( ! gGeoManager->cd(path)) { Warning("acorde_raw", "Module id=%d, path='%s' not found.\n", module, path.Data()); continue; } // From Matevz: // Here check state and assign color, I do it partially for now. Int_t word_idx = module / 30; Int_t bit_idx = module % 30; Bool_t val = (dy[word_idx] & (1 << bit_idx)) != 0; //printf("Module %2d: word_idx = %d, bit_idx = %2d => val = %d\n", // module, word_idx, bit_idx, val); TEveGeoShape* eg_shape = new TEveGeoShape(TString::Format("Module %d", module), TString::Format("Module %d, %s", module, val ? "ON" : "OFF")); eg_shape->SetPickable(kTRUE); eg_shape->SetMainColor(val ? kRed : kBlue); eg_shape->RefMainTrans().SetFrom(*gGeoManager->GetCurrentMatrix()); eg_shape->SetShape((TGeoShape*) gGeoManager->GetCurrentVolume()->GetShape()->Clone()); acorde->AddElement(eg_shape); } delete stream; gEve->Redraw3D(); } //============================================================================== //============================================================================== TString acorde_module_path(Int_t module) { if (module < 0 || module > 59) { Error("acorde_module_path", "module %d out of range.", module); return ""; } TGeoPNEntry* pne = gGeoManager->GetAlignableEntry(Form("ACORDE/Array%d", module + 1)); if(!pne) return "missing_pne"; return Form("%s/ACORDE2_5", pne->GetTitle()); } <commit_msg>Make ACORDE modules transparent.<commit_after>// $Id$ // Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007 /************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. * * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for * * full copyright notice. * **************************************************************************/ TString acorde_module_path(Int_t module); Color_t g_acorde_raw_color_on = kRed; Color_t g_acorde_raw_color_off = kBlue; UChar_t g_acorde_raw_transp_on = 30; UChar_t g_acorde_raw_transp_off = 60; void acorde_raw() { AliEveEventManager::AssertGeometry(); AliRawReader * reader = AliEveEventManager::AssertRawReader(); AliACORDERawStream * stream = new AliACORDERawStream(reader); stream->Reset(); stream->Next(); UInt_t dy[4]; dy[0] = stream->GetWord(0); dy[1] = stream->GetWord(1); dy[2] = stream->GetWord(2); dy[3] = stream->GetWord(3); printf ("ACORDE event 0x%08x 0x%08x 0x%08x 0x%08x\n", dy[0], dy[1], dy[2], dy[3]); TEveElementList* acorde = new TEveElementList("ACORDE Raw"); gEve->AddElement(acorde); for (Int_t module=0; module < 60; ++module) { TString path = acorde_module_path(module); // printf("%2d - %s\n", i, path.Data()); if ( ! gGeoManager->cd(path)) { Warning("acorde_raw", "Module id=%d, path='%s' not found.\n", module, path.Data()); continue; } // From Matevz: // Here check state and assign color, I do it partially for now. Int_t word_idx = module / 30; Int_t bit_idx = module % 30; Bool_t val = (dy[word_idx] & (1 << bit_idx)) != 0; //printf("Module %2d: word_idx = %d, bit_idx = %2d => val = %d\n", // module, word_idx, bit_idx, val); TEveGeoShape* eg_shape = new TEveGeoShape(TString::Format("Module %d", module), TString::Format("Module %d, %s", module, val ? "ON" : "OFF")); eg_shape->SetMainColor (val ? g_acorde_raw_color_on : g_acorde_raw_color_off); eg_shape->SetMainTransparency(val ? g_acorde_raw_transp_on : g_acorde_raw_transp_off); eg_shape->SetPickable(kTRUE); eg_shape->RefMainTrans().SetFrom(*gGeoManager->GetCurrentMatrix()); eg_shape->SetShape((TGeoShape*) gGeoManager->GetCurrentVolume()->GetShape()->Clone()); acorde->AddElement(eg_shape); } delete stream; gEve->Redraw3D(); } //============================================================================== //============================================================================== TString acorde_module_path(Int_t module) { if (module < 0 || module > 59) { Error("acorde_module_path", "module %d out of range.", module); return ""; } TGeoPNEntry* pne = gGeoManager->GetAlignableEntry(Form("ACORDE/Array%d", module + 1)); if(!pne) return "missing_pne"; return Form("%s/ACORDE2_5", pne->GetTitle()); } <|endoftext|>
<commit_before>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: python/pybind11_variant.hpp * * Copyright 2018 Patrik Huber * * 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. */ #pragma once #ifndef EOS_PYBIND11_VARIANT_HPP_ #define EOS_PYBIND11_VARIANT_HPP_ /** * @file python/pybind11_variant.hpp * @brief Define a type_caster for mpark::variant, which is used when the compiler doesn't have <variant> (e.g. on Apple). */ #if __cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) #include "pybind11/stl.h" #else #include "eos/cpp17/variant.hpp" #include "pybind11/stl.h" namespace pybind11 { namespace detail { /** * @brief Type caster for mpark::variant, which is used when the compiler doesn't have <variant> (e.g. on Apple). */ template <typename... Ts> class type_caster<mpark::variant<Ts...>> : variant_caster<mpark::variant<Ts...>> { }; } /* namespace detail */ } /* namespace pybind11 */ #endif #endif /* EOS_PYBIND11_VARIANT_HPP_ */ <commit_msg>Change variant type_caster back to struct for public inheritance<commit_after>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: python/pybind11_variant.hpp * * Copyright 2018 Patrik Huber * * 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. */ #pragma once #ifndef EOS_PYBIND11_VARIANT_HPP_ #define EOS_PYBIND11_VARIANT_HPP_ /** * @file python/pybind11_variant.hpp * @brief Define a type_caster for mpark::variant, which is used when the compiler doesn't have <variant> (e.g. on Apple). */ #if __cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) #include "pybind11/stl.h" #else #include "eos/cpp17/variant.hpp" #include "pybind11/stl.h" namespace pybind11 { namespace detail { /** * @brief Type caster for mpark::variant, which is used when the compiler doesn't have <variant> (e.g. on Apple). */ template <typename... Ts> struct type_caster<mpark::variant<Ts...>> : variant_caster<mpark::variant<Ts...>> { }; } /* namespace detail */ } /* namespace pybind11 */ #endif #endif /* EOS_PYBIND11_VARIANT_HPP_ */ <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // LLVM 'OPT' UTILITY // // Optimizations may be specified an arbitrary number of times on the command // line, they are run in the order specified. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Bytecode/Reader.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Transforms/ConstantMerge.h" #include "llvm/Transforms/CleanupGCCOutput.h" #include "llvm/Transforms/LevelChange.h" #include "llvm/Transforms/FunctionInlining.h" #include "llvm/Transforms/ChangeAllocations.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/IPO/SimpleStructMutation.h" #include "llvm/Transforms/IPO/Internalize.h" #include "llvm/Transforms/IPO/GlobalDCE.h" #include "llvm/Transforms/IPO/PoolAllocate.h" #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h" #include "llvm/Transforms/Instrumentation/TraceValues.h" #include "llvm/Transforms/Instrumentation/ProfilePaths.h" #include "llvm/Target/TargetData.h" #include "Support/CommandLine.h" #include "Support/Signals.h" #include <fstream> #include <memory> // FIXME: This should be parameterizable eventually for different target // types... static TargetData TD("opt target"); // Opts enum - All of the transformations we can do... enum Opts { // Basic optimizations dce, die, constprop, gcse, licm, inlining, constmerge, strip, mstrip, mergereturn, // Miscellaneous Transformations raiseallocs, lowerallocs, funcresolve, cleangcc, lowerrefs, // Printing and verifying... print, printm, verify, // More powerful optimizations indvars, instcombine, sccp, adce, raise, reassociate, mem2reg, pinodes, // Instrumentation trace, tracem, paths, // Interprocedural optimizations... internalize, globaldce, swapstructs, sortstructs, poolalloc, }; static Pass *createPrintFunctionPass() { return new PrintFunctionPass("Current Function: \n", &cerr); } static Pass *createPrintModulePass() { return new PrintModulePass(&cerr); } static Pass *createLowerAllocationsPassNT() { return createLowerAllocationsPass(TD); } // OptTable - Correlate enum Opts to Pass constructors... // struct { enum Opts OptID; Pass * (*PassCtor)(); } OptTable[] = { { dce , createDeadCodeEliminationPass }, { die , createDeadInstEliminationPass }, { constprop , createConstantPropogationPass }, { gcse , createGCSEPass }, { licm , createLICMPass }, { inlining , createFunctionInliningPass }, { constmerge , createConstantMergePass }, { strip , createSymbolStrippingPass }, { mstrip , createFullSymbolStrippingPass }, { mergereturn, createUnifyFunctionExitNodesPass }, { indvars , createIndVarSimplifyPass }, { instcombine, createInstructionCombiningPass }, { sccp , createSCCPPass }, { adce , createAggressiveDCEPass }, { raise , createRaisePointerReferencesPass }, { reassociate, createReassociatePass }, { mem2reg , createPromoteMemoryToRegister }, { pinodes , createPiNodeInsertionPass }, { lowerrefs , createDecomposeMultiDimRefsPass }, { trace , createTraceValuesPassForBasicBlocks }, { tracem , createTraceValuesPassForFunction }, { paths , createProfilePathsPass }, { print , createPrintFunctionPass }, { printm , createPrintModulePass }, { verify , createVerifierPass }, { raiseallocs, createRaiseAllocationsPass }, { lowerallocs, createLowerAllocationsPassNT }, { cleangcc , createCleanupGCCOutputPass }, { funcresolve, createFunctionResolvingPass }, { internalize, createInternalizePass }, { globaldce , createGlobalDCEPass }, { swapstructs, createSwapElementsPass }, { sortstructs, createSortElementsPass }, { poolalloc , createPoolAllocatePass }, }; // Command line option handling code... // cl::String InputFilename ("", "Load <arg> file to optimize", cl::NoFlags, "-"); cl::String OutputFilename("o", "Override output filename", cl::NoFlags, ""); cl::Flag Force ("f", "Overwrite output files", cl::NoFlags, false); cl::Flag PrintEachXForm("p", "Print module after each transformation"); cl::Flag Quiet ("q", "Don't print modifying pass names", 0, false); cl::Alias QuietA ("quiet", "Alias for -q", cl::NoFlags, Quiet); cl::EnumList<enum Opts> OptimizationList(cl::NoFlags, clEnumVal(dce , "Dead Code Elimination"), clEnumVal(die , "Dead Instruction Elimination"), clEnumVal(constprop , "Simple constant propogation"), clEnumVal(gcse , "Global Common Subexpression Elimination"), clEnumVal(licm , "Loop Invariant Code Motion"), clEnumValN(inlining , "inline", "Function integration"), clEnumVal(constmerge , "Merge identical global constants"), clEnumVal(strip , "Strip symbols"), clEnumVal(mstrip , "Strip module symbols"), clEnumVal(mergereturn, "Unify function exit nodes"), clEnumVal(indvars , "Simplify Induction Variables"), clEnumVal(instcombine, "Combine redundant instructions"), clEnumVal(sccp , "Sparse Conditional Constant Propogation"), clEnumVal(adce , "Aggressive DCE"), clEnumVal(reassociate, "Reassociate expressions"), clEnumVal(mem2reg , "Promote alloca locations to registers"), clEnumVal(pinodes , "Insert Pi nodes after definitions"), clEnumVal(internalize, "Mark all fn's internal except for main"), clEnumVal(globaldce , "Remove unreachable globals"), clEnumVal(swapstructs, "Swap structure types around"), clEnumVal(sortstructs, "Sort structure elements"), clEnumVal(poolalloc , "Pool allocate disjoint datastructures"), clEnumVal(raiseallocs, "Raise allocations from calls to instructions"), clEnumVal(lowerallocs, "Lower allocations from instructions to calls (TD)"), clEnumVal(cleangcc , "Cleanup GCC Output"), clEnumVal(funcresolve, "Resolve calls to foo(...) to foo(<concrete types>)"), clEnumVal(raise , "Raise to Higher Level"), clEnumVal(trace , "Insert BB and Function trace code"), clEnumVal(tracem , "Insert Function trace code only"), clEnumVal(paths , "Insert path profiling instrumentation"), clEnumVal(print , "Print working function to stderr"), clEnumVal(printm , "Print working module to stderr"), clEnumVal(verify , "Verify module is well formed"), clEnumVal(lowerrefs , "Decompose multi-dimensional structure/array refs to use one index per instruction"), 0); int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm .bc -> .bc modular optimizer\n"); // Load the input module... std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename)); if (M.get() == 0) { cerr << "bytecode didn't read correctly.\n"; return 1; } // Figure out what stream we are supposed to write to... std::ostream *Out = &std::cout; // Default to printing to stdout... if (OutputFilename != "") { if (!Force && std::ifstream(OutputFilename.c_str())) { // If force is not specified, make sure not to overwrite a file! cerr << "Error opening '" << OutputFilename << "': File exists!\n" << "Use -f command line argument to force output\n"; return 1; } Out = new std::ofstream(OutputFilename.c_str()); if (!Out->good()) { cerr << "Error opening " << OutputFilename << "!\n"; return 1; } // Make sure that the Output file gets unlink'd from the disk if we get a // SIGINT RemoveFileOnSignal(OutputFilename); } // Create a PassManager to hold and optimize the collection of passes we are // about to build... // PassManager Passes; // Create a new optimization pass for each one specified on the command line for (unsigned i = 0; i < OptimizationList.size(); ++i) { enum Opts Opt = OptimizationList[i]; for (unsigned j = 0; j < sizeof(OptTable)/sizeof(OptTable[0]); ++j) if (Opt == OptTable[j].OptID) { Passes.add(OptTable[j].PassCtor()); break; } if (PrintEachXForm) Passes.add(new PrintModulePass(&std::cerr)); } // Check that the module is well formed on completion of optimization Passes.add(createVerifierPass()); // Write bytecode out to disk or cout as the last step... Passes.add(new WriteBytecodePass(Out, Out != &std::cout)); // Now that we have all of the passes ready, run them. if (Passes.run(M.get()) && !Quiet) cerr << "Program modified.\n"; return 0; } <commit_msg>Expose cfg simplification pass<commit_after>//===----------------------------------------------------------------------===// // LLVM 'OPT' UTILITY // // Optimizations may be specified an arbitrary number of times on the command // line, they are run in the order specified. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Bytecode/Reader.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Transforms/ConstantMerge.h" #include "llvm/Transforms/CleanupGCCOutput.h" #include "llvm/Transforms/LevelChange.h" #include "llvm/Transforms/FunctionInlining.h" #include "llvm/Transforms/ChangeAllocations.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/IPO/SimpleStructMutation.h" #include "llvm/Transforms/IPO/Internalize.h" #include "llvm/Transforms/IPO/GlobalDCE.h" #include "llvm/Transforms/IPO/PoolAllocate.h" #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h" #include "llvm/Transforms/Instrumentation/TraceValues.h" #include "llvm/Transforms/Instrumentation/ProfilePaths.h" #include "llvm/Target/TargetData.h" #include "Support/CommandLine.h" #include "Support/Signals.h" #include <fstream> #include <memory> // FIXME: This should be parameterizable eventually for different target // types... static TargetData TD("opt target"); // Opts enum - All of the transformations we can do... enum Opts { // Basic optimizations dce, die, constprop, gcse, licm, inlining, constmerge, strip, mstrip, mergereturn, simplifycfg, // Miscellaneous Transformations raiseallocs, lowerallocs, funcresolve, cleangcc, lowerrefs, // Printing and verifying... print, printm, verify, // More powerful optimizations indvars, instcombine, sccp, adce, raise, reassociate, mem2reg, pinodes, // Instrumentation trace, tracem, paths, // Interprocedural optimizations... internalize, globaldce, swapstructs, sortstructs, poolalloc, }; static Pass *createPrintFunctionPass() { return new PrintFunctionPass("Current Function: \n", &cerr); } static Pass *createPrintModulePass() { return new PrintModulePass(&cerr); } static Pass *createLowerAllocationsPassNT() { return createLowerAllocationsPass(TD); } // OptTable - Correlate enum Opts to Pass constructors... // struct { enum Opts OptID; Pass * (*PassCtor)(); } OptTable[] = { { dce , createDeadCodeEliminationPass }, { die , createDeadInstEliminationPass }, { constprop , createConstantPropogationPass }, { gcse , createGCSEPass }, { licm , createLICMPass }, { inlining , createFunctionInliningPass }, { constmerge , createConstantMergePass }, { strip , createSymbolStrippingPass }, { mstrip , createFullSymbolStrippingPass }, { mergereturn, createUnifyFunctionExitNodesPass }, { simplifycfg, createCFGSimplificationPass }, { indvars , createIndVarSimplifyPass }, { instcombine, createInstructionCombiningPass }, { sccp , createSCCPPass }, { adce , createAggressiveDCEPass }, { raise , createRaisePointerReferencesPass }, { reassociate, createReassociatePass }, { mem2reg , createPromoteMemoryToRegister }, { pinodes , createPiNodeInsertionPass }, { lowerrefs , createDecomposeMultiDimRefsPass }, { trace , createTraceValuesPassForBasicBlocks }, { tracem , createTraceValuesPassForFunction }, { paths , createProfilePathsPass }, { print , createPrintFunctionPass }, { printm , createPrintModulePass }, { verify , createVerifierPass }, { raiseallocs, createRaiseAllocationsPass }, { lowerallocs, createLowerAllocationsPassNT }, { cleangcc , createCleanupGCCOutputPass }, { funcresolve, createFunctionResolvingPass }, { internalize, createInternalizePass }, { globaldce , createGlobalDCEPass }, { swapstructs, createSwapElementsPass }, { sortstructs, createSortElementsPass }, { poolalloc , createPoolAllocatePass }, }; // Command line option handling code... // cl::String InputFilename ("", "Load <arg> file to optimize", cl::NoFlags, "-"); cl::String OutputFilename("o", "Override output filename", cl::NoFlags, ""); cl::Flag Force ("f", "Overwrite output files", cl::NoFlags, false); cl::Flag PrintEachXForm("p", "Print module after each transformation"); cl::Flag Quiet ("q", "Don't print modifying pass names", 0, false); cl::Alias QuietA ("quiet", "Alias for -q", cl::NoFlags, Quiet); cl::EnumList<enum Opts> OptimizationList(cl::NoFlags, clEnumVal(dce , "Dead Code Elimination"), clEnumVal(die , "Dead Instruction Elimination"), clEnumVal(constprop , "Simple constant propogation"), clEnumVal(gcse , "Global Common Subexpression Elimination"), clEnumVal(licm , "Loop Invariant Code Motion"), clEnumValN(inlining , "inline", "Function integration"), clEnumVal(constmerge , "Merge identical global constants"), clEnumVal(strip , "Strip symbols"), clEnumVal(mstrip , "Strip module symbols"), clEnumVal(mergereturn, "Unify function exit nodes"), clEnumVal(simplifycfg, "CFG Simplification"), clEnumVal(indvars , "Simplify Induction Variables"), clEnumVal(instcombine, "Combine redundant instructions"), clEnumVal(sccp , "Sparse Conditional Constant Propogation"), clEnumVal(adce , "Aggressive DCE"), clEnumVal(reassociate, "Reassociate expressions"), clEnumVal(mem2reg , "Promote alloca locations to registers"), clEnumVal(pinodes , "Insert Pi nodes after definitions"), clEnumVal(internalize, "Mark all fn's internal except for main"), clEnumVal(globaldce , "Remove unreachable globals"), clEnumVal(swapstructs, "Swap structure types around"), clEnumVal(sortstructs, "Sort structure elements"), clEnumVal(poolalloc , "Pool allocate disjoint datastructures"), clEnumVal(raiseallocs, "Raise allocations from calls to instructions"), clEnumVal(lowerallocs, "Lower allocations from instructions to calls (TD)"), clEnumVal(cleangcc , "Cleanup GCC Output"), clEnumVal(funcresolve, "Resolve calls to foo(...) to foo(<concrete types>)"), clEnumVal(raise , "Raise to Higher Level"), clEnumVal(trace , "Insert BB and Function trace code"), clEnumVal(tracem , "Insert Function trace code only"), clEnumVal(paths , "Insert path profiling instrumentation"), clEnumVal(print , "Print working function to stderr"), clEnumVal(printm , "Print working module to stderr"), clEnumVal(verify , "Verify module is well formed"), clEnumVal(lowerrefs , "Decompose multi-dimensional structure/array refs to use one index per instruction"), 0); int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm .bc -> .bc modular optimizer\n"); // Load the input module... std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename)); if (M.get() == 0) { cerr << "bytecode didn't read correctly.\n"; return 1; } // Figure out what stream we are supposed to write to... std::ostream *Out = &std::cout; // Default to printing to stdout... if (OutputFilename != "") { if (!Force && std::ifstream(OutputFilename.c_str())) { // If force is not specified, make sure not to overwrite a file! cerr << "Error opening '" << OutputFilename << "': File exists!\n" << "Use -f command line argument to force output\n"; return 1; } Out = new std::ofstream(OutputFilename.c_str()); if (!Out->good()) { cerr << "Error opening " << OutputFilename << "!\n"; return 1; } // Make sure that the Output file gets unlink'd from the disk if we get a // SIGINT RemoveFileOnSignal(OutputFilename); } // Create a PassManager to hold and optimize the collection of passes we are // about to build... // PassManager Passes; // Create a new optimization pass for each one specified on the command line for (unsigned i = 0; i < OptimizationList.size(); ++i) { enum Opts Opt = OptimizationList[i]; for (unsigned j = 0; j < sizeof(OptTable)/sizeof(OptTable[0]); ++j) if (Opt == OptTable[j].OptID) { Passes.add(OptTable[j].PassCtor()); break; } if (PrintEachXForm) Passes.add(new PrintModulePass(&std::cerr)); } // Check that the module is well formed on completion of optimization Passes.add(createVerifierPass()); // Write bytecode out to disk or cout as the last step... Passes.add(new WriteBytecodePass(Out, Out != &std::cout)); // Now that we have all of the passes ready, run them. if (Passes.run(M.get()) && !Quiet) cerr << "Program modified.\n"; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * Copyright (C) 2011-2013 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of Teapotnet. * * * * Teapotnet is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * Teapotnet is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with Teapotnet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "tpn/interface.h" #include "tpn/html.h" #include "tpn/user.h" #include "tpn/store.h" #include "tpn/splicer.h" #include "tpn/config.h" #include "tpn/directory.h" #include "tpn/mime.h" namespace tpn { Interface *Interface::Instance = NULL; Interface::Interface(int port) : Http::Server(port) { } Interface::~Interface(void) { } void Interface::add(const String &prefix, HttpInterfaceable *interfaceable) { Assert(interfaceable != NULL); String cprefix(prefix); if(cprefix.empty() || cprefix[0] != '/') cprefix = "/" + cprefix; mMutex.lock(); mPrefixes.insert(cprefix, interfaceable); mMutex.unlock(); } void Interface::remove(const String &prefix, HttpInterfaceable *interfaceable) { mMutex.lock(); HttpInterfaceable *test = NULL; if(mPrefixes.get(prefix, test) && (!interfaceable || test == interfaceable)) mPrefixes.erase(prefix); mMutex.unlock(); } void Interface::process(Http::Request &request) { Address remoteAddr = request.sock->getRemoteAddress(); LogDebug("Interface", "Request for URL \""+request.fullUrl+"\""); // URL must begin with / if(request.url.empty() || request.url[0] != '/') throw 404; if(request.url == "/") { if(request.method == "POST") { String name, password, tracker; request.post.get("name", name); request.post.get("password", password); request.post.get("tracker", tracker); if(name.contains('@')) tracker = name.cut('@'); User *user = NULL; try { if(request.post.contains("create") && !User::Exist(name)) { user = new User(name, password, tracker); } else { user = User::Authenticate(name, password); if(user && !tracker.empty()) user->setTracker(tracker); } } catch(const Exception &e) { Http::Response response(request, 200); response.send(); Html page(response.sock); page.header("Error", false, "/"); page.text(e.what()); page.footer(); return; } if(!user) throw 401; // TODO String token = user->generateToken("auth"); Http::Response response(request, 303); response.headers["Location"] = "/" + user->name(); response.cookies["auth_"+user->name()] = token; response.send(); return; } /* #ifdef ANDROID if(!user && remoteAddr.isLocal() && User::Count() == 1) { Array<String> names; User::GetNames(names); user = User::Get(names[0]); if(user) { Http::Response response(request, 303); response.headers["Location"] = "/" + user->name(); response.send(); return; } } #endif */ Http::Response response(request, 200); response.send(); Html page(response.sock); page.header("Login - Teapotnet", true); page.open("div","login"); page.open("div","logo"); page.openLink("/"); page.image("/logo.png", "Teapotnet"); page.closeLink(); page.close("div"); page.openForm("/", "post"); page.open("table"); page.open("tr"); page.open("td",".label"); page.label("name", "Name"); page.close("td"); page.open("td"); page.input("text", "name"); page.close("td"); page.open("td"); page.link("#", "Change trackers", "trackerlink"); page.close("td"); page.close("tr"); page.open("tr", "trackerselection"); page.open("td",".label"); page.label("tracker", "Tracker"); page.close("td"); page.open("td"); page.input("tracker", "tracker", ""); page.close("td"); page.open("td"); page.close("td"); page.close("tr"); page.open("tr"); page.open("td",".label"); page.label("password", "Password"); page.close("td"); page.open("td"); page.input("password", "password"); page.close("td"); page.open("td"); page.close("td"); page.close("tr"); page.open("tr"); page.open("td",".label"); page.close("td"); page.open("td"); if(User::Count() > 0) page.button("login", "Login"); page.button("create", "Create"); page.close("td"); page.close("tr"); page.close("table"); page.closeForm(); for(StringMap::iterator it = request.cookies.begin(); it != request.cookies.end(); ++it) { String cookieName = it->first; String name = cookieName.cut('_'); if(cookieName != "auth" || name.empty()) continue; User *user = User::Get(name); if(!user || !user->checkToken(it->second, "auth")) continue; page.open("div",".user"); page.openLink("/" + name); page.image(user->profile()->avatarUrl(), "", ".avatar"); page.open("span", ".username"); page.text(name); page.close("span"); page.closeLink(); page.text(" - "); page.link("#", "Logout", ".logoutlink"); page.close("div"); page.javascript("$('.user a.logoutlink').click(function() {\n\ unsetCookie('auth_'+$(this).parent().find('.username').text());\n\ window.location.reload();\n\ return false;\n\ });"); } page.close("div"); page.javascript("$('#trackerselection').hide();\n\ $('#trackerlink').click(function() {\n\ $(this).hide();\n\ $('#trackerselection').show();\n\ $('#trackerselection .tracker').val('"+Config::Get("tracker")+"');\n\ });"); page.footer(); return; } List<String> list; request.url.explode(list,'/'); list.pop_front(); // first element is empty because url begin with '/' if(list.empty()) throw 500; if(list.front().empty()) throw 404; if(list.size() == 1 && list.front().contains('.') && request.url[request.url.size()-1] != '/') { String fileName = Config::Get("static_dir") + Directory::Separator + list.front(); if(File::Exist(fileName)) { Http::RespondWithFile(request, fileName); return; } if(!User::Exist(list.front())) throw 404; } if(User::Exist(list.front())) { String name = list.front(); User *user = NULL; String auth; if(request.headers.get("Authorization", auth)) { String tmp = auth.cut(' '); auth.trim(); tmp.trim(); if(auth != "Basic") throw 400; String authName = tmp.base64Decode(); String authPassword = authName.cut(':'); if(authName == name) user = User::Authenticate(authName, authPassword); } else { String token; request.cookies.get("auth_"+name, token); User *tmp = User::Get(list.front()); if(tmp->checkToken(token, "auth")) user = tmp; } if(!user) { String userAgent; request.headers.get("User-Agent", userAgent); // If it is a browser if(userAgent.substr(0,7) == "Mozilla") { Http::Response response(request, 303); response.headers["Location"] = "/"; response.send(); return; } else { Http::Response response(request, 401); response.headers.insert("WWW-Authenticate", "Basic realm=\""+String(APPNAME)+"\""); response.send(); Html page(response.sock); page.header(response.message, true); page.open("div", "error"); page.openLink("/"); page.image("/error.png", "Error"); page.closeLink(); page.br(); page.br(); page.open("h1",".huge"); page.text("Authentication required"); page.close("h1"); page.close("div"); page.footer(); return; } } while(!list.empty()) { String prefix; prefix.implode(list,'/'); prefix = "/" + prefix; list.pop_back(); mMutex.lock(); HttpInterfaceable *interfaceable; if(mPrefixes.get(prefix,interfaceable)) { mMutex.unlock(); request.url.ignore(prefix.size()); LogDebug("Interface", "Matched prefix \""+prefix+"\""); if(prefix != "/" && request.url.empty()) { Http::Response response(request, 301); // Moved Permanently response.headers["Location"] = prefix+"/"; response.send(); return; } interfaceable->http(prefix, request); return; } mMutex.unlock(); } } else { if(list.size() != 1) throw 404; // TODO: Security: if remote address is not local, check if one user at least is authenticated try { ByteString digest; String tmp = list.front(); try { tmp >> digest; } catch(...) { throw 404; } if(request.get.contains("play") || request.get.contains("playlist")) { String host; if(!request.headers.get("Host", host)) host = String("localhost:") + Config::Get("interface_port"); Http::Response response(request, 200); response.headers["Content-Disposition"] = "attachment; filename=\"stream.m3u\""; response.headers["Content-Type"] = "audio/x-mpegurl"; response.send(); response.sock->writeLine("#EXTM3U"); response.sock->writeLine(String("#EXTINF:-1, ") + APPNAME + " stream"); response.sock->writeLine("http://" + host + "/" + digest.toString()); response.sock->close(); try { // Request the sources now to gain some time afterwards Resource resource(digest); resource.fetch(); } catch(...) {} return; } // Query resource Resource resource(digest); resource.fetch(); // this can take some time // Get range int64_t rangeBegin = 0; int64_t rangeEnd = 0; bool hasRange = request.extractRange(rangeBegin, rangeEnd, resource.size()); int64_t rangeSize = rangeEnd - rangeBegin + 1; // Get resource accessor Resource::Accessor *accessor = resource.accessor(); if(!accessor) throw 404; // Forge HTTP response header Http::Response response(request, 200); if(!hasRange) response.headers["Content-SHA512"] << resource.digest(); response.headers["Content-Length"] << rangeSize; response.headers["Content-Name"] = resource.name(); response.headers["Last-Modified"] = resource.time().toHttpDate(); response.headers["Accept-Ranges"] = "bytes"; String ext = resource.name().afterLast('.'); if(request.get.contains("download") || ext == "htm" || ext == "html" || ext == "xhtml") { response.headers["Content-Disposition"] = "attachment; filename=\"" + resource.name() + "\""; response.headers["Content-Type"] = "application/force-download"; } else { response.headers["Content-Disposition"] = "inline; filename=\"" + resource.name() + "\""; response.headers["Content-Type"] = Mime::GetType(resource.name()); } response.send(); if(request.method == "HEAD") return; try { // Launch transfer if(hasRange) accessor->seekRead(rangeBegin); int64_t size = accessor->readBinary(*response.sock, rangeSize); // let's go ! if(size != rangeSize) throw Exception("range size is " + String::number(rangeSize) + ", but sent size is " + String::number(size)); } catch(const NetException &e) { return; // nothing to do } catch(const Exception &e) { LogWarn("Interface::process", String("Error during file transfer: ") + e.what()); } return; } catch(const NetException &e) { return; // nothing to do } catch(const std::exception &e) { LogWarn("Interface::process", e.what()); throw 404; } } throw 404; } } <commit_msg>Prevent leaking info on valid usernames<commit_after>/************************************************************************* * Copyright (C) 2011-2013 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of Teapotnet. * * * * Teapotnet is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * Teapotnet is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with Teapotnet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "tpn/interface.h" #include "tpn/html.h" #include "tpn/user.h" #include "tpn/store.h" #include "tpn/splicer.h" #include "tpn/config.h" #include "tpn/directory.h" #include "tpn/mime.h" namespace tpn { Interface *Interface::Instance = NULL; Interface::Interface(int port) : Http::Server(port) { } Interface::~Interface(void) { } void Interface::add(const String &prefix, HttpInterfaceable *interfaceable) { Assert(interfaceable != NULL); String cprefix(prefix); if(cprefix.empty() || cprefix[0] != '/') cprefix = "/" + cprefix; mMutex.lock(); mPrefixes.insert(cprefix, interfaceable); mMutex.unlock(); } void Interface::remove(const String &prefix, HttpInterfaceable *interfaceable) { mMutex.lock(); HttpInterfaceable *test = NULL; if(mPrefixes.get(prefix, test) && (!interfaceable || test == interfaceable)) mPrefixes.erase(prefix); mMutex.unlock(); } void Interface::process(Http::Request &request) { Address remoteAddr = request.sock->getRemoteAddress(); LogDebug("Interface", "Request for URL \""+request.fullUrl+"\""); // URL must begin with / if(request.url.empty() || request.url[0] != '/') throw 404; if(request.url == "/") { if(request.method == "POST") { String name, password, tracker; request.post.get("name", name); request.post.get("password", password); request.post.get("tracker", tracker); if(name.contains('@')) tracker = name.cut('@'); User *user = NULL; try { if(request.post.contains("create") && !User::Exist(name)) { user = new User(name, password, tracker); } else { user = User::Authenticate(name, password); if(user && !tracker.empty()) user->setTracker(tracker); } } catch(const Exception &e) { Http::Response response(request, 200); response.send(); Html page(response.sock); page.header("Error", false, "/"); page.text(e.what()); page.footer(); return; } if(!user) throw 401; // TODO String token = user->generateToken("auth"); Http::Response response(request, 303); response.headers["Location"] = "/" + user->name(); response.cookies["auth_"+user->name()] = token; response.send(); return; } /* #ifdef ANDROID if(!user && remoteAddr.isLocal() && User::Count() == 1) { Array<String> names; User::GetNames(names); user = User::Get(names[0]); if(user) { Http::Response response(request, 303); response.headers["Location"] = "/" + user->name(); response.send(); return; } } #endif */ Http::Response response(request, 200); response.send(); Html page(response.sock); page.header("Login - Teapotnet", true); page.open("div","login"); page.open("div","logo"); page.openLink("/"); page.image("/logo.png", "Teapotnet"); page.closeLink(); page.close("div"); page.openForm("/", "post"); page.open("table"); page.open("tr"); page.open("td",".label"); page.label("name", "Name"); page.close("td"); page.open("td"); page.input("text", "name"); page.close("td"); page.open("td"); page.link("#", "Change trackers", "trackerlink"); page.close("td"); page.close("tr"); page.open("tr", "trackerselection"); page.open("td",".label"); page.label("tracker", "Tracker"); page.close("td"); page.open("td"); page.input("tracker", "tracker", ""); page.close("td"); page.open("td"); page.close("td"); page.close("tr"); page.open("tr"); page.open("td",".label"); page.label("password", "Password"); page.close("td"); page.open("td"); page.input("password", "password"); page.close("td"); page.open("td"); page.close("td"); page.close("tr"); page.open("tr"); page.open("td",".label"); page.close("td"); page.open("td"); if(User::Count() > 0) page.button("login", "Login"); page.button("create", "Create"); page.close("td"); page.close("tr"); page.close("table"); page.closeForm(); for(StringMap::iterator it = request.cookies.begin(); it != request.cookies.end(); ++it) { String cookieName = it->first; String name = cookieName.cut('_'); if(cookieName != "auth" || name.empty()) continue; User *user = User::Get(name); if(!user || !user->checkToken(it->second, "auth")) continue; page.open("div",".user"); page.openLink("/" + name); page.image(user->profile()->avatarUrl(), "", ".avatar"); page.open("span", ".username"); page.text(name); page.close("span"); page.closeLink(); page.text(" - "); page.link("#", "Logout", ".logoutlink"); page.close("div"); page.javascript("$('.user a.logoutlink').click(function() {\n\ unsetCookie('auth_'+$(this).parent().find('.username').text());\n\ window.location.reload();\n\ return false;\n\ });"); } page.close("div"); page.javascript("$('#trackerselection').hide();\n\ $('#trackerlink').click(function() {\n\ $(this).hide();\n\ $('#trackerselection').show();\n\ $('#trackerselection .tracker').val('"+Config::Get("tracker")+"');\n\ });"); page.footer(); return; } List<String> list; request.url.explode(list,'/'); list.pop_front(); // first element is empty because url begin with '/' if(list.empty()) throw 500; if(list.front().empty()) throw 404; if(list.size() == 1 && list.front().contains('.') && request.url[request.url.size()-1] != '/') { String fileName = Config::Get("static_dir") + Directory::Separator + list.front(); if(File::Exist(fileName)) { Http::RespondWithFile(request, fileName); return; } if(!User::Exist(list.front())) throw 404; } if(list.front().size() < 64 || User::Exist(list.front())) { String name = list.front(); User *user = NULL; String auth; if(request.headers.get("Authorization", auth)) { String tmp = auth.cut(' '); auth.trim(); tmp.trim(); if(auth != "Basic") throw 400; String authName = tmp.base64Decode(); String authPassword = authName.cut(':'); if(authName == name) user = User::Authenticate(authName, authPassword); } else { String token; request.cookies.get("auth_"+name, token); User *tmp = User::Get(list.front()); if(tmp && tmp->checkToken(token, "auth")) user = tmp; } if(!user) { String userAgent; request.headers.get("User-Agent", userAgent); // If it is a browser if(userAgent.substr(0,7) == "Mozilla") { Http::Response response(request, 303); response.headers["Location"] = "/"; response.send(); return; } else { Http::Response response(request, 401); response.headers.insert("WWW-Authenticate", "Basic realm=\""+String(APPNAME)+"\""); response.send(); Html page(response.sock); page.header(response.message, true); page.open("div", "error"); page.openLink("/"); page.image("/error.png", "Error"); page.closeLink(); page.br(); page.br(); page.open("h1",".huge"); page.text("Authentication required"); page.close("h1"); page.close("div"); page.footer(); return; } } while(!list.empty()) { String prefix; prefix.implode(list,'/'); prefix = "/" + prefix; list.pop_back(); mMutex.lock(); HttpInterfaceable *interfaceable; if(mPrefixes.get(prefix,interfaceable)) { mMutex.unlock(); request.url.ignore(prefix.size()); LogDebug("Interface", "Matched prefix \""+prefix+"\""); if(prefix != "/" && request.url.empty()) { Http::Response response(request, 301); // Moved Permanently response.headers["Location"] = prefix+"/"; response.send(); return; } interfaceable->http(prefix, request); return; } mMutex.unlock(); } } else { if(list.size() != 1) throw 404; // TODO: Security: if remote address is not local, check if one user at least is authenticated try { ByteString digest; String tmp = list.front(); try { tmp >> digest; } catch(...) { throw 404; } if(request.get.contains("play") || request.get.contains("playlist")) { String host; if(!request.headers.get("Host", host)) host = String("localhost:") + Config::Get("interface_port"); Http::Response response(request, 200); response.headers["Content-Disposition"] = "attachment; filename=\"stream.m3u\""; response.headers["Content-Type"] = "audio/x-mpegurl"; response.send(); response.sock->writeLine("#EXTM3U"); response.sock->writeLine(String("#EXTINF:-1, ") + APPNAME + " stream"); response.sock->writeLine("http://" + host + "/" + digest.toString()); response.sock->close(); try { // Request the sources now to gain some time afterwards Resource resource(digest); resource.fetch(); } catch(...) {} return; } // Query resource Resource resource(digest); resource.fetch(); // this can take some time // Get range int64_t rangeBegin = 0; int64_t rangeEnd = 0; bool hasRange = request.extractRange(rangeBegin, rangeEnd, resource.size()); int64_t rangeSize = rangeEnd - rangeBegin + 1; // Get resource accessor Resource::Accessor *accessor = resource.accessor(); if(!accessor) throw 404; // Forge HTTP response header Http::Response response(request, 200); if(!hasRange) response.headers["Content-SHA512"] << resource.digest(); response.headers["Content-Length"] << rangeSize; response.headers["Content-Name"] = resource.name(); response.headers["Last-Modified"] = resource.time().toHttpDate(); response.headers["Accept-Ranges"] = "bytes"; String ext = resource.name().afterLast('.'); if(request.get.contains("download") || ext == "htm" || ext == "html" || ext == "xhtml") { response.headers["Content-Disposition"] = "attachment; filename=\"" + resource.name() + "\""; response.headers["Content-Type"] = "application/force-download"; } else { response.headers["Content-Disposition"] = "inline; filename=\"" + resource.name() + "\""; response.headers["Content-Type"] = Mime::GetType(resource.name()); } response.send(); if(request.method == "HEAD") return; try { // Launch transfer if(hasRange) accessor->seekRead(rangeBegin); int64_t size = accessor->readBinary(*response.sock, rangeSize); // let's go ! if(size != rangeSize) throw Exception("range size is " + String::number(rangeSize) + ", but sent size is " + String::number(size)); } catch(const NetException &e) { return; // nothing to do } catch(const Exception &e) { LogWarn("Interface::process", String("Error during file transfer: ") + e.what()); } return; } catch(const NetException &e) { return; // nothing to do } catch(const std::exception &e) { LogWarn("Interface::process", e.what()); throw 404; } } throw 404; } } <|endoftext|>
<commit_before>// Time: O(n * (C(2n, n) - C(2n, n - 1))) // Space: O(n^2 * (C(2n, n) - C(2n, n - 1))) class Solution { public: vector<int> diffWaysToCompute(string input) { vector<vector<vector<int>>> lookup(input.length() + 1, vector<vector<int>>(input.length() + 1, vector<int>())); return diffWaysToComputeRecu(input, 0, input.length(), lookup); } vector<int> diffWaysToComputeRecu(const string& input, const int start, const int end, vector<vector<vector<int>>>& lookup) { if (start == end) { return {}; } if (!lookup[start][end].empty()) { return lookup[start][end]; } vector<int> result; int i = start; while (i < end && !isOperator(input[i])) { ++i; } if (i == end) { result.emplace_back(move(stoi(input.substr(start, end - start)))); return result; } i = start; while (i < end) { while (i < end && !isOperator(input[i])) { ++i; } if (i < end) { vector<int> left = diffWaysToComputeRecu(input, start, i, lookup); vector<int> right = diffWaysToComputeRecu(input, i + 1, end, lookup); for (int j = 0; j < left.size(); ++j) { for(int k = 0; k < right.size(); ++k) { result.emplace_back(move(compute(input[i],left[j], right[k]))); } } } ++i; } lookup[start][end] = move(result); return lookup[start][end]; } bool isOperator(const char c){ return string("+-*").find(string(1, c)) != string::npos; } int compute(const char c, const int left, const int right){ switch (c) { case '+': return left + right; case '-': return left - right; case '*': return left * right; default: return 0; } return 0; } }; // Time: O(n^2 * (C(2n, n) - C(2n, n - 1))) // Space: O(C(2n, n) - C(2n, n - 1)) class Solution2 { public: vector<int> diffWaysToCompute(string input) { return diffWaysToComputeRecu(input, 0, input.length()); } vector<int> diffWaysToComputeRecu(const string& input, const int start, const int end) { if (start == end) { return {}; } vector<int> result; int i = start; while (i < end && !isOperator(input[i])) { ++i; } if (i == end) { result.emplace_back(move(stoi(input.substr(start, end - start)))); return result; } i = start; while (i < end) { while (i < end && !isOperator(input[i])) { ++i; } if (i < end) { vector<int> left = diffWaysToComputeRecu(input, start, i); vector<int> right = diffWaysToComputeRecu(input, i + 1, end); for (int j = 0; j < left.size(); ++j) { for(int k = 0; k < right.size(); ++k) { result.emplace_back(move(compute(input[i],left[j], right[k]))); } } } ++i; } return result; } bool isOperator(const char c){ return string("+-*").find(string(1, c)) != string::npos; } int compute(const char c, const int left, const int right){ switch (c) { case '+': return left + right; case '-': return left - right; case '*': return left * right; default: return 0; } return 0; } }; <commit_msg>Update different-ways-to-add-parentheses.cpp<commit_after>// Time: O(n * (C(2n, n) - C(2n, n - 1))) // Space: O(n^2 * (C(2n, n) - C(2n, n - 1))) class Solution { public: vector<int> diffWaysToCompute(string input) { vector<vector<vector<int>>> lookup(input.length() + 1, vector<vector<int>>(input.length() + 1, vector<int>())); return diffWaysToComputeRecu(input, 0, input.length(), lookup); } vector<int> diffWaysToComputeRecu(const string& input, const int start, const int end, vector<vector<vector<int>>>& lookup) { if (start == end) { return {}; } if (!lookup[start][end].empty()) { return lookup[start][end]; } vector<int> result; int i = start; while (i < end && !isOperator(input[i])) { ++i; } if (i == end) { result.emplace_back(move(stoi(input.substr(start, end - start)))); return result; } i = start; while (i < end) { while (i < end && !isOperator(input[i])) { ++i; } if (i < end) { vector<int> left = diffWaysToComputeRecu(input, start, i, lookup); vector<int> right = diffWaysToComputeRecu(input, i + 1, end, lookup); for (int j = 0; j < left.size(); ++j) { for(int k = 0; k < right.size(); ++k) { result.emplace_back(move(compute(input[i],left[j], right[k]))); } } } ++i; } lookup[start][end] = move(result); return lookup[start][end]; } bool isOperator(const char c){ return string("+-*").find(string(1, c)) != string::npos; } int compute(const char c, const int left, const int right){ switch (c) { case '+': return left + right; case '-': return left - right; case '*': return left * right; default: return 0; } return 0; } }; // Time: O(n^2 * (C(2n, n) - C(2n, n - 1))) // Space: O(C(2n, n) - C(2n, n - 1)) class Solution2 { public: vector<int> diffWaysToCompute(string input) { vector<int> result; for (int i = 0; i < input.size(); ++i) { char cur = input[i]; if (cur == '+' || cur == '-' || cur == '*') { vector<int> left = diffWaysToCompute(input.substr(0, i)); vector<int> right = diffWaysToCompute(input.substr(i + 1)); for (const auto& num1 : left) { for (const auto& num2 : right) { if (cur == '+') { result.emplace_back(num1 + num2); } else if (cur == '-') { result.emplace_back(num1 - num2); } else { result.emplace_back(num1 * num2); } } } } } // if the input string contains only number if (result.empty()) { result.emplace_back(stoi(input)); } return result; } }; <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #include <cstdio> #include <random> #if qPlatform_POSIX //@todo see how many of these includes are needed #include <unistd.h> #include <arpa/inet.h> #include <net/if.h> #include <netinet/in.h> #include <netdb.h> #include <sys/socket.h> #include <sys/ioctl.h> #if qPlatform_Linux #include <linux/types.h> // needed on RedHat5 #include <linux/ethtool.h> #include <linux/sockios.h> #endif #elif qPlatform_Windows #include <WinSock2.h> #include <WS2tcpip.h> #include <Iphlpapi.h> #include <netioapi.h> #endif #include "../../Characters/CString/Utilities.h" #include "../../Characters/Format.h" #include "../../Containers/Collection.h" #include "../../Containers/Mapping.h" #include "../../Execution/ErrNoException.h" #include "../../Execution/Finally.h" #if qPlatform_Windows #include "../../../Foundation/Execution/Platform/Windows/Exception.h" #endif #include "../../Execution/Synchronized.h" #include "../../Memory/SmallStackBuffer.h" #include "Socket.h" #include "Interface.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::Memory; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 #if defined (_MSC_VER) // support use of Iphlpapi - but better to reference here than in lib entry of project file cuz // easiser to see/modularize (and only pulled in if this module is referenced) #pragma comment (lib, "Iphlpapi.lib") #endif /* ******************************************************************************** **************************** Network::Interface ******************************** ******************************************************************************** */ const Configuration::EnumNames<Interface::Status> Interface::Stroika_Enum_Names(Status) { { Interface::Status::eConnected, L"Connected" }, { Interface::Status::eRunning, L"Running" }, }; const Configuration::EnumNames<Interface::Type> Interface::Stroika_Enum_Names(Type) { { Interface::Type::eLoopback, L"Loopback" }, { Interface::Type::eWiredEthernet, L"WiredEthernet" }, { Interface::Type::eWIFI, L"WIFI" }, { Interface::Type::eTunnel, L"Tunnel" }, { Interface::Type::eOther, L"Other" }, }; #if qPlatform_Linux // Hack for centos5 support: // Overload with linux version so other one wins, but this gets called if other doesnt exist // TRY --LGP 2015-05-19 template <typename HACK = int> static __inline__ __u32 ethtool_cmd_speed (const struct ethtool_cmd* ep, HACK i = 0) { //return (ep->speed_hi << 16) | ep->speed; return ep->speed; } #endif namespace { // Windows uses '-' as separator, and linux ':'. Pick arbitrarily (more linux machines // than windows, or soon will be) auto PrintMacAddr_ (const uint8_t* macaddrBytes, const uint8_t* macaddrBytesEnd) -> String { Require (macaddrBytesEnd - macaddrBytes == 6); char buf[100] {}; (void)snprintf (buf, sizeof (buf), "%02x:%02x:%02x:%02x:%02x:%02x", macaddrBytes[0], macaddrBytes[1], macaddrBytes[2], macaddrBytes[3], macaddrBytes[4], macaddrBytes[5] ); return String::FromAscii (buf); }; } /* ******************************************************************************** ************************** Network::GetInterfaces ****************************** ******************************************************************************** */ Traversal::Iterable<Interface> Network::GetInterfaces () { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Network::GetInterfaces"); #endif Collection<Interface> result; #if qPlatform_POSIX auto getFlags = [] (int sd, const char* name) { struct ifreq ifreq {}; Characters::CString::Copy (ifreq.ifr_name, NEltsOf (ifreq.ifr_name), name); int r = ::ioctl (sd, SIOCGIFFLAGS, (char*)&ifreq); Assert (r == 0); return ifreq.ifr_flags; }; struct ifreq ifreqs[128] {}; struct ifconf ifconf {}; ifconf.ifc_req = ifreqs; ifconf.ifc_len = sizeof(ifreqs); int sd = ::socket (PF_INET, SOCK_STREAM, 0); Assert (sd >= 0); Execution::Finally cleanup ([sd] () { ::close (sd); }); int r = ::ioctl (sd, SIOCGIFCONF, (char*)&ifconf); Assert (r == 0); for (int i = 0; i < ifconf.ifc_len / sizeof(struct ifreq); ++i) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace ("interface: ifr_name=%s; ifr_addr.sa_family = %d", ifreqs[i].ifr_name, ifreqs[i].ifr_addr.sa_family); #endif #if qPlatform_AIX // I don't understand the logic behind this, but without this, we get errors // in getFlags(). We could check there - and handle that with an extra return value, but this // is simpler. // // And - its somewhat prescribed in https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014698597 // if (ifreqs[i].ifr_addr.sa_family != AF_INET and ifreqs[i].ifr_addr.sa_family != AF_INET6 and ifreqs[i].ifr_addr.sa_family != AF_LINK) { // Skip interfaces not bound to and IPv4 or IPv6 address, or AF_LINK (not sure what later is used for) // this list of exceptions arrived at experimentally on the one AIX machine I tested (so not good) continue; } #endif Interface newInterface; String interfaceName { String::FromSDKString (ifreqs[i].ifr_name) }; newInterface.fInternalInterfaceID = interfaceName; newInterface.fFriendlyName = interfaceName; // not great - maybe find better name - but this will do for now... int flags = getFlags (sd, ifreqs[i].ifr_name); if (flags & IFF_LOOPBACK) { newInterface.fType = Interface::Type::eLoopback; } else { // NYI newInterface.fType = Interface::Type::eWiredEthernet; // WAY - not the right way to tell! } if (::ioctl (sd, SIOCGIFHWADDR, &ifr) == 0 and ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) { newInterface.fHwardwareAddress = PrintMacAddr_ (reinterpret_cast<const uint8_t*> (ifr.ifr_hwaddr.sa_data), reinterpret_cast<const uint8_t*> (ifr.ifr_hwaddr.sa_data) + 6); } #if qPlatform_AIX { auto getSpeed = [] (int sd, const char* name) -> Optional<uint64_t> { struct ifreq ifreq; (void)::memset (&ifreq, 0, sizeof (ifreq)); Characters::CString::Copy (ifreq.ifr_name, NEltsOf (ifreq.ifr_name), name); int r = ioctl (sd, SIOCGIFBAUDRATE, &ifreq); if (r != 0) { DbgTrace ("No speed for interface %s, errno=%d", name, errno); return Optional<uint64_t> (); } return ifreq.ifr_baudrate; }; newInterface.fTransmitSpeedBaud = getSpeed (sd, ifreqs[i].ifr_name); newInterface.fReceiveLinkSpeedBaud = newInterface.fTransmitSpeedBaud; } #elif qPlatform_Linux { auto getSpeed = [] (int sd, const char* name) -> Optional<uint64_t> { struct ifreq ifreq {}; Characters::CString::Copy (ifreq.ifr_name, NEltsOf (ifreq.ifr_name), name); struct ethtool_cmd edata {}; ifreq.ifr_data = reinterpret_cast<caddr_t> (&edata); edata.cmd = ETHTOOL_GSET; int r = ioctl(sd, SIOCETHTOOL, &ifreq); if (r != 0) { DbgTrace ("No speed for interface %s, errno=%d", name, errno); return Optional<uint64_t> (); } constexpr uint64_t kMegabit_ = 1000 * 1000; DbgTrace ("ethtool_cmd_speed (&edata)=%d", ethtool_cmd_speed (&edata)); switch (ethtool_cmd_speed (&edata)) { case SPEED_10: return 10 * kMegabit_; case SPEED_100: return 100 * kMegabit_; case SPEED_1000: return 1000 * kMegabit_; case SPEED_2500: return 2500 * kMegabit_; case SPEED_10000: return 10000 * kMegabit_; default: return Optional<uint64_t> (); } }; newInterface.fTransmitSpeedBaud = getSpeed (sd, ifreqs[i].ifr_name); newInterface.fReceiveLinkSpeedBaud = newInterface.fTransmitSpeedBaud; } #endif { Containers::Set<Interface::Status> status; if (flags & IFF_RUNNING) { // not right!!! But a start... status.Add (Interface::Status::eConnected); status.Add (Interface::Status::eRunning); } newInterface.fStatus = status; } newInterface.fBindings.Add (InternetAddress (((struct sockaddr_in*)&ifreqs[i].ifr_addr)->sin_addr)); // @todo fix so works for ipv6 addresses as well! result.Add (newInterface); } #elif qPlatform_Windows ULONG flags = GAA_FLAG_INCLUDE_PREFIX; ULONG family = AF_UNSPEC; // Both IPv4 and IPv6 addresses Memory::SmallStackBuffer<Byte> buf(0); Again: ULONG ulOutBufLen = static_cast<ULONG> (buf.GetSize ()); PIP_ADAPTER_ADDRESSES pAddresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES> (buf.begin ()); // NB: we use GetAdapaterAddresses () instead of GetInterfaceInfo () so we get non-ipv4 addresses DWORD dwRetVal = ::GetAdaptersAddresses (family, flags, nullptr, pAddresses, &ulOutBufLen); if (dwRetVal == NO_ERROR) { for (PIP_ADAPTER_ADDRESSES currAddresses = pAddresses; currAddresses != nullptr; currAddresses = currAddresses->Next) { Interface newInterface; String adapterName { String::FromNarrowSDKString (currAddresses->AdapterName) }; newInterface.fInternalInterfaceID = adapterName; newInterface.fFriendlyName = currAddresses->FriendlyName; newInterface.fDescription = currAddresses->Description; switch (currAddresses->IfType) { case IF_TYPE_SOFTWARE_LOOPBACK: newInterface.fType = Interface::Type::eLoopback; break; case IF_TYPE_IEEE80211: newInterface.fType = Interface::Type::eWIFI; break; case IF_TYPE_ETHERNET_CSMACD: newInterface.fType = Interface::Type::eWiredEthernet; break; default: newInterface.fType = Interface::Type::eOther; break; } if (currAddresses->TunnelType != TUNNEL_TYPE_NONE) { newInterface.fType = Interface::Type::eTunnel; } switch (currAddresses->OperStatus) { case IfOperStatusUp: newInterface.fStatus = Set<Interface::Status> ({Interface::Status::eConnected, Interface::Status::eRunning}); break; case IfOperStatusDown: newInterface.fStatus = Set<Interface::Status> (); break; default: // Dont know how to interpret the other status states break; } for (PIP_ADAPTER_UNICAST_ADDRESS pu = currAddresses->FirstUnicastAddress; pu != nullptr; pu = pu->Next) { SocketAddress sa { pu->Address }; if (sa.IsInternetAddress ()) { newInterface.fBindings.Add (sa.GetInternetAddress ()); } } for (PIP_ADAPTER_ANYCAST_ADDRESS pa = currAddresses->FirstAnycastAddress; pa != nullptr; pa = pa->Next) { SocketAddress sa { pa->Address }; if (sa.IsInternetAddress ()) { newInterface.fBindings.Add (sa.GetInternetAddress ()); } } for (PIP_ADAPTER_MULTICAST_ADDRESS pm = currAddresses->FirstMulticastAddress; pm != nullptr; pm = pm->Next) { SocketAddress sa { pm->Address }; if (sa.IsInternetAddress ()) { newInterface.fBindings.Add (sa.GetInternetAddress ()); } } if (currAddresses->PhysicalAddressLength == 6) { newInterface.fHwardwareAddress = PrintMacAddr_ (currAddresses->PhysicalAddress, currAddresses->PhysicalAddress + 6); } #if (NTDDI_VERSION >= NTDDI_WIN6) newInterface.fTransmitSpeedBaud = currAddresses->TransmitLinkSpeed; newInterface.fReceiveLinkSpeedBaud = currAddresses->ReceiveLinkSpeed; #endif result.Add (newInterface); } } else if (dwRetVal == ERROR_BUFFER_OVERFLOW) { buf.GrowToSize (ulOutBufLen); goto Again; } else if (dwRetVal == ERROR_NO_DATA) { DbgTrace ("There are no network adapters with IPv4 enabled on the local system"); } else { Execution::Platform::Windows::Exception::DoThrow (dwRetVal); } #else AssertNotImplemented (); #endif return result; } /* ******************************************************************************** ************************** Network::GetInterfaceById *************************** ******************************************************************************** */ Optional<Interface> Network::GetInterfaceById (const String& internalInterfaceID) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Network::GetInterfaceById"); #endif // @todo - a much more efficent implemenation - maybe good enuf to use caller staleness cache with a few seconds staleness for (Interface i : Network::GetInterfaces ()) { if (i.fInternalInterfaceID == internalInterfaceID) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"found interface %s", internalInterfaceID.c_str ()); #endif return i; } } #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"interface %s not found", internalInterfaceID.c_str ()); #endif return Optional<Interface> (); } <commit_msg>fixed newInterface.fHwardwareAddress for Unix<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #include <cstdio> #include <random> #if qPlatform_POSIX //@todo see how many of these includes are needed #include <unistd.h> #include <arpa/inet.h> #include <net/if.h> #include <netinet/in.h> #include <netdb.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if_arp.h> #if qPlatform_Linux #include <linux/types.h> // needed on RedHat5 #include <linux/ethtool.h> #include <linux/sockios.h> #endif #elif qPlatform_Windows #include <WinSock2.h> #include <WS2tcpip.h> #include <Iphlpapi.h> #include <netioapi.h> #endif #include "../../Characters/CString/Utilities.h" #include "../../Characters/Format.h" #include "../../Containers/Collection.h" #include "../../Containers/Mapping.h" #include "../../Execution/ErrNoException.h" #include "../../Execution/Finally.h" #if qPlatform_Windows #include "../../../Foundation/Execution/Platform/Windows/Exception.h" #endif #include "../../Execution/Synchronized.h" #include "../../Memory/SmallStackBuffer.h" #include "Socket.h" #include "Interface.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::Memory; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 #if defined (_MSC_VER) // support use of Iphlpapi - but better to reference here than in lib entry of project file cuz // easiser to see/modularize (and only pulled in if this module is referenced) #pragma comment (lib, "Iphlpapi.lib") #endif /* ******************************************************************************** **************************** Network::Interface ******************************** ******************************************************************************** */ const Configuration::EnumNames<Interface::Status> Interface::Stroika_Enum_Names(Status) { { Interface::Status::eConnected, L"Connected" }, { Interface::Status::eRunning, L"Running" }, }; const Configuration::EnumNames<Interface::Type> Interface::Stroika_Enum_Names(Type) { { Interface::Type::eLoopback, L"Loopback" }, { Interface::Type::eWiredEthernet, L"WiredEthernet" }, { Interface::Type::eWIFI, L"WIFI" }, { Interface::Type::eTunnel, L"Tunnel" }, { Interface::Type::eOther, L"Other" }, }; #if qPlatform_Linux // Hack for centos5 support: // Overload with linux version so other one wins, but this gets called if other doesnt exist // TRY --LGP 2015-05-19 template <typename HACK = int> static __inline__ __u32 ethtool_cmd_speed (const struct ethtool_cmd* ep, HACK i = 0) { //return (ep->speed_hi << 16) | ep->speed; return ep->speed; } #endif namespace { // Windows uses '-' as separator, and linux ':'. Pick arbitrarily (more linux machines // than windows, or soon will be) auto PrintMacAddr_ (const uint8_t* macaddrBytes, const uint8_t* macaddrBytesEnd) -> String { Require (macaddrBytesEnd - macaddrBytes == 6); char buf[100] {}; (void)snprintf (buf, sizeof (buf), "%02x:%02x:%02x:%02x:%02x:%02x", macaddrBytes[0], macaddrBytes[1], macaddrBytes[2], macaddrBytes[3], macaddrBytes[4], macaddrBytes[5] ); return String::FromAscii (buf); }; } /* ******************************************************************************** ************************** Network::GetInterfaces ****************************** ******************************************************************************** */ Traversal::Iterable<Interface> Network::GetInterfaces () { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Network::GetInterfaces"); #endif Collection<Interface> result; #if qPlatform_POSIX auto getFlags = [] (int sd, const char* name) { struct ifreq ifreq {}; Characters::CString::Copy (ifreq.ifr_name, NEltsOf (ifreq.ifr_name), name); int r = ::ioctl (sd, SIOCGIFFLAGS, (char*)&ifreq); Assert (r == 0); return ifreq.ifr_flags; }; struct ifreq ifreqs[128] {}; struct ifconf ifconf {}; ifconf.ifc_req = ifreqs; ifconf.ifc_len = sizeof(ifreqs); int sd = ::socket (PF_INET, SOCK_STREAM, 0); Assert (sd >= 0); Execution::Finally cleanup ([sd] () { ::close (sd); }); int r = ::ioctl (sd, SIOCGIFCONF, (char*)&ifconf); Assert (r == 0); for (int i = 0; i < ifconf.ifc_len / sizeof(struct ifreq); ++i) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace ("interface: ifr_name=%s; ifr_addr.sa_family = %d", ifreqs[i].ifr_name, ifreqs[i].ifr_addr.sa_family); #endif #if qPlatform_AIX // I don't understand the logic behind this, but without this, we get errors // in getFlags(). We could check there - and handle that with an extra return value, but this // is simpler. // // And - its somewhat prescribed in https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014698597 // if (ifreqs[i].ifr_addr.sa_family != AF_INET and ifreqs[i].ifr_addr.sa_family != AF_INET6 and ifreqs[i].ifr_addr.sa_family != AF_LINK) { // Skip interfaces not bound to and IPv4 or IPv6 address, or AF_LINK (not sure what later is used for) // this list of exceptions arrived at experimentally on the one AIX machine I tested (so not good) continue; } #endif Interface newInterface; String interfaceName { String::FromSDKString (ifreqs[i].ifr_name) }; newInterface.fInternalInterfaceID = interfaceName; newInterface.fFriendlyName = interfaceName; // not great - maybe find better name - but this will do for now... int flags = getFlags (sd, ifreqs[i].ifr_name); if (flags & IFF_LOOPBACK) { newInterface.fType = Interface::Type::eLoopback; } else { // NYI newInterface.fType = Interface::Type::eWiredEthernet; // WAY - not the right way to tell! } { ifreq tmp = ifreqs[i]; if (::ioctl (sd, SIOCGIFHWADDR, &tmp) == 0 and tmp.ifr_hwaddr.sa_family == ARPHRD_ETHER) { newInterface.fHwardwareAddress = PrintMacAddr_ (reinterpret_cast<const uint8_t*> (tmp.ifr_hwaddr.sa_data), reinterpret_cast<const uint8_t*> (tmp.ifr_hwaddr.sa_data) + 6); } } #if qPlatform_AIX { auto getSpeed = [] (int sd, const char* name) -> Optional<uint64_t> { struct ifreq ifreq; (void)::memset (&ifreq, 0, sizeof (ifreq)); Characters::CString::Copy (ifreq.ifr_name, NEltsOf (ifreq.ifr_name), name); int r = ioctl (sd, SIOCGIFBAUDRATE, &ifreq); if (r != 0) { DbgTrace ("No speed for interface %s, errno=%d", name, errno); return Optional<uint64_t> (); } return ifreq.ifr_baudrate; }; newInterface.fTransmitSpeedBaud = getSpeed (sd, ifreqs[i].ifr_name); newInterface.fReceiveLinkSpeedBaud = newInterface.fTransmitSpeedBaud; } #elif qPlatform_Linux { auto getSpeed = [] (int sd, const char* name) -> Optional<uint64_t> { struct ifreq ifreq {}; Characters::CString::Copy (ifreq.ifr_name, NEltsOf (ifreq.ifr_name), name); struct ethtool_cmd edata {}; ifreq.ifr_data = reinterpret_cast<caddr_t> (&edata); edata.cmd = ETHTOOL_GSET; int r = ioctl(sd, SIOCETHTOOL, &ifreq); if (r != 0) { DbgTrace ("No speed for interface %s, errno=%d", name, errno); return Optional<uint64_t> (); } constexpr uint64_t kMegabit_ = 1000 * 1000; DbgTrace ("ethtool_cmd_speed (&edata)=%d", ethtool_cmd_speed (&edata)); switch (ethtool_cmd_speed (&edata)) { case SPEED_10: return 10 * kMegabit_; case SPEED_100: return 100 * kMegabit_; case SPEED_1000: return 1000 * kMegabit_; case SPEED_2500: return 2500 * kMegabit_; case SPEED_10000: return 10000 * kMegabit_; default: return Optional<uint64_t> (); } }; newInterface.fTransmitSpeedBaud = getSpeed (sd, ifreqs[i].ifr_name); newInterface.fReceiveLinkSpeedBaud = newInterface.fTransmitSpeedBaud; } #endif { Containers::Set<Interface::Status> status; if (flags & IFF_RUNNING) { // not right!!! But a start... status.Add (Interface::Status::eConnected); status.Add (Interface::Status::eRunning); } newInterface.fStatus = status; } newInterface.fBindings.Add (InternetAddress (((struct sockaddr_in*)&ifreqs[i].ifr_addr)->sin_addr)); // @todo fix so works for ipv6 addresses as well! result.Add (newInterface); } #elif qPlatform_Windows ULONG flags = GAA_FLAG_INCLUDE_PREFIX; ULONG family = AF_UNSPEC; // Both IPv4 and IPv6 addresses Memory::SmallStackBuffer<Byte> buf(0); Again: ULONG ulOutBufLen = static_cast<ULONG> (buf.GetSize ()); PIP_ADAPTER_ADDRESSES pAddresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES> (buf.begin ()); // NB: we use GetAdapaterAddresses () instead of GetInterfaceInfo () so we get non-ipv4 addresses DWORD dwRetVal = ::GetAdaptersAddresses (family, flags, nullptr, pAddresses, &ulOutBufLen); if (dwRetVal == NO_ERROR) { for (PIP_ADAPTER_ADDRESSES currAddresses = pAddresses; currAddresses != nullptr; currAddresses = currAddresses->Next) { Interface newInterface; String adapterName { String::FromNarrowSDKString (currAddresses->AdapterName) }; newInterface.fInternalInterfaceID = adapterName; newInterface.fFriendlyName = currAddresses->FriendlyName; newInterface.fDescription = currAddresses->Description; switch (currAddresses->IfType) { case IF_TYPE_SOFTWARE_LOOPBACK: newInterface.fType = Interface::Type::eLoopback; break; case IF_TYPE_IEEE80211: newInterface.fType = Interface::Type::eWIFI; break; case IF_TYPE_ETHERNET_CSMACD: newInterface.fType = Interface::Type::eWiredEthernet; break; default: newInterface.fType = Interface::Type::eOther; break; } if (currAddresses->TunnelType != TUNNEL_TYPE_NONE) { newInterface.fType = Interface::Type::eTunnel; } switch (currAddresses->OperStatus) { case IfOperStatusUp: newInterface.fStatus = Set<Interface::Status> ({Interface::Status::eConnected, Interface::Status::eRunning}); break; case IfOperStatusDown: newInterface.fStatus = Set<Interface::Status> (); break; default: // Dont know how to interpret the other status states break; } for (PIP_ADAPTER_UNICAST_ADDRESS pu = currAddresses->FirstUnicastAddress; pu != nullptr; pu = pu->Next) { SocketAddress sa { pu->Address }; if (sa.IsInternetAddress ()) { newInterface.fBindings.Add (sa.GetInternetAddress ()); } } for (PIP_ADAPTER_ANYCAST_ADDRESS pa = currAddresses->FirstAnycastAddress; pa != nullptr; pa = pa->Next) { SocketAddress sa { pa->Address }; if (sa.IsInternetAddress ()) { newInterface.fBindings.Add (sa.GetInternetAddress ()); } } for (PIP_ADAPTER_MULTICAST_ADDRESS pm = currAddresses->FirstMulticastAddress; pm != nullptr; pm = pm->Next) { SocketAddress sa { pm->Address }; if (sa.IsInternetAddress ()) { newInterface.fBindings.Add (sa.GetInternetAddress ()); } } if (currAddresses->PhysicalAddressLength == 6) { newInterface.fHwardwareAddress = PrintMacAddr_ (currAddresses->PhysicalAddress, currAddresses->PhysicalAddress + 6); } #if (NTDDI_VERSION >= NTDDI_WIN6) newInterface.fTransmitSpeedBaud = currAddresses->TransmitLinkSpeed; newInterface.fReceiveLinkSpeedBaud = currAddresses->ReceiveLinkSpeed; #endif result.Add (newInterface); } } else if (dwRetVal == ERROR_BUFFER_OVERFLOW) { buf.GrowToSize (ulOutBufLen); goto Again; } else if (dwRetVal == ERROR_NO_DATA) { DbgTrace ("There are no network adapters with IPv4 enabled on the local system"); } else { Execution::Platform::Windows::Exception::DoThrow (dwRetVal); } #else AssertNotImplemented (); #endif return result; } /* ******************************************************************************** ************************** Network::GetInterfaceById *************************** ******************************************************************************** */ Optional<Interface> Network::GetInterfaceById (const String& internalInterfaceID) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Network::GetInterfaceById"); #endif // @todo - a much more efficent implemenation - maybe good enuf to use caller staleness cache with a few seconds staleness for (Interface i : Network::GetInterfaces ()) { if (i.fInternalInterfaceID == internalInterfaceID) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"found interface %s", internalInterfaceID.c_str ()); #endif return i; } } #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"interface %s not found", internalInterfaceID.c_str ()); #endif return Optional<Interface> (); } <|endoftext|>
<commit_before>/* * LuaSceneObject.cpp * * Created on: 27/05/2011 * Author: victor */ #include "LuaSceneObject.h" #include "SceneObject.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/cell/CellObject.h" #include "server/zone/packets/cell/UpdateCellPermissionsMessage.h" const char LuaSceneObject::className[] = "LuaSceneObject"; Luna<LuaSceneObject>::RegType LuaSceneObject::Register[] = { { "_setObject", &LuaSceneObject::_setObject }, { "getParent", &LuaSceneObject::getParent }, { "getObjectID", &LuaSceneObject::getObjectID }, { "getPositionX", &LuaSceneObject::getPositionX }, { "getPositionY", &LuaSceneObject::getPositionY }, { "getPositionZ", &LuaSceneObject::getPositionZ }, { "getParentID", &LuaSceneObject::getParentID }, { "isInRangeWithObject", &LuaSceneObject::isInRangeWithObject }, { "getDistanceTo", &LuaSceneObject::getDistanceTo }, { "updateDirection", &LuaSceneObject::updateDirection }, { "getServerObjectCRC", &LuaSceneObject::getServerObjectCRC }, { "showFlyText", &LuaSceneObject::showFlyText }, { "getContainerObject", &LuaSceneObject::getContainerObject }, { "getContainerObjectsSize", &LuaSceneObject::getContainerObjectsSize }, { "getSlottedObject", &LuaSceneObject::getSlottedObject }, { "transferObject", &LuaSceneObject::transferObject }, // { "removeObject", &LuaSceneObject::removeObject }, { "getGameObjectType", &LuaSceneObject::getGameObjectType }, { "faceObject", &LuaSceneObject::faceObject }, { "destroyObjectFromWorld", &LuaSceneObject::destroyObjectFromWorld }, { "isCreatureObject", &LuaSceneObject::isCreatureObject }, { "updateCellPermission", &LuaSceneObject::updateCellPermission }, { "sendTo", &LuaSceneObject::sendTo }, { "getCustomObjectName", &LuaSceneObject::getCustomObjectName }, { "getContainerObjectById", &LuaSceneObject::getContainerObjectById }, { "setDirectionalHeading", &LuaSceneObject::setDirectionalHeading }, { 0, 0 } }; LuaSceneObject::LuaSceneObject(lua_State *L) { realObject = (SceneObject*)lua_touserdata(L, 1); } LuaSceneObject::~LuaSceneObject(){ } int LuaSceneObject::_setObject(lua_State* L) { realObject = (SceneObject*)lua_touserdata(L, -1); return 0; } int LuaSceneObject::getPositionX(lua_State* L) { lua_pushnumber(L, realObject->getPositionX()); return 1; } int LuaSceneObject::getPositionZ(lua_State* L) { lua_pushnumber(L, realObject->getPositionZ()); return 1; } int LuaSceneObject::getPositionY(lua_State* L) { lua_pushnumber(L, realObject->getPositionY()); return 1; } int LuaSceneObject::getObjectID(lua_State* L) { lua_pushinteger(L, realObject->getObjectID()); return 1; } int LuaSceneObject::getParentID(lua_State* L) { lua_pushinteger(L, realObject->getParentID()); return 1; } int LuaSceneObject::isInRange(lua_State* L) { //public boolean isInRange(float x, float y, float range) { float range = lua_tonumber(L, -1); float y = lua_tonumber(L, -2); float x = lua_tonumber(L, -3); bool res = (static_cast<QuadTreeEntry*>(realObject))->isInRange(x, y, range); lua_pushnumber(L, res); return 1; } int LuaSceneObject::getGameObjectType(lua_State* L) { uint32 type = realObject->getGameObjectType(); lua_pushnumber(L, type); return 1; } int LuaSceneObject::getDistanceTo(lua_State* L) { SceneObject* obj = (SceneObject*)lua_touserdata(L, -1); float res = realObject->getDistanceTo(obj); lua_pushnumber(L, res); return 1; } int LuaSceneObject::getServerObjectCRC(lua_State* L) { uint32 crc = realObject->getServerObjectCRC(); lua_pushnumber(L, crc); return 1; } int LuaSceneObject::faceObject(lua_State* L) { SceneObject* obj = (SceneObject*)lua_touserdata(L, -1); realObject->faceObject(obj); return 0; } int LuaSceneObject::isInRangeWithObject(lua_State* L) { float range = lua_tonumber(L, -1); SceneObject* obj = (SceneObject*)lua_touserdata(L, -2); bool res = realObject->isInRange(obj, range); lua_pushnumber(L, res); return 1; } int LuaSceneObject::getParent(lua_State* L) { SceneObject* obj = realObject->getParent(); lua_pushlightuserdata(L, obj); return 1; } int LuaSceneObject::getContainerObject(lua_State* L) { int idx = lua_tonumber(L, -1); SceneObject* obj = realObject->getContainerObject(idx); lua_pushlightuserdata(L, obj); return 1; } int LuaSceneObject::getContainerObjectById(lua_State* L) { uint64 objectID = lua_tointeger(L, -1); SceneObject* obj = realObject->getContainerObject(objectID); lua_pushlightuserdata(L, obj); return 1; } int LuaSceneObject::getSlottedObject(lua_State* L) { String slot = lua_tostring(L, -1); SceneObject* obj = realObject->getSlottedObject(slot); lua_pushlightuserdata(L, obj); return 1; } int LuaSceneObject::transferObject(lua_State* L) { //transferObject(SceneObject object, int containmentType, boolean notifyClient = false); bool notifyClient = lua_tonumber(L, -1); int containmentType = lua_tonumber(L, -2); SceneObject* obj = (SceneObject*) lua_touserdata(L, -3); realObject->transferObject(obj, containmentType, notifyClient); return 0; } /*int LuaSceneObject::removeObject(lua_State* L) { //removeObject(SceneObject object, boolean notifyClient = false); bool notifyClient = lua_tonumber(L, -1); SceneObject* obj = (SceneObject*) lua_touserdata(L, -2); realObject->removeObject(obj, notifyClient); return 0; }*/ int LuaSceneObject::getContainerObjectsSize(lua_State* L) { int num = realObject->getContainerObjectsSize(); lua_pushnumber(L, num); return 1; } int LuaSceneObject::showFlyText(lua_State* L) { //final string file, final string uax, byte red, byte green, byte blue byte blue = lua_tonumber(L, -1); byte green = lua_tonumber(L, -2); byte red = lua_tonumber(L, -3); String aux = lua_tostring(L, -4); String file = lua_tostring(L, -5); realObject->showFlyText(file, aux, red, green, blue); return 0; } int LuaSceneObject::updateDirection(lua_State* L) { //void updateDirection(float fw, float fx, float fy, float fz); float fz = lua_tonumber(L, -1); float fy = lua_tonumber(L, -2); float fx = lua_tonumber(L, -3); float fw = lua_tonumber(L, -4); realObject->updateDirection(fw, fx, fy, fz); return 0; } int LuaSceneObject::destroyObjectFromWorld(lua_State* L) { realObject->destroyObjectFromWorld(true); return 0; } int LuaSceneObject::isCreatureObject(lua_State* L) { bool val = realObject->isCreatureObject(); lua_pushboolean(L, val); return 1; } int LuaSceneObject::updateCellPermission(lua_State* L) { //realObject->info("getting values",true); int allowEntry = lua_tonumber(L, -2); CreatureObject* obj = (CreatureObject*)lua_touserdata(L, -1); //realObject->info("allowentry:" + String::valueOf(allowEntry), true); if (obj == NULL) return 0; //realObject->info("values not NULL", true); if (!realObject->isCellObject()) { realObject->info("Unknown entity error: Cell", true); return 0; } if (!obj->isCreatureObject()) { //realObject->info("Unknown entity error: Creature", true); obj->info("Unknown entity error: Creature", true); return 0; } //realObject->info("checks are fine", true); BaseMessage* perm = new UpdateCellPermissionsMessage(realObject->getObjectID(), allowEntry); obj->sendMessage(perm); return 0; } int LuaSceneObject::wlock(lua_State* L) { return 0; } int LuaSceneObject::unlock(lua_State* L) { return 0; } int LuaSceneObject::sendTo(lua_State* L) { SceneObject* obj = (SceneObject*) lua_touserdata(L, -1); realObject->sendTo(obj, true); return 0; } int LuaSceneObject::getCustomObjectName(lua_State* L) { String objname = realObject->getCustomObjectName().toString(); lua_pushstring(L, objname); return 1; } int LuaSceneObject::setDirectionalHeading(lua_State* L) { int heading = lua_tointeger(L, -1); SceneObject* obj = (SceneObject*) lua_touserdata(L, -2); realObject->setDirection(heading); return 0; } <commit_msg>[fixed] Hopefully fixes a lua issue that crashes when Sith Altar is missing from inventory.<commit_after>/* * LuaSceneObject.cpp * * Created on: 27/05/2011 * Author: victor */ #include "LuaSceneObject.h" #include "SceneObject.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/cell/CellObject.h" #include "server/zone/packets/cell/UpdateCellPermissionsMessage.h" const char LuaSceneObject::className[] = "LuaSceneObject"; Luna<LuaSceneObject>::RegType LuaSceneObject::Register[] = { { "_setObject", &LuaSceneObject::_setObject }, { "getParent", &LuaSceneObject::getParent }, { "getObjectID", &LuaSceneObject::getObjectID }, { "getPositionX", &LuaSceneObject::getPositionX }, { "getPositionY", &LuaSceneObject::getPositionY }, { "getPositionZ", &LuaSceneObject::getPositionZ }, { "getParentID", &LuaSceneObject::getParentID }, { "isInRangeWithObject", &LuaSceneObject::isInRangeWithObject }, { "getDistanceTo", &LuaSceneObject::getDistanceTo }, { "updateDirection", &LuaSceneObject::updateDirection }, { "getServerObjectCRC", &LuaSceneObject::getServerObjectCRC }, { "showFlyText", &LuaSceneObject::showFlyText }, { "getContainerObject", &LuaSceneObject::getContainerObject }, { "getContainerObjectsSize", &LuaSceneObject::getContainerObjectsSize }, { "getSlottedObject", &LuaSceneObject::getSlottedObject }, { "transferObject", &LuaSceneObject::transferObject }, // { "removeObject", &LuaSceneObject::removeObject }, { "getGameObjectType", &LuaSceneObject::getGameObjectType }, { "faceObject", &LuaSceneObject::faceObject }, { "destroyObjectFromWorld", &LuaSceneObject::destroyObjectFromWorld }, { "isCreatureObject", &LuaSceneObject::isCreatureObject }, { "updateCellPermission", &LuaSceneObject::updateCellPermission }, { "sendTo", &LuaSceneObject::sendTo }, { "getCustomObjectName", &LuaSceneObject::getCustomObjectName }, { "getContainerObjectById", &LuaSceneObject::getContainerObjectById }, { "setDirectionalHeading", &LuaSceneObject::setDirectionalHeading }, { 0, 0 } }; LuaSceneObject::LuaSceneObject(lua_State *L) { realObject = (SceneObject*)lua_touserdata(L, 1); } LuaSceneObject::~LuaSceneObject(){ } int LuaSceneObject::_setObject(lua_State* L) { realObject = (SceneObject*)lua_touserdata(L, -1); return 0; } int LuaSceneObject::getPositionX(lua_State* L) { lua_pushnumber(L, realObject->getPositionX()); return 1; } int LuaSceneObject::getPositionZ(lua_State* L) { lua_pushnumber(L, realObject->getPositionZ()); return 1; } int LuaSceneObject::getPositionY(lua_State* L) { lua_pushnumber(L, realObject->getPositionY()); return 1; } int LuaSceneObject::getObjectID(lua_State* L) { lua_pushinteger(L, realObject->getObjectID()); return 1; } int LuaSceneObject::getParentID(lua_State* L) { lua_pushinteger(L, realObject->getParentID()); return 1; } int LuaSceneObject::isInRange(lua_State* L) { //public boolean isInRange(float x, float y, float range) { float range = lua_tonumber(L, -1); float y = lua_tonumber(L, -2); float x = lua_tonumber(L, -3); bool res = (static_cast<QuadTreeEntry*>(realObject))->isInRange(x, y, range); lua_pushnumber(L, res); return 1; } int LuaSceneObject::getGameObjectType(lua_State* L) { uint32 type = realObject->getGameObjectType(); lua_pushnumber(L, type); return 1; } int LuaSceneObject::getDistanceTo(lua_State* L) { SceneObject* obj = (SceneObject*)lua_touserdata(L, -1); float res = realObject->getDistanceTo(obj); lua_pushnumber(L, res); return 1; } int LuaSceneObject::getServerObjectCRC(lua_State* L) { uint32 crc = realObject->getServerObjectCRC(); lua_pushnumber(L, crc); return 1; } int LuaSceneObject::faceObject(lua_State* L) { SceneObject* obj = (SceneObject*)lua_touserdata(L, -1); realObject->faceObject(obj); return 0; } int LuaSceneObject::isInRangeWithObject(lua_State* L) { float range = lua_tonumber(L, -1); SceneObject* obj = (SceneObject*)lua_touserdata(L, -2); bool res = realObject->isInRange(obj, range); lua_pushnumber(L, res); return 1; } int LuaSceneObject::getParent(lua_State* L) { SceneObject* obj = realObject->getParent(); lua_pushlightuserdata(L, obj); return 1; } int LuaSceneObject::getContainerObject(lua_State* L) { int idx = lua_tonumber(L, -1); SceneObject* obj = realObject->getContainerObject(idx); lua_pushlightuserdata(L, obj); return 1; } int LuaSceneObject::getContainerObjectById(lua_State* L) { uint64 objectID = lua_tointeger(L, -1); SceneObject* obj = realObject->getContainerObject(objectID); if (obj != NULL) { lua_pushlightuserdata(L, obj); } else { lua_pushnil(L); } return 1; } int LuaSceneObject::getSlottedObject(lua_State* L) { String slot = lua_tostring(L, -1); SceneObject* obj = realObject->getSlottedObject(slot); lua_pushlightuserdata(L, obj); return 1; } int LuaSceneObject::transferObject(lua_State* L) { //transferObject(SceneObject object, int containmentType, boolean notifyClient = false); bool notifyClient = lua_tonumber(L, -1); int containmentType = lua_tonumber(L, -2); SceneObject* obj = (SceneObject*) lua_touserdata(L, -3); realObject->transferObject(obj, containmentType, notifyClient); return 0; } /*int LuaSceneObject::removeObject(lua_State* L) { //removeObject(SceneObject object, boolean notifyClient = false); bool notifyClient = lua_tonumber(L, -1); SceneObject* obj = (SceneObject*) lua_touserdata(L, -2); realObject->removeObject(obj, notifyClient); return 0; }*/ int LuaSceneObject::getContainerObjectsSize(lua_State* L) { int num = realObject->getContainerObjectsSize(); lua_pushnumber(L, num); return 1; } int LuaSceneObject::showFlyText(lua_State* L) { //final string file, final string uax, byte red, byte green, byte blue byte blue = lua_tonumber(L, -1); byte green = lua_tonumber(L, -2); byte red = lua_tonumber(L, -3); String aux = lua_tostring(L, -4); String file = lua_tostring(L, -5); realObject->showFlyText(file, aux, red, green, blue); return 0; } int LuaSceneObject::updateDirection(lua_State* L) { //void updateDirection(float fw, float fx, float fy, float fz); float fz = lua_tonumber(L, -1); float fy = lua_tonumber(L, -2); float fx = lua_tonumber(L, -3); float fw = lua_tonumber(L, -4); realObject->updateDirection(fw, fx, fy, fz); return 0; } int LuaSceneObject::destroyObjectFromWorld(lua_State* L) { realObject->destroyObjectFromWorld(true); return 0; } int LuaSceneObject::isCreatureObject(lua_State* L) { bool val = realObject->isCreatureObject(); lua_pushboolean(L, val); return 1; } int LuaSceneObject::updateCellPermission(lua_State* L) { //realObject->info("getting values",true); int allowEntry = lua_tonumber(L, -2); CreatureObject* obj = (CreatureObject*)lua_touserdata(L, -1); //realObject->info("allowentry:" + String::valueOf(allowEntry), true); if (obj == NULL) return 0; //realObject->info("values not NULL", true); if (!realObject->isCellObject()) { realObject->info("Unknown entity error: Cell", true); return 0; } if (!obj->isCreatureObject()) { //realObject->info("Unknown entity error: Creature", true); obj->info("Unknown entity error: Creature", true); return 0; } //realObject->info("checks are fine", true); BaseMessage* perm = new UpdateCellPermissionsMessage(realObject->getObjectID(), allowEntry); obj->sendMessage(perm); return 0; } int LuaSceneObject::wlock(lua_State* L) { return 0; } int LuaSceneObject::unlock(lua_State* L) { return 0; } int LuaSceneObject::sendTo(lua_State* L) { SceneObject* obj = (SceneObject*) lua_touserdata(L, -1); realObject->sendTo(obj, true); return 0; } int LuaSceneObject::getCustomObjectName(lua_State* L) { String objname = realObject->getCustomObjectName().toString(); lua_pushstring(L, objname); return 1; } int LuaSceneObject::setDirectionalHeading(lua_State* L) { int heading = lua_tointeger(L, -1); SceneObject* obj = (SceneObject*) lua_touserdata(L, -2); realObject->setDirection(heading); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbVectorImage.h" #include "itkVector.h" #include "otbImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbStreamingWarpImageFilter.h" // Images definition const unsigned int Dimension = 2; typedef double PixelType; typedef otb::Image<PixelType, Dimension> ImageType; typedef itk::Vector<PixelType, 2> DisplacementValueType; typedef otb::Image<DisplacementValueType, Dimension> DisplacementFieldType; // Warper typedef otb::StreamingWarpImageFilter<ImageType, ImageType, DisplacementFieldType> ImageWarperType; int otbStreamingWarpImageFilter(int argc, char* argv[]) { if (argc != 5) { std::cout << "usage: " << argv[0] << "infname deffname outfname radius" << std::endl; return EXIT_SUCCESS; } // Input parameters const char * infname = argv[1]; const char * deffname = argv[2]; const char * outfname = argv[3]; const double maxdef = atoi(argv[4]); // Change default output origin ImageType::PointType origin; origin.Fill(0.5); // Reader/Writer typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileReader<DisplacementFieldType> DisplacementReaderType; typedef otb::ImageFileWriter<ImageType> WriterType; // Objects creation DisplacementReaderType::Pointer displacementReader = DisplacementReaderType::New(); ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); ImageWarperType::Pointer warper = ImageWarperType::New(); // Reading reader->SetFileName(infname); displacementReader->SetFileName(deffname); // Warping DisplacementValueType maxDisplacement; maxDisplacement.Fill(maxdef); warper->SetMaximumDisplacement(maxDisplacement); warper->SetInput(reader->GetOutput()); warper->SetDisplacementField(displacementReader->GetOutput()); warper->SetOutputOrigin(origin); // Writing writer->SetInput(warper->GetOutput()); writer->SetFileName(outfname); writer->Update(); return EXIT_SUCCESS; } int otbStreamingWarpImageFilterEmptyRegion(int, const char**) { ImageType:: Pointer inputPtr = ImageType::New(); ImageType::RegionType largestRegion; ImageType::SizeType largestSize = {{10,10}}; ImageType::IndexType largestIndex = {{1,1}}; largestRegion.SetIndex(largestIndex); largestRegion.SetSize(largestSize); inputPtr->SetRegions(largestRegion); ImageType::RegionType emptyRegion; ImageType::SizeType emptySize = {{0,0}}; ImageType::IndexType emptyIndex = {{0,0}}; emptyRegion.SetSize(emptySize); emptyRegion.SetIndex(emptyIndex); inputPtr->SetRequestedRegion(emptyRegion); inputPtr->SetBufferedRegion(emptyRegion); DisplacementFieldType::Pointer dispPtr = DisplacementFieldType::New(); dispPtr->SetRegions(largestRegion); dispPtr->Allocate(); DisplacementValueType v; v[0]=-100; v[1]=-100; dispPtr->FillBuffer(v); ImageWarperType::Pointer warper = ImageWarperType::New(); warper->SetDisplacementField(dispPtr); warper->SetInput(inputPtr); ImageType::PointType outputOrigin; outputOrigin.Fill(0); warper->SetOutputOrigin(outputOrigin); // requested region for full output is completely outside largest // possible region of input warper->GetOutput()->UpdateOutputInformation(); // Before bugfix this would lead to famous ITK exception outside of // largest possible region warper->GetOutput()->PropagateRequestedRegion(); // After requested region has been propagated, we need to be sure // that requested region can be cropped by largest region auto requestedRegion = inputPtr->GetRequestedRegion(); if (! requestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) { std::cerr<<"Requested region can not be cropped by largest region"<<std::endl; return EXIT_FAILURE; } // And we also need to check that requested region is not largest // region if( inputPtr->GetRequestedRegion().GetNumberOfPixels() != 0) { std::cerr<<"Requested region should have {{0, 0}} size"<<std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>COMP: attempt to fix windows builds 2/2<commit_after>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbVectorImage.h" #include "itkVector.h" #include "otbImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbStreamingWarpImageFilter.h" // Images definition const unsigned int Dimension = 2; typedef double PixelType; typedef otb::Image<PixelType, Dimension> ImageType; typedef itk::Vector<PixelType, 2> DisplacementValueType; typedef otb::Image<DisplacementValueType, Dimension> DisplacementFieldType; // Warper typedef otb::StreamingWarpImageFilter<ImageType, ImageType, DisplacementFieldType> ImageWarperType; int otbStreamingWarpImageFilter(int argc, char* argv[]) { if (argc != 5) { std::cout << "usage: " << argv[0] << "infname deffname outfname radius" << std::endl; return EXIT_SUCCESS; } // Input parameters const char * infname = argv[1]; const char * deffname = argv[2]; const char * outfname = argv[3]; const double maxdef = atoi(argv[4]); // Change default output origin ImageType::PointType origin; origin.Fill(0.5); // Reader/Writer typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileReader<DisplacementFieldType> DisplacementReaderType; typedef otb::ImageFileWriter<ImageType> WriterType; // Objects creation DisplacementReaderType::Pointer displacementReader = DisplacementReaderType::New(); ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); ImageWarperType::Pointer warper = ImageWarperType::New(); // Reading reader->SetFileName(infname); displacementReader->SetFileName(deffname); // Warping DisplacementValueType maxDisplacement; maxDisplacement.Fill(maxdef); warper->SetMaximumDisplacement(maxDisplacement); warper->SetInput(reader->GetOutput()); warper->SetDisplacementField(displacementReader->GetOutput()); warper->SetOutputOrigin(origin); // Writing writer->SetInput(warper->GetOutput()); writer->SetFileName(outfname); writer->Update(); return EXIT_SUCCESS; } int otbStreamingWarpImageFilterEmptyRegion(int itkNotUsed(argc), char* itkNotUsed(argv)[]) { ImageType:: Pointer inputPtr = ImageType::New(); ImageType::RegionType largestRegion; ImageType::SizeType largestSize = {{10,10}}; ImageType::IndexType largestIndex = {{1,1}}; largestRegion.SetIndex(largestIndex); largestRegion.SetSize(largestSize); inputPtr->SetRegions(largestRegion); ImageType::RegionType emptyRegion; ImageType::SizeType emptySize = {{0,0}}; ImageType::IndexType emptyIndex = {{0,0}}; emptyRegion.SetSize(emptySize); emptyRegion.SetIndex(emptyIndex); inputPtr->SetRequestedRegion(emptyRegion); inputPtr->SetBufferedRegion(emptyRegion); DisplacementFieldType::Pointer dispPtr = DisplacementFieldType::New(); dispPtr->SetRegions(largestRegion); dispPtr->Allocate(); DisplacementValueType v; v[0]=-100; v[1]=-100; dispPtr->FillBuffer(v); ImageWarperType::Pointer warper = ImageWarperType::New(); warper->SetDisplacementField(dispPtr); warper->SetInput(inputPtr); ImageType::PointType outputOrigin; outputOrigin.Fill(0); warper->SetOutputOrigin(outputOrigin); // requested region for full output is completely outside largest // possible region of input warper->GetOutput()->UpdateOutputInformation(); // Before bugfix this would lead to famous ITK exception outside of // largest possible region warper->GetOutput()->PropagateRequestedRegion(); // After requested region has been propagated, we need to be sure // that requested region can be cropped by largest region auto requestedRegion = inputPtr->GetRequestedRegion(); if (! requestedRegion.Crop(inputPtr->GetLargestPossibleRegion()) ) { std::cerr<<"Requested region can not be cropped by largest region"<<std::endl; return EXIT_FAILURE; } // And we also need to check that requested region is not largest // region if( inputPtr->GetRequestedRegion().GetNumberOfPixels() != 0) { std::cerr<<"Requested region should have {{0, 0}} size"<<std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// CommonFunc.cpp -- source file /* * Author: Ivan Chapkailo (septimomend) * Date: 02.07.2017 * * Β© 2017 Ivan Chapkailo. All rights reserved * e-mail: [email protected] */ #include "stdafx.h" #include "CommonFunc.h" Common::Common() { m_All = tml.getAllControllerObj(); m_pCnfg = m_All->getConfigObj(); } Common::Common(AllControllers* all) : m_pCnfg(all->getConfigObj()) { } void Common::openFile(char *filename) { free(m_pCnfg->pFilename); // free pFilename becouse strdup uses malloc and in next func // call need to free memory m_pCnfg->pFilename = strdup(filename); // duplicate filename to pFilename m_All->pickSyntaxClr(); FILE* fln = fopen(filename, "r"); // open file foe reading if (!fln) // if can't to open file tml.emergencyDestruction("fopen"); // forced closure char* pStr = NULL; size_t strUSZ = 0; // size ssize_t strSSZ; // signed size while ((strSSZ = getline(&pStr, &strUSZ, fln)) != -1) // while strUSZ size of pStr that reads from file fp { while (strSSZ > 0 && (pStr[strSSZ - 1] == '\n' || pStr[strSSZ - 1] == '\r')) // if this is end of line strSSZ--; // decrease line size m_pCnfg->setRow(m_pCnfg->rowCount, pStr, strSSZ); // set rows from file } free(pStr); fclose(fln); // close file m_pCnfg->smear = 0; // no changes in now opened file } void detectCallback(char* query, int key) { // TODO } void Common::save() { // TODO } void Common::find() { // TODO } void Common::drawRows(Adbfr* abfr); { // TODO } void Common::drawStatusBar(Adbfr* abfr) { // TODO } void Common::drawMessageBar(Adbfr* abfr) { // TODO } void Common::scrolling() { // TODO } void Common::statusMsg(const char *fmt, ...) { va_list arg; // for unknown number of parameters va_start(arg, fmt); // initialize arg vsnprintf(cnfg.statusMessage, sizeof(cnfg.statusMessage), fmt, arg); // output parameters to statusMessage va_end(arg); // end cnfg.statusMessageTime = time(NULL); // gets time } void Common::updateScreen() { scrolling(); m_abfr = ADBFR_IMPL; // implement to NULL m_abfr.reallocateBfr("\x1b[?25l", 6); // reallocate data m_abfr.reallocateBfr("\x1b[H", 3); // reallocate data /* * draw rows, message bar and status bar */ drawRows(&m_abfr); drawStatusBar(&m_abfr); drawMessageBar(&m_abfr); /* * write to buff cursor | position */ char buff[32]; snprintf(buff, sizeof(buff), "\x1b[%d;%dH", (m_pCnfg->configY - m_pCnfg->disableRow) + 1, (m_pCnfg->rowX - m_pCnfg->disableClr) + 1); m_abfr.reallocateBfr(buff, strlen(buff)); m_abfr.reallocateBfr("\x1b[?25h", 6); /* * update screen */ write(STDOUT_FILENO, ab.b, ab.len); m_abfr.freeBfr(); // free memory } char* Common::callPrompt(char *prompt, void (*callback)(char*, int)) { size_t buffsize = 128; char* bfr = malloc(buffsize); // allocate memory size_t bufflen = 0; // lenght bfr[0] = '\0'; while (1) { statusMsg(prompt, bfr); // set prompt updateScreen(); // and update screen int key = tml.whatKey(); // read key if (key == DELETE_KEY || key == CTRL_KEY('h') || key == BACKSPACE) { if (bufflen != 0) // if buffer is not empty bfr[--bufflen] = '\0'; // set end of row } else if (key == '\x1b') // if this is ESC { statusMsg(""); // erase if (callback) // if callback is not NULL callback(bfr, key); // call func for callback which pointed by callback() free(bfr); // free memory return NULL; // and cancel } else if (key == '\r') // if carriage return (move the cursor at the start of the line) { if (bufflen != 0) // and bufflen is not empty { statusMsg(""); // clean message if (callback) callback(bfr, key); // and get callback return bfr; // returning of buffer } } else if (!iscntrl(key) && key < 128) // checks, whether the argument, transmitted via the parameter сharacter, control character { /* * reallocation of buffer if needs */ if (bufflen == buffsize - 1) { buffsize *= 2; bfr = realloc(bfr, buffsize); } bfr[bufflen++] = key; // write this key to buffer bfr[bufflen] = '\0'; // and end of row } if (callback) callback(bfr, key); // call of callback } } void Common::moveCursor(int key) { // instancing RowController // if empty - to zero position, else to the end of row // RowController* pRowctrl = (m_pCnfg->configY >= m_pCnfg->rowCount) ? NULL : &m_pCnfg->pRowObj[m_pCnfg->configY]; switch (key) { case ARROW_LEFT: if (m_pCnfg->configX != 0) // if horizontal position isn't zero { m_pCnfg->configX--; // move left } else if (m_pCnfg->configY > 0) // else if there is at least 1 row { m_pCnfg->configY--; // move to that row m_pCnfg->configX = m_pCnfg->pRowObj[m_pCnfg->configY].size; // and to the end of that row } break; case ARROW_RIGHT: if (pRowctrl && m_pCnfg->configX < pRowctrl->size) // if there is row and if cursor is not in the end of row { m_pCnfg->configX++; // move cursor right along of row } else if (pRowctrl && m_pCnfg->configX == pRowctrl->size) // if there is row and cursor in the end of this row { m_pCnfg->configY++; // move to next row E.cx = 0; // on zero position } break; case ARROW_UP: if (m_pCnfg->configY != 0) // if there is at least 1 row { m_pCnfg->configY--; // move up } break; case ARROW_DOWN: if (m_pCnfg->configY < m_pCnfg->rowCount) // if cursor is not on last row { m_pCnfg->configY++; // move down } break; } } void Common::processingKeypress() { static int sQuitCounter = EDITORRMEND_QUIT_COUNTER; // counter clicking for exit int key = whatKey(); // read key switch (key) { case '\r': // if carriage return (Enter key) setNewline(); // set newline break; case CTRL_KEY('q'): if (m_pCnfg->smear && sQuitCounter > 0) // if there is any changes and counter > 0 { statusMsg("! File was changed and unsaved and data can be lost after exiting. " "Press Ctrl-Q %d more times to exit.", sQuitCounter); sQuitCounter--; // counter decrement return; } write(STDOUT_FILENO, "\x1b[2J", 4); write(STDOUT_FILENO, "\x1b[H", 3); exit(0); break; case CTRL_KEY('s'): save(); // TODO: save changes break; case HOME_KEY: m_pCnfg->configX = 0; // to the row beginning break; case END_KEY: if (m_pCnfg->configY < m_pCnfg->rowCount) // if not last row m_pCnfg->configX = m_pCnfg->pRowObj[m_pCnfg->configY].size; // to the end of row break; case CTRL_KEY('f'): find(); // find func break; case BACKSPACE: case CTRL_KEY('h'): case DELETE_KEY: if (key == DELETE_KEY) moveCursor(ARROW_RIGHT); // move cursor right deleteChar(); // delete char break; // page up/down // case PAGE_UP: case PAGE_DOWN: { if (key == PAGE_UP) { m_pCnfg->configY = m_pCnfg->disableRow; // move page up } else if (key == PAGE_DOWN) { m_pCnfg->configY = m_pCnfg->disableRow + m_pCnfg->enableRow - 1; // move page down if (m_pCnfg->configY > m_pCnfg->rowCount) m_pCnfg->configY = m_pCnfg->rowCount; } int times = m_pCnfg->enableRow; while (times--) moveCursor(key == PAGE_UP ? ARROW_UP : ARROW_DOWN); } break; case ARROW_UP: case ARROW_DOWN: case ARROW_LEFT: case ARROW_RIGHT: moveCursor(key); break; case CTRL_KEY('l'): case '\x1b': break; default: setChar(key); // just write chars break; } sQuitCounter = EDITORRMEND_QUIT_COUNTER; } <commit_msg>implemented saving function<commit_after>// CommonFunc.cpp -- source file /* * Author: Ivan Chapkailo (septimomend) * Date: 02.07.2017 * * Β© 2017 Ivan Chapkailo. All rights reserved * e-mail: [email protected] */ #include "stdafx.h" #include "CommonFunc.h" Common::Common() { m_pAll = tml.getAllControllerObj(); m_pCnfg = m_pAll->getConfigObj(); } Common::Common(AllControllers* all) : m_pCnfg(all->getConfigObj()) { } void Common::openFile(char *filename) { free(m_pCnfg->pFilename); // free pFilename becouse strdup uses malloc and in next func // call need to free memory m_pCnfg->pFilename = strdup(filename); // duplicate filename to pFilename m_pAll->pickSyntaxClr(); FILE* fln = fopen(filename, "r"); // open file foe reading if (!fln) // if can't to open file tml.emergencyDestruction("fopen"); // forced closure char* pStr = NULL; size_t strUSZ = 0; // size ssize_t strSSZ; // signed size while ((strSSZ = getline(&pStr, &strUSZ, fln)) != -1) // while strUSZ size of pStr that reads from file fp { while (strSSZ > 0 && (pStr[strSSZ - 1] == '\n' || pStr[strSSZ - 1] == '\r')) // if this is end of line strSSZ--; // decrease line size m_pCnfg->setRow(m_pCnfg->rowCount, pStr, strSSZ); // set rows from file } free(pStr); fclose(fln); // close file m_pCnfg->smear = 0; // no changes in now opened file } void detectCallback(char* query, int key) { // TODO } void Common::save() { if (m_pCnfg->pFilename == NULL) // if no falename { m_pCnfg->pFilename = callPrompt("Save as: %s (ESC - cancel)", NULL); // set message if (m_pCnfg->pFilename == NULL) // if filename still is not { statusMsg("Saving operation is canceled"); // lead out status message about cancelling return; // and go out of save function } m_pAll->pickSyntaxClr(); // colorize text in dependence of filename extension } size_t sz; char *pBuff = m_pCnfg->row2Str(&sz); // get strings and size of these int fd = open(m_pCnfg->pFilename, O_RDWR | O_CREAT, 0644); // open the file for read/write and if the file does not exist, it will be created // 0644 - look here: https://stackoverflow.com/questions/18415904/what-does-mode-t-0644-mean if (fd != -1) { if (ftruncate(fd, sz) != -1) // set file size { if (write(fd, pBuff, sz) == sz) // if writing from buffer to file is success { close(fd); // close free(pBuff); // free memory m_pCnfg->smear = 0; // no changes in syntax after copying to file statusMsg("%d bytes is written successfully", sz); // set status message return; // go out } } close(fd); // if can't change size - close file } free(pBuff); // free buffer statusMsg("Saving operation has error: %s", strerror(errno)); // lead out error about } void Common::find() { // TODO } void Common::drawRows(Adbfr* abfr); { // TODO } void Common::drawStatusBar(Adbfr* abfr) { // TODO } void Common::drawMessageBar(Adbfr* abfr) { // TODO } void Common::scrolling() { // TODO } void Common::statusMsg(const char *fmt, ...) { va_list arg; // for unknown number of parameters va_start(arg, fmt); // initialize arg vsnprintf(cnfg.statusMessage, sizeof(cnfg.statusMessage), fmt, arg); // output parameters to statusMessage va_end(arg); // end cnfg.statusMessageTime = time(NULL); // gets time } void Common::updateScreen() { scrolling(); m_abfr = ADBFR_IMPL; // implement to NULL m_abfr.reallocateBfr("\x1b[?25l", 6); // reallocate data m_abfr.reallocateBfr("\x1b[H", 3); // reallocate data /* * draw rows, message bar and status bar */ drawRows(&m_abfr); drawStatusBar(&m_abfr); drawMessageBar(&m_abfr); /* * write to buff cursor | position */ char buff[32]; snprintf(buff, sizeof(buff), "\x1b[%d;%dH", (m_pCnfg->configY - m_pCnfg->disableRow) + 1, (m_pCnfg->rowX - m_pCnfg->disableClr) + 1); m_abfr.reallocateBfr(buff, strlen(buff)); m_abfr.reallocateBfr("\x1b[?25h", 6); /* * update screen */ write(STDOUT_FILENO, ab.b, ab.len); m_abfr.freeBfr(); // free memory } char* Common::callPrompt(char *prompt, void (*callback)(char*, int)) { size_t buffsize = 128; char* bfr = malloc(buffsize); // allocate memory size_t bufflen = 0; // lenght bfr[0] = '\0'; while (1) { statusMsg(prompt, bfr); // set prompt updateScreen(); // and update screen int key = tml.whatKey(); // read key if (key == DELETE_KEY || key == CTRL_KEY('h') || key == BACKSPACE) { if (bufflen != 0) // if buffer is not empty bfr[--bufflen] = '\0'; // set end of row } else if (key == '\x1b') // if this is ESC { statusMsg(""); // erase if (callback) // if callback is not NULL callback(bfr, key); // call func for callback which pointed by callback() free(bfr); // free memory return NULL; // and cancel } else if (key == '\r') // if carriage return (move the cursor at the start of the line) { if (bufflen != 0) // and bufflen is not empty { statusMsg(""); // clean message if (callback) callback(bfr, key); // and get callback return bfr; // returning of buffer } } else if (!iscntrl(key) && key < 128) // checks, whether the argument, transmitted via the parameter сharacter, control character { /* * reallocation of buffer if needs */ if (bufflen == buffsize - 1) { buffsize *= 2; bfr = realloc(bfr, buffsize); } bfr[bufflen++] = key; // write this key to buffer bfr[bufflen] = '\0'; // and end of row } if (callback) callback(bfr, key); // call of callback } } void Common::moveCursor(int key) { // instancing RowController // if empty - to zero position, else to the end of row // RowController* pRowctrl = (m_pCnfg->configY >= m_pCnfg->rowCount) ? NULL : &m_pCnfg->pRowObj[m_pCnfg->configY]; switch (key) { case ARROW_LEFT: if (m_pCnfg->configX != 0) // if horizontal position isn't zero { m_pCnfg->configX--; // move left } else if (m_pCnfg->configY > 0) // else if there is at least 1 row { m_pCnfg->configY--; // move to that row m_pCnfg->configX = m_pCnfg->pRowObj[m_pCnfg->configY].size; // and to the end of that row } break; case ARROW_RIGHT: if (pRowctrl && m_pCnfg->configX < pRowctrl->size) // if there is row and if cursor is not in the end of row { m_pCnfg->configX++; // move cursor right along of row } else if (pRowctrl && m_pCnfg->configX == pRowctrl->size) // if there is row and cursor in the end of this row { m_pCnfg->configY++; // move to next row E.cx = 0; // on zero position } break; case ARROW_UP: if (m_pCnfg->configY != 0) // if there is at least 1 row { m_pCnfg->configY--; // move up } break; case ARROW_DOWN: if (m_pCnfg->configY < m_pCnfg->rowCount) // if cursor is not on last row { m_pCnfg->configY++; // move down } break; } } void Common::processingKeypress() { static int sQuitCounter = EDITORRMEND_QUIT_COUNTER; // counter clicking for exit int key = whatKey(); // read key switch (key) { case '\r': // if carriage return (Enter key) setNewline(); // set newline break; case CTRL_KEY('q'): if (m_pCnfg->smear && sQuitCounter > 0) // if there is any changes and counter > 0 { statusMsg("! File was changed and unsaved and data can be lost after exiting. " "Press Ctrl-Q %d more times to exit.", sQuitCounter); sQuitCounter--; // counter decrement return; } write(STDOUT_FILENO, "\x1b[2J", 4); write(STDOUT_FILENO, "\x1b[H", 3); exit(0); break; case CTRL_KEY('s'): save(); // TODO: save changes break; case HOME_KEY: m_pCnfg->configX = 0; // to the row beginning break; case END_KEY: if (m_pCnfg->configY < m_pCnfg->rowCount) // if not last row m_pCnfg->configX = m_pCnfg->pRowObj[m_pCnfg->configY].size; // to the end of row break; case CTRL_KEY('f'): find(); // find func break; case BACKSPACE: case CTRL_KEY('h'): case DELETE_KEY: if (key == DELETE_KEY) moveCursor(ARROW_RIGHT); // move cursor right deleteChar(); // delete char break; // page up/down // case PAGE_UP: case PAGE_DOWN: { if (key == PAGE_UP) { m_pCnfg->configY = m_pCnfg->disableRow; // move page up } else if (key == PAGE_DOWN) { m_pCnfg->configY = m_pCnfg->disableRow + m_pCnfg->enableRow - 1; // move page down if (m_pCnfg->configY > m_pCnfg->rowCount) m_pCnfg->configY = m_pCnfg->rowCount; } int times = m_pCnfg->enableRow; while (times--) moveCursor(key == PAGE_UP ? ARROW_UP : ARROW_DOWN); } break; case ARROW_UP: case ARROW_DOWN: case ARROW_LEFT: case ARROW_RIGHT: moveCursor(key); break; case CTRL_KEY('l'): case '\x1b': break; default: setChar(key); // just write chars break; } sQuitCounter = EDITORRMEND_QUIT_COUNTER; } <|endoftext|>
<commit_before>/************************************************************************* * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /********************************** * create an event and perform * * flow analysis 'on the fly' * * * * authors: Raimond Snellings * * ([email protected]) * * Ante Bilandzic * * ([email protected]) * *********************************/ #include "Riostream.h" #include "TMath.h" #include "TF1.h" #include "TRandom3.h" #include "AliFlowEventSimpleMakerOnTheFly.h" #include "AliFlowEventSimple.h" #include "AliFlowTrackSimple.h" ClassImp(AliFlowEventSimpleMakerOnTheFly) //======================================================================== AliFlowEventSimpleMakerOnTheFly::AliFlowEventSimpleMakerOnTheFly(UInt_t iseed): fMultiplicityOfRP(0), fMultiplicitySpreadOfRP(0.), fV1RP(0.), fV1SpreadRP(0.), fV2RP(0.), fV2SpreadRP(0.), fPtSpectra(NULL), fPhiDistribution(NULL), fMyTRandom3(NULL), fCount(0) { // constructor fMyTRandom3 = new TRandom3(iseed); } //======================================================================== AliFlowEventSimpleMakerOnTheFly::~AliFlowEventSimpleMakerOnTheFly() { // destructor if (fPtSpectra) delete fPtSpectra; if (fPhiDistribution) delete fPhiDistribution; if (fMyTRandom3) delete fMyTRandom3; } //======================================================================== AliFlowEventSimple* AliFlowEventSimpleMakerOnTheFly::CreateEventOnTheFly() { // method to create event on the fly AliFlowEventSimple* pEvent = new AliFlowEventSimple(fMultiplicityOfRP); //reaction plane Double_t fMCReactionPlaneAngle = fMyTRandom3->Uniform(0.,TMath::TwoPi()); // pt: Double_t dPtMin = 0.; // to be improved Double_t dPtMax = 10.; // to be improved fPtSpectra = new TF1("fPtSpectra","[0]*x*TMath::Exp(-x*x)",dPtMin,dPtMax); fPtSpectra->SetParName(0,"Multiplicity of RPs"); // sampling the multiplicity: Int_t fNewMultiplicityOfRP = fMyTRandom3->Gaus(fMultiplicityOfRP,fMultiplicitySpreadOfRP); fPtSpectra->SetParameter(0,fNewMultiplicityOfRP); // phi: Double_t dPhiMin = 0.; // to be improved Double_t dPhiMax = TMath::TwoPi(); // to be improved fPhiDistribution = new TF1("fPhiDistribution","1+2.*[0]*TMath::Cos(x)+2.*[1]*TMath::Cos(2*x)",dPhiMin,dPhiMax); // sampling the V1: fPhiDistribution->SetParName(0,"directed flow"); if(fV1RP>0.0) fV1RP = fMyTRandom3->Gaus(fV1RP,fV1SpreadRP); fPhiDistribution->SetParameter(0,fV1RP); // sampling the V2: fPhiDistribution->SetParName(1,"elliptic flow"); fV2RP = fMyTRandom3->Gaus(fV2RP,fV2SpreadRP); fPhiDistribution->SetParameter(1,fV2RP); // eta: Double_t dEtaMin = -1.; // to be improved Double_t dEtaMax = 1.; // to be improved Int_t iGoodTracks = 0; Int_t iSelParticlesRP = 0; Int_t iSelParticlesPOI = 0; for(Int_t i=0;i<fNewMultiplicityOfRP;i++) { AliFlowTrackSimple* pTrack = new AliFlowTrackSimple(); pTrack->SetPt(fPtSpectra->GetRandom()); pTrack->SetEta(fMyTRandom3->Uniform(dEtaMin,dEtaMax)); pTrack->SetPhi(fPhiDistribution->GetRandom()+fMCReactionPlaneAngle); pTrack->SetForRPSelection(kTRUE); iSelParticlesRP++; pTrack->SetForPOISelection(kTRUE); iSelParticlesPOI++; pEvent->TrackCollection()->Add(pTrack); iGoodTracks++; } pEvent->SetEventNSelTracksRP(iSelParticlesRP); pEvent->SetNumberOfTracks(iGoodTracks);//tracks used either for RP or for POI selection pEvent->SetMCReactionPlaneAngle(fMCReactionPlaneAngle); if (!fMCReactionPlaneAngle == 0) cout<<" MC Reaction Plane Angle = "<< fMCReactionPlaneAngle << endl; else cout<<" MC Reaction Plane Angle = unknown "<< endl; cout<<" iGoodTracks = "<< iGoodTracks << endl; cout<<" # of RP selected tracks = "<<iSelParticlesRP<<endl; cout<<" # of POI selected tracks = "<<iSelParticlesPOI<<endl; cout << "# " << ++fCount << " events processed" << endl; delete fPhiDistribution; delete fPtSpectra; return pEvent; } // end of CreateEventOnTheFly() <commit_msg>a few more fixes for the fluctuations<commit_after>/************************************************************************* * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /********************************** * create an event and perform * * flow analysis 'on the fly' * * * * authors: Raimond Snellings * * ([email protected]) * * Ante Bilandzic * * ([email protected]) * *********************************/ #include "Riostream.h" #include "TMath.h" #include "TF1.h" #include "TRandom3.h" #include "AliFlowEventSimpleMakerOnTheFly.h" #include "AliFlowEventSimple.h" #include "AliFlowTrackSimple.h" ClassImp(AliFlowEventSimpleMakerOnTheFly) //======================================================================== AliFlowEventSimpleMakerOnTheFly::AliFlowEventSimpleMakerOnTheFly(UInt_t iseed): fMultiplicityOfRP(0), fMultiplicitySpreadOfRP(0.), fV1RP(0.), fV1SpreadRP(0.), fV2RP(0.), fV2SpreadRP(0.), fPtSpectra(NULL), fPhiDistribution(NULL), fMyTRandom3(NULL), fCount(0) { // constructor fMyTRandom3 = new TRandom3(iseed); } //======================================================================== AliFlowEventSimpleMakerOnTheFly::~AliFlowEventSimpleMakerOnTheFly() { // destructor if (fPtSpectra) delete fPtSpectra; if (fPhiDistribution) delete fPhiDistribution; if (fMyTRandom3) delete fMyTRandom3; } //======================================================================== AliFlowEventSimple* AliFlowEventSimpleMakerOnTheFly::CreateEventOnTheFly() { // method to create event on the fly AliFlowEventSimple* pEvent = new AliFlowEventSimple(fMultiplicityOfRP); //reaction plane Double_t fMCReactionPlaneAngle = fMyTRandom3->Uniform(0.,TMath::TwoPi()); // pt: Double_t dPtMin = 0.; // to be improved Double_t dPtMax = 10.; // to be improved fPtSpectra = new TF1("fPtSpectra","[0]*x*TMath::Exp(-x*x)",dPtMin,dPtMax); fPtSpectra->SetParName(0,"Multiplicity of RPs"); // sampling the multiplicity: Int_t fNewMultiplicityOfRP = fMyTRandom3->Gaus(fMultiplicityOfRP,fMultiplicitySpreadOfRP); fPtSpectra->SetParameter(0,fNewMultiplicityOfRP); // phi: Double_t dPhiMin = 0.; // to be improved Double_t dPhiMax = TMath::TwoPi(); // to be improved fPhiDistribution = new TF1("fPhiDistribution","1+2.*[0]*TMath::Cos(x)+2.*[1]*TMath::Cos(2*x)",dPhiMin,dPhiMax); // sampling the V1: fPhiDistribution->SetParName(0,"directed flow"); Double_t fNewV1RP=0.; if(fV1RP>0.0) {fNewV1RP = fMyTRandom3->Gaus(fV1RP,fV1SpreadRP);} fPhiDistribution->SetParameter(0,fNewV1RP); // sampling the V2: fPhiDistribution->SetParName(1,"elliptic flow"); Double_t fNewV2RP = fMyTRandom3->Gaus(fV2RP,fV2SpreadRP); fPhiDistribution->SetParameter(1,fNewV2RP); // eta: Double_t dEtaMin = -1.; // to be improved Double_t dEtaMax = 1.; // to be improved Int_t iGoodTracks = 0; Int_t iSelParticlesRP = 0; Int_t iSelParticlesPOI = 0; for(Int_t i=0;i<fNewMultiplicityOfRP;i++) { AliFlowTrackSimple* pTrack = new AliFlowTrackSimple(); pTrack->SetPt(fPtSpectra->GetRandom()); pTrack->SetEta(fMyTRandom3->Uniform(dEtaMin,dEtaMax)); pTrack->SetPhi(fPhiDistribution->GetRandom()+fMCReactionPlaneAngle); pTrack->SetForRPSelection(kTRUE); iSelParticlesRP++; pTrack->SetForPOISelection(kTRUE); iSelParticlesPOI++; pEvent->TrackCollection()->Add(pTrack); iGoodTracks++; } pEvent->SetEventNSelTracksRP(iSelParticlesRP); pEvent->SetNumberOfTracks(iGoodTracks);//tracks used either for RP or for POI selection pEvent->SetMCReactionPlaneAngle(fMCReactionPlaneAngle); if (!fMCReactionPlaneAngle == 0) cout<<" MC Reaction Plane Angle = "<< fMCReactionPlaneAngle << endl; else cout<<" MC Reaction Plane Angle = unknown "<< endl; cout<<" iGoodTracks = "<< iGoodTracks << endl; cout<<" # of RP selected tracks = "<<iSelParticlesRP<<endl; cout<<" # of POI selected tracks = "<<iSelParticlesPOI<<endl; cout << "# " << ++fCount << " events processed" << endl; delete fPhiDistribution; delete fPtSpectra; return pEvent; } // end of CreateEventOnTheFly() <|endoftext|>
<commit_before>/* Joey Button * * */ #include <stdio.h> #include "opencv2/opencv.hpp" using namespace cv; using namespace std; const char *win = "video"; void drawCircle( Mat img, Point center ) { int thickness = -1; int lineType = 8; circle( img, center, 32.0, Scalar( 0, 0, 255 ), thickness, lineType ); } int main() { int cam = 0; // default camera VideoCapture cap(cam); if (!cap.isOpened()) { fprintf(stderr, "cannot open camera %d\n", cam); exit(1); } //namedWindow(win); namedWindow(win, 1); Mat frame, screen; Point pt; pt.x = 500; pt.y = 0; int momentumY = 10; int momentumX = 0; while (1) { cap >> frame; cvtColor(frame, screen, CV_LOAD_IMAGE_COLOR); pt.x += momentumX; pt.y += momentumY; if(pt.y<990){ momentumY += 1; }else { momentumY = -(momentumY/2); } if (momentumY*momentumY <= 49 && pt.y > 990){ momentumY =0; } //This will zero out the entire image, and draw a red circle Mat BGRChannels[3]; split(screen,BGRChannels); // split the BGR channesl BGRChannels[1]=Mat::zeros(screen.rows,screen.cols,CV_8UC1); // removing Green channel BGRChannels[0]=Mat::zeros(screen.rows,screen.cols,CV_8UC1); // removing Green channel BGRChannels[2]=Mat::zeros(screen.rows,screen.cols,CV_8UC1); // removing Green channel merge(BGRChannels,3,screen); drawCircle(screen,pt); // pack the image imshow(win, screen); if (waitKey(30) >= 0) // wait up to 30 msec break; } return 0; } /* Mat BGRChannels[3]; split(screen,BGRChannels); // split the BGR channesl BGRChannels[1]=Mat::zeros(screen.rows,screen.cols,CV_8UC1);// removing Green channel merge(BGRChannels,3,screen); // pack the image waitKey(0); */ <commit_msg>Still confused<commit_after>/* * Joey Button * * */ #include <stdio.h> #include "opencv2/opencv.hpp" using namespace cv; using namespace std; const char *win = "video"; void drawCircle(Mat img, Point center) { int thickness = -1; int lineType = 8; circle( img, center, 32.0, Scalar( 0, 0, 255 ), thickness, lineType); } int main() { int cam = 0; // default camera VideoCapture cap(cam); if (!cap.isOpened()) { fprintf(stderr, "cannot open camera %d\n", cam); exit(1); } // namedWindow(win); namedWindow(win, 1); Mat frame, screen; Point pt; pt.x = 500; pt.y = 0; int momentumY = 10; // initial momentum hardcoded as 10 int momentumX = 0; while (1) { cap >> frame; cvtColor(frame, screen, CV_LOAD_IMAGE_COLOR); pt.x += momentumX; pt.y += momentumY; if (pt.y < 990) { // not at bottom momentumY += 1; } else { momentumY = -(momentumY * .5); // bounce back up and halt it } if (momentumY * momentumY <= 49 && pt.y > 990){ momentumY = 0; } // This will zero out the entire image, and draw a red circle Mat BGRChannels[3]; split(screen, BGRChannels); // split the BGR channesl BGRChannels[1] = Mat::zeros(screen.rows, screen.cols, CV_8UC1); // removing Green channel BGRChannels[0] = Mat::zeros(screen.rows, screen.cols, CV_8UC1); // removing Green channel BGRChannels[2] = Mat::zeros(screen.rows, screen.cols, CV_8UC1); // removing Green channel // TODO: what? merge(BGRChannels, 3, screen); drawCircle(screen, pt); // pack the image imshow(win, screen); if (waitKey(30) >= 0) // wait up to 30 msec break; } return 0; } /* Mat BGRChannels[3]; split(screen,BGRChannels); // split the BGR channesl BGRChannels[1]=Mat::zeros(screen.rows,screen.cols,CV_8UC1);// removing Green channel merge(BGRChannels,3,screen); // pack the image waitKey(0); */ <|endoftext|>
<commit_before>#include <iostream> #include <stack> #include <cstring> bool analise_parentesis(char* entrada, int tamanho_entrada){ int i; std::stack<char> pilha; for(i = 0; i < tamanho_entrada; i++){ if(entrada[i] == '(' or entrada[i] == '['){ pilha.push(entrada[i]); } else if(pilha.size() and entrada[i] == ')' and pilha.top() == '('){ pilha.pop(); } else if(pilha.size() and entrada[i] == ']' and pilha.top() == '['){ pilha.pop(); } else if(entrada[i] != ' '){ return false; } } if(pilha.size() > 0){ return false; } else { return true; } } int main(){ int qnt_entradas; int tamanho_entrada; char s[140]; // Especificamente para o problema..// std::cin >> qnt_entradas; getchar(); //.................................// while(qnt_entradas > 0){ // Especificamente para o problema..// fgets(s, 140, stdin); tamanho_entrada = strlen(s) - 1; //..................................// if(analise_parentesis(s, tamanho_entrada)){ std::cout << "Yes" << std::endl; } else { std::cout << "No" << std::endl; } qnt_entradas -= 1; } return 0; } <commit_msg>ModificaΓ§Γ΅es na questΓ£o do parentesis do UVA<commit_after>#include <iostream> #include <stack> #include <cstring> #define MAX_SIZE 130 bool analise_parentesis(char* entrada, int tamanho_entrada){ int i; std::stack<char> pilha; for(i = 0; i < tamanho_entrada; i++){ if(entrada[i] == '(' or entrada[i] == '['){ pilha.push(entrada[i]); } else if(pilha.size() and entrada[i] == ')' and pilha.top() == '('){ pilha.pop(); } else if(pilha.size() and entrada[i] == ']' and pilha.top() == '['){ pilha.pop(); } else if(entrada[i] != ' '){ return false; } } if(pilha.size() > 0){ return false; } else { return true; } } int main(){ int qnt_entradas; int tamanho_entrada; char s[MAX_SIZE]; // Especificamente para o problema..// std::cin >> qnt_entradas; getchar(); //.................................// while(qnt_entradas > 0){ // Especificamente para o problema..// fgets(s, MAX_SIZE, stdin); tamanho_entrada = strlen(s) - 1; //..................................// if(analise_parentesis(s, tamanho_entrada)){ std::cout << "Yes" << std::endl; } else { std::cout << "No" << std::endl; } qnt_entradas -= 1; } return 0; } <|endoftext|>
<commit_before>#include <kvs/Stat> #include <kvs/ValueArray> #include <kvs/MersenneTwister> #include <iostream> #include <fstream> #include <iterator> #include <algorithm> template <typename T> std::ostream& operator << ( std::ostream& os, const kvs::ValueArray<T>& values ) { std::copy( values.begin(), values.end(), std::ostream_iterator<T>( os, ", " ) ); return os; } template <typename T> kvs::ValueArray<T> Random( const size_t n ) { kvs::ValueArray<T> values( n ); kvs::MersenneTwister engine; std::generate( values.begin(), values.end(), engine ); return values; } int main( int argc, char** argv ) { const size_t n = 10; kvs::ValueArray<float> values1 = Random<float>( n ); kvs::ValueArray<float> values2 = Random<float>( n ); std::cout << "X = {" << values1 << "}" << std::endl; std::cout << "Y = {" << values2 << "}" << std::endl; std::cout << std::endl; std::cout << "Sum(X): " << kvs::Stat::Sum( values1 ) << std::endl; std::cout << "Mean(X): " << kvs::Stat::Mean( values1 ) << std::endl; std::cout << "Var(X): " << kvs::Stat::Var( values1 ) << std::endl; std::cout << "ShiftedVar(X): " << kvs::Stat::ShiftedVar( values1 ) << std::endl; std::cout << "TwoPassVar(X): " << kvs::Stat::TwoPassVar( values1 ) << std::endl; std::cout << "CompensatedVar(X): " << kvs::Stat::CompensatedVar( values1 ) << std::endl; std::cout << "OnlineVar(X): " << kvs::Stat::OnlineVar( values1 ) << std::endl; std::cout << "Cov(X,Y): " << kvs::Stat::Cov( values1, values2 ) << std::endl; std::cout << "ShiftedCov(X,Y): " << kvs::Stat::ShiftedCov( values1, values2 ) << std::endl; std::cout << "TwoPassCov(X,Y): " << kvs::Stat::TwoPassCov( values1, values2 ) << std::endl; std::cout << "OnlineCov(X,Y): " << kvs::Stat::OnlineCov( values1, values2 ) << std::endl; std::cout << "StdDev(X): " << kvs::Stat::StdDev( values1 ) << std::endl; std::cout << "StdDev(X,ShiftedVar): " << kvs::Stat::StdDev( values1, kvs::Stat::ShiftedVar<float> ) << std::endl; std::cout << "Corr(X,Y): " << kvs::Stat::Corr( values1, values2 ) << std::endl; std::cout << "AutoCorr(X,1): " << kvs::Stat::AutoCorr( values1, 1 ) << std::endl; std::cout << "CrossCorr(X,Y,1): " << kvs::Stat::CrossCorr( values1, values2, 1 ) << std::endl; return 0; } <commit_msg>Modified.<commit_after>#include <kvs/Stat> #include <kvs/ValueArray> #include <kvs/MersenneTwister> #include <iostream> #include <fstream> #include <iterator> #include <algorithm> template <typename T> std::ostream& operator << ( std::ostream& os, const kvs::ValueArray<T>& values ) { std::copy( values.begin(), values.end(), std::ostream_iterator<T>( os, ", " ) ); return os; } template <typename T> kvs::ValueArray<T> Random( const size_t n ) { kvs::ValueArray<T> values( n ); kvs::MersenneTwister engine; std::generate( values.begin(), values.end(), engine ); return values; } int main( int argc, char** argv ) { const size_t n = 10; kvs::ValueArray<float> values1 = Random<float>( n ); kvs::ValueArray<float> values2 = Random<float>( n ); std::cout << "X = {" << values1 << "}" << std::endl; std::cout << "Y = {" << values2 << "}" << std::endl; std::cout << std::endl; std::cout << "Sum(X): " << kvs::Stat::Sum( values1 ) << std::endl; std::cout << "Mean(X): " << kvs::Stat::Mean( values1 ) << std::endl; std::cout << "Var(X): " << kvs::Stat::Var( values1 ) << std::endl; std::cout << "ShiftedVar(X): " << kvs::Stat::ShiftedVar( values1 ) << std::endl; std::cout << "TwoPassVar(X): " << kvs::Stat::TwoPassVar( values1 ) << std::endl; std::cout << "CompensatedVar(X): " << kvs::Stat::CompensatedVar( values1 ) << std::endl; std::cout << "OnlineVar(X): " << kvs::Stat::OnlineVar( values1 ) << std::endl; std::cout << "Cov(X,Y): " << kvs::Stat::Cov( values1, values2 ) << std::endl; std::cout << "ShiftedCov(X,Y): " << kvs::Stat::ShiftedCov( values1, values2 ) << std::endl; std::cout << "TwoPassCov(X,Y): " << kvs::Stat::TwoPassCov( values1, values2 ) << std::endl; std::cout << "OnlineCov(X,Y): " << kvs::Stat::OnlineCov( values1, values2 ) << std::endl; std::cout << "StdDev(X): " << kvs::Stat::StdDev( values1 ) << std::endl; std::cout << "StdDev(X,ShiftedVar): " << kvs::Stat::StdDev( values1, kvs::Stat::ShiftedVar<float> ) << std::endl; std::cout << "Corr(X,Y): " << kvs::Stat::Corr( values1, values2 ) << std::endl; std::cout << "AutoCorr(X): " << kvs::Stat::AutoCorr( values1 ) << std::endl; std::cout << "AutoCorr(X,1): " << kvs::Stat::AutoCorr( values1, 1 ) << std::endl; std::cout << "CrossCorr(X,Y): " << kvs::Stat::CrossCorr( values1, values2 ) << std::endl; std::cout << "CrossCorr(X,Y,1): " << kvs::Stat::CrossCorr( values1, values2, 1 ) << std::endl; return 0; } <|endoftext|>
<commit_before>// Copyright 2010-2013 The CefSharp Project. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "Stdafx.h" #include "Internals/CefRequestWrapper.h" #include "Internals/JavascriptBinding/BindingHandler.h" #include "Internals/RequestResponse.h" #include "ClientAdapter.h" #include "Cef.h" #include "DownloadAdapter.h" #include "StreamAdapter.h" using namespace std; using namespace CefSharp::Internals::JavascriptBinding; namespace CefSharp { namespace Internals { bool ClientAdapter::OnBeforePopup(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& target_url, const CefString& target_frame_name, const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, CefRefPtr<CefClient>& client, CefBrowserSettings& settings, bool* no_javascript_access) { ILifeSpanHandler^ handler = _browserControl->LifeSpanHandler; if (handler == nullptr) { return false; } return handler->OnBeforePopup(_browserControl, StringUtils::ToClr(target_url), windowInfo.x, windowInfo.y, windowInfo.width, windowInfo.height); } void ClientAdapter::OnAfterCreated(CefRefPtr<CefBrowser> browser) { if (!browser->IsPopup()) { _browserHwnd = browser->GetHost()->GetWindowHandle(); _cefBrowser = browser; _browserControl->OnInitialized(); } } void ClientAdapter::OnBeforeClose(CefRefPtr<CefBrowser> browser) { if (_browserHwnd == browser->GetHost()->GetWindowHandle()) { ILifeSpanHandler^ handler = _browserControl->LifeSpanHandler; if (handler != nullptr) { handler->OnBeforeClose(_browserControl); } _cefBrowser = nullptr; } } void ClientAdapter::OnLoadingStateChange(CefRefPtr<CefBrowser> browser, bool isLoading, bool canGoBack, bool canGoForward) { _browserControl->SetIsLoading(isLoading); auto canReload = !isLoading; _browserControl->SetNavState(canGoBack, canGoForward, canReload); } void ClientAdapter::OnAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& address) { if (frame->IsMain()) { _browserControl->SetAddress(StringUtils::ToClr(address)); } } void ClientAdapter::OnTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title) { _browserControl->SetTitle(StringUtils::ToClr(title)); } bool ClientAdapter::OnTooltip(CefRefPtr<CefBrowser> browser, CefString& text) { String^ tooltip = StringUtils::ToClr(text); if (tooltip != _tooltip) { _tooltip = tooltip; _browserControl->SetTooltipText(_tooltip); } return true; } bool ClientAdapter::OnConsoleMessage(CefRefPtr<CefBrowser> browser, const CefString& message, const CefString& source, int line) { String^ messageStr = StringUtils::ToClr(message); String^ sourceStr = StringUtils::ToClr(source); _browserControl->OnConsoleMessage(messageStr, sourceStr, line); return true; } KeyType KeyTypeToManaged(cef_key_event_type_t keytype) { switch (keytype) { case KEYEVENT_RAWKEYDOWN: return KeyType::RawKeyDown; case KEYEVENT_KEYDOWN: return KeyType::KeyDown; case KEYEVENT_KEYUP: return KeyType::KeyUp; case KEYEVENT_CHAR: default: return KeyType::Char; } } bool ClientAdapter::OnKeyEvent(CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event) { IKeyboardHandler^ handler = _browserControl->KeyboardHandler; if (handler == nullptr) { return false; } // TODO: windows_key_code could possibly be the wrong choice here (the OnKeyEvent signature has changed since CEF1). The // other option would be native_key_code. return handler->OnKeyEvent(_browserControl, KeyTypeToManaged(event.type), event.windows_key_code, event.modifiers, event.is_system_key); } void ClientAdapter::OnLoadStart(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame) { if (browser->IsPopup()) { return; } AutoLock lock_scope(this); if (frame->IsMain()) { _browserControl->SetIsLoading(true); _browserControl->SetNavState(false, false, false); } _browserControl->OnFrameLoadStart(StringUtils::ToClr(frame->GetURL())); } void ClientAdapter::OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) { if (browser->IsPopup()) { return; } AutoLock lock_scope(this); if (frame->IsMain()) { _browserControl->SetIsLoading(false); } _browserControl->OnFrameLoadEnd(StringUtils::ToClr(frame->GetURL())); } void ClientAdapter::OnLoadError(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, ErrorCode errorCode, const CefString& errorText, const CefString& failedUrl) { _browserControl->OnLoadError(StringUtils::ToClr(failedUrl), (CefErrorCode)errorCode, StringUtils::ToClr(errorText)); } // TODO: Check how we can support this with CEF3. /* bool ClientAdapter::OnBeforeBrowse(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request, NavType navType, bool isRedirect) { IRequestHandler^ handler = _browserControl->RequestHandler; if (handler == nullptr) { return false; } CefRequestWrapper^ wrapper = gcnew CefRequestWrapper(request); NavigationType navigationType = (NavigationType)navType; return handler->OnBeforeBrowse(_browserControl, wrapper, navigationType, isRedirect); } */ bool ClientAdapter::OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request) { // TOOD: Try to support with CEF3; seems quite difficult because the method signature has changed greatly with many parts // seemingly MIA... IRequestHandler^ handler = _browserControl->RequestHandler; if (handler == nullptr) { return false; } CefRequestWrapper^ wrapper = gcnew CefRequestWrapper(request); RequestResponse^ requestResponse = gcnew RequestResponse(wrapper); bool ret = handler->OnBeforeResourceLoad(_browserControl, requestResponse); if (requestResponse->Action == ResponseAction::Redirect) { // TODO: Not supported at the moment; there does not seem any obvious way to give a redirect back in an // OnBeforeResourceLoad() handler nowadays. //request.redirectUrl = StringUtils::ToNative(requestResponse->RedirectUrl); } else if (requestResponse->Action == ResponseAction::Respond) { CefRefPtr<StreamAdapter> adapter = new StreamAdapter(requestResponse->ResponseStream); throw gcnew NotImplementedException("Respond is not yet supported."); //resourceStream = CefStreamReader::CreateForHandler(static_cast<CefRefPtr<CefReadHandler>>(adapter)); //response->SetMimeType(StringUtils::ToNative(requestResponse->MimeType)); //response->SetStatus(requestResponse->StatusCode); //response->SetStatusText(StringUtils::ToNative(requestResponse->StatusText)); //CefResponse::HeaderMap map; //if (requestResponse->ResponseHeaders != nullptr) //{ // for each (KeyValuePair<String^, String^>^ kvp in requestResponse->ResponseHeaders) // { // map.insert(pair<CefString,CefString>(StringUtils::ToNative(kvp->Key),StringUtils::ToNative(kvp->Value))); // } //} //response->SetHeaderMap(map); } return ret; } CefRefPtr<CefDownloadHandler> ClientAdapter::GetDownloadHandler() { IRequestHandler^ requestHandler = _browserControl->RequestHandler; if (requestHandler == nullptr) { return false; } IDownloadHandler^ downloadHandler; bool ret = requestHandler->GetDownloadHandler(_browserControl, downloadHandler); if (ret) { return new DownloadAdapter(downloadHandler); } else { return nullptr; } } bool ClientAdapter::GetAuthCredentials(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, bool isProxy, const CefString& host, int port, const CefString& realm, const CefString& scheme, CefRefPtr<CefAuthCallback> callback) { IRequestHandler^ handler = _browserControl->RequestHandler; if (handler == nullptr) { return false; } String^ usernameString = nullptr; String^ passwordString = nullptr; bool handled = handler->GetAuthCredentials(_browserControl, isProxy, StringUtils::ToClr(host), port, StringUtils::ToClr(realm), StringUtils::ToClr(scheme), usernameString, passwordString); if (handled) { CefString username; CefString password; if (usernameString != nullptr) { username = StringUtils::ToNative(usernameString); } if (passwordString != nullptr) { password = StringUtils::ToNative(passwordString); } callback->Continue(username, password); } else { // TOOD: Should we call Cancel() here or not? At first glance, I believe we should since there will otherwise be no // way to cancel the auth request from an IRequestHandler. callback->Cancel(); } return handled; } // TODO: Investigate how we can support in CEF3. /* void ClientAdapter::OnResourceResponse(CefRefPtr<CefBrowser> browser, const CefString& url, CefRefPtr<CefResponse> response, CefRefPtr<CefContentFilter>& filter) { IRequestHandler^ handler = _browserControl->RequestHandler; if (handler == nullptr) { return; } WebHeaderCollection^ headers = gcnew WebHeaderCollection(); CefResponse::HeaderMap map; response->GetHeaderMap(map); for (CefResponse::HeaderMap::iterator it = map.begin(); it != map.end(); ++it) { try { headers->Add(StringUtils::ToClr(it->first), StringUtils::ToClr(it->second)); } catch (Exception ^ex) { // adding a header with invalid characters can cause an exception to be // thrown. we will drop those headers for now. // we could eventually use reflection to call headers->AddWithoutValidate(). } } handler->OnResourceResponse( _browserControl, StringUtils::ToClr(url), response->GetStatus(), StringUtils::ToClr(response->GetStatusText()), StringUtils::ToClr(response->GetMimeType()), headers); }*/ void ClientAdapter::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) { // TODO: Support the BindingHandler with CEF3. /* for each(KeyValuePair<String^, Object^>^ kvp in Cef::GetBoundObjects()) { BindingHandler::Bind(kvp->Key, kvp->Value, context->GetGlobal()); } for each(KeyValuePair<String^, Object^>^ kvp in _browserControl->GetBoundObjects()) { BindingHandler::Bind(kvp->Key, kvp->Value, context->GetGlobal()); } */ } void ClientAdapter::OnBeforeContextMenu(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefContextMenuParams> params, CefRefPtr<CefMenuModel> model) { // Something like this... auto winFormsWebBrowserControl = dynamic_cast<IWinFormsWebBrowser^>((IWebBrowserInternal^)_browserControl); if (winFormsWebBrowserControl == nullptr) return; IMenuHandler^ handler = winFormsWebBrowserControl->MenuHandler; if (handler == nullptr) return; auto result = handler->OnBeforeContextMenu(_browserControl); if (!result) { // The only way I found for preventing the context menu to be displayed is by removing all items. :-) while (model->GetCount() > 0) { model->RemoveAt(0); } } } void ClientAdapter::OnTakeFocus(CefRefPtr<CefBrowser> browser, bool next) { _browserControl->OnTakeFocus(next); } bool ClientAdapter::OnJSDialog(CefRefPtr<CefBrowser> browser, const CefString& origin_url, const CefString& accept_lang, JSDialogType dialog_type, const CefString& message_text, const CefString& default_prompt_text, CefRefPtr<CefJSDialogCallback> callback, bool& suppress_message) { IJsDialogHandler^ handler = _browserControl->JsDialogHandler; if (handler == nullptr) { return false; } bool result; bool handled; switch (dialog_type) { case JSDIALOGTYPE_ALERT: handled = handler->OnJSAlert(_browserControl, StringUtils::ToClr(origin_url), StringUtils::ToClr(message_text)); break; case JSDIALOGTYPE_CONFIRM: handled = handler->OnJSConfirm(_browserControl, StringUtils::ToClr(origin_url), StringUtils::ToClr(message_text), result); callback->Continue(result, CefString()); break; case JSDIALOGTYPE_PROMPT: String^ resultString = nullptr; result = handler->OnJSPrompt(_browserControl, StringUtils::ToClr(origin_url), StringUtils::ToClr(message_text), StringUtils::ToClr(default_prompt_text), result, resultString); callback->Continue(result, StringUtils::ToNative(resultString)); break; } // Unknown dialog type, so we return "not handled". return false; } } } <commit_msg>throw exception instead of returning shit<commit_after>// Copyright 2010-2013 The CefSharp Project. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "Stdafx.h" #include "Internals/CefRequestWrapper.h" #include "Internals/JavascriptBinding/BindingHandler.h" #include "Internals/RequestResponse.h" #include "ClientAdapter.h" #include "Cef.h" #include "DownloadAdapter.h" #include "StreamAdapter.h" using namespace std; using namespace CefSharp::Internals::JavascriptBinding; namespace CefSharp { namespace Internals { bool ClientAdapter::OnBeforePopup(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& target_url, const CefString& target_frame_name, const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, CefRefPtr<CefClient>& client, CefBrowserSettings& settings, bool* no_javascript_access) { ILifeSpanHandler^ handler = _browserControl->LifeSpanHandler; if (handler == nullptr) { return false; } return handler->OnBeforePopup(_browserControl, StringUtils::ToClr(target_url), windowInfo.x, windowInfo.y, windowInfo.width, windowInfo.height); } void ClientAdapter::OnAfterCreated(CefRefPtr<CefBrowser> browser) { if (!browser->IsPopup()) { _browserHwnd = browser->GetHost()->GetWindowHandle(); _cefBrowser = browser; _browserControl->OnInitialized(); } } void ClientAdapter::OnBeforeClose(CefRefPtr<CefBrowser> browser) { if (_browserHwnd == browser->GetHost()->GetWindowHandle()) { ILifeSpanHandler^ handler = _browserControl->LifeSpanHandler; if (handler != nullptr) { handler->OnBeforeClose(_browserControl); } _cefBrowser = nullptr; } } void ClientAdapter::OnLoadingStateChange(CefRefPtr<CefBrowser> browser, bool isLoading, bool canGoBack, bool canGoForward) { _browserControl->SetIsLoading(isLoading); auto canReload = !isLoading; _browserControl->SetNavState(canGoBack, canGoForward, canReload); } void ClientAdapter::OnAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& address) { if (frame->IsMain()) { _browserControl->SetAddress(StringUtils::ToClr(address)); } } void ClientAdapter::OnTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title) { _browserControl->SetTitle(StringUtils::ToClr(title)); } bool ClientAdapter::OnTooltip(CefRefPtr<CefBrowser> browser, CefString& text) { String^ tooltip = StringUtils::ToClr(text); if (tooltip != _tooltip) { _tooltip = tooltip; _browserControl->SetTooltipText(_tooltip); } return true; } bool ClientAdapter::OnConsoleMessage(CefRefPtr<CefBrowser> browser, const CefString& message, const CefString& source, int line) { String^ messageStr = StringUtils::ToClr(message); String^ sourceStr = StringUtils::ToClr(source); _browserControl->OnConsoleMessage(messageStr, sourceStr, line); return true; } KeyType KeyTypeToManaged(cef_key_event_type_t keytype) { switch (keytype) { case KEYEVENT_RAWKEYDOWN: return KeyType::RawKeyDown; case KEYEVENT_KEYDOWN: return KeyType::KeyDown; case KEYEVENT_KEYUP: return KeyType::KeyUp; case KEYEVENT_CHAR: default: throw gcnew ArgumentOutOfRangeException("keytype", String::Format("'{0}' is not a valid keytype", gcnew array<Object^>(keytype))); } } bool ClientAdapter::OnKeyEvent(CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event) { IKeyboardHandler^ handler = _browserControl->KeyboardHandler; if (handler == nullptr) { return false; } // TODO: windows_key_code could possibly be the wrong choice here (the OnKeyEvent signature has changed since CEF1). The // other option would be native_key_code. return handler->OnKeyEvent(_browserControl, KeyTypeToManaged(event.type), event.windows_key_code, event.modifiers, event.is_system_key); } void ClientAdapter::OnLoadStart(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame) { if (browser->IsPopup()) { return; } AutoLock lock_scope(this); if (frame->IsMain()) { _browserControl->SetIsLoading(true); _browserControl->SetNavState(false, false, false); } _browserControl->OnFrameLoadStart(StringUtils::ToClr(frame->GetURL())); } void ClientAdapter::OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) { if (browser->IsPopup()) { return; } AutoLock lock_scope(this); if (frame->IsMain()) { _browserControl->SetIsLoading(false); } _browserControl->OnFrameLoadEnd(StringUtils::ToClr(frame->GetURL())); } void ClientAdapter::OnLoadError(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, ErrorCode errorCode, const CefString& errorText, const CefString& failedUrl) { _browserControl->OnLoadError(StringUtils::ToClr(failedUrl), (CefErrorCode)errorCode, StringUtils::ToClr(errorText)); } // TODO: Check how we can support this with CEF3. /* bool ClientAdapter::OnBeforeBrowse(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request, NavType navType, bool isRedirect) { IRequestHandler^ handler = _browserControl->RequestHandler; if (handler == nullptr) { return false; } CefRequestWrapper^ wrapper = gcnew CefRequestWrapper(request); NavigationType navigationType = (NavigationType)navType; return handler->OnBeforeBrowse(_browserControl, wrapper, navigationType, isRedirect); } */ bool ClientAdapter::OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request) { // TOOD: Try to support with CEF3; seems quite difficult because the method signature has changed greatly with many parts // seemingly MIA... IRequestHandler^ handler = _browserControl->RequestHandler; if (handler == nullptr) { return false; } CefRequestWrapper^ wrapper = gcnew CefRequestWrapper(request); RequestResponse^ requestResponse = gcnew RequestResponse(wrapper); bool ret = handler->OnBeforeResourceLoad(_browserControl, requestResponse); if (requestResponse->Action == ResponseAction::Redirect) { // TODO: Not supported at the moment; there does not seem any obvious way to give a redirect back in an // OnBeforeResourceLoad() handler nowadays. //request.redirectUrl = StringUtils::ToNative(requestResponse->RedirectUrl); } else if (requestResponse->Action == ResponseAction::Respond) { CefRefPtr<StreamAdapter> adapter = new StreamAdapter(requestResponse->ResponseStream); throw gcnew NotImplementedException("Respond is not yet supported."); //resourceStream = CefStreamReader::CreateForHandler(static_cast<CefRefPtr<CefReadHandler>>(adapter)); //response->SetMimeType(StringUtils::ToNative(requestResponse->MimeType)); //response->SetStatus(requestResponse->StatusCode); //response->SetStatusText(StringUtils::ToNative(requestResponse->StatusText)); //CefResponse::HeaderMap map; //if (requestResponse->ResponseHeaders != nullptr) //{ // for each (KeyValuePair<String^, String^>^ kvp in requestResponse->ResponseHeaders) // { // map.insert(pair<CefString,CefString>(StringUtils::ToNative(kvp->Key),StringUtils::ToNative(kvp->Value))); // } //} //response->SetHeaderMap(map); } return ret; } CefRefPtr<CefDownloadHandler> ClientAdapter::GetDownloadHandler() { IRequestHandler^ requestHandler = _browserControl->RequestHandler; if (requestHandler == nullptr) { return false; } IDownloadHandler^ downloadHandler; bool ret = requestHandler->GetDownloadHandler(_browserControl, downloadHandler); if (ret) { return new DownloadAdapter(downloadHandler); } else { return nullptr; } } bool ClientAdapter::GetAuthCredentials(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, bool isProxy, const CefString& host, int port, const CefString& realm, const CefString& scheme, CefRefPtr<CefAuthCallback> callback) { IRequestHandler^ handler = _browserControl->RequestHandler; if (handler == nullptr) { return false; } String^ usernameString = nullptr; String^ passwordString = nullptr; bool handled = handler->GetAuthCredentials(_browserControl, isProxy, StringUtils::ToClr(host), port, StringUtils::ToClr(realm), StringUtils::ToClr(scheme), usernameString, passwordString); if (handled) { CefString username; CefString password; if (usernameString != nullptr) { username = StringUtils::ToNative(usernameString); } if (passwordString != nullptr) { password = StringUtils::ToNative(passwordString); } callback->Continue(username, password); } else { // TOOD: Should we call Cancel() here or not? At first glance, I believe we should since there will otherwise be no // way to cancel the auth request from an IRequestHandler. callback->Cancel(); } return handled; } // TODO: Investigate how we can support in CEF3. /* void ClientAdapter::OnResourceResponse(CefRefPtr<CefBrowser> browser, const CefString& url, CefRefPtr<CefResponse> response, CefRefPtr<CefContentFilter>& filter) { IRequestHandler^ handler = _browserControl->RequestHandler; if (handler == nullptr) { return; } WebHeaderCollection^ headers = gcnew WebHeaderCollection(); CefResponse::HeaderMap map; response->GetHeaderMap(map); for (CefResponse::HeaderMap::iterator it = map.begin(); it != map.end(); ++it) { try { headers->Add(StringUtils::ToClr(it->first), StringUtils::ToClr(it->second)); } catch (Exception ^ex) { // adding a header with invalid characters can cause an exception to be // thrown. we will drop those headers for now. // we could eventually use reflection to call headers->AddWithoutValidate(). } } handler->OnResourceResponse( _browserControl, StringUtils::ToClr(url), response->GetStatus(), StringUtils::ToClr(response->GetStatusText()), StringUtils::ToClr(response->GetMimeType()), headers); }*/ void ClientAdapter::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) { // TODO: Support the BindingHandler with CEF3. /* for each(KeyValuePair<String^, Object^>^ kvp in Cef::GetBoundObjects()) { BindingHandler::Bind(kvp->Key, kvp->Value, context->GetGlobal()); } for each(KeyValuePair<String^, Object^>^ kvp in _browserControl->GetBoundObjects()) { BindingHandler::Bind(kvp->Key, kvp->Value, context->GetGlobal()); } */ } void ClientAdapter::OnBeforeContextMenu(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefContextMenuParams> params, CefRefPtr<CefMenuModel> model) { // Something like this... auto winFormsWebBrowserControl = dynamic_cast<IWinFormsWebBrowser^>((IWebBrowserInternal^)_browserControl); if (winFormsWebBrowserControl == nullptr) return; IMenuHandler^ handler = winFormsWebBrowserControl->MenuHandler; if (handler == nullptr) return; auto result = handler->OnBeforeContextMenu(_browserControl); if (!result) { // The only way I found for preventing the context menu to be displayed is by removing all items. :-) while (model->GetCount() > 0) { model->RemoveAt(0); } } } void ClientAdapter::OnTakeFocus(CefRefPtr<CefBrowser> browser, bool next) { _browserControl->OnTakeFocus(next); } bool ClientAdapter::OnJSDialog(CefRefPtr<CefBrowser> browser, const CefString& origin_url, const CefString& accept_lang, JSDialogType dialog_type, const CefString& message_text, const CefString& default_prompt_text, CefRefPtr<CefJSDialogCallback> callback, bool& suppress_message) { IJsDialogHandler^ handler = _browserControl->JsDialogHandler; if (handler == nullptr) { return false; } bool result; bool handled; switch (dialog_type) { case JSDIALOGTYPE_ALERT: handled = handler->OnJSAlert(_browserControl, StringUtils::ToClr(origin_url), StringUtils::ToClr(message_text)); break; case JSDIALOGTYPE_CONFIRM: handled = handler->OnJSConfirm(_browserControl, StringUtils::ToClr(origin_url), StringUtils::ToClr(message_text), result); callback->Continue(result, CefString()); break; case JSDIALOGTYPE_PROMPT: String^ resultString = nullptr; result = handler->OnJSPrompt(_browserControl, StringUtils::ToClr(origin_url), StringUtils::ToClr(message_text), StringUtils::ToClr(default_prompt_text), result, resultString); callback->Continue(result, StringUtils::ToNative(resultString)); break; } // Unknown dialog type, so we return "not handled". return false; } } } <|endoftext|>
<commit_before>#pragma once #if defined(__arm__) # define __NR_inotify_init1 360 #elif defined(__x86_64__) # define __NR_inotify_init1 294 #else # error #endif #error <commit_msg>inotify_init1: not needed (yet)<commit_after><|endoftext|>
<commit_before><commit_msg>Fix inverted logic from review.<commit_after><|endoftext|>
<commit_before>#include <iostream> #include "CaffeBatchPrediction.hpp" #include "scalefactor.hpp" #include "fast_nms.hpp" #include "detect.hpp" #include <opencv2/highgui/highgui.hpp> #include <opencv2/gpu/gpu.hpp> static double gtod_wrapper(void) { struct timeval tv; gettimeofday(&tv, NULL); return (double)tv.tv_sec + (double)tv.tv_usec/1000000.0; } // TODO :: can we keep output data in GPU as well? // Simple multi-scale detect. Take a single image, scale it into a number // of diffent sized images. Run a fixed-size detection window across each // of them. Keep track of the scale of each scaled image to map the // detected rectangles back to the correct location and size on the // original input images template <class MatT> void NNDetect<MatT>::detectMultiscale(const cv::Mat &inputImg, const cv::Size &minSize, const cv::Size &maxSize, std::vector<cv::Rect> &rectsOut) { int wsize = classifier.getInputGeometry().width; std::vector<std::pair<MatT, float> > scaledimages; std::vector<cv::Rect> rects; std::vector<int> scales; std::vector<int> scalesOut; generateInitialWindows(inputImg, minSize, maxSize, wsize, scaledimages, rects, scales); runDetection(classifier, scaledimages, rects, scales, .7, "ball", rectsOut, scalesOut); for(size_t i = 0; i < rectsOut.size(); i++) { float scale = scaledimages[scalesOut[i]].second; rectsOut[i] = cv::Rect(rectsOut[i].x/scale, rectsOut[i].y/scale, rectsOut[i].width/scale, rectsOut[i].height/scale); } } template <class MatT> void NNDetect<MatT>::generateInitialWindows( const cv::Mat &input, const cv::Size &minSize, const cv::Size &maxSize, const int wsize, std::vector<std::pair<MatT, float> > &scaledimages, std::vector<cv::Rect> &rects, std::vector<int> &scales) { rects.clear(); scales.clear(); // How many pixels to move the window for each step // TODO : figure out if it makes sense to change this depending on // the size of the scaled input image - i.e. it is possible that // a small step size on an image scaled way larger than the input // will end up detecting too much stuff ... each step on the larger // image might not correspond to a step of 1 pixel on the // input image? const int step = 6; //int step = std::min(img.cols, img.rows) *0.05; double start = gtod_wrapper(); // grab start time // The net expects each pixel to be 3x 32-bit floating point // values. Convert it once here rather than later for every // individual input image. MatT f32Img; MatT(input).convertTo(f32Img, CV_32FC3); // Create array of scaled images scalefactor(f32Img, cv::Size(wsize,wsize), minSize, maxSize, 1.35, scaledimages); // Main loop. Look at each scaled image in turn for (size_t scale = 0; scale < scaledimages.size(); ++scale) { // Start at the upper left corner. Loop through the rows and cols until // the detection window falls off the edges of the scaled image for (int r = 0; (r + wsize) < scaledimages[scale].first.rows; r += step) { for (int c = 0; (c + wsize) < scaledimages[scale].first.cols; c += step) { // Save location and image data for each sub-image rects.push_back(cv::Rect(c, r, wsize, wsize)); scales.push_back(scale); } } } double end = gtod_wrapper(); std::cout << "Elapsed time = " << (end - start) << std::endl; } template <class MatT> void NNDetect<MatT>::runDetection(CaffeClassifier<MatT> &classifier, const std::vector<std::pair<MatT, float> > &scaledimages, const std::vector<cv::Rect> &rects, const std::vector<int> &scales, float threshold, std::string label, std::vector<cv::Rect> &rectsOut, std::vector<int> &scalesOut) { std::vector<MatT> images; std::vector<size_t> detected; int counter = 0; double start = gtod_wrapper(); // grab start time for (size_t i = 0; i < rects.size(); ++i) { images.push_back(scaledimages[scales[i]].first(rects[i])); if((images.size() == classifier.BatchSize()) || (i == rects.size() - 1)) { doBatchPrediction(classifier, images, threshold, label, detected); images.clear(); for(size_t j = 0; j < detected.size(); j++) { rectsOut.push_back(rects[counter*classifier.BatchSize() + detected[j]]); scalesOut.push_back(scales[counter*classifier.BatchSize() + detected[j]]); } counter++; } } double end = gtod_wrapper(); std::cout << "Elapsed time = " << (end - start) << std::endl; } // do 1 run of the classifier. This takes up batch_size predictions and adds anything found // to the detected list template <class MatT> void NNDetect<MatT>::doBatchPrediction(CaffeClassifier<MatT> &classifier, const std::vector<MatT> &imgs, const float threshold, const std::string &label, std::vector<size_t> &detected) { detected.clear(); std::vector <std::vector<Prediction> >predictions = classifier.ClassifyBatch(imgs, 1); // Each outer loop is the predictions for one input image for (size_t i = 0; i < imgs.size(); ++i) { // Look for bins, > 90% confidence for (std::vector <Prediction>::const_iterator it = predictions[i].begin(); it != predictions[i].end(); ++it) { if (it->first == label) { if (it->second > threshold) { detected.push_back(i); } break; } } } } template class NNDetect<cv::Mat>; template class NNDetect<cv::gpu::GpuMat>; <commit_msg>Clean up formatting<commit_after>#include <iostream> #include "CaffeBatchPrediction.hpp" #include "scalefactor.hpp" #include "fast_nms.hpp" #include "detect.hpp" #include <opencv2/highgui/highgui.hpp> #include <opencv2/gpu/gpu.hpp> static double gtod_wrapper(void) { struct timeval tv; gettimeofday(&tv, NULL); return (double)tv.tv_sec + (double)tv.tv_usec/1000000.0; } // TODO :: can we keep output data in GPU as well? // Simple multi-scale detect. Take a single image, scale it into a number // of diffent sized images. Run a fixed-size detection window across each // of them. Keep track of the scale of each scaled image to map the // detected rectangles back to the correct location and size on the // original input images template <class MatT> void NNDetect<MatT>::detectMultiscale(const cv::Mat &inputImg, const cv::Size &minSize, const cv::Size &maxSize, std::vector<cv::Rect> &rectsOut) { int wsize = classifier.getInputGeometry().width; std::vector<std::pair<MatT, float> > scaledimages; std::vector<cv::Rect> rects; std::vector<int> scales; std::vector<int> scalesOut; generateInitialWindows(inputImg, minSize, maxSize, wsize, scaledimages, rects, scales); runDetection(classifier, scaledimages, rects, scales, .7, "ball", rectsOut, scalesOut); for(size_t i = 0; i < rectsOut.size(); i++) { float scale = scaledimages[scalesOut[i]].second; rectsOut[i] = cv::Rect(rectsOut[i].x/scale, rectsOut[i].y/scale, rectsOut[i].width/scale, rectsOut[i].height/scale); } } template <class MatT> void NNDetect<MatT>::generateInitialWindows( const cv::Mat &input, const cv::Size &minSize, const cv::Size &maxSize, const int wsize, std::vector<std::pair<MatT, float> > &scaledimages, std::vector<cv::Rect> &rects, std::vector<int> &scales) { rects.clear(); scales.clear(); // How many pixels to move the window for each step // TODO : figure out if it makes sense to change this depending on // the size of the scaled input image - i.e. it is possible that // a small step size on an image scaled way larger than the input // will end up detecting too much stuff ... each step on the larger // image might not correspond to a step of 1 pixel on the // input image? const int step = 6; //int step = std::min(img.cols, img.rows) *0.05; double start = gtod_wrapper(); // grab start time // The net expects each pixel to be 3x 32-bit floating point // values. Convert it once here rather than later for every // individual input image. MatT f32Img; MatT(input).convertTo(f32Img, CV_32FC3); // Create array of scaled images scalefactor(f32Img, cv::Size(wsize,wsize), minSize, maxSize, 1.35, scaledimages); // Main loop. Look at each scaled image in turn for (size_t scale = 0; scale < scaledimages.size(); ++scale) { // Start at the upper left corner. Loop through the rows and cols until // the detection window falls off the edges of the scaled image for (int r = 0; (r + wsize) < scaledimages[scale].first.rows; r += step) { for (int c = 0; (c + wsize) < scaledimages[scale].first.cols; c += step) { // Save location and image data for each sub-image rects.push_back(cv::Rect(c, r, wsize, wsize)); scales.push_back(scale); } } } double end = gtod_wrapper(); std::cout << "Generate initial windows time = " << (end - start) << std::endl; } template <class MatT> void NNDetect<MatT>::runDetection(CaffeClassifier<MatT> &classifier, const std::vector<std::pair<MatT, float> > &scaledimages, const std::vector<cv::Rect> &rects, const std::vector<int> &scales, float threshold, std::string label, std::vector<cv::Rect> &rectsOut, std::vector<int> &scalesOut) { std::vector<MatT> images; std::vector<size_t> detected; int counter = 0; double start = gtod_wrapper(); // grab start time for (size_t i = 0; i < rects.size(); ++i) { images.push_back(scaledimages[scales[i]].first(rects[i])); if((images.size() == classifier.BatchSize()) || (i == rects.size() - 1)) { doBatchPrediction(classifier, images, threshold, label, detected); images.clear(); for(size_t j = 0; j < detected.size(); j++) { rectsOut.push_back(rects[counter*classifier.BatchSize() + detected[j]]); scalesOut.push_back(scales[counter*classifier.BatchSize() + detected[j]]); } counter++; } } double end = gtod_wrapper(); std::cout << "runDetection time = " << (end - start) << std::endl; } // do 1 run of the classifier. This takes up batch_size predictions and adds anything found // to the detected list template <class MatT> void NNDetect<MatT>::doBatchPrediction(CaffeClassifier<MatT> &classifier, const std::vector<MatT> &imgs, const float threshold, const std::string &label, std::vector<size_t> &detected) { detected.clear(); std::vector <std::vector<Prediction> >predictions = classifier.ClassifyBatch(imgs, 1); // Each outer loop is the predictions for one input image for (size_t i = 0; i < imgs.size(); ++i) { // Each inner loop is the prediction for a particular label // for the given image, sorted by score. // // Look for object with label <label>, > threshold confidence for (std::vector <Prediction>::const_iterator it = predictions[i].begin(); it != predictions[i].end(); ++it) { if (it->first == label) { if (it->second > threshold) { detected.push_back(i); } break; } } } } // Explicitly instatiate classes used elsewhere template class NNDetect<cv::Mat>; template class NNDetect<cv::gpu::GpuMat>; <|endoftext|>
<commit_before>// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <iostream> // Local Includes #include "adjoint_residual_error_estimator.h" #include "error_vector.h" #include "patch_recovery_error_estimator.h" #include "libmesh_logging.h" #include "numeric_vector.h" #include "system.h" #include "system_norm.h" #include "qoi_set.h" namespace libMesh { //----------------------------------------------------------------- // AdjointResidualErrorEstimator implementations AdjointResidualErrorEstimator::AdjointResidualErrorEstimator () : adjoint_already_solved(false), error_plot_suffix(), _primal_error_estimator(new PatchRecoveryErrorEstimator()), _dual_error_estimator(new PatchRecoveryErrorEstimator()), _qoi_set(QoISet()) { } void AdjointResidualErrorEstimator::estimate_error (const System& _system, ErrorVector& error_per_cell, const NumericVector<Number>* solution_vector, bool estimate_parent_error) { START_LOG("estimate_error()", "AdjointResidualErrorEstimator"); // The current mesh const MeshBase& mesh = _system.get_mesh(); // Resize the error_per_cell vector to be // the number of elements, initialize it to 0. error_per_cell.resize (mesh.max_elem_id()); std::fill (error_per_cell.begin(), error_per_cell.end(), 0.); // Get the number of variables in the system unsigned int n_vars = _system.n_vars(); // We need to make a map of the pointer to the solution vector std::map<const System*, const NumericVector<Number>*>solutionvecs; solutionvecs[&_system] = _system.solution.get(); // Solve the dual problem if we have to if (!adjoint_already_solved) { // FIXME - we'll need to change a lot of APIs to make this trick // work with a const System... System& system = const_cast<System&>(_system); system.adjoint_solve(_qoi_set); } // Flag to check whether we have not been asked to weight the variable error contributions in any specific manner bool error_norm_is_identity = error_norm.is_identity(); // Create an ErrorMap/ErrorVector to store the primal, dual and total_dual variable errors ErrorMap primal_errors_per_cell; ErrorMap dual_errors_per_cell; ErrorMap total_dual_errors_per_cell; // Allocate ErrorVectors to this map if we're going to use it if (!error_norm_is_identity) for(unsigned int v = 0; v < n_vars; v++) { primal_errors_per_cell[std::make_pair(&_system, v)] = new ErrorVector; dual_errors_per_cell[std::make_pair(&_system, v)] = new ErrorVector; total_dual_errors_per_cell[std::make_pair(&_system, v)] = new ErrorVector; } ErrorVector primal_error_per_cell; ErrorVector dual_error_per_cell; ErrorVector total_dual_error_per_cell; // Get the error estimator object's SystemNorm object to compute the weighted error estimate u^T M z error_norm = this->error_norm; // Have we been asked to weight the variable error contributions in any specific manner if(!error_norm_is_identity) // If we do { // Estimate the primal problem error for each variable _primal_error_estimator->estimate_errors (_system.get_equation_systems(), primal_errors_per_cell, &solutionvecs, estimate_parent_error); } else // If not { // Just get the combined error estimate _primal_error_estimator->estimate_error (_system, primal_error_per_cell, solution_vector, estimate_parent_error); } // Sum and weight the dual error estimate based on our QoISet for (unsigned int i = 0; i != _system.qoi.size(); ++i) { if (_qoi_set.has_index(i)) { // Get the weight for the current QoI Real error_weight = _qoi_set.weight(i); // We need to make a map of the pointer to the adjoint solution vector std::map<const System*, const NumericVector<Number>*>adjointsolutionvecs; adjointsolutionvecs[&_system] = &_system.get_adjoint_solution(i); // Have we been asked to weight the variable error contributions in any specific manner if(!error_norm_is_identity) // If we have { _dual_error_estimator->estimate_errors (_system.get_equation_systems(), dual_errors_per_cell, &adjointsolutionvecs, estimate_parent_error); } else // If not { // Just get the combined error estimate _dual_error_estimator->estimate_error (_system, dual_error_per_cell, &(_system.get_adjoint_solution(i)), estimate_parent_error); } unsigned int error_size; // Get the size of the first ErrorMap vector; this will give us the number of elements if(!error_norm_is_identity) // If in non default weights case { error_size = dual_errors_per_cell[std::make_pair(&_system, 0)]->size(); } else // If in the standard default weights case { error_size = dual_error_per_cell.size(); } // Resize the ErrorVector(s) if(!error_norm_is_identity) { // Loop over variables for(unsigned int v = 0; v < n_vars; v++) { libmesh_assert(!total_dual_errors_per_cell[std::make_pair(&_system, v)]->size() || total_dual_errors_per_cell[std::make_pair(&_system, v)]->size() == error_size) ; total_dual_errors_per_cell[std::make_pair(&_system, v)]->resize(error_size); } } else { libmesh_assert(!total_dual_error_per_cell.size() || total_dual_error_per_cell.size() == error_size); total_dual_error_per_cell.resize(error_size); } for (unsigned int e = 0; e != error_size; ++e) { // Have we been asked to weight the variable error contributions in any specific manner if(!error_norm_is_identity) // If we have { // Loop over variables for(unsigned int v = 0; v < n_vars; v++) { // Now fill in total_dual_error ErrorMap with the weight (*total_dual_errors_per_cell[std::make_pair(&_system, v)])[e] += error_weight * (*dual_errors_per_cell[std::make_pair(&_system, v)])[e]; } } else // If not { total_dual_error_per_cell[e] += error_weight * dual_error_per_cell[e]; } } } } // Do some debugging plots if requested if (!error_plot_suffix.empty()) { if(!error_norm_is_identity) // If we have { // Loop over variables for(unsigned int v = 0; v < n_vars; v++) { OStringStream primal_out; OStringStream dual_out; primal_out << "primal_" << error_plot_suffix << "."; dual_out << "dual_" << error_plot_suffix << "."; OSSRealzeroright(primal_out, 1,0,v); OSSRealzeroright(dual_out, 1,0,v); (*primal_errors_per_cell[std::make_pair(&_system, v)]).plot_error(primal_out.str(), _system.get_mesh()); (*total_dual_errors_per_cell[std::make_pair(&_system, v)]).plot_error(dual_out.str(), _system.get_mesh()); primal_out.clear(); dual_out.clear(); } } else // If not { OStringStream primal_out; OStringStream dual_out; primal_out << "primal_" << error_plot_suffix ; dual_out << "dual_" << error_plot_suffix ; primal_error_per_cell.plot_error(primal_out.str(), _system.get_mesh()); total_dual_error_per_cell.plot_error(dual_out.str(), _system.get_mesh()); primal_out.clear(); dual_out.clear(); } } // Weight the primal error by the dual error using the system norm object // FIXME: we ought to thread this for (unsigned int i=0; i != error_per_cell.size(); ++i) { // Have we been asked to weight the variable error contributions in any specific manner if(!error_norm_is_identity) // If we do { // Create Error Vectors to pass to calculate_norm std::vector<Real> cell_primal_error; std::vector<Real> cell_dual_error; for(unsigned int v = 0; v < n_vars; v++) { cell_primal_error.push_back((*primal_errors_per_cell[std::make_pair(&_system, v)])[i]); cell_dual_error.push_back((*total_dual_errors_per_cell[std::make_pair(&_system, v)])[i]); } error_per_cell[i] = error_norm.calculate_norm(cell_primal_error, cell_dual_error); } else // If not { error_per_cell[i] = primal_error_per_cell[i]*total_dual_error_per_cell[i]; } } // Deallocate the ErrorMap contents if we allocated them earlier if (!error_norm_is_identity) for(unsigned int v = 0; v < n_vars; v++) { delete primal_errors_per_cell[std::make_pair(&_system, v)]; delete dual_errors_per_cell[std::make_pair(&_system, v)]; delete total_dual_errors_per_cell[std::make_pair(&_system, v)]; } STOP_LOG("estimate_error()", "AdjointResidualErrorEstimator"); } } // namespace libMesh <commit_msg>Removing redundant copy<commit_after>// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <iostream> // Local Includes #include "adjoint_residual_error_estimator.h" #include "error_vector.h" #include "patch_recovery_error_estimator.h" #include "libmesh_logging.h" #include "numeric_vector.h" #include "system.h" #include "system_norm.h" #include "qoi_set.h" namespace libMesh { //----------------------------------------------------------------- // AdjointResidualErrorEstimator implementations AdjointResidualErrorEstimator::AdjointResidualErrorEstimator () : adjoint_already_solved(false), error_plot_suffix(), _primal_error_estimator(new PatchRecoveryErrorEstimator()), _dual_error_estimator(new PatchRecoveryErrorEstimator()), _qoi_set(QoISet()) { } void AdjointResidualErrorEstimator::estimate_error (const System& _system, ErrorVector& error_per_cell, const NumericVector<Number>* solution_vector, bool estimate_parent_error) { START_LOG("estimate_error()", "AdjointResidualErrorEstimator"); // The current mesh const MeshBase& mesh = _system.get_mesh(); // Resize the error_per_cell vector to be // the number of elements, initialize it to 0. error_per_cell.resize (mesh.max_elem_id()); std::fill (error_per_cell.begin(), error_per_cell.end(), 0.); // Get the number of variables in the system unsigned int n_vars = _system.n_vars(); // We need to make a map of the pointer to the solution vector std::map<const System*, const NumericVector<Number>*>solutionvecs; solutionvecs[&_system] = _system.solution.get(); // Solve the dual problem if we have to if (!adjoint_already_solved) { // FIXME - we'll need to change a lot of APIs to make this trick // work with a const System... System& system = const_cast<System&>(_system); system.adjoint_solve(_qoi_set); } // Flag to check whether we have not been asked to weight the variable error contributions in any specific manner bool error_norm_is_identity = error_norm.is_identity(); // Create an ErrorMap/ErrorVector to store the primal, dual and total_dual variable errors ErrorMap primal_errors_per_cell; ErrorMap dual_errors_per_cell; ErrorMap total_dual_errors_per_cell; // Allocate ErrorVectors to this map if we're going to use it if (!error_norm_is_identity) for(unsigned int v = 0; v < n_vars; v++) { primal_errors_per_cell[std::make_pair(&_system, v)] = new ErrorVector; dual_errors_per_cell[std::make_pair(&_system, v)] = new ErrorVector; total_dual_errors_per_cell[std::make_pair(&_system, v)] = new ErrorVector; } ErrorVector primal_error_per_cell; ErrorVector dual_error_per_cell; ErrorVector total_dual_error_per_cell; // Have we been asked to weight the variable error contributions in any specific manner if(!error_norm_is_identity) // If we do { // Estimate the primal problem error for each variable _primal_error_estimator->estimate_errors (_system.get_equation_systems(), primal_errors_per_cell, &solutionvecs, estimate_parent_error); } else // If not { // Just get the combined error estimate _primal_error_estimator->estimate_error (_system, primal_error_per_cell, solution_vector, estimate_parent_error); } // Sum and weight the dual error estimate based on our QoISet for (unsigned int i = 0; i != _system.qoi.size(); ++i) { if (_qoi_set.has_index(i)) { // Get the weight for the current QoI Real error_weight = _qoi_set.weight(i); // We need to make a map of the pointer to the adjoint solution vector std::map<const System*, const NumericVector<Number>*>adjointsolutionvecs; adjointsolutionvecs[&_system] = &_system.get_adjoint_solution(i); // Have we been asked to weight the variable error contributions in any specific manner if(!error_norm_is_identity) // If we have { _dual_error_estimator->estimate_errors (_system.get_equation_systems(), dual_errors_per_cell, &adjointsolutionvecs, estimate_parent_error); } else // If not { // Just get the combined error estimate _dual_error_estimator->estimate_error (_system, dual_error_per_cell, &(_system.get_adjoint_solution(i)), estimate_parent_error); } unsigned int error_size; // Get the size of the first ErrorMap vector; this will give us the number of elements if(!error_norm_is_identity) // If in non default weights case { error_size = dual_errors_per_cell[std::make_pair(&_system, 0)]->size(); } else // If in the standard default weights case { error_size = dual_error_per_cell.size(); } // Resize the ErrorVector(s) if(!error_norm_is_identity) { // Loop over variables for(unsigned int v = 0; v < n_vars; v++) { libmesh_assert(!total_dual_errors_per_cell[std::make_pair(&_system, v)]->size() || total_dual_errors_per_cell[std::make_pair(&_system, v)]->size() == error_size) ; total_dual_errors_per_cell[std::make_pair(&_system, v)]->resize(error_size); } } else { libmesh_assert(!total_dual_error_per_cell.size() || total_dual_error_per_cell.size() == error_size); total_dual_error_per_cell.resize(error_size); } for (unsigned int e = 0; e != error_size; ++e) { // Have we been asked to weight the variable error contributions in any specific manner if(!error_norm_is_identity) // If we have { // Loop over variables for(unsigned int v = 0; v < n_vars; v++) { // Now fill in total_dual_error ErrorMap with the weight (*total_dual_errors_per_cell[std::make_pair(&_system, v)])[e] += error_weight * (*dual_errors_per_cell[std::make_pair(&_system, v)])[e]; } } else // If not { total_dual_error_per_cell[e] += error_weight * dual_error_per_cell[e]; } } } } // Do some debugging plots if requested if (!error_plot_suffix.empty()) { if(!error_norm_is_identity) // If we have { // Loop over variables for(unsigned int v = 0; v < n_vars; v++) { OStringStream primal_out; OStringStream dual_out; primal_out << "primal_" << error_plot_suffix << "."; dual_out << "dual_" << error_plot_suffix << "."; OSSRealzeroright(primal_out, 1,0,v); OSSRealzeroright(dual_out, 1,0,v); (*primal_errors_per_cell[std::make_pair(&_system, v)]).plot_error(primal_out.str(), _system.get_mesh()); (*total_dual_errors_per_cell[std::make_pair(&_system, v)]).plot_error(dual_out.str(), _system.get_mesh()); primal_out.clear(); dual_out.clear(); } } else // If not { OStringStream primal_out; OStringStream dual_out; primal_out << "primal_" << error_plot_suffix ; dual_out << "dual_" << error_plot_suffix ; primal_error_per_cell.plot_error(primal_out.str(), _system.get_mesh()); total_dual_error_per_cell.plot_error(dual_out.str(), _system.get_mesh()); primal_out.clear(); dual_out.clear(); } } // Weight the primal error by the dual error using the system norm object // FIXME: we ought to thread this for (unsigned int i=0; i != error_per_cell.size(); ++i) { // Have we been asked to weight the variable error contributions in any specific manner if(!error_norm_is_identity) // If we do { // Create Error Vectors to pass to calculate_norm std::vector<Real> cell_primal_error; std::vector<Real> cell_dual_error; for(unsigned int v = 0; v < n_vars; v++) { cell_primal_error.push_back((*primal_errors_per_cell[std::make_pair(&_system, v)])[i]); cell_dual_error.push_back((*total_dual_errors_per_cell[std::make_pair(&_system, v)])[i]); } error_per_cell[i] = error_norm.calculate_norm(cell_primal_error, cell_dual_error); } else // If not { error_per_cell[i] = primal_error_per_cell[i]*total_dual_error_per_cell[i]; } } // Deallocate the ErrorMap contents if we allocated them earlier if (!error_norm_is_identity) for(unsigned int v = 0; v < n_vars; v++) { delete primal_errors_per_cell[std::make_pair(&_system, v)]; delete dual_errors_per_cell[std::make_pair(&_system, v)]; delete total_dual_errors_per_cell[std::make_pair(&_system, v)]; } STOP_LOG("estimate_error()", "AdjointResidualErrorEstimator"); } } // namespace libMesh <|endoftext|>
<commit_before>/* * Use potentiometer to set servo arm angle through Servo API. * This example uses an 8-bit timer. * * Wiring: * - on ATmega328P based boards (including Arduino UNO): * - A0: connected to the wiper of a 10K pot or trimmer, which terminals are connected between Vcc and Gnd * - D6: LED connected to GND through a 1K resistor */ #include <fastarduino/boards/board.h> #include <fastarduino/analog_input.h> #include <fastarduino/time.h> #include <fastarduino/pulse_timer.h> #include <fastarduino/devices/servo.h> constexpr const board::Timer TIMER = board::Timer::TIMER0; using TCALC = timer::Calculator<TIMER>; using TPRESCALER = TCALC::TIMER_PRESCALER; // Constants for servo and prescaler to be used for TIMER constexpr const uint16_t MAX_PULSE_US = 2000; constexpr const uint16_t MIN_PULSE_US = 1000; constexpr const uint16_t PULSE_FREQUENCY = 50; constexpr const TPRESCALER PRESCALER = TCALC::PulseTimer_prescaler(MAX_PULSE_US, PULSE_FREQUENCY); // PIN connected to servo signal constexpr const board::DigitalPin SERVO_PIN1 = board::PWMPin::D6_PD6_OC0A; // Predefine types used for Timer and Servo using PULSE_TIMER = timer::PulseTimer<TIMER, PRESCALER>; using SERVO1 = devices::servo::Servo<PULSE_TIMER, SERVO_PIN1>; constexpr const board::AnalogPin POT1 = board::AnalogPin::A1; using ANALOG1_INPUT = analog::AnalogInput<POT1, board::AnalogReference::AVCC, uint8_t, board::AnalogClock::MAX_FREQ_200KHz>; // Register ISR needed for PulseTimer (8 bits specific) //REGISTER_PULSE_TIMER8_AB_ISR(0, PRESCALER, SERVO_PIN1, SERVO_PIN2) REGISTER_PULSE_TIMER8_A_ISR(0, PRESCALER, SERVO_PIN1) int main() __attribute__((OS_main)); int main() { // Instantiate pulse timer for servo PULSE_TIMER servo_timer{PULSE_FREQUENCY}; // Instantiate servo SERVO1 servo1{servo_timer, MIN_PULSE_US, MAX_PULSE_US}; // Start pulse timer servo_timer._begin(); // Enable interrupts sei(); ANALOG1_INPUT pot1; // servo1.detach(); while (true) { uint16_t input1 = pot1.sample(); // 3 API methods are available to set the Servo signal // 1. Direct timer counter value (0..255 on 8-bits timer, constrained to servo range) // servo1.set_counter(input1); // 2. Pulse duration in us (MIN_PULSE_US..MAX_PULSE_US) // servo1.set_pulse(MIN_PULSE_US + input1 * 4); // 3. Angle in degrees (-90..+90) servo1.rotate(int16_t(input1) - 128); time::delay_ms(100); } } <commit_msg>Improve first example for new Servo API.<commit_after>/* * Use potentiometer to set servo arm angle through Servo API. * This example uses an 8-bit timer. * The servo I use in this example is a TowerPro SG90. * * Wiring: * - on ATmega328P based boards (including Arduino UNO): * - A1: connected to the wiper of a 10K pot or trimmer, which terminals are connected between Vcc and Gnd * - D6: connected to servo signal pin (orange wire) */ #include <fastarduino/boards/board.h> #include <fastarduino/analog_input.h> #include <fastarduino/time.h> #include <fastarduino/pulse_timer.h> #include <fastarduino/devices/servo.h> constexpr const board::Timer TIMER = board::Timer::TIMER0; using TCALC = timer::Calculator<TIMER>; using TPRESCALER = TCALC::TIMER_PRESCALER; // Constants for servo and prescaler to be used for TIMER //constexpr const uint16_t MAX_PULSE_US = 2400; //constexpr const uint16_t MIN_PULSE_US = 900; constexpr const uint16_t MAX_PULSE_US = 2400; constexpr const uint16_t MIN_PULSE_US = 544; constexpr const uint16_t NEUTRAL_PULSE_US = 1500; constexpr const uint16_t PULSE_FREQUENCY = 50; constexpr const TPRESCALER PRESCALER = TCALC::PulseTimer_prescaler(MAX_PULSE_US, PULSE_FREQUENCY); // PIN connected to servo signal constexpr const board::DigitalPin SERVO_PIN1 = board::PWMPin::D6_PD6_OC0A; // Predefine types used for Timer and Servo using PULSE_TIMER = timer::PulseTimer<TIMER, PRESCALER>; using SERVO1 = devices::servo::Servo<PULSE_TIMER, SERVO_PIN1>; constexpr const board::AnalogPin POT1 = board::AnalogPin::A1; using ANALOG1_INPUT = analog::AnalogInput<POT1, board::AnalogReference::AVCC, uint8_t, board::AnalogClock::MAX_FREQ_200KHz>; // Register ISR needed for PulseTimer (8 bits specific) //REGISTER_PULSE_TIMER8_AB_ISR(0, PRESCALER, SERVO_PIN1, SERVO_PIN2) REGISTER_PULSE_TIMER8_A_ISR(0, PRESCALER, SERVO_PIN1) int main() __attribute__((OS_main)); int main() { // Instantiate pulse timer for servo PULSE_TIMER servo_timer{PULSE_FREQUENCY}; // Instantiate servo SERVO1 servo1{servo_timer, MIN_PULSE_US, MAX_PULSE_US, NEUTRAL_PULSE_US}; // Start pulse timer servo_timer._begin(); // Enable interrupts sei(); ANALOG1_INPUT pot1; // servo1.detach(); while (true) { uint16_t input1 = pot1.sample(); // 3 API methods are available to set the Servo signal // 1. Direct timer counter value (0..255 on 8-bits timer, constrained to servo range) // servo1.set_counter(input1); // 2. Pulse duration in us (MIN_PULSE_US..MAX_PULSE_US) // servo1.set_pulse(MIN_PULSE_US + input1 * 4); // 3. Angle in degrees (-90..+90) servo1.rotate(int16_t(input1) - 128); time::delay_ms(100); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageWriter.h" #include "mitkDataNodeFactory.h" #include "mitkTestingMacros.h" #include <iostream> #include <fstream> #ifdef WIN32 #include "process.h" #endif std::string AppendExtension(const std::string &filename, const char *extension) { std::string new_filename = filename; new_filename += extension; return new_filename; } /** * test for "ImageWriter". * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test image for the image tests (see CMakeLists.txt). */ int mitkImageWriterTest(int argc , char* argv[]) { // always start with this! MITK_TEST_BEGIN("ImageWriter") // let's create an object of our class mitk::ImageWriter::Pointer myImageWriter = mitk::ImageWriter::New(); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(myImageWriter.IsNotNull(),"Testing instantiation") // write your own tests here and use the macros from mitkTestingMacros.h !!! // do not write to std::cout and do not return from this function yourself! // load image MITK_TEST_CONDITION_REQUIRED(argc != 0, "File to load has been specified"); mitk::Image::Pointer image = NULL; mitk::DataNodeFactory::Pointer factory = mitk::DataNodeFactory::New(); try { MITK_TEST_OUTPUT(<< "Loading file: " << argv[1]); factory->SetFileName( argv[1] ); factory->Update(); MITK_TEST_CONDITION_REQUIRED(factory->GetNumberOfOutputs() > 0, "file loaded"); mitk::DataNode::Pointer node = factory->GetOutput( 0 ); image = dynamic_cast<mitk::Image*>(node->GetData()); if(image.IsNull()) { std::cout<<"file "<< argv[1]<< "is not an image - test will not be applied."<<std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } } catch (itk::ExceptionObject & ex) { MITK_TEST_FAILED_MSG(<< "Exception during file loading: " << ex.GetDescription()); } MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"loaded image not NULL") std::stringstream filename_stream; #ifdef WIN32 filename_stream << "test" << _getpid(); #else filename_stream << "test" << getpid(); #endif std::string filename = filename_stream.str(); // test set/get methods myImageWriter->SetInput(image); MITK_TEST_CONDITION_REQUIRED(myImageWriter->GetInput()==image,"test Set/GetInput()"); myImageWriter->SetFileName(filename); MITK_TEST_CONDITION_REQUIRED(!strcmp(myImageWriter->GetFileName(),filename.c_str()),"test Set/GetFileName()"); myImageWriter->SetFilePrefix("pref"); MITK_TEST_CONDITION_REQUIRED(!strcmp(myImageWriter->GetFilePrefix(),"pref"),"test Set/GetFilePrefix()"); myImageWriter->SetFilePattern("pattern"); MITK_TEST_CONDITION_REQUIRED(!strcmp(myImageWriter->GetFilePattern(),"pattern"),"test Set/GetFilePattern()"); // write ITK .mhd image (2D and 3D only) if( image->GetDimension() <= 3 ) { try { myImageWriter->SetExtension(".mhd"); myImageWriter->Update(); std::fstream fin, fin2; fin.open(AppendExtension(filename, ".mhd").c_str(),std::ios::in); fin2.open(AppendExtension(filename, ".raw").c_str(),std::ios::in); MITK_TEST_CONDITION_REQUIRED(fin.is_open(),"Write .mhd file"); MITK_TEST_CONDITION_REQUIRED(fin2.is_open(),"Write .raw file"); fin.close(); fin2.close(); remove(AppendExtension(filename, ".mhd").c_str()); remove(AppendExtension(filename, ".raw").c_str()); } catch (...) { MITK_TEST_FAILED_MSG(<< "Exception during .mhd file writing"); } } //testing more component image writing as nrrd files try { myImageWriter->SetExtension(".nrrd"); myImageWriter->Update(); std::fstream fin; fin.open(AppendExtension(filename, ".nrrd").c_str(),std::ios::in); MITK_TEST_CONDITION_REQUIRED(fin.is_open(),"Write .nrrd file"); fin.close(); remove(AppendExtension(filename, ".nrrd").c_str()); } catch(...) { MITK_TEST_FAILED_MSG(<< "Exception during .nrrd file writing"); } // test for exception handling try { MITK_TEST_FOR_EXCEPTION_BEGIN(itk::ExceptionObject) myImageWriter->SetInput(image); myImageWriter->SetFileName("/usr/bin"); myImageWriter->Update(); MITK_TEST_FOR_EXCEPTION_END(itk::ExceptionObject) } catch(...) { //this means that a wrong exception (i.e. no itk:Exception) has been thrown MITK_TEST_FAILED_MSG(<< "Wrong exception (i.e. no itk:Exception) caught during write"); } // always end with this! MITK_TEST_END(); } <commit_msg>COMP support raw files in its compressed form<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageWriter.h" #include "mitkDataNodeFactory.h" #include "mitkTestingMacros.h" #include <iostream> #include <fstream> #ifdef WIN32 #include "process.h" #endif std::string AppendExtension(const std::string &filename, const char *extension) { std::string new_filename = filename; new_filename += extension; return new_filename; } /** * test for "ImageWriter". * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test image for the image tests (see CMakeLists.txt). */ int mitkImageWriterTest(int argc , char* argv[]) { // always start with this! MITK_TEST_BEGIN("ImageWriter") // let's create an object of our class mitk::ImageWriter::Pointer myImageWriter = mitk::ImageWriter::New(); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(myImageWriter.IsNotNull(),"Testing instantiation") // write your own tests here and use the macros from mitkTestingMacros.h !!! // do not write to std::cout and do not return from this function yourself! // load image MITK_TEST_CONDITION_REQUIRED(argc != 0, "File to load has been specified"); mitk::Image::Pointer image = NULL; mitk::DataNodeFactory::Pointer factory = mitk::DataNodeFactory::New(); try { MITK_TEST_OUTPUT(<< "Loading file: " << argv[1]); factory->SetFileName( argv[1] ); factory->Update(); MITK_TEST_CONDITION_REQUIRED(factory->GetNumberOfOutputs() > 0, "file loaded"); mitk::DataNode::Pointer node = factory->GetOutput( 0 ); image = dynamic_cast<mitk::Image*>(node->GetData()); if(image.IsNull()) { std::cout<<"file "<< argv[1]<< "is not an image - test will not be applied."<<std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } } catch (itk::ExceptionObject & ex) { MITK_TEST_FAILED_MSG(<< "Exception during file loading: " << ex.GetDescription()); } MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"loaded image not NULL") std::stringstream filename_stream; #ifdef WIN32 filename_stream << "test" << _getpid(); #else filename_stream << "test" << getpid(); #endif std::string filename = filename_stream.str(); // test set/get methods myImageWriter->SetInput(image); MITK_TEST_CONDITION_REQUIRED(myImageWriter->GetInput()==image,"test Set/GetInput()"); myImageWriter->SetFileName(filename); MITK_TEST_CONDITION_REQUIRED(!strcmp(myImageWriter->GetFileName(),filename.c_str()),"test Set/GetFileName()"); myImageWriter->SetFilePrefix("pref"); MITK_TEST_CONDITION_REQUIRED(!strcmp(myImageWriter->GetFilePrefix(),"pref"),"test Set/GetFilePrefix()"); myImageWriter->SetFilePattern("pattern"); MITK_TEST_CONDITION_REQUIRED(!strcmp(myImageWriter->GetFilePattern(),"pattern"),"test Set/GetFilePattern()"); // write ITK .mhd image (2D and 3D only) if( image->GetDimension() <= 3 ) { try { myImageWriter->SetExtension(".mhd"); myImageWriter->Update(); std::fstream fin, fin2; fin.open(AppendExtension(filename, ".mhd").c_str(),std::ios::in); std::string rawExtension = ".raw"; fin2.open(AppendExtension(filename, ".raw").c_str(),std::ios::in); if( !fin2.is_open() ) { rawExtension = ".zraw"; fin2.open(AppendExtension(filename, ".zraw").c_str(),std::ios::in); } MITK_TEST_CONDITION_REQUIRED(fin.is_open(),"Write .mhd file"); MITK_TEST_CONDITION_REQUIRED(fin2.is_open(),"Write .raw file"); fin.close(); fin2.close(); remove(AppendExtension(filename, ".mhd").c_str()); remove(AppendExtension(filename, rawExtension.c_str()).c_str()); } catch (...) { MITK_TEST_FAILED_MSG(<< "Exception during .mhd file writing"); } } //testing more component image writing as nrrd files try { myImageWriter->SetExtension(".nrrd"); myImageWriter->Update(); std::fstream fin; fin.open(AppendExtension(filename, ".nrrd").c_str(),std::ios::in); MITK_TEST_CONDITION_REQUIRED(fin.is_open(),"Write .nrrd file"); fin.close(); remove(AppendExtension(filename, ".nrrd").c_str()); } catch(...) { MITK_TEST_FAILED_MSG(<< "Exception during .nrrd file writing"); } // test for exception handling try { MITK_TEST_FOR_EXCEPTION_BEGIN(itk::ExceptionObject) myImageWriter->SetInput(image); myImageWriter->SetFileName("/usr/bin"); myImageWriter->Update(); MITK_TEST_FOR_EXCEPTION_END(itk::ExceptionObject) } catch(...) { //this means that a wrong exception (i.e. no itk:Exception) has been thrown MITK_TEST_FAILED_MSG(<< "Wrong exception (i.e. no itk:Exception) caught during write"); } // always end with this! MITK_TEST_END(); } <|endoftext|>
<commit_before>/* Copyright (C) 2011 by Ivan Safrin 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 "PolyTweenManager.h" #include "PolyTween.h" #include "PolyCore.h" using namespace Polycode; TweenManager::TweenManager() { } TweenManager::~TweenManager() { } void TweenManager::addTween(Tween *tween) { tweensToAdd.push_back(tween); } void TweenManager::removeTween(Tween *tween) { for(int i=0; i < tweens.size(); i++) { if(tweens[i] == tween) { tweens.erase(tweens.begin()+i); return; } } } void TweenManager::removeTweensForTarget(Number *target) { std::vector<Tween*>::iterator iter = tweens.begin(); while (iter != tweens.end()) { bool mustRemove = false; if(target == (*iter)->getTarget()) { mustRemove = true; (*iter)->doOnComplete(); if((*iter)->deleteOnComplete) { Tween *tween = (*iter); delete tween; } } if(mustRemove) { iter = tweens.erase(iter); } else { ++iter; } } } void TweenManager::Update(Number elapsed) { std::vector<Tween*>::iterator iter = tweens.begin(); while (iter != tweens.end()) { bool mustRemove = false; (*iter)->updateTween(elapsed/1000.0); if((*iter)->isComplete()) { if((*iter)->repeat) { (*iter)->Reset(); } else { mustRemove = true; (*iter)->doOnComplete(); if((*iter)->deleteOnComplete) { Tween *tween = (*iter); delete tween; } } } if(mustRemove) { iter = tweens.erase(iter); } else { ++iter; } } for(int i=0; i < tweensToAdd.size(); i++) { tweens.push_back(tweensToAdd[i]); } tweensToAdd.clear(); } <commit_msg>Fixed bug in TweenManager that called onComplete on forced tween removal<commit_after>/* Copyright (C) 2011 by Ivan Safrin 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 "PolyTweenManager.h" #include "PolyTween.h" #include "PolyCore.h" using namespace Polycode; TweenManager::TweenManager() { } TweenManager::~TweenManager() { } void TweenManager::addTween(Tween *tween) { tweensToAdd.push_back(tween); } void TweenManager::removeTween(Tween *tween) { for(int i=0; i < tweens.size(); i++) { if(tweens[i] == tween) { tweens.erase(tweens.begin()+i); return; } } } void TweenManager::removeTweensForTarget(Number *target) { std::vector<Tween*>::iterator iter = tweens.begin(); while (iter != tweens.end()) { bool mustRemove = false; if(target == (*iter)->getTarget()) { mustRemove = true; if((*iter)->deleteOnComplete) { Tween *tween = (*iter); delete tween; } } if(mustRemove) { iter = tweens.erase(iter); } else { ++iter; } } } void TweenManager::Update(Number elapsed) { std::vector<Tween*>::iterator iter = tweens.begin(); while (iter != tweens.end()) { bool mustRemove = false; (*iter)->updateTween(elapsed/1000.0); if((*iter)->isComplete()) { if((*iter)->repeat) { (*iter)->Reset(); } else { mustRemove = true; (*iter)->doOnComplete(); if((*iter)->deleteOnComplete) { Tween *tween = (*iter); delete tween; } } } if(mustRemove) { iter = tweens.erase(iter); } else { ++iter; } } for(int i=0; i < tweensToAdd.size(); i++) { tweens.push_back(tweensToAdd[i]); } tweensToAdd.clear(); } <|endoftext|>
<commit_before>#include "virtualbicycle.h" #include "angle.h" #include "packet/serialize.h" #include "packet/frame.h" #include "parameters.h" #include <array> namespace { std::array<uint8_t, BicyclePoseMessage_size> serialize_buffer; std::array<uint8_t, BicyclePoseMessage_size + packet::frame::PACKET_OVERHEAD> frame_buffer; } // namespace VirtualBicycle::VirtualBicycle(float v, float dt, float sigma0, float sigma1) : m_bicycle(v , dt), m_kalman(m_bicycle, /* bicycle model used in Kalman filter */ parameters::defaultvalue::kalman::Q(dt), /* process noise cov */ (kalman_t::measurement_noise_covariance_t() << /* measurement noise cov */ sigma0, 0, 0, sigma1).finished(), bicycle_t::state_t::Zero(), /* initial state estimate */ std::pow(sigma0, 2)*bicycle_t::state_matrix_t::Identity()), /* error cov */ // FIXME m_pose_size(0) { m_u.setZero(); m_z.setZero(); m_x_aux.setZero(); /* use an initial guess of 30 degrees for pitch */ m_x_aux[2] = m_bicycle.solve_constraint_pitch(m_kalman.x(), 30 * constants::as_radians); m_pose = BicyclePoseMessage_init_zero; m_pose.pitch = m_x_aux[2]; } void VirtualBicycle::update(float roll_torque_input, float steer_torque_input, /* u[0], u[1] */ float yaw_angle_measurement, float steer_angle_measurement) { /* z[0], z[1] */ m_u << roll_torque_input, steer_torque_input; m_z << yaw_angle_measurement, steer_angle_measurement; m_kalman.time_update(m_u); m_kalman.measurement_update(m_z); m_x_aux = m_bicycle.x_aux_next(m_kalman.x(), m_x_aux); m_pose.timestamp = 1; // FIXME when running at a different rate m_pose.x = m_x_aux[0]; m_pose.y = m_x_aux[1]; m_pose.pitch = m_x_aux[2]; m_pose.yaw = m_kalman.x()[0]; m_pose.roll = m_kalman.x()[1]; m_pose.steer = m_kalman.x()[2]; } /* WARNING: this member function is not thread safe with multiple VirtualBicycle objects */ uint8_t VirtualBicycle::encode_and_stuff_pose() { uint8_t bytes_written = packet::serialize::encode(m_pose, serialize_buffer.data(), serialize_buffer.size()); packet::frame::stuff(serialize_buffer.data(), frame_buffer.data(), bytes_written); m_pose_size = bytes_written + packet::frame::PACKET_OVERHEAD; return m_pose_size; } const VirtualBicycle::bicycle_t::state_t& VirtualBicycle::x() const { return m_kalman.x(); } const VirtualBicycle::bicycle_t::input_t& VirtualBicycle::u() const { return m_u; } const VirtualBicycle::bicycle_t::output_t& VirtualBicycle::z() const { return m_z; } const VirtualBicycle::bicycle_t::auxiliary_state_t& VirtualBicycle::x_aux() const { return m_x_aux; } const BicyclePoseMessage& VirtualBicycle::pose() const { return m_pose; } const VirtualBicycle::bicycle_t& VirtualBicycle::model() const { return m_bicycle; } const VirtualBicycle::kalman_t& VirtualBicycle::kalman() const { return m_kalman; } const uint8_t* VirtualBicycle::pose_buffer() const { return frame_buffer.data(); } uint8_t VirtualBicycle::pose_buffer_size() const { return m_pose_size; } <commit_msg>Fix clustril project build<commit_after>#include "virtualbicycle.h" #include "angle.h" #include "packet/serialize.h" #include "packet/frame.h" #include "parameters.h" #include <array> namespace { std::array<uint8_t, BicyclePoseMessage_size> serialize_buffer; std::array<uint8_t, BicyclePoseMessage_size + packet::frame::PACKET_OVERHEAD> frame_buffer; } // namespace VirtualBicycle::VirtualBicycle(float v, float dt, float sigma0, float sigma1) : m_bicycle(v , dt), m_kalman(m_bicycle, /* bicycle model used in Kalman filter */ bicycle_t::state_t::Zero(), /* initial state estimate */ parameters::defaultvalue::kalman::Q(dt), /* process noise cov */ (kalman_t::measurement_noise_covariance_t() << /* measurement noise cov */ sigma0, 0, 0, sigma1).finished(), std::pow(sigma0, 2)*bicycle_t::state_matrix_t::Identity()), /* error cov */ // FIXME m_pose_size(0) { m_u.setZero(); m_z.setZero(); m_x_aux.setZero(); /* use an initial guess of 30 degrees for pitch */ m_x_aux[2] = m_bicycle.solve_constraint_pitch(m_kalman.x(), 30 * constants::as_radians); m_pose = BicyclePoseMessage_init_zero; m_pose.pitch = m_x_aux[2]; } void VirtualBicycle::update(float roll_torque_input, float steer_torque_input, /* u[0], u[1] */ float yaw_angle_measurement, float steer_angle_measurement) { /* z[0], z[1] */ m_u << roll_torque_input, steer_torque_input; m_z << yaw_angle_measurement, steer_angle_measurement; m_kalman.time_update(m_u); m_kalman.measurement_update(m_z); m_x_aux = m_bicycle.update_auxiliary_state(m_kalman.x(), m_x_aux); m_pose.timestamp = 1; // FIXME when running at a different rate m_pose.x = m_x_aux[0]; m_pose.y = m_x_aux[1]; m_pose.pitch = m_x_aux[2]; m_pose.yaw = m_kalman.x()[0]; m_pose.roll = m_kalman.x()[1]; m_pose.steer = m_kalman.x()[2]; } /* WARNING: this member function is not thread safe with multiple VirtualBicycle objects */ uint8_t VirtualBicycle::encode_and_stuff_pose() { uint8_t bytes_written = packet::serialize::encode(m_pose, serialize_buffer.data(), serialize_buffer.size()); packet::frame::stuff(serialize_buffer.data(), frame_buffer.data(), bytes_written); m_pose_size = bytes_written + packet::frame::PACKET_OVERHEAD; return m_pose_size; } const VirtualBicycle::bicycle_t::state_t& VirtualBicycle::x() const { return m_kalman.x(); } const VirtualBicycle::bicycle_t::input_t& VirtualBicycle::u() const { return m_u; } const VirtualBicycle::bicycle_t::output_t& VirtualBicycle::z() const { return m_z; } const VirtualBicycle::bicycle_t::auxiliary_state_t& VirtualBicycle::x_aux() const { return m_x_aux; } const BicyclePoseMessage& VirtualBicycle::pose() const { return m_pose; } const VirtualBicycle::bicycle_t& VirtualBicycle::model() const { return m_bicycle; } const VirtualBicycle::kalman_t& VirtualBicycle::kalman() const { return m_kalman; } const uint8_t* VirtualBicycle::pose_buffer() const { return frame_buffer.data(); } uint8_t VirtualBicycle::pose_buffer_size() const { return m_pose_size; } <|endoftext|>
<commit_before>#include "mangaupdates_parser.hpp" #include "http_utility.hpp" #include <algorithm> #include <cstdint> #include <functional> #include <numeric> #include <utf8/utf8.h> namespace { static std::string const name_entry_search_str = "alt='Series Info'>"; static std::string const id_search_str = "<a href='http://www.mangaupdates.com/series.html?id="; static std::string const desc_search_str = "<div class=\"sCat\"><b>Description</b></div>"; static std::string const ass_names_search_str = "<div class=\"sCat\"><b>Associated Names</b></div>"; static std::string const genres_search_str = "act=genresearch&amp;genre="; static std::string const authors_search_str = "<div class=\"sCat\"><b>Author(s)</b></div>"; static std::string const artists_search_str = "<div class=\"sCat\"><b>Artist(s)</b></div>"; static std::string const year_search_str = "<div class=\"sCat\"><b>Year</b></div>"; static std::string const img_search_str = "<div class=\"sContent\" ><center><img"; static std::pair<std::string, std::string> const junk_table[] = { { "<i>", "</i>" }, // Name junk in search results { "&nbsp; [", "]" } // Artists and Authors junk }; enum junk_type { NAME_SEARCH = 0, ARTIST_AUTHOR, }; static std::string & find_remove_junk(std::string & str, junk_type type) { auto const & start_pattern = junk_table[type].first; auto const & end_pattern = junk_table[type].second; auto start_pos = str.find(start_pattern); if (start_pos != std::string::npos) { auto end_pos = str.find(end_pattern, start_pos + start_pattern.length()); if (end_pos != std::string::npos) { str.erase(start_pos, start_pattern.length()); str.erase(end_pos - start_pattern.length(), end_pattern.length()); } } return str; } //https://en.wikipedia.org/wiki/Levenshtein_distance static uint32_t levenshtein_distance(std::string const & s, std::string const & t) { if (s == t) return 0; if (s.length() == 0) return t.length(); if (t.length() == 0) return s.length(); std::vector<uint32_t> v0(t.length() + 1); std::vector<uint32_t> v1(t.length() + 1); auto n = 0; std::generate(v0.begin(), v0.end(), [&n]() { return n++; }); for (size_t i = 0; i < s.length(); i++) { v1[0] = i + 1; for (size_t j = 0; j < t.length(); j++) { auto cost = s[i] == t[j] ? 0 : 1; v1[j + 1] = std::min({ v1[j] + 1, v0[j + 1], v0[j] + cost }); } v0 = v1; } return v1[t.length()]; } } std::string const mangaupdates::get_id(std::string const & contents, std::string const & name) { using match_type = std::pair<float, std::string>; std::vector<match_type> matches; std::string id; // mangaupdates sends the names NCR encoded, so we must encode ours to NCR as well auto ncr_name = http_utility::encode_ncr(name); size_t id_start_pos = contents.find(id_search_str); // Iterate through every search result entry while (id_start_pos != std::string::npos) { id_start_pos += id_search_str.length(); size_t id_end_pos = contents.find("'", id_start_pos); if (id_end_pos == std::string::npos) break; id = contents.substr(id_start_pos, id_end_pos - id_start_pos); size_t name_start_pos = contents.find(name_entry_search_str, id_start_pos); if (name_start_pos != std::string::npos) { name_start_pos += name_entry_search_str.length(); size_t name_end_pos = contents.find("</a>", name_start_pos); if (name_end_pos == std::string::npos) break; // Get the string from positions and remove any junk auto potential_match = contents.substr(name_start_pos, name_end_pos - name_start_pos); potential_match = find_remove_junk(potential_match, NAME_SEARCH); // Do the names match? if (potential_match == ncr_name) return id; auto larger_length = std::max(potential_match.length(), name.length()); auto match_percentage = 1.0f - (static_cast<float>(levenshtein_distance(potential_match, name)) / larger_length); matches.emplace_back(match_percentage, id); } id_start_pos = contents.find(id_search_str, id_start_pos); } // Sort the potential matches based on their match percentage; the frontmost being the highest std::sort(matches.begin(), matches.end(), [](match_type const & left, match_type const & right) -> bool { return left.first > right.first; }); return matches.size() > 0 ? matches.front().second : ""; } std::string const mangaupdates::get_description(std::string const & contents) { std::string description; size_t start_pos = contents.find(desc_search_str); if (start_pos != std::string::npos) { start_pos += desc_search_str.length(); start_pos = contents.find(">", start_pos); if (start_pos != std::string::npos) { ++start_pos; size_t end_pos = contents.find("</div>", start_pos); if (end_pos != std::string::npos) description = contents.substr(start_pos, end_pos - start_pos); } } return description; } std::vector<std::string> const mangaupdates::get_associated_names(std::string const & contents) { std::vector<std::string> associated_names; size_t start_pos = contents.find(ass_names_search_str); if (start_pos != std::string::npos) { start_pos += ass_names_search_str.length(); size_t div_end_pos = contents.find("</div>", start_pos); if (div_end_pos != std::string::npos) { --div_end_pos; size_t end_pos = 0; start_pos = contents.find(">", start_pos); if (start_pos != std::string::npos) { ++start_pos; for (size_t i = 0; start_pos < div_end_pos; i++) { end_pos = contents.find("<br />", start_pos); if (end_pos == std::string::npos) break; associated_names.emplace_back(contents.substr(start_pos, end_pos - start_pos)); start_pos = end_pos + 6; } } } } return associated_names; } std::vector<std::string> const mangaupdates::get_genres(std::string const & contents) { std::vector<std::string> genres; size_t start_pos = contents.find(genres_search_str); if (start_pos != std::string::npos) { start_pos += genres_search_str.length(); size_t end_pos = 0; size_t div_end_pos = contents.find("</div>", start_pos); if (div_end_pos != std::string::npos) { --div_end_pos; for (size_t i = 0; start_pos < div_end_pos; i++) { start_pos = contents.find("<u>", start_pos); if (start_pos == std::string::npos) break; start_pos += 3; end_pos = contents.find("</u>", start_pos); if (end_pos == std::string::npos) break; genres.emplace_back(contents.substr(start_pos, end_pos - start_pos)); start_pos = end_pos + 4; } /* ******** IMPROVE THIS ****** */ // Remove the last two elements as they're rubbish we don't need genres.pop_back(); genres.pop_back(); /* ***************************** */ } } return genres; } std::vector<std::string> const mangaupdates::get_authors(std::string const & contents) { std::vector<std::string> authors; size_t start_pos = contents.find(authors_search_str); if (start_pos != std::string::npos) { start_pos += authors_search_str.length(); size_t end_pos = 0; size_t div_end_pos = contents.find("</div>", start_pos); if (div_end_pos != std::string::npos) { --div_end_pos; for (size_t i = 0; start_pos < div_end_pos; i++) { start_pos = contents.find("<u>", start_pos); if (start_pos == std::string::npos) break; start_pos += 3; end_pos = contents.find("</u></a><BR>", start_pos); if (end_pos == std::string::npos) break; authors.emplace_back(contents.substr(start_pos, end_pos - start_pos)); start_pos = end_pos + 12; } } } return authors; } std::vector<std::string> const mangaupdates::get_artists(std::string const & contents) { std::vector<std::string> artists; size_t start_pos = contents.find(artists_search_str); if (start_pos != std::string::npos) { start_pos += artists_search_str.length(); size_t end_pos = 0; size_t div_end_pos = contents.find("</div>", start_pos); if (div_end_pos != std::string::npos) { --div_end_pos; for (size_t i = 0; start_pos < div_end_pos; i++) { start_pos = contents.find("<u>", start_pos); if (start_pos == std::string::npos) break; start_pos += 3; end_pos = contents.find("</u></a><BR>", start_pos); if (end_pos == std::string::npos) break; artists.emplace_back(contents.substr(start_pos, end_pos - start_pos)); start_pos = end_pos + 12; } } } return artists; } std::string const mangaupdates::get_year(std::string const & contents) { std::string year; size_t start_pos = contents.find(year_search_str); if (start_pos != std::string::npos) { start_pos += year_search_str.length(); start_pos = contents.find(">", start_pos); if (start_pos != std::string::npos) { ++start_pos; size_t end_pos = contents.find("</div>", start_pos); if (end_pos != std::string::npos) { --end_pos; // new line character year = contents.substr(start_pos, end_pos - start_pos); } } } return year; } std::string const mangaupdates::get_img_url(std::string const & contents) { std::string img_url; size_t start_pos = contents.find(img_search_str); if (start_pos != std::string::npos) { start_pos += img_search_str.length(); start_pos = contents.find("src='", start_pos); if (start_pos != std::string::npos) { start_pos += 5; size_t end_pos = contents.find('\'', start_pos); if (end_pos != std::string::npos) { img_url = contents.substr(start_pos, end_pos - start_pos); } } } return img_url; }<commit_msg>Modify search string for MU id Would result in failure with HTTPS<commit_after>#include "mangaupdates_parser.hpp" #include "http_utility.hpp" #include <algorithm> #include <cstdint> #include <functional> #include <numeric> #include <utf8/utf8.h> namespace { static std::string const name_entry_search_str = "alt='Series Info'>"; static std::string const id_search_str = "www.mangaupdates.com/series.html?id="; static std::string const desc_search_str = "<div class=\"sCat\"><b>Description</b></div>"; static std::string const ass_names_search_str = "<div class=\"sCat\"><b>Associated Names</b></div>"; static std::string const genres_search_str = "act=genresearch&amp;genre="; static std::string const authors_search_str = "<div class=\"sCat\"><b>Author(s)</b></div>"; static std::string const artists_search_str = "<div class=\"sCat\"><b>Artist(s)</b></div>"; static std::string const year_search_str = "<div class=\"sCat\"><b>Year</b></div>"; static std::string const img_search_str = "<div class=\"sContent\" ><center><img"; static std::pair<std::string, std::string> const junk_table[] = { { "<i>", "</i>" }, // Name junk in search results { "&nbsp; [", "]" } // Artists and Authors junk }; enum junk_type { NAME_SEARCH = 0, ARTIST_AUTHOR, }; static std::string & find_remove_junk(std::string & str, junk_type type) { auto const & start_pattern = junk_table[type].first; auto const & end_pattern = junk_table[type].second; auto start_pos = str.find(start_pattern); if (start_pos != std::string::npos) { auto end_pos = str.find(end_pattern, start_pos + start_pattern.length()); if (end_pos != std::string::npos) { str.erase(start_pos, start_pattern.length()); str.erase(end_pos - start_pattern.length(), end_pattern.length()); } } return str; } //https://en.wikipedia.org/wiki/Levenshtein_distance static uint32_t levenshtein_distance(std::string const & s, std::string const & t) { if (s == t) return 0; if (s.length() == 0) return t.length(); if (t.length() == 0) return s.length(); std::vector<uint32_t> v0(t.length() + 1); std::vector<uint32_t> v1(t.length() + 1); auto n = 0; std::generate(v0.begin(), v0.end(), [&n]() { return n++; }); for (size_t i = 0; i < s.length(); i++) { v1[0] = i + 1; for (size_t j = 0; j < t.length(); j++) { auto cost = s[i] == t[j] ? 0 : 1; v1[j + 1] = std::min({ v1[j] + 1, v0[j + 1], v0[j] + cost }); } v0 = v1; } return v1[t.length()]; } } std::string const mangaupdates::get_id(std::string const & contents, std::string const & name) { using match_type = std::pair<float, std::string>; std::vector<match_type> matches; std::string id; // mangaupdates sends the names NCR encoded, so we must encode ours to NCR as well auto ncr_name = http_utility::encode_ncr(name); size_t id_start_pos = contents.find(id_search_str); // Iterate through every search result entry while (id_start_pos != std::string::npos) { id_start_pos += id_search_str.length(); size_t id_end_pos = contents.find("'", id_start_pos); if (id_end_pos == std::string::npos) break; id = contents.substr(id_start_pos, id_end_pos - id_start_pos); size_t name_start_pos = contents.find(name_entry_search_str, id_start_pos); if (name_start_pos != std::string::npos) { name_start_pos += name_entry_search_str.length(); size_t name_end_pos = contents.find("</a>", name_start_pos); if (name_end_pos == std::string::npos) break; // Get the string from positions and remove any junk auto potential_match = contents.substr(name_start_pos, name_end_pos - name_start_pos); potential_match = find_remove_junk(potential_match, NAME_SEARCH); // Do the names match? if (potential_match == ncr_name) return id; auto larger_length = std::max(potential_match.length(), name.length()); auto match_percentage = 1.0f - (static_cast<float>(levenshtein_distance(potential_match, name)) / larger_length); matches.emplace_back(match_percentage, id); } id_start_pos = contents.find(id_search_str, id_start_pos); } // Sort the potential matches based on their match percentage; the frontmost being the highest std::sort(matches.begin(), matches.end(), [](match_type const & left, match_type const & right) -> bool { return left.first > right.first; }); return matches.size() > 0 ? matches.front().second : ""; } std::string const mangaupdates::get_description(std::string const & contents) { std::string description; size_t start_pos = contents.find(desc_search_str); if (start_pos != std::string::npos) { start_pos += desc_search_str.length(); start_pos = contents.find(">", start_pos); if (start_pos != std::string::npos) { ++start_pos; size_t end_pos = contents.find("</div>", start_pos); if (end_pos != std::string::npos) description = contents.substr(start_pos, end_pos - start_pos); } } return description; } std::vector<std::string> const mangaupdates::get_associated_names(std::string const & contents) { std::vector<std::string> associated_names; size_t start_pos = contents.find(ass_names_search_str); if (start_pos != std::string::npos) { start_pos += ass_names_search_str.length(); size_t div_end_pos = contents.find("</div>", start_pos); if (div_end_pos != std::string::npos) { --div_end_pos; size_t end_pos = 0; start_pos = contents.find(">", start_pos); if (start_pos != std::string::npos) { ++start_pos; for (size_t i = 0; start_pos < div_end_pos; i++) { end_pos = contents.find("<br />", start_pos); if (end_pos == std::string::npos) break; associated_names.emplace_back(contents.substr(start_pos, end_pos - start_pos)); start_pos = end_pos + 6; } } } } return associated_names; } std::vector<std::string> const mangaupdates::get_genres(std::string const & contents) { std::vector<std::string> genres; size_t start_pos = contents.find(genres_search_str); if (start_pos != std::string::npos) { start_pos += genres_search_str.length(); size_t end_pos = 0; size_t div_end_pos = contents.find("</div>", start_pos); if (div_end_pos != std::string::npos) { --div_end_pos; for (size_t i = 0; start_pos < div_end_pos; i++) { start_pos = contents.find("<u>", start_pos); if (start_pos == std::string::npos) break; start_pos += 3; end_pos = contents.find("</u>", start_pos); if (end_pos == std::string::npos) break; genres.emplace_back(contents.substr(start_pos, end_pos - start_pos)); start_pos = end_pos + 4; } /* ******** IMPROVE THIS ****** */ // Remove the last two elements as they're rubbish we don't need genres.pop_back(); genres.pop_back(); /* ***************************** */ } } return genres; } std::vector<std::string> const mangaupdates::get_authors(std::string const & contents) { std::vector<std::string> authors; size_t start_pos = contents.find(authors_search_str); if (start_pos != std::string::npos) { start_pos += authors_search_str.length(); size_t end_pos = 0; size_t div_end_pos = contents.find("</div>", start_pos); if (div_end_pos != std::string::npos) { --div_end_pos; for (size_t i = 0; start_pos < div_end_pos; i++) { start_pos = contents.find("<u>", start_pos); if (start_pos == std::string::npos) break; start_pos += 3; end_pos = contents.find("</u></a><BR>", start_pos); if (end_pos == std::string::npos) break; authors.emplace_back(contents.substr(start_pos, end_pos - start_pos)); start_pos = end_pos + 12; } } } return authors; } std::vector<std::string> const mangaupdates::get_artists(std::string const & contents) { std::vector<std::string> artists; size_t start_pos = contents.find(artists_search_str); if (start_pos != std::string::npos) { start_pos += artists_search_str.length(); size_t end_pos = 0; size_t div_end_pos = contents.find("</div>", start_pos); if (div_end_pos != std::string::npos) { --div_end_pos; for (size_t i = 0; start_pos < div_end_pos; i++) { start_pos = contents.find("<u>", start_pos); if (start_pos == std::string::npos) break; start_pos += 3; end_pos = contents.find("</u></a><BR>", start_pos); if (end_pos == std::string::npos) break; artists.emplace_back(contents.substr(start_pos, end_pos - start_pos)); start_pos = end_pos + 12; } } } return artists; } std::string const mangaupdates::get_year(std::string const & contents) { std::string year; size_t start_pos = contents.find(year_search_str); if (start_pos != std::string::npos) { start_pos += year_search_str.length(); start_pos = contents.find(">", start_pos); if (start_pos != std::string::npos) { ++start_pos; size_t end_pos = contents.find("</div>", start_pos); if (end_pos != std::string::npos) { --end_pos; // new line character year = contents.substr(start_pos, end_pos - start_pos); } } } return year; } std::string const mangaupdates::get_img_url(std::string const & contents) { std::string img_url; size_t start_pos = contents.find(img_search_str); if (start_pos != std::string::npos) { start_pos += img_search_str.length(); start_pos = contents.find("src='", start_pos); if (start_pos != std::string::npos) { start_pos += 5; size_t end_pos = contents.find('\'', start_pos); if (end_pos != std::string::npos) { img_url = contents.substr(start_pos, end_pos - start_pos); } } } return img_url; }<|endoftext|>
<commit_before>void emcal_digits() { AliRunLoader* rl = Alieve::Event::AssertRunLoader(); rl->LoadgAlice(); AliEMCAL * emcal = (AliEMCAL*) rl->GetAliRun()->GetDetector("EMCAL"); AliEMCALGeometry * geom = emcal->GetGeometry(); rl->LoadDigits("EMCAL"); TTree* dt = rl->GetTreeD("EMCAL", kFALSE); gGeoManager = gReve->GetGeometry("$REVESYS/alice-data/alice_fullgeo.root"); TGeoNode* node = gGeoManager->GetTopVolume()->FindNode("XEN1_1"); TGeoBBox* bbbox = (TGeoBBox*) node->GetDaughter(0) ->GetVolume()->GetShape(); bbbox->Dump(); TGeoBBox* sbbox = (TGeoBBox*) node->GetDaughter(10)->GetVolume()->GetShape(); sbbox->Dump(); Reve::RenderElementList* l = new Reve::RenderElementList("EMCAL"); l->SetTitle("Tooltip"); gReve->AddRenderElement(l); Reve::FrameBox* frame_big = new Reve::FrameBox(); frame_big->SetAABoxCenterHalfSize(0, 0, 0, bbbox->GetDX(), bbbox->GetDY(), bbbox->GetDZ()); Reve::FrameBox* frame_sml = new Reve::FrameBox(); frame_sml->SetAABoxCenterHalfSize(0, 0, 0, sbbox->GetDX(), sbbox->GetDY(), sbbox->GetDZ()); Reve::QuadSet* smodules[12]; for (Int_t sm=0; sm<12; ++sm) { Reve::QuadSet* q = new Reve::QuadSet(Form("SM %d", sm+1)); q->SetOwnIds(kTRUE); q->Reset(Reve::QuadSet::QT_RectangleXYFixedDimZ, kFALSE, 32); q->SetDefWidth (geom->GetPhiTileSize()); q->SetDefHeight(geom->GetEtaTileSize()); // node->GetDaughter(sm)->GetMatrix()->Print(); q->RefHMTrans().SetFrom(*node->GetDaughter(sm)->GetMatrix()); q->RefHMTrans().TransposeRotationPart(); // Spook? q->SetFrame(sm < 10 ? frame_big : frame_sml); gReve->AddRenderElement(l, q); smodules[sm] = q; } TClonesArray *digits = 0; dt->SetBranchAddress("EMCAL", &digits); dt->GetEntry(0); Int_t nEnt = digits->GetEntriesFast(); AliEMCALDigit * dig; Int_t iEvent = -1 ; Float_t amp = -1 ; Float_t time = -1 ; Int_t id = -1 ; Int_t iSupMod = 0 ; Int_t iTower = 0 ; Int_t iIphi = 0 ; Int_t iIeta = 0 ; Int_t iphi = 0 ; Int_t ieta = 0 ; Double_t x, y, z; for(Int_t idig = 0; idig<nEnt; idig++) { dig = static_cast<AliEMCALDigit *>(digits->At(idig)); if(dig != 0) { id = dig->GetId() ; //cell (digit) label amp = dig->GetAmp(); //amplitude in cell (digit) time = dig->GetTime();//time of creation of digit after collision cout<<"Cell ID "<<id<<" Amp "<<amp<<endl;//" time "<<time<<endl; //Geometry methods geom->GetCellIndex(id,iSupMod,iTower,iIphi,iIeta); //Gives SuperModule and Tower numbers geom->GetCellPhiEtaIndexInSModule(iSupMod,iTower, iIphi, iIeta,iphi,ieta); //Gives label of cell in eta-phi position per each supermodule cout<< "SModule "<<iSupMod<<"; Tower "<<iTower <<"; Eta "<<iIeta<<"; Phi "<<iIphi <<"; Cell Eta "<<ieta<<"; Cell Phi "<<iphi<<endl; geom->RelPosCellInSModule(id, x, y, z); cout << x <<" "<< y <<" "<< z <<endl; Reve::QuadSet* q = smodules[iSupMod]; q->AddQuad(y, z); q->QuadValue(amp); q->QuadId(dig); } else { cout<<"Digit pointer 0x0"<<endl; } } gReve->Redraw3D(); } <commit_msg>Use the y-z mode of QuadSet to represent calo-cells.<commit_after>void emcal_digits() { AliRunLoader* rl = Alieve::Event::AssertRunLoader(); rl->LoadgAlice(); AliEMCAL * emcal = (AliEMCAL*) rl->GetAliRun()->GetDetector("EMCAL"); AliEMCALGeometry * geom = emcal->GetGeometry(); rl->LoadDigits("EMCAL"); TTree* dt = rl->GetTreeD("EMCAL", kFALSE); gGeoManager = gReve->GetGeometry("$REVESYS/alice-data/alice_fullgeo.root"); TGeoNode* node = gGeoManager->GetTopVolume()->FindNode("XEN1_1"); TGeoBBox* bbbox = (TGeoBBox*) node->GetDaughter(0) ->GetVolume()->GetShape(); bbbox->Dump(); TGeoBBox* sbbox = (TGeoBBox*) node->GetDaughter(10)->GetVolume()->GetShape(); sbbox->Dump(); Reve::RenderElementList* l = new Reve::RenderElementList("EMCAL"); l->SetTitle("Tooltip"); gReve->AddRenderElement(l); Reve::FrameBox* frame_big = new Reve::FrameBox(); frame_big->SetAABoxCenterHalfSize(0, 0, 0, bbbox->GetDX(), bbbox->GetDY(), bbbox->GetDZ()); Reve::FrameBox* frame_sml = new Reve::FrameBox(); frame_sml->SetAABoxCenterHalfSize(0, 0, 0, sbbox->GetDX(), sbbox->GetDY(), sbbox->GetDZ()); gStyle->SetPalette(1, 0); Reve::RGBAPalette* pal = new Reve::RGBAPalette(0, 512); pal->SetLimits(0, 1024); Reve::QuadSet* smodules[12]; for (Int_t sm=0; sm<12; ++sm) { Reve::QuadSet* q = new Reve::QuadSet(Form("SM %d", sm+1)); q->SetOwnIds(kTRUE); q->Reset(Reve::QuadSet::QT_RectangleYZFixedDimX, kFALSE, 32); q->SetDefWidth (geom->GetPhiTileSize()); q->SetDefHeight(geom->GetEtaTileSize()); // node->GetDaughter(sm)->GetMatrix()->Print(); q->RefHMTrans().SetFrom(*node->GetDaughter(sm)->GetMatrix()); q->RefHMTrans().TransposeRotationPart(); // Spook? q->SetFrame(sm < 10 ? frame_big : frame_sml); q->SetPalette(pal); gReve->AddRenderElement(l, q); smodules[sm] = q; } TClonesArray *digits = 0; dt->SetBranchAddress("EMCAL", &digits); dt->GetEntry(0); Int_t nEnt = digits->GetEntriesFast(); AliEMCALDigit * dig; Int_t iEvent = -1 ; Float_t amp = -1 ; Float_t time = -1 ; Int_t id = -1 ; Int_t iSupMod = 0 ; Int_t iTower = 0 ; Int_t iIphi = 0 ; Int_t iIeta = 0 ; Int_t iphi = 0 ; Int_t ieta = 0 ; Double_t x, y, z; for(Int_t idig = 0; idig<nEnt; idig++) { dig = static_cast<AliEMCALDigit *>(digits->At(idig)); if(dig != 0) { id = dig->GetId() ; //cell (digit) label amp = dig->GetAmp(); //amplitude in cell (digit) time = dig->GetTime();//time of creation of digit after collision cout<<"Cell ID "<<id<<" Amp "<<amp<<endl;//" time "<<time<<endl; //Geometry methods geom->GetCellIndex(id,iSupMod,iTower,iIphi,iIeta); //Gives SuperModule and Tower numbers geom->GetCellPhiEtaIndexInSModule(iSupMod,iTower, iIphi, iIeta,iphi,ieta); //Gives label of cell in eta-phi position per each supermodule cout<< "SModule "<<iSupMod<<"; Tower "<<iTower <<"; Eta "<<iIeta<<"; Phi "<<iIphi <<"; Cell Eta "<<ieta<<"; Cell Phi "<<iphi<<endl; geom->RelPosCellInSModule(id, x, y, z); cout << x <<" "<< y <<" "<< z <<endl; Reve::QuadSet* q = smodules[iSupMod]; q->AddQuad(y, z); q->QuadValue(amp); q->QuadId(dig); } else { cout<<"Digit pointer 0x0"<<endl; } } for (Int_t sm=0; sm<12; ++sm) { smodules[iSupMod]->RefitPlex(); } gReve->Redraw3D(); } <|endoftext|>
<commit_before>/* Copyright(c) 2016-2017 Panos Karabelas 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. */ //= INCLUDES ==================== #include "Hierarchy.h" #include "../imgui/imgui.h" #include "Scene/Scene.h" #include "Scene/GameObject.h" #include "Components/Transform.h" #include "Core/Engine.h" //=============================== //= NAMESPACES ========== using namespace std; using namespace Directus; //======================= weak_ptr<GameObject> Hierarchy::m_gameObjectSelected; weak_ptr<GameObject> g_gameObjectEmpty; static Engine* g_engine = nullptr; static Scene* g_scene = nullptr; static bool g_wasItemHovered = false; Hierarchy::Hierarchy() { m_title = "Hierarchy"; m_context = nullptr; g_scene = nullptr; } void Hierarchy::Initialize(Context* context) { Widget::Initialize(context); g_engine = m_context->GetSubsystem<Engine>(); g_scene = m_context->GetSubsystem<Scene>(); } void Hierarchy::Update() { g_wasItemHovered = false; // If the engine is not updating, don't populate the hierarchy yet if (!g_engine->IsUpdating()) return; if (ImGui::TreeNodeEx("Scene", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize() * 3); // Increase spacing to differentiate leaves from expanded contents. Tree_Populate(); ImGui::PopStyleVar(); ImGui::TreePop(); } } void Hierarchy::Tree_Populate() { auto rootGameObjects = g_scene->GetRootGameObjects(); for (const auto& gameObject : rootGameObjects) { Tree_AddGameObject(gameObject); } } void Hierarchy::Tree_AddGameObject(const weak_ptr<GameObject>& currentGameObject) { GameObject* gameObjPtr = currentGameObject.lock().get(); // Node children visibility bool hasVisibleChildren = false; auto children = gameObjPtr->GetTransform()->GetChildren(); for (const auto& child : children) { if (child->GetGameObject()->IsVisibleInHierarchy()) { hasVisibleChildren = true; break; } } // Node flags -> Default ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnDoubleClick; // Node flags -> Expandable? node_flags |= hasVisibleChildren ? ImGuiTreeNodeFlags_OpenOnArrow : ImGuiTreeNodeFlags_Leaf; // Node flags -> Selected? if (!m_gameObjectSelected.expired()) { node_flags |= (m_gameObjectSelected.lock()->GetID() == gameObjPtr->GetID()) ? ImGuiTreeNodeFlags_Selected : 0; } // Node bool isNodeOpen = ImGui::TreeNodeEx((void*)(intptr_t)gameObjPtr->GetID(), node_flags, gameObjPtr->GetName().c_str()); // Handle clicking if (ImGui::IsMouseHoveringWindow()) { // Left click if (ImGui::IsMouseClicked(0) && ImGui::IsItemHovered(ImGuiHoveredFlags_Default)) { m_gameObjectSelected = currentGameObject; g_wasItemHovered = true; } // Right click if (ImGui::IsMouseClicked(1)) { if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) { m_gameObjectSelected = currentGameObject; } else { ImGui::OpenPopup("##HierarchyContextMenu"); } g_wasItemHovered = true; } // Clicking inside the window (but not on an item) if ((ImGui::IsMouseClicked(0) || ImGui::IsMouseClicked(1)) && !g_wasItemHovered) { m_gameObjectSelected = g_gameObjectEmpty; } } // Context menu if (ImGui::BeginPopup("##HierarchyContextMenu")) { if (!m_gameObjectSelected.expired()) { ImGui::MenuItem("Rename"); if (ImGui::MenuItem("Delete")) { GameObject_Delete(m_gameObjectSelected); } ImGui::Separator(); } if (ImGui::MenuItem("Creaty Empty")) { GameObject_CreateEmpty(); } ImGui::EndPopup(); } // Child nodes if (isNodeOpen) { if (hasVisibleChildren) { for (const auto& child : children) { if (!child->GetGameObject()->IsVisibleInHierarchy()) continue; Tree_AddGameObject(child->GetGameObjectRef()); } } ImGui::TreePop(); } } void Hierarchy::GameObject_Delete(weak_ptr<GameObject> gameObject) { g_scene->RemoveGameObject(gameObject); } void Hierarchy::GameObject_CreateEmpty() { g_scene->CreateGameObject(); } <commit_msg>Creating an empty GameObject will another GameObject is selected, will cause it to become a child.<commit_after>/* Copyright(c) 2016-2017 Panos Karabelas 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. */ //= INCLUDES ==================== #include "Hierarchy.h" #include "../imgui/imgui.h" #include "Scene/Scene.h" #include "Scene/GameObject.h" #include "Components/Transform.h" #include "Core/Engine.h" //=============================== //= NAMESPACES ========== using namespace std; using namespace Directus; //======================= weak_ptr<GameObject> Hierarchy::m_gameObjectSelected; weak_ptr<GameObject> g_gameObjectEmpty; static Engine* g_engine = nullptr; static Scene* g_scene = nullptr; static bool g_wasItemHovered = false; Hierarchy::Hierarchy() { m_title = "Hierarchy"; m_context = nullptr; g_scene = nullptr; } void Hierarchy::Initialize(Context* context) { Widget::Initialize(context); g_engine = m_context->GetSubsystem<Engine>(); g_scene = m_context->GetSubsystem<Scene>(); } void Hierarchy::Update() { g_wasItemHovered = false; // If the engine is not updating, don't populate the hierarchy yet if (!g_engine->IsUpdating()) return; if (ImGui::TreeNodeEx("Scene", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize() * 3); // Increase spacing to differentiate leaves from expanded contents. Tree_Populate(); ImGui::PopStyleVar(); ImGui::TreePop(); } } void Hierarchy::Tree_Populate() { auto rootGameObjects = g_scene->GetRootGameObjects(); for (const auto& gameObject : rootGameObjects) { Tree_AddGameObject(gameObject); } } void Hierarchy::Tree_AddGameObject(const weak_ptr<GameObject>& currentGameObject) { GameObject* gameObjPtr = currentGameObject.lock().get(); // Node children visibility bool hasVisibleChildren = false; auto children = gameObjPtr->GetTransform()->GetChildren(); for (const auto& child : children) { if (child->GetGameObject()->IsVisibleInHierarchy()) { hasVisibleChildren = true; break; } } // Node flags -> Default ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnDoubleClick; // Node flags -> Expandable? node_flags |= hasVisibleChildren ? ImGuiTreeNodeFlags_OpenOnArrow : ImGuiTreeNodeFlags_Leaf; // Node flags -> Selected? if (!m_gameObjectSelected.expired()) { node_flags |= (m_gameObjectSelected.lock()->GetID() == gameObjPtr->GetID()) ? ImGuiTreeNodeFlags_Selected : 0; } // Node bool isNodeOpen = ImGui::TreeNodeEx((void*)(intptr_t)gameObjPtr->GetID(), node_flags, gameObjPtr->GetName().c_str()); // Handle clicking if (ImGui::IsMouseHoveringWindow()) { // Left click if (ImGui::IsMouseClicked(0) && ImGui::IsItemHovered(ImGuiHoveredFlags_Default)) { m_gameObjectSelected = currentGameObject; g_wasItemHovered = true; } // Right click if (ImGui::IsMouseClicked(1)) { if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) { m_gameObjectSelected = currentGameObject; } else { ImGui::OpenPopup("##HierarchyContextMenu"); } g_wasItemHovered = true; } // Clicking inside the window (but not on an item) if ((ImGui::IsMouseClicked(0) || ImGui::IsMouseClicked(1)) && !g_wasItemHovered) { m_gameObjectSelected = g_gameObjectEmpty; } } // Context menu if (ImGui::BeginPopup("##HierarchyContextMenu")) { if (!m_gameObjectSelected.expired()) { ImGui::MenuItem("Rename"); if (ImGui::MenuItem("Delete")) { GameObject_Delete(m_gameObjectSelected); } ImGui::Separator(); } if (ImGui::MenuItem("Creaty Empty")) { GameObject_CreateEmpty(); } ImGui::EndPopup(); } // Child nodes if (isNodeOpen) { if (hasVisibleChildren) { for (const auto& child : children) { if (!child->GetGameObject()->IsVisibleInHierarchy()) continue; Tree_AddGameObject(child->GetGameObjectRef()); } } ImGui::TreePop(); } } void Hierarchy::GameObject_Delete(weak_ptr<GameObject> gameObject) { g_scene->RemoveGameObject(gameObject); } void Hierarchy::GameObject_CreateEmpty() { auto gameObject = g_scene->CreateGameObject(); if (auto selected = m_gameObjectSelected.lock()) { gameObject.lock()->GetTransform()->SetParent(selected->GetTransform()); } } <|endoftext|>
<commit_before>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_UTILS_CXX_ATTRIBUTES_HPP #define IOX_UTILS_CXX_ATTRIBUTES_HPP namespace iox { namespace cxx { /// @brief if a function has a return value which you do not want to use then you can wrap the function with that macro. /// Purpose is to suppress the unused compiler warning by adding an attribute to the return value /// @param[in] expr name of the function where the return value is not used. /// @code /// uint32_t foo(); /// IOX_DISCARD_RESULT(foo()); // suppress compiler warning for unused return value /// @endcode #define IOX_DISCARD_RESULT(expr) static_cast<void>(expr) // NOLINT /// @brief IOX_NO_DISCARD adds the [[nodiscard]] keyword if it is available for the current compiler. /// If additionally the keyword [[gnu::warn_unused]] is present it will be added as well. /// @note // [[nodiscard]], [[gnu::warn_unused]] supported since gcc 4.8 (https://gcc.gnu.org/projects/cxx-status.html) /// [[nodiscard]], [[gnu::warn_unused]] supported since clang 3.9 (https://clang.llvm.org/cxx_status.html) /// activate keywords for gcc>=5 or clang>=4 #if defined(_WIN32) // On WIN32 we are using C++17 which makes the keyword [[nodiscard]] available #define IOX_NO_DISCARD [[nodiscard]] // NOLINT #elif defined(__APPLE__) && defined(__clang__) // On APPLE we are using C++17 which makes the keyword [[nodiscard]] available #define IOX_NO_DISCARD [[nodiscard, gnu::warn_unused]] // NOLINT #elif (defined(__clang__) && __clang_major__ >= 4) #define IOX_NO_DISCARD [[gnu::warn_unused]] // NOLINT #elif (defined(__GNUC__) && __GNUC__ >= 5) #define IOX_NO_DISCARD [[nodiscard, gnu::warn_unused]] // NOLINT #else // on an unknown platform we use for now nothing since we do not know what is supported there #define IOX_NO_DISCARD #endif #endif /// @brief IOX_FALLTHROUGH adds the [[fallthrough]] keyword when it is available for the current compiler. /// @note // [[fallthrough]] supported since gcc 7 (https://gcc.gnu.org/projects/cxx-status.html) /// [[fallthrough]] supported since clang 3.9 (https://clang.llvm.org/cxx_status.html) /// activate keywords for gcc>=7 or clang>=4 #if (defined(__GNUC__) && __GNUC__ >= 7) || (defined(__clang__) && __clang_major__ >= 4) #define IOX_FALLTHROUGH [[fallthrough]] // NOLINT #else // On WIN32 we are using C++17 which makes the keyword [[fallthrough]] available #if defined(_WIN32) #define IOX_FALLTHROUGH [[fallthrough]] // NOLINT // on an unknown platform we use for now nothing since we do not know what is supported there #else #define IOX_FALLTHROUGH #endif #endif /// @brief IOX_MAYBE_UNUSED adds the [[gnu::unused]] or [[maybe_unused]] attribute when it is available for the current /// compiler. /// @note /// activate attribute for gcc or clang #if defined(__GNUC__) || defined(__clang__) #define IOX_MAYBE_UNUSED [[gnu::unused]] // NOLINT #else // On WIN32 we are using C++17 which makes the attribute [[maybe_unused]] available #if defined(_WIN32) #define IOX_MAYBE_UNUSED [[maybe_unused]] // NOLINT // on an unknown platform we use for now nothing since we do not know what is supported there #else #define IOX_MAYBE_UNUSED #endif #endif } // namespace cxx } // namespace iox #endif <commit_msg>iox-#743 adjusted endif and using elif instead of else and another if in attribute macros<commit_after>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_UTILS_CXX_ATTRIBUTES_HPP #define IOX_UTILS_CXX_ATTRIBUTES_HPP namespace iox { namespace cxx { /// @brief if a function has a return value which you do not want to use then you can wrap the function with that macro. /// Purpose is to suppress the unused compiler warning by adding an attribute to the return value /// @param[in] expr name of the function where the return value is not used. /// @code /// uint32_t foo(); /// IOX_DISCARD_RESULT(foo()); // suppress compiler warning for unused return value /// @endcode #define IOX_DISCARD_RESULT(expr) static_cast<void>(expr) // NOLINT /// @brief IOX_NO_DISCARD adds the [[nodiscard]] keyword if it is available for the current compiler. /// If additionally the keyword [[gnu::warn_unused]] is present it will be added as well. /// @note // [[nodiscard]], [[gnu::warn_unused]] supported since gcc 4.8 (https://gcc.gnu.org/projects/cxx-status.html) /// [[nodiscard]], [[gnu::warn_unused]] supported since clang 3.9 (https://clang.llvm.org/cxx_status.html) /// activate keywords for gcc>=5 or clang>=4 #if defined(_WIN32) // On WIN32 we are using C++17 which makes the keyword [[nodiscard]] available #define IOX_NO_DISCARD [[nodiscard]] // NOLINT #elif defined(__APPLE__) && defined(__clang__) // On APPLE we are using C++17 which makes the keyword [[nodiscard]] available #define IOX_NO_DISCARD [[nodiscard, gnu::warn_unused]] // NOLINT #elif (defined(__clang__) && __clang_major__ >= 4) #define IOX_NO_DISCARD [[gnu::warn_unused]] // NOLINT #elif (defined(__GNUC__) && __GNUC__ >= 5) #define IOX_NO_DISCARD [[nodiscard, gnu::warn_unused]] // NOLINT #else // on an unknown platform we use for now nothing since we do not know what is supported there #define IOX_NO_DISCARD #endif /// @brief IOX_FALLTHROUGH adds the [[fallthrough]] keyword when it is available for the current compiler. /// @note // [[fallthrough]] supported since gcc 7 (https://gcc.gnu.org/projects/cxx-status.html) /// [[fallthrough]] supported since clang 3.9 (https://clang.llvm.org/cxx_status.html) /// activate keywords for gcc>=7 or clang>=4 #if (defined(__GNUC__) && __GNUC__ >= 7) || (defined(__clang__) && __clang_major__ >= 4) #define IOX_FALLTHROUGH [[fallthrough]] // NOLINT #elif defined(_WIN32) // On WIN32 we are using C++17 which makes the keyword [[fallthrough]] available #define IOX_FALLTHROUGH [[fallthrough]] // NOLINT // on an unknown platform we use for now nothing since we do not know what is supported there #else #define IOX_FALLTHROUGH #endif /// @brief IOX_MAYBE_UNUSED adds the [[gnu::unused]] or [[maybe_unused]] attribute when it is available for the current /// compiler. /// @note /// activate attribute for gcc or clang #if defined(__GNUC__) || defined(__clang__) #define IOX_MAYBE_UNUSED [[gnu::unused]] // NOLINT #elif defined(_WIN32) // On WIN32 we are using C++17 which makes the attribute [[maybe_unused]] available #define IOX_MAYBE_UNUSED [[maybe_unused]] // NOLINT // on an unknown platform we use for now nothing since we do not know what is supported there #else #define IOX_MAYBE_UNUSED #endif } // namespace cxx } // namespace iox #endif <|endoftext|>
<commit_before>#pragma once #include <vector> #include <tudocomp/compressors/lz78/LZ78Trie.hpp> #include <tudocomp/Algorithm.hpp> namespace tdc { namespace lz78 { class BinarySortedTrie : public Algorithm, public LZ78Trie<factorid_t> { /* * The trie is not stored in standard form. Each node stores the pointer to its first child and a pointer to its next sibling (first as first come first served) */ std::vector<factorid_t> m_first_child; std::vector<factorid_t> m_next_sibling; std::vector<literal_t> m_literal; IF_STATS( size_t m_resizes = 0; size_t m_specialresizes = 0; ) public: inline static Meta meta() { Meta m("lz78trie", "binarysorted", "Lempel-Ziv 78 Sorted Binary Trie"); return m; } inline BinarySortedTrie(Env&& env, size_t n, const size_t& remaining_characters, factorid_t reserve = 0) : Algorithm(std::move(env)) , LZ78Trie(n,remaining_characters) { if(reserve > 0) { m_first_child.reserve(reserve); m_next_sibling.reserve(reserve); m_literal.reserve(reserve); } } node_t add_rootnode(uliteral_t c) override { m_first_child.push_back(undef_id); m_next_sibling.push_back(undef_id); m_literal.push_back(c); return size() - 1; } node_t get_rootnode(uliteral_t c) override { return c; } void clear() override { m_first_child.clear(); m_next_sibling.clear(); m_literal.clear(); } inline factorid_t new_node(uliteral_t c, const factorid_t m_first_child_id, const factorid_t m_next_sibling_id) { m_first_child.push_back(m_first_child_id); m_next_sibling.push_back(m_next_sibling_id); m_literal.push_back(c); return undef_id; } node_t find_or_insert(const node_t& parent_w, uliteral_t c) override { auto parent = parent_w.id(); const factorid_t newleaf_id = size(); //! if we add a new node, its index will be equal to the current size of the dictionary DCHECK_LT(parent, size()); if(m_first_child[parent] == undef_id) { m_first_child[parent] = newleaf_id; return new_node(c, undef_id, undef_id); } else { factorid_t node = m_first_child[parent]; if(m_literal[node] > c) { m_first_child[parent] = newleaf_id; return new_node(c, undef_id, node); } while(true) { // search the binary tree stored in parent (following left/right siblings) if(c == m_literal[node]) return node; if(m_next_sibling[node] == undef_id) { m_next_sibling[node] = newleaf_id; return new_node(c, undef_id, undef_id); } const factorid_t nextnode = m_next_sibling[node]; if(m_literal[nextnode] > c) { m_next_sibling[node] = newleaf_id; return new_node(c, undef_id, nextnode); } node = m_next_sibling[node]; if(m_first_child.capacity() == m_first_child.size()) { const size_t newbound = m_first_child.size()+lz78_expected_number_of_remaining_elements(size(),m_n,m_remaining_characters); if(newbound < m_first_child.size()*2 ) { m_first_child.reserve (newbound); m_next_sibling.reserve (newbound); m_literal.reserve (newbound); IF_STATS(++m_specialresizes); } IF_STATS(++m_resizes); } } } DCHECK(false); return undef_id; } factorid_t size() const override { return m_first_child.size(); } }; }} //ns <commit_msg>remove tabs<commit_after>#pragma once #include <vector> #include <tudocomp/compressors/lz78/LZ78Trie.hpp> #include <tudocomp/Algorithm.hpp> namespace tdc { namespace lz78 { class BinarySortedTrie : public Algorithm, public LZ78Trie<factorid_t> { /* * The trie is not stored in standard form. Each node stores the pointer to its first child and a pointer to its next sibling (first as first come first served) */ std::vector<factorid_t> m_first_child; std::vector<factorid_t> m_next_sibling; std::vector<literal_t> m_literal; IF_STATS( size_t m_resizes = 0; size_t m_specialresizes = 0; ) public: inline static Meta meta() { Meta m("lz78trie", "binarysorted", "Lempel-Ziv 78 Sorted Binary Trie"); return m; } inline BinarySortedTrie(Env&& env, size_t n, const size_t& remaining_characters, factorid_t reserve = 0) : Algorithm(std::move(env)) , LZ78Trie(n,remaining_characters) { if(reserve > 0) { m_first_child.reserve(reserve); m_next_sibling.reserve(reserve); m_literal.reserve(reserve); } } node_t add_rootnode(uliteral_t c) override { m_first_child.push_back(undef_id); m_next_sibling.push_back(undef_id); m_literal.push_back(c); return size() - 1; } node_t get_rootnode(uliteral_t c) override { return c; } void clear() override { m_first_child.clear(); m_next_sibling.clear(); m_literal.clear(); } inline factorid_t new_node(uliteral_t c, const factorid_t m_first_child_id, const factorid_t m_next_sibling_id) { m_first_child.push_back(m_first_child_id); m_next_sibling.push_back(m_next_sibling_id); m_literal.push_back(c); return undef_id; } node_t find_or_insert(const node_t& parent_w, uliteral_t c) override { auto parent = parent_w.id(); const factorid_t newleaf_id = size(); //! if we add a new node, its index will be equal to the current size of the dictionary DCHECK_LT(parent, size()); if(m_first_child[parent] == undef_id) { m_first_child[parent] = newleaf_id; return new_node(c, undef_id, undef_id); } else { factorid_t node = m_first_child[parent]; if(m_literal[node] > c) { m_first_child[parent] = newleaf_id; return new_node(c, undef_id, node); } while(true) { // search the binary tree stored in parent (following left/right siblings) if(c == m_literal[node]) return node; if(m_next_sibling[node] == undef_id) { m_next_sibling[node] = newleaf_id; return new_node(c, undef_id, undef_id); } const factorid_t nextnode = m_next_sibling[node]; if(m_literal[nextnode] > c) { m_next_sibling[node] = newleaf_id; return new_node(c, undef_id, nextnode); } node = m_next_sibling[node]; if(m_first_child.capacity() == m_first_child.size()) { const size_t newbound = m_first_child.size()+lz78_expected_number_of_remaining_elements(size(),m_n,m_remaining_characters); if(newbound < m_first_child.size()*2 ) { m_first_child.reserve (newbound); m_next_sibling.reserve (newbound); m_literal.reserve (newbound); IF_STATS(++m_specialresizes); } IF_STATS(++m_resizes); } } } DCHECK(false); return undef_id; } factorid_t size() const override { return m_first_child.size(); } }; }} //ns <|endoftext|>
<commit_before><commit_msg>Fix crash on startup<commit_after><|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <[email protected]> // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Path.h" #include "clang/Sema/Sema.h" #include "clang/Basic/Diagnostic.h" #include "clang/AST/AST.h" #include "clang/AST/ASTContext.h" // for operator new[](unsigned long, ASTCtx..) #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/DeclVisitor.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/AutoloadCallback.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/Output.h" #include "DeclUnloader.h" #include <clang/Lex/HeaderSearch.h> namespace { static const char annoTag[] = "$clingAutoload$"; static const size_t lenAnnoTag = sizeof(annoTag) - 1; } using namespace clang; namespace cling { void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name, llvm::StringRef header) { Sema& sema= m_Interpreter->getSema(); unsigned id = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning, "Note: '%0' can be found in %1"); /* unsigned idn //TODO: To be enabled after we have a way to get the full path = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note, "Type : %0 , Full Path: %1")*/; if (header.startswith(llvm::StringRef(annoTag, lenAnnoTag))) sema.Diags.Report(l, id) << name << header.drop_front(lenAnnoTag); } bool AutoloadCallback::LookupObject (TagDecl *t) { if (m_ShowSuggestions && t->hasAttr<AnnotateAttr>()) report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation()); return false; } class AutoloadingVisitor: public RecursiveASTVisitor<AutoloadingVisitor> { private: ///\brief Flag determining the visitor's actions. If true, register autoload /// entries, i.e. remember the connection between filename and the declaration /// that needs to be updated on #include of the filename. /// If false, react on an #include by adjusting the forward decls, e.g. by /// removing the default tremplate arguments (that will now be provided by /// the definition read from the include) and by removing enum declarations /// that would otherwise be duplicates. bool m_IsStoringState; bool m_IsAutloadEntry; // True during the traversal of an explicitly annotated decl. AutoloadCallback::FwdDeclsMap* m_Map; clang::Preprocessor* m_PP; clang::Sema* m_Sema; std::pair<const clang::FileEntry*,const clang::FileEntry*> m_PrevFE; std::pair<std::string,std::string> m_PrevFileName; private: bool IsAutoloadEntry(Decl *D) { for(auto attr = D->specific_attr_begin<AnnotateAttr>(), end = D->specific_attr_end<AnnotateAttr> (); attr != end; ++attr) { // cling::errs() << "Annotation: " << c->getAnnotation() << "\n"; if (!attr->isInherited()) { llvm::StringRef annotation = attr->getAnnotation(); assert(!annotation.empty() && "Empty annotation!"); if (annotation.startswith(llvm::StringRef(annoTag, lenAnnoTag))) { // autoload annotation. return true; } } } return false; } using Annotations_t = std::pair<llvm::StringRef,llvm::StringRef>; void InsertIntoAutoloadingState(Decl* decl, Annotations_t FileNames) { assert(m_PP); auto addFile = [this,decl](llvm::StringRef FileName, bool warn) { if (FileName.empty()) return (const FileEntry*)nullptr; const FileEntry* FE = 0; SourceLocation fileNameLoc; bool isAngled = false; const DirectoryLookup* FromDir = 0; const FileEntry* FromFile = 0; const DirectoryLookup* CurDir = 0; bool needCacheUpdate = false; if (FileName.equals(m_PrevFileName.first)) FE = m_PrevFE.first; else if (FileName.equals(m_PrevFileName.second)) FE = m_PrevFE.second; else { FE = m_PP->LookupFile(fileNameLoc, FileName, isAngled, FromDir, FromFile, CurDir, /*SearchPath*/0, /*RelativePath*/ 0, /*suggestedModule*/0, /*IsMapped*/0, /*SkipCache*/ false, /*OpenFile*/ false, /*CacheFail*/ true); needCacheUpdate = true; } if (FE) { auto& Vec = (*m_Map)[FE]; Vec.push_back(decl); if (needCacheUpdate) return FE; else return (const FileEntry*)nullptr; } else if (warn) { // If the top level header is expected to be findable at run-time, // the direct header might not because the include path might be // different enough and only the top-header is guaranteed to be seen // by the user as an interface header to be available on the // run-time include path. cling::errs() << "Error in cling::AutoloadingVisitor::InsertIntoAutoloadingState:\n" " Missing FileEntry for " << FileName << "\n"; if (NamedDecl* ND = dyn_cast<NamedDecl>(decl)) { cling::errs() << " requested to autoload type "; ND->getNameForDiagnostic(cling::errs(), ND->getASTContext().getPrintingPolicy(), true /*qualified*/); cling::errs() << "\n"; } return (const FileEntry*)nullptr; } else { // Case of the direct header that is not a top level header, no // warning in this case (to likely to be a false positive). return (const FileEntry*)nullptr; } }; const FileEntry* cacheUpdate; if ( (cacheUpdate = addFile(FileNames.first,true)) ) { m_PrevFE.first = cacheUpdate; m_PrevFileName.first = FileNames.first; } if ( (cacheUpdate = addFile(FileNames.second,false)) ) { m_PrevFE.second = cacheUpdate; m_PrevFileName.second = FileNames.second; } } public: AutoloadingVisitor(): m_IsStoringState(false), m_IsAutloadEntry(false), m_Map(0), m_PP(0), m_Sema(0), m_PrevFE({nullptr,nullptr}) {} void RemoveDefaultArgsOf(Decl* D, Sema* S) { m_Sema = S; auto cursor = D->getMostRecentDecl(); m_IsAutloadEntry = IsAutoloadEntry(cursor); TraverseDecl(cursor); while (cursor != D && (cursor = cursor->getPreviousDecl())) { m_IsAutloadEntry = IsAutoloadEntry(cursor); TraverseDecl(cursor); } m_IsAutloadEntry = false; } void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map, Preprocessor& PP) { m_IsStoringState = true; m_Map = &map; m_PP = &PP; TraverseDecl(D); m_PP = 0; m_Map = 0; m_IsStoringState = false; } bool shouldVisitTemplateInstantiations() { return true; } bool VisitDecl(Decl* D) { if (!m_IsStoringState) return true; if (!D->hasAttr<AnnotateAttr>()) return true; Annotations_t annotations; for(auto attr = D->specific_attr_begin<AnnotateAttr> (), end = D->specific_attr_end<AnnotateAttr> (); attr != end; ++attr) { if (!attr->isInherited()) { auto annot = attr->getAnnotation(); if (annot.startswith(llvm::StringRef(annoTag, lenAnnoTag))) { if (annotations.first.empty()) { annotations.first = annot.drop_front(lenAnnoTag); } else { annotations.second = annot.drop_front(lenAnnoTag); } } } } InsertIntoAutoloadingState(D, annotations); return true; } bool VisitCXXRecordDecl(CXXRecordDecl* D) { // Since we are only interested in fixing forward declaration // there is no need to continue on when we see a complete definition. if (D->isCompleteDefinition()) return false; if (!D->hasAttr<AnnotateAttr>()) return true; if (ClassTemplateDecl* TmplD = D->getDescribedClassTemplate()) return VisitTemplateDecl(TmplD); return true; } bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } else { if (D->hasDefaultArgument() && D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } return true; } bool VisitTemplateDecl(TemplateDecl* D) { if (D->getTemplatedDecl() && !D->getTemplatedDecl()->hasAttr<AnnotateAttr>()) return true; // If we have a definition we might be about to re-#include the // same header containing definition that was #included previously, // i.e. we might have multiple fwd decls for the same template. // DO NOT remove the defaults here; the definition needs to keep it. // (ROOT-7037) if (ClassTemplateDecl* CTD = dyn_cast<ClassTemplateDecl>(D)) if (CXXRecordDecl* TemplatedD = CTD->getTemplatedDecl()) if (TemplatedD->getDefinition()) return true; for(auto P: D->getTemplateParameters()->asArray()) TraverseDecl(P); return true; } bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } else { if (D->hasDefaultArgument() && D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } return true; } bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } else { if (D->hasDefaultArgument() && D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } return true; } bool VisitParmVarDecl(ParmVarDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArg() && !D->hasInheritedDefaultArg()) D->setDefaultArg(nullptr); } else { if (D->hasDefaultArg() && D->hasInheritedDefaultArg()) D->setDefaultArg(nullptr); } return true; } bool VisitEnumDecl(EnumDecl* D) { if (m_IsStoringState) return true; // Now that we will read the full enum, unload the forward decl. if (IsAutoloadEntry(D)) UnloadDecl(m_Sema, D); return true; } }; void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc, const clang::Token &IncludeTok, llvm::StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, const clang::FileEntry *File, llvm::StringRef SearchPath, llvm::StringRef RelativePath, const clang::Module *Imported) { // If File is 0 this means that the #included file doesn't exist. if (!File) return; auto found = m_Map.find(File); if (found == m_Map.end()) return; // nothing to do, file not referred in any annotation AutoloadingVisitor defaultArgsCleaner; for (auto D : found->second) { defaultArgsCleaner.RemoveDefaultArgsOf(D, &getInterpreter()->getSema()); } // Don't need to keep track of cleaned up decls from file. m_Map.erase(found); } AutoloadCallback::~AutoloadCallback() { } void AutoloadCallback::TransactionCommitted(const Transaction &T) { if (T.decls_begin() == T.decls_end()) return; if (T.decls_begin()->m_DGR.isNull()) return; // The first decl must be // extern int __Cling_Autoloading_Map; bool HaveAutoloadingMapMarker = false; for (auto I = T.decls_begin(), E = T.decls_end(); !HaveAutoloadingMapMarker && I != E; ++I) { if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl) return; for (auto&& D: I->m_DGR) { if (isa<EmptyDecl>(D)) continue; else if (auto VD = dyn_cast<VarDecl>(D)) { HaveAutoloadingMapMarker = VD->hasExternalStorage() && VD->getIdentifier() && VD->getName().equals("__Cling_Autoloading_Map"); if (!HaveAutoloadingMapMarker) return; break; } else return; } } if (!HaveAutoloadingMapMarker) return; AutoloadingVisitor defaultArgsStateCollector; Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor(); for (auto I = T.decls_begin(), E = T.decls_end(); I != E; ++I) for (auto&& D: I->m_DGR) defaultArgsStateCollector.TrackDefaultArgStateOf(D, m_Map, PP); } } //end namespace cling <commit_msg>Claim #include <auto-parse-hdr> to remember the full path (ROOT-8863).<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <[email protected]> // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Path.h" #include "clang/Sema/Sema.h" #include "clang/Basic/Diagnostic.h" #include "clang/AST/AST.h" #include "clang/AST/ASTContext.h" // for operator new[](unsigned long, ASTCtx..) #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/DeclVisitor.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/AutoloadCallback.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/Output.h" #include "DeclUnloader.h" #include <clang/Lex/HeaderSearch.h> namespace { static const char annoTag[] = "$clingAutoload$"; static const size_t lenAnnoTag = sizeof(annoTag) - 1; } using namespace clang; namespace cling { void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name, llvm::StringRef header) { Sema& sema= m_Interpreter->getSema(); unsigned id = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning, "Note: '%0' can be found in %1"); /* unsigned idn //TODO: To be enabled after we have a way to get the full path = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note, "Type : %0 , Full Path: %1")*/; if (header.startswith(llvm::StringRef(annoTag, lenAnnoTag))) sema.Diags.Report(l, id) << name << header.drop_front(lenAnnoTag); } bool AutoloadCallback::LookupObject (TagDecl *t) { if (m_ShowSuggestions && t->hasAttr<AnnotateAttr>()) report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation()); return false; } class AutoloadingVisitor: public RecursiveASTVisitor<AutoloadingVisitor> { private: ///\brief Flag determining the visitor's actions. If true, register autoload /// entries, i.e. remember the connection between filename and the declaration /// that needs to be updated on #include of the filename. /// If false, react on an #include by adjusting the forward decls, e.g. by /// removing the default tremplate arguments (that will now be provided by /// the definition read from the include) and by removing enum declarations /// that would otherwise be duplicates. bool m_IsStoringState; bool m_IsAutloadEntry; // True during the traversal of an explicitly annotated decl. AutoloadCallback::FwdDeclsMap* m_Map; clang::Preprocessor* m_PP; clang::Sema* m_Sema; std::pair<const clang::FileEntry*,const clang::FileEntry*> m_PrevFE; std::pair<std::string,std::string> m_PrevFileName; private: bool IsAutoloadEntry(Decl *D) { for(auto attr = D->specific_attr_begin<AnnotateAttr>(), end = D->specific_attr_end<AnnotateAttr> (); attr != end; ++attr) { // cling::errs() << "Annotation: " << c->getAnnotation() << "\n"; if (!attr->isInherited()) { llvm::StringRef annotation = attr->getAnnotation(); assert(!annotation.empty() && "Empty annotation!"); if (annotation.startswith(llvm::StringRef(annoTag, lenAnnoTag))) { // autoload annotation. return true; } } } return false; } using Annotations_t = std::pair<llvm::StringRef,llvm::StringRef>; void InsertIntoAutoloadingState(Decl* decl, Annotations_t FileNames) { assert(m_PP); auto addFile = [this,decl](llvm::StringRef FileName, bool warn) { if (FileName.empty()) return (const FileEntry*)nullptr; const FileEntry* FE = 0; SourceLocation fileNameLoc; // Remember this file wth full path, not "./File.h" (ROOT-8863). bool isAngled = true; const DirectoryLookup* FromDir = 0; const FileEntry* FromFile = 0; const DirectoryLookup* CurDir = 0; bool needCacheUpdate = false; if (FileName.equals(m_PrevFileName.first)) FE = m_PrevFE.first; else if (FileName.equals(m_PrevFileName.second)) FE = m_PrevFE.second; else { FE = m_PP->LookupFile(fileNameLoc, FileName, isAngled, FromDir, FromFile, CurDir, /*SearchPath*/0, /*RelativePath*/ 0, /*suggestedModule*/0, /*IsMapped*/0, /*SkipCache*/ false, /*OpenFile*/ false, /*CacheFail*/ true); needCacheUpdate = true; } if (FE) { auto& Vec = (*m_Map)[FE]; Vec.push_back(decl); if (needCacheUpdate) return FE; else return (const FileEntry*)nullptr; } else if (warn) { // If the top level header is expected to be findable at run-time, // the direct header might not because the include path might be // different enough and only the top-header is guaranteed to be seen // by the user as an interface header to be available on the // run-time include path. cling::errs() << "Error in cling::AutoloadingVisitor::InsertIntoAutoloadingState:\n" " Missing FileEntry for " << FileName << "\n"; if (NamedDecl* ND = dyn_cast<NamedDecl>(decl)) { cling::errs() << " requested to autoload type "; ND->getNameForDiagnostic(cling::errs(), ND->getASTContext().getPrintingPolicy(), true /*qualified*/); cling::errs() << "\n"; } return (const FileEntry*)nullptr; } else { // Case of the direct header that is not a top level header, no // warning in this case (to likely to be a false positive). return (const FileEntry*)nullptr; } }; const FileEntry* cacheUpdate; if ( (cacheUpdate = addFile(FileNames.first,true)) ) { m_PrevFE.first = cacheUpdate; m_PrevFileName.first = FileNames.first; } if ( (cacheUpdate = addFile(FileNames.second,false)) ) { m_PrevFE.second = cacheUpdate; m_PrevFileName.second = FileNames.second; } } public: AutoloadingVisitor(): m_IsStoringState(false), m_IsAutloadEntry(false), m_Map(0), m_PP(0), m_Sema(0), m_PrevFE({nullptr,nullptr}) {} void RemoveDefaultArgsOf(Decl* D, Sema* S) { m_Sema = S; auto cursor = D->getMostRecentDecl(); m_IsAutloadEntry = IsAutoloadEntry(cursor); TraverseDecl(cursor); while (cursor != D && (cursor = cursor->getPreviousDecl())) { m_IsAutloadEntry = IsAutoloadEntry(cursor); TraverseDecl(cursor); } m_IsAutloadEntry = false; } void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map, Preprocessor& PP) { m_IsStoringState = true; m_Map = &map; m_PP = &PP; TraverseDecl(D); m_PP = 0; m_Map = 0; m_IsStoringState = false; } bool shouldVisitTemplateInstantiations() { return true; } bool VisitDecl(Decl* D) { if (!m_IsStoringState) return true; if (!D->hasAttr<AnnotateAttr>()) return true; Annotations_t annotations; for(auto attr = D->specific_attr_begin<AnnotateAttr> (), end = D->specific_attr_end<AnnotateAttr> (); attr != end; ++attr) { if (!attr->isInherited()) { auto annot = attr->getAnnotation(); if (annot.startswith(llvm::StringRef(annoTag, lenAnnoTag))) { if (annotations.first.empty()) { annotations.first = annot.drop_front(lenAnnoTag); } else { annotations.second = annot.drop_front(lenAnnoTag); } } } } InsertIntoAutoloadingState(D, annotations); return true; } bool VisitCXXRecordDecl(CXXRecordDecl* D) { // Since we are only interested in fixing forward declaration // there is no need to continue on when we see a complete definition. if (D->isCompleteDefinition()) return false; if (!D->hasAttr<AnnotateAttr>()) return true; if (ClassTemplateDecl* TmplD = D->getDescribedClassTemplate()) return VisitTemplateDecl(TmplD); return true; } bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } else { if (D->hasDefaultArgument() && D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } return true; } bool VisitTemplateDecl(TemplateDecl* D) { if (D->getTemplatedDecl() && !D->getTemplatedDecl()->hasAttr<AnnotateAttr>()) return true; // If we have a definition we might be about to re-#include the // same header containing definition that was #included previously, // i.e. we might have multiple fwd decls for the same template. // DO NOT remove the defaults here; the definition needs to keep it. // (ROOT-7037) if (ClassTemplateDecl* CTD = dyn_cast<ClassTemplateDecl>(D)) if (CXXRecordDecl* TemplatedD = CTD->getTemplatedDecl()) if (TemplatedD->getDefinition()) return true; for(auto P: D->getTemplateParameters()->asArray()) TraverseDecl(P); return true; } bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } else { if (D->hasDefaultArgument() && D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } return true; } bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } else { if (D->hasDefaultArgument() && D->defaultArgumentWasInherited()) D->removeDefaultArgument(); } return true; } bool VisitParmVarDecl(ParmVarDecl* D) { if (m_IsStoringState) return true; if (m_IsAutloadEntry) { if (D->hasDefaultArg() && !D->hasInheritedDefaultArg()) D->setDefaultArg(nullptr); } else { if (D->hasDefaultArg() && D->hasInheritedDefaultArg()) D->setDefaultArg(nullptr); } return true; } bool VisitEnumDecl(EnumDecl* D) { if (m_IsStoringState) return true; // Now that we will read the full enum, unload the forward decl. if (IsAutoloadEntry(D)) UnloadDecl(m_Sema, D); return true; } }; void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc, const clang::Token &IncludeTok, llvm::StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, const clang::FileEntry *File, llvm::StringRef SearchPath, llvm::StringRef RelativePath, const clang::Module *Imported) { // If File is 0 this means that the #included file doesn't exist. if (!File) return; auto found = m_Map.find(File); if (found == m_Map.end()) return; // nothing to do, file not referred in any annotation AutoloadingVisitor defaultArgsCleaner; for (auto D : found->second) { defaultArgsCleaner.RemoveDefaultArgsOf(D, &getInterpreter()->getSema()); } // Don't need to keep track of cleaned up decls from file. m_Map.erase(found); } AutoloadCallback::~AutoloadCallback() { } void AutoloadCallback::TransactionCommitted(const Transaction &T) { if (T.decls_begin() == T.decls_end()) return; if (T.decls_begin()->m_DGR.isNull()) return; // The first decl must be // extern int __Cling_Autoloading_Map; bool HaveAutoloadingMapMarker = false; for (auto I = T.decls_begin(), E = T.decls_end(); !HaveAutoloadingMapMarker && I != E; ++I) { if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl) return; for (auto&& D: I->m_DGR) { if (isa<EmptyDecl>(D)) continue; else if (auto VD = dyn_cast<VarDecl>(D)) { HaveAutoloadingMapMarker = VD->hasExternalStorage() && VD->getIdentifier() && VD->getName().equals("__Cling_Autoloading_Map"); if (!HaveAutoloadingMapMarker) return; break; } else return; } } if (!HaveAutoloadingMapMarker) return; AutoloadingVisitor defaultArgsStateCollector; Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor(); for (auto I = T.decls_begin(), E = T.decls_end(); I != E; ++I) for (auto&& D: I->m_DGR) defaultArgsStateCollector.TrackDefaultArgStateOf(D, m_Map, PP); } } //end namespace cling <|endoftext|>
<commit_before>#define GUILITE_ON //Do not define this macro once more!!! #include "GuiLite.h" #include <stdlib.h> #include <string.h> #include <math.h> // 3D engine void multiply(int m, int n, int p, float* a, float* b, float* c)// a[m][n] * b[n][p] = c[m][p] { for (int i = 0; i < m; i++) { for (int j = 0; j < p; j++) { c[i * p + j] = 0; for (int k = 0; k < n; k++) { c[i * p + j] += a[i * n + k] * b[k * p + j]; } } } } void rotateX(float angle, float* point, float* output)// rotate matrix for X { static float rotation[3][3]; rotation[0][0] = 1; rotation[1][1] = cos(angle); rotation[1][2] = 0 - sin(angle); rotation[2][1] = sin(angle); rotation[2][2] = cos(angle); multiply(3, 3, 1, (float*)rotation, point, output); } void rotateY(float angle, float* point, float* output)// rotate matrix for Y { static float rotation[3][3]; rotation[0][0] = cos(angle); rotation[0][2] = sin(angle); rotation[1][1] = 1; rotation[2][0] = 0 - sin(angle); rotation[2][2] = cos(angle); multiply(3, 3, 1, (float*)rotation, point, output); } void rotateZ(float angle, float* point, float* output)// rotate matrix for Z { static float rotation[3][3]; rotation[0][0] = cos(angle); rotation[0][1] = 0 - sin(angle); rotation[1][0] = sin(angle); rotation[1][1] = cos(angle); rotation[2][2] = 1; multiply(3, 3, 1, (float*)rotation, point, output); } void projectOnXY(float* point, float* output, float zFactor = 1) { static float projection[2][3];//project on X/Y face projection[0][0] = zFactor;//the raio of point.z and camera.z projection[1][1] = zFactor;//the raio of point.z and camera.z multiply(2, 3, 1, (float*)projection, point, output); } #define UI_WIDTH 240 #define UI_HEIGHT 320 #define SPACE 20 #define ROW 10 #define COL 10 #define POINT_CNT ROW * COL #define AMPLITUDE 50 static c_surface* s_surface; static c_display* s_display; class Cwave { public: Cwave() { rotate_angle = 1.0; angle = 0; memset(points2d, 0, sizeof(points2d)); for (int y = 0; y < ROW; y++) { for (int x = 0; x < COL; x++) { points[y * COL + x][0] = x * SPACE; points[y * COL + x][1] = y * SPACE - (UI_WIDTH / 2); } } } virtual void draw(int x, int y, bool isErase) { for (int i = 0; i < POINT_CNT; i++) { unsigned int color = (points[i][2] > 0) ? GL_RGB(231, 11, 117) : GL_RGB(92, 45, 145); s_surface->fill_rect(points2d[i][0] + x - 1, points2d[i][1] + y - 1, points2d[i][0] + x + 1, points2d[i][1] + y + 1, (isErase) ? 0 : color, Z_ORDER_LEVEL_0); } } virtual void swing() { angle += 0.1; for (int y = 0; y < ROW; y++) { for (int x = 0; x < COL; x++) { float offset = sqrt((x - 5) * (x - 5) + (y - 5) * (y - 5)) / 2; points[y * COL + x][2] = sin(angle + offset) * AMPLITUDE; } } float rotateOut1[3][1]; for (int i = 0; i < POINT_CNT; i++) { rotateX(rotate_angle, points[i], (float*)rotateOut1); projectOnXY((float*)rotateOut1, (float*)points2d[i]); } //rotate_angle += 0.1; } private: static float points[POINT_CNT][3]; float points2d[POINT_CNT][2]; float angle, rotate_angle; }; float Cwave::points[POINT_CNT][3];//x, y, z // Demo void create_ui(void* phy_fb, int screen_width, int screen_height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op) { if (phy_fb) { static c_surface surface(UI_WIDTH, UI_HEIGHT, color_bytes, Z_ORDER_LEVEL_0); static c_display display(phy_fb, screen_width, screen_height, &surface); s_surface = &surface; s_display = &display; } else {//for MCU without framebuffer static c_surface_no_fb surface_no_fb(UI_WIDTH, UI_HEIGHT, color_bytes, gfx_op, Z_ORDER_LEVEL_0); static c_display display(phy_fb, screen_width, screen_height, &surface_no_fb); s_surface = &surface_no_fb; s_display = &display; } s_surface->fill_rect(0, 0, UI_WIDTH - 1, UI_HEIGHT - 1, 0, Z_ORDER_LEVEL_0); Cwave theCwave; while(1) { theCwave.draw(30, UI_HEIGHT / 2, true);//erase footprint theCwave.swing(); theCwave.draw(30, UI_HEIGHT / 2, false);//refresh Cwave thread_sleep(50); } } //////////////////////// interface for all platform //////////////////////// extern "C" void startHello3Dwave(void* phy_fb, int width, int height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op) { create_ui(phy_fb, width, height, color_bytes, gfx_op); } extern "C" void* getUiOfHello3Dwave(int* width, int* height, bool force_update) { return s_display->get_updated_fb(width, height, force_update); } <commit_msg>change color of hell3Dwave<commit_after>#define GUILITE_ON //Do not define this macro once more!!! #include "GuiLite.h" #include <stdlib.h> #include <string.h> #include <math.h> // 3D engine void multiply(int m, int n, int p, float* a, float* b, float* c)// a[m][n] * b[n][p] = c[m][p] { for (int i = 0; i < m; i++) { for (int j = 0; j < p; j++) { c[i * p + j] = 0; for (int k = 0; k < n; k++) { c[i * p + j] += a[i * n + k] * b[k * p + j]; } } } } void rotateX(float angle, float* point, float* output)// rotate matrix for X { static float rotation[3][3]; rotation[0][0] = 1; rotation[1][1] = cos(angle); rotation[1][2] = 0 - sin(angle); rotation[2][1] = sin(angle); rotation[2][2] = cos(angle); multiply(3, 3, 1, (float*)rotation, point, output); } void rotateY(float angle, float* point, float* output)// rotate matrix for Y { static float rotation[3][3]; rotation[0][0] = cos(angle); rotation[0][2] = sin(angle); rotation[1][1] = 1; rotation[2][0] = 0 - sin(angle); rotation[2][2] = cos(angle); multiply(3, 3, 1, (float*)rotation, point, output); } void rotateZ(float angle, float* point, float* output)// rotate matrix for Z { static float rotation[3][3]; rotation[0][0] = cos(angle); rotation[0][1] = 0 - sin(angle); rotation[1][0] = sin(angle); rotation[1][1] = cos(angle); rotation[2][2] = 1; multiply(3, 3, 1, (float*)rotation, point, output); } void projectOnXY(float* point, float* output, float zFactor = 1) { static float projection[2][3];//project on X/Y face projection[0][0] = zFactor;//the raio of point.z and camera.z projection[1][1] = zFactor;//the raio of point.z and camera.z multiply(2, 3, 1, (float*)projection, point, output); } #define UI_WIDTH 240 #define UI_HEIGHT 320 #define SPACE 13 #define ROW 15 #define COL 15 #define POINT_CNT ROW * COL #define AMPLITUDE 50 static c_surface* s_surface; static c_display* s_display; class Cwave { public: Cwave() { rotate_angle = 1.0;//1.57; angle = 0; memset(points2d, 0, sizeof(points2d)); for (int y = 0; y < ROW; y++) { for (int x = 0; x < COL; x++) { points[y * COL + x][0] = x * SPACE; points[y * COL + x][1] = y * SPACE - (UI_WIDTH / 2); } } } virtual void draw(int x, int y, bool isErase) { for (int i = 0; i < POINT_CNT; i++) { float factor = (1 + points[i][2] / AMPLITUDE) / 2; unsigned int color = GL_RGB(147 * factor, 72 * factor, 232 * factor); s_surface->fill_rect(points2d[i][0] + x - 1, points2d[i][1] + y - 1, points2d[i][0] + x + 1, points2d[i][1] + y + 1, (isErase) ? 0 : color, Z_ORDER_LEVEL_0); } } virtual void swing() { angle += 0.1; for (int y = 0; y < ROW; y++) { for (int x = 0; x < COL; x++) { float offset = sqrt((x - COL / 2) * (x - COL / 2) + (y - ROW / 2) * (y - ROW / 2)) / 2; points[y * COL + x][2] = sin(angle + offset) * AMPLITUDE; } } float rotateOut1[3][1]; for (int i = 0; i < POINT_CNT; i++) { rotateX(rotate_angle, points[i], (float*)rotateOut1); float zFactor = UI_WIDTH / (UI_WIDTH - rotateOut1[2][0]); projectOnXY((float*)rotateOut1, (float*)points2d[i], zFactor); } //rotate_angle += 0.001; } private: static float points[POINT_CNT][3]; float points2d[POINT_CNT][2]; float angle, rotate_angle; }; float Cwave::points[POINT_CNT][3];//x, y, z // Demo void create_ui(void* phy_fb, int screen_width, int screen_height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op) { if (phy_fb) { static c_surface surface(UI_WIDTH, UI_HEIGHT, color_bytes, Z_ORDER_LEVEL_0); static c_display display(phy_fb, screen_width, screen_height, &surface); s_surface = &surface; s_display = &display; } else {//for MCU without framebuffer static c_surface_no_fb surface_no_fb(UI_WIDTH, UI_HEIGHT, color_bytes, gfx_op, Z_ORDER_LEVEL_0); static c_display display(phy_fb, screen_width, screen_height, &surface_no_fb); s_surface = &surface_no_fb; s_display = &display; } s_surface->fill_rect(0, 0, UI_WIDTH - 1, UI_HEIGHT - 1, 0, Z_ORDER_LEVEL_0); Cwave theCwave; while(1) { theCwave.draw(30, UI_HEIGHT / 2, true);//erase footprint theCwave.swing(); theCwave.draw(30, UI_HEIGHT / 2, false);//refresh Cwave thread_sleep(50); } } //////////////////////// interface for all platform //////////////////////// extern "C" void startHello3Dwave(void* phy_fb, int width, int height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op) { create_ui(phy_fb, width, height, color_bytes, gfx_op); } extern "C" void* getUiOfHello3Dwave(int* width, int* height, bool force_update) { return s_display->get_updated_fb(width, height, force_update); } <|endoftext|>
<commit_before>/* Copyright (C) 2009, Eric Sabouraud <[email protected]> Copyright (C) 2008-2009, Pier Castonguay <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 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 Mumble Developers 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 FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <tchar.h> #include "iig_settings.h" #include "iig_gui.h" //* \brief Do not check these processes for game modules static const TCHAR* defaultBlackList[] = { _T("<unknown>"), _T("RGSC.EXE"), // rockstar social games club _T("WMPLAYER.EXE"), _T("ITUNES.EXE"), _T("VLC.EXE"), // videolan _T("BSPLAYER.EXE"), _T("IEXPLORE.EXE"), _T("FIREFOX.EXE"), _T("OPERA.EXE"), _T("WINAMP.EXE"), _T("MPLAYERC.EXE"), // media player classic _T("EXPLORER.EXE"), _T("STEAM.EXE"), _T("SMP.EXE"), // steam media player _T("msnmsgr.exe"), // msn/live messenger _T("nvCplUI.exe"), // nvidia control panel _T("mumble.exe"), _T("GameOverlayUI.exe") // steam in-game overlay }; //* \brief Do not check these processes for game modules static const TCHAR* defaultWhiteList[][2] = { { _T("chuzzle.exe"), _T("Chuzzle") }, { _T("WinBej.exe"), _T("Bejeweled") }, }; static int bwListCompare(const void* elt1, const void* elt2) { return _tcsicmp(((struct bwListElt*)elt1)->procname, ((struct bwListElt*)elt2)->procname); } static int bwListCompareKey(const void* key, const void* elt) { return _tcsicmp((TCHAR*)key, ((struct bwListElt*)elt)->procname); } struct bwListElt* bwListSearch(const TCHAR* procname, const struct bwListElt list[], int listSize) { return (struct bwListElt*)bsearch(procname, list, listSize, sizeof(*list), bwListCompareKey); } static void RemoveDoublesFromBWList(struct bwListElt list[], UINT* pListSize) { UINT i = 0; for (i = 0; *pListSize > 1 && i < *pListSize - 1;) { if (_tcsicmp(list[i].procname, list[i+1].procname) == 0) { if (i < *pListSize - 2) { memmove(&list[i+1], &list[i+2], (*pListSize - (i+2)) * sizeof(*list)); } (*pListSize)--; } else { ++i; } } } void SaveBlackList(const SystemSettings* settings) { FILE *file = NULL; UINT i = 0; TCHAR filepath[_MAX_PATH]; _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\blist.txt"), settings->path); if ((file = _tfopen(filepath, _T("w"))) != NULL) { for (i = 0; i < settings->blackListSize; ++i) { _ftprintf(file, _T("%s\n"), settings->blackList[i].procname); } fclose(file); } } void SaveWhiteList(const SystemSettings* settings) { FILE *file = NULL; UINT i = 0; TCHAR filepath[_MAX_PATH]; _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\wlist.txt"), settings->path); if ((file = _tfopen(filepath, _T("w"))) != NULL) { for (i = 0; i < settings->whiteListSize; ++i) { _ftprintf(file, _T("%s|%s\n"), settings->whiteList[i].procname, settings->whiteList[i].windowName); } fclose(file); } } void LoadWhiteList(SystemSettings* settings) { FILE *file = NULL; TCHAR filepath[_MAX_PATH]; // Read whitelist, restore default if missing settings->whiteListSize = 0; _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\wlist.txt"), settings->path); if ((file = _tfopen(filepath, _T("r"))) != NULL) { while (settings->whiteListSize < sizeof(settings->whiteList)/sizeof(*settings->whiteList)) { if (_ftscanf(file, _T("%255[^|]|%255[^\n]\n"), settings->whiteList[settings->whiteListSize].procname, settings->whiteList[settings->whiteListSize].windowName) == 2) { ++settings->whiteListSize; } else { break; } } fclose(file); } else { while (settings->whiteListSize < sizeof(defaultWhiteList)/sizeof(*defaultWhiteList) && settings->whiteListSize < sizeof(settings->whiteList)/sizeof(*settings->whiteList)) { _tcsncpy(settings->whiteList[settings->whiteListSize].procname, defaultWhiteList[settings->whiteListSize][0], 255); _tcsncpy(settings->whiteList[settings->whiteListSize].windowName, defaultWhiteList[settings->whiteListSize][1], 255); ++settings->whiteListSize; } } qsort(settings->whiteList, settings->whiteListSize, sizeof(*settings->whiteList), bwListCompare); RemoveDoublesFromBWList(settings->whiteList, &settings->whiteListSize); } void LoadBlackList(SystemSettings* settings) { FILE *file = NULL; TCHAR filepath[_MAX_PATH]; // Read blacklist, restore default if missing settings->blackListSize = 0; _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\blist.txt"), settings->path); if ((file = _tfopen(filepath, _T("r"))) != NULL) { while (settings->blackListSize < sizeof(settings->blackList)/sizeof(*settings->blackList)) { if (_ftscanf(file, _T("%255[^\n]\n"), settings->blackList[settings->blackListSize].procname) == 1) { ++settings->blackListSize; } else { break; } } fclose(file); } // Always add default blacklist in order to propagate updates while (settings->blackListSize < sizeof(defaultBlackList)/sizeof(*defaultBlackList) && settings->blackListSize < sizeof(settings->blackList)/sizeof(*settings->blackList)) { _tcsncpy(settings->blackList[settings->blackListSize].procname, defaultBlackList[settings->blackListSize], 255); ++settings->blackListSize; } qsort(settings->blackList, settings->blackListSize, sizeof(*settings->blackList), bwListCompare); RemoveDoublesFromBWList(settings->blackList, &settings->blackListSize); } static void AddToBWList(struct bwListElt list[], UINT listCapacity, UINT* pListSize, const TCHAR* procname, const TCHAR* windowName) { if (*pListSize < listCapacity) { _tcscpy(list[*pListSize].procname, procname); if (windowName) { _tcscpy(list[*pListSize].windowName, windowName); } ++(*pListSize); qsort(list, *pListSize, sizeof(*list), bwListCompare); } } static void RemoveFromBWList(struct bwListElt list[], UINT* pListSize, const TCHAR* procname) { struct bwListElt* elt = bwListSearch(procname, list, *pListSize); if (elt) { int len = &list[*pListSize] - elt; if (--len) { memmove(elt, elt + 1, len * sizeof(*list)); } --(*pListSize); } } void AddToBlackList(SystemSettings* settings, const TCHAR* procname) { AddToBWList(settings->blackList, sizeof(settings->blackList)/sizeof(*settings->blackList), &settings->blackListSize, procname, NULL); SaveBlackList(settings); } void RemoveFromBlackList(SystemSettings* settings, const TCHAR* procname) { RemoveFromBWList(settings->blackList, &settings->blackListSize, procname); SaveBlackList(settings); } void AddToWhiteList(SystemSettings* settings, const TCHAR* procname, const TCHAR* windowName) { AddToBWList(settings->whiteList, sizeof(settings->whiteList)/sizeof(*settings->whiteList), &settings->whiteListSize, procname, windowName); SaveWhiteList(settings); } void RemoveFromWhiteList(SystemSettings* settings, const TCHAR* procname) { RemoveFromBWList(settings->whiteList, &settings->whiteListSize, procname); SaveWhiteList(settings); } void SaveSettings(const SystemSettings* settings) { FILE *file = NULL; UINT i = 0; TCHAR filepath[_MAX_PATH]; _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\settings.ini"), settings->path); if ((file = _tfopen(filepath, _T("w"))) != NULL) { _ftprintf(file, _T("[general]\nuserMessage=%s\ninterval=%u\nasGame=%d\nlegacyTimer=%d\nlang=%u\n"), settings->userMessage, settings->interval, settings->asGame, settings->legacyTimer, settings->lang); fclose(file); } SaveWhiteList(settings); SaveBlackList(settings); } void LoadSettings(SystemSettings* settings) { FILE *file = NULL; BOOL loadSuccess = FALSE; UINT lang = 0; TCHAR filepath[_MAX_PATH]; DWORD pathlen = sizeof(settings->path); HKEY hkey = NULL; memset(settings->path, 0, pathlen); // Try and read installation directory from registry, use current directory if it fails if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\IMinGame"), 0, KEY_READ, &hkey)) { if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\IMinGame"), 0, KEY_READ, &hkey)) { hkey = NULL; } } if (hkey) { if (ERROR_SUCCESS != RegQueryValueEx(hkey, _T("Path"), NULL, NULL, (LPBYTE)settings->path, &pathlen)) { _sntprintf(settings->path, sizeof(settings->path)/sizeof(*settings->path), _T(".")); } RegCloseKey(hkey); } // Read settings file if present _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\settings.ini"), settings->path); if ((file = _tfopen(filepath, _T("r"))) != NULL) { // This part could be replaced with GetPrivateProfileSection/GetPrivateProfileString loadSuccess = _ftscanf(file, _T("[general]\nuserMessage=%62[^\n]\ninterval=%u\nasGame=%d\nlegacyTimer=%d\nlang=%u\n"), &settings->userMessage, &settings->interval, &settings->asGame, &settings->legacyTimer, &settings->lang) == 5; fclose(file); } // Fallback on pre-settings file (created by installer) if settings file is missing or corrupted _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\presettings.ini"), settings->path); if (!loadSuccess && (file = _tfopen(filepath, _T("r"))) != NULL) { _ftscanf(file, _T("[general]\nlang=%u\n"), &lang); fclose(file); } // Set default settings if (!loadSuccess) { settings->interval = 25; settings->asGame = FALSE; settings->legacyTimer = FALSE; settings->lang = lang; _tcscpy(settings->userMessage, getLangString(settings->lang, IIG_LANGSTR_USERMSGDEF)); } LoadWhiteList(settings); LoadBlackList(settings); } <commit_msg>fix current directory not used to store config if registry key not found<commit_after>/* Copyright (C) 2009, Eric Sabouraud <[email protected]> Copyright (C) 2008-2009, Pier Castonguay <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - 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 Mumble Developers 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 FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <tchar.h> #include "iig_settings.h" #include "iig_gui.h" //* \brief Do not check these processes for game modules static const TCHAR* defaultBlackList[] = { _T("<unknown>"), _T("RGSC.EXE"), // rockstar social games club _T("WMPLAYER.EXE"), _T("ITUNES.EXE"), _T("VLC.EXE"), // videolan _T("BSPLAYER.EXE"), _T("IEXPLORE.EXE"), _T("FIREFOX.EXE"), _T("OPERA.EXE"), _T("WINAMP.EXE"), _T("MPLAYERC.EXE"), // media player classic _T("EXPLORER.EXE"), _T("STEAM.EXE"), _T("SMP.EXE"), // steam media player _T("msnmsgr.exe"), // msn/live messenger _T("nvCplUI.exe"), // nvidia control panel _T("mumble.exe"), _T("GameOverlayUI.exe") // steam in-game overlay }; //* \brief Do not check these processes for game modules static const TCHAR* defaultWhiteList[][2] = { { _T("chuzzle.exe"), _T("Chuzzle") }, { _T("WinBej.exe"), _T("Bejeweled") }, }; static int bwListCompare(const void* elt1, const void* elt2) { return _tcsicmp(((struct bwListElt*)elt1)->procname, ((struct bwListElt*)elt2)->procname); } static int bwListCompareKey(const void* key, const void* elt) { return _tcsicmp((TCHAR*)key, ((struct bwListElt*)elt)->procname); } struct bwListElt* bwListSearch(const TCHAR* procname, const struct bwListElt list[], int listSize) { return (struct bwListElt*)bsearch(procname, list, listSize, sizeof(*list), bwListCompareKey); } static void RemoveDoublesFromBWList(struct bwListElt list[], UINT* pListSize) { UINT i = 0; for (i = 0; *pListSize > 1 && i < *pListSize - 1;) { if (_tcsicmp(list[i].procname, list[i+1].procname) == 0) { if (i < *pListSize - 2) { memmove(&list[i+1], &list[i+2], (*pListSize - (i+2)) * sizeof(*list)); } (*pListSize)--; } else { ++i; } } } void SaveBlackList(const SystemSettings* settings) { FILE *file = NULL; UINT i = 0; TCHAR filepath[_MAX_PATH]; _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\blist.txt"), settings->path); if ((file = _tfopen(filepath, _T("w"))) != NULL) { for (i = 0; i < settings->blackListSize; ++i) { _ftprintf(file, _T("%s\n"), settings->blackList[i].procname); } fclose(file); } } void SaveWhiteList(const SystemSettings* settings) { FILE *file = NULL; UINT i = 0; TCHAR filepath[_MAX_PATH]; _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\wlist.txt"), settings->path); if ((file = _tfopen(filepath, _T("w"))) != NULL) { for (i = 0; i < settings->whiteListSize; ++i) { _ftprintf(file, _T("%s|%s\n"), settings->whiteList[i].procname, settings->whiteList[i].windowName); } fclose(file); } } void LoadWhiteList(SystemSettings* settings) { FILE *file = NULL; TCHAR filepath[_MAX_PATH]; // Read whitelist, restore default if missing settings->whiteListSize = 0; _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\wlist.txt"), settings->path); if ((file = _tfopen(filepath, _T("r"))) != NULL) { while (settings->whiteListSize < sizeof(settings->whiteList)/sizeof(*settings->whiteList)) { if (_ftscanf(file, _T("%255[^|]|%255[^\n]\n"), settings->whiteList[settings->whiteListSize].procname, settings->whiteList[settings->whiteListSize].windowName) == 2) { ++settings->whiteListSize; } else { break; } } fclose(file); } else { while (settings->whiteListSize < sizeof(defaultWhiteList)/sizeof(*defaultWhiteList) && settings->whiteListSize < sizeof(settings->whiteList)/sizeof(*settings->whiteList)) { _tcsncpy(settings->whiteList[settings->whiteListSize].procname, defaultWhiteList[settings->whiteListSize][0], 255); _tcsncpy(settings->whiteList[settings->whiteListSize].windowName, defaultWhiteList[settings->whiteListSize][1], 255); ++settings->whiteListSize; } } qsort(settings->whiteList, settings->whiteListSize, sizeof(*settings->whiteList), bwListCompare); RemoveDoublesFromBWList(settings->whiteList, &settings->whiteListSize); } void LoadBlackList(SystemSettings* settings) { FILE *file = NULL; TCHAR filepath[_MAX_PATH]; // Read blacklist, restore default if missing settings->blackListSize = 0; _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\blist.txt"), settings->path); if ((file = _tfopen(filepath, _T("r"))) != NULL) { while (settings->blackListSize < sizeof(settings->blackList)/sizeof(*settings->blackList)) { if (_ftscanf(file, _T("%255[^\n]\n"), settings->blackList[settings->blackListSize].procname) == 1) { ++settings->blackListSize; } else { break; } } fclose(file); } // Always add default blacklist in order to propagate updates while (settings->blackListSize < sizeof(defaultBlackList)/sizeof(*defaultBlackList) && settings->blackListSize < sizeof(settings->blackList)/sizeof(*settings->blackList)) { _tcsncpy(settings->blackList[settings->blackListSize].procname, defaultBlackList[settings->blackListSize], 255); ++settings->blackListSize; } qsort(settings->blackList, settings->blackListSize, sizeof(*settings->blackList), bwListCompare); RemoveDoublesFromBWList(settings->blackList, &settings->blackListSize); } static void AddToBWList(struct bwListElt list[], UINT listCapacity, UINT* pListSize, const TCHAR* procname, const TCHAR* windowName) { if (*pListSize < listCapacity) { _tcscpy(list[*pListSize].procname, procname); if (windowName) { _tcscpy(list[*pListSize].windowName, windowName); } ++(*pListSize); qsort(list, *pListSize, sizeof(*list), bwListCompare); } } static void RemoveFromBWList(struct bwListElt list[], UINT* pListSize, const TCHAR* procname) { struct bwListElt* elt = bwListSearch(procname, list, *pListSize); if (elt) { int len = &list[*pListSize] - elt; if (--len) { memmove(elt, elt + 1, len * sizeof(*list)); } --(*pListSize); } } void AddToBlackList(SystemSettings* settings, const TCHAR* procname) { AddToBWList(settings->blackList, sizeof(settings->blackList)/sizeof(*settings->blackList), &settings->blackListSize, procname, NULL); SaveBlackList(settings); } void RemoveFromBlackList(SystemSettings* settings, const TCHAR* procname) { RemoveFromBWList(settings->blackList, &settings->blackListSize, procname); SaveBlackList(settings); } void AddToWhiteList(SystemSettings* settings, const TCHAR* procname, const TCHAR* windowName) { AddToBWList(settings->whiteList, sizeof(settings->whiteList)/sizeof(*settings->whiteList), &settings->whiteListSize, procname, windowName); SaveWhiteList(settings); } void RemoveFromWhiteList(SystemSettings* settings, const TCHAR* procname) { RemoveFromBWList(settings->whiteList, &settings->whiteListSize, procname); SaveWhiteList(settings); } void SaveSettings(const SystemSettings* settings) { FILE *file = NULL; UINT i = 0; TCHAR filepath[_MAX_PATH]; _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\settings.ini"), settings->path); if ((file = _tfopen(filepath, _T("w"))) != NULL) { _ftprintf(file, _T("[general]\nuserMessage=%s\ninterval=%u\nasGame=%d\nlegacyTimer=%d\nlang=%u\n"), settings->userMessage, settings->interval, settings->asGame, settings->legacyTimer, settings->lang); fclose(file); } SaveWhiteList(settings); SaveBlackList(settings); } void LoadSettings(SystemSettings* settings) { FILE *file = NULL; BOOL loadSuccess = FALSE; UINT lang = 0; TCHAR filepath[_MAX_PATH]; DWORD pathlen = sizeof(settings->path); HKEY hkey = NULL; memset(settings->path, 0, pathlen); _sntprintf(settings->path, sizeof(settings->path)/sizeof(*settings->path), _T(".")); // Try and read installation directory from registry, use current directory if it fails if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\IMinGame"), 0, KEY_READ, &hkey)) { if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\IMinGame"), 0, KEY_READ, &hkey)) { hkey = NULL; } } if (hkey) { if (ERROR_SUCCESS != RegQueryValueEx(hkey, _T("Path"), NULL, NULL, (LPBYTE)settings->path, &pathlen)) { _sntprintf(settings->path, sizeof(settings->path)/sizeof(*settings->path), _T(".")); } RegCloseKey(hkey); } // Read settings file if present _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\settings.ini"), settings->path); if ((file = _tfopen(filepath, _T("r"))) != NULL) { // This part could be replaced with GetPrivateProfileSection/GetPrivateProfileString loadSuccess = _ftscanf(file, _T("[general]\nuserMessage=%62[^\n]\ninterval=%u\nasGame=%d\nlegacyTimer=%d\nlang=%u\n"), &settings->userMessage, &settings->interval, &settings->asGame, &settings->legacyTimer, &settings->lang) == 5; fclose(file); } // Fallback on pre-settings file (created by installer) if settings file is missing or corrupted _sntprintf(filepath, sizeof(filepath)/sizeof(*filepath), _T("%s\\presettings.ini"), settings->path); if (!loadSuccess && (file = _tfopen(filepath, _T("r"))) != NULL) { _ftscanf(file, _T("[general]\nlang=%u\n"), &lang); fclose(file); } // Set default settings if (!loadSuccess) { settings->interval = 25; settings->asGame = FALSE; settings->legacyTimer = FALSE; settings->lang = lang; _tcscpy(settings->userMessage, getLangString(settings->lang, IIG_LANGSTR_USERMSGDEF)); } LoadWhiteList(settings); LoadBlackList(settings); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestMetaIO.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME Test of vtkMetaIO / MetaImage // .SECTION Description // #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include "vtkOutputWindow.h" #include "vtkObjectFactory.h" #include "vtkDataObject.h" #include "vtkImageData.h" #include "vtkImageMathematics.h" int TestMetaIO(int argc, char *argv[]) { vtkOutputWindow::GetInstance()->PromptUserOn(); if ( argc <= 1 ) { cout << "Usage: " << argv[0] << " <xml file>" << endl; return 1; } vtkMetaImageReader *reader = vtkMetaImageReader::New(); reader->SetFileName(argv[1]); reader->Update(); cout << "10, 10, 10 : (1) : " << reader->GetOutput()->GetScalarComponentAsFloat(10, 10, 10, 0) << endl; cout << "24, 37, 10 : (168) : " << reader->GetOutput()->GetScalarComponentAsFloat(24, 37, 10, 0) << endl; vtkMetaImageWriter *writer = vtkMetaImageWriter::New(); writer->SetFileName("TestMetaIO.mha"); writer->SetInputConnection(reader->GetOutputPort()); writer->Write(); reader->Delete(); writer->Delete(); vtkMetaImageReader *readerStd = vtkMetaImageReader::New(); readerStd->SetFileName(argv[1]); readerStd->Update(); vtkMetaImageReader *readerNew = vtkMetaImageReader::New(); readerNew->SetFileName("TestMetaIO.mha"); readerNew->Update(); double error = 0; int * ext = readerStd->GetOutput()->GetWholeExtent(); for(int z=ext[4]; z<=ext[5]; z++) { for(int y=ext[2]; y<=ext[3]; y++) { for(int x=ext[0]; x<=ext[1]; x++) { error += fabs( readerStd->GetOutput()->GetScalarComponentAsFloat(x, y, z, 0) - readerNew->GetOutput()->GetScalarComponentAsFloat(x, y, z, 0) ); } } } if(error > 1) { cerr << "Error: Image difference on read/write = " << error << endl; return 1; } cout << "Success! Error = " << error << endl; return 0; } <commit_msg>BUG: fixing leaks<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestMetaIO.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME Test of vtkMetaIO / MetaImage // .SECTION Description // #include "vtkMetaImageReader.h" #include "vtkMetaImageWriter.h" #include "vtkOutputWindow.h" #include "vtkObjectFactory.h" #include "vtkDataObject.h" #include "vtkImageData.h" #include "vtkImageMathematics.h" int TestMetaIO(int argc, char *argv[]) { vtkOutputWindow::GetInstance()->PromptUserOn(); if ( argc <= 1 ) { cout << "Usage: " << argv[0] << " <xml file>" << endl; return 1; } vtkMetaImageReader *reader = vtkMetaImageReader::New(); reader->SetFileName(argv[1]); reader->Update(); cout << "10, 10, 10 : (1) : " << reader->GetOutput()->GetScalarComponentAsFloat(10, 10, 10, 0) << endl; cout << "24, 37, 10 : (168) : " << reader->GetOutput()->GetScalarComponentAsFloat(24, 37, 10, 0) << endl; vtkMetaImageWriter *writer = vtkMetaImageWriter::New(); writer->SetFileName("TestMetaIO.mha"); writer->SetInputConnection(reader->GetOutputPort()); writer->Write(); reader->Delete(); writer->Delete(); vtkMetaImageReader *readerStd = vtkMetaImageReader::New(); readerStd->SetFileName(argv[1]); readerStd->Update(); vtkMetaImageReader *readerNew = vtkMetaImageReader::New(); readerNew->SetFileName("TestMetaIO.mha"); readerNew->Update(); double error = 0; int * ext = readerStd->GetOutput()->GetWholeExtent(); for(int z=ext[4]; z<=ext[5]; z++) { for(int y=ext[2]; y<=ext[3]; y++) { for(int x=ext[0]; x<=ext[1]; x++) { error += fabs( readerStd->GetOutput()->GetScalarComponentAsFloat(x, y, z, 0) - readerNew->GetOutput()->GetScalarComponentAsFloat(x, y, z, 0) ); } } } readerStd->Delete(); readerNew->Delete(); if(error > 1) { cerr << "Error: Image difference on read/write = " << error << endl; return 1; } cout << "Success! Error = " << error << endl; return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbMultiToMonoChannelExtractROI.h" #include "itkRescaleIntensityImageFilter.h" #include "otbVectorRescaleIntensityImageFilter.h" // Software Guide : BeginCommandLineArgs // INPUTS: {ROI_QB_MUL_1.png} // OUTPUTS: {PCAOutput.tif}, {InversePCAOutput.tif}, {InversePCAOutput1.png}, {PCAOutput1.png}, {PCAOutput2.png}, {PCAOutput3.png} // 3 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example illustrates the use of the // \doxygen{otb}{PCAImageFilter}. // This filter computes a Principal Component Analysis using an // efficient method based on the inner product in order to compute the // covariance matrix. // // The first step required to use this filter is to include its header file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbPCAImageFilter.h" // Software Guide : EndCodeSnippet int main(int argc, char* argv[]) { typedef double PixelType; const unsigned int Dimension = 2; const char * inputFileName = argv[1]; const char * outputFilename = argv[2]; const char * outputInverseFilename = argv[3]; const unsigned int numberOfPrincipalComponentsRequired(atoi(argv[8])); // Software Guide : BeginLatex // // We start by defining the types for the images and the reader and // the writer. We choose to work with a \doxygen{otb}{VectorImage}, // since we will produce a multi-channel image (the principal // components) from a multi-channel input image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::VectorImage<PixelType, Dimension> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileWriter<ImageType> WriterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We instantiate now the image reader and we set the image file name. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(inputFileName); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We define the type for the filter. It is templated over the input // and the output image types and also the transformation direction. The // internal structure of this filter is a filter-to-filter like structure. // We can now the instantiate the filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::PCAImageFilter<ImageType, ImageType, otb::Transform::FORWARD> PCAFilterType; PCAFilterType::Pointer pcafilter = PCAFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The only parameter needed for the PCA is the number of principal // components required as output. We can choose to get less PCs than // the number of input bands. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet pcafilter->SetNumberOfPrincipalComponentsRequired( numberOfPrincipalComponentsRequired); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We now instantiate the writer and set the file name for the // output image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outputFilename); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We finally plug the pipeline and trigger the PCA computation with // the method \code{Update()} of the writer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet pcafilter->SetInput(reader->GetOutput()); writer->SetInput(pcafilter->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // \doxygen{otb}{PCAImageFilter} allows also to compute inverse // transformation from PCA coefficients. In REVERSE mode, the // covariance matrix or the transformation matrix // (which may not be square) has to be given. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::PCAImageFilter< ImageType, ImageType, otb::Transform::INVERSE > InvPCAFilterType; InvPCAFilterType::Pointer invFilter = InvPCAFilterType::New(); invFilter->SetInput(pcafilter->GetOutput()); invFilter->SetTransformationMatrix(pcafilter->GetTransformationMatrix()); WriterType::Pointer invWriter = WriterType::New(); invWriter->SetFileName(outputInverseFilename ); invWriter->SetInput(invFilter->GetOutput() ); invWriter->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // Figure~\ref{fig:PCA_FILTER} shows the result of applying // the PCA to a 3 band RGB image. // \begin{figure} // \center // \includegraphics[width=0.25\textwidth]{ROI_QB_MUL_1.eps} // \includegraphics[width=0.25\textwidth]{PCAOutput1.eps} // \includegraphics[width=0.25\textwidth]{PCAOutput2.eps} // \includegraphics[width=0.25\textwidth]{PCAOutput3.eps} // \includegraphics[width=0.25\textwidth]{InversePCAOutput1.eps} // \itkcaption[PCA Filter (forward trasnformation)]{Result of applying the // \doxygen{otb}{PCAImageFilter} to an image. From left // to right and top to bottom: // original image, first PC, second PC, third PC and inverse mode output.} // \label{fig:PCA_FILTER} // \end{figure} // // Software Guide : EndLatex typedef otb::Image<PixelType, Dimension> MonoImageType; typedef otb::MultiToMonoChannelExtractROI<PixelType, PixelType> ExtractROIFilterType; typedef otb::Image<unsigned char, 2> OutputImageType; typedef otb::VectorImage<unsigned char, 2> OutputPrettyImageType; typedef otb::ImageFileWriter<OutputImageType> WriterType2; typedef otb::ImageFileWriter<OutputPrettyImageType> WriterType3; typedef itk::RescaleIntensityImageFilter<MonoImageType, OutputImageType> RescalerType; typedef otb::VectorRescaleIntensityImageFilter<ImageType, OutputPrettyImageType> RescalerType2; typedef ImageType::PixelType VectorPixelType; for (unsigned int cpt = 0; cpt < numberOfPrincipalComponentsRequired; cpt++) { ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New(); RescalerType::Pointer rescaler = RescalerType::New(); WriterType2::Pointer writer2 = WriterType2::New(); extractROIFilter->SetInput(pcafilter->GetOutput()); extractROIFilter->SetChannel(cpt + 1); rescaler->SetInput(extractROIFilter->GetOutput()); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); writer2->SetInput(rescaler->GetOutput()); writer2->SetFileName(argv[cpt + 5]); writer2->Update(); } WriterType3::Pointer writerInverse = WriterType3::New(); RescalerType2::Pointer rescalerInverse = RescalerType2::New(); rescalerInverse->SetInput(invFilter->GetOutput()); VectorPixelType minimum, maximum; minimum.SetSize(3); maximum.SetSize(3); minimum.Fill(0); maximum.Fill(255); rescalerInverse->SetOutputMinimum(minimum); rescalerInverse->SetOutputMaximum(maximum); writerInverse->SetInput(rescalerInverse->GetOutput()); writerInverse->SetFileName(argv[4]); writerInverse->Update(); return EXIT_SUCCESS; } <commit_msg>ENH:minor modifications of pca example<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbMultiToMonoChannelExtractROI.h" #include "itkRescaleIntensityImageFilter.h" #include "otbVectorRescaleIntensityImageFilter.h" // Software Guide : BeginCommandLineArgs // INPUTS: {ROI_QB_MUL_1.png} // OUTPUTS: {PCAOutput.tif}, {InversePCAOutput.tif}, {InversePCAOutput1.png}, {PCAOutput1.png}, {PCAOutput2.png}, {PCAOutput3.png} // 3 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example illustrates the use of the // \doxygen{otb}{PCAImageFilter}. // This filter computes a Principal Component Analysis using an // efficient method based on the inner product in order to compute the // covariance matrix. // // The first step required to use this filter is to include its header file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbPCAImageFilter.h" // Software Guide : EndCodeSnippet int main(int argc, char* argv[]) { typedef double PixelType; const unsigned int Dimension = 2; const char * inputFileName = argv[1]; const char * outputFilename = argv[2]; const char * outputInverseFilename = argv[3]; const unsigned int numberOfPrincipalComponentsRequired(atoi(argv[8])); // Software Guide : BeginLatex // // We start by defining the types for the images and the reader and // the writer. We choose to work with a \doxygen{otb}{VectorImage}, // since we will produce a multi-channel image (the principal // components) from a multi-channel input image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::VectorImage<PixelType, Dimension> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileWriter<ImageType> WriterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We instantiate now the image reader and we set the image file name. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(inputFileName); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We define the type for the filter. It is templated over the input // and the output image types and also the transformation direction. The // internal structure of this filter is a filter-to-filter like structure. // We can now the instantiate the filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::PCAImageFilter<ImageType, ImageType, otb::Transform::FORWARD> PCAFilterType; PCAFilterType::Pointer pcafilter = PCAFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The only parameter needed for the PCA is the number of principal // components required as output. We can choose to get less PCs than // the number of input bands. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet pcafilter->SetNumberOfPrincipalComponentsRequired( numberOfPrincipalComponentsRequired); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We now instantiate the writer and set the file name for the // output image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outputFilename); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We finally plug the pipeline and trigger the PCA computation with // the method \code{Update()} of the writer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet pcafilter->SetInput(reader->GetOutput()); writer->SetInput(pcafilter->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // \doxygen{otb}{PCAImageFilter} allows also to compute inverse // transformation from PCA coefficients. In reverse mode, the // covariance matrix or the transformation matrix // (which may not be square) has to be given. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::PCAImageFilter< ImageType, ImageType, otb::Transform::INVERSE > InvPCAFilterType; InvPCAFilterType::Pointer invFilter = InvPCAFilterType::New(); invFilter->SetInput(pcafilter->GetOutput()); invFilter->SetTransformationMatrix(pcafilter->GetTransformationMatrix()); WriterType::Pointer invWriter = WriterType::New(); invWriter->SetFileName(outputInverseFilename ); invWriter->SetInput(invFilter->GetOutput() ); invWriter->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // Figure~\ref{fig:PCA_FILTER} shows the result of applying forward // and reverse PCA transformation to a 3 band RGB image. // \begin{figure} // \center // \includegraphics[width=0.25\textwidth]{ROI_QB_MUL_1.eps} // \includegraphics[width=0.25\textwidth]{PCAOutput1.eps} // \includegraphics[width=0.25\textwidth]{PCAOutput2.eps} // \includegraphics[width=0.25\textwidth]{PCAOutput3.eps} // \includegraphics[width=0.25\textwidth]{InversePCAOutput1.eps} // \itkcaption[PCA Filter (forward trasnformation)]{Result of applying the // \doxygen{otb}{PCAImageFilter} to an image. From left // to right and top to bottom: // original image, first PC, second PC, third PC and output of the // inverse mode (the input RGB image).} // \label{fig:PCA_FILTER} // \end{figure} // // Software Guide : EndLatex typedef otb::Image<PixelType, Dimension> MonoImageType; typedef otb::MultiToMonoChannelExtractROI<PixelType, PixelType> ExtractROIFilterType; typedef otb::Image<unsigned char, 2> OutputImageType; typedef otb::VectorImage<unsigned char, 2> OutputPrettyImageType; typedef otb::ImageFileWriter<OutputImageType> WriterType2; typedef otb::ImageFileWriter<OutputPrettyImageType> WriterType3; typedef itk::RescaleIntensityImageFilter<MonoImageType, OutputImageType> RescalerType; typedef otb::VectorRescaleIntensityImageFilter<ImageType, OutputPrettyImageType> RescalerType2; typedef ImageType::PixelType VectorPixelType; for (unsigned int cpt = 0; cpt < numberOfPrincipalComponentsRequired; cpt++) { ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New(); RescalerType::Pointer rescaler = RescalerType::New(); WriterType2::Pointer writer2 = WriterType2::New(); extractROIFilter->SetInput(pcafilter->GetOutput()); extractROIFilter->SetChannel(cpt + 1); rescaler->SetInput(extractROIFilter->GetOutput()); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); writer2->SetInput(rescaler->GetOutput()); writer2->SetFileName(argv[cpt + 5]); writer2->Update(); } WriterType3::Pointer writerInverse = WriterType3::New(); RescalerType2::Pointer rescalerInverse = RescalerType2::New(); rescalerInverse->SetInput(invFilter->GetOutput()); VectorPixelType minimum, maximum; minimum.SetSize(3); maximum.SetSize(3); minimum.Fill(0); maximum.Fill(255); rescalerInverse->SetOutputMinimum(minimum); rescalerInverse->SetOutputMaximum(maximum); writerInverse->SetInput(rescalerInverse->GetOutput()); writerInverse->SetFileName(argv[4]); writerInverse->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: FourierDescriptors1.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif // Software Guide : BeginLatex // // Fourier Descriptors provide a mechanism for representing a closed curve in // space. The represented curve has infinite continuiity because the // parametric coordinate of its points are computed from a Fourier Series. // // In this example we illustrate how a curve that is initially defined by a // set of points in space can be represented in terms for Fourier Descriptors. // This representation is useful for several purposes. For example, it // provides a mechanmism for interpolating values among the points, it // provides a way of analyzing the smoothness of the curve. In this particular // example we will focus on this second application of the Fourier Descriptors. // // The first operation that we should use in this context is the computation // of the discrete fourier transform of the point coordinates. The coordinates // of the points are considered to be independent functions and each one is // decomposed in a Fourier Series. In this section we will use $t$ as the // parameter of the curve, and will assume that it goes from $0$ to $1$ and // cycles as we go around the closed curve. // // \begin{equation} // \textbf{V(t)} = \left( X(t), Y(t) \rigth) // \end{equation} // // We take now the functions $X(t)$, $Y(t)$ and interpret them as the // components of a complex number for wich we compute its discrete fourier // series in the form // // \begin{equation} // V(t) = \sum_{k=0}^{N} \exp(-\frac{2 k \pi \textbf{i}}{N}) F_k // \end{equation} // // Where the set of coefficients $F_k$ is the discrete spectrum of the complex // function $V(t)$. These coefficients are in general complex numbers and both // their magnitude and phase must be considered in any further analysis of the // spectrum. // // Software Guide : EndLatex // Software Guide : BeginLatex // // The class \code{vnl_fft_1D} is the VNL class that computes such transform. // In order to use it, we should include its header file first. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "vnl/algo/vnl_fft_1d.h" // Software Guide : EndCodeSnippet #include "itkPoint.h" #include "itkVectorContainer.h" #include <fstream> int main(int argc, char * argv[] ) { if( argc < 2 ) { std::cerr << "Missing arguments" << std::endl; std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << "inputFileWithPointCoordinates" << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // We should now instantiate the filter that will compute the Fourier // transform of the set of coordinates. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef vnl_fft_1d< double > FFTCalculator; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The points representing the curve are stored in a // \doxygen{VectorContainer} of \doxygen{Point}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::Point< double, 2 > PointType; typedef itk::VectorContainer< unsigned int, PointType > PointsContainer; PointsContainer::Pointer points = PointsContainer::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // In this example we read the set of points from a text file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::ifstream inputFile; inputFile.open( argv[1] ); if( inputFile.fail() ) { std::cerr << "Problems opening file " << argv[1] << std::endl; } unsigned int numberOfPoints; inputFile >> numberOfPoints; points->Reserve( numberOfPoints ); typedef PointsContainer::Iterator PointIterator; PointIterator pointItr = points->Begin(); PointType point; for( unsigned int pt=0; pt<numberOfPoints; pt++) { inputFile >> point[0] >> point[1]; pointItr.Value() = point; ++pointItr; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // This class will compute the Fast Fourier transform of the input an it will // return it in the same array. We must therefore copy the original data into // an auxiliary array that will in its turn contain the results of the // transform. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef vcl_complex<double> FFTCoefficientType; typedef vcl_vector< FFTCoefficientType > FFTSpectrumType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The choice of the spectrum size is very important. Here we select to use // the next power of two that is larger than the number of points. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const unsigned int powerOfTwo = (unsigned int)ceil( log( (double)(numberOfPoints)) / log( (double)(2.0))); const unsigned int spectrumSize = 1 << powerOfTwo; // Software Guide : BeginLatex // // The Fourier Transform type can now be used for constructing one of such // filters. Note that this is a VNL class and does not follows ITK notation // for construction and assignment to SmartPointers. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet FFTCalculator fftCalculator( spectrumSize ); // Software Guide : EndCodeSnippet FFTSpectrumType signal( spectrumSize ); pointItr = points->Begin(); for(unsigned int p=0; p<numberOfPoints; p++) { signal[p] = FFTCoefficientType( pointItr.Value()[0], pointItr.Value()[1] ); ++pointItr; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Fill in the rest of the input with zeros. This padding may have // undesirable effects on the spectrum if the signal is not attenuated to // zero close to their boundaries. Instead of zero-padding we could have used // repetition of the last value or mirroring of the signal. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet for(unsigned int pad=numberOfPoints; pad<spectrumSize; pad++) { signal[pad] = 0.0; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now we print out the signal as it is passed to the transform calculator // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::cout << "Input to the FFT transform" << std::endl; for(unsigned int s=0; s<spectrumSize; s++) { std::cout << s << " : "; std::cout << signal[s] << std::endl; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The actual transform is computed by invoking the \code{fwd_transform} // method in the FFT calculator class. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet fftCalculator.fwd_transform( signal ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now we print out the results of the transform. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::cout << std::endl; std::cout << "Result from the FFT transform" << std::endl; for(unsigned int k=0; k<spectrumSize; k++) { const double real = signal[k].real(); const double imag = signal[k].imag(); const double magnitude = vcl_sqrt( real * real + imag * imag ); std::cout << k << " " << magnitude << std::endl; } // Software Guide : EndCodeSnippet return EXIT_SUCCESS; } <commit_msg>COMP: Replacing "log" and "ceil" with "vcl_log" and "vcl_ceil" in order to support Sun-CC with -stlport4.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: FourierDescriptors1.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif // Software Guide : BeginLatex // // Fourier Descriptors provide a mechanism for representing a closed curve in // space. The represented curve has infinite continuiity because the // parametric coordinate of its points are computed from a Fourier Series. // // In this example we illustrate how a curve that is initially defined by a // set of points in space can be represented in terms for Fourier Descriptors. // This representation is useful for several purposes. For example, it // provides a mechanmism for interpolating values among the points, it // provides a way of analyzing the smoothness of the curve. In this particular // example we will focus on this second application of the Fourier Descriptors. // // The first operation that we should use in this context is the computation // of the discrete fourier transform of the point coordinates. The coordinates // of the points are considered to be independent functions and each one is // decomposed in a Fourier Series. In this section we will use $t$ as the // parameter of the curve, and will assume that it goes from $0$ to $1$ and // cycles as we go around the closed curve. // // \begin{equation} // \textbf{V(t)} = \left( X(t), Y(t) \rigth) // \end{equation} // // We take now the functions $X(t)$, $Y(t)$ and interpret them as the // components of a complex number for wich we compute its discrete fourier // series in the form // // \begin{equation} // V(t) = \sum_{k=0}^{N} \exp(-\frac{2 k \pi \textbf{i}}{N}) F_k // \end{equation} // // Where the set of coefficients $F_k$ is the discrete spectrum of the complex // function $V(t)$. These coefficients are in general complex numbers and both // their magnitude and phase must be considered in any further analysis of the // spectrum. // // Software Guide : EndLatex // Software Guide : BeginLatex // // The class \code{vnl_fft_1D} is the VNL class that computes such transform. // In order to use it, we should include its header file first. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "vnl/algo/vnl_fft_1d.h" // Software Guide : EndCodeSnippet #include "itkPoint.h" #include "itkVectorContainer.h" #include <fstream> int main(int argc, char * argv[] ) { if( argc < 2 ) { std::cerr << "Missing arguments" << std::endl; std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << "inputFileWithPointCoordinates" << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // We should now instantiate the filter that will compute the Fourier // transform of the set of coordinates. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef vnl_fft_1d< double > FFTCalculator; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The points representing the curve are stored in a // \doxygen{VectorContainer} of \doxygen{Point}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::Point< double, 2 > PointType; typedef itk::VectorContainer< unsigned int, PointType > PointsContainer; PointsContainer::Pointer points = PointsContainer::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // In this example we read the set of points from a text file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::ifstream inputFile; inputFile.open( argv[1] ); if( inputFile.fail() ) { std::cerr << "Problems opening file " << argv[1] << std::endl; } unsigned int numberOfPoints; inputFile >> numberOfPoints; points->Reserve( numberOfPoints ); typedef PointsContainer::Iterator PointIterator; PointIterator pointItr = points->Begin(); PointType point; for( unsigned int pt=0; pt<numberOfPoints; pt++) { inputFile >> point[0] >> point[1]; pointItr.Value() = point; ++pointItr; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // This class will compute the Fast Fourier transform of the input an it will // return it in the same array. We must therefore copy the original data into // an auxiliary array that will in its turn contain the results of the // transform. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef vcl_complex<double> FFTCoefficientType; typedef vcl_vector< FFTCoefficientType > FFTSpectrumType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The choice of the spectrum size is very important. Here we select to use // the next power of two that is larger than the number of points. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const unsigned int powerOfTwo = (unsigned int)vcl_ceil( vcl_log( (double)(numberOfPoints)) / vcl_log( (double)(2.0)) ); const unsigned int spectrumSize = 1 << powerOfTwo; // Software Guide : BeginLatex // // The Fourier Transform type can now be used for constructing one of such // filters. Note that this is a VNL class and does not follows ITK notation // for construction and assignment to SmartPointers. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet FFTCalculator fftCalculator( spectrumSize ); // Software Guide : EndCodeSnippet FFTSpectrumType signal( spectrumSize ); pointItr = points->Begin(); for(unsigned int p=0; p<numberOfPoints; p++) { signal[p] = FFTCoefficientType( pointItr.Value()[0], pointItr.Value()[1] ); ++pointItr; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Fill in the rest of the input with zeros. This padding may have // undesirable effects on the spectrum if the signal is not attenuated to // zero close to their boundaries. Instead of zero-padding we could have used // repetition of the last value or mirroring of the signal. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet for(unsigned int pad=numberOfPoints; pad<spectrumSize; pad++) { signal[pad] = 0.0; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now we print out the signal as it is passed to the transform calculator // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::cout << "Input to the FFT transform" << std::endl; for(unsigned int s=0; s<spectrumSize; s++) { std::cout << s << " : "; std::cout << signal[s] << std::endl; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The actual transform is computed by invoking the \code{fwd_transform} // method in the FFT calculator class. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet fftCalculator.fwd_transform( signal ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now we print out the results of the transform. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::cout << std::endl; std::cout << "Result from the FFT transform" << std::endl; for(unsigned int k=0; k<spectrumSize; k++) { const double real = signal[k].real(); const double imag = signal[k].imag(); const double magnitude = vcl_sqrt( real * real + imag * imag ); std::cout << k << " " << magnitude << std::endl; } // Software Guide : EndCodeSnippet return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "helpers.hpp" #include <compress.hpp> #include <vector> #include <list> #include <string> #include <vector> #include <iterator> #include <utility> #include "catch.hpp" using iter::compress; using itertest::SolidInt; using itertest::BasicIterable; using Vec = const std::vector<int>; TEST_CASE("compress: alternating", "[compress]") { std::vector<int> ivec{1, 2, 3, 4, 5, 6}; std::vector<bool> bvec{true, false, true, false, true, false}; auto c = compress(ivec, bvec); Vec v(std::begin(c), std::end(c)); Vec vc = {1,3,5}; REQUIRE( v == vc ); } TEST_CASE("compress: consecutive falses", "[compress]") { std::vector<int> ivec{1, 2, 3, 4, 5}; std::vector<bool> bvec{true, false, false, false, true}; auto c = compress(ivec, bvec); Vec v(std::begin(c), std::end(c)); Vec vc = {1,5}; REQUIRE( v == vc ); } TEST_CASE("compress: consecutive trues", "[compress]") { std::vector<int> ivec{1, 2, 3, 4, 5}; std::vector<bool> bvec{false, true, true, true, false}; auto c = compress(ivec, bvec); Vec v(std::begin(c), std::end(c)); Vec vc = {2,3,4}; REQUIRE( v == vc ); } TEST_CASE("compress: all true", "[compress]") { std::vector<int> ivec{1, 2, 3, 4, 5}; std::vector<bool> bvec(ivec.size(), true); auto c = compress(ivec, bvec); Vec v(std::begin(c), std::end(c)); REQUIRE( v == ivec ); } TEST_CASE("compress: all false", "[compress]") { std::vector<int> ivec{1, 2, 3, 4, 5}; std::vector<bool> bvec(ivec.size(), false); auto c = compress(ivec, bvec); REQUIRE( std::begin(c) == std::end(c) ); } TEST_CASE("compress: binds to lvalues, moves rvalues", "[compress]") { BasicIterable<char> bi{'x', 'y', 'z'}; std::vector<bool> bl{true, true, true}; SECTION("binds to lvalues") { compress(bi, bl); REQUIRE_FALSE( bi.was_moved_from() ); } SECTION("moves rvalues") { compress(std::move(bi), bl); REQUIRE( bi.was_moved_from() ); } } struct BoolLike { public: bool state; explicit operator bool() const { return this->state; } }; TEST_CASE("compress: workds with truthy and falsey values", "[compress]") { std::vector<BoolLike> bvec{{true}, {false}, {true}, {false}}; Vec ivec{1,2,3,4}; auto c = compress(ivec, bvec); Vec v(std::begin(c), std::end(c)); Vec vc = {1,3}; REQUIRE( v == vc ); } TEST_CASE("compress: terminates on shorter selectors", "[compress]") { std::vector<int> ivec{1, 2, 3, 4, 5}; std::vector<bool> bvec{true}; auto c = compress(ivec, bvec); REQUIRE( std::distance(std::begin(c), std::end(c)) == 1 ); } TEST_CASE("compress: terminates on shorter data", "[compress]") { std::vector<int> ivec{1}; std::vector<bool> bvec{true, true, true, true, true}; auto c = compress(ivec, bvec); REQUIRE( std::distance(std::begin(c), std::end(c)) == 1 ); } <commit_msg>tests compress with empty selectors<commit_after>#include "helpers.hpp" #include <compress.hpp> #include <vector> #include <list> #include <string> #include <vector> #include <iterator> #include <utility> #include "catch.hpp" using iter::compress; using itertest::SolidInt; using itertest::BasicIterable; using Vec = const std::vector<int>; TEST_CASE("compress: alternating", "[compress]") { std::vector<int> ivec{1, 2, 3, 4, 5, 6}; std::vector<bool> bvec{true, false, true, false, true, false}; auto c = compress(ivec, bvec); Vec v(std::begin(c), std::end(c)); Vec vc = {1,3,5}; REQUIRE( v == vc ); } TEST_CASE("compress: consecutive falses", "[compress]") { std::vector<int> ivec{1, 2, 3, 4, 5}; std::vector<bool> bvec{true, false, false, false, true}; auto c = compress(ivec, bvec); Vec v(std::begin(c), std::end(c)); Vec vc = {1,5}; REQUIRE( v == vc ); } TEST_CASE("compress: consecutive trues", "[compress]") { std::vector<int> ivec{1, 2, 3, 4, 5}; std::vector<bool> bvec{false, true, true, true, false}; auto c = compress(ivec, bvec); Vec v(std::begin(c), std::end(c)); Vec vc = {2,3,4}; REQUIRE( v == vc ); } TEST_CASE("compress: all true", "[compress]") { std::vector<int> ivec{1, 2, 3, 4, 5}; std::vector<bool> bvec(ivec.size(), true); auto c = compress(ivec, bvec); Vec v(std::begin(c), std::end(c)); REQUIRE( v == ivec ); } TEST_CASE("compress: all false", "[compress]") { std::vector<int> ivec{1, 2, 3, 4, 5}; std::vector<bool> bvec(ivec.size(), false); auto c = compress(ivec, bvec); REQUIRE( std::begin(c) == std::end(c) ); } TEST_CASE("compress: binds to lvalues, moves rvalues", "[compress]") { BasicIterable<char> bi{'x', 'y', 'z'}; std::vector<bool> bl{true, true, true}; SECTION("binds to lvalues") { compress(bi, bl); REQUIRE_FALSE( bi.was_moved_from() ); } SECTION("moves rvalues") { compress(std::move(bi), bl); REQUIRE( bi.was_moved_from() ); } } struct BoolLike { public: bool state; explicit operator bool() const { return this->state; } }; TEST_CASE("compress: workds with truthy and falsey values", "[compress]") { std::vector<BoolLike> bvec{{true}, {false}, {true}, {false}}; Vec ivec{1,2,3,4}; auto c = compress(ivec, bvec); Vec v(std::begin(c), std::end(c)); Vec vc = {1,3}; REQUIRE( v == vc ); } TEST_CASE("compress: terminates on shorter selectors", "[compress]") { std::vector<int> ivec{1, 2, 3, 4, 5}; std::vector<bool> bvec{true}; auto c = compress(ivec, bvec); REQUIRE( std::distance(std::begin(c), std::end(c)) == 1 ); } TEST_CASE("compress: terminates on shorter data", "[compress]") { std::vector<int> ivec{1}; std::vector<bool> bvec{true, true, true, true, true}; auto c = compress(ivec, bvec); REQUIRE( std::distance(std::begin(c), std::end(c)) == 1 ); } TEST_CASE("compress: nothing on empty selectors", "[compress]") { std::vector<int> ivec{1,2,3}; std::vector<bool> bvec{}; auto c = compress(ivec, bvec); REQUIRE( std::begin(c) == std::end(c) ); } <|endoftext|>
<commit_before>#ifneq(,) // in var: sParam: rstStruct.param1 // in var: sParamName: param1 // in var: sdoParam: rdoParam || rdoParam.CreateChild("$($sParam)") #ifeqend \ \ \ #var elementForm $(Interface.Options.*elementFormDefault) #var attributeForm $(Interface.Options.*attributeFormDefault) \ #ifeq($(.Name),Nillable||Optional) #var recreateChild false #else #ifeq($(.Type),generic||string) #var recreateChild false #else #var recreateChild $($sdoParam.!match/.CreateChild/) #ifeqend \ \ #ifneq($(.Options.*form),) #ifeq($(.Options.*isAttribute),true||1) #var attributeForm $(.Options.form) #else #var elementForm $(.Options.form) #ifeqend #ifeqend #ifeq($(.Options.*isRef),true||1) #var elementForm qualified #ifeqend \ #ifeqend // Nillable||Optional \ #ifeq($($recreateChild),true) #var doName tdoParam$($sParamName) staff::DataObject $($doName) = $($sdoParam); #else #var doName $($sdoParam) #ifeqend \ \ #ifeq($(.Name),Optional||Nillable) // ######### Optional or Nillable ############ if (!($($sOptMod)$($sParam)).IsNull()) // $(.Name) { #cgpushvars #var sOptMod $($sOptMod)* #indent + #context $(.TemplateParams.TemplateParam1) #cginclude "TypeSerialization.cpp" #contextend #indent - #cgpopvars } #ifeq($(.Name),Nillable) // */ else { $($doName).SetNil(); } #ifeqend #else // not optional or nillable \ #ifeq($($elementForm),qualified) #ifneq($(.Type),generic||string) #var elPath $($ThisElementPath) #ifneq($($elPath.!match/.Class./),true) // don't set namespace for request element #ifneq($(.Options.*targetNamespace||Interface.Options.*targetNamespace),) $($doName).SetNamespaceUriGenPrefix("$(.Options.*targetNamespace||Interface.Options.*targetNamespace)"); #ifeqend #ifeqend #ifeqend #ifeqend \ \ #ifeq($(.Name),Abstract) // ########## abstract ################# #ifeq($(.Options.*isAttribute),true||1) // attribute #cgerror Can't serialize abstract member $($sParam) into attribute. #ifeqend #ifneq($(.TemplateParams.TemplateParam1.Type),struct) #cgerror Abstract template type is not struct. Member $($sParam) #ifeqend $($doName) << $($sOptMod)$($sParam); #else // ######### not abstract ##################### \ #ifeq($(.Options.*isAttribute),true||1) // serialize to attribute \ #ifeq($($attributeForm),qualified) std::string sPrefix$($sParamName); $($doName).SetNamespaceUriGenPrefix("$(.Options.*targetNamespace||Interface.Options.*targetNamespace)", &sPrefix$($sParamName), false); #var sAttrPrefix sPrefix$($sParamName) + ": \ #else #var sAttrPrefix " #ifeqend \ #ifeq($(.Type),generic||string||typedef) $($doName).CreateAttribute($($sAttrPrefix)$(.Options.*elementName||$sParamName)", $($sOptMod)$($sParam)); #else #ifeq($(.Type),enum) $($doName).CreateAttribute($($sAttrPrefix)$(.Options.*elementName||$sParamName)", \ ::staff::SerializeEnum_$(.NsName.!mangle)_ToString($($sOptMod)$($sParam))$($attrFormDecl)); #else #cgerror Cannot serialize type $(.Type) to attribute value. $($sParamName) #ifeqend #ifeqend \ #else // ############ common serialization ########## \ \ #ifeq($(.Type),generic||string) // ==== generic, anyAttribute ==== #ifeq($(.Name),anyAttribute) for (anyAttribute::const_iterator itAttr = ($($sOptMod)$($sParam)).begin(), itAttrEnd = ($($sOptMod)$($sParam)).end(); itAttr != itAttrEnd; ++itAttr) { $($doName).AppendAttribute(const_cast<Attribute&>(*itAttr)); } #else #ifeq($($sdoParam.!match/.CreateChild/),true) #ifeq($($elementForm),qualified) #var doName tdoParam$($sParamName) $($sdoParam.!depostfix/\)/), $($sOptMod)$($sParam)).SetNamespaceUriGenPrefix("$(.Options.*targetNamespace||Interface.Options.*targetNamespace)"); #else $($sdoParam.!depostfix/\)/), $($sOptMod)$($sParam)); #ifeqend #else #ifeq($($elementForm),qualified) $($doName).SetNamespaceUriGenPrefix("$(.Options.*targetNamespace||Interface.Options.*targetNamespace)"); #ifeqend // form $($doName).SetValue($($sOptMod)$($sParam)); #ifeqend // param optimization #ifeqend // anyAttribute #else \ \ #ifeq($(.Type),dataobject) // ==== dataobject ==== $($doName).AppendChild($($sOptMod)$($sParam)); #else \ \ #ifeq($(.Type),typedef) SerializeTypedef_$(.NsName.!mangle)($($doName), $($sOptMod)$($sParam)); #else \ \ #ifeq($(.Type),struct||enum) // ==== enum, struct ==== $($doName) << $($sOptMod)$($sParam); #else \ \ #ifeq($(.Namespace)$(.Name),staff::Array) // ### soapArray ### #cginclude "ArraySerialization.cpp" #else \ #ifeq($(.Type),template) // ==== template ==== for ($(.NsName)::const_iterator itItem$($nItemLevel) = ($($sOptMod)$($sParam)).begin(),\ itItem$($nItemLevel)End = ($($sOptMod)$($sParam)).end(); itItem$($nItemLevel) != itItem$($nItemLevel)End; ++itItem$($nItemLevel)) { #var sItemName $(.Options.*itemName||"Item") #ifeq($(.Name),map||multimap) // ==== map ==== #ifeq($($bUseParentElement),true||1) #var sdoItem $($doName) #else #var sdoItem tdoItem staff::DataObject $($sdoItem) = $($doName).CreateChild("$($sItemName)"); #ifeqend \ #indent + #context $(.TemplateParams.TemplateParam1) #cgpushvars #var nItemLevelPrev $($nItemLevel) #var nItemLevel $($nItemLevel.!inc.!trunc) #var bUseParentElement #var sOptMod #var sParam itItem$($nItemLevelPrev)->first #var sParamName Item #var sdoParam $($sdoItem).CreateChild("Key") #cginclude "TypeSerialization.cpp" #cgpopvars #contextend #indent - \ #indent + #context $(.TemplateParams.TemplateParam2) #cgpushvars #var nItemLevelPrev $($nItemLevel) #var nItemLevel $($nItemLevel.!inc.!trunc) #var bUseParentElement #var sOptMod #var sParam itItem$($nItemLevelPrev)->second #var sParamName Item #var sdoParam $($sdoItem).CreateChild("Value") #cginclude "TypeSerialization.cpp" #cgpopvars #contextend #indent - #else \ #ifeq($(.Name),list||vector) // ==== list ==== #indent + #context $(.TemplateParams.TemplateParam1) #cgpushvars #var nItemLevelPrev $($nItemLevel) #var nItemLevel $($nItemLevel.!inc.!trunc) #var sOptMod #var sParam (*itItem$($nItemLevelPrev)) #var sParamName Item #ifeq($($bUseParentElement),true||1) #var sdoItem $($doName) #else #var sdoParam $($doName).CreateChild("$($sItemName)") #ifeqend #var bUseParentElement #cginclude "TypeSerialization.cpp" #cgpopvars #contextend #indent - #else #cgerror template type $(.NsName) is not supported #ifeqend #ifeqend } #else #cgerror unknown type($(.Type)) of sParamName: $(Struct.NsName)::$(.Name) #ifeqend #ifeqend #ifeqend #ifeqend #ifeqend #ifeqend #ifeqend // abstract #ifeqend // attribute #ifeqend // optional or nillable <commit_msg>codegen: fixed serializing of sub-containers<commit_after>#ifneq(,) // in var: sParam: rstStruct.param1 // in var: sParamName: param1 // in var: sdoParam: rdoParam || rdoParam.CreateChild("$($sParam)") #ifeqend \ \ \ #var elementForm $(Interface.Options.*elementFormDefault) #var attributeForm $(Interface.Options.*attributeFormDefault) \ #ifeq($(.Name),Nillable||Optional) #var recreateChild false #else #ifeq($(.Type),generic||string) #var recreateChild false #else #var recreateChild $($sdoParam.!match/.CreateChild/) #ifeqend \ \ #ifneq($(.Options.*form),) #ifeq($(.Options.*isAttribute),true||1) #var attributeForm $(.Options.form) #else #var elementForm $(.Options.form) #ifeqend #ifeqend #ifeq($(.Options.*isRef),true||1) #var elementForm qualified #ifeqend \ #ifeqend // Nillable||Optional \ #ifeq($($recreateChild),true) #var doName tdoParam$($sParamName)$($nItemLevel) staff::DataObject $($doName) = $($sdoParam); #else #var doName $($sdoParam) #ifeqend \ \ #ifeq($(.Name),Optional||Nillable) // ######### Optional or Nillable ############ if (!($($sOptMod)$($sParam)).IsNull()) // $(.Name) { #cgpushvars #var sOptMod $($sOptMod)* #indent + #context $(.TemplateParams.TemplateParam1) #cginclude "TypeSerialization.cpp" #contextend #indent - #cgpopvars } #ifeq($(.Name),Nillable) // */ else { $($doName).SetNil(); } #ifeqend #else // not optional or nillable \ #ifeq($($elementForm),qualified) #ifneq($(.Type),generic||string) #var elPath $($ThisElementPath) #ifneq($($elPath.!match/.Class./),true) // don't set namespace for request element #ifneq($(.Options.*targetNamespace||Interface.Options.*targetNamespace),) $($doName).SetNamespaceUriGenPrefix("$(.Options.*targetNamespace||Interface.Options.*targetNamespace)"); #ifeqend #ifeqend #ifeqend #ifeqend \ \ #ifeq($(.Name),Abstract) // ########## abstract ################# #ifeq($(.Options.*isAttribute),true||1) // attribute #cgerror Can't serialize abstract member $($sParam) into attribute. #ifeqend #ifneq($(.TemplateParams.TemplateParam1.Type),struct) #cgerror Abstract template type is not struct. Member $($sParam) #ifeqend $($doName) << $($sOptMod)$($sParam); #else // ######### not abstract ##################### \ #ifeq($(.Options.*isAttribute),true||1) // serialize to attribute \ #ifeq($($attributeForm),qualified) std::string sPrefix$($sParamName); $($doName).SetNamespaceUriGenPrefix("$(.Options.*targetNamespace||Interface.Options.*targetNamespace)", &sPrefix$($sParamName), false); #var sAttrPrefix sPrefix$($sParamName) + ": \ #else #var sAttrPrefix " #ifeqend \ #ifeq($(.Type),generic||string||typedef) $($doName).CreateAttribute($($sAttrPrefix)$(.Options.*elementName||$sParamName)", $($sOptMod)$($sParam)); #else #ifeq($(.Type),enum) $($doName).CreateAttribute($($sAttrPrefix)$(.Options.*elementName||$sParamName)", \ ::staff::SerializeEnum_$(.NsName.!mangle)_ToString($($sOptMod)$($sParam))$($attrFormDecl)); #else #cgerror Cannot serialize type $(.Type) to attribute value. $($sParamName) #ifeqend #ifeqend \ #else // ############ common serialization ########## \ \ #ifeq($(.Type),generic||string) // ==== generic, anyAttribute ==== #ifeq($(.Name),anyAttribute) for (anyAttribute::const_iterator itAttr = ($($sOptMod)$($sParam)).begin(), itAttrEnd = ($($sOptMod)$($sParam)).end(); itAttr != itAttrEnd; ++itAttr) { $($doName).AppendAttribute(const_cast<Attribute&>(*itAttr)); } #else #ifeq($($sdoParam.!match/.CreateChild/),true) #ifeq($($elementForm),qualified) #var doName tdoParam$($sParamName)$($nItemLevel) $($sdoParam.!depostfix/\)/), $($sOptMod)$($sParam)).SetNamespaceUriGenPrefix("$(.Options.*targetNamespace||Interface.Options.*targetNamespace)"); #else $($sdoParam.!depostfix/\)/), $($sOptMod)$($sParam)); #ifeqend #else #ifeq($($elementForm),qualified) $($doName).SetNamespaceUriGenPrefix("$(.Options.*targetNamespace||Interface.Options.*targetNamespace)"); #ifeqend // form $($doName).SetValue($($sOptMod)$($sParam)); #ifeqend // param optimization #ifeqend // anyAttribute #else \ \ #ifeq($(.Type),dataobject) // ==== dataobject ==== $($doName).AppendChild($($sOptMod)$($sParam)); #else \ \ #ifeq($(.Type),typedef) SerializeTypedef_$(.NsName.!mangle)($($doName), $($sOptMod)$($sParam)); #else \ \ #ifeq($(.Type),struct||enum) // ==== enum, struct ==== $($doName) << $($sOptMod)$($sParam); #else \ \ #ifeq($(.Namespace)$(.Name),staff::Array) // ### soapArray ### #cginclude "ArraySerialization.cpp" #else \ #ifeq($(.Type),template) // ==== template ==== for ($(.NsName)::const_iterator itItem$($nItemLevel) = ($($sOptMod)$($sParam)).begin(),\ itItem$($nItemLevel)End = ($($sOptMod)$($sParam)).end(); itItem$($nItemLevel) != itItem$($nItemLevel)End; ++itItem$($nItemLevel)) { #var sItemName $(.Options.*itemName||"Item") #ifeq($(.Name),map||multimap) // ==== map ==== #ifeq($($bUseParentElement),true||1) #var sdoItem $($doName) #else #var sdoItem tdoItem staff::DataObject $($sdoItem) = $($doName).CreateChild("$($sItemName)"); #ifeqend \ #indent + #context $(.TemplateParams.TemplateParam1) #cgpushvars #var nItemLevelPrev $($nItemLevel) #var nItemLevel $($nItemLevel.!inc.!trunc) #var bUseParentElement #var sOptMod #var sParam itItem$($nItemLevelPrev)->first #var sParamName Item #var sdoParam $($sdoItem).CreateChild("Key") #cginclude "TypeSerialization.cpp" #cgpopvars #contextend #indent - \ #indent + #context $(.TemplateParams.TemplateParam2) #cgpushvars #var nItemLevelPrev $($nItemLevel) #var nItemLevel $($nItemLevel.!inc.!trunc) #var bUseParentElement #var sOptMod #var sParam itItem$($nItemLevelPrev)->second #var sParamName Item #var sdoParam $($sdoItem).CreateChild("Value") #cginclude "TypeSerialization.cpp" #cgpopvars #contextend #indent - #else \ #ifeq($(.Name),list||vector) // ==== list ==== #indent + #context $(.TemplateParams.TemplateParam1) #cgpushvars #var nItemLevelPrev $($nItemLevel) #var nItemLevel $($nItemLevel.!inc.!trunc) #var sOptMod #var sParam (*itItem$($nItemLevelPrev)) #var sParamName Item #ifeq($($bUseParentElement),true||1) #var sdoItem $($doName) #else #var sdoParam $($doName).CreateChild("$($sItemName)") #ifeqend #var bUseParentElement #cginclude "TypeSerialization.cpp" #cgpopvars #contextend #indent - #else #cgerror template type $(.NsName) is not supported #ifeqend #ifeqend } #else #cgerror unknown type($(.Type)) of sParamName: $(Struct.NsName)::$(.Name) #ifeqend #ifeqend #ifeqend #ifeqend #ifeqend #ifeqend #ifeqend // abstract #ifeqend // attribute #ifeqend // optional or nillable <|endoftext|>
<commit_before>/* Copyright 2017 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 "python_api.h" #include "c_api_internal.h" namespace tensorflow { void UpdateEdge(TF_Graph* graph, TF_Output new_src, TF_Input dst, TF_Status* status) { mutex_lock l(graph->mu); status->status = graph->graph.UpdateEdge(&new_src.oper->node, new_src.index, &dst.oper->node, dst.index); } void AddControlInput(TF_Graph* graph, TF_Operation* op, TF_Operation* input) { mutex_lock l(graph->mu); graph->graph.AddControlEdge(&input->node, &op->node); } void ClearControlInputs(TF_Graph* graph, TF_Operation* op) { mutex_lock l(graph->mu); for (const auto* edge : op->node.in_edges()) { if (edge->IsControlEdge()) { graph->graph.RemoveControlEdge(edge); } } } void SetRequestedDevice(TF_Graph* graph, TF_Operation* op, const char* device) { mutex_lock l(graph->mu); op->node.set_requested_device(device); } } // namespace tensorflow <commit_msg>Updated the Python API C++ file.<commit_after>/* Copyright 2017 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 "python_api.h" #include "c_api_internal.h" namespace tensorflow { void UpdateEdge(TF_Graph* graph, TF_Output new_src, TF_Input dst, TF_Status* status) { mutex_lock l(graph->mu); tensorflow::shape_inference::InferenceContext* ic = graph->refiner.GetContext(&new_src.oper->node); if (ic->num_outputs() <= new_src.index) { status->status = tensorflow::errors::OutOfRange( "Cannot update edge. Output index [", new_src.index, "] is greater than the number of total outputs [", ic->num_outputs(), "]."); return; } tensorflow::shape_inference::ShapeHandle shape = ic->output(new_src.index); tensorflow::shape_inference::InferenceContext* ic_dst = graph->refiner.GetContext(&dst.oper->node); if (ic_dst->num_inputs() <= dst.index) { status->status = tensorflow::errors::OutOfRange( "Cannot update edge. Input index [", dst.index, "] is greater than the number of total inputs [", ic_dst->num_inputs(), "]."); return; } if (!ic_dst->MergeInput(dst.index, shape)) { status->status = tensorflow::errors::InvalidArgument( "Cannot update edge, incompatible shapes: ", ic_dst->DebugString(shape), " and ", ic_dst->DebugString(ic_dst->input(dst.index)), "."); return; } status->status = graph->graph.UpdateEdge(&new_src.oper->node, new_src.index, &dst.oper->node, dst.index); } void AddControlInput(TF_Graph* graph, TF_Operation* op, TF_Operation* input) { mutex_lock l(graph->mu); graph->graph.AddControlEdge(&input->node, &op->node); } void ClearControlInputs(TF_Graph* graph, TF_Operation* op) { mutex_lock l(graph->mu); for (const auto* edge : op->node.in_edges()) { if (edge->IsControlEdge()) { graph->graph.RemoveControlEdge(edge); } } } void SetRequestedDevice(TF_Graph* graph, TF_Operation* op, const char* device) { mutex_lock l(graph->mu); op->node.set_requested_device(device); } } // namespace tensorflow <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File: ConstantExpression.hpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: // /////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_CONSTANT_EXPRESSION_HPP #define NEKTAR_LIB_UTILITIES_CONSTANT_EXPRESSION_HPP #ifdef NEKTAR_USE_EXPRESSION_TEMPLATES #include <boost/call_traits.hpp> #include <LibUtilities/ExpressionTemplates/ExpressionReturnType.hpp> #include <LibUtilities/ExpressionTemplates/Expression.hpp> #include <LibUtilities/ExpressionTemplates/ExpressionMetadata.hpp> #include <LibUtilities/ExpressionTemplates/Accumulator.hpp> #include <LibUtilities/ExpressionTemplates/ConstantExpressionTraits.hpp> #include <LibUtilities/ExpressionTemplates/NullOp.hpp> #include <LibUtilities/BasicUtils/ErrorUtil.hpp> namespace Nektar { template<typename Type> class ConstantExpressionPolicy { public: typedef Type ResultType; typedef typename boost::call_traits<Type>::const_reference DataType; typedef ConstantNullOp NullOp; typedef typename ConstantExpressionTraits<Type>::MetadataType MetadataType; public: static void InitializeMetadata(typename boost::call_traits<DataType>::const_reference data, MetadataType& m) { m = MetadataType(data); } static void Evaluate(Accumulator<ResultType>& accum, typename boost::call_traits<DataType>::const_reference d) { *accum = d; } template<template <typename, typename> class ParentOpType> static void Evaluate(Accumulator<ResultType>& accum, typename boost::call_traits<DataType>::const_reference d) { ParentOpType<ResultType, DataType>::ApplyEqual(accum, d); } template<typename CheckType> static typename boost::enable_if<boost::is_same<CheckType, Type>, bool>::type ContainsReference(const CheckType& result, DataType m_data) { return &result == &m_data; } template<typename CheckType> static typename boost::disable_if<boost::is_same<CheckType, Type>, bool>::type ContainsReference(const CheckType& result, DataType m_data) { return false; } static void Print(std::ostream& os, typename boost::call_traits<DataType>::const_reference data) { os << data; } }; template<typename DataType> Expression<ConstantExpressionPolicy<DataType> > MakeExpr(const DataType& rhs) { return Expression<ConstantExpressionPolicy<DataType> >(rhs); } template<typename T> struct IsConstantExpressionPolicy : public boost::false_type {}; template<typename T> struct IsConstantExpressionPolicy<ConstantExpressionPolicy<T> > : public boost::true_type {}; } #endif //NEKTAR_USE_EXPRESSION_TEMPLATES #endif // NEKTAR_LIB_UTILITIES_CONSTANT_EXPRESSION_HPP /** $Log: ConstantExpression.hpp,v $ Revision 1.15 2008/01/03 04:16:41 bnelson Changed method name in the expression library from Apply to Evaluate. Revision 1.14 2008/01/02 20:11:22 bnelson Fixed error detecting if incoming type was the same as the constant expression's type when looking for aliasing. Revision 1.13 2008/01/02 18:20:12 bnelson *** empty log message *** Revision 1.12 2007/12/19 05:09:21 bnelson First pass at detecting aliasing. Still need to test performance implications. Revision 1.11 2007/11/13 18:05:27 bnelson Added MakeExpr helper function. Revision 1.10 2007/10/04 03:48:54 bnelson *** empty log message *** Revision 1.9 2007/08/16 02:14:21 bnelson Moved expression templates to the Nektar namespace. Revision 1.8 2007/01/30 23:37:16 bnelson *** empty log message *** Revision 1.7 2007/01/16 17:37:55 bnelson Wrapped everything with #ifdef NEKTAR_USE_EXPRESSION_TEMPLATES Revision 1.6 2007/01/16 05:29:50 bnelson Major improvements for expression templates. Revision 1.5 2006/09/14 02:08:59 bnelson Fixed gcc compile errors Revision 1.4 2006/09/11 03:24:24 bnelson Updated expression templates so they are all specializations of an Expression object, using policies to differentiate. Revision 1.3 2006/08/28 02:39:53 bnelson *** empty log message *** Revision 1.2 2006/08/25 01:33:47 bnelson no message Revision 1.1 2006/06/01 09:20:55 kirby *** empty log message *** Revision 1.1 2006/05/04 18:57:41 kirby *** empty log message *** Revision 1.2 2006/01/31 13:51:12 bnelson Updated for new configure. Revision 1.1 2006/01/10 14:50:30 bnelson Initial Revision. **/ <commit_msg>Alias checks now look at the actual array held by vectors and matrices.<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File: ConstantExpression.hpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: // /////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_CONSTANT_EXPRESSION_HPP #define NEKTAR_LIB_UTILITIES_CONSTANT_EXPRESSION_HPP #ifdef NEKTAR_USE_EXPRESSION_TEMPLATES #include <boost/call_traits.hpp> #include <LibUtilities/ExpressionTemplates/ExpressionReturnType.hpp> #include <LibUtilities/ExpressionTemplates/Expression.hpp> #include <LibUtilities/ExpressionTemplates/ExpressionMetadata.hpp> #include <LibUtilities/ExpressionTemplates/Accumulator.hpp> #include <LibUtilities/ExpressionTemplates/ConstantExpressionTraits.hpp> #include <LibUtilities/ExpressionTemplates/NullOp.hpp> #include <LibUtilities/BasicUtils/ErrorUtil.hpp> #include <LibUtilities/LinearAlgebra/NekVectorFwd.hpp> #include <LibUtilities/LinearAlgebra/NekMatrixFwd.hpp> namespace Nektar { template<typename Type> class ConstantExpressionPolicy { public: typedef Type ResultType; typedef typename boost::call_traits<Type>::const_reference DataType; typedef ConstantNullOp NullOp; typedef typename ConstantExpressionTraits<Type>::MetadataType MetadataType; public: static void InitializeMetadata(typename boost::call_traits<DataType>::const_reference data, MetadataType& m) { m = MetadataType(data); } static void Evaluate(Accumulator<ResultType>& accum, typename boost::call_traits<DataType>::const_reference d) { *accum = d; } template<template <typename, typename> class ParentOpType> static void Evaluate(Accumulator<ResultType>& accum, typename boost::call_traits<DataType>::const_reference d) { ParentOpType<ResultType, DataType>::ApplyEqual(accum, d); } template<typename CheckType> static typename boost::enable_if < boost::mpl::and_ < boost::is_same<CheckType, Type>, boost::mpl::or_ < IsVector<typename boost::remove_cv<CheckType>::type>, IsMatrix<typename boost::remove_cv<CheckType>::type> > >, bool>::type ContainsReference(const CheckType& result, DataType m_data) { return result.GetPtr().data() == m_data.GetPtr().data(); } template<typename CheckType> static typename boost::enable_if < boost::mpl::and_ < boost::is_same<CheckType, Type>, boost::mpl::and_ < boost::mpl::not_<IsVector<typename boost::remove_cv<CheckType>::type> >, boost::mpl::not_<IsMatrix<typename boost::remove_cv<CheckType>::type> > > >, bool>::type ContainsReference(const CheckType& result, DataType m_data) { return &result == &m_data; } template<typename CheckType> static typename boost::disable_if<boost::is_same<CheckType, Type>, bool>::type ContainsReference(const CheckType& result, DataType m_data) { return false; } static void Print(std::ostream& os, typename boost::call_traits<DataType>::const_reference data) { os << data; } }; template<typename DataType> Expression<ConstantExpressionPolicy<DataType> > MakeExpr(const DataType& rhs) { return Expression<ConstantExpressionPolicy<DataType> >(rhs); } template<typename T> struct IsConstantExpressionPolicy : public boost::false_type {}; template<typename T> struct IsConstantExpressionPolicy<ConstantExpressionPolicy<T> > : public boost::true_type {}; } #endif //NEKTAR_USE_EXPRESSION_TEMPLATES #endif // NEKTAR_LIB_UTILITIES_CONSTANT_EXPRESSION_HPP /** $Log: ConstantExpression.hpp,v $ Revision 1.16 2008/01/20 04:01:05 bnelson Expression template updates. Revision 1.15 2008/01/03 04:16:41 bnelson Changed method name in the expression library from Apply to Evaluate. Revision 1.14 2008/01/02 20:11:22 bnelson Fixed error detecting if incoming type was the same as the constant expression's type when looking for aliasing. Revision 1.13 2008/01/02 18:20:12 bnelson *** empty log message *** Revision 1.12 2007/12/19 05:09:21 bnelson First pass at detecting aliasing. Still need to test performance implications. Revision 1.11 2007/11/13 18:05:27 bnelson Added MakeExpr helper function. Revision 1.10 2007/10/04 03:48:54 bnelson *** empty log message *** Revision 1.9 2007/08/16 02:14:21 bnelson Moved expression templates to the Nektar namespace. Revision 1.8 2007/01/30 23:37:16 bnelson *** empty log message *** Revision 1.7 2007/01/16 17:37:55 bnelson Wrapped everything with #ifdef NEKTAR_USE_EXPRESSION_TEMPLATES Revision 1.6 2007/01/16 05:29:50 bnelson Major improvements for expression templates. Revision 1.5 2006/09/14 02:08:59 bnelson Fixed gcc compile errors Revision 1.4 2006/09/11 03:24:24 bnelson Updated expression templates so they are all specializations of an Expression object, using policies to differentiate. Revision 1.3 2006/08/28 02:39:53 bnelson *** empty log message *** Revision 1.2 2006/08/25 01:33:47 bnelson no message Revision 1.1 2006/06/01 09:20:55 kirby *** empty log message *** Revision 1.1 2006/05/04 18:57:41 kirby *** empty log message *** Revision 1.2 2006/01/31 13:51:12 bnelson Updated for new configure. Revision 1.1 2006/01/10 14:50:30 bnelson Initial Revision. **/ <|endoftext|>
<commit_before>/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ #include <signal.h> #include <glog/logging.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <process/gmock.hpp> #include <process/gtest.hpp> #include <process/process.hpp> #include <stout/os/signals.hpp> int main(int argc, char** argv) { // Initialize Google Mock/Test. testing::InitGoogleMock(&argc, argv); // Initialize libprocess. process::initialize(); // Install GLOG's signal handler. google::InstallFailureSignalHandler(); // We reset the GLOG's signal handler for SIGTERM because // 'SubprocessTest.Status' sends SIGTERM to a subprocess which // results in a stack trace otherwise. os::signals::reset(SIGTERM); // Add the libprocess test event listeners. ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Append(process::ClockTestEventListener::instance()); listeners.Append(process::FilterTestEventListener::instance()); int result = RUN_ALL_TESTS(); process::finalize(); return result; } <commit_msg>Added a SIGPIPE handler for the libprocess tests.<commit_after>/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ #include <signal.h> #include <glog/logging.h> #include <glog/raw_logging.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <process/gmock.hpp> #include <process/gtest.hpp> #include <process/process.hpp> #include <stout/os/signals.hpp> // NOTE: We use RAW_LOG instead of LOG because RAW_LOG doesn't // allocate any memory or grab locks. And according to // https://code.google.com/p/google-glog/issues/detail?id=161 // it should work in 'most' cases in signal handlers. inline void handler(int signal) { if (signal == SIGPIPE) { RAW_LOG(WARNING, "Received signal SIGPIPE; escalating to SIGABRT"); raise(SIGABRT); } else { RAW_LOG(FATAL, "Unexpected signal in signal handler: %d", signal); } } int main(int argc, char** argv) { // Initialize Google Mock/Test. testing::InitGoogleMock(&argc, argv); // Initialize libprocess. process::initialize(); // Install GLOG's signal handler. google::InstallFailureSignalHandler(); // We reset the GLOG's signal handler for SIGTERM because // 'SubprocessTest.Status' sends SIGTERM to a subprocess which // results in a stack trace otherwise. os::signals::reset(SIGTERM); // Set up the SIGPIPE signal handler to escalate to SIGABRT // in order to have the glog handler catch it and print all // of its lovely information. os::signals::install(SIGPIPE, handler); // Add the libprocess test event listeners. ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Append(process::ClockTestEventListener::instance()); listeners.Append(process::FilterTestEventListener::instance()); int result = RUN_ALL_TESTS(); process::finalize(); return result; } <|endoftext|>
<commit_before>// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "subprocess.h" #include <assert.h> #include <stdio.h> #include <algorithm> #include "util.h" using namespace std; Subprocess::Subprocess(bool use_console) : child_(NULL) , overlapped_(), is_reading_(false), use_console_(use_console) { } Subprocess::~Subprocess() { if (pipe_) { if (!CloseHandle(pipe_)) Win32Fatal("CloseHandle"); } // Reap child if forgotten. if (child_) Finish(); } HANDLE Subprocess::SetupPipe(HANDLE ioport) { char pipe_name[100]; snprintf(pipe_name, sizeof(pipe_name), "\\\\.\\pipe\\ninja_pid%lu_sp%p", GetCurrentProcessId(), this); pipe_ = ::CreateNamedPipeA(pipe_name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, 0, 0, INFINITE, NULL); if (pipe_ == INVALID_HANDLE_VALUE) Win32Fatal("CreateNamedPipe"); if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0)) Win32Fatal("CreateIoCompletionPort"); memset(&overlapped_, 0, sizeof(overlapped_)); if (!ConnectNamedPipe(pipe_, &overlapped_) && GetLastError() != ERROR_IO_PENDING) { Win32Fatal("ConnectNamedPipe"); } // Get the write end of the pipe as a handle inheritable across processes. HANDLE output_write_handle = CreateFileA(pipe_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); HANDLE output_write_child; if (!DuplicateHandle(GetCurrentProcess(), output_write_handle, GetCurrentProcess(), &output_write_child, 0, TRUE, DUPLICATE_SAME_ACCESS)) { Win32Fatal("DuplicateHandle"); } CloseHandle(output_write_handle); return output_write_child; } bool Subprocess::Start(SubprocessSet* set, const string& command, const vector<string> & environment, bool useStderr) { HANDLE child_pipe = SetupPipe(set->ioport_); SECURITY_ATTRIBUTES security_attributes; memset(&security_attributes, 0, sizeof(SECURITY_ATTRIBUTES)); security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES); security_attributes.bInheritHandle = TRUE; // Must be inheritable so subprocesses can dup to children. HANDLE nul = CreateFileA("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &security_attributes, OPEN_EXISTING, 0, NULL); if (nul == INVALID_HANDLE_VALUE) Fatal("couldn't open nul"); STARTUPINFOA startup_info; memset(&startup_info, 0, sizeof(startup_info)); startup_info.cb = sizeof(STARTUPINFO); if (!use_console_) { startup_info.dwFlags = STARTF_USESTDHANDLES; startup_info.hStdInput = nul; startup_info.hStdOutput = child_pipe; startup_info.hStdError = useStderr ? child_pipe : nul; } // In the console case, child_pipe is still inherited by the child and closed // when the subprocess finishes, which then notifies ninja. PROCESS_INFORMATION process_info; memset(&process_info, 0, sizeof(process_info)); // Ninja handles ctrl-c, except for subprocesses in console pools. DWORD process_flags = use_console_ ? 0 : CREATE_NEW_PROCESS_GROUP; LPVOID lpEnvironment = nullptr; std::string envData; if (!environment.empty()) { for (const auto & keyValue : environment) envData += keyValue + std::string("\0", 1); envData += std::string("\0", 1); lpEnvironment = (void*)envData.c_str(); } // Do not prepend 'cmd /c' on Windows, this breaks command // lines greater than 8,191 chars. if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL, /* inherit handles */ TRUE, process_flags, lpEnvironment, NULL, &startup_info, &process_info)) { DWORD error = GetLastError(); if (error == ERROR_FILE_NOT_FOUND) { // File (program) not found error is treated as a normal build // action failure. if (child_pipe) CloseHandle(child_pipe); CloseHandle(pipe_); CloseHandle(nul); pipe_ = NULL; // child_ is already NULL; buf_ = "CreateProcess failed: The system cannot find the file " "specified.\n"; return true; } else { fprintf(stderr, "\nCreateProcess failed. Command attempted:\n\"%s\"\n", command.c_str()); const char* hint = NULL; // ERROR_INVALID_PARAMETER means the command line was formatted // incorrectly. This can be caused by a command line being too long or // leading whitespace in the command. Give extra context for this case. if (error == ERROR_INVALID_PARAMETER) { if (command.length() > 0 && (command[0] == ' ' || command[0] == '\t')) hint = "command contains leading whitespace"; else hint = "is the command line too long?"; } Win32Fatal("CreateProcess", hint); } } // Close pipe channel only used by the child. if (child_pipe) CloseHandle(child_pipe); CloseHandle(nul); CloseHandle(process_info.hThread); child_ = process_info.hProcess; return true; } void Subprocess::OnPipeReady() { DWORD bytes; if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } Win32Fatal("GetOverlappedResult"); } if (is_reading_ && bytes) buf_.append(overlapped_buf_, bytes); memset(&overlapped_, 0, sizeof(overlapped_)); is_reading_ = true; if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_), &bytes, &overlapped_)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } if (GetLastError() != ERROR_IO_PENDING) Win32Fatal("ReadFile"); } // Even if we read any bytes in the readfile call, we'll enter this // function again later and get them at that point. } ExitStatus Subprocess::Finish() { if (!child_) return ExitFailure; // TODO: add error handling for all of these. WaitForSingleObject(child_, INFINITE); DWORD exit_code = 0; GetExitCodeProcess(child_, &exit_code); CloseHandle(child_); child_ = NULL; return exit_code == 0 ? ExitSuccess : exit_code == CONTROL_C_EXIT ? ExitInterrupted : ExitFailure; } bool Subprocess::Done() const { return pipe_ == NULL; } const string& Subprocess::GetOutput() const { return buf_; } HANDLE SubprocessSet::ioport_; SubprocessSet::SubprocessSet(bool setupSignalHandlers) : setupSignalHandlers_(setupSignalHandlers) { ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1); if (!ioport_) Win32Fatal("CreateIoCompletionPort"); if (setupSignalHandlers_ && !SetConsoleCtrlHandler(NotifyInterrupted, TRUE)) Win32Fatal("SetConsoleCtrlHandler"); } SubprocessSet::~SubprocessSet() { Clear(); if (setupSignalHandlers_) SetConsoleCtrlHandler(NotifyInterrupted, FALSE); CloseHandle(ioport_); } BOOL WINAPI SubprocessSet::NotifyInterrupted(DWORD dwCtrlType) { if (dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT) { if (!PostQueuedCompletionStatus(ioport_, 0, 0, NULL)) Win32Fatal("PostQueuedCompletionStatus"); return TRUE; } return FALSE; } Subprocess *SubprocessSet::Add(const string& command, bool use_console, const vector<string> & environment, bool useStderr) { Subprocess *subprocess = new Subprocess(use_console); if (!subprocess->Start(this, command, environment, useStderr)) { delete subprocess; return 0; } if (subprocess->child_) running_.push_back(subprocess); else finished_.push(subprocess); return subprocess; } bool SubprocessSet::DoWork() { DWORD bytes_read; Subprocess* subproc; OVERLAPPED* overlapped; if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc, &overlapped, INFINITE)) { if (GetLastError() != ERROR_BROKEN_PIPE) Win32Fatal("GetQueuedCompletionStatus"); } if (!subproc) // A NULL subproc indicates that we were interrupted and is // delivered by NotifyInterrupted above. return true; subproc->OnPipeReady(); if (subproc->Done()) { vector<Subprocess*>::iterator end = remove(running_.begin(), running_.end(), subproc); if (running_.end() != end) { finished_.push(subproc); running_.resize(end - running_.begin()); } } return false; } Subprocess* SubprocessSet::NextFinished() { if (finished_.empty()) return NULL; Subprocess* subproc = finished_.front(); finished_.pop(); return subproc; } void SubprocessSet::Clear() { for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ++i) { // Since the foreground process is in our process group, it will receive a // CTRL_C_EVENT or CTRL_BREAK_EVENT at the same time as us. if ((*i)->child_ && !(*i)->use_console_) { if (!GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, GetProcessId((*i)->child_))) { Win32Fatal("GenerateConsoleCtrlEvent"); } } } for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ++i) delete *i; running_.clear(); } <commit_msg>HOTFIX: revert win32 part for useStderr param.<commit_after>// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "subprocess.h" #include <assert.h> #include <stdio.h> #include <algorithm> #include "util.h" using namespace std; Subprocess::Subprocess(bool use_console) : child_(NULL) , overlapped_(), is_reading_(false), use_console_(use_console) { } Subprocess::~Subprocess() { if (pipe_) { if (!CloseHandle(pipe_)) Win32Fatal("CloseHandle"); } // Reap child if forgotten. if (child_) Finish(); } HANDLE Subprocess::SetupPipe(HANDLE ioport) { char pipe_name[100]; snprintf(pipe_name, sizeof(pipe_name), "\\\\.\\pipe\\ninja_pid%lu_sp%p", GetCurrentProcessId(), this); pipe_ = ::CreateNamedPipeA(pipe_name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, 0, 0, INFINITE, NULL); if (pipe_ == INVALID_HANDLE_VALUE) Win32Fatal("CreateNamedPipe"); if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0)) Win32Fatal("CreateIoCompletionPort"); memset(&overlapped_, 0, sizeof(overlapped_)); if (!ConnectNamedPipe(pipe_, &overlapped_) && GetLastError() != ERROR_IO_PENDING) { Win32Fatal("ConnectNamedPipe"); } // Get the write end of the pipe as a handle inheritable across processes. HANDLE output_write_handle = CreateFileA(pipe_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); HANDLE output_write_child; if (!DuplicateHandle(GetCurrentProcess(), output_write_handle, GetCurrentProcess(), &output_write_child, 0, TRUE, DUPLICATE_SAME_ACCESS)) { Win32Fatal("DuplicateHandle"); } CloseHandle(output_write_handle); return output_write_child; } bool Subprocess::Start(SubprocessSet* set, const string& command, const vector<string> & environment, bool useStderr) { HANDLE child_pipe = SetupPipe(set->ioport_); SECURITY_ATTRIBUTES security_attributes; memset(&security_attributes, 0, sizeof(SECURITY_ATTRIBUTES)); security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES); security_attributes.bInheritHandle = TRUE; // Must be inheritable so subprocesses can dup to children. HANDLE nul = CreateFileA("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &security_attributes, OPEN_EXISTING, 0, NULL); if (nul == INVALID_HANDLE_VALUE) Fatal("couldn't open nul"); STARTUPINFOA startup_info; memset(&startup_info, 0, sizeof(startup_info)); startup_info.cb = sizeof(STARTUPINFO); if (!use_console_) { startup_info.dwFlags = STARTF_USESTDHANDLES; startup_info.hStdInput = nul; startup_info.hStdOutput = child_pipe; startup_info.hStdError = child_pipe; // TODO: utilize useStderr. } // In the console case, child_pipe is still inherited by the child and closed // when the subprocess finishes, which then notifies ninja. PROCESS_INFORMATION process_info; memset(&process_info, 0, sizeof(process_info)); // Ninja handles ctrl-c, except for subprocesses in console pools. DWORD process_flags = use_console_ ? 0 : CREATE_NEW_PROCESS_GROUP; LPVOID lpEnvironment = nullptr; std::string envData; if (!environment.empty()) { for (const auto & keyValue : environment) envData += keyValue + std::string("\0", 1); envData += std::string("\0", 1); lpEnvironment = (void*)envData.c_str(); } // Do not prepend 'cmd /c' on Windows, this breaks command // lines greater than 8,191 chars. if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL, /* inherit handles */ TRUE, process_flags, lpEnvironment, NULL, &startup_info, &process_info)) { DWORD error = GetLastError(); if (error == ERROR_FILE_NOT_FOUND) { // File (program) not found error is treated as a normal build // action failure. if (child_pipe) CloseHandle(child_pipe); CloseHandle(pipe_); CloseHandle(nul); pipe_ = NULL; // child_ is already NULL; buf_ = "CreateProcess failed: The system cannot find the file " "specified.\n"; return true; } else { fprintf(stderr, "\nCreateProcess failed. Command attempted:\n\"%s\"\n", command.c_str()); const char* hint = NULL; // ERROR_INVALID_PARAMETER means the command line was formatted // incorrectly. This can be caused by a command line being too long or // leading whitespace in the command. Give extra context for this case. if (error == ERROR_INVALID_PARAMETER) { if (command.length() > 0 && (command[0] == ' ' || command[0] == '\t')) hint = "command contains leading whitespace"; else hint = "is the command line too long?"; } Win32Fatal("CreateProcess", hint); } } // Close pipe channel only used by the child. if (child_pipe) CloseHandle(child_pipe); CloseHandle(nul); CloseHandle(process_info.hThread); child_ = process_info.hProcess; return true; } void Subprocess::OnPipeReady() { DWORD bytes; if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } Win32Fatal("GetOverlappedResult"); } if (is_reading_ && bytes) buf_.append(overlapped_buf_, bytes); memset(&overlapped_, 0, sizeof(overlapped_)); is_reading_ = true; if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_), &bytes, &overlapped_)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } if (GetLastError() != ERROR_IO_PENDING) Win32Fatal("ReadFile"); } // Even if we read any bytes in the readfile call, we'll enter this // function again later and get them at that point. } ExitStatus Subprocess::Finish() { if (!child_) return ExitFailure; // TODO: add error handling for all of these. WaitForSingleObject(child_, INFINITE); DWORD exit_code = 0; GetExitCodeProcess(child_, &exit_code); CloseHandle(child_); child_ = NULL; return exit_code == 0 ? ExitSuccess : exit_code == CONTROL_C_EXIT ? ExitInterrupted : ExitFailure; } bool Subprocess::Done() const { return pipe_ == NULL; } const string& Subprocess::GetOutput() const { return buf_; } HANDLE SubprocessSet::ioport_; SubprocessSet::SubprocessSet(bool setupSignalHandlers) : setupSignalHandlers_(setupSignalHandlers) { ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1); if (!ioport_) Win32Fatal("CreateIoCompletionPort"); if (setupSignalHandlers_ && !SetConsoleCtrlHandler(NotifyInterrupted, TRUE)) Win32Fatal("SetConsoleCtrlHandler"); } SubprocessSet::~SubprocessSet() { Clear(); if (setupSignalHandlers_) SetConsoleCtrlHandler(NotifyInterrupted, FALSE); CloseHandle(ioport_); } BOOL WINAPI SubprocessSet::NotifyInterrupted(DWORD dwCtrlType) { if (dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT) { if (!PostQueuedCompletionStatus(ioport_, 0, 0, NULL)) Win32Fatal("PostQueuedCompletionStatus"); return TRUE; } return FALSE; } Subprocess *SubprocessSet::Add(const string& command, bool use_console, const vector<string> & environment, bool useStderr) { Subprocess *subprocess = new Subprocess(use_console); if (!subprocess->Start(this, command, environment, useStderr)) { delete subprocess; return 0; } if (subprocess->child_) running_.push_back(subprocess); else finished_.push(subprocess); return subprocess; } bool SubprocessSet::DoWork() { DWORD bytes_read; Subprocess* subproc; OVERLAPPED* overlapped; if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc, &overlapped, INFINITE)) { if (GetLastError() != ERROR_BROKEN_PIPE) Win32Fatal("GetQueuedCompletionStatus"); } if (!subproc) // A NULL subproc indicates that we were interrupted and is // delivered by NotifyInterrupted above. return true; subproc->OnPipeReady(); if (subproc->Done()) { vector<Subprocess*>::iterator end = remove(running_.begin(), running_.end(), subproc); if (running_.end() != end) { finished_.push(subproc); running_.resize(end - running_.begin()); } } return false; } Subprocess* SubprocessSet::NextFinished() { if (finished_.empty()) return NULL; Subprocess* subproc = finished_.front(); finished_.pop(); return subproc; } void SubprocessSet::Clear() { for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ++i) { // Since the foreground process is in our process group, it will receive a // CTRL_C_EVENT or CTRL_BREAK_EVENT at the same time as us. if ((*i)->child_ && !(*i)->use_console_) { if (!GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, GetProcessId((*i)->child_))) { Win32Fatal("GenerateConsoleCtrlEvent"); } } } for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ++i) delete *i; running_.clear(); } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2017 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file FlightTaskSport.hpp * * Manual controlled position with maximum speed and no smoothing. */ #pragma once #include "FlightTaskManualPosition.hpp" #include "mathlib/mathlib.h" #include <float.h> class FlightTaskSport : public FlightTaskManualPosition { public: FlightTaskSport(control::SuperBlock *parent, const char *name) : FlightTaskManualPosition(parent, name), _vel_xy_max(parent, "MPC_XY_VEL_MAX", false) { } virtual ~FlightTaskSport() = default; protected: void _scaleSticks() override { /* Get all stick scaling from FlightTaskManualAltitude */ FlightTaskManualAltitude::_scaleSticks(); /* Constrain length of stick inputs to 1 for xy*/ matrix::Vector2f stick_xy(_sticks_expo(0), _sticks_expo(1)); float mag = math::constrain(stick_xy.length(), 0.0f, 1.0f); if (mag > FLT_EPSILON) { stick_xy = stick_xy.normalized() * mag; } /* Scale to velocity using max velocity */ _vel_sp_xy = stick_xy * _vel_xy_max.get(); /* Rotate setpoint into local frame. */ matrix::Vector3f vel_sp { _vel_sp_xy(0), _vel_sp_xy(1), 0.0f }; vel_sp = (matrix::Dcmf(matrix::Eulerf(0.0f, 0.0f, _yaw)) * vel_sp); _vel_sp_xy = matrix::Vector2f(vel_sp(0), vel_sp(1)); } private: control::BlockParamFloat _vel_xy_max; /**< maximal allowed horizontal speed, in sport mode full stick input*/ }; <commit_msg>FlightTaskSport: replace rotation by axis angle<commit_after>/**************************************************************************** * * Copyright (c) 2017 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file FlightTaskSport.hpp * * Manual controlled position with maximum speed and no smoothing. */ #pragma once #include "FlightTaskManualPosition.hpp" #include "mathlib/mathlib.h" #include <float.h> using namespace matrix; class FlightTaskSport : public FlightTaskManualPosition { public: FlightTaskSport(control::SuperBlock *parent, const char *name) : FlightTaskManualPosition(parent, name), _vel_xy_max(parent, "MPC_XY_VEL_MAX", false) { } virtual ~FlightTaskSport() = default; protected: void _scaleSticks() override { /* Get all stick scaling from FlightTaskManualAltitude */ FlightTaskManualAltitude::_scaleSticks(); /* Constrain length of stick inputs to 1 for xy*/ matrix::Vector2f stick_xy(_sticks_expo(0), _sticks_expo(1)); float mag = math::constrain(stick_xy.length(), 0.0f, 1.0f); if (mag > FLT_EPSILON) { stick_xy = stick_xy.normalized() * mag; } /* Scale to velocity using max velocity */ Vector2f vel_sp_xy = stick_xy * _vel_xy_max.get(); /* Rotate setpoint into local frame. */ matrix::Quatf q_yaw = matrix::AxisAnglef(matrix::Vector3f(0.0f, 0.0f, 1.0f), _yaw); matrix::Vector3f vel_world = q_yaw.conjugate(matrix::Vector3f(vel_sp_xy(0), vel_sp_xy(1), 0.0f)); _vel_sp(0) = vel_world(0); _vel_sp(1) = vel_world(1); } private: control::BlockParamFloat _vel_xy_max; /**< maximal allowed horizontal speed, in sport mode full stick input*/ }; <|endoftext|>
<commit_before>// Point.hpp #ifndef _RATIONAL_GEOMETRY_POINT_HPP_INCLUDED_ #define _RATIONAL_GEOMETRY_POINT_HPP_INCLUDED_ //β”‚ β–Ό1 β”‚ Preprocesser Flag Stuff //└────┴───────────────────────── #if !defined RATIONAL_GEOMETRY_THIS_IS_THE_TEST_BINARY \ && !defined DOCTEST_CONFIG_DISABLE #define DOCTEST_CONFIG_DISABLE #endif //β”‚ β–Ό1 β”‚ Includes //└────┴────────── #include "doctest/doctest.h" #include <array> #include <cstdarg> #include <cstddef> #ifndef DOCTEST_CONFIG_DISABLE #include <string> #include <typeinfo> #endif //β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ //β”‚ β–²1 β”‚ Includes namespace rational_geometry { //β”‚ β–Ό1 β”‚ Class Template Declaration //└────┴──────────────────────────── //β–Ό /// A geometric point in n-space with rational number coordinates. /// /// This class template should actually work with any type that has infinite /// precision, or with any type in uses where the type is not used outside of /// its full accuracy. One suggestion might be to throw an exception on a /// inaccurate operation from your RatT type. //β–² template <typename RatT, std::size_t kDimension = 3> class Point { public: // INTERNAL STATE std::array<RatT, kDimension> values_; // CONSTRUCTORS Point(); Point(std::array<RatT, kDimension> values); Point(const Point<RatT, kDimension - 1>& smaller_point, RatT last); // ACCESSORS Point<RatT, kDimension + 1> as_point(); Point<RatT, kDimension + 1> as_vector(); }; //β”‚ β–Ό1 β”‚ Convenience typedefs //└────┴────────────────────── template <typename RatT> using Point3D = Point<RatT, 3>; template <typename RatT> using Point2D = Point<RatT, 2>; //β”‚ β–Ό1 β”‚ Test Conveniences //└────┴─────────────────── #ifndef DOCTEST_CONFIG_DISABLE namespace point { namespace test_helpers { typedef Point<int, 3> IPoint3D; typedef Point<int, 2> IPoint2D; /// \todo Consider opening use of these to library users. const IPoint3D origin3{{0, 0, 0}}; const IPoint3D i3{{1, 0, 0}}; const IPoint3D j3{{0, 1, 0}}; const IPoint3D k3{{0, 0, 1}}; const IPoint2D origin2{{0, 0}}; const IPoint2D i2{{1, 0}}; const IPoint2D j2{{0, 1}}; } // namespace test_helpers } // namespace point #endif //β”‚ β–Ό1 β”‚ Class Template Definitions //└─┬──┴─┬────────────────────────── // β”‚ β–Ό2 β”‚ Constructors // └────┴────────────── template <typename RatT, size_t kDimension> Point<RatT, kDimension>::Point() : values_{} { } template <typename RatT, size_t kDimension> Point<RatT, kDimension>::Point(std::array<RatT, kDimension> values) : values_{values} { } TEST_CASE("Testing Point<>::Point(std::array<>)") { using namespace point::test_helpers; IPoint3D val_a{{1, 2, 3}}; CHECK(val_a.values_.size() == 3); } template <typename RatT, size_t kDimension> Point<RatT, kDimension>::Point( const Point<RatT, kDimension - 1>& smaller_point, RatT last) { using namespace std; copy( begin(smaller_point.values_), end(smaller_point.values_), begin(values_)); *rbegin(values_) = last; } TEST_CASE( "Testing Point<RatT, kDimension>::Point(Point<RatT, kDimension - 1>, RatT)") { using namespace point::test_helpers; IPoint3D val_in{{1, 2, 3}}; for (const auto& arbitrary_val : {-10, -1, 0, 1, 3, 50, 10'000}) { Point<int, 4> val_out{val_in, arbitrary_val}; CHECK(val_out.values_[3] == arbitrary_val); } } // β”‚ β–Ό2 β”‚ Accessors // └────┴─────────── template <typename RatT, size_t kDimension> Point<RatT, kDimension + 1> Point<RatT, kDimension>::as_point() { return {*this, 1}; } TEST_CASE("Testing Point<>::as_point()") { static const size_t dimension = 3; static const size_t result_dimension = dimension + 1; Point<int, dimension> val_a{{1, 2, 3}}; auto val_b = val_a.as_point(); CHECK(val_b.values_.size() == result_dimension); CHECK(val_b.values_[result_dimension - 1] == 1); std::string expected_value{typeid(Point<int, 4>).name()}; CHECK(expected_value == typeid(val_b).name()); } template <typename RatT, size_t kDimension> Point<RatT, kDimension + 1> Point<RatT, kDimension>::as_vector() { return {*this, 0}; } TEST_CASE("Testing Point<>::as_vector()") { static const size_t dimension = 3; static const size_t result_dimension = dimension + 1; Point<int, dimension> val_a{{1, 2, 3}}; auto val_b = val_a.as_vector(); CHECK(val_b.values_.size() == result_dimension); CHECK(val_b.values_[result_dimension - 1] == 0); std::string expected_value{typeid(Point<int, 4>).name()}; CHECK(expected_value == typeid(val_b).name()); } //β”‚ β–Ό1 β”‚ Related Operators //└────┴─────────────────── template <typename RatT_l, typename RatT_r, std::size_t kDimension> bool operator==(const Point<RatT_l, kDimension>& l_op, const Point<RatT_r, kDimension>& r_op) { return l_op.values_ == r_op.values_; } TEST_CASE("Testing Point<> == Point<>") { using namespace point::test_helpers; IPoint3D arbitrary_a{{1, 5, 24}}; IPoint3D arbitrary_b{{1, 5, 24}}; // To see if it even compiles, I guess. CHECK(arbitrary_a == arbitrary_b); } template <typename RatT_l, typename RatT_r, std::size_t kDimension> auto operator+(const Point<RatT_l, kDimension>& l_op, const Point<RatT_r, kDimension>& r_op) { using std::declval; Point<decltype(declval<RatT_l>() + declval<RatT_r>()), kDimension> ret; for (std::size_t i = 0; i < kDimension; ++i) { ret.values_[i] = l_op.values_[i] + r_op.values_[i]; } return ret; } TEST_CASE("Testing Point<> + Point<>") { using namespace point::test_helpers; IPoint3D a{origin3}; IPoint3D b{{1, 2, 3}}; IPoint3D c{{10, 20, 30}}; IPoint3D d{{4, 5, 6}}; for (const auto& val : {a, b, c, d}) { CHECK(val == val + origin3); } IPoint3D a_b{{1, 2, 3}}; CHECK(a_b == a + b); IPoint3D b_b{{2, 4, 6}}; CHECK(b_b == b + b); IPoint3D b_c{{11, 22, 33}}; CHECK(b_c == b + c); IPoint3D b_d{{5, 7, 9}}; CHECK(b_d == b + d); } template <typename RatT_l, typename RatT_r, std::size_t kDimension> auto operator*(const Point<RatT_l, kDimension>& l_op, const RatT_r& r_op) { using std::declval; Point<decltype(declval<RatT_l>() * r_op), kDimension> ret; for (std::size_t i = 0; i < kDimension; ++i) { ret.values_[i] = l_op.values_[i] * r_op; } return ret; } TEST_CASE("Testing Point<> * RatT") { using namespace point::test_helpers; IPoint3D a{{3, 5, 7}}; static const int factor{2}; IPoint3D expected{{6, 10, 14}}; CHECK(expected == a * factor); } template <typename RatT_l, typename RatT_r, std::size_t kDimension> auto operator*(RatT_l l_op, const Point<RatT_r, kDimension>& r_op) { // commutative return r_op * l_op; } TEST_CASE("Testing RatT * Point<>") { using namespace point::test_helpers; static const int factor{2}; IPoint3D a{{3, 5, 7}}; IPoint3D expected{{6, 10, 14}}; CHECK(expected == factor * a); } template <typename RatT_l, typename RatT_r, std::size_t kDimension> auto dot(const Point<RatT_l, kDimension>& l_op, const Point<RatT_r, kDimension>& r_op) { using std::declval; // clang-format off decltype(declval<RatT_l>() * declval<RatT_r>() + declval<RatT_l>() * declval<RatT_r>()) sum{0}; // clang-format on for (std::size_t i = 0; i < kDimension; ++i) { sum += l_op.values_[i] * r_op.values_[i]; } return sum; } TEST_CASE("Testing dot(Point<>, Point<>)") { using namespace point::test_helpers; IPoint2D i{i2}; IPoint2D j{j2}; auto i_j = dot(i, j); CHECK(0 == i_j); auto orthogonal = dot(3 * i + 4 * j, -4 * i + 3 * j); CHECK(0 == orthogonal); auto something_different = dot(3 * i, 2 * i); CHECK(6 == something_different); } template <typename RatT_l, typename RatT_r> auto cross(const Point<RatT_l, 3>& l_op, const Point<RatT_r, 3>& r_op) { using std::declval; // clang-format off Point<decltype(declval<RatT_l>() * declval<RatT_r>() - declval<RatT_l>() * declval<RatT_r>()), 3> ret{}; // clang-format on const auto& l = l_op.values_; const auto& r = r_op.values_; ret.values_[0] = l[1] * r[2] - l[2] * r[1]; ret.values_[1] = l[2] * r[0] - l[0] * r[2]; ret.values_[2] = l[0] * r[1] - l[1] * r[0]; return ret; } TEST_CASE("Testing cross(Point<>, Point<>, bool right_handed = true)") { using namespace point::test_helpers; static const IPoint3D i{i3}; static const IPoint3D j{j3}; static const IPoint3D k{k3}; CHECK(i == cross(j, k)); CHECK(j == cross(k, i)); CHECK(k == cross(i, j)); // Non-commutative CHECK(-1 * i == cross(k, j)); CHECK(-1 * j == cross(i, k)); CHECK(-1 * k == cross(j, i)); } //β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ //β”‚ β–²1 β”‚ Related Operators } // namespace rational_geometry #endif // _RATIONAL_GEOMETRY_POINT_HPP_INCLUDED_ // vim:set fdm=marker fmr=β–Ό,β–² cms=\ //%s et ts=2 sw=2 sts=2: <commit_msg>Add initializer list constructor for Point<commit_after>// Point.hpp #ifndef _RATIONAL_GEOMETRY_POINT_HPP_INCLUDED_ #define _RATIONAL_GEOMETRY_POINT_HPP_INCLUDED_ //β”‚ β–Ό1 β”‚ Preprocesser Flag Stuff //└────┴───────────────────────── #if !defined RATIONAL_GEOMETRY_THIS_IS_THE_TEST_BINARY \ && !defined DOCTEST_CONFIG_DISABLE #define DOCTEST_CONFIG_DISABLE #endif //β”‚ β–Ό1 β”‚ Includes //└────┴────────── #include "doctest/doctest.h" #include <array> #include <cstdarg> #include <cstddef> #include <initializer_list> #ifndef DOCTEST_CONFIG_DISABLE #include <string> #include <typeinfo> #endif //β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ //β”‚ β–²1 β”‚ Includes namespace rational_geometry { //β”‚ β–Ό1 β”‚ Class Template Declaration //└────┴──────────────────────────── //β–Ό /// A geometric point in n-space with rational number coordinates. /// /// This class template should actually work with any type that has infinite /// precision, or with any type in uses where the type is not used outside of /// its full accuracy. One suggestion might be to throw an exception on a /// inaccurate operation from your RatT type. //β–² template <typename RatT, std::size_t kDimension = 3> class Point { public: // INTERNAL STATE std::array<RatT, kDimension> values_; // CONSTRUCTORS Point(); Point(const std::initializer_list<RatT>& values); Point(const std::array<RatT, kDimension>& values); Point(const Point<RatT, kDimension - 1>& smaller_point, RatT last); // ACCESSORS Point<RatT, kDimension + 1> as_point(); Point<RatT, kDimension + 1> as_vector(); }; //β”‚ β–Ό1 β”‚ Convenience typedefs //└────┴────────────────────── template <typename RatT> using Point3D = Point<RatT, 3>; template <typename RatT> using Point2D = Point<RatT, 2>; //β”‚ β–Ό1 β”‚ Test Conveniences //└────┴─────────────────── #ifndef DOCTEST_CONFIG_DISABLE namespace point { namespace test_helpers { typedef Point<int, 3> IPoint3D; typedef Point<int, 2> IPoint2D; /// \todo Consider opening use of these to library users. const IPoint3D origin3{0, 0, 0}; const IPoint3D i3{1, 0, 0}; const IPoint3D j3{0, 1, 0}; const IPoint3D k3{0, 0, 1}; const IPoint2D origin2{0, 0}; const IPoint2D i2{1, 0}; const IPoint2D j2{0, 1}; } // namespace test_helpers } // namespace point #endif //β”‚ β–Ό1 β”‚ Class Template Definitions //└─┬──┴─┬────────────────────────── // β”‚ β–Ό2 β”‚ Constructors // └────┴────────────── template <typename RatT, size_t kDimension> Point<RatT, kDimension>::Point() : values_{} { } template <typename RatT, size_t kDimension> Point<RatT, kDimension>::Point(const std::initializer_list<RatT>& values) : values_{} // 0 initialize { using namespace std; auto start = begin(values); auto stop = start + min(values.size(), values_.size()); copy(start, stop, begin(values_)); } TEST_CASE("Testing Point<>::Point(std::initializer_list)") { using namespace point::test_helpers; IPoint3D val_a{1, 2, 3}; CHECK(val_a.values_.size() == 3); IPoint3D val_b{2, 5}; CHECK(val_b.values_[1] == 5); CHECK(val_b.values_[2] == 0); } template <typename RatT, size_t kDimension> Point<RatT, kDimension>::Point(const std::array<RatT, kDimension>& values) : values_{values} { } TEST_CASE("Testing Point<>::Point(std::array<>)") { using namespace point::test_helpers; std::array<int, 3> argument{1, 2, 3}; IPoint3D val_a{argument}; CHECK(val_a.values_.size() == 3); } template <typename RatT, size_t kDimension> Point<RatT, kDimension>::Point( const Point<RatT, kDimension - 1>& smaller_point, RatT last) { using namespace std; copy( begin(smaller_point.values_), end(smaller_point.values_), begin(values_)); *rbegin(values_) = last; } TEST_CASE( "Testing Point<RatT, kDimension>::Point(Point<RatT, kDimension - 1>, RatT)") { using namespace point::test_helpers; IPoint3D val_in{1, 2, 3}; for (const auto& arbitrary_val : {-10, -1, 0, 1, 3, 50, 10'000}) { Point<int, 4> val_out{val_in, arbitrary_val}; CHECK(val_out.values_[3] == arbitrary_val); } } // β”‚ β–Ό2 β”‚ Accessors // └────┴─────────── template <typename RatT, size_t kDimension> Point<RatT, kDimension + 1> Point<RatT, kDimension>::as_point() { return {*this, 1}; } TEST_CASE("Testing Point<>::as_point()") { static const size_t dimension = 3; static const size_t result_dimension = dimension + 1; Point<int, dimension> val_a{1, 2, 3}; auto val_b = val_a.as_point(); CHECK(val_b.values_.size() == result_dimension); CHECK(val_b.values_[result_dimension - 1] == 1); std::string expected_value{typeid(Point<int, 4>).name()}; CHECK(expected_value == typeid(val_b).name()); } template <typename RatT, size_t kDimension> Point<RatT, kDimension + 1> Point<RatT, kDimension>::as_vector() { return {*this, 0}; } TEST_CASE("Testing Point<>::as_vector()") { static const size_t dimension = 3; static const size_t result_dimension = dimension + 1; Point<int, dimension> val_a{1, 2, 3}; auto val_b = val_a.as_vector(); CHECK(val_b.values_.size() == result_dimension); CHECK(val_b.values_[result_dimension - 1] == 0); std::string expected_value{typeid(Point<int, 4>).name()}; CHECK(expected_value == typeid(val_b).name()); } //β”‚ β–Ό1 β”‚ Related Operators //└────┴─────────────────── template <typename RatT_l, typename RatT_r, std::size_t kDimension> bool operator==(const Point<RatT_l, kDimension>& l_op, const Point<RatT_r, kDimension>& r_op) { return l_op.values_ == r_op.values_; } TEST_CASE("Testing Point<> == Point<>") { using namespace point::test_helpers; IPoint3D arbitrary_a{1, 5, 24}; IPoint3D arbitrary_b{1, 5, 24}; // To see if it even compiles, I guess. CHECK(arbitrary_a == arbitrary_b); } template <typename RatT_l, typename RatT_r, std::size_t kDimension> auto operator+(const Point<RatT_l, kDimension>& l_op, const Point<RatT_r, kDimension>& r_op) { using std::declval; Point<decltype(declval<RatT_l>() + declval<RatT_r>()), kDimension> ret; for (std::size_t i = 0; i < kDimension; ++i) { ret.values_[i] = l_op.values_[i] + r_op.values_[i]; } return ret; } TEST_CASE("Testing Point<> + Point<>") { using namespace point::test_helpers; IPoint3D a{origin3}; IPoint3D b{1, 2, 3}; IPoint3D c{10, 20, 30}; IPoint3D d{4, 5, 6}; for (const auto& val : {a, b, c, d}) { CHECK(val == val + origin3); } IPoint3D a_b{1, 2, 3}; CHECK(a_b == a + b); IPoint3D b_b{2, 4, 6}; CHECK(b_b == b + b); IPoint3D b_c{11, 22, 33}; CHECK(b_c == b + c); IPoint3D b_d{5, 7, 9}; CHECK(b_d == b + d); } template <typename RatT_l, typename RatT_r, std::size_t kDimension> auto operator*(const Point<RatT_l, kDimension>& l_op, const RatT_r& r_op) { using std::declval; Point<decltype(declval<RatT_l>() * r_op), kDimension> ret; for (std::size_t i = 0; i < kDimension; ++i) { ret.values_[i] = l_op.values_[i] * r_op; } return ret; } TEST_CASE("Testing Point<> * RatT") { using namespace point::test_helpers; IPoint3D a{3, 5, 7}; static const int factor{2}; IPoint3D expected{6, 10, 14}; CHECK(expected == a * factor); } template <typename RatT_l, typename RatT_r, std::size_t kDimension> auto operator*(RatT_l l_op, const Point<RatT_r, kDimension>& r_op) { // commutative return r_op * l_op; } TEST_CASE("Testing RatT * Point<>") { using namespace point::test_helpers; static const int factor{2}; IPoint3D a{3, 5, 7}; IPoint3D expected{6, 10, 14}; CHECK(expected == factor * a); } template <typename RatT_l, typename RatT_r, std::size_t kDimension> auto dot(const Point<RatT_l, kDimension>& l_op, const Point<RatT_r, kDimension>& r_op) { using std::declval; // clang-format off decltype(declval<RatT_l>() * declval<RatT_r>() + declval<RatT_l>() * declval<RatT_r>()) sum{0}; // clang-format on for (std::size_t i = 0; i < kDimension; ++i) { sum += l_op.values_[i] * r_op.values_[i]; } return sum; } TEST_CASE("Testing dot(Point<>, Point<>)") { using namespace point::test_helpers; IPoint2D i{i2}; IPoint2D j{j2}; auto i_j = dot(i, j); CHECK(0 == i_j); auto orthogonal = dot(3 * i + 4 * j, -4 * i + 3 * j); CHECK(0 == orthogonal); auto something_different = dot(3 * i, 2 * i); CHECK(6 == something_different); } template <typename RatT_l, typename RatT_r> auto cross(const Point<RatT_l, 3>& l_op, const Point<RatT_r, 3>& r_op) { using std::declval; // clang-format off Point<decltype(declval<RatT_l>() * declval<RatT_r>() - declval<RatT_l>() * declval<RatT_r>()), 3> ret{}; // clang-format on const auto& l = l_op.values_; const auto& r = r_op.values_; ret.values_[0] = l[1] * r[2] - l[2] * r[1]; ret.values_[1] = l[2] * r[0] - l[0] * r[2]; ret.values_[2] = l[0] * r[1] - l[1] * r[0]; return ret; } TEST_CASE("Testing cross(Point<>, Point<>, bool right_handed = true)") { using namespace point::test_helpers; static const IPoint3D i{i3}; static const IPoint3D j{j3}; static const IPoint3D k{k3}; CHECK(i == cross(j, k)); CHECK(j == cross(k, i)); CHECK(k == cross(i, j)); // Non-commutative CHECK(-1 * i == cross(k, j)); CHECK(-1 * j == cross(i, k)); CHECK(-1 * k == cross(j, i)); } //β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ //β”‚ β–²1 β”‚ Related Operators } // namespace rational_geometry #endif // _RATIONAL_GEOMETRY_POINT_HPP_INCLUDED_ // vim:set fdm=marker fmr=β–Ό,β–² cms=\ //%s et ts=2 sw=2 sts=2: <|endoftext|>
<commit_before>/// \file util.cpp /// Contains generic functions for managing processes and configuration. #include "util.h" #include <string.h> #include <sys/types.h> #include <signal.h> #ifdef __FreeBSD__ #include <sys/wait.h> #else #include <wait.h> #endif #include <errno.h> #include <iostream> #include <sys/types.h> #include <pwd.h> #include <getopt.h> #include <stdlib.h> #include <stdio.h> #include <fstream> std::map<pid_t, std::string> Util::Procs::plist; bool Util::Procs::handler_set = false; /// Sets the current process' running user void Util::setUser(std::string username){ if (username != "root"){ struct passwd * user_info = getpwnam(username.c_str()); if (!user_info){ #if DEBUG >= 1 fprintf(stderr, "Error: could not setuid %s: could not get PID\n", username.c_str()); #endif return; }else{ if (setuid(user_info->pw_uid) != 0){ #if DEBUG >= 1 fprintf(stderr, "Error: could not setuid %s: not allowed\n", username.c_str()); #endif }else{ #if DEBUG >= 3 fprintf(stderr, "Changed user to %s\n", username.c_str()); #endif } } } } /// Used internally to capture child signals and update plist. void Util::Procs::childsig_handler(int signum){ if (signum != SIGCHLD){return;} pid_t ret = wait(0); #if DEBUG >= 1 std::string pname = plist[ret]; #endif plist.erase(ret); #if DEBUG >= 1 if (isActive(pname)){ std::cerr << "Process " << pname << " half-terminated." << std::endl; Stop(pname); }else{ std::cerr << "Process " << pname << " fully terminated." << std::endl; } #endif } /// Attempts to run the command cmd. /// Replaces the current process - use after forking first! /// This function will never return - it will either run the given /// command or kill itself with return code 42. void Util::Procs::runCmd(std::string & cmd){ //split cmd into arguments //supports a maximum of 20 arguments char * tmp = (char*)cmd.c_str(); char * tmp2 = 0; char * args[21]; int i = 0; tmp2 = strtok(tmp, " "); args[0] = tmp2; while (tmp2 != 0 && (i < 20)){ tmp2 = strtok(0, " "); ++i; args[i] = tmp2; } if (i == 20){args[20] = 0;} //execute the command execvp(args[0], args); #if DEBUG >= 1 std::cerr << "Error running \"" << cmd << "\": " << strerror(errno) << std::endl; #endif _exit(42); } /// Starts a new process if the name is not already active. /// \return 0 if process was not started, process PID otherwise. /// \arg name Name for this process - only used internally. /// \arg cmd Commandline for this process. pid_t Util::Procs::Start(std::string name, std::string cmd){ if (isActive(name)){return getPid(name);} if (!handler_set){ struct sigaction new_action; new_action.sa_handler = Util::Procs::childsig_handler; sigemptyset(&new_action.sa_mask); new_action.sa_flags = 0; sigaction(SIGCHLD, &new_action, NULL); handler_set = true; } pid_t ret = fork(); if (ret == 0){ runCmd(cmd); }else{ if (ret > 0){ #if DEBUG >= 1 std::cerr << "Process " << name << " started, PID " << ret << ": " << cmd << std::endl; #endif plist.insert(std::pair<pid_t, std::string>(ret, name)); }else{ #if DEBUG >= 1 std::cerr << "Process " << name << " could not be started. fork() failed." << std::endl; #endif return 0; } } return ret; } /// Starts two piped processes if the name is not already active. /// \return 0 if process was not started, main (receiving) process PID otherwise. /// \arg name Name for this process - only used internally. /// \arg cmd Commandline for sub (sending) process. /// \arg cmd2 Commandline for main (receiving) process. pid_t Util::Procs::Start(std::string name, std::string cmd, std::string cmd2){ if (isActive(name)){return getPid(name);} if (!handler_set){ struct sigaction new_action; new_action.sa_handler = Util::Procs::childsig_handler; sigemptyset(&new_action.sa_mask); new_action.sa_flags = 0; sigaction(SIGCHLD, &new_action, NULL); handler_set = true; } int pfildes[2]; if (pipe(pfildes) == -1){ #if DEBUG >= 1 std::cerr << "Process " << name << " could not be started. Pipe creation failed." << std::endl; #endif return 0; } pid_t ret = fork(); if (ret == 0){ close(pfildes[0]); dup2(pfildes[1],1); close(pfildes[1]); runCmd(cmd); }else{ if (ret > 0){ plist.insert(std::pair<pid_t, std::string>(ret, name)); }else{ #if DEBUG >= 1 std::cerr << "Process " << name << " could not be started. fork() failed." << std::endl; #endif close(pfildes[1]); close(pfildes[0]); return 0; } } pid_t ret2 = fork(); if (ret2 == 0){ close(pfildes[1]); dup2(pfildes[0],0); close(pfildes[0]); runCmd(cmd2); }else{ if (ret2 > 0){ #if DEBUG >= 1 std::cerr << "Process " << name << " started, PIDs (" << ret << ", " << ret2 << "): " << cmd << " | " << cmd2 << std::endl; #endif plist.insert(std::pair<pid_t, std::string>(ret2, name)); }else{ #if DEBUG >= 1 std::cerr << "Process " << name << " could not be started. fork() failed." << std::endl; #endif Stop(name); close(pfildes[1]); close(pfildes[0]); return 0; } } close(pfildes[1]); close(pfildes[0]); return ret; } /// Stops the named process, if running. /// \arg name (Internal) name of process to stop void Util::Procs::Stop(std::string name){ int max = 5; while (isActive(name)){ Stop(getPid(name)); max--; if (max <= 0){return;} } } /// Stops the process with this pid, if running. /// \arg name The PID of the process to stop. void Util::Procs::Stop(pid_t name){ if (isActive(name)){ kill(name, SIGTERM); } } /// (Attempts to) stop all running child processes. void Util::Procs::StopAll(){ std::map<pid_t, std::string>::iterator it; for (it = plist.begin(); it != plist.end(); it++){ Stop((*it).first); } } /// Returns the number of active child processes. int Util::Procs::Count(){ return plist.size(); } /// Returns true if a process by this name is currently active. bool Util::Procs::isActive(std::string name){ std::map<pid_t, std::string>::iterator it; for (it = plist.begin(); it != plist.end(); it++){ if ((*it).second == name){return true;} } return false; } /// Returns true if a process with this PID is currently active. bool Util::Procs::isActive(pid_t name){ return (plist.count(name) == 1); } /// Gets PID for this named process, if active. /// \return NULL if not active, process PID otherwise. pid_t Util::Procs::getPid(std::string name){ std::map<pid_t, std::string>::iterator it; for (it = plist.begin(); it != plist.end(); it++){ if ((*it).second == name){return (*it).first;} } return 0; } /// Gets name for this process PID, if active. /// \return Empty string if not active, name otherwise. std::string Util::Procs::getName(pid_t name){ if (plist.count(name) == 1){ return plist[name]; } return ""; } /// Creates a new configuration manager. Util::Config::Config(){ listen_port = 4242; daemon_mode = true; interface = "0.0.0.0"; configfile = "/etc/ddvtech.conf"; username = "root"; ignore_daemon = false; ignore_interface = false; ignore_port = false; ignore_user = false; } /// Parses commandline arguments. /// Calls exit if an unknown option is encountered, printing a help message. /// Assumes confsection is set. void Util::Config::parseArgs(int argc, char ** argv){ int opt = 0; static const char *optString = "ndvp:i:u:c:h?"; static const struct option longOpts[] = { {"help",0,0,'h'}, {"port",1,0,'p'}, {"interface",1,0,'i'}, {"username",1,0,'u'}, {"no-daemon",0,0,'n'}, {"daemon",0,0,'d'}, {"configfile",1,0,'c'}, {"version",0,0,'v'} }; while ((opt = getopt_long(argc, argv, optString, longOpts, 0)) != -1){ switch (opt){ case 'p': listen_port = atoi(optarg); ignore_port = true; break; case 'i': interface = optarg; ignore_interface = true; break; case 'n': daemon_mode = false; ignore_daemon = true; break; case 'd': daemon_mode = true; ignore_daemon = true; break; case 'c': configfile = optarg; break; case 'u': username = optarg; ignore_user = true; break; case 'v': printf("%s\n", TOSTRING(VERSION)); exit(1); break; case 'h': case '?': printf("Options: -h[elp], -?, -v[ersion], -n[odaemon], -d[aemon], -p[ort] VAL, -i[nterface] VAL, -c[onfigfile] VAL, -u[sername] VAL\n"); printf("Defaults:\n interface: 0.0.0.0\n port: %i\n daemon mode: true\n configfile: /etc/ddvtech.conf\n username: root\n", listen_port); printf("Username root means no change to UID, no matter what the UID is.\n"); printf("If the configfile exists, it is always loaded first. Commandline settings then overwrite the config file.\n"); printf("\nThis process takes it directives from the %s section of the configfile.\n", confsection.c_str()); printf("This is %s version %s\n", argv[0], TOSTRING(VERSION)); exit(1); break; } }//commandline options parser } /// Parses the configuration file at configfile, if it exists. /// Assumes confsection is set. void Util::Config::parseFile(){ std::ifstream conf(configfile.c_str(), std::ifstream::in); std::string tmpstr; bool acc_comm = false; size_t foundeq; if (conf.fail()){ #if DEBUG >= 3 fprintf(stderr, "Configuration file %s not found - using build-in defaults...\n", configfile.c_str()); #endif }else{ while (conf.good()){ getline(conf, tmpstr); if (tmpstr[0] == '['){//new section? check if we care. if (tmpstr == confsection){acc_comm = true;}else{acc_comm = false;} }else{ if (!acc_comm){break;}//skip all lines in this section if we do not care about it foundeq = tmpstr.find('='); if (foundeq != std::string::npos){ if ((tmpstr.substr(0, foundeq) == "port") && !ignore_port){listen_port = atoi(tmpstr.substr(foundeq+1).c_str());} if ((tmpstr.substr(0, foundeq) == "interface") && !ignore_interface){interface = tmpstr.substr(foundeq+1);} if ((tmpstr.substr(0, foundeq) == "username") && !ignore_user){username = tmpstr.substr(foundeq+1);} if ((tmpstr.substr(0, foundeq) == "daemon") && !ignore_daemon){daemon_mode = true;} if ((tmpstr.substr(0, foundeq) == "nodaemon") && !ignore_daemon){daemon_mode = false;} }//found equals sign }//section contents }//configfile line loop }//configuration } /// Will turn the current process into a daemon. /// Works by calling daemon(1,0): /// Does not change directory to root. /// Does redirect output to /dev/null void Util::Daemonize(){ #if DEBUG >= 3 fprintf(stderr, "Going into background mode...\n"); #endif daemon(1, 0); } <commit_msg>Fixes config util for nonsection applications, attempt to fix DDV_Controller process spawning.<commit_after>/// \file util.cpp /// Contains generic functions for managing processes and configuration. #include "util.h" #include <string.h> #include <sys/types.h> #include <signal.h> #ifdef __FreeBSD__ #include <sys/wait.h> #else #include <wait.h> #endif #include <errno.h> #include <iostream> #include <sys/types.h> #include <pwd.h> #include <getopt.h> #include <stdlib.h> #include <stdio.h> #include <fstream> std::map<pid_t, std::string> Util::Procs::plist; bool Util::Procs::handler_set = false; /// Sets the current process' running user void Util::setUser(std::string username){ if (username != "root"){ struct passwd * user_info = getpwnam(username.c_str()); if (!user_info){ #if DEBUG >= 1 fprintf(stderr, "Error: could not setuid %s: could not get PID\n", username.c_str()); #endif return; }else{ if (setuid(user_info->pw_uid) != 0){ #if DEBUG >= 1 fprintf(stderr, "Error: could not setuid %s: not allowed\n", username.c_str()); #endif }else{ #if DEBUG >= 3 fprintf(stderr, "Changed user to %s\n", username.c_str()); #endif } } } } /// Used internally to capture child signals and update plist. void Util::Procs::childsig_handler(int signum){ if (signum != SIGCHLD){return;} pid_t ret = wait(0); #if DEBUG >= 1 std::string pname = plist[ret]; #endif plist.erase(ret); #if DEBUG >= 1 if (isActive(pname)){ std::cerr << "Process " << pname << " half-terminated." << std::endl; Stop(pname); }else{ std::cerr << "Process " << pname << " fully terminated." << std::endl; } #endif } /// Attempts to run the command cmd. /// Replaces the current process - use after forking first! /// This function will never return - it will either run the given /// command or kill itself with return code 42. void Util::Procs::runCmd(std::string & cmd){ //split cmd into arguments //supports a maximum of 20 arguments char * tmp = (char*)cmd.c_str(); char * tmp2 = 0; char * args[21]; int i = 0; tmp2 = strtok(tmp, " "); args[0] = tmp2; while (tmp2 != 0 && (i < 20)){ tmp2 = strtok(0, " "); ++i; args[i] = tmp2; } if (i == 20){args[20] = 0;} //execute the command execvp(args[0], args); #if DEBUG >= 1 std::cerr << "Error running \"" << cmd << "\": " << strerror(errno) << std::endl; #endif _exit(42); } /// Starts a new process if the name is not already active. /// \return 0 if process was not started, process PID otherwise. /// \arg name Name for this process - only used internally. /// \arg cmd Commandline for this process. pid_t Util::Procs::Start(std::string name, std::string cmd){ if (isActive(name)){return getPid(name);} if (!handler_set){ struct sigaction new_action; new_action.sa_handler = Util::Procs::childsig_handler; sigemptyset(&new_action.sa_mask); new_action.sa_flags = 0; sigaction(SIGCHLD, &new_action, NULL); handler_set = true; } pid_t ret = fork(); if (ret == 0){ runCmd(cmd); }else{ if (ret > 0){ #if DEBUG >= 1 std::cerr << "Process " << name << " started, PID " << ret << ": " << cmd << std::endl; #endif plist.insert(std::pair<pid_t, std::string>(ret, name)); }else{ #if DEBUG >= 1 std::cerr << "Process " << name << " could not be started. fork() failed." << std::endl; #endif return 0; } } return ret; } /// Starts two piped processes if the name is not already active. /// \return 0 if process was not started, main (receiving) process PID otherwise. /// \arg name Name for this process - only used internally. /// \arg cmd Commandline for sub (sending) process. /// \arg cmd2 Commandline for main (receiving) process. pid_t Util::Procs::Start(std::string name, std::string cmd, std::string cmd2){ if (isActive(name)){return getPid(name);} if (!handler_set){ struct sigaction new_action; new_action.sa_handler = Util::Procs::childsig_handler; sigemptyset(&new_action.sa_mask); new_action.sa_flags = 0; sigaction(SIGCHLD, &new_action, NULL); handler_set = true; } int pfildes[2]; if (pipe(pfildes) == -1){ #if DEBUG >= 1 std::cerr << "Process " << name << " could not be started. Pipe creation failed." << std::endl; #endif return 0; } pid_t ret = fork(); if (ret == 0){ close(pfildes[0]); dup2(pfildes[1],1); close(pfildes[1]); runCmd(cmd); }else{ if (ret > 0){ plist.insert(std::pair<pid_t, std::string>(ret, name)); }else{ #if DEBUG >= 1 std::cerr << "Process " << name << " could not be started. fork() failed." << std::endl; #endif close(pfildes[1]); close(pfildes[0]); return 0; } } pid_t ret2 = fork(); if (ret2 == 0){ close(pfildes[1]); dup2(pfildes[0],0); close(pfildes[0]); runCmd(cmd2); }else{ if (ret2 > 0){ #if DEBUG >= 1 std::cerr << "Process " << name << " started, PIDs (" << ret << ", " << ret2 << "): " << cmd << " | " << cmd2 << std::endl; #endif plist.insert(std::pair<pid_t, std::string>(ret2, name)); }else{ #if DEBUG >= 1 std::cerr << "Process " << name << " could not be started. fork() failed." << std::endl; #endif Stop(name); close(pfildes[1]); close(pfildes[0]); return 0; } } close(pfildes[1]); close(pfildes[0]); return ret; } /// Stops the named process, if running. /// \arg name (Internal) name of process to stop void Util::Procs::Stop(std::string name){ int max = 5; while (isActive(name)){ Stop(getPid(name)); max--; if (max <= 0){return;} } } /// Stops the process with this pid, if running. /// \arg name The PID of the process to stop. void Util::Procs::Stop(pid_t name){ if (isActive(name)){ kill(name, SIGTERM); } } /// (Attempts to) stop all running child processes. void Util::Procs::StopAll(){ std::map<pid_t, std::string>::iterator it; for (it = plist.begin(); it != plist.end(); it++){ Stop((*it).first); } } /// Returns the number of active child processes. int Util::Procs::Count(){ return plist.size(); } /// Returns true if a process by this name is currently active. bool Util::Procs::isActive(std::string name){ std::map<pid_t, std::string>::iterator it; for (it = plist.begin(); it != plist.end(); it++){ if ((*it).second == name){return true;} } return false; } /// Returns true if a process with this PID is currently active. bool Util::Procs::isActive(pid_t name){ return (plist.count(name) == 1); } /// Gets PID for this named process, if active. /// \return NULL if not active, process PID otherwise. pid_t Util::Procs::getPid(std::string name){ std::map<pid_t, std::string>::iterator it; for (it = plist.begin(); it != plist.end(); it++){ if ((*it).second == name){return (*it).first;} } return 0; } /// Gets name for this process PID, if active. /// \return Empty string if not active, name otherwise. std::string Util::Procs::getName(pid_t name){ if (plist.count(name) == 1){ return plist[name]; } return ""; } /// Creates a new configuration manager. Util::Config::Config(){ listen_port = 4242; daemon_mode = true; interface = "0.0.0.0"; configfile = "/etc/ddvtech.conf"; username = "root"; ignore_daemon = false; ignore_interface = false; ignore_port = false; ignore_user = false; } /// Parses commandline arguments. /// Calls exit if an unknown option is encountered, printing a help message. /// confsection must be either already set or never be set at all when this function is called. /// In other words: do not change confsection after calling this function. void Util::Config::parseArgs(int argc, char ** argv){ int opt = 0; static const char *optString = "ndvp:i:u:c:h?"; static const struct option longOpts[] = { {"help",0,0,'h'}, {"port",1,0,'p'}, {"interface",1,0,'i'}, {"username",1,0,'u'}, {"no-daemon",0,0,'n'}, {"daemon",0,0,'d'}, {"configfile",1,0,'c'}, {"version",0,0,'v'} }; while ((opt = getopt_long(argc, argv, optString, longOpts, 0)) != -1){ switch (opt){ case 'p': listen_port = atoi(optarg); ignore_port = true; break; case 'i': interface = optarg; ignore_interface = true; break; case 'n': daemon_mode = false; ignore_daemon = true; break; case 'd': daemon_mode = true; ignore_daemon = true; break; case 'c': configfile = optarg; break; case 'u': username = optarg; ignore_user = true; break; case 'v': printf("%s\n", TOSTRING(VERSION)); exit(1); break; case 'h': case '?': std::string doingdaemon = "true"; if (!daemon_mode){doingdaemon = "false";} if (confsection == ""){ printf("Options: -h[elp], -?, -v[ersion], -n[odaemon], -d[aemon], -p[ort] VAL, -i[nterface] VAL, -u[sername] VAL\n"); printf("Defaults:\n interface: %s\n port: %i\n daemon mode: %s\n username: %s\n", interface.c_str(), listen_port, doingdaemon.c_str(), username.c_str()); }else{ printf("Options: -h[elp], -?, -v[ersion], -n[odaemon], -d[aemon], -p[ort] VAL, -i[nterface] VAL, -c[onfigfile] VAL, -u[sername] VAL\n"); printf("Defaults:\n interface: %s\n port: %i\n daemon mode: %s\n configfile: %s\n username: %s\n", interface.c_str(), listen_port, doingdaemon.c_str(), configfile.c_str(), username.c_str()); printf("Username root means no change to UID, no matter what the UID is.\n"); printf("If the configfile exists, it is always loaded first. Commandline settings then overwrite the config file.\n"); printf("\nThis process takes it directives from the %s section of the configfile.\n", confsection.c_str()); } printf("This is %s version %s\n", argv[0], TOSTRING(VERSION)); exit(1); break; } }//commandline options parser } /// Parses the configuration file at configfile, if it exists. /// Assumes confsection is set. void Util::Config::parseFile(){ std::ifstream conf(configfile.c_str(), std::ifstream::in); std::string tmpstr; bool acc_comm = false; size_t foundeq; if (conf.fail()){ #if DEBUG >= 3 fprintf(stderr, "Configuration file %s not found - using build-in defaults...\n", configfile.c_str()); #endif }else{ while (conf.good()){ getline(conf, tmpstr); if (tmpstr[0] == '['){//new section? check if we care. if (tmpstr == confsection){acc_comm = true;}else{acc_comm = false;} }else{ if (!acc_comm){break;}//skip all lines in this section if we do not care about it foundeq = tmpstr.find('='); if (foundeq != std::string::npos){ if ((tmpstr.substr(0, foundeq) == "port") && !ignore_port){listen_port = atoi(tmpstr.substr(foundeq+1).c_str());} if ((tmpstr.substr(0, foundeq) == "interface") && !ignore_interface){interface = tmpstr.substr(foundeq+1);} if ((tmpstr.substr(0, foundeq) == "username") && !ignore_user){username = tmpstr.substr(foundeq+1);} if ((tmpstr.substr(0, foundeq) == "daemon") && !ignore_daemon){daemon_mode = true;} if ((tmpstr.substr(0, foundeq) == "nodaemon") && !ignore_daemon){daemon_mode = false;} }//found equals sign }//section contents }//configfile line loop }//configuration } /// Will turn the current process into a daemon. /// Works by calling daemon(1,0): /// Does not change directory to root. /// Does redirect output to /dev/null void Util::Daemonize(){ #if DEBUG >= 3 fprintf(stderr, "Going into background mode...\n"); #endif daemon(1, 0); } <|endoftext|>