text
stringlengths
54
60.6k
<commit_before>//---------------------------- hp_dof_accessor.cc ------------------------ // $Id$ // Version: $Name$ // // Copyright (C) 2003 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- hp_dof_accessor.cc ------------------------ #include <lac/vector.h> #include <lac/block_vector.h> #include <lac/sparse_matrix.h> #include <dofs/dof_accessor.h> #include <dofs/dof_accessor.templates.h> #include <dofs/dof_levels.h> #include <dofs/hp_dof_handler.h> #include <dofs/hp_dof_levels.h> #include <grid/tria_iterator.h> #include <grid/tria_iterator.templates.h> #include <fe/fe.h> #include <vector> /*------------------------- Functions: DoFCellAccessor -----------------------*/ #if deal_II_dimension == 1 template <> TriaIterator<1, DoFObjectAccessor<0,1,hpDoFHandler> > DoFCellAccessor<1,hpDoFHandler>::face (const unsigned int) const { Assert (false, ExcImpossibleInDim(1)); return TriaIterator<1, DoFObjectAccessor<0,1, hpDoFHandler> >(); } #endif #if deal_II_dimension == 2 template <> TriaIterator<2, DoFObjectAccessor<1,2,hpDoFHandler> > DoFCellAccessor<2,hpDoFHandler>::face (const unsigned int i) const { return this->line(i); } #endif #if deal_II_dimension == 3 template <> TriaIterator<3, DoFObjectAccessor<2, 3, hpDoFHandler> > DoFCellAccessor<3,hpDoFHandler>::face (const unsigned int i) const { return this->quad(i); } #endif /*----------------- Functions: DoFObjectAccessor<1,dim,hpDoFHander> ----------*/ template <> void DoFObjectAccessor<1, 1, hpDoFHandler>::set_dof_index (const unsigned int i, const unsigned int index) const { typedef DoFAccessor<1, hpDoFHandler> BaseClass; Assert (this->dof_handler != 0, BaseClass::ExcInvalidObject()); // make sure a FE has been selected // and enough room was reserved Assert (&this->get_fe() != 0, BaseClass::ExcInvalidObject()); Assert (i<this->get_fe().dofs_per_line, ExcIndexRange (i, 0, this->get_fe().dofs_per_line)); unsigned int offset = this->dof_handler->levels[this->present_level] ->dof_line_index_offset[this->present_index]; this->dof_handler->levels[this->present_level] ->line_dofs[offset+i] = index; } template <> void DoFObjectAccessor<1, 2, hpDoFHandler>::set_dof_index (const unsigned int i, const unsigned int index) const { typedef DoFAccessor<2, hpDoFHandler> BaseClass; Assert (this->dof_handler != 0, BaseClass::ExcInvalidObject()); // make sure a FE has been selected // and enough room was reserved Assert (&this->get_fe() != 0, BaseClass::ExcInvalidObject()); Assert (i<this->get_fe().dofs_per_line, ExcIndexRange (i, 0, this->get_fe().dofs_per_line)); //TODO:[?] In two dimension it could happen that we have different active_fe_indices // on a line between to cells. Hence we have to differentiate between these two cases. // Unfortunately, this requires more information then available now. unsigned int offset = this->dof_handler->levels[this->present_level] ->dof_line_index_offset[this->present_index]; this->dof_handler->levels[this->present_level] ->line_dofs[offset+i] = index; } template <> void DoFObjectAccessor<1, 3, hpDoFHandler>::set_dof_index (const unsigned int i, const unsigned int index) const { typedef DoFAccessor<3, hpDoFHandler> BaseClass; Assert (this->dof_handler != 0, BaseClass::ExcInvalidObject()); // make sure a FE has been selected // and enough room was reserved Assert (&this->get_fe() != 0, BaseClass::ExcInvalidObject()); Assert (i<this->get_fe().dofs_per_line, ExcIndexRange (i, 0, this->get_fe().dofs_per_line)); unsigned int offset = this->dof_handler->levels[this->present_level] ->dof_line_index_offset[this->present_index]; this->dof_handler->levels[this->present_level] ->line_dofs[offset+i] = index; } /*----------------- Functions: DoFObjectAccessor<2,dim,hpDoFHander> ----------*/ template <> void DoFObjectAccessor<2, 2, hpDoFHandler>::set_dof_index (const unsigned int i, const unsigned int index) const { typedef DoFAccessor<2, hpDoFHandler> BaseClass; Assert (this->dof_handler != 0, BaseClass::ExcInvalidObject()); // make sure a FE has been selected // and enough room was reserved Assert (&this->get_fe() != 0, BaseClass::ExcInvalidObject()); Assert (i<this->get_fe().dofs_per_quad, ExcIndexRange (i, 0, this->get_fe().dofs_per_quad)); unsigned int offset = this->dof_handler->levels[this->present_level] ->dof_quad_index_offset[this->present_index]; this->dof_handler->levels[this->present_level] ->quad_dofs[offset+i] = index; } template <> void DoFObjectAccessor<2, 3, hpDoFHandler>::set_dof_index (const unsigned int i, const unsigned int index) const { typedef DoFAccessor<3, hpDoFHandler> BaseClass; Assert (this->dof_handler != 0, BaseClass::ExcInvalidObject()); // make sure a FE has been selected // and enough room was reserved Assert (&this->get_fe() != 0, BaseClass::ExcInvalidObject()); Assert (i<this->get_fe().dofs_per_quad, ExcIndexRange (i, 0, this->get_fe().dofs_per_quad)); unsigned int offset = this->dof_handler->levels[this->present_level] ->dof_quad_index_offset[this->present_index]; this->dof_handler->levels[this->present_level] ->quad_dofs[offset+i] = index; } /*----------------- Functions: DoFObjectAccessor<3,dim,hpDoFHander> ----------*/ template <> void DoFObjectAccessor<3, 3, hpDoFHandler>::set_dof_index (const unsigned int i, const unsigned int index) const { typedef DoFAccessor<3, hpDoFHandler> BaseClass; Assert (this->dof_handler != 0, BaseClass::ExcInvalidObject()); // make sure a FE has been selected // and enough room was reserved Assert (&this->get_fe() != 0, BaseClass::ExcInvalidObject()); Assert (i<this->get_fe().dofs_per_hex, ExcIndexRange (i, 0, this->get_fe().dofs_per_hex)); unsigned int offset = this->dof_handler->levels[this->present_level] ->dof_hex_index_offset[this->present_index]; this->dof_handler->levels[this->present_level] ->hex_dofs[offset+i] = index; } <commit_msg>Make a few functions inline.<commit_after>//---------------------------- hp_dof_accessor.cc ------------------------ // $Id$ // Version: $Name$ // // Copyright (C) 2003, 2005 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- hp_dof_accessor.cc ------------------------ #include <lac/vector.h> #include <lac/block_vector.h> #include <lac/sparse_matrix.h> #include <dofs/dof_accessor.h> #include <dofs/dof_accessor.templates.h> #include <dofs/dof_levels.h> #include <dofs/hp_dof_handler.h> #include <dofs/hp_dof_levels.h> #include <grid/tria_iterator.h> #include <grid/tria_iterator.templates.h> #include <fe/fe.h> #include <vector> /*------------------------- Functions: DoFCellAccessor -----------------------*/ #if deal_II_dimension == 1 template <> TriaIterator<1, DoFObjectAccessor<0,1,hpDoFHandler> > DoFCellAccessor<1,hpDoFHandler>::face (const unsigned int) const { Assert (false, ExcImpossibleInDim(1)); return TriaIterator<1, DoFObjectAccessor<0,1, hpDoFHandler> >(); } #endif #if deal_II_dimension == 2 template <> TriaIterator<2, DoFObjectAccessor<1,2,hpDoFHandler> > DoFCellAccessor<2,hpDoFHandler>::face (const unsigned int i) const { return this->line(i); } #endif #if deal_II_dimension == 3 template <> TriaIterator<3, DoFObjectAccessor<2, 3, hpDoFHandler> > DoFCellAccessor<3,hpDoFHandler>::face (const unsigned int i) const { return this->quad(i); } #endif /*----------------- Functions: DoFObjectAccessor<1,dim,hpDoFHander> ----------*/ template <> void DoFObjectAccessor<1, 1, hpDoFHandler>::set_dof_index (const unsigned int i, const unsigned int index) const { typedef DoFAccessor<1, hpDoFHandler> BaseClass; Assert (this->dof_handler != 0, BaseClass::ExcInvalidObject()); // make sure a FE has been selected // and enough room was reserved Assert (&this->get_fe() != 0, BaseClass::ExcInvalidObject()); Assert (i<this->get_fe().dofs_per_line, ExcIndexRange (i, 0, this->get_fe().dofs_per_line)); const unsigned int offset = this->dof_handler->levels[this->present_level] ->dof_line_index_offset[this->present_index]; this->dof_handler->levels[this->present_level] ->line_dofs[offset+i] = index; } template <> void DoFObjectAccessor<1, 2, hpDoFHandler>::set_dof_index (const unsigned int i, const unsigned int index) const { typedef DoFAccessor<2, hpDoFHandler> BaseClass; Assert (this->dof_handler != 0, BaseClass::ExcInvalidObject()); // make sure a FE has been selected // and enough room was reserved Assert (&this->get_fe() != 0, BaseClass::ExcInvalidObject()); Assert (i<this->get_fe().dofs_per_line, ExcIndexRange (i, 0, this->get_fe().dofs_per_line)); //TODO:[?] In two dimension it could happen that we have different active_fe_indices // on a line between to cells. Hence we have to differentiate between these two cases. // Unfortunately, this requires more information then available now. const unsigned int offset = this->dof_handler->levels[this->present_level] ->dof_line_index_offset[this->present_index]; this->dof_handler->levels[this->present_level] ->line_dofs[offset+i] = index; } template <> void DoFObjectAccessor<1, 3, hpDoFHandler>::set_dof_index (const unsigned int i, const unsigned int index) const { typedef DoFAccessor<3, hpDoFHandler> BaseClass; Assert (this->dof_handler != 0, BaseClass::ExcInvalidObject()); // make sure a FE has been selected // and enough room was reserved Assert (&this->get_fe() != 0, BaseClass::ExcInvalidObject()); Assert (i<this->get_fe().dofs_per_line, ExcIndexRange (i, 0, this->get_fe().dofs_per_line)); const unsigned int offset = this->dof_handler->levels[this->present_level] ->dof_line_index_offset[this->present_index]; this->dof_handler->levels[this->present_level] ->line_dofs[offset+i] = index; } /*----------------- Functions: DoFObjectAccessor<2,dim,hpDoFHander> ----------*/ template <> void DoFObjectAccessor<2, 2, hpDoFHandler>::set_dof_index (const unsigned int i, const unsigned int index) const { typedef DoFAccessor<2, hpDoFHandler> BaseClass; Assert (this->dof_handler != 0, BaseClass::ExcInvalidObject()); // make sure a FE has been selected // and enough room was reserved Assert (&this->get_fe() != 0, BaseClass::ExcInvalidObject()); Assert (i<this->get_fe().dofs_per_quad, ExcIndexRange (i, 0, this->get_fe().dofs_per_quad)); const unsigned int offset = this->dof_handler->levels[this->present_level] ->dof_quad_index_offset[this->present_index]; this->dof_handler->levels[this->present_level] ->quad_dofs[offset+i] = index; } template <> void DoFObjectAccessor<2, 3, hpDoFHandler>::set_dof_index (const unsigned int i, const unsigned int index) const { typedef DoFAccessor<3, hpDoFHandler> BaseClass; Assert (this->dof_handler != 0, BaseClass::ExcInvalidObject()); // make sure a FE has been selected // and enough room was reserved Assert (&this->get_fe() != 0, BaseClass::ExcInvalidObject()); Assert (i<this->get_fe().dofs_per_quad, ExcIndexRange (i, 0, this->get_fe().dofs_per_quad)); const unsigned int offset = this->dof_handler->levels[this->present_level] ->dof_quad_index_offset[this->present_index]; this->dof_handler->levels[this->present_level] ->quad_dofs[offset+i] = index; } /*----------------- Functions: DoFObjectAccessor<3,dim,hpDoFHander> ----------*/ template <> void DoFObjectAccessor<3, 3, hpDoFHandler>::set_dof_index (const unsigned int i, const unsigned int index) const { typedef DoFAccessor<3, hpDoFHandler> BaseClass; Assert (this->dof_handler != 0, BaseClass::ExcInvalidObject()); // make sure a FE has been selected // and enough room was reserved Assert (&this->get_fe() != 0, BaseClass::ExcInvalidObject()); Assert (i<this->get_fe().dofs_per_hex, ExcIndexRange (i, 0, this->get_fe().dofs_per_hex)); const unsigned int offset = this->dof_handler->levels[this->present_level] ->dof_hex_index_offset[this->present_index]; this->dof_handler->levels[this->present_level] ->hex_dofs[offset+i] = index; } <|endoftext|>
<commit_before>/* TidyEngine Copyright (C) 2016 Jakob Sinclair This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact the author at: jakob.sinclair99@gmail.com */ #pragma once class Sheet; #include <cstdint> #include <vector> #include <glm/vec4.hpp> #include <glm/vec3.hpp> #include "renderable.hpp" #include "vertex.hpp" class Sprite : public Renderable { public: Sprite(Sheet *sheet, uint32_t w = 0, uint32_t h = 0); virtual ~Sprite(); virtual bool Initialise(Sheet *sheet, uint32_t w = 0, uint32_t h = 0); virtual const std::vector<Vertex> &GetVertices(); virtual void SetPos(const glm::vec3 &pos); virtual const glm::vec3 &GetPos() const; virtual const uint32_t &GetWidth(); virtual const uint32_t &GetHeight(); virtual void SetWidth(uint32_t w); virtual void SetHeight(uint32_t h); protected: glm::vec3 m_Position = glm::vec3(0.0f, 0.0f, 0.0f); uint32_t m_Width = 0; uint32_t m_Height = 0; glm::vec4 m_TexCoords = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f); bool m_Update = false; };<commit_msg>libTidyEngine: Reformatted the sprite class\nChanged the position of variable m_Position to better organize the members of the class by their type.<commit_after>/* TidyEngine Copyright (C) 2016 Jakob Sinclair This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact the author at: jakob.sinclair99@gmail.com */ #pragma once class Sheet; #include <cstdint> #include <vector> #include <glm/vec4.hpp> #include <glm/vec3.hpp> #include "renderable.hpp" #include "vertex.hpp" class Sprite : public Renderable { public: Sprite(Sheet *sheet, uint32_t w = 0, uint32_t h = 0); virtual ~Sprite(); virtual bool Initialise(Sheet *sheet, uint32_t w = 0, uint32_t h = 0); virtual const std::vector<Vertex> &GetVertices(); virtual void SetPos(const glm::vec3 &pos); virtual const glm::vec3 &GetPos() const; virtual const uint32_t &GetWidth(); virtual const uint32_t &GetHeight(); virtual void SetWidth(uint32_t w); virtual void SetHeight(uint32_t h); protected: uint32_t m_Width = 0; uint32_t m_Height = 0; glm::vec3 m_Position = glm::vec3(0.0f, 0.0f, 0.0f); glm::vec4 m_TexCoords = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f); bool m_Update = false; }; <|endoftext|>
<commit_before>/*! \file uconnection.cc ******************************************************************************* File: uconnection.cc\n Implementation of the UConnection class. This file is part of %URBI Kernel, version __kernelversion__\n (c) Jean-Christophe Baillie, 2004-2005. Permission to use, copy, modify, and redistribute this software for non-commercial use is hereby granted. This software is provided "as is" without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of fitness for a particular purpose. For more information, comments, bug reports: http://www.urbiforge.net **************************************************************************** */ //#define ENABLE_DEBUG_TRACES #include "libport/compiler.hh" #include "libport/config.h" #include "libport/cstring" #include "libport/cstdio" #include <cassert> #include <cstdarg> #include <sstream> #include <iomanip> #include <boost/lexical_cast.hpp> #include <boost/foreach.hpp> #include "libport/assert.hh" #include "libport/ref-pt.hh" #include "kernel/userver.hh" #include "kernel/uconnection.hh" #include "ast/ast.hh" #include "ast/nary.hh" #include "object/object.hh" #include "object/atom.hh" #include "runner/fwd.hh" #include "runner/runner.hh" #include "parser/uparser.hh" #include "ubanner.hh" #include "uqueue.hh" #include "object/atom.hh" // object::Lobby #include "object/alien.hh" // object::box UConnection::UConnection (UServer& server, size_t packetSize) : uerror_ (USUCCESS), closing_ (false), receiving_ (false), new_data_added_ (false), server_ (server), send_queue_ (new UQueue ()), recv_queue_ (new UQueue ()), packet_size_ (packetSize), blocked_ (false), // Initial state of the connection: unblocked, not receiving binary. active_ (true), lobby_ (object::Lobby::fresh(object::State(*this))), parser_ (new parser::UParser ()), active_command_ (new ast::Nary()) { //FIXME: This would be better done in Lobby ctor, in Urbi maybe. lobby_->slot_set(SYMBOL(lobby), lobby_); for (int i = 0; i < MAX_ERRORSIGNALS ; ++i) error_signals_[i] = false; // initialize the connection tag used to reference local variables std::ostringstream o; o << 'U' << (long) this; connection_tag_ = o.str(); object::rObject tag = object::Object::fresh(); tag->proto_add(object::tag_class); tag->slot_set(SYMBOL(tag), box(scheduler::rTag, scheduler::Tag::fresh(libport::Symbol(connection_tag_)))); lobby_->slot_set(SYMBOL(connectionTag), tag); } UConnection::~UConnection () { extract_tag(lobby_->slot_get(SYMBOL(connectionTag))) ->stop(server_.getScheduler()); DEBUG(("Destroying UConnection...")); delete parser_; delete send_queue_; delete recv_queue_; DEBUG(("done\n")); } UConnection& UConnection::initialize() { for (int i = 0; ::HEADER_BEFORE_CUSTOM[i]; ++i) send(::HEADER_BEFORE_CUSTOM[i], "start"); for (int i = 0; ; ++i) { char buf[1024]; server_.getCustomHeader(i, buf, sizeof buf); if (!buf[0]) break; send(buf, "start"); } for (int i = 0; ::HEADER_AFTER_CUSTOM[i]; ++i) send(::HEADER_AFTER_CUSTOM[i], "start"); { char buf[1024]; snprintf(buf, sizeof buf, "*** ID: %s\n", connection_tag_.c_str()); send(buf, "ident"); snprintf(buf, sizeof buf, "%s created", connection_tag_.c_str()); server_.echo(::DISPLAY_FORMAT, (long)this, "UConnection::initialize", buf); } server_.loadFile("CLIENT.INI", *recv_queue_); new_data_added_ = true; return *this; } UConnection& UConnection::send (const char* buf, int len, const char* tag, bool flush) { if (tag) { std::string pref = make_prefix (tag); send_queue (pref.c_str(), pref.length()); } if (buf) { UErrorValue ret = send_queue (buf, len).error_get (); if (flush && ret != UFAIL) this->flush (); CONN_ERR_RET(ret); } return *this; } UConnection& UConnection::send_queue (const char* buf, size_t len) { if (!closing_) send_queue_->push(buf, len); CONN_ERR_RET(USUCCESS); } UConnection& UConnection::continue_send () { if (closing_) CONN_ERR_RET(UFAIL); # if ! defined LIBPORT_URBI_ENV_AIBO boost::mutex::scoped_lock lock(mutex_); # endif blocked_ = false; // continue_send unblocks the connection. // nb of bytes to send. size_t toSend = std::min(packet_size_, send_queue_->size()); ECHO(toSend); if (!toSend) CONN_ERR_RET(USUCCESS); if (char* popData = send_queue_->front(toSend)) { ECHO(popData); int wasSent = effective_send (popData, toSend); if (wasSent < 0) CONN_ERR_RET(UFAIL); else if (wasSent == 0 || send_queue_->pop(wasSent)) CONN_ERR_RET(USUCCESS); } CONN_ERR_RET(UFAIL); } UConnection& UConnection::received (const char* s) { return received (s, strlen (s)); } UConnection& UConnection::received (const char* buffer, size_t length) { PING(); #if ! defined LIBPORT_URBI_ENV_AIBO boost::recursive_mutex::scoped_lock serverLock(server_.mutex); #endif { // Lock the connection. #if ! defined LIBPORT_URBI_ENV_AIBO boost::mutex::scoped_lock lock(mutex_); #endif recv_queue_->push(buffer, length); } #if ! defined LIBPORT_URBI_ENV_AIBO // If the following code does not compile with Boost 1.34, then use // CPP to discrimate bw Boost < 1.35 and Boost >= 1.35 to pass // (resp.) "false" or "boost::defer_lock" as second arg. // // http://www.boost.org/doc/libs/1_35_0/doc/html/thread/changes.html boost::try_mutex::scoped_try_lock tree_lock(tree_mutex_, boost::defer_lock); if (!tree_lock.try_lock()) #endif { new_data_added_ = true; //server will call us again right after work CONN_ERR_RET(USUCCESS); } parser::UParser& p = parser_get(); // There should be no tree sitting in the parser. passert (*p.ast_get(), !p.ast_get()); // Starts processing receiving_ = true; // active_command_: The command to be executed (root of the AST). // passert (*active_command_, active_command_->empty()); // If active_command_ is not empty, a runner is still alive, so set // obstructed to true. This is a temporary fix to avoid having several // runners on the same Nary, until runners become managed outside UConnection. bool obstructed = !active_command_->empty(); // Get all the commands that are ready to be executed. for (std::string command = recv_queue_->pop_command(); !command.empty(); command = recv_queue_->pop_command()) { int result = p.parse (command); passert (result, result != -1); p.process_errors(active_command_); if (ast::Nary* ast = p.ast_take().release()) { ECHO ("parsed: {{{" << *ast << "}}}"); // Append to the current list. active_command_->splice_back(*ast); ECHO ("appended: " << *active_command_ << "}}}"); } else { std::cerr << make_prefix("error") << "the parser returned NULL" << std::endl; // FIXME: Is this line usefull ? server_.error(::DISPLAY_FORMAT, (long) this, "UConnection::received", "the parser returned NULL\n"); } } // Execute the new command. if (!obstructed) execute (); receiving_ = false; p.ast_set (0); #if ! defined LIBPORT_URBI_ENV_AIBO tree_lock.unlock(); #endif CONN_ERR_RET(USUCCESS); } UConnection& UConnection::send (UErrorCode n) { const char* msg = message (UERRORCODE, n); UErrorValue result = send(msg, "error").error_get (); if (result == USUCCESS) { char buf[80]; strncpy (buf, msg, sizeof buf); if (strlen (msg) - 1 < sizeof buf) //remove the '\n' at the end. buf[strlen(msg)-1] = 0; server_.error(::DISPLAY_FORMAT, (long)this, "UConnection::error", buf); } CONN_ERR_RET(result); } UConnection& UConnection::send (UWarningCode n) { const char* msg = message (UWARNINGCODE, n); UErrorValue result = send(msg, "warning").error_get (); if (result == USUCCESS) { char buf[80]; strncpy (buf, msg, sizeof buf); if (strlen (msg) - 1 < sizeof buf) //remove the '\n' at the end. buf[strlen(msg)-1] = 0; server_.echoKey("WARNG", ::DISPLAY_FORMAT, (long)this, "UConnection::warning", buf); } CONN_ERR_RET(result); } UConnection& UConnection::send (object::rObject result, const char* tag, const char* p) { // "Display" the result. std::ostringstream os; if (p) os << p; runner::Runner& r = server_.getCurrentRunner(); try { result = urbi_call(r, result, SYMBOL(asToplevelPrintable)); } catch (object::LookupError&) { // nothing } result->print (os, r); if (!os.str ().empty ()) { std::string prefix = make_prefix (tag); send (prefix.c_str (), (const char*)0, false); send_queue (os.str ().c_str(), os.str().length()); endline (); } return *this; } void UConnection::new_result (object::rObject result) { // The prefix should be (getTag().c_str()) instead of 0. // FIXME: the prefix should not be built manually. send (result, 0, 0); } UConnection& UConnection::execute () { PING (); if (active_command_->empty()) return *this; ECHO("Command is: {{{" << *active_command_ << "}}}"); // Our active_command_ is a ast::Nary, we must now "tell" it that // it's a top-level Nary so that it can send its results back to the // UConnection. It also entitles the Runner to free this Nary when // it has evaluated it. active_command_->toplevel_set (true); // FIXME: There is an obvious memory leak here runner::Runner* runner = new runner::Runner(lobby_, 0, ::urbiserver->getScheduler (), active_command_); runner->start_job (); PING (); return *this; } std::string UConnection::make_prefix (const char* tag) const { std::ostringstream o; char fill = o.fill('0'); o << '[' << std::setw(8) << server_.lastTime() / 1000L; o.fill(fill); if (tag && strlen(tag)) o << ':' << tag; o << "] "; return o.str (); } bool UConnection::has_pending_command () const { return !active_command_->empty(); } void UConnection::drop_pending_commands () { active_command_->clear(); } bool UConnection::send_queue_empty () const { return send_queue_->empty(); } <commit_msg>Do not require boost 1.35.0<commit_after>/*! \file uconnection.cc ******************************************************************************* File: uconnection.cc\n Implementation of the UConnection class. This file is part of %URBI Kernel, version __kernelversion__\n (c) Jean-Christophe Baillie, 2004-2005. Permission to use, copy, modify, and redistribute this software for non-commercial use is hereby granted. This software is provided "as is" without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of fitness for a particular purpose. For more information, comments, bug reports: http://www.urbiforge.net **************************************************************************** */ //#define ENABLE_DEBUG_TRACES #include "libport/compiler.hh" #include "libport/config.h" #include "libport/cstring" #include "libport/cstdio" #include <cassert> #include <cstdarg> #include <sstream> #include <iomanip> #include <boost/lexical_cast.hpp> #include <boost/foreach.hpp> #include "libport/assert.hh" #include "libport/ref-pt.hh" #include "kernel/userver.hh" #include "kernel/uconnection.hh" #include "ast/ast.hh" #include "ast/nary.hh" #include "object/object.hh" #include "object/atom.hh" #include "runner/fwd.hh" #include "runner/runner.hh" #include "parser/uparser.hh" #include "ubanner.hh" #include "uqueue.hh" #include "object/atom.hh" // object::Lobby #include "object/alien.hh" // object::box UConnection::UConnection (UServer& server, size_t packetSize) : uerror_ (USUCCESS), closing_ (false), receiving_ (false), new_data_added_ (false), server_ (server), send_queue_ (new UQueue ()), recv_queue_ (new UQueue ()), packet_size_ (packetSize), blocked_ (false), // Initial state of the connection: unblocked, not receiving binary. active_ (true), lobby_ (object::Lobby::fresh(object::State(*this))), parser_ (new parser::UParser ()), active_command_ (new ast::Nary()) { //FIXME: This would be better done in Lobby ctor, in Urbi maybe. lobby_->slot_set(SYMBOL(lobby), lobby_); for (int i = 0; i < MAX_ERRORSIGNALS ; ++i) error_signals_[i] = false; // initialize the connection tag used to reference local variables std::ostringstream o; o << 'U' << (long) this; connection_tag_ = o.str(); object::rObject tag = object::Object::fresh(); tag->proto_add(object::tag_class); tag->slot_set(SYMBOL(tag), box(scheduler::rTag, scheduler::Tag::fresh(libport::Symbol(connection_tag_)))); lobby_->slot_set(SYMBOL(connectionTag), tag); } UConnection::~UConnection () { extract_tag(lobby_->slot_get(SYMBOL(connectionTag))) ->stop(server_.getScheduler()); DEBUG(("Destroying UConnection...")); delete parser_; delete send_queue_; delete recv_queue_; DEBUG(("done\n")); } UConnection& UConnection::initialize() { for (int i = 0; ::HEADER_BEFORE_CUSTOM[i]; ++i) send(::HEADER_BEFORE_CUSTOM[i], "start"); for (int i = 0; ; ++i) { char buf[1024]; server_.getCustomHeader(i, buf, sizeof buf); if (!buf[0]) break; send(buf, "start"); } for (int i = 0; ::HEADER_AFTER_CUSTOM[i]; ++i) send(::HEADER_AFTER_CUSTOM[i], "start"); { char buf[1024]; snprintf(buf, sizeof buf, "*** ID: %s\n", connection_tag_.c_str()); send(buf, "ident"); snprintf(buf, sizeof buf, "%s created", connection_tag_.c_str()); server_.echo(::DISPLAY_FORMAT, (long)this, "UConnection::initialize", buf); } server_.loadFile("CLIENT.INI", *recv_queue_); new_data_added_ = true; return *this; } UConnection& UConnection::send (const char* buf, int len, const char* tag, bool flush) { if (tag) { std::string pref = make_prefix (tag); send_queue (pref.c_str(), pref.length()); } if (buf) { UErrorValue ret = send_queue (buf, len).error_get (); if (flush && ret != UFAIL) this->flush (); CONN_ERR_RET(ret); } return *this; } UConnection& UConnection::send_queue (const char* buf, size_t len) { if (!closing_) send_queue_->push(buf, len); CONN_ERR_RET(USUCCESS); } UConnection& UConnection::continue_send () { if (closing_) CONN_ERR_RET(UFAIL); # if ! defined LIBPORT_URBI_ENV_AIBO boost::mutex::scoped_lock lock(mutex_); # endif blocked_ = false; // continue_send unblocks the connection. // nb of bytes to send. size_t toSend = std::min(packet_size_, send_queue_->size()); ECHO(toSend); if (!toSend) CONN_ERR_RET(USUCCESS); if (char* popData = send_queue_->front(toSend)) { ECHO(popData); int wasSent = effective_send (popData, toSend); if (wasSent < 0) CONN_ERR_RET(UFAIL); else if (wasSent == 0 || send_queue_->pop(wasSent)) CONN_ERR_RET(USUCCESS); } CONN_ERR_RET(UFAIL); } UConnection& UConnection::received (const char* s) { return received (s, strlen (s)); } UConnection& UConnection::received (const char* buffer, size_t length) { PING(); #if ! defined LIBPORT_URBI_ENV_AIBO boost::recursive_mutex::scoped_lock serverLock(server_.mutex); #endif { // Lock the connection. #if ! defined LIBPORT_URBI_ENV_AIBO boost::mutex::scoped_lock lock(mutex_); #endif recv_queue_->push(buffer, length); } #if ! defined LIBPORT_URBI_ENV_AIBO // http://www.boost.org/doc/libs/1_35_0/doc/html/thread/changes.html #if BOOST_VERSION >= 103500 boost::try_mutex::scoped_try_lock tree_lock(tree_mutex_, boost::defer_lock); #else boost::try_mutex::scoped_try_lock tree_lock(tree_mutex_, false); #endif // BOOST_VERSION >= 103500 if (!tree_lock.try_lock()) #endif { new_data_added_ = true; //server will call us again right after work CONN_ERR_RET(USUCCESS); } parser::UParser& p = parser_get(); // There should be no tree sitting in the parser. passert (*p.ast_get(), !p.ast_get()); // Starts processing receiving_ = true; // active_command_: The command to be executed (root of the AST). // passert (*active_command_, active_command_->empty()); // If active_command_ is not empty, a runner is still alive, so set // obstructed to true. This is a temporary fix to avoid having several // runners on the same Nary, until runners become managed outside UConnection. bool obstructed = !active_command_->empty(); // Get all the commands that are ready to be executed. for (std::string command = recv_queue_->pop_command(); !command.empty(); command = recv_queue_->pop_command()) { int result = p.parse (command); passert (result, result != -1); p.process_errors(active_command_); if (ast::Nary* ast = p.ast_take().release()) { ECHO ("parsed: {{{" << *ast << "}}}"); // Append to the current list. active_command_->splice_back(*ast); ECHO ("appended: " << *active_command_ << "}}}"); } else { std::cerr << make_prefix("error") << "the parser returned NULL" << std::endl; // FIXME: Is this line usefull ? server_.error(::DISPLAY_FORMAT, (long) this, "UConnection::received", "the parser returned NULL\n"); } } // Execute the new command. if (!obstructed) execute (); receiving_ = false; p.ast_set (0); #if ! defined LIBPORT_URBI_ENV_AIBO tree_lock.unlock(); #endif CONN_ERR_RET(USUCCESS); } UConnection& UConnection::send (UErrorCode n) { const char* msg = message (UERRORCODE, n); UErrorValue result = send(msg, "error").error_get (); if (result == USUCCESS) { char buf[80]; strncpy (buf, msg, sizeof buf); if (strlen (msg) - 1 < sizeof buf) //remove the '\n' at the end. buf[strlen(msg)-1] = 0; server_.error(::DISPLAY_FORMAT, (long)this, "UConnection::error", buf); } CONN_ERR_RET(result); } UConnection& UConnection::send (UWarningCode n) { const char* msg = message (UWARNINGCODE, n); UErrorValue result = send(msg, "warning").error_get (); if (result == USUCCESS) { char buf[80]; strncpy (buf, msg, sizeof buf); if (strlen (msg) - 1 < sizeof buf) //remove the '\n' at the end. buf[strlen(msg)-1] = 0; server_.echoKey("WARNG", ::DISPLAY_FORMAT, (long)this, "UConnection::warning", buf); } CONN_ERR_RET(result); } UConnection& UConnection::send (object::rObject result, const char* tag, const char* p) { // "Display" the result. std::ostringstream os; if (p) os << p; runner::Runner& r = server_.getCurrentRunner(); try { result = urbi_call(r, result, SYMBOL(asToplevelPrintable)); } catch (object::LookupError&) { // nothing } result->print (os, r); if (!os.str ().empty ()) { std::string prefix = make_prefix (tag); send (prefix.c_str (), (const char*)0, false); send_queue (os.str ().c_str(), os.str().length()); endline (); } return *this; } void UConnection::new_result (object::rObject result) { // The prefix should be (getTag().c_str()) instead of 0. // FIXME: the prefix should not be built manually. send (result, 0, 0); } UConnection& UConnection::execute () { PING (); if (active_command_->empty()) return *this; ECHO("Command is: {{{" << *active_command_ << "}}}"); // Our active_command_ is a ast::Nary, we must now "tell" it that // it's a top-level Nary so that it can send its results back to the // UConnection. It also entitles the Runner to free this Nary when // it has evaluated it. active_command_->toplevel_set (true); // FIXME: There is an obvious memory leak here runner::Runner* runner = new runner::Runner(lobby_, 0, ::urbiserver->getScheduler (), active_command_); runner->start_job (); PING (); return *this; } std::string UConnection::make_prefix (const char* tag) const { std::ostringstream o; char fill = o.fill('0'); o << '[' << std::setw(8) << server_.lastTime() / 1000L; o.fill(fill); if (tag && strlen(tag)) o << ':' << tag; o << "] "; return o.str (); } bool UConnection::has_pending_command () const { return !active_command_->empty(); } void UConnection::drop_pending_commands () { active_command_->clear(); } bool UConnection::send_queue_empty () const { return send_queue_->empty(); } <|endoftext|>
<commit_before>/*! \file uconnection.cc ******************************************************************************* File: uconnection.cc\n Implementation of the UConnection class. This file is part of %URBI Kernel, version __kernelversion__\n (c) Jean-Christophe Baillie, 2004-2005. Permission to use, copy, modify, and redistribute this software for non-commercial use is hereby granted. This software is provided "as is" without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of fitness for a particular purpose. For more information, comments, bug reports: http://www.urbiforge.net **************************************************************************** */ //#define ENABLE_DEBUG_TRACES #include "libport/compiler.hh" #include "libport/config.h" #include "libport/cstring" #include "libport/cstdio" #include <cassert> #include <cstdarg> #include <sstream> #include <iomanip> #include <boost/lexical_cast.hpp> #include <boost/foreach.hpp> #include "libport/assert.hh" #include "libport/ref-pt.hh" #include "kernel/userver.hh" #include "kernel/uconnection.hh" #include "ast/ast.hh" #include "ast/nary.hh" #include "object/object.hh" #include "object/atom.hh" #include "runner/fwd.hh" #include "runner/runner.hh" #include "parser/uparser.hh" #include "ubanner.hh" #include "uqueue.hh" #include "object/atom.hh" // object::Lobby UConnection::UConnection (UServer* userver,size_t packetSize) : uerror_ (USUCCESS), client_ip_ (0), closing_ (false), receiving_ (false), new_data_added_ (false), send_queue_ (new UQueue ()), recv_queue_ (new UQueue ()), packet_size_ (packetSize), blocked_ (false), // Initial state of the connection: unblocked, not receiving binary. active_ (true), lobby_ (new object::Lobby (object::State(*this))), parser_ (new UParser ()), active_command_ (new ast::Nary()), server_ (userver) { //FIXME: This would be better done in Lobby ctor, in Urbi maybe. lobby_->slot_set(SYMBOL(lobby), lobby_); for (int i = 0; i < MAX_ERRORSIGNALS ; ++i) error_signals_[i] = false; // initialize the connection tag used to reference local variables std::ostringstream o; o << 'U' << (long) this; connection_tag_ = o.str(); } UConnection::~UConnection () { DEBUG(("Destroying UConnection...")); delete parser_; delete send_queue_; delete recv_queue_; DEBUG(("done\n")); } UConnection& UConnection::initialize() { for (int i = 0; ::HEADER_BEFORE_CUSTOM[i]; ++i) send(::HEADER_BEFORE_CUSTOM[i], "start"); for (int i = 0; ; ++i) { char buf[1024]; server_->getCustomHeader(i, buf, sizeof buf); if (!buf[0]) break; send(buf, "start"); } for (int i = 0; ::HEADER_AFTER_CUSTOM[i]; ++i) send(::HEADER_AFTER_CUSTOM[i], "start"); { char buf[1024]; snprintf(buf, sizeof buf, "*** ID: %s\n", connection_tag_.c_str()); send(buf, "ident"); snprintf(buf, sizeof buf, "%s created", connection_tag_.c_str()); server_->echo(::DISPLAY_FORMAT, (long)this, "UConnection::initialize", buf); } server_->loadFile("CLIENT.INI", *recv_queue_); new_data_added_ = true; return *this; } UConnection& UConnection::send (const char* buf, const char* tag, bool flush) { if (tag) { std::string pref = make_prefix (tag); send_queue (pref.c_str(), pref.length()); } if (buf) { UErrorValue ret = send_queue (buf, strlen(buf)).error_get (); if (flush && ret != UFAIL) this->flush (); CONN_ERR_RET(ret); } return *this; } UConnection& UConnection::send_queue (const char *buffer, int length) { if (closing_) CONN_ERR_RET(USUCCESS); // Add to Queue send_queue_->push(buffer, length); CONN_ERR_RET(USUCCESS); } UConnection& UConnection::continue_send () { if (closing_) CONN_ERR_RET(UFAIL); # if ! defined LIBPORT_URBI_ENV_AIBO boost::mutex::scoped_lock lock(mutex_); # endif blocked_ = false; // continue_send unblocks the connection. size_t toSend = send_queue_->size(); // nb of bytes to send if (toSend > packet_size_) toSend = packet_size_; if (toSend == 0) CONN_ERR_RET(USUCCESS); char* popData = send_queue_->front(toSend); if (popData != 0) { int wasSent = effective_send ((const char*)popData, toSend); if (wasSent < 0) CONN_ERR_RET(UFAIL); else if (wasSent == 0 || send_queue_->pop(wasSent) != 0) CONN_ERR_RET(USUCCESS); } CONN_ERR_RET(UFAIL); } UConnection& UConnection::received (const char *s) { return received ((const char*) s, strlen (s)); } UConnection& UConnection::received (const char *buffer, int length) { PING(); #if ! defined LIBPORT_URBI_ENV_AIBO boost::recursive_mutex::scoped_lock serverLock(server_->mutex); #endif { // Lock the connection. #if ! defined LIBPORT_URBI_ENV_AIBO boost::mutex::scoped_lock lock(mutex_); #endif recv_queue_->push(buffer, length); } #if ! defined LIBPORT_URBI_ENV_AIBO boost::try_mutex::scoped_try_lock treeLock(tree_mutex_, false); #endif #if ! defined LIBPORT_URBI_ENV_AIBO if (!treeLock.try_lock()) #endif { new_data_added_ = true; //server will call us again right after work CONN_ERR_RET(USUCCESS); } UParser& p = parser_get(); PING(); if (p.ast_get ()) { // This chunk of code seems suspect in k2, meanwhile: pabort ("SHOULD NEVER BE HERE"); PING(); //reentrency trouble #if ! defined LIBPORT_URBI_ENV_AIBO treeLock.unlock(); #endif CONN_ERR_RET(USUCCESS); } // Starts processing receiving_ = true; // active_command_: The command to be executed (root of the AST). // passert (*active_command_, active_command_->empty()); // If active_command_ is not empty, a runner is still alive, so set // obstructed to true. This is a temporary fix to avoid having several // runners on the same Nary, until runners become managed outside UConnection. bool obstructed = !active_command_->empty(); // Loop to get all the commands that are ready to be executed. for (std::string command = recv_queue_->pop_command(); !command.empty(); command = recv_queue_->pop_command()) { server_->setSystemCommand (false); int result = p.process (command); passert (result, result != -1); p.process_errors(active_command_); server_->setSystemCommand (true); if (ast::Nary* ast = p.ast_take().release()) { ECHO ("parsed: {{{" << *ast << "}}}"); // Append to the current list. active_command_->splice_back(*ast); ECHO ("appended: " << *active_command_ << "}}}"); } else { std::cerr << make_prefix("error") << "the parser returned NULL" << std::endl; // FIXME: Is this line usefull ? server_->error(::DISPLAY_FORMAT, (long) this, "UConnection::received", "the parser returned NULL\n"); } } // FIXME: recv_queue_->clear(); // Execute the new command. if (!obstructed) execute (); receiving_ = false; p.ast_set (0); #if ! defined LIBPORT_URBI_ENV_AIBO treeLock.unlock(); #endif CONN_ERR_RET(USUCCESS); } UConnection& UConnection::send (UErrorCode n) { const char* msg = message (UERRORCODE, n); UErrorValue result = send(msg, "error").error_get (); if (result == USUCCESS) { char buf[80]; strncpy (buf, msg, sizeof buf); if (strlen (msg) - 1 < sizeof buf) //remove the '\n' at the end. buf[strlen(msg)-1] = 0; server_->error(::DISPLAY_FORMAT, (long)this, "UConnection::error", buf); } CONN_ERR_RET(result); } UConnection& UConnection::send (UWarningCode n) { const char* msg = message (UWARNINGCODE, n); UErrorValue result = send(msg, "warning").error_get (); if (result == USUCCESS) { char buf[80]; strncpy (buf, msg, sizeof buf); if (strlen (msg) - 1 < sizeof buf) //remove the '\n' at the end. buf[strlen(msg)-1] = 0; server_->echoKey("WARNG", ::DISPLAY_FORMAT, (long)this, "UConnection::warning", buf); } CONN_ERR_RET(result); } UConnection& UConnection::send (object::rObject result, const char* tag, const char* p) { // "Display" the result. std::ostringstream os; if (p) os << p; result->print (os); if (!os.str ().empty ()) { std::string prefix = make_prefix (tag); send (prefix.c_str (), 0, false); send (os.str ().c_str (), 0, false); endline (); } return *this; } void UConnection::new_result (object::rObject result) { // The prefix should be (getTag().c_str()) instead of 0. // FIXME: the prefix should not be built manually. send (result, 0, 0); } UConnection& UConnection::execute () { PING (); if (active_command_->empty()) return *this; ECHO("Command is: {{{" << *active_command_ << "}}}"); // Our active_command_ is a ast::Nary, we must now "tell" it that // it's a top-level Nary so that it can send its results back to the // UConnection. It also entitles the Runner to free this Nary when // it has evaluated it. active_command_->toplevel_set (true); // FIXME: There is an obvious memory leak here runner::Runner* runner = new runner::Runner(lobby_, lobby_, ::urbiserver->getScheduler (), active_command_); runner->start_job (); PING (); return *this; } std::string UConnection::make_prefix (const char* tag) const { std::ostringstream o; char fill = o.fill('0'); o << '[' << std::setw(8) << server_->lastTime(); o.fill(fill); if (tag && strlen(tag)) o << ':' << tag; o << "] "; return o.str (); } bool UConnection::has_pending_command () const { return !active_command_->empty(); } void UConnection::drop_pending_commands () { active_command_->clear(); } bool UConnection::send_queue_empty () const { return send_queue_->empty(); } <commit_msg>Use std::min.<commit_after>/*! \file uconnection.cc ******************************************************************************* File: uconnection.cc\n Implementation of the UConnection class. This file is part of %URBI Kernel, version __kernelversion__\n (c) Jean-Christophe Baillie, 2004-2005. Permission to use, copy, modify, and redistribute this software for non-commercial use is hereby granted. This software is provided "as is" without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of fitness for a particular purpose. For more information, comments, bug reports: http://www.urbiforge.net **************************************************************************** */ #define ENABLE_DEBUG_TRACES #include "libport/compiler.hh" #include "libport/config.h" #include "libport/cstring" #include "libport/cstdio" #include <cassert> #include <cstdarg> #include <sstream> #include <iomanip> #include <boost/lexical_cast.hpp> #include <boost/foreach.hpp> #include "libport/assert.hh" #include "libport/ref-pt.hh" #include "kernel/userver.hh" #include "kernel/uconnection.hh" #include "ast/ast.hh" #include "ast/nary.hh" #include "object/object.hh" #include "object/atom.hh" #include "runner/fwd.hh" #include "runner/runner.hh" #include "parser/uparser.hh" #include "ubanner.hh" #include "uqueue.hh" #include "object/atom.hh" // object::Lobby UConnection::UConnection (UServer* userver,size_t packetSize) : uerror_ (USUCCESS), client_ip_ (0), closing_ (false), receiving_ (false), new_data_added_ (false), send_queue_ (new UQueue ()), recv_queue_ (new UQueue ()), packet_size_ (packetSize), blocked_ (false), // Initial state of the connection: unblocked, not receiving binary. active_ (true), lobby_ (new object::Lobby (object::State(*this))), parser_ (new UParser ()), active_command_ (new ast::Nary()), server_ (userver) { //FIXME: This would be better done in Lobby ctor, in Urbi maybe. lobby_->slot_set(SYMBOL(lobby), lobby_); for (int i = 0; i < MAX_ERRORSIGNALS ; ++i) error_signals_[i] = false; // initialize the connection tag used to reference local variables std::ostringstream o; o << 'U' << (long) this; connection_tag_ = o.str(); } UConnection::~UConnection () { DEBUG(("Destroying UConnection...")); delete parser_; delete send_queue_; delete recv_queue_; DEBUG(("done\n")); } UConnection& UConnection::initialize() { for (int i = 0; ::HEADER_BEFORE_CUSTOM[i]; ++i) send(::HEADER_BEFORE_CUSTOM[i], "start"); for (int i = 0; ; ++i) { char buf[1024]; server_->getCustomHeader(i, buf, sizeof buf); if (!buf[0]) break; send(buf, "start"); } for (int i = 0; ::HEADER_AFTER_CUSTOM[i]; ++i) send(::HEADER_AFTER_CUSTOM[i], "start"); { char buf[1024]; snprintf(buf, sizeof buf, "*** ID: %s\n", connection_tag_.c_str()); send(buf, "ident"); snprintf(buf, sizeof buf, "%s created", connection_tag_.c_str()); server_->echo(::DISPLAY_FORMAT, (long)this, "UConnection::initialize", buf); } server_->loadFile("CLIENT.INI", *recv_queue_); new_data_added_ = true; return *this; } UConnection& UConnection::send (const char* buf, const char* tag, bool flush) { if (tag) { std::string pref = make_prefix (tag); send_queue (pref.c_str(), pref.length()); } if (buf) { UErrorValue ret = send_queue (buf, strlen(buf)).error_get (); if (flush && ret != UFAIL) this->flush (); CONN_ERR_RET(ret); } return *this; } UConnection& UConnection::send_queue (const char* buffer, int length) { if (closing_) CONN_ERR_RET(USUCCESS); // Add to Queue send_queue_->push(buffer, length); CONN_ERR_RET(USUCCESS); } UConnection& UConnection::continue_send () { if (closing_) CONN_ERR_RET(UFAIL); # if ! defined LIBPORT_URBI_ENV_AIBO boost::mutex::scoped_lock lock(mutex_); # endif blocked_ = false; // continue_send unblocks the connection. // nb of bytes to send. size_t toSend = std::min(packet_size_, send_queue_->size()); ECHO(toSend); if (!toSend) CONN_ERR_RET(USUCCESS); if (char* popData = send_queue_->front(toSend)) { ECHO(popData); int wasSent = effective_send (popData, toSend); if (wasSent < 0) CONN_ERR_RET(UFAIL); else if (wasSent == 0 || send_queue_->pop(wasSent) != 0) CONN_ERR_RET(USUCCESS); } CONN_ERR_RET(UFAIL); } UConnection& UConnection::received (const char *s) { return received ((const char*) s, strlen (s)); } UConnection& UConnection::received (const char *buffer, int length) { PING(); #if ! defined LIBPORT_URBI_ENV_AIBO boost::recursive_mutex::scoped_lock serverLock(server_->mutex); #endif { // Lock the connection. #if ! defined LIBPORT_URBI_ENV_AIBO boost::mutex::scoped_lock lock(mutex_); #endif recv_queue_->push(buffer, length); } #if ! defined LIBPORT_URBI_ENV_AIBO boost::try_mutex::scoped_try_lock treeLock(tree_mutex_, false); #endif #if ! defined LIBPORT_URBI_ENV_AIBO if (!treeLock.try_lock()) #endif { new_data_added_ = true; //server will call us again right after work CONN_ERR_RET(USUCCESS); } UParser& p = parser_get(); PING(); if (p.ast_get ()) { // This chunk of code seems suspect in k2, meanwhile: pabort ("SHOULD NEVER BE HERE"); PING(); //reentrency trouble #if ! defined LIBPORT_URBI_ENV_AIBO treeLock.unlock(); #endif CONN_ERR_RET(USUCCESS); } // Starts processing receiving_ = true; // active_command_: The command to be executed (root of the AST). // passert (*active_command_, active_command_->empty()); // If active_command_ is not empty, a runner is still alive, so set // obstructed to true. This is a temporary fix to avoid having several // runners on the same Nary, until runners become managed outside UConnection. bool obstructed = !active_command_->empty(); // Loop to get all the commands that are ready to be executed. for (std::string command = recv_queue_->pop_command(); !command.empty(); command = recv_queue_->pop_command()) { server_->setSystemCommand (false); int result = p.process (command); passert (result, result != -1); p.process_errors(active_command_); server_->setSystemCommand (true); if (ast::Nary* ast = p.ast_take().release()) { ECHO ("parsed: {{{" << *ast << "}}}"); // Append to the current list. active_command_->splice_back(*ast); ECHO ("appended: " << *active_command_ << "}}}"); } else { std::cerr << make_prefix("error") << "the parser returned NULL" << std::endl; // FIXME: Is this line usefull ? server_->error(::DISPLAY_FORMAT, (long) this, "UConnection::received", "the parser returned NULL\n"); } } // FIXME: recv_queue_->clear(); // Execute the new command. if (!obstructed) execute (); receiving_ = false; p.ast_set (0); #if ! defined LIBPORT_URBI_ENV_AIBO treeLock.unlock(); #endif CONN_ERR_RET(USUCCESS); } UConnection& UConnection::send (UErrorCode n) { const char* msg = message (UERRORCODE, n); UErrorValue result = send(msg, "error").error_get (); if (result == USUCCESS) { char buf[80]; strncpy (buf, msg, sizeof buf); if (strlen (msg) - 1 < sizeof buf) //remove the '\n' at the end. buf[strlen(msg)-1] = 0; server_->error(::DISPLAY_FORMAT, (long)this, "UConnection::error", buf); } CONN_ERR_RET(result); } UConnection& UConnection::send (UWarningCode n) { const char* msg = message (UWARNINGCODE, n); UErrorValue result = send(msg, "warning").error_get (); if (result == USUCCESS) { char buf[80]; strncpy (buf, msg, sizeof buf); if (strlen (msg) - 1 < sizeof buf) //remove the '\n' at the end. buf[strlen(msg)-1] = 0; server_->echoKey("WARNG", ::DISPLAY_FORMAT, (long)this, "UConnection::warning", buf); } CONN_ERR_RET(result); } UConnection& UConnection::send (object::rObject result, const char* tag, const char* p) { // "Display" the result. std::ostringstream os; if (p) os << p; result->print (os); if (!os.str ().empty ()) { std::string prefix = make_prefix (tag); send (prefix.c_str (), 0, false); send (os.str ().c_str (), 0, false); endline (); } return *this; } void UConnection::new_result (object::rObject result) { // The prefix should be (getTag().c_str()) instead of 0. // FIXME: the prefix should not be built manually. send (result, 0, 0); } UConnection& UConnection::execute () { PING (); if (active_command_->empty()) return *this; ECHO("Command is: {{{" << *active_command_ << "}}}"); // Our active_command_ is a ast::Nary, we must now "tell" it that // it's a top-level Nary so that it can send its results back to the // UConnection. It also entitles the Runner to free this Nary when // it has evaluated it. active_command_->toplevel_set (true); // FIXME: There is an obvious memory leak here runner::Runner* runner = new runner::Runner(lobby_, lobby_, ::urbiserver->getScheduler (), active_command_); runner->start_job (); PING (); return *this; } std::string UConnection::make_prefix (const char* tag) const { std::ostringstream o; char fill = o.fill('0'); o << '[' << std::setw(8) << server_->lastTime(); o.fill(fill); if (tag && strlen(tag)) o << ':' << tag; o << "] "; return o.str (); } bool UConnection::has_pending_command () const { return !active_command_->empty(); } void UConnection::drop_pending_commands () { active_command_->clear(); } bool UConnection::send_queue_empty () const { return send_queue_->empty(); } <|endoftext|>
<commit_before>/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "blob_handler.hpp" #include "blob_errors.hpp" #include "crc.hpp" #include "ipmi_errors.hpp" #include <array> #include <cstring> namespace host_tool { namespace { const std::array<std::uint8_t, 3> ipmiPhosphorOen = {0xcf, 0xc2, 0x00}; } std::vector<std::uint8_t> BlobHandler::sendIpmiPayload(BlobOEMCommands command, const std::vector<std::uint8_t>& payload) { std::vector<std::uint8_t> request, reply; std::copy(ipmiPhosphorOen.begin(), ipmiPhosphorOen.end(), std::back_inserter(request)); request.push_back(command); if (payload.size() > 0) { /* Grow the vector to hold the bytes. */ request.reserve(request.size() + sizeof(std::uint16_t)); /* CRC required. */ std::uint16_t crc = generateCrc(payload); std::uint8_t* src = reinterpret_cast<std::uint8_t*>(&crc); std::copy(src, src + sizeof(crc), std::back_inserter(request)); /* Copy the payload. */ std::copy(payload.begin(), payload.end(), std::back_inserter(request)); } try { reply = ipmi->sendPacket(request); } catch (const IpmiException& e) { throw BlobException(e.what()); } /* IPMI_CC was OK, and it returned no bytes, so let's be happy with that for * now. */ if (reply.size() == 0) { return reply; } std::size_t headerSize = ipmiPhosphorOen.size() + sizeof(std::uint16_t); /* This cannot be a response because it's smaller than the smallest * response. */ if (reply.size() < headerSize) { throw BlobException("Invalid response length"); } /* Verify the OEN. */ if (std::memcmp(ipmiPhosphorOen.data(), reply.data(), ipmiPhosphorOen.size()) != 0) { throw BlobException("Invalid OEN received"); } /* Validate CRC. */ std::uint16_t crc; auto ptr = reinterpret_cast<std::uint8_t*>(&crc); std::memcpy(ptr, &reply[ipmiPhosphorOen.size()], sizeof(crc)); for (const auto& byte : reply) { std::fprintf(stderr, "0x%02x ", byte); } std::fprintf(stderr, "\n"); std::vector<std::uint8_t> bytes; bytes.insert(bytes.begin(), reply.begin() + headerSize, reply.end()); auto computed = generateCrc(bytes); if (crc != computed) { std::fprintf(stderr, "Invalid CRC, received: 0x%x, computed: 0x%x\n", crc, computed); throw BlobException("Invalid CRC on received data."); } return bytes; } int BlobHandler::getBlobCount() { std::uint32_t count; try { auto resp = sendIpmiPayload(BlobOEMCommands::bmcBlobGetCount, {}); if (resp.size() != sizeof(count)) { return 0; } /* LE to LE (need to make this portable as some point. */ std::memcpy(&count, resp.data(), sizeof(count)); } catch (const BlobException& b) { return 0; } std::fprintf(stderr, "BLOB Count: %d\n", count); return count; } std::string BlobHandler::enumerateBlob(std::uint32_t index) { std::vector<std::uint8_t> payload; std::uint8_t* data = reinterpret_cast<std::uint8_t*>(&index); std::copy(data, data + sizeof(std::uint32_t), std::back_inserter(payload)); try { auto resp = sendIpmiPayload(BlobOEMCommands::bmcBlobEnumerate, payload); return (resp.size() > 0) ? std::string(&resp[0], &resp[resp.size() - 1]) : ""; } catch (const BlobException& b) { return ""; } } std::vector<std::string> BlobHandler::getBlobList() { std::vector<std::string> list; int blobCount = getBlobCount(); for (int i = 0; i < blobCount; i++) { auto name = enumerateBlob(i); /* Currently ignore failures. */ if (!name.empty()) { list.push_back(name); } } return list; } StatResponse BlobHandler::getStat(const std::string& id) { StatResponse meta; std::vector<std::uint8_t> name, resp; std::copy(id.begin(), id.end(), std::back_inserter(name)); name.push_back(0x00); /* need to add nul-terminator. */ try { resp = sendIpmiPayload(BlobOEMCommands::bmcBlobStat, name); } catch (const BlobException& b) { throw; } std::memcpy(&meta.blob_state, &resp[0], sizeof(meta.blob_state)); std::memcpy(&meta.size, &resp[sizeof(meta.blob_state)], sizeof(meta.size)); int offset = sizeof(meta.blob_state) + sizeof(meta.size); std::uint8_t len = resp[offset]; if (len > 0) { std::copy(&resp[offset + 1], &resp[resp.size()], std::back_inserter(meta.metadata)); } return meta; } std::uint16_t BlobHandler::openBlob(const std::string& id, blobs::FirmwareBlobHandler::UpdateFlags handlerFlags) { std::uint16_t session; std::vector<std::uint8_t> request, resp; std::uint16_t flags = blobs::FirmwareBlobHandler::UpdateFlags::openWrite | handlerFlags; auto addrFlags = reinterpret_cast<std::uint8_t*>(&flags); std::copy(addrFlags, addrFlags + sizeof(flags), std::back_inserter(request)); std::copy(id.begin(), id.end(), std::back_inserter(request)); request.push_back(0x00); /* need to add nul-terminator. */ try { resp = sendIpmiPayload(BlobOEMCommands::bmcBlobOpen, request); } catch (const BlobException& b) { throw; } if (resp.size() != sizeof(session)) { throw BlobException("Did not receive session."); } std::memcpy(&session, resp.data(), sizeof(session)); return session; } void BlobHandler::closeBlob(std::uint16_t session) { std::vector<std::uint8_t> request, resp; auto addrSession = reinterpret_cast<std::uint8_t*>(&session); std::copy(addrSession, addrSession + sizeof(session), std::back_inserter(request)); try { resp = sendIpmiPayload(BlobOEMCommands::bmcBlobClose, request); } catch (const BlobException& b) { std::fprintf(stderr, "Received failure on close: %s\n", b.what()); } return; } } // namespace host_tool <commit_msg>bugfix: tools: blob_handler: properly handle smallest reply<commit_after>/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "blob_handler.hpp" #include "blob_errors.hpp" #include "crc.hpp" #include "ipmi_errors.hpp" #include <array> #include <cstring> namespace host_tool { namespace { const std::array<std::uint8_t, 3> ipmiPhosphorOen = {0xcf, 0xc2, 0x00}; } std::vector<std::uint8_t> BlobHandler::sendIpmiPayload(BlobOEMCommands command, const std::vector<std::uint8_t>& payload) { std::vector<std::uint8_t> request, reply, bytes; std::copy(ipmiPhosphorOen.begin(), ipmiPhosphorOen.end(), std::back_inserter(request)); request.push_back(command); if (payload.size() > 0) { /* Grow the vector to hold the bytes. */ request.reserve(request.size() + sizeof(std::uint16_t)); /* CRC required. */ std::uint16_t crc = generateCrc(payload); std::uint8_t* src = reinterpret_cast<std::uint8_t*>(&crc); std::copy(src, src + sizeof(crc), std::back_inserter(request)); /* Copy the payload. */ std::copy(payload.begin(), payload.end(), std::back_inserter(request)); } try { reply = ipmi->sendPacket(request); } catch (const IpmiException& e) { throw BlobException(e.what()); } /* IPMI_CC was OK, and it returned no bytes, so let's be happy with that for * now. */ if (reply.size() == 0) { return reply; } /* This cannot be a response because it's smaller than the smallest * response. */ if (reply.size() < ipmiPhosphorOen.size()) { throw BlobException("Invalid response length"); } /* Verify the OEN. */ if (std::memcmp(ipmiPhosphorOen.data(), reply.data(), ipmiPhosphorOen.size()) != 0) { throw BlobException("Invalid OEN received"); } /* In this case there was no data, as there was no CRC. */ std::size_t headerSize = ipmiPhosphorOen.size() + sizeof(std::uint16_t); if (reply.size() < headerSize) { return {}; } /* Validate CRC. */ std::uint16_t crc; auto ptr = reinterpret_cast<std::uint8_t*>(&crc); std::memcpy(ptr, &reply[ipmiPhosphorOen.size()], sizeof(crc)); for (const auto& byte : reply) { std::fprintf(stderr, "0x%02x ", byte); } std::fprintf(stderr, "\n"); bytes.insert(bytes.begin(), reply.begin() + headerSize, reply.end()); auto computed = generateCrc(bytes); if (crc != computed) { std::fprintf(stderr, "Invalid CRC, received: 0x%x, computed: 0x%x\n", crc, computed); throw BlobException("Invalid CRC on received data."); } return bytes; } int BlobHandler::getBlobCount() { std::uint32_t count; try { auto resp = sendIpmiPayload(BlobOEMCommands::bmcBlobGetCount, {}); if (resp.size() != sizeof(count)) { return 0; } /* LE to LE (need to make this portable as some point. */ std::memcpy(&count, resp.data(), sizeof(count)); } catch (const BlobException& b) { return 0; } std::fprintf(stderr, "BLOB Count: %d\n", count); return count; } std::string BlobHandler::enumerateBlob(std::uint32_t index) { std::vector<std::uint8_t> payload; std::uint8_t* data = reinterpret_cast<std::uint8_t*>(&index); std::copy(data, data + sizeof(std::uint32_t), std::back_inserter(payload)); try { auto resp = sendIpmiPayload(BlobOEMCommands::bmcBlobEnumerate, payload); return (resp.size() > 0) ? std::string(&resp[0], &resp[resp.size() - 1]) : ""; } catch (const BlobException& b) { return ""; } } std::vector<std::string> BlobHandler::getBlobList() { std::vector<std::string> list; int blobCount = getBlobCount(); for (int i = 0; i < blobCount; i++) { auto name = enumerateBlob(i); /* Currently ignore failures. */ if (!name.empty()) { list.push_back(name); } } return list; } StatResponse BlobHandler::getStat(const std::string& id) { StatResponse meta; std::vector<std::uint8_t> name, resp; std::copy(id.begin(), id.end(), std::back_inserter(name)); name.push_back(0x00); /* need to add nul-terminator. */ try { resp = sendIpmiPayload(BlobOEMCommands::bmcBlobStat, name); } catch (const BlobException& b) { throw; } std::memcpy(&meta.blob_state, &resp[0], sizeof(meta.blob_state)); std::memcpy(&meta.size, &resp[sizeof(meta.blob_state)], sizeof(meta.size)); int offset = sizeof(meta.blob_state) + sizeof(meta.size); std::uint8_t len = resp[offset]; if (len > 0) { std::copy(&resp[offset + 1], &resp[resp.size()], std::back_inserter(meta.metadata)); } return meta; } std::uint16_t BlobHandler::openBlob(const std::string& id, blobs::FirmwareBlobHandler::UpdateFlags handlerFlags) { std::uint16_t session; std::vector<std::uint8_t> request, resp; std::uint16_t flags = blobs::FirmwareBlobHandler::UpdateFlags::openWrite | handlerFlags; auto addrFlags = reinterpret_cast<std::uint8_t*>(&flags); std::copy(addrFlags, addrFlags + sizeof(flags), std::back_inserter(request)); std::copy(id.begin(), id.end(), std::back_inserter(request)); request.push_back(0x00); /* need to add nul-terminator. */ try { resp = sendIpmiPayload(BlobOEMCommands::bmcBlobOpen, request); } catch (const BlobException& b) { throw; } if (resp.size() != sizeof(session)) { throw BlobException("Did not receive session."); } std::memcpy(&session, resp.data(), sizeof(session)); return session; } void BlobHandler::closeBlob(std::uint16_t session) { std::vector<std::uint8_t> request, resp; auto addrSession = reinterpret_cast<std::uint8_t*>(&session); std::copy(addrSession, addrSession + sizeof(session), std::back_inserter(request)); try { resp = sendIpmiPayload(BlobOEMCommands::bmcBlobClose, request); } catch (const BlobException& b) { std::fprintf(stderr, "Received failure on close: %s\n", b.what()); } return; } } // namespace host_tool <|endoftext|>
<commit_before>#include <gmock/gmock.h> #include <gtest/gtest.h> #include <babylon/core/future_then.h> #define USE_TIMINGS 0 inline std::string thread_id_string(const std::thread::id& threadId) { std::stringstream ss; ss << threadId; return ss.str(); } inline size_t string_counter(const std::string& s) { #if USE_TIMINGS std::this_thread::sleep_for(std::chrono::seconds(1)); #endif return s.size(); } std::size_t string_count_accumulator(const std::vector<std::string>& strings) { std::vector<std::future<size_t>> calcs; for (auto&& s : strings) { calcs.push_back(std::async(std::launch::async, [&s]() -> size_t { return string_counter(s); })); } std::size_t total = 0; for (auto&& fut : calcs) { total += fut.get(); } return total; } TEST(TestFutureThen, AsyncContinuation) { using namespace BABYLON; #ifndef __APPLE__ // TODO: these tests may fail under OSX (with a 30% chance of failure) // thread_id might sometimes be the same (even if forcing std::launch::async policy) { auto task1 = std::async([] { return thread_id_string(std::this_thread::get_id()); }); auto task2 = then(task1, [](std::future<std::string>& f) { auto currentThreadId = thread_id_string(std::this_thread::get_id()); EXPECT_NE(f.get(), currentThreadId); return currentThreadId; }); auto task3 = then(task2, [](std::future<std::string>& f) { auto currentThreadId = thread_id_string(std::this_thread::get_id()); EXPECT_NE(f.get(), currentThreadId); return currentThreadId; }); task3.wait(); } #endif { auto task1 = std::async(std::launch::async, [] { return 1; }); auto task2 = then(task1, std::launch::async, [](std::future<int>& f) { return f.get() + 2; }); auto task3 = then(task2, std::launch::async, [](std::future<int>& f) { return f.get() + 3; }); // Check result received from continuation in parent task EXPECT_EQ(task3.get(), 6); } { #if USE_TIMINGS // Get Start Time std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); #endif auto task1 = std::async(std::launch::async, [] { return string_count_accumulator({"this", "is", "task1"}); }); auto task2 = then(task1, std::launch::async, [](std::future<std::size_t>& f) { return f.get() + string_count_accumulator({"and", "this", "is", "task2"}); }); #if USE_TIMINGS // Get End Time auto end = std::chrono::system_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(end - start) .count(); std::cout << "Total Time Taken = " << diff << " milliseconds\n"; #endif // Check result received from continuation in parent task EXPECT_EQ(task2.get(), 25); } } <commit_msg>TEST(TestFutureThen, AsyncContinuation) disabled under MSVC ansd apple<commit_after>#include <gmock/gmock.h> #include <gtest/gtest.h> #include <babylon/core/future_then.h> #define USE_TIMINGS 0 inline std::string thread_id_string(const std::thread::id& threadId) { std::stringstream ss; ss << threadId; return ss.str(); } inline size_t string_counter(const std::string& s) { #if USE_TIMINGS std::this_thread::sleep_for(std::chrono::seconds(1)); #endif return s.size(); } std::size_t string_count_accumulator(const std::vector<std::string>& strings) { std::vector<std::future<size_t>> calcs; for (auto&& s : strings) { calcs.push_back(std::async(std::launch::async, [&s]() -> size_t { return string_counter(s); })); } std::size_t total = 0; for (auto&& fut : calcs) { total += fut.get(); } return total; } TEST(TestFutureThen, AsyncContinuation) { using namespace BABYLON; #if !defined(__APPLE__) && !defined(_MSC_VER) // TODO: these tests may fail under OSX and MSVC // thread_id might sometimes be the same (even if forcing std::launch::async policy) // However, it seems acceptable that a "then" action reuses the seme thread id. Am I wrong? { auto task1 = std::async([] { return thread_id_string(std::this_thread::get_id()); }); auto task2 = then(task1, [](std::future<std::string>& f) { auto currentThreadId = thread_id_string(std::this_thread::get_id()); EXPECT_NE(f.get(), currentThreadId); return currentThreadId; }); auto task3 = then(task2, [](std::future<std::string>& f) { auto currentThreadId = thread_id_string(std::this_thread::get_id()); EXPECT_NE(f.get(), currentThreadId); return currentThreadId; }); task3.wait(); } #endif { auto task1 = std::async(std::launch::async, [] { return 1; }); auto task2 = then(task1, std::launch::async, [](std::future<int>& f) { return f.get() + 2; }); auto task3 = then(task2, std::launch::async, [](std::future<int>& f) { return f.get() + 3; }); // Check result received from continuation in parent task EXPECT_EQ(task3.get(), 6); } { #if USE_TIMINGS // Get Start Time std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); #endif auto task1 = std::async(std::launch::async, [] { return string_count_accumulator({"this", "is", "task1"}); }); auto task2 = then(task1, std::launch::async, [](std::future<std::size_t>& f) { return f.get() + string_count_accumulator({"and", "this", "is", "task2"}); }); #if USE_TIMINGS // Get End Time auto end = std::chrono::system_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(end - start) .count(); std::cout << "Total Time Taken = " << diff << " milliseconds\n"; #endif // Check result received from continuation in parent task EXPECT_EQ(task2.get(), 25); } } <|endoftext|>
<commit_before>#include <kv/Heine.hpp> #include <kv/qAiry.hpp> #include <kv/qBessel.hpp> #include <cmath> #include <iostream> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/io.hpp> typedef kv::interval<double> itv; typedef kv::complex< kv::interval<double> > cp; using namespace std; namespace ub = boost::numeric::ublas; int main() { cout.precision(17); int n=20; itv nu,q; ub::vector< itv > x(100); q="0.7"; nu=1.5; x(0)=4.5; x(1)=4.45; for(int i=1;i<=n;i++){ x(i+1)=x(i)-kv::Jackson2(itv(x(i)),itv(nu),itv(q))*(x(i)-x(i-1)) /(kv::Jackson2(itv(x(i)),itv(nu),itv(q))-kv::Jackson2(itv(x(i-1)),itv(nu),itv(q))); cout<<x(i+1)<<endl; cout<<"value of J2"<<kv::Jackson2(itv(x(i+1)),itv(nu),itv(q))<<endl; } } <commit_msg>Update J2secant.cc<commit_after>#include <kv/Heine.hpp> #include <kv/qAiry.hpp> #include <kv/qBessel.hpp> #include <cmath> #include <iostream> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/io.hpp> typedef kv::interval<double> itv; typedef kv::complex< kv::interval<double> > cp; using namespace std; namespace ub = boost::numeric::ublas; int main() { cout.precision(17); int n=20; itv nu,q; ub::vector< itv > x(100); q="0.7"; nu=1.5; x(0)=4.5; x(1)=4.45; for(int i=1;i<=n;i++){ x(i+1)=x(i)-kv::Jackson2(itv(x(i)),itv(nu),itv(q))*(x(i)-x(i-1)) /(kv::Jackson2(itv(x(i)),itv(nu),itv(q))-kv::Jackson2(itv(x(i-1)),itv(nu),itv(q))); cout<<x(i+1)<<endl; cout<<"value of J2 inf"<<kv::Jackson2(itv(x(i+1).lower()),itv(nu),itv(q))<<endl; cout<<"value of J2 sup"<<kv::Jackson2(itv(x(i+1).upper()),itv(nu),itv(q))<<endl; cout<<"value of J2 mid"<<kv::Jackson2(itv(mid(x(i+1))),itv(nu),itv(q))<<endl; } } <|endoftext|>
<commit_before>#include "search_panel.hpp" #include "draw_widget.hpp" #include "../map/settings.hpp" #include "../std/bind.hpp" #include <QtCore/QTimer> #include <QtGui/QHeaderView> #include <QtGui/QTableWidget> #include <QtGui/QLineEdit> #include <QtGui/QVBoxLayout> #include <QtGui/QHBoxLayout> #include <QtGui/QPushButton> #include <QtGui/QBitmap> namespace qt { SearchPanel::SearchPanel(DrawWidget * drawWidget, QWidget * parent) : QWidget(parent), m_pDrawWidget(drawWidget), m_busyIcon(":/ui/busy.png"), m_queryId(0) { m_pEditor = new QLineEdit(this); connect(m_pEditor, SIGNAL(textChanged(QString const &)), this, SLOT(OnSearchTextChanged(QString const &))); m_pTable = new QTableWidget(0, 4, this); m_pTable->setFocusPolicy(Qt::NoFocus); m_pTable->setAlternatingRowColors(true); m_pTable->setShowGrid(false); m_pTable->setSelectionBehavior(QAbstractItemView::SelectRows); m_pTable->verticalHeader()->setVisible(false); m_pTable->horizontalHeader()->setVisible(false); m_pTable->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents); connect(m_pTable, SIGNAL(cellClicked(int, int)), this, SLOT(OnSearchPanelItemClicked(int,int))); m_pClearButton = new QPushButton(this); connect(m_pClearButton, SIGNAL(pressed()), this, SLOT(OnClearButton())); m_pClearButton->setVisible(false); m_pClearButton->setFocusPolicy(Qt::NoFocus); m_pAnimationTimer = new QTimer(this); connect(m_pAnimationTimer, SIGNAL(timeout()), this, SLOT(OnAnimationTimer())); QHBoxLayout * horizontalLayout = new QHBoxLayout(); horizontalLayout->addWidget(m_pEditor); horizontalLayout->addWidget(m_pClearButton); QVBoxLayout * verticalLayout = new QVBoxLayout(); verticalLayout->addLayout(horizontalLayout); verticalLayout->addWidget(m_pTable); setLayout(verticalLayout); // for multithreading support CHECK(connect(this, SIGNAL(SearchResultSignal(ResultT *, int)), this, SLOT(OnSearchResult(ResultT *, int)), Qt::QueuedConnection), ()); setFocusPolicy(Qt::StrongFocus); setFocusProxy(m_pEditor); } template<class T> static void ClearVector(vector<T *> & v) { for(size_t i = 0; i < v.size(); ++i) delete v[i]; v.clear(); } SearchPanel::~SearchPanel() { ClearVector(m_results); } void SearchPanel::SearchResultThreadFunc(ResultT const & result, int queryId) { if (queryId == m_queryId) emit SearchResultSignal(new ResultT(result), queryId); } namespace { QTableWidgetItem * create_item(QString const & s) { QTableWidgetItem * item = new QTableWidgetItem(s); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); return item; } QString format_distance_impl(double m, bool & drawDir, char const * high, char const * low, double highF, double lowF) { double const lowV = m / lowF; drawDir = true; if (lowV < 1.0) { drawDir = false; return (QString::fromAscii("0") + QString::fromAscii(low)); } if (m >= highF) return QString("%1").arg(m / highF, 0, 'f', 1) + QString::fromAscii(high); else return QString("%1").arg(lowV, 0, 'f', 0) + QString::fromAscii(low); } QString format_distance(double m, bool & drawDir) { using namespace Settings; Units u; if (!Settings::Get("Units", u)) u = Metric; switch (u) { case Yard: return format_distance_impl(m, drawDir, " mi", " yd", 1609.344, 0.9144); case Foot: return format_distance_impl(m, drawDir, " mi", " ft", 1609.344, 0.3048); default: return format_distance_impl(m, drawDir, " km", " m", 1000.0, 1.0); } } QIcon draw_direction(double a) { int const dim = 64; QPixmap pm(dim, dim); QBitmap mask(dim, dim); mask.clear(); pm.setMask(mask); QPainter painter(&pm); painter.setBackgroundMode(Qt::TransparentMode); QMatrix m; m.translate(dim/2, dim/2); m.rotate(-a / math::pi * 180.0); m.translate(-dim/2, -dim/2); typedef QPointF P; QPolygonF poly(5); poly[0] = P(dim/3, dim/2); poly[1] = P(0, dim/2 - dim/3); poly[2] = P(dim, dim/2); poly[3] = P(0, dim/2 + dim/3); poly[4] = P(dim/3, dim/2); painter.setBrush(Qt::black); painter.drawPolygon(m.map(poly)); return pm; } } void SearchPanel::OnSearchResult(ResultT * res, int queryId) { if (queryId != m_queryId) return; if (!res->IsEndMarker()) { int const rowCount = m_pTable->rowCount(); m_pTable->insertRow(rowCount); m_pTable->setItem(rowCount, 1, create_item(QString::fromUtf8(res->GetString()))); if (res->GetResultType() == ResultT::RESULT_FEATURE) { m_pTable->setItem(rowCount, 0, create_item(QString::fromUtf8(res->GetFetureTypeAsString().c_str()))); bool drawDir; m_pTable->setItem(rowCount, 2, create_item(format_distance(res->GetDistanceFromCenter(), drawDir))); if (drawDir) { QTableWidgetItem * item = new QTableWidgetItem(draw_direction(res->GetDirectionFromCenter()), QString()); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); m_pTable->setItem(rowCount, 3, item); } } m_results.push_back(res); } else { // last element delete res; // stop search busy indicator m_pAnimationTimer->stop(); m_pClearButton->setIcon(QIcon(":/ui/x.png")); } } void SearchPanel::OnSearchTextChanged(QString const & str) { // clear old results m_pTable->clear(); m_pTable->setRowCount(0); ClearVector(m_results); ++m_queryId; QString const normalized = str.normalized(QString::NormalizationForm_KC); if (!normalized.isEmpty()) { m_pDrawWidget->Search(normalized.toUtf8().constData(), bind(&SearchPanel::SearchResultThreadFunc, this, _1, m_queryId)); // show busy indicator if (!m_pAnimationTimer->isActive()) m_pAnimationTimer->start(200); OnAnimationTimer(); m_pClearButton->setFlat(true); m_pClearButton->setVisible(true); } else { // hide X button m_pClearButton->setVisible(false); } } void SearchPanel::OnSearchPanelItemClicked(int row, int) { disconnect(m_pDrawWidget, SIGNAL(ViewportChanged()), this, SLOT(OnViewportChanged())); ASSERT_EQUAL(m_results.size(), static_cast<size_t>(m_pTable->rowCount()), ()); if (m_results[row]->GetResultType() == ResultT::RESULT_FEATURE) { // center viewport on clicked item m_pDrawWidget->ShowFeature(m_results[row]->GetFeatureRect()); } else { // insert suggestion into the search bar string const suggestion = m_results[row]->GetSuggestionString(); m_pEditor->setText(QString::fromUtf8(suggestion.c_str())); } connect(m_pDrawWidget, SIGNAL(ViewportChanged()), this, SLOT(OnViewportChanged())); } void SearchPanel::showEvent(QShowEvent *) { connect(m_pDrawWidget, SIGNAL(ViewportChanged()), this, SLOT(OnViewportChanged())); } void SearchPanel::hideEvent(QHideEvent *) { disconnect(m_pDrawWidget, SIGNAL(ViewportChanged()), this, SLOT(OnViewportChanged())); } void SearchPanel::OnViewportChanged() { QString const txt = m_pEditor->text(); if (!txt.isEmpty()) OnSearchTextChanged(txt); } void SearchPanel::OnAnimationTimer() { static int angle = 0; QMatrix rm; angle += 15; if (angle >= 360) angle = 0; rm.rotate(angle); m_pClearButton->setIcon(QIcon(m_busyIcon.transformed(rm))); } void SearchPanel::OnClearButton() { m_pEditor->setText(""); } } <commit_msg>100 chars / line.<commit_after>#include "search_panel.hpp" #include "draw_widget.hpp" #include "../map/settings.hpp" #include "../std/bind.hpp" #include <QtCore/QTimer> #include <QtGui/QHeaderView> #include <QtGui/QTableWidget> #include <QtGui/QLineEdit> #include <QtGui/QVBoxLayout> #include <QtGui/QHBoxLayout> #include <QtGui/QPushButton> #include <QtGui/QBitmap> namespace qt { SearchPanel::SearchPanel(DrawWidget * drawWidget, QWidget * parent) : QWidget(parent), m_pDrawWidget(drawWidget), m_busyIcon(":/ui/busy.png"), m_queryId(0) { m_pEditor = new QLineEdit(this); connect(m_pEditor, SIGNAL(textChanged(QString const &)), this, SLOT(OnSearchTextChanged(QString const &))); m_pTable = new QTableWidget(0, 4, this); m_pTable->setFocusPolicy(Qt::NoFocus); m_pTable->setAlternatingRowColors(true); m_pTable->setShowGrid(false); m_pTable->setSelectionBehavior(QAbstractItemView::SelectRows); m_pTable->verticalHeader()->setVisible(false); m_pTable->horizontalHeader()->setVisible(false); m_pTable->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents); connect(m_pTable, SIGNAL(cellClicked(int, int)), this, SLOT(OnSearchPanelItemClicked(int,int))); m_pClearButton = new QPushButton(this); connect(m_pClearButton, SIGNAL(pressed()), this, SLOT(OnClearButton())); m_pClearButton->setVisible(false); m_pClearButton->setFocusPolicy(Qt::NoFocus); m_pAnimationTimer = new QTimer(this); connect(m_pAnimationTimer, SIGNAL(timeout()), this, SLOT(OnAnimationTimer())); QHBoxLayout * horizontalLayout = new QHBoxLayout(); horizontalLayout->addWidget(m_pEditor); horizontalLayout->addWidget(m_pClearButton); QVBoxLayout * verticalLayout = new QVBoxLayout(); verticalLayout->addLayout(horizontalLayout); verticalLayout->addWidget(m_pTable); setLayout(verticalLayout); // for multithreading support CHECK(connect(this, SIGNAL(SearchResultSignal(ResultT *, int)), this, SLOT(OnSearchResult(ResultT *, int)), Qt::QueuedConnection), ()); setFocusPolicy(Qt::StrongFocus); setFocusProxy(m_pEditor); } template<class T> static void ClearVector(vector<T *> & v) { for(size_t i = 0; i < v.size(); ++i) delete v[i]; v.clear(); } SearchPanel::~SearchPanel() { ClearVector(m_results); } void SearchPanel::SearchResultThreadFunc(ResultT const & result, int queryId) { if (queryId == m_queryId) emit SearchResultSignal(new ResultT(result), queryId); } namespace { QTableWidgetItem * create_item(QString const & s) { QTableWidgetItem * item = new QTableWidgetItem(s); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); return item; } QString format_distance_impl(double m, bool & drawDir, char const * high, char const * low, double highF, double lowF) { double const lowV = m / lowF; drawDir = true; if (lowV < 1.0) { drawDir = false; return (QString::fromAscii("0") + QString::fromAscii(low)); } if (m >= highF) return QString("%1").arg(m / highF, 0, 'f', 1) + QString::fromAscii(high); else return QString("%1").arg(lowV, 0, 'f', 0) + QString::fromAscii(low); } QString format_distance(double m, bool & drawDir) { using namespace Settings; Units u; if (!Settings::Get("Units", u)) u = Metric; switch (u) { case Yard: return format_distance_impl(m, drawDir, " mi", " yd", 1609.344, 0.9144); case Foot: return format_distance_impl(m, drawDir, " mi", " ft", 1609.344, 0.3048); default: return format_distance_impl(m, drawDir, " km", " m", 1000.0, 1.0); } } QIcon draw_direction(double a) { int const dim = 64; QPixmap pm(dim, dim); QBitmap mask(dim, dim); mask.clear(); pm.setMask(mask); QPainter painter(&pm); painter.setBackgroundMode(Qt::TransparentMode); QMatrix m; m.translate(dim/2, dim/2); m.rotate(-a / math::pi * 180.0); m.translate(-dim/2, -dim/2); typedef QPointF P; QPolygonF poly(5); poly[0] = P(dim/3, dim/2); poly[1] = P(0, dim/2 - dim/3); poly[2] = P(dim, dim/2); poly[3] = P(0, dim/2 + dim/3); poly[4] = P(dim/3, dim/2); painter.setBrush(Qt::black); painter.drawPolygon(m.map(poly)); return pm; } } void SearchPanel::OnSearchResult(ResultT * res, int queryId) { if (queryId != m_queryId) return; if (!res->IsEndMarker()) { int const rowCount = m_pTable->rowCount(); m_pTable->insertRow(rowCount); m_pTable->setItem(rowCount, 1, create_item(QString::fromUtf8(res->GetString()))); if (res->GetResultType() == ResultT::RESULT_FEATURE) { m_pTable->setItem(rowCount, 0, create_item(QString::fromUtf8(res->GetFetureTypeAsString().c_str()))); bool drawDir; m_pTable->setItem(rowCount, 2, create_item(format_distance(res->GetDistanceFromCenter(), drawDir))); if (drawDir) { QTableWidgetItem * item = new QTableWidgetItem(draw_direction(res->GetDirectionFromCenter()), QString()); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); m_pTable->setItem(rowCount, 3, item); } } m_results.push_back(res); } else { // last element delete res; // stop search busy indicator m_pAnimationTimer->stop(); m_pClearButton->setIcon(QIcon(":/ui/x.png")); } } void SearchPanel::OnSearchTextChanged(QString const & str) { // clear old results m_pTable->clear(); m_pTable->setRowCount(0); ClearVector(m_results); ++m_queryId; QString const normalized = str.normalized(QString::NormalizationForm_KC); if (!normalized.isEmpty()) { m_pDrawWidget->Search(normalized.toUtf8().constData(), bind(&SearchPanel::SearchResultThreadFunc, this, _1, m_queryId)); // show busy indicator if (!m_pAnimationTimer->isActive()) m_pAnimationTimer->start(200); OnAnimationTimer(); m_pClearButton->setFlat(true); m_pClearButton->setVisible(true); } else { // hide X button m_pClearButton->setVisible(false); } } void SearchPanel::OnSearchPanelItemClicked(int row, int) { disconnect(m_pDrawWidget, SIGNAL(ViewportChanged()), this, SLOT(OnViewportChanged())); ASSERT_EQUAL(m_results.size(), static_cast<size_t>(m_pTable->rowCount()), ()); if (m_results[row]->GetResultType() == ResultT::RESULT_FEATURE) { // center viewport on clicked item m_pDrawWidget->ShowFeature(m_results[row]->GetFeatureRect()); } else { // insert suggestion into the search bar string const suggestion = m_results[row]->GetSuggestionString(); m_pEditor->setText(QString::fromUtf8(suggestion.c_str())); } connect(m_pDrawWidget, SIGNAL(ViewportChanged()), this, SLOT(OnViewportChanged())); } void SearchPanel::showEvent(QShowEvent *) { connect(m_pDrawWidget, SIGNAL(ViewportChanged()), this, SLOT(OnViewportChanged())); } void SearchPanel::hideEvent(QHideEvent *) { disconnect(m_pDrawWidget, SIGNAL(ViewportChanged()), this, SLOT(OnViewportChanged())); } void SearchPanel::OnViewportChanged() { QString const txt = m_pEditor->text(); if (!txt.isEmpty()) OnSearchTextChanged(txt); } void SearchPanel::OnAnimationTimer() { static int angle = 0; QMatrix rm; angle += 15; if (angle >= 360) angle = 0; rm.rotate(angle); m_pClearButton->setIcon(QIcon(m_busyIcon.transformed(rm))); } void SearchPanel::OnClearButton() { m_pEditor->setText(""); } } <|endoftext|>
<commit_before>#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "alert.h" #include "main.h" #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64_t nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), pollTimer(0) { numBlocksAtStartup = -1; pollTimer = new QTimer(this); pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } QDateTime ClientModel::getLastBlockDate() const { if (pindexBest) return QDateTime::fromTime_t(pindexBest->GetBlockTime()); else return QDateTime::fromTime_t(1400512373); // Genesis block's time } void ClientModel::updateTimer() { // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) { cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); } } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit error(tr("BoostCoin Network Alert"), QString::fromStdString(alert.strStatusBar), false); } } // Emit a numBlocksChanged when the status message changes, // so that the view recomputes and updates the status bar. emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers()); } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); } <commit_msg>More generic network alerting<commit_after>#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "alert.h" #include "main.h" #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64_t nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), pollTimer(0) { numBlocksAtStartup = -1; pollTimer = new QTimer(this); pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } QDateTime ClientModel::getLastBlockDate() const { if (pindexBest) return QDateTime::fromTime_t(pindexBest->GetBlockTime()); else return QDateTime::fromTime_t(1400512373); // Genesis block's time } void ClientModel::updateTimer() { // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) { cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); } } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit error(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false); } } // Emit a numBlocksChanged when the status message changes, // so that the view recomputes and updates the status bar. emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers()); } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); } <|endoftext|>
<commit_before>#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "alert.h" #include "main.h" #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64_t nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), pollTimer(0) { numBlocksAtStartup = -1; pollTimer = new QTimer(this); pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } QDateTime ClientModel::getLastBlockDate() const { if (pindexBest) return QDateTime::fromTime_t(pindexBest->GetBlockTime()); else return QDateTime::fromTime_t(1393221600); // Genesis block's time } void ClientModel::updateTimer() { // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) { cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); } } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit error(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false); } } // Emit a numBlocksChanged when the status message changes, // so that the view recomputes and updates the status bar. emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers()); } int ClientModel::GetNetworkHashPS(int lookup) const { if (pindexBest == NULL) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pindexBest->nHeight; // If lookup is larger than chain, then set it to chain length. if (lookup > pindexBest->nHeight) lookup = pindexBest->nHeight; CBlockIndex* pindexPrev = pindexBest; for (int i = 0; i < lookup; i++) pindexPrev = pindexPrev->pprev; double timeDiff = pindexBest->GetBlockTime() - pindexPrev->GetBlockTime(); double timePerBlock = timeDiff / lookup; return (boost::int64_t)(((double)GetDifficulty() * pow(2.0, 32)) / timePerBlock); } // Litecoin: copied from bitcoinrpc.cpp. double ClientModel::GetDifficulty() const { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (pindexBest == NULL) return 1.0; int nShift = (pindexBest->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(pindexBest->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); } <commit_msg>QT fix<commit_after>#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "alert.h" #include "main.h" #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64_t nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), pollTimer(0) { numBlocksAtStartup = -1; pollTimer = new QTimer(this); pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } QDateTime ClientModel::getLastBlockDate() const { if (pindexBest) return QDateTime::fromTime_t(pindexBest->GetBlockTime()); else return QDateTime::fromTime_t(1403793711); // Genesis block's time } void ClientModel::updateTimer() { // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) { cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); } } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit error(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false); } } // Emit a numBlocksChanged when the status message changes, // so that the view recomputes and updates the status bar. emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers()); } int ClientModel::GetNetworkHashPS(int lookup) const { if (pindexBest == NULL) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pindexBest->nHeight; // If lookup is larger than chain, then set it to chain length. if (lookup > pindexBest->nHeight) lookup = pindexBest->nHeight; CBlockIndex* pindexPrev = pindexBest; for (int i = 0; i < lookup; i++) pindexPrev = pindexPrev->pprev; double timeDiff = pindexBest->GetBlockTime() - pindexPrev->GetBlockTime(); double timePerBlock = timeDiff / lookup; return (boost::int64_t)(((double)GetDifficulty() * pow(2.0, 32)) / timePerBlock); } // Litecoin: copied from bitcoinrpc.cpp. double ClientModel::GetDifficulty() const { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (pindexBest == NULL) return 1.0; int nShift = (pindexBest->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(pindexBest->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); } <|endoftext|>
<commit_before>/* Crystal Space utility library: string class Copyright (C) 1999,2000 by Andrew Zabolotny <bit@eltech.ru> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ extern "C" { #include <ctype.h> #include <stdarg.h> } #include "cssysdef.h" #include "csutil/csstring.h" #include "csutil/snprintf.h" csString::~csString () { Free (); } void csString::Free () { if (Data) { delete[] Data; Data = 0; Size = 0; MaxSize = 0; } } void csString::SetCapacity (size_t NewSize) { NewSize++; // Plus one for implicit null byte. if (NewSize <= MaxSize) return; MaxSize = NewSize; char* buff = new char[MaxSize]; if (Data == 0 || Size == 0) buff[0] = '\0'; else memcpy(buff, Data, Size + 1); if (Data) delete[] Data; Data = buff; } csString &csString::Reclaim() { if (Size == 0) Free(); else { CS_ASSERT(Data != 0); MaxSize = Size + 1; // Plus one for implicit null byte. char* s = new char[MaxSize]; memcpy(s, Data, MaxSize); delete[] Data; Data = s; } return *this; } csString &csString::Truncate (size_t iPos) { if (iPos < Size) { Size = iPos; Data [Size] = '\0'; } return *this; } csString &csString::DeleteAt (size_t iPos, size_t iCount) { CS_ASSERT (iPos < Size && iPos + iCount <= Size); if (iPos + iCount < Size) memmove(Data + iPos, Data + iPos + iCount, Size - (iPos + iCount)); Size -= iCount; Data[Size] = '\0'; return *this; } csString &csString::Insert (size_t iPos, const csString &iStr) { CS_ASSERT(iPos <= Size); if (Data == 0 || iPos == Size) return Append (iStr); size_t const sl = iStr.Length (); size_t const NewSize = sl + Size; SetCapacity (NewSize); memmove (Data + iPos + sl, Data + iPos, Size - iPos + 1); // Also move null. memcpy (Data + iPos, iStr.GetData (), sl); Size = NewSize; return *this; } csString &csString::Insert (size_t iPos, const char iChar) { csString s(iChar); return Insert(iPos, s); } csString &csString::Overwrite (size_t iPos, const csString &iStr) { CS_ASSERT (iPos <= Size); if (Data == 0 || iPos == Size) return Append (iStr); size_t const sl = iStr.Length (); size_t const NewSize = iPos + sl; SetCapacity (NewSize); memcpy (Data + iPos, iStr.GetData (), sl + 1); // Also copy null terminator. Size = NewSize; return *this; } csString &csString::Append (const csString &iStr, size_t iCount) { return Append(iStr.GetData(), iCount); } csString &csString::Append (const char *iStr, size_t iCount) { if (iStr == 0) return *this; if (iCount == (size_t)-1) iCount = strlen (iStr); if (iCount == 0) return *this; size_t const NewSize = Size + iCount; SetCapacity (NewSize); memcpy (Data + Size, iStr, iCount); Size = NewSize; Data [Size] = '\0'; return *this; } csString &csString::LTrim() { size_t i; for (i = 0; i < Size; i++) if (!isspace (Data[i])) break; if (i > 0) DeleteAt (0, i); return *this; } csString &csString::RTrim() { if (Size > 0) { int i; for (i = Size - 1; i >= 0; i--) if (!isspace (Data[i])) break; if (i < int(Size - 1)) Truncate(i + 1); } return *this; } csString &csString::Trim() { return LTrim().RTrim(); } csString &csString::Collapse() { if (Size > 0) { char const* src = Data; char const* slim = Data + Size; char* dst = Data; bool saw_white = false; for ( ; src < slim; src++) { char const c = *src; if (isspace(c)) saw_white = true; else { if (saw_white && dst > Data) *dst++ = ' '; *dst++ = c; saw_white = false; } } Size = dst - Data; Data[Size] = '\0'; } return *this; } csString &csString::Format(const char *format, ...) { va_list args; va_start(args, format); if (Data == 0) // Ensure that backing-store exists prior to vsnprintf(). SetCapacity(255); int rc = 0; while (1) { rc = cs_vsnprintf(Data, MaxSize, format, args); // Buffer was big enough for entire string? if (rc >= 0 && rc < (int)MaxSize) break; // Some vsnprintf()s return -1 on failure, others return desired capacity. if (rc >= 0) SetCapacity(rc); // SetCapacity() ensures room for null byte. else SetCapacity(MaxSize * 2 - 1); } Size = rc; va_end(args); return *this; } #define STR_FORMAT(TYPE,FMT,SZ) \ csString csString::Format (TYPE v) \ { char s[SZ]; cs_snprintf (s, SZ, #FMT, v); return csString ().Append (s); } STR_FORMAT(short, %hd, 32) STR_FORMAT(unsigned short, %hu, 32) STR_FORMAT(int, %d, 32) STR_FORMAT(unsigned int, %u, 32) STR_FORMAT(long, %ld, 32) STR_FORMAT(unsigned long, %lu, 32) STR_FORMAT(float, %g, 64) STR_FORMAT(double, %g, 64) #undef STR_FORMAT #define STR_FORMAT_INT(TYPE,FMT) \ csString csString::Format (TYPE v, int width, int prec/*=0*/) \ { char s[64], s1[64]; \ cs_snprintf (s1, sizeof(s1), "%%%d.%d"#FMT, width, prec); \ cs_snprintf (s, sizeof(s), s1, v); \ return csString ().Append (s); } STR_FORMAT_INT(short, hd) STR_FORMAT_INT(unsigned short, hu) STR_FORMAT_INT(int, d) STR_FORMAT_INT(unsigned int, u) STR_FORMAT_INT(long, ld) STR_FORMAT_INT(unsigned long, lu) #undef STR_FORMAT_INT #define STR_FORMAT_FLOAT(TYPE) \ csString csString::Format (TYPE v, int width, int prec/*=6*/) \ { char s[64], s1[64]; \ cs_snprintf (s1, sizeof(s1), "%%%d.%dg", width, prec); \ cs_snprintf (s, sizeof(s), s1, v); \ return csString ().Append (s); } STR_FORMAT_FLOAT(float) STR_FORMAT_FLOAT(double) #undef STR_FORMAT_FLOAT csString &csString::PadLeft (size_t iNewSize, char iChar) { if (iNewSize > Size) { SetCapacity (iNewSize); const size_t toInsert = iNewSize - Size; memmove (Data + toInsert, Data, Size + 1); // Also move null terminator. for (size_t x = 0; x < toInsert; x++) Data [x] = iChar; Size = iNewSize; } return *this; } csString csString::AsPadLeft (size_t iNewSize, char iChar) { csString newStr = Clone (); newStr.PadLeft (iChar, iNewSize); return newStr; } #define STR_PADLEFT(TYPE) \ csString csString::PadLeft (TYPE v, size_t iNewSize, char iChar) \ { csString newStr; return newStr.Append (v).PadLeft (iNewSize, iChar); } STR_PADLEFT(const csString&) STR_PADLEFT(const char*) STR_PADLEFT(char) STR_PADLEFT(unsigned char) STR_PADLEFT(short) STR_PADLEFT(unsigned short) STR_PADLEFT(int) STR_PADLEFT(unsigned int) STR_PADLEFT(long) STR_PADLEFT(unsigned long) STR_PADLEFT(float) STR_PADLEFT(double) #if !defined(CS_USE_FAKE_BOOL_TYPE) STR_PADLEFT(bool) #endif #undef STR_PADLEFT csString& csString::PadRight (size_t iNewSize, char iChar) { if (iNewSize > Size) { SetCapacity (iNewSize); for (size_t x = Size; x < iNewSize; x++) Data [x] = iChar; Size = iNewSize; Data [Size] = '\0'; } return *this; } csString csString::AsPadRight (size_t iNewSize, char iChar) { csString newStr = Clone (); newStr.PadRight (iChar, iNewSize); return newStr; } #define STR_PADRIGHT(TYPE) \ csString csString::PadRight (TYPE v, size_t iNewSize, char iChar) \ { csString newStr; return newStr.Append (v).PadRight (iNewSize, iChar); } STR_PADRIGHT(const csString&) STR_PADRIGHT(const char*) STR_PADRIGHT(char) STR_PADRIGHT(unsigned char) STR_PADRIGHT(short) STR_PADRIGHT(unsigned short) STR_PADRIGHT(int) STR_PADRIGHT(unsigned int) STR_PADRIGHT(long) STR_PADRIGHT(unsigned long) STR_PADRIGHT(float) STR_PADRIGHT(double) #if !defined(CS_USE_FAKE_BOOL_TYPE) STR_PADRIGHT(bool) #endif #undef STR_PADRIGHT csString& csString::PadCenter (size_t iNewSize, char iChar) { if (iNewSize > Size) { SetCapacity (iNewSize); const size_t toInsert = iNewSize - Size; const size_t halfInsert = toInsert / 2; if (Size > 0) memmove (Data + halfInsert, Data, Size); size_t x; for (x = 0; x < halfInsert; x++) Data [x] = iChar; for (x = halfInsert + Size; x < iNewSize; x++) Data [x] = iChar; Size = iNewSize; Data [Size] = '\0'; } return *this; } csString csString::AsPadCenter (size_t iNewSize, char iChar) { csString newStr = Clone (); newStr.PadCenter (iChar, iNewSize); return newStr; } #define STR_PADCENTER(TYPE) \ csString csString::PadCenter (TYPE v, size_t iNewSize, char iChar) \ { csString newStr; return newStr.Append (v).PadCenter (iNewSize, iChar); } STR_PADCENTER(const csString&) STR_PADCENTER(const char*) STR_PADCENTER(char) STR_PADCENTER(unsigned char) STR_PADCENTER(short) STR_PADCENTER(unsigned short) STR_PADCENTER(int) STR_PADCENTER(unsigned int) STR_PADCENTER(long) STR_PADCENTER(unsigned long) STR_PADCENTER(float) STR_PADCENTER(double) #if !defined(CS_USE_FAKE_BOOL_TYPE) STR_PADCENTER(bool) #endif #undef STR_PADCENTER <commit_msg>fixed bug in csString when appending zero length strings<commit_after>/* Crystal Space utility library: string class Copyright (C) 1999,2000 by Andrew Zabolotny <bit@eltech.ru> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ extern "C" { #include <ctype.h> #include <stdarg.h> } #include "cssysdef.h" #include "csutil/csstring.h" #include "csutil/snprintf.h" csString::~csString () { Free (); } void csString::Free () { if (Data) { delete[] Data; Data = 0; Size = 0; MaxSize = 0; } } void csString::SetCapacity (size_t NewSize) { NewSize++; // Plus one for implicit null byte. if (NewSize <= MaxSize) return; MaxSize = NewSize; char* buff = new char[MaxSize]; if (Data == 0 || Size == 0) buff[0] = '\0'; else memcpy(buff, Data, Size + 1); if (Data) delete[] Data; Data = buff; } csString &csString::Reclaim() { if (Size == 0) Free(); else { CS_ASSERT(Data != 0); MaxSize = Size + 1; // Plus one for implicit null byte. char* s = new char[MaxSize]; memcpy(s, Data, MaxSize); delete[] Data; Data = s; } return *this; } csString &csString::Truncate (size_t iPos) { if (iPos < Size) { Size = iPos; Data [Size] = '\0'; } return *this; } csString &csString::DeleteAt (size_t iPos, size_t iCount) { CS_ASSERT (iPos < Size && iPos + iCount <= Size); if (iPos + iCount < Size) memmove(Data + iPos, Data + iPos + iCount, Size - (iPos + iCount)); Size -= iCount; Data[Size] = '\0'; return *this; } csString &csString::Insert (size_t iPos, const csString &iStr) { CS_ASSERT(iPos <= Size); if (Data == 0 || iPos == Size) return Append (iStr); size_t const sl = iStr.Length (); size_t const NewSize = sl + Size; SetCapacity (NewSize); memmove (Data + iPos + sl, Data + iPos, Size - iPos + 1); // Also move null. memcpy (Data + iPos, iStr.GetData (), sl); Size = NewSize; return *this; } csString &csString::Insert (size_t iPos, const char iChar) { csString s(iChar); return Insert(iPos, s); } csString &csString::Overwrite (size_t iPos, const csString &iStr) { CS_ASSERT (iPos <= Size); if (Data == 0 || iPos == Size) return Append (iStr); size_t const sl = iStr.Length (); size_t const NewSize = iPos + sl; SetCapacity (NewSize); memcpy (Data + iPos, iStr.GetData (), sl + 1); // Also copy null terminator. Size = NewSize; return *this; } csString &csString::Append (const csString &iStr, size_t iCount) { return Append(iStr.GetData(), iCount); } csString &csString::Append (const char *iStr, size_t iCount) { if (iStr == 0) return *this; if (iCount == (size_t)-1) iCount = strlen (iStr); if (iCount == 0) { // make sure string is correctly terminated Data[Size]='\0'; return *this; } size_t const NewSize = Size + iCount; SetCapacity (NewSize); memcpy (Data + Size, iStr, iCount); Size = NewSize; Data [Size] = '\0'; return *this; } csString &csString::LTrim() { size_t i; for (i = 0; i < Size; i++) if (!isspace (Data[i])) break; if (i > 0) DeleteAt (0, i); return *this; } csString &csString::RTrim() { if (Size > 0) { int i; for (i = Size - 1; i >= 0; i--) if (!isspace (Data[i])) break; if (i < int(Size - 1)) Truncate(i + 1); } return *this; } csString &csString::Trim() { return LTrim().RTrim(); } csString &csString::Collapse() { if (Size > 0) { char const* src = Data; char const* slim = Data + Size; char* dst = Data; bool saw_white = false; for ( ; src < slim; src++) { char const c = *src; if (isspace(c)) saw_white = true; else { if (saw_white && dst > Data) *dst++ = ' '; *dst++ = c; saw_white = false; } } Size = dst - Data; Data[Size] = '\0'; } return *this; } csString &csString::Format(const char *format, ...) { va_list args; va_start(args, format); if (Data == 0) // Ensure that backing-store exists prior to vsnprintf(). SetCapacity(255); int rc = 0; while (1) { rc = cs_vsnprintf(Data, MaxSize, format, args); // Buffer was big enough for entire string? if (rc >= 0 && rc < (int)MaxSize) break; // Some vsnprintf()s return -1 on failure, others return desired capacity. if (rc >= 0) SetCapacity(rc); // SetCapacity() ensures room for null byte. else SetCapacity(MaxSize * 2 - 1); } Size = rc; va_end(args); return *this; } #define STR_FORMAT(TYPE,FMT,SZ) \ csString csString::Format (TYPE v) \ { char s[SZ]; cs_snprintf (s, SZ, #FMT, v); return csString ().Append (s); } STR_FORMAT(short, %hd, 32) STR_FORMAT(unsigned short, %hu, 32) STR_FORMAT(int, %d, 32) STR_FORMAT(unsigned int, %u, 32) STR_FORMAT(long, %ld, 32) STR_FORMAT(unsigned long, %lu, 32) STR_FORMAT(float, %g, 64) STR_FORMAT(double, %g, 64) #undef STR_FORMAT #define STR_FORMAT_INT(TYPE,FMT) \ csString csString::Format (TYPE v, int width, int prec/*=0*/) \ { char s[64], s1[64]; \ cs_snprintf (s1, sizeof(s1), "%%%d.%d"#FMT, width, prec); \ cs_snprintf (s, sizeof(s), s1, v); \ return csString ().Append (s); } STR_FORMAT_INT(short, hd) STR_FORMAT_INT(unsigned short, hu) STR_FORMAT_INT(int, d) STR_FORMAT_INT(unsigned int, u) STR_FORMAT_INT(long, ld) STR_FORMAT_INT(unsigned long, lu) #undef STR_FORMAT_INT #define STR_FORMAT_FLOAT(TYPE) \ csString csString::Format (TYPE v, int width, int prec/*=6*/) \ { char s[64], s1[64]; \ cs_snprintf (s1, sizeof(s1), "%%%d.%dg", width, prec); \ cs_snprintf (s, sizeof(s), s1, v); \ return csString ().Append (s); } STR_FORMAT_FLOAT(float) STR_FORMAT_FLOAT(double) #undef STR_FORMAT_FLOAT csString &csString::PadLeft (size_t iNewSize, char iChar) { if (iNewSize > Size) { SetCapacity (iNewSize); const size_t toInsert = iNewSize - Size; memmove (Data + toInsert, Data, Size + 1); // Also move null terminator. for (size_t x = 0; x < toInsert; x++) Data [x] = iChar; Size = iNewSize; } return *this; } csString csString::AsPadLeft (size_t iNewSize, char iChar) { csString newStr = Clone (); newStr.PadLeft (iChar, iNewSize); return newStr; } #define STR_PADLEFT(TYPE) \ csString csString::PadLeft (TYPE v, size_t iNewSize, char iChar) \ { csString newStr; return newStr.Append (v).PadLeft (iNewSize, iChar); } STR_PADLEFT(const csString&) STR_PADLEFT(const char*) STR_PADLEFT(char) STR_PADLEFT(unsigned char) STR_PADLEFT(short) STR_PADLEFT(unsigned short) STR_PADLEFT(int) STR_PADLEFT(unsigned int) STR_PADLEFT(long) STR_PADLEFT(unsigned long) STR_PADLEFT(float) STR_PADLEFT(double) #if !defined(CS_USE_FAKE_BOOL_TYPE) STR_PADLEFT(bool) #endif #undef STR_PADLEFT csString& csString::PadRight (size_t iNewSize, char iChar) { if (iNewSize > Size) { SetCapacity (iNewSize); for (size_t x = Size; x < iNewSize; x++) Data [x] = iChar; Size = iNewSize; Data [Size] = '\0'; } return *this; } csString csString::AsPadRight (size_t iNewSize, char iChar) { csString newStr = Clone (); newStr.PadRight (iChar, iNewSize); return newStr; } #define STR_PADRIGHT(TYPE) \ csString csString::PadRight (TYPE v, size_t iNewSize, char iChar) \ { csString newStr; return newStr.Append (v).PadRight (iNewSize, iChar); } STR_PADRIGHT(const csString&) STR_PADRIGHT(const char*) STR_PADRIGHT(char) STR_PADRIGHT(unsigned char) STR_PADRIGHT(short) STR_PADRIGHT(unsigned short) STR_PADRIGHT(int) STR_PADRIGHT(unsigned int) STR_PADRIGHT(long) STR_PADRIGHT(unsigned long) STR_PADRIGHT(float) STR_PADRIGHT(double) #if !defined(CS_USE_FAKE_BOOL_TYPE) STR_PADRIGHT(bool) #endif #undef STR_PADRIGHT csString& csString::PadCenter (size_t iNewSize, char iChar) { if (iNewSize > Size) { SetCapacity (iNewSize); const size_t toInsert = iNewSize - Size; const size_t halfInsert = toInsert / 2; if (Size > 0) memmove (Data + halfInsert, Data, Size); size_t x; for (x = 0; x < halfInsert; x++) Data [x] = iChar; for (x = halfInsert + Size; x < iNewSize; x++) Data [x] = iChar; Size = iNewSize; Data [Size] = '\0'; } return *this; } csString csString::AsPadCenter (size_t iNewSize, char iChar) { csString newStr = Clone (); newStr.PadCenter (iChar, iNewSize); return newStr; } #define STR_PADCENTER(TYPE) \ csString csString::PadCenter (TYPE v, size_t iNewSize, char iChar) \ { csString newStr; return newStr.Append (v).PadCenter (iNewSize, iChar); } STR_PADCENTER(const csString&) STR_PADCENTER(const char*) STR_PADCENTER(char) STR_PADCENTER(unsigned char) STR_PADCENTER(short) STR_PADCENTER(unsigned short) STR_PADCENTER(int) STR_PADCENTER(unsigned int) STR_PADCENTER(long) STR_PADCENTER(unsigned long) STR_PADCENTER(float) STR_PADCENTER(double) #if !defined(CS_USE_FAKE_BOOL_TYPE) STR_PADCENTER(bool) #endif #undef STR_PADCENTER <|endoftext|>
<commit_before>/* * ===================================================================================== * * Filename: requesthandler.cpp * * Description: Handle requests * * Version: 1.1 * Created: 28/01/13 21:47:34 * Revision: none * Compiler: g++ * * Author: Daniel Bugl <Daniel.Bugl@touchlay.com> * Organization: TouchLay * * ===================================================================================== */ // Headers #include "requesthandler.h" /* RequestHandler: Constructor */ RequestHandler::RequestHandler(int connection, char *cip) { // TODO: Create a blacklist for IPs clientip = cip; // Initialise request InitRequest(&request); // Handle request and check request type if (handle(connection) == true) { #ifdef DEBUG std::cout << "[DEBUG] [request ] handle() returned true, continuing!" << std::endl; #endif if (request.type == HTTP) { #ifdef DEBUG std::cout << "[DEBUG] [request_http] This is an HTTP request." << std::endl; #endif if (request.status == 200) { #ifdef DEBUG std::cout << "[DEBUG] [request_http] Status 200, returning result." << std::endl; #endif if (parseJSON()) { API api = API(); std::string apiresult = api.init(jRoot, cip); #ifdef DEBUG std::cout << "[DEBUG] [request_api ] Got API result(" << strlen(apiresult.c_str()) << "): " << apiresult << std::endl; #endif outputHTTP(connection, &request, apiresult.c_str()); } else outputHTTP(connection, &request, "{\"type\": \"error\", \"msg\": \"Invalid JSON.\"}"); #ifdef DEBUG std::cout << "[DEBUG] [request_http] Answered to request with HTTP." << std::endl; #endif } else { std::stringstream sbuffer; sbuffer << "{\"type\": \"error\", \"msg\": \"HTTP Error " << request.status << "\"}"; outputHTTP(connection, &request, sbuffer.str()); } usleep(REQUEST_TIMEOUT_SEND*1000000); } else if (request.type == TN) { #ifdef DEBUG std::cout << "[DEBUG] [request_tn ] This is a TN request." << std::endl; #endif if (parseJSON()) { API api = API(); std::string apiresult = api.init(jRoot, cip); #ifdef DEBUG std::cout << "[DEBUG] [request_api ] Got API result(" << strlen(apiresult.c_str()) << "): " << apiresult << std::endl; #endif s_writeline(connection, apiresult.c_str(), strlen(apiresult.c_str())); } else s_writeline(connection, "{\"type\": \"error\", \"msg\": \"Invalid JSON.\"}", 41); #ifdef DEBUG std::cout << "[DEBUG] [request_tn ] Answered to request with TN." << std::endl; usleep(REQUEST_TIMEOUT_SEND*1000000); #endif } else std::cout << "[WARN ] [request ] Unknown request type, killing request." << std::endl; } else std::cout << "[WARN ] [request ] Couldn't handle request, killing it." << std::endl; } /* parseJSON: JSON parser */ bool RequestHandler::parseJSON() { std::string data(""); if (request.resource != 0) data = request.resource; if ((request.type == HTTP) && (data != "")) data.erase(data.begin()); // Remove / prefix from the GET request data = decodeURI(data); #ifdef DEBUG std::cout << "[DEBUG] [request_json] Got data: " << data << "\n"; #endif if (!jReader.parse(data, jRoot, false)) { #ifdef DEBUG std::cout << "[DEBUG] [request_json] Invalid JSON (" << data << ")." << std::endl; #endif return false; } else return true; } /* ~RequestHandler: Destructor */ RequestHandler::~RequestHandler() { #ifdef DEBUG std::cout << "[DEBUG] [request ] Destructed RequestHandler." << std::endl; #endif } /* InitRequest: Initialises the request data */ void RequestHandler::InitRequest(Request *request) { request->status = 200; request->method = UNSUPPORTED; request->resource = NULL; #ifdef DEBUG std::cout << "[DEBUG] [request ] Initialised request." << std::endl; #endif } /* handle: Handle a request */ bool RequestHandler::handle(int connection) { char buffer[MAX_REQ_LINE] = {0}; int rval; fd_set fds; struct timeval tv; // Timeout tv.tv_sec = REQUEST_TIMEOUT_RECV; tv.tv_usec = 0; do { // Reset FD FD_ZERO(&fds); FD_SET(connection, &fds); rval = select(connection+1, &fds, NULL, NULL, &tv); // Select from request if (rval < 0) std::cout << "[WARN ] [request ] Couldn't select from request." << std::endl; else if (rval == 0) return false; // Timeout, kill request else { s_readline(connection, buffer, MAX_REQ_LINE - 1); #ifdef DEBUG std::cout << "[DEBUG] [request ] Received buffer: " << buffer << std::endl; #endif if (buffer[0] == '{') { request.type = TN; request.resource = buffer; request.level = SIMPLE; return true; } else { request.type = HTTP; strim(buffer); char *buf = buffer; char *endptr = NULL; int len; if (!strncmp(buffer, "GET ", 4)) { request.method = GET; buf += 4; } else if (!strncmp(buffer, "HEAD ", 5)) { request.method = HEAD; buf += 5; } else { request.method = UNSUPPORTED; request.status = 501; return true; } while (*buf && isspace(*buf)) buf++; // Skip the start endptr = strchr(buf, ' '); if (endptr == NULL) len = strlen(buf); else len = endptr - buf; if (len == 0) { request.status = 400; return true; } request.resource = (char *)calloc(len + 1, sizeof(char)); strncpy(request.resource, buf, len); request.level = SIMPLE; return true; } } } while (request.level != SIMPLE); return true; // Successfully processed } bool RequestHandler::outputHTTP(int connection, Request *request, std::string content) { std::stringstream sbuffer; if (request->status == 200) sbuffer << "HTTP/1.1 " << request->status << " OK\r\n"; else if (request->status == 400) sbuffer << "HTTP/1.1 " << request->status << " Bad Request\r\n"; else sbuffer << "HTTP/1.1 501 Not Implemented\r\n"; s_writeline(connection, sbuffer.str().c_str(), strlen(sbuffer.str().c_str())); sbuffer.str(std::string()); sbuffer << "Server: " << NAME << "/" << VERSION << "\r\n"; s_writeline(connection, sbuffer.str().c_str(), strlen(sbuffer.str().c_str())); sbuffer.str(std::string()); s_writeline(connection, "Content-Type: application/json\r\n", 32); sbuffer << "Content-Length: " << strlen(content.c_str()) << "\r\n"; s_writeline(connection, sbuffer.str().c_str(), strlen(sbuffer.str().c_str())); sbuffer.str(std::string()); s_writeline(connection, "\r\n", 2); s_writeline(connection, content.c_str(), strlen(content.c_str())); return true; } <commit_msg>Implemented HTTP HEAD method.<commit_after>/* * ===================================================================================== * * Filename: requesthandler.cpp * * Description: Handle requests * * Version: 1.1 * Created: 28/01/13 21:47:34 * Revision: none * Compiler: g++ * * Author: Daniel Bugl <Daniel.Bugl@touchlay.com> * Organization: TouchLay * * ===================================================================================== */ // Headers #include "requesthandler.h" /* RequestHandler: Constructor */ RequestHandler::RequestHandler(int connection, char *cip) { // TODO: Create a blacklist for IPs clientip = cip; // Initialise request InitRequest(&request); // Handle request and check request type if (handle(connection) == true) { #ifdef DEBUG std::cout << "[DEBUG] [request ] handle() returned true, continuing!" << std::endl; #endif if (request.type == HTTP) { #ifdef DEBUG std::cout << "[DEBUG] [request_http] This is an HTTP request." << std::endl; #endif if ((request.status == 200) && (request.method != UNSUPPORTED)) { #ifdef DEBUG std::cout << "[DEBUG] [request_http] Status 200, returning result." << std::endl; #endif if (request.method == HEAD) { outputHTTP(connection, &request, ""); // Only show the headers. } else { if (parseJSON()) { API api = API(); std::string apiresult = api.init(jRoot, cip); #ifdef DEBUG std::cout << "[DEBUG] [request_api ] Got API result(" << strlen(apiresult.c_str()) << "): " << apiresult << std::endl; #endif outputHTTP(connection, &request, apiresult.c_str()); } else outputHTTP(connection, &request, "{\"type\": \"error\", \"msg\": \"Invalid JSON.\"}"); #ifdef DEBUG std::cout << "[DEBUG] [request_http] Answered to request with HTTP." << std::endl; #endif } } else { std::stringstream sbuffer; sbuffer << "{\"type\": \"error\", \"msg\": \"HTTP Error " << request.status << "\"}"; outputHTTP(connection, &request, sbuffer.str()); } usleep(REQUEST_TIMEOUT_SEND*1000000); } else if (request.type == TN) { #ifdef DEBUG std::cout << "[DEBUG] [request_tn ] This is a TN request." << std::endl; #endif if (parseJSON()) { API api = API(); std::string apiresult = api.init(jRoot, cip); #ifdef DEBUG std::cout << "[DEBUG] [request_api ] Got API result(" << strlen(apiresult.c_str()) << "): " << apiresult << std::endl; #endif s_writeline(connection, apiresult.c_str(), strlen(apiresult.c_str())); } else s_writeline(connection, "{\"type\": \"error\", \"msg\": \"Invalid JSON.\"}", 41); #ifdef DEBUG std::cout << "[DEBUG] [request_tn ] Answered to request with TN." << std::endl; usleep(REQUEST_TIMEOUT_SEND*1000000); #endif } else std::cout << "[WARN ] [request ] Unknown request type, killing request." << std::endl; } else std::cout << "[WARN ] [request ] Couldn't handle request, killing it." << std::endl; } /* parseJSON: JSON parser */ bool RequestHandler::parseJSON() { std::string data(""); if (request.resource != 0) data = request.resource; if ((request.type == HTTP) && (data != "")) data.erase(data.begin()); // Remove / prefix from the GET request data = decodeURI(data); #ifdef DEBUG std::cout << "[DEBUG] [request_json] Got data: " << data << "\n"; #endif if (!jReader.parse(data, jRoot, false)) { #ifdef DEBUG std::cout << "[DEBUG] [request_json] Invalid JSON (" << data << ")." << std::endl; #endif return false; } else return true; } /* ~RequestHandler: Destructor */ RequestHandler::~RequestHandler() { #ifdef DEBUG std::cout << "[DEBUG] [request ] Destructed RequestHandler." << std::endl; #endif } /* InitRequest: Initialises the request data */ void RequestHandler::InitRequest(Request *request) { request->status = 200; request->method = UNSUPPORTED; request->resource = NULL; #ifdef DEBUG std::cout << "[DEBUG] [request ] Initialised request." << std::endl; #endif } /* handle: Handle a request */ bool RequestHandler::handle(int connection) { char buffer[MAX_REQ_LINE] = {0}; int rval; fd_set fds; struct timeval tv; // Timeout tv.tv_sec = REQUEST_TIMEOUT_RECV; tv.tv_usec = 0; do { // Reset FD FD_ZERO(&fds); FD_SET(connection, &fds); rval = select(connection+1, &fds, NULL, NULL, &tv); // Select from request if (rval < 0) std::cout << "[WARN ] [request ] Couldn't select from request." << std::endl; else if (rval == 0) return false; // Timeout, kill request else { s_readline(connection, buffer, MAX_REQ_LINE - 1); #ifdef DEBUG std::cout << "[DEBUG] [request ] Received buffer: " << buffer << std::endl; #endif if (buffer[0] == '{') { request.type = TN; request.resource = buffer; request.level = SIMPLE; return true; } else { request.type = HTTP; strim(buffer); char *buf = buffer; char *endptr = NULL; int len; if (!strncmp(buffer, "GET ", 4)) { request.method = GET; buf += 4; } else if (!strncmp(buffer, "HEAD ", 5)) { request.method = HEAD; buf += 5; } else { request.method = UNSUPPORTED; request.status = 501; return true; } while (*buf && isspace(*buf)) buf++; // Skip the start endptr = strchr(buf, ' '); if (endptr == NULL) len = strlen(buf); else len = endptr - buf; if (len == 0) { request.status = 400; return true; } request.resource = (char *)calloc(len + 1, sizeof(char)); strncpy(request.resource, buf, len); request.level = SIMPLE; return true; } } } while (request.level != SIMPLE); return true; // Successfully processed } bool RequestHandler::outputHTTP(int connection, Request *request, std::string content) { std::stringstream sbuffer; if (request->status == 200) sbuffer << "HTTP/1.1 " << request->status << " OK\r\n"; else if (request->status == 400) sbuffer << "HTTP/1.1 " << request->status << " Bad Request\r\n"; else sbuffer << "HTTP/1.1 501 Not Implemented\r\n"; s_writeline(connection, sbuffer.str().c_str(), strlen(sbuffer.str().c_str())); sbuffer.str(std::string()); sbuffer << "Server: " << NAME << "/" << VERSION << "\r\n"; s_writeline(connection, sbuffer.str().c_str(), strlen(sbuffer.str().c_str())); sbuffer.str(std::string()); s_writeline(connection, "Content-Type: application/json\r\n", 32); sbuffer << "Content-Length: " << strlen(content.c_str()) << "\r\n"; s_writeline(connection, sbuffer.str().c_str(), strlen(sbuffer.str().c_str())); sbuffer.str(std::string()); s_writeline(connection, "\r\n", 2); if (request->method == GET) s_writeline(connection, content.c_str(), strlen(content.c_str())); // If this isn't a GET request, it's a HEAD request, which doesn't want the contents. return true; } <|endoftext|>
<commit_before>#include <chrono> #include <stdio.h> #include <stdlib.h> #include <thread> #include "protocol.h" namespace sweep { namespace protocol { typedef struct error { const char* what; // always literal, do not deallocate } error; // Constructor hidden from users static error_s error_construct(const char* what) { SWEEP_ASSERT(what); auto out = new error{what}; return out; } const char* error_message(error_s error) { SWEEP_ASSERT(error); return error->what; } void error_destruct(error_s error) { SWEEP_ASSERT(error); delete error; } static uint8_t checksum_response_header(response_header_s* v) { SWEEP_ASSERT(v); return ((v->cmdStatusByte1 + v->cmdStatusByte2) & 0x3F) + 0x30; } static uint8_t checksum_response_param(response_param_s* v) { SWEEP_ASSERT(v); return ((v->cmdStatusByte1 + v->cmdStatusByte2) & 0x3F) + 0x30; } static uint8_t checksum_response_scan_packet(response_scan_packet_s* v) { SWEEP_ASSERT(v); uint64_t checksum = 0; checksum += v->sync_error; checksum += v->angle & 0xff00; checksum += v->angle & 0x00ff; checksum += v->distance & 0xff00; checksum += v->distance & 0x00ff; checksum += v->signal_strength; return checksum % 255; } void write_command(serial::device_s serial, const uint8_t cmd[2], error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(error); cmd_packet_s packet; packet.cmdByte1 = cmd[0]; packet.cmdByte2 = cmd[1]; packet.cmdParamTerm = '\n'; // pause for 2ms, so the device is never bombarded with back to back commands std::this_thread::sleep_for(std::chrono::milliseconds(2)); serial::error_s serialerror = nullptr; serial::device_write(serial, &packet, sizeof(cmd_packet_s), &serialerror); if (serialerror) { *error = error_construct("unable to write command"); serial::error_destruct(serialerror); return; } } void write_command_with_arguments(serial::device_s serial, const uint8_t cmd[2], const uint8_t arg[2], error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(arg); SWEEP_ASSERT(error); cmd_param_packet_s packet; packet.cmdByte1 = cmd[0]; packet.cmdByte2 = cmd[1]; packet.cmdParamByte1 = arg[0]; packet.cmdParamByte2 = arg[1]; packet.cmdParamTerm = '\n'; serial::error_s serialerror = nullptr; serial::device_write(serial, &packet, sizeof(cmd_param_packet_s), &serialerror); if (serialerror) { *error = error_construct("unable to write command with arguments"); serial::error_destruct(serialerror); return; } } void read_response_header(serial::device_s serial, const uint8_t cmd[2], response_header_s* header, error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(header); SWEEP_ASSERT(error); serial::error_s serialerror = nullptr; serial::device_read(serial, header, sizeof(response_header_s), &serialerror); if (serialerror) { *error = error_construct("unable to read response header"); serial::error_destruct(serialerror); return; } uint8_t checksum = checksum_response_header(header); if (checksum != header->cmdSum) { *error = error_construct("invalid response header checksum"); return; } bool ok = header->cmdByte1 == cmd[0] && header->cmdByte2 == cmd[1]; if (!ok) { *error = error_construct("invalid header response commands"); return; } } void read_response_param(serial::device_s serial, const uint8_t cmd[2], response_param_s* param, error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(param); SWEEP_ASSERT(error); serial::error_s serialerror = nullptr; serial::device_read(serial, param, sizeof(response_param_s), &serialerror); if (serialerror) { *error = error_construct("unable to read response param header"); serial::error_destruct(serialerror); return; } uint8_t checksum = checksum_response_param(param); if (checksum != param->cmdSum) { *error = error_construct("invalid response param header checksum"); return; } bool ok = param->cmdByte1 == cmd[0] && param->cmdByte2 == cmd[1]; if (!ok) { *error = error_construct("invalid param response commands"); return; } } void read_response_scan(serial::device_s serial, response_scan_packet_s* scan, error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(scan); SWEEP_ASSERT(error); serial::error_s serialerror = nullptr; serial::device_read(serial, scan, sizeof(response_scan_packet_s), &serialerror); if (serialerror) { *error = error_construct("invalid response scan packet checksum"); serial::error_destruct(serialerror); return; } uint8_t checksum = checksum_response_scan_packet(scan); if (checksum != scan->checksum) { *error = error_construct("invalid scan response commands"); return; } } void read_response_info_motor_ready(serial::device_s serial, const uint8_t cmd[2], response_info_motor_ready_s* info, error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(info); SWEEP_ASSERT(error); serial::error_s serialerror = nullptr; serial::device_read(serial, info, sizeof(response_info_motor_ready_s), &serialerror); if (serialerror) { *error = error_construct("unable to read response motor ready"); serial::error_destruct(serialerror); return; } bool ok = info->cmdByte1 == cmd[0] && info->cmdByte2 == cmd[1]; if (!ok) { *error = error_construct("invalid motor ready response commands"); return; } } void read_response_info_motor_speed(serial::device_s serial, const uint8_t cmd[2], response_info_motor_speed_s* info, error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(info); SWEEP_ASSERT(error); serial::error_s serialerror = nullptr; serial::device_read(serial, info, sizeof(response_info_motor_speed_s), &serialerror); if (serialerror) { *error = error_construct("unable to read response motor info"); serial::error_destruct(serialerror); return; } bool ok = info->cmdByte1 == cmd[0] && info->cmdByte2 == cmd[1]; if (!ok) { *error = error_construct("invalid motor info response commands"); return; } } void read_response_info_sample_rate(sweep::serial::device_s serial, const uint8_t cmd[2], response_info_sample_rate_s* info, error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(info); SWEEP_ASSERT(error); serial::error_s serialerror = nullptr; serial::device_read(serial, info, sizeof(response_info_sample_rate_s), &serialerror); if (serialerror) { *error = error_construct("unable to read response sample rate info"); serial::error_destruct(serialerror); return; } bool ok = info->cmdByte1 == cmd[0] && info->cmdByte2 == cmd[1]; if (!ok) { *error = error_construct("invalid sample rate info response commands"); return; } } } // ns protocol } // ns sweep <commit_msg>[libsweep/proto] Remove unused headers<commit_after>#include <chrono> #include <thread> #include "protocol.h" namespace sweep { namespace protocol { typedef struct error { const char* what; // always literal, do not deallocate } error; // Constructor hidden from users static error_s error_construct(const char* what) { SWEEP_ASSERT(what); auto out = new error{what}; return out; } const char* error_message(error_s error) { SWEEP_ASSERT(error); return error->what; } void error_destruct(error_s error) { SWEEP_ASSERT(error); delete error; } static uint8_t checksum_response_header(response_header_s* v) { SWEEP_ASSERT(v); return ((v->cmdStatusByte1 + v->cmdStatusByte2) & 0x3F) + 0x30; } static uint8_t checksum_response_param(response_param_s* v) { SWEEP_ASSERT(v); return ((v->cmdStatusByte1 + v->cmdStatusByte2) & 0x3F) + 0x30; } static uint8_t checksum_response_scan_packet(response_scan_packet_s* v) { SWEEP_ASSERT(v); uint64_t checksum = 0; checksum += v->sync_error; checksum += v->angle & 0xff00; checksum += v->angle & 0x00ff; checksum += v->distance & 0xff00; checksum += v->distance & 0x00ff; checksum += v->signal_strength; return checksum % 255; } void write_command(serial::device_s serial, const uint8_t cmd[2], error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(error); cmd_packet_s packet; packet.cmdByte1 = cmd[0]; packet.cmdByte2 = cmd[1]; packet.cmdParamTerm = '\n'; // pause for 2ms, so the device is never bombarded with back to back commands std::this_thread::sleep_for(std::chrono::milliseconds(2)); serial::error_s serialerror = nullptr; serial::device_write(serial, &packet, sizeof(cmd_packet_s), &serialerror); if (serialerror) { *error = error_construct("unable to write command"); serial::error_destruct(serialerror); return; } } void write_command_with_arguments(serial::device_s serial, const uint8_t cmd[2], const uint8_t arg[2], error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(arg); SWEEP_ASSERT(error); cmd_param_packet_s packet; packet.cmdByte1 = cmd[0]; packet.cmdByte2 = cmd[1]; packet.cmdParamByte1 = arg[0]; packet.cmdParamByte2 = arg[1]; packet.cmdParamTerm = '\n'; serial::error_s serialerror = nullptr; serial::device_write(serial, &packet, sizeof(cmd_param_packet_s), &serialerror); if (serialerror) { *error = error_construct("unable to write command with arguments"); serial::error_destruct(serialerror); return; } } void read_response_header(serial::device_s serial, const uint8_t cmd[2], response_header_s* header, error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(header); SWEEP_ASSERT(error); serial::error_s serialerror = nullptr; serial::device_read(serial, header, sizeof(response_header_s), &serialerror); if (serialerror) { *error = error_construct("unable to read response header"); serial::error_destruct(serialerror); return; } uint8_t checksum = checksum_response_header(header); if (checksum != header->cmdSum) { *error = error_construct("invalid response header checksum"); return; } bool ok = header->cmdByte1 == cmd[0] && header->cmdByte2 == cmd[1]; if (!ok) { *error = error_construct("invalid header response commands"); return; } } void read_response_param(serial::device_s serial, const uint8_t cmd[2], response_param_s* param, error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(param); SWEEP_ASSERT(error); serial::error_s serialerror = nullptr; serial::device_read(serial, param, sizeof(response_param_s), &serialerror); if (serialerror) { *error = error_construct("unable to read response param header"); serial::error_destruct(serialerror); return; } uint8_t checksum = checksum_response_param(param); if (checksum != param->cmdSum) { *error = error_construct("invalid response param header checksum"); return; } bool ok = param->cmdByte1 == cmd[0] && param->cmdByte2 == cmd[1]; if (!ok) { *error = error_construct("invalid param response commands"); return; } } void read_response_scan(serial::device_s serial, response_scan_packet_s* scan, error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(scan); SWEEP_ASSERT(error); serial::error_s serialerror = nullptr; serial::device_read(serial, scan, sizeof(response_scan_packet_s), &serialerror); if (serialerror) { *error = error_construct("invalid response scan packet checksum"); serial::error_destruct(serialerror); return; } uint8_t checksum = checksum_response_scan_packet(scan); if (checksum != scan->checksum) { *error = error_construct("invalid scan response commands"); return; } } void read_response_info_motor_ready(serial::device_s serial, const uint8_t cmd[2], response_info_motor_ready_s* info, error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(info); SWEEP_ASSERT(error); serial::error_s serialerror = nullptr; serial::device_read(serial, info, sizeof(response_info_motor_ready_s), &serialerror); if (serialerror) { *error = error_construct("unable to read response motor ready"); serial::error_destruct(serialerror); return; } bool ok = info->cmdByte1 == cmd[0] && info->cmdByte2 == cmd[1]; if (!ok) { *error = error_construct("invalid motor ready response commands"); return; } } void read_response_info_motor_speed(serial::device_s serial, const uint8_t cmd[2], response_info_motor_speed_s* info, error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(info); SWEEP_ASSERT(error); serial::error_s serialerror = nullptr; serial::device_read(serial, info, sizeof(response_info_motor_speed_s), &serialerror); if (serialerror) { *error = error_construct("unable to read response motor info"); serial::error_destruct(serialerror); return; } bool ok = info->cmdByte1 == cmd[0] && info->cmdByte2 == cmd[1]; if (!ok) { *error = error_construct("invalid motor info response commands"); return; } } void read_response_info_sample_rate(sweep::serial::device_s serial, const uint8_t cmd[2], response_info_sample_rate_s* info, error_s* error) { SWEEP_ASSERT(serial); SWEEP_ASSERT(cmd); SWEEP_ASSERT(info); SWEEP_ASSERT(error); serial::error_s serialerror = nullptr; serial::device_read(serial, info, sizeof(response_info_sample_rate_s), &serialerror); if (serialerror) { *error = error_construct("unable to read response sample rate info"); serial::error_destruct(serialerror); return; } bool ok = info->cmdByte1 == cmd[0] && info->cmdByte2 == cmd[1]; if (!ok) { *error = error_construct("invalid sample rate info response commands"); return; } } } // ns protocol } // ns sweep <|endoftext|>
<commit_before>#include <QtGui/QGuiApplication> #include <QtQml> #include <QtQuick/QQuickView> #include <QJsonDocument> #include <QJsonArray> #include <QSqlQuery> #include "kernel.h" #include "errorobject.h" #include "resource.h" #include "ilwistype.h" #include "catalog.h" #include "mastercatalog.h" #include "catalogview.h" #include "ilwiscontext.h" #include "datadefinition.h" #include "columndefinition.h" #include "table.h" #include "models/catalogfiltermodel.h" #include "models/mastercatalogmodel.h" #include "models/operationmodel.h" #include "models/operationcatalogmodel.h" #include "models/usermessagehandler.h" #include "applicationformexpressionparser.h" #include "workflowmetadataformbuilder.h" #include "models/tranquilizerhandler.h" #include "models/layermanager.h" #include "models/coveragelayermodel.h" #include "models/ilwisobjectmodel.h" #include "models/attributemodel.h" #include "models/domainitemmodel.h" #include "models/operationsbykeymodel.h" #include "models/uicontextmodel.h" #include "models/projectionparametermodel.h" #include "models/workflow/workflowmodel.h" #include "models/workflow/workflowcatalogmodel.h" #include "models/visualattributemodel.h" #include "models/tablemodel.h" #include "models/layerinfoitem.h" #include "models/catalogmapitem.h" #include "models/columnmodel.h" #include "models/graphmodel.h" #include "models/chartmodel.h" #include "models/consolescriptmodel.h" #include "models/tabmodel.h" #include "models/datapanemodel.h" #include "ilwiscoreui/propertyeditors/numericrepresentationsetter.h" #include "ilwiscoreui/tableoperations/tableoperation.h" #include "keyfilter.h" #define TEST_WORKINGDIR QString("file:///s:/data/coding/ilwis/2014-03-18_testdata") using namespace Ilwis; //using namespace Desktopclient; int main(int argc, char *argv[]) { try{ QGuiApplication app(argc, argv); QQmlApplicationEngine engine; QQmlContext *ctx = engine.rootContext(); Ilwis::initIlwis(Ilwis::rmDESKTOP); QFileInfo ilwisroot = context()->ilwisFolder(); QString qmlpluginpath = ilwisroot.absoluteFilePath() + "/extensions/ui"; engine.addImportPath(qmlpluginpath); engine.addPluginPath(qmlpluginpath); qmlRegisterType<MasterCatalogModel>("MasterCatalogModel",1,0,"MasterCatalogModel"); qmlRegisterType<CatalogModel>("CatalogModel",1,0,"CatalogModel"); qmlRegisterType<WorkSpaceModel>("WorkSpaceModel",1,0,"WorkSpaceModel"); qmlRegisterType<ResourceModel>("ResourceModel",1,0,"ResourceModel"); qmlRegisterType<OperationCatalogModel>("OperationCatalogModel",1,0,"OperationCatalogModel"); qmlRegisterType<OperationModel>("OperationModel",1,0,"OperationModel"); qmlRegisterType<ApplicationFormExpressionParser>("ApplicationFormExpressionParser",1,0,"FormBuilder"); qmlRegisterType<WorkflowMetadataFormBuilder>("WorkflowMetadataFormBuilder",1,0,"WorkflowMetadataFormBuilder"); qmlRegisterType<UserMessageHandler>("UserMessageHandler",1,0,"UserMessageHandler"); qmlRegisterType<MessageModel>("MessageModel",1,0,"MessageModel"); qmlRegisterType<TranquilizerHandler>("TranquilizerHandler",1,0, "TranquilizerHandler"); qmlRegisterType<TranquilizerModel>("TranquilizerModel",1,0, "TranquilizerModel"); qmlRegisterType<LayerManager>("LayerManager",1,0,"LayerManager"); qmlRegisterType<CoverageLayerModel>("CoverageLayerModel",1,0,"CoverageLayerModel"); qmlRegisterType<IlwisObjectModel>("IlwisObjectModel",1,0,"IlwisObjectModel"); qmlRegisterType<AttributeModel>("AttributeModel",1,0,"AttributeModel"); qmlRegisterType<DomainItemModel>("DomainItemModel",1,0,"DomainItemModel"); qmlRegisterType<OperationsByKeyModel>("OperationsByKeyModel",1,0,"OperationsByKeyModel"); qmlRegisterType<UIContextModel>("UIContextModel", 1,0, "UIContextModel"); qmlRegisterType<VisualAttributeEditor>("VisualAttributeEditor", 1,0, "VisualAttributeEditor"); qmlRegisterType<NumericRepresentationSetter>("NumericRepresentationSetter", 1,0, "NumericRepresentationSetter"); qmlRegisterType<RepresentationElement>("RepresentationElement", 1,0, "RepresentationElement"); qmlRegisterType<ProjectionParameterModel>("ProjectionParameterModel", 1,0, "ProjectionParameterModel"); qmlRegisterType<WorkflowCatalogModel>("WorkflowCatalogModel", 1,0, "WorkflowCatalogModel"); qmlRegisterType<WorkflowModel>("WorkflowModel", 1,0, "WorkflowModel"); qmlRegisterType<VisualAttributeModel>("VisualAttributeModel", 1,0,"VisualAttributeModel"); qmlRegisterType<TableModel>("TableModel", 1,0,"TableModel"); qmlRegisterType<Ilwis::Desktop::TableOperation>("TableOperation",1,0,"TableOperation"); qmlRegisterType<ColumnModel>("ColumnModel", 1,0,"ColumnModel"); qmlRegisterType<LayerInfoItem>("LayerInfoItem", 1,0,"LayerInfoItem"); qmlRegisterType<CatalogMapItem>("CatalogMapItem", 1,0,"CatalogMapItem"); qmlRegisterType<ChartModel>("ChartModel", 1,0,"ChartModel"); qmlRegisterType<GraphModel>("GraphModel", 1,0,"GraphModel"); qmlRegisterType<CatalogFilterModel>("CatalogFilterModel", 1,0,"CatalogFilterModel"); qmlRegisterType<ConsoleLineModel>("ConsoleLineModel", 1,0,"ConsoleLineModel"); qmlRegisterType<ConsoleScriptModel>("ConsoleScriptModel", 1,0,"ConsoleScriptModel"); qmlRegisterType<DataPaneModel>("DataPaneModel", 1,0,"DataPaneModel"); qmlRegisterType<TabModel>("TabModel", 1,0,"TabModel"); qmlRegisterType<SidePanelModel>("SidePanelModel", 1,0,"SidePanelModel"); MasterCatalogModel mastercatalogmodel(ctx); ApplicationFormExpressionParser formbuilder; WorkflowMetadataFormBuilder workflowmetadataformbuilder; UserMessageHandler messageHandler; OperationCatalogModel operations; TranquilizerHandler *tranquilizers = new TranquilizerHandler(); WorkflowCatalogModel workflows; DataPaneModel datapane; uicontext()->prepare(); uicontext()->qmlContext(ctx); operations.prepare(); QThread *trqthread = new QThread; ctx->setContextProperty("mastercatalog", &mastercatalogmodel); ctx->setContextProperty("formbuilder", &formbuilder); ctx->setContextProperty("workflowmetadataformbuilder", &workflowmetadataformbuilder); ctx->setContextProperty("messagehandler", &messageHandler); ctx->setContextProperty("tranquilizerHandler", tranquilizers); ctx->setContextProperty("operations", &operations); ctx->setContextProperty("workflows", &workflows); ctx->setContextProperty("datapane", &datapane); ctx->setContextProperty("uicontext", uicontext().get()); mastercatalogmodel.connect(&operations, &OperationCatalogModel::updateCatalog,&mastercatalogmodel, &MasterCatalogModel::updateCatalog ); mastercatalogmodel.connect(&workflows, &WorkflowCatalogModel::updateCatalog,&mastercatalogmodel, &MasterCatalogModel::updateCatalog ); operations.connect(uicontext().get(),&UIContextModel::currentWorkSpaceChanged, &operations, &OperationCatalogModel::workSpaceChanged); messageHandler.connect(kernel()->issues().data(), &IssueLogger::updateIssues,&messageHandler, &UserMessageHandler::addMessage ); TranquilizerWorker *trw = new TranquilizerWorker; trw->moveToThread(trqthread); trqthread->connect(kernel(), &Kernel::updateTranquilizer, trw, &TranquilizerWorker::updateTranquilizer); trqthread->connect(kernel(), &Kernel::createTranquilizer, trw, &TranquilizerWorker::createTranquilizer); trqthread->connect(kernel(), &Kernel::removeTranquilizer, trw, &TranquilizerWorker::removeTranquilizer); trqthread->connect(trw, &TranquilizerWorker::sendUpdateTranquilizer, tranquilizers, &TranquilizerHandler::updateTranquilizer); trqthread->connect(trw, &TranquilizerWorker::sendCreateTranquilizer, tranquilizers, &TranquilizerHandler::createTranquilizer); trqthread->connect(trw, &TranquilizerWorker::sendRemoveTranquilizer, tranquilizers, &TranquilizerHandler::removeTranquilizer); engine.load("qml/DesktopClient.qml"); QObject *topLevel = engine.rootObjects().value(0); uicontext()->rootObject(topLevel); QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel); window->setIcon(QIcon("./qml/images/ilwis4.bmp")); if ( !window ) { qWarning("Error: Your root item has to be a Window."); return -1; } // mastercatalogmodel.root(window); window->show(); KeyFilter keys; app.installEventFilter(&keys); trqthread->start(); uicontext()->initializeDataPane(); int ret = app.exec(); Ilwis::exitIlwis(); return ret; }catch (const ErrorObject& err){ qDebug() << err.message(); } return 0; } <commit_msg>added the objectcreator which handles the creation of ilwisobjects from scatch<commit_after>#include <QtGui/QGuiApplication> #include <QtQml> #include <QtQuick/QQuickView> #include <QJsonDocument> #include <QJsonArray> #include <QSqlQuery> #include "kernel.h" #include "errorobject.h" #include "resource.h" #include "ilwistype.h" #include "catalog.h" #include "mastercatalog.h" #include "catalogview.h" #include "ilwiscontext.h" #include "datadefinition.h" #include "columndefinition.h" #include "table.h" #include "models/catalogfiltermodel.h" #include "models/mastercatalogmodel.h" #include "models/operationmodel.h" #include "models/operationcatalogmodel.h" #include "models/usermessagehandler.h" #include "applicationformexpressionparser.h" #include "workflowmetadataformbuilder.h" #include "models/tranquilizerhandler.h" #include "models/layermanager.h" #include "models/coveragelayermodel.h" #include "models/ilwisobjectmodel.h" #include "models/attributemodel.h" #include "models/domainitemmodel.h" #include "models/operationsbykeymodel.h" #include "models/uicontextmodel.h" #include "models/projectionparametermodel.h" #include "models/workflow/workflowmodel.h" #include "models/workflow/workflowcatalogmodel.h" #include "models/visualattributemodel.h" #include "models/tablemodel.h" #include "models/layerinfoitem.h" #include "models/catalogmapitem.h" #include "models/columnmodel.h" #include "models/graphmodel.h" #include "models/chartmodel.h" #include "models/consolescriptmodel.h" #include "models/tabmodel.h" #include "models/datapanemodel.h" #include "models/objectcreator.h" #include "ilwiscoreui/propertyeditors/numericrepresentationsetter.h" #include "ilwiscoreui/tableoperations/tableoperation.h" #include "keyfilter.h" #define TEST_WORKINGDIR QString("file:///s:/data/coding/ilwis/2014-03-18_testdata") using namespace Ilwis; //using namespace Desktopclient; int main(int argc, char *argv[]) { try{ QGuiApplication app(argc, argv); QQmlApplicationEngine engine; QQmlContext *ctx = engine.rootContext(); Ilwis::initIlwis(Ilwis::rmDESKTOP); QFileInfo ilwisroot = context()->ilwisFolder(); QString qmlpluginpath = ilwisroot.absoluteFilePath() + "/extensions/ui"; engine.addImportPath(qmlpluginpath); engine.addPluginPath(qmlpluginpath); qmlRegisterType<MasterCatalogModel>("MasterCatalogModel",1,0,"MasterCatalogModel"); qmlRegisterType<CatalogModel>("CatalogModel",1,0,"CatalogModel"); qmlRegisterType<WorkSpaceModel>("WorkSpaceModel",1,0,"WorkSpaceModel"); qmlRegisterType<ResourceModel>("ResourceModel",1,0,"ResourceModel"); qmlRegisterType<OperationCatalogModel>("OperationCatalogModel",1,0,"OperationCatalogModel"); qmlRegisterType<OperationModel>("OperationModel",1,0,"OperationModel"); qmlRegisterType<ApplicationFormExpressionParser>("ApplicationFormExpressionParser",1,0,"FormBuilder"); qmlRegisterType<WorkflowMetadataFormBuilder>("WorkflowMetadataFormBuilder",1,0,"WorkflowMetadataFormBuilder"); qmlRegisterType<UserMessageHandler>("UserMessageHandler",1,0,"UserMessageHandler"); qmlRegisterType<MessageModel>("MessageModel",1,0,"MessageModel"); qmlRegisterType<TranquilizerHandler>("TranquilizerHandler",1,0, "TranquilizerHandler"); qmlRegisterType<TranquilizerModel>("TranquilizerModel",1,0, "TranquilizerModel"); qmlRegisterType<LayerManager>("LayerManager",1,0,"LayerManager"); qmlRegisterType<CoverageLayerModel>("CoverageLayerModel",1,0,"CoverageLayerModel"); qmlRegisterType<IlwisObjectModel>("IlwisObjectModel",1,0,"IlwisObjectModel"); qmlRegisterType<AttributeModel>("AttributeModel",1,0,"AttributeModel"); qmlRegisterType<DomainItemModel>("DomainItemModel",1,0,"DomainItemModel"); qmlRegisterType<OperationsByKeyModel>("OperationsByKeyModel",1,0,"OperationsByKeyModel"); qmlRegisterType<UIContextModel>("UIContextModel", 1,0, "UIContextModel"); qmlRegisterType<VisualAttributeEditor>("VisualAttributeEditor", 1,0, "VisualAttributeEditor"); qmlRegisterType<NumericRepresentationSetter>("NumericRepresentationSetter", 1,0, "NumericRepresentationSetter"); qmlRegisterType<RepresentationElement>("RepresentationElement", 1,0, "RepresentationElement"); qmlRegisterType<ProjectionParameterModel>("ProjectionParameterModel", 1,0, "ProjectionParameterModel"); qmlRegisterType<WorkflowCatalogModel>("WorkflowCatalogModel", 1,0, "WorkflowCatalogModel"); qmlRegisterType<WorkflowModel>("WorkflowModel", 1,0, "WorkflowModel"); qmlRegisterType<VisualAttributeModel>("VisualAttributeModel", 1,0,"VisualAttributeModel"); qmlRegisterType<TableModel>("TableModel", 1,0,"TableModel"); qmlRegisterType<Ilwis::Desktop::TableOperation>("TableOperation",1,0,"TableOperation"); qmlRegisterType<ColumnModel>("ColumnModel", 1,0,"ColumnModel"); qmlRegisterType<LayerInfoItem>("LayerInfoItem", 1,0,"LayerInfoItem"); qmlRegisterType<CatalogMapItem>("CatalogMapItem", 1,0,"CatalogMapItem"); qmlRegisterType<ChartModel>("ChartModel", 1,0,"ChartModel"); qmlRegisterType<GraphModel>("GraphModel", 1,0,"GraphModel"); qmlRegisterType<CatalogFilterModel>("CatalogFilterModel", 1,0,"CatalogFilterModel"); qmlRegisterType<ConsoleLineModel>("ConsoleLineModel", 1,0,"ConsoleLineModel"); qmlRegisterType<ConsoleScriptModel>("ConsoleScriptModel", 1,0,"ConsoleScriptModel"); qmlRegisterType<DataPaneModel>("DataPaneModel", 1,0,"DataPaneModel"); qmlRegisterType<TabModel>("TabModel", 1,0,"TabModel"); qmlRegisterType<SidePanelModel>("SidePanelModel", 1,0,"SidePanelModel"); qmlRegisterType<ObjectCreator>("ObjectCreator", 1,0,"ObjectCreator"); MasterCatalogModel mastercatalogmodel(ctx); ApplicationFormExpressionParser formbuilder; WorkflowMetadataFormBuilder workflowmetadataformbuilder; UserMessageHandler messageHandler; OperationCatalogModel operations; TranquilizerHandler *tranquilizers = new TranquilizerHandler(); WorkflowCatalogModel workflows; DataPaneModel datapane; ObjectCreator objcreator; uicontext()->prepare(); uicontext()->qmlContext(ctx); operations.prepare(); QThread *trqthread = new QThread; ctx->setContextProperty("mastercatalog", &mastercatalogmodel); ctx->setContextProperty("formbuilder", &formbuilder); ctx->setContextProperty("workflowmetadataformbuilder", &workflowmetadataformbuilder); ctx->setContextProperty("messagehandler", &messageHandler); ctx->setContextProperty("tranquilizerHandler", tranquilizers); ctx->setContextProperty("operations", &operations); ctx->setContextProperty("workflows", &workflows); ctx->setContextProperty("datapane", &datapane); ctx->setContextProperty("objectcreator", &objcreator); ctx->setContextProperty("uicontext", uicontext().get()); mastercatalogmodel.connect(&operations, &OperationCatalogModel::updateCatalog,&mastercatalogmodel, &MasterCatalogModel::updateCatalog ); mastercatalogmodel.connect(&workflows, &WorkflowCatalogModel::updateCatalog,&mastercatalogmodel, &MasterCatalogModel::updateCatalog ); operations.connect(uicontext().get(),&UIContextModel::currentWorkSpaceChanged, &operations, &OperationCatalogModel::workSpaceChanged); messageHandler.connect(kernel()->issues().data(), &IssueLogger::updateIssues,&messageHandler, &UserMessageHandler::addMessage ); TranquilizerWorker *trw = new TranquilizerWorker; trw->moveToThread(trqthread); trqthread->connect(kernel(), &Kernel::updateTranquilizer, trw, &TranquilizerWorker::updateTranquilizer); trqthread->connect(kernel(), &Kernel::createTranquilizer, trw, &TranquilizerWorker::createTranquilizer); trqthread->connect(kernel(), &Kernel::removeTranquilizer, trw, &TranquilizerWorker::removeTranquilizer); trqthread->connect(trw, &TranquilizerWorker::sendUpdateTranquilizer, tranquilizers, &TranquilizerHandler::updateTranquilizer); trqthread->connect(trw, &TranquilizerWorker::sendCreateTranquilizer, tranquilizers, &TranquilizerHandler::createTranquilizer); trqthread->connect(trw, &TranquilizerWorker::sendRemoveTranquilizer, tranquilizers, &TranquilizerHandler::removeTranquilizer); engine.load("qml/DesktopClient.qml"); QObject *topLevel = engine.rootObjects().value(0); uicontext()->rootObject(topLevel); QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel); window->setIcon(QIcon("./qml/images/ilwis4.bmp")); if ( !window ) { qWarning("Error: Your root item has to be a Window."); return -1; } // mastercatalogmodel.root(window); window->show(); KeyFilter keys; app.installEventFilter(&keys); trqthread->start(); uicontext()->initializeDataPane(); int ret = app.exec(); Ilwis::exitIlwis(); return ret; }catch (const ErrorObject& err){ qDebug() << err.message(); } return 0; } <|endoftext|>
<commit_before>#ifndef VAST_ALIASES_HPP #define VAST_ALIASES_HPP #include <cstdint> #include <limits> #include <map> #include <memory> #include <set> #include <vector> namespace vast { // -- data ------------------------------------------------------------------- class data; using boolean = bool; using integer = int64_t; using count = uint64_t; using real = double; /// A random-access sequence of data. using vector = std::vector<data>; /// A mathematical set where each element is ::data. using set = std::set<data>; /// An associative array with ::data as both key and value. using table = std::map<data, data>; // --------------------------------------------------------------------------- class ewah_bitstream; using default_bitstream = ewah_bitstream; /// Uniquely identifies a VAST event. using event_id = uint64_t; /// The ID for invalid events constexpr event_id invalid_event_id = std::numeric_limits<event_id>::max(); /// The largest possible event ID. constexpr event_id max_event_id = invalid_event_id - 1; /// The largest possible event ID. constexpr event_id max_events = max_event_id + 1; /// Uniquely identifies a VAST type. using type_id = uint64_t; /// The data type for an enumeration. using enumeration = uint32_t; } // namespace vast #endif <commit_msg>Fix documentation<commit_after>#ifndef VAST_ALIASES_HPP #define VAST_ALIASES_HPP #include <cstdint> #include <limits> #include <map> #include <memory> #include <set> #include <vector> namespace vast { // -- data ------------------------------------------------------------------- class data; using boolean = bool; using integer = int64_t; using count = uint64_t; using real = double; /// A random-access sequence of data. using vector = std::vector<data>; /// A mathematical set where each element is ::data. using set = std::set<data>; /// An associative array with ::data as both key and value. using table = std::map<data, data>; // --------------------------------------------------------------------------- class ewah_bitstream; using default_bitstream = ewah_bitstream; /// Uniquely identifies a VAST event. using event_id = uint64_t; /// The ID for invalid events constexpr event_id invalid_event_id = std::numeric_limits<event_id>::max(); /// The largest possible event ID. constexpr event_id max_event_id = invalid_event_id - 1; /// The largest number of representable events. constexpr event_id max_events = max_event_id + 1; /// Uniquely identifies a VAST type. using type_id = uint64_t; /// The data type for an enumeration. using enumeration = uint32_t; } // namespace vast #endif <|endoftext|>
<commit_before>/** * @file rodsfindwindow.cpp * @brief Implementation of class RodsFindWindow * * The RodsFindWindow class extends the Qt window class QMainWindow and * implements an iRODS find window UI. * * Copyright (C) 2014-2015 University of Jyväskylä. All rights reserved. * License: The BSD 3-Clause License, see LICENSE file for details. * * @author Ilari Korhonen */ // application class RodsFindWindow header #include "rodsfindwindow.h" // generated UI class Ui::RodsFindWindow header #include "ui_rodsfindwindow.h" RodsFindWindow::RodsFindWindow(Kanki::RodsConnection *rodsConn, QWidget *parent) : QMainWindow(parent), ui(new Ui::RodsFindWindow) { this->conn = rodsConn; this->ui->setupUi(this); this->ui->criteriaLayout->setAlignment(Qt::AlignTop); // setup combo box for condition selection this->ui->condSel->addItem("Data Object Name", RodsFindWindow::DataObjName); this->ui->condSel->addItem("Data Object Checksum", RodsFindWindow::DataObjChksum); this->ui->condSel->addItem("Collection Name (Path)", RodsFindWindow::CollName); // connect ui event signals to handler slots connect(this->ui->condAdd, &QPushButton::clicked, this, &RodsFindWindow::addCondition); connect(this->ui->actionExecute, &QAction::triggered, this, &RodsFindWindow::executeSearch); } RodsFindWindow::~RodsFindWindow() { delete (this->ui); // delete dynamically created widgets for (std::vector<RodsConditionWidget*>::iterator i = this->condWidgets.begin(); i != this->condWidgets.end(); i++) { RodsConditionWidget *ptr = *i; delete (ptr); } } void RodsFindWindow::closeEvent(QCloseEvent *event) { (void)event; // signal out unregistering this->unregister(); } void RodsFindWindow::addCondition() { RodsConditionWidget *widget = NULL; int cond = this->ui->condSel->currentData().toInt(); QString label = this->ui->condSel->currentText(); // depending on condition, instantiate appropriate widget switch (cond) { case RodsFindWindow::DataObjName: widget = new RodsStringConditionWidget(COL_DATA_NAME, label); break; case RodsFindWindow::DataObjChksum: widget = new RodsStringConditionWidget(COL_D_DATA_CHECKSUM, label); break; case RodsFindWindow::CollName: widget = new RodsStringConditionWidget(COL_COLL_NAME, label); break; default: break; } // if we have a widget, add it if (widget) { this->ui->criteriaLayout->addWidget(widget); this->condWidgets.push_back(widget); } } void RodsFindWindow::executeSearch() { int status = 0; Kanki::RodsGenQuery query(this->conn); query.addQueryAttribute(COL_DATA_NAME); query.addQueryAttribute(COL_COLL_NAME); // evaluate genquery conditions from the condition widgets for (std::vector<RodsConditionWidget*>::iterator i = this->condWidgets.begin(); i != this->condWidgets.end(); i++) { RodsConditionWidget *widget = *i; widget->evaluateConds(&query); } if (this->conn->isReady()) { if ((status = query.execute()) < 0) { // report error } // when success, parse thru query result set else { std::vector<std::string> names = query.getResultSetForAttr(COL_DATA_NAME); std::vector<std::string> colls = query.getResultSetForAttr(COL_COLL_NAME); for (unsigned int i = 0; i < names.size() && i < colls.size(); i++) { QTreeWidgetItem *item = new QTreeWidgetItem(); std::string path = colls.at(i) + '/' + names.at(i); item->setText(0, path.c_str()); this->ui->treeWidget->addTopLevelItem(item); } } } } <commit_msg>report query result set size and execution time in status bar<commit_after>/** * @file rodsfindwindow.cpp * @brief Implementation of class RodsFindWindow * * The RodsFindWindow class extends the Qt window class QMainWindow and * implements an iRODS find window UI. * * Copyright (C) 2014-2015 University of Jyväskylä. All rights reserved. * License: The BSD 3-Clause License, see LICENSE file for details. * * @author Ilari Korhonen */ // application class RodsFindWindow header #include "rodsfindwindow.h" // generated UI class Ui::RodsFindWindow header #include "ui_rodsfindwindow.h" RodsFindWindow::RodsFindWindow(Kanki::RodsConnection *rodsConn, QWidget *parent) : QMainWindow(parent), ui(new Ui::RodsFindWindow) { this->conn = rodsConn; this->ui->setupUi(this); this->ui->criteriaLayout->setAlignment(Qt::AlignTop); // setup combo box for condition selection this->ui->condSel->addItem("Data Object Name", RodsFindWindow::DataObjName); this->ui->condSel->addItem("Data Object Checksum", RodsFindWindow::DataObjChksum); this->ui->condSel->addItem("Collection Name (Path)", RodsFindWindow::CollName); // connect ui event signals to handler slots connect(this->ui->condAdd, &QPushButton::clicked, this, &RodsFindWindow::addCondition); connect(this->ui->actionExecute, &QAction::triggered, this, &RodsFindWindow::executeSearch); } RodsFindWindow::~RodsFindWindow() { delete (this->ui); // delete dynamically created widgets for (std::vector<RodsConditionWidget*>::iterator i = this->condWidgets.begin(); i != this->condWidgets.end(); i++) { RodsConditionWidget *ptr = *i; delete (ptr); } } void RodsFindWindow::closeEvent(QCloseEvent *event) { (void)event; // signal out unregistering this->unregister(); } void RodsFindWindow::addCondition() { RodsConditionWidget *widget = NULL; int cond = this->ui->condSel->currentData().toInt(); QString label = this->ui->condSel->currentText(); // depending on condition, instantiate appropriate widget switch (cond) { case RodsFindWindow::DataObjName: widget = new RodsStringConditionWidget(COL_DATA_NAME, label); break; case RodsFindWindow::DataObjChksum: widget = new RodsStringConditionWidget(COL_D_DATA_CHECKSUM, label); break; case RodsFindWindow::CollName: widget = new RodsStringConditionWidget(COL_COLL_NAME, label); break; default: break; } // if we have a widget, add it if (widget) { this->ui->criteriaLayout->addWidget(widget); this->condWidgets.push_back(widget); } } void RodsFindWindow::executeSearch() { int status = 0; Kanki::RodsGenQuery query(this->conn); query.addQueryAttribute(COL_DATA_NAME); query.addQueryAttribute(COL_COLL_NAME); // evaluate genquery conditions from the condition widgets for (std::vector<RodsConditionWidget*>::iterator i = this->condWidgets.begin(); i != this->condWidgets.end(); i++) { RodsConditionWidget *widget = *i; widget->evaluateConds(&query); } if (this->conn->isReady()) { // execute a timed query std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now(); status = query.execute(); std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); // report errors if (status < 0) { } // when success, parse thru query result set else { std::vector<std::string> names = query.getResultSetForAttr(COL_DATA_NAME); std::vector<std::string> colls = query.getResultSetForAttr(COL_COLL_NAME); std::chrono::milliseconds diff = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0); QString statusMsg = "Search query successful: " + QVariant((int)names.size()).toString(); statusMsg += " results (execution time " + QVariant(((double)diff.count() / (double)1000)).toString() + " sec)."; this->statusBar()->showMessage(statusMsg); for (unsigned int i = 0; i < names.size() && i < colls.size(); i++) { QTreeWidgetItem *item = new QTreeWidgetItem(); std::string path = colls.at(i) + '/' + names.at(i); item->setText(0, path.c_str()); this->ui->treeWidget->addTopLevelItem(item); } } } } <|endoftext|>
<commit_before>/* * IceWM * * Copyright (C) 1997-2001 Marko Macek */ #include "config.h" #include "ylib.h" #include <X11/keysym.h> #include "wmcontainer.h" #include "wmframe.h" #include "yxapp.h" #include "prefs.h" #include <stdio.h> YClientContainer::YClientContainer(YWindow *parent, YFrameWindow *frame) :YWindow(parent) { fFrame = frame; fHaveGrab = false; fHaveActionGrab = false; setStyle(wsManager); setDoubleBuffer(false); setPointer(YXApplication::leftPointer); } YClientContainer::~YClientContainer() { releaseButtons(); } void YClientContainer::handleButton(const XButtonEvent &button) { bool doRaise = false; bool doActivate = false; bool firstClick = false; if (!(button.state & ControlMask) && (buttonRaiseMask & (1 << (button.button - 1))) && (!useMouseWheel || (button.button != 4 && button.button != 5))) { if (focusOnClickClient) { if (!getFrame()->isTypeDock()) { doActivate = true; if (getFrame()->canFocusByMouse() && !getFrame()->focused()) firstClick = true; } } if (raiseOnClickClient) { doRaise = true; if (getFrame()->canRaise()) firstClick = true; } } #if 1 if (clientMouseActions) { unsigned int k = button.button + XK_Pointer_Button1 - 1; unsigned int m = KEY_MODMASK(button.state); unsigned int vm = VMod(m); if (IS_WMKEY(k, vm, gMouseWinSize)) { XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); int px = button.x + x(); int py = button.y + y(); int gx = (px * 3 / (int)width() - 1); int gy = (py * 3 / (int)height() - 1); if (gx < 0) gx = -1; if (gx > 0) gx = 1; if (gy < 0) gy = -1; if (gy > 0) gy = 1; bool doMove = (gx == 0 && gy == 0) ? true : false; int mx, my; if (doMove) { mx = px; my = py; } else { mx = button.x_root; my = button.y_root; } if ((doMove && getFrame()->canMove()) || (!doMove && getFrame()->canSize())) { getFrame()->startMoveSize(doMove, true, gx, gy, mx, my); } return ; } else if (IS_WMKEY(k, vm, gMouseWinMove)) { XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); if (getFrame()->canMove()) { int px = button.x + x(); int py = button.y + y(); getFrame()->startMoveSize(true, true, 0, 0, px, py); } return ; } else if (IS_WMKEY(k, vm, gMouseWinRaise)) { XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); getFrame()->wmRaise(); return ; } } #endif ///!!! do this first? if (doActivate) getFrame()->activate(); if (doRaise) getFrame()->wmRaise(); ///!!! it might be nice if this was per-window option (app-request) if (!firstClick || passFirstClickToClient) XAllowEvents(xapp->display(), ReplayPointer, CurrentTime); else XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); XSync(xapp->display(), False); } // manage button grab on frame window to capture clicks to client window // we want to keep the grab when: // focusOnClickClient && not focused // || raiseOnClickClient && not can be raised // ('not on top' != 'can be raised') // the difference is when we have transients and explicitFocus // also there is the difference with layers and multiple workspaces void YClientContainer::grabButtons() { grabActions(); if (!fHaveGrab && (clickFocus || focusOnClickClient || raiseOnClickClient)) { fHaveGrab = true; XGrabButton(xapp->display(), AnyButton, AnyModifier, handle(), True, ButtonPressMask, GrabModeSync, GrabModeAsync, None, None); } } void YClientContainer::releaseButtons() { if (fHaveGrab) { fHaveGrab = false; XUngrabButton(xapp->display(), AnyButton, AnyModifier, handle()); fHaveActionGrab = false; } grabActions(); } void YClientContainer::regrabMouse() { XUngrabButton(xapp->display(), AnyButton, AnyModifier, handle()); if (fHaveActionGrab) { fHaveActionGrab = false; grabActions(); } if (fHaveGrab ) { fHaveGrab = false; grabButtons(); } } void YClientContainer::grabActions() { if (clientMouseActions) { if (!fHaveActionGrab) { fHaveActionGrab = true; if (gMouseWinMove.key != 0) grabVButton(gMouseWinMove.key - XK_Pointer_Button1 + 1, gMouseWinMove.mod); if (gMouseWinSize.key != 0) grabVButton(gMouseWinSize.key - XK_Pointer_Button1 + 1, gMouseWinSize.mod); if (gMouseWinRaise.key != 0) grabVButton(gMouseWinRaise.key - XK_Pointer_Button1 + 1, gMouseWinRaise.mod); } } } void YClientContainer::handleConfigureRequest(const XConfigureRequestEvent &configureRequest) { MSG(("configure request in frame")); if (getFrame() && configureRequest.window == getFrame()->client()->handle()) { XConfigureRequestEvent cre = configureRequest; getFrame()->configureClient(cre); } } void YClientContainer::handleMapRequest(const XMapRequestEvent &mapRequest) { if (mapRequest.window == getFrame()->client()->handle()) { manager->lockFocus(); getFrame()->setState(WinStateMinimized | WinStateHidden | WinStateRollup, 0); manager->unlockFocus(); bool doActivate = true; getFrame()->updateFocusOnMap(doActivate); if (doActivate) { getFrame()->activateWindow(true); } } } void YClientContainer::handleCrossing(const XCrossingEvent &crossing) { if (getFrame() && pointerColormap) { if (crossing.type == EnterNotify) manager->setColormapWindow(getFrame()); else if (crossing.type == LeaveNotify && crossing.detail != NotifyInferior && crossing.mode == NotifyNormal && manager->colormapWindow() == getFrame()) { manager->setColormapWindow(0); } } } // vim: set sw=4 ts=4 et: <commit_msg>Only grab buttons 1,2,3, but not 4+5. This solves all scroll wheel problems in issue #202.<commit_after>/* * IceWM * * Copyright (C) 1997-2001 Marko Macek */ #include "config.h" #include "ylib.h" #include <X11/keysym.h> #include "wmcontainer.h" #include "wmframe.h" #include "yxapp.h" #include "prefs.h" #include <stdio.h> YClientContainer::YClientContainer(YWindow *parent, YFrameWindow *frame) :YWindow(parent) { fFrame = frame; fHaveGrab = false; fHaveActionGrab = false; setStyle(wsManager); setDoubleBuffer(false); setPointer(YXApplication::leftPointer); } YClientContainer::~YClientContainer() { releaseButtons(); } void YClientContainer::handleButton(const XButtonEvent &button) { bool doRaise = false; bool doActivate = false; bool firstClick = false; if (!(button.state & ControlMask) && (buttonRaiseMask & (1 << (button.button - 1))) && (!useMouseWheel || (button.button != 4 && button.button != 5))) { if (focusOnClickClient) { if (!getFrame()->isTypeDock()) { doActivate = true; if (getFrame()->canFocusByMouse() && !getFrame()->focused()) firstClick = true; } } if (raiseOnClickClient) { doRaise = true; if (getFrame()->canRaise()) firstClick = true; } } #if 1 if (clientMouseActions) { unsigned int k = button.button + XK_Pointer_Button1 - 1; unsigned int m = KEY_MODMASK(button.state); unsigned int vm = VMod(m); if (IS_WMKEY(k, vm, gMouseWinSize)) { XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); int px = button.x + x(); int py = button.y + y(); int gx = (px * 3 / (int)width() - 1); int gy = (py * 3 / (int)height() - 1); if (gx < 0) gx = -1; if (gx > 0) gx = 1; if (gy < 0) gy = -1; if (gy > 0) gy = 1; bool doMove = (gx == 0 && gy == 0) ? true : false; int mx, my; if (doMove) { mx = px; my = py; } else { mx = button.x_root; my = button.y_root; } if ((doMove && getFrame()->canMove()) || (!doMove && getFrame()->canSize())) { getFrame()->startMoveSize(doMove, true, gx, gy, mx, my); } return ; } else if (IS_WMKEY(k, vm, gMouseWinMove)) { XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); if (getFrame()->canMove()) { int px = button.x + x(); int py = button.y + y(); getFrame()->startMoveSize(true, true, 0, 0, px, py); } return ; } else if (IS_WMKEY(k, vm, gMouseWinRaise)) { XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); getFrame()->wmRaise(); return ; } } #endif ///!!! do this first? if (doActivate) getFrame()->activate(); if (doRaise) getFrame()->wmRaise(); ///!!! it might be nice if this was per-window option (app-request) if (!firstClick || passFirstClickToClient) XAllowEvents(xapp->display(), ReplayPointer, CurrentTime); else XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); XSync(xapp->display(), False); } // manage button grab on frame window to capture clicks to client window // we want to keep the grab when: // focusOnClickClient && not focused // || raiseOnClickClient && not can be raised // ('not on top' != 'can be raised') // the difference is when we have transients and explicitFocus // also there is the difference with layers and multiple workspaces void YClientContainer::grabButtons() { grabActions(); if (!fHaveGrab && (clickFocus || focusOnClickClient || raiseOnClickClient)) { fHaveGrab = true; XGrabButton(xapp->display(), Button1, AnyModifier, handle(), True, ButtonPressMask, GrabModeSync, GrabModeAsync, None, None); XGrabButton(xapp->display(), Button2, AnyModifier, handle(), True, ButtonPressMask, GrabModeSync, GrabModeAsync, None, None); XGrabButton(xapp->display(), Button3, AnyModifier, handle(), True, ButtonPressMask, GrabModeSync, GrabModeAsync, None, None); } } void YClientContainer::releaseButtons() { if (fHaveGrab) { fHaveGrab = false; XUngrabButton(xapp->display(), Button1, AnyModifier, handle()); XUngrabButton(xapp->display(), Button2, AnyModifier, handle()); XUngrabButton(xapp->display(), Button3, AnyModifier, handle()); fHaveActionGrab = false; } grabActions(); } void YClientContainer::regrabMouse() { XUngrabButton(xapp->display(), Button1, AnyModifier, handle()); XUngrabButton(xapp->display(), Button2, AnyModifier, handle()); XUngrabButton(xapp->display(), Button3, AnyModifier, handle()); if (fHaveActionGrab) { fHaveActionGrab = false; grabActions(); } if (fHaveGrab ) { fHaveGrab = false; grabButtons(); } } void YClientContainer::grabActions() { if (clientMouseActions && fHaveActionGrab == false) { fHaveActionGrab = true; const KeySym minButton = XK_Pointer_Button1; const KeySym maxButton = XK_Pointer_Button3; const KeySym xkButton0 = XK_Pointer_Button1 - 1; if (inrange(gMouseWinMove.key, minButton, maxButton)) grabVButton(gMouseWinMove.key - xkButton0, gMouseWinMove.mod); if (inrange(gMouseWinSize.key, minButton, maxButton)) grabVButton(gMouseWinSize.key - xkButton0, gMouseWinSize.mod); if (inrange(gMouseWinRaise.key, minButton, maxButton)) grabVButton(gMouseWinRaise.key - xkButton0, gMouseWinRaise.mod); } } void YClientContainer::handleConfigureRequest(const XConfigureRequestEvent &configureRequest) { MSG(("configure request in frame")); if (getFrame() && configureRequest.window == getFrame()->client()->handle()) { XConfigureRequestEvent cre = configureRequest; getFrame()->configureClient(cre); } } void YClientContainer::handleMapRequest(const XMapRequestEvent &mapRequest) { if (mapRequest.window == getFrame()->client()->handle()) { manager->lockFocus(); getFrame()->setState(WinStateMinimized | WinStateHidden | WinStateRollup, 0); manager->unlockFocus(); bool doActivate = true; getFrame()->updateFocusOnMap(doActivate); if (doActivate) { getFrame()->activateWindow(true); } } } void YClientContainer::handleCrossing(const XCrossingEvent &crossing) { if (getFrame() && pointerColormap) { if (crossing.type == EnterNotify) manager->setColormapWindow(getFrame()); else if (crossing.type == LeaveNotify && crossing.detail != NotifyInferior && crossing.mode == NotifyNormal && manager->colormapWindow() == getFrame()) { manager->setColormapWindow(0); } } } // vim: set sw=4 ts=4 et: <|endoftext|>
<commit_before>// Copyright (c) 2017-2019 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "server.h" #include "validation.h" #include "llmq/quorums.h" #include "llmq/quorums_blockprocessor.h" #include "llmq/quorums_debug.h" #include "llmq/quorums_dkgsession.h" #include "llmq/quorums_signing.h" void quorum_list_help() { throw std::runtime_error( "quorum list ( count )\n" "\nArguments:\n" "1. count (number, optional) Number of quorums to list. Will list active quorums\n" " if \"count\" is not specified.\n" "\nResult:\n" "{\n" " \"quorumName\" : [ (array of strings) List of quorum hashes per some quorum type.\n" " \"quorumHash\" (string) Quorum hash. Note: most recent quorums come first.\n" " ,...\n" " ],\n" "}\n" "\nExamples:\n" + HelpExampleCli("quorum", "list") + HelpExampleCli("quorum", "list 10") + HelpExampleRpc("quorum", "list, 10") ); } UniValue quorum_list(const JSONRPCRequest& request) { if (request.fHelp || (request.params.size() != 1 && request.params.size() != 2)) quorum_list_help(); LOCK(cs_main); int count = -1; if (request.params.size() > 1) { count = ParseInt32V(request.params[1], "count"); if (count < 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, "count can't be negative"); } } UniValue ret(UniValue::VOBJ); for (auto& p : Params().GetConsensus().llmqs) { UniValue v(UniValue::VARR); auto quorums = llmq::quorumManager->ScanQuorums(p.first, chainActive.Tip(), count > -1 ? count : p.second.signingActiveQuorumCount); for (auto& q : quorums) { v.push_back(q->qc.quorumHash.ToString()); } ret.push_back(Pair(p.second.name, v)); } return ret; } void quorum_info_help() { throw std::runtime_error( "quorum info llmqType \"quorumHash\" ( includeSkShare )\n" "\nArguments:\n" "1. llmqType (int, required) LLMQ type.\n" "2. \"quorumHash\" (string, required) Block hash of quorum.\n" "3. includeSkShare (boolean, optional) Include secret key share in output.\n" ); } UniValue quorum_info(const JSONRPCRequest& request) { if (request.fHelp || (request.params.size() != 3 && request.params.size() != 4)) quorum_info_help(); LOCK(cs_main); Consensus::LLMQType llmqType = (Consensus::LLMQType)ParseInt32V(request.params[1], "llmqType"); if (!Params().GetConsensus().llmqs.count(llmqType)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid LLMQ type"); } const auto& llmqParams = Params().GetConsensus().llmqs.at(llmqType); uint256 quorumHash = ParseHashV(request.params[2], "quorumHash"); bool includeSkShare = false; if (request.params.size() > 3) { includeSkShare = ParseBoolV(request.params[3], "includeSkShare"); } auto quorum = llmq::quorumManager->GetQuorum(llmqType, quorumHash); if (!quorum) { throw JSONRPCError(RPC_INVALID_PARAMETER, "quorum not found"); } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("height", quorum->height)); ret.push_back(Pair("quorumHash", quorum->qc.quorumHash.ToString())); ret.push_back(Pair("minedBlock", quorum->minedBlockHash.ToString())); UniValue membersArr(UniValue::VARR); for (size_t i = 0; i < quorum->members.size(); i++) { auto& dmn = quorum->members[i]; UniValue mo(UniValue::VOBJ); mo.push_back(Pair("proTxHash", dmn->proTxHash.ToString())); mo.push_back(Pair("valid", quorum->qc.validMembers[i])); if (quorum->qc.validMembers[i]) { CBLSPublicKey pubKey = quorum->GetPubKeyShare(i); if (pubKey.IsValid()) { mo.push_back(Pair("pubKeyShare", pubKey.ToString())); } } membersArr.push_back(mo); } ret.push_back(Pair("members", membersArr)); ret.push_back(Pair("quorumPublicKey", quorum->qc.quorumPublicKey.ToString())); CBLSSecretKey skShare = quorum->GetSkShare(); if (includeSkShare && skShare.IsValid()) { ret.push_back(Pair("secretKeyShare", skShare.ToString())); } return ret; } void quorum_dkgstatus_help() { throw std::runtime_error( "quorum dkgstatus ( detail_level )\n" "Return the status of the current DKG process.\n" "Works only when SPORK_17_QUORUM_DKG_ENABLED spork is ON.\n" "\nArguments:\n" "1. detail_level (number, optional, default=0) Detail level of output.\n" " 0=Only show counts. 1=Show member indexes. 2=Show member's ProTxHashes.\n" ); } UniValue quorum_dkgstatus(const JSONRPCRequest& request) { if (request.fHelp || (request.params.size() < 1 || request.params.size() > 2)) { quorum_dkgstatus_help(); } int detailLevel = 0; if (request.params.size() > 1) { detailLevel = ParseInt32V(request.params[1], "detail_level"); if (detailLevel < 0 || detailLevel > 2) { throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid detail_level"); } } llmq::CDKGDebugStatus status; llmq::quorumDKGDebugManager->GetLocalDebugStatus(status); auto ret = status.ToJson(detailLevel); LOCK(cs_main); int tipHeight = chainActive.Height(); UniValue minableCommitments(UniValue::VOBJ); for (const auto& p : Params().GetConsensus().llmqs) { auto& params = p.second; llmq::CFinalCommitment fqc; if (llmq::quorumBlockProcessor->GetMinableCommitment(params.type, tipHeight, fqc)) { UniValue obj(UniValue::VOBJ); fqc.ToJson(obj); minableCommitments.push_back(Pair(params.name, obj)); } } ret.push_back(Pair("minableCommitments", minableCommitments)); return ret; } void quorum_sign_help() { throw std::runtime_error( "quorum sign llmqType \"id\" \"msgHash\"\n" "\nArguments:\n" "1. llmqType (int, required) LLMQ type.\n" "2. \"id\" (string, required) Request id.\n" "3. \"msgHash\" (string, required) Message hash.\n" ); } void quorum_hasrecsig_help() { throw std::runtime_error( "quorum hasrecsig llmqType \"id\" \"msgHash\"\n" "\nArguments:\n" "1. llmqType (int, required) LLMQ type.\n" "2. \"id\" (string, required) Request id.\n" "3. \"msgHash\" (string, required) Message hash.\n" ); } void quorum_getrecsig_help() { throw std::runtime_error( "quorum getrecsig llmqType \"id\" \"msgHash\"\n" "\nArguments:\n" "1. llmqType (int, required) LLMQ type.\n" "2. \"id\" (string, required) Request id.\n" "3. \"msgHash\" (string, required) Message hash.\n" ); } void quorum_isconflicting_help() { throw std::runtime_error( "quorum isconflicting llmqType \"id\" \"msgHash\"\n" "\nArguments:\n" "1. llmqType (int, required) LLMQ type.\n" "2. \"id\" (string, required) Request id.\n" "3. \"msgHash\" (string, required) Message hash.\n" ); } UniValue quorum_sigs_cmd(const JSONRPCRequest& request) { auto cmd = request.params[0].get_str(); if (request.fHelp || (request.params.size() != 4)) { if (cmd == "sign") { quorum_sign_help(); } else if (cmd == "hasrecsig") { quorum_hasrecsig_help(); } else if (cmd == "getrecsig") { quorum_getrecsig_help(); } else if (cmd == "isconflicting") { quorum_isconflicting_help(); } else { // shouldn't happen as it's already handled by the caller throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid cmd"); } } Consensus::LLMQType llmqType = (Consensus::LLMQType)ParseInt32V(request.params[1], "llmqType"); if (!Params().GetConsensus().llmqs.count(llmqType)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid LLMQ type"); } uint256 id = ParseHashV(request.params[2], "id"); uint256 msgHash = ParseHashV(request.params[3], "msgHash"); if (cmd == "sign") { return llmq::quorumSigningManager->AsyncSignIfMember(llmqType, id, msgHash); } else if (cmd == "hasrecsig") { return llmq::quorumSigningManager->HasRecoveredSig(llmqType, id, msgHash); } else if (cmd == "getrecsig") { llmq::CRecoveredSig recSig; if (!llmq::quorumSigningManager->GetRecoveredSigForId(llmqType, id, recSig)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "recovered signature not found"); } if (recSig.msgHash != msgHash) { throw JSONRPCError(RPC_INVALID_PARAMETER, "recovered signature not found"); } return recSig.ToJson(); } else if (cmd == "isconflicting") { return llmq::quorumSigningManager->IsConflicting(llmqType, id, msgHash); } else { // shouldn't happen as it's already handled by the caller throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid cmd"); } } void quorum_dkgsimerror_help() { throw std::runtime_error( "quorum dkgsimerror \"type\" rate\n" "This enables simulation of errors and malicious behaviour in the DKG. Do NOT use this on mainnet\n" "as you will get yourself very likely PoSe banned for this.\n" "\nArguments:\n" "1. \"type\" (string, required) Error type.\n" "2. rate (number, required) Rate at which to simulate this error type.\n" ); } UniValue quorum_dkgsimerror(const JSONRPCRequest& request) { auto cmd = request.params[0].get_str(); if (request.fHelp || (request.params.size() != 3)) { quorum_dkgsimerror_help(); } std::string type = request.params[1].get_str(); double rate = ParseDoubleV(request.params[2], "rate"); if (rate < 0 || rate > 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid rate. Must be between 0 and 1"); } llmq::SetSimulatedDKGErrorRate(type, rate); return UniValue(); } [[ noreturn ]] void quorum_help() { throw std::runtime_error( "quorum \"command\" ...\n" "Set of commands for quorums/LLMQs.\n" "To get help on individual commands, use \"help quorum command\".\n" "\nArguments:\n" "1. \"command\" (string, required) The command to execute\n" "\nAvailable commands:\n" " list - List of on-chain quorums\n" " info - Return information about a quorum\n" " dkgsimerror - Simulates DKG errors and malicious behavior.\n" " dkgstatus - Return the status of the current DKG process\n" " sign - Threshold-sign a message\n" " hasrecsig - Test if a valid recovered signature is present\n" " getrecsig - Get a recovered signature\n" " isconflicting - Test if a conflict exists\n" ); } UniValue quorum(const JSONRPCRequest& request) { if (request.fHelp && request.params.empty()) { quorum_help(); } std::string command; if (request.params.size() >= 1) { command = request.params[0].get_str(); } if (command == "list") { return quorum_list(request); } else if (command == "info") { return quorum_info(request); } else if (command == "dkgstatus") { return quorum_dkgstatus(request); } else if (command == "sign" || command == "hasrecsig" || command == "getrecsig" || command == "isconflicting") { return quorum_sigs_cmd(request); } else if (command == "dkgsimerror") { return quorum_dkgsimerror(request); } else { quorum_help(); } } static const CRPCCommand commands[] = { // category name actor (function) okSafeMode // --------------------- ------------------------ ----------------------- ---------- { "evo", "quorum", &quorum, false, {} }, }; void RegisterQuorumsRPCCommands(CRPCTable &tableRPC) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) tableRPC.appendCommand(commands[vcidx].name, &commands[vcidx]); } <commit_msg>Implement "quorum memberof" (#3004)<commit_after>// Copyright (c) 2017-2019 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "server.h" #include "validation.h" #include "llmq/quorums.h" #include "llmq/quorums_blockprocessor.h" #include "llmq/quorums_debug.h" #include "llmq/quorums_dkgsession.h" #include "llmq/quorums_signing.h" void quorum_list_help() { throw std::runtime_error( "quorum list ( count )\n" "\nArguments:\n" "1. count (number, optional) Number of quorums to list. Will list active quorums\n" " if \"count\" is not specified.\n" "\nResult:\n" "{\n" " \"quorumName\" : [ (array of strings) List of quorum hashes per some quorum type.\n" " \"quorumHash\" (string) Quorum hash. Note: most recent quorums come first.\n" " ,...\n" " ],\n" "}\n" "\nExamples:\n" + HelpExampleCli("quorum", "list") + HelpExampleCli("quorum", "list 10") + HelpExampleRpc("quorum", "list, 10") ); } UniValue quorum_list(const JSONRPCRequest& request) { if (request.fHelp || (request.params.size() != 1 && request.params.size() != 2)) quorum_list_help(); LOCK(cs_main); int count = -1; if (request.params.size() > 1) { count = ParseInt32V(request.params[1], "count"); if (count < 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, "count can't be negative"); } } UniValue ret(UniValue::VOBJ); for (auto& p : Params().GetConsensus().llmqs) { UniValue v(UniValue::VARR); auto quorums = llmq::quorumManager->ScanQuorums(p.first, chainActive.Tip(), count > -1 ? count : p.second.signingActiveQuorumCount); for (auto& q : quorums) { v.push_back(q->qc.quorumHash.ToString()); } ret.push_back(Pair(p.second.name, v)); } return ret; } void quorum_info_help() { throw std::runtime_error( "quorum info llmqType \"quorumHash\" ( includeSkShare )\n" "\nArguments:\n" "1. llmqType (int, required) LLMQ type.\n" "2. \"quorumHash\" (string, required) Block hash of quorum.\n" "3. includeSkShare (boolean, optional) Include secret key share in output.\n" ); } UniValue BuildQuorumInfo(const llmq::CQuorumCPtr& quorum, bool includeMembers, bool includeSkShare) { UniValue ret(UniValue::VOBJ); ret.push_back(Pair("height", quorum->height)); ret.push_back(Pair("type", quorum->params.name)); ret.push_back(Pair("quorumHash", quorum->qc.quorumHash.ToString())); ret.push_back(Pair("minedBlock", quorum->minedBlockHash.ToString())); if (includeMembers) { UniValue membersArr(UniValue::VARR); for (size_t i = 0; i < quorum->members.size(); i++) { auto& dmn = quorum->members[i]; UniValue mo(UniValue::VOBJ); mo.push_back(Pair("proTxHash", dmn->proTxHash.ToString())); mo.push_back(Pair("valid", quorum->qc.validMembers[i])); if (quorum->qc.validMembers[i]) { CBLSPublicKey pubKey = quorum->GetPubKeyShare(i); if (pubKey.IsValid()) { mo.push_back(Pair("pubKeyShare", pubKey.ToString())); } } membersArr.push_back(mo); } ret.push_back(Pair("members", membersArr)); } ret.push_back(Pair("quorumPublicKey", quorum->qc.quorumPublicKey.ToString())); CBLSSecretKey skShare = quorum->GetSkShare(); if (includeSkShare && skShare.IsValid()) { ret.push_back(Pair("secretKeyShare", skShare.ToString())); } return ret; } UniValue quorum_info(const JSONRPCRequest& request) { if (request.fHelp || (request.params.size() != 3 && request.params.size() != 4)) quorum_info_help(); LOCK(cs_main); Consensus::LLMQType llmqType = (Consensus::LLMQType)ParseInt32V(request.params[1], "llmqType"); if (!Params().GetConsensus().llmqs.count(llmqType)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid LLMQ type"); } const auto& llmqParams = Params().GetConsensus().llmqs.at(llmqType); uint256 quorumHash = ParseHashV(request.params[2], "quorumHash"); bool includeSkShare = false; if (request.params.size() > 3) { includeSkShare = ParseBoolV(request.params[3], "includeSkShare"); } auto quorum = llmq::quorumManager->GetQuorum(llmqType, quorumHash); if (!quorum) { throw JSONRPCError(RPC_INVALID_PARAMETER, "quorum not found"); } return BuildQuorumInfo(quorum, true, includeSkShare); } void quorum_dkgstatus_help() { throw std::runtime_error( "quorum dkgstatus ( detail_level )\n" "Return the status of the current DKG process.\n" "Works only when SPORK_17_QUORUM_DKG_ENABLED spork is ON.\n" "\nArguments:\n" "1. detail_level (number, optional, default=0) Detail level of output.\n" " 0=Only show counts. 1=Show member indexes. 2=Show member's ProTxHashes.\n" ); } UniValue quorum_dkgstatus(const JSONRPCRequest& request) { if (request.fHelp || (request.params.size() < 1 || request.params.size() > 2)) { quorum_dkgstatus_help(); } int detailLevel = 0; if (request.params.size() > 1) { detailLevel = ParseInt32V(request.params[1], "detail_level"); if (detailLevel < 0 || detailLevel > 2) { throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid detail_level"); } } llmq::CDKGDebugStatus status; llmq::quorumDKGDebugManager->GetLocalDebugStatus(status); auto ret = status.ToJson(detailLevel); LOCK(cs_main); int tipHeight = chainActive.Height(); UniValue minableCommitments(UniValue::VOBJ); for (const auto& p : Params().GetConsensus().llmqs) { auto& params = p.second; llmq::CFinalCommitment fqc; if (llmq::quorumBlockProcessor->GetMinableCommitment(params.type, tipHeight, fqc)) { UniValue obj(UniValue::VOBJ); fqc.ToJson(obj); minableCommitments.push_back(Pair(params.name, obj)); } } ret.push_back(Pair("minableCommitments", minableCommitments)); return ret; } void quorum_memberof_help() { throw std::runtime_error( "quorum memberof \"proTxHash\"\n" "Checks which quorums the given masternode is a member of.\n" "\nArguments:\n" "1. \"proTxHash\" (string, required) ProTxHash of the masternode.\n" ); } UniValue quorum_memberof(const JSONRPCRequest& request) { if (request.fHelp || (request.params.size() != 2)) { quorum_memberof_help(); } uint256 protxHash = ParseHashV(request.params[1], "proTxHash"); const CBlockIndex* pindexTip; { LOCK(cs_main); pindexTip = chainActive.Tip(); } auto mnList = deterministicMNManager->GetListForBlock(pindexTip->GetBlockHash()); auto dmn = mnList.GetMN(protxHash); if (!dmn) { throw JSONRPCError(RPC_INVALID_PARAMETER, "masternode not found"); } std::set<std::pair<Consensus::LLMQType, uint256>> quorumHashes; for (const auto& p : Params().GetConsensus().llmqs) { auto& params = p.second; auto quorums = llmq::quorumManager->ScanQuorums(params.type, params.signingActiveQuorumCount); for (auto& quorum : quorums) { for (auto& m : quorum->members) { if (m->proTxHash == dmn->proTxHash) { quorumHashes.emplace(params.type, quorum->qc.quorumHash); } } } } UniValue result(UniValue::VARR); for (auto& p : quorumHashes) { auto quorum = llmq::quorumManager->GetQuorum(p.first, p.second); assert(quorum); result.push_back(BuildQuorumInfo(quorum, false, false)); } return result; } void quorum_sign_help() { throw std::runtime_error( "quorum sign llmqType \"id\" \"msgHash\"\n" "\nArguments:\n" "1. llmqType (int, required) LLMQ type.\n" "2. \"id\" (string, required) Request id.\n" "3. \"msgHash\" (string, required) Message hash.\n" ); } void quorum_hasrecsig_help() { throw std::runtime_error( "quorum hasrecsig llmqType \"id\" \"msgHash\"\n" "\nArguments:\n" "1. llmqType (int, required) LLMQ type.\n" "2. \"id\" (string, required) Request id.\n" "3. \"msgHash\" (string, required) Message hash.\n" ); } void quorum_getrecsig_help() { throw std::runtime_error( "quorum getrecsig llmqType \"id\" \"msgHash\"\n" "\nArguments:\n" "1. llmqType (int, required) LLMQ type.\n" "2. \"id\" (string, required) Request id.\n" "3. \"msgHash\" (string, required) Message hash.\n" ); } void quorum_isconflicting_help() { throw std::runtime_error( "quorum isconflicting llmqType \"id\" \"msgHash\"\n" "\nArguments:\n" "1. llmqType (int, required) LLMQ type.\n" "2. \"id\" (string, required) Request id.\n" "3. \"msgHash\" (string, required) Message hash.\n" ); } UniValue quorum_sigs_cmd(const JSONRPCRequest& request) { auto cmd = request.params[0].get_str(); if (request.fHelp || (request.params.size() != 4)) { if (cmd == "sign") { quorum_sign_help(); } else if (cmd == "hasrecsig") { quorum_hasrecsig_help(); } else if (cmd == "getrecsig") { quorum_getrecsig_help(); } else if (cmd == "isconflicting") { quorum_isconflicting_help(); } else { // shouldn't happen as it's already handled by the caller throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid cmd"); } } Consensus::LLMQType llmqType = (Consensus::LLMQType)ParseInt32V(request.params[1], "llmqType"); if (!Params().GetConsensus().llmqs.count(llmqType)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid LLMQ type"); } uint256 id = ParseHashV(request.params[2], "id"); uint256 msgHash = ParseHashV(request.params[3], "msgHash"); if (cmd == "sign") { return llmq::quorumSigningManager->AsyncSignIfMember(llmqType, id, msgHash); } else if (cmd == "hasrecsig") { return llmq::quorumSigningManager->HasRecoveredSig(llmqType, id, msgHash); } else if (cmd == "getrecsig") { llmq::CRecoveredSig recSig; if (!llmq::quorumSigningManager->GetRecoveredSigForId(llmqType, id, recSig)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "recovered signature not found"); } if (recSig.msgHash != msgHash) { throw JSONRPCError(RPC_INVALID_PARAMETER, "recovered signature not found"); } return recSig.ToJson(); } else if (cmd == "isconflicting") { return llmq::quorumSigningManager->IsConflicting(llmqType, id, msgHash); } else { // shouldn't happen as it's already handled by the caller throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid cmd"); } } void quorum_dkgsimerror_help() { throw std::runtime_error( "quorum dkgsimerror \"type\" rate\n" "This enables simulation of errors and malicious behaviour in the DKG. Do NOT use this on mainnet\n" "as you will get yourself very likely PoSe banned for this.\n" "\nArguments:\n" "1. \"type\" (string, required) Error type.\n" "2. rate (number, required) Rate at which to simulate this error type.\n" ); } UniValue quorum_dkgsimerror(const JSONRPCRequest& request) { auto cmd = request.params[0].get_str(); if (request.fHelp || (request.params.size() != 3)) { quorum_dkgsimerror_help(); } std::string type = request.params[1].get_str(); double rate = ParseDoubleV(request.params[2], "rate"); if (rate < 0 || rate > 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid rate. Must be between 0 and 1"); } llmq::SetSimulatedDKGErrorRate(type, rate); return UniValue(); } [[ noreturn ]] void quorum_help() { throw std::runtime_error( "quorum \"command\" ...\n" "Set of commands for quorums/LLMQs.\n" "To get help on individual commands, use \"help quorum command\".\n" "\nArguments:\n" "1. \"command\" (string, required) The command to execute\n" "\nAvailable commands:\n" " list - List of on-chain quorums\n" " info - Return information about a quorum\n" " dkgsimerror - Simulates DKG errors and malicious behavior.\n" " dkgstatus - Return the status of the current DKG process\n" " memberof - Checks which quorums the given masternode is a member of\n" " sign - Threshold-sign a message\n" " hasrecsig - Test if a valid recovered signature is present\n" " getrecsig - Get a recovered signature\n" " isconflicting - Test if a conflict exists\n" ); } UniValue quorum(const JSONRPCRequest& request) { if (request.fHelp && request.params.empty()) { quorum_help(); } std::string command; if (request.params.size() >= 1) { command = request.params[0].get_str(); } if (command == "list") { return quorum_list(request); } else if (command == "info") { return quorum_info(request); } else if (command == "dkgstatus") { return quorum_dkgstatus(request); } else if (command == "memberof") { return quorum_memberof(request); } else if (command == "sign" || command == "hasrecsig" || command == "getrecsig" || command == "isconflicting") { return quorum_sigs_cmd(request); } else if (command == "dkgsimerror") { return quorum_dkgsimerror(request); } else { quorum_help(); } } static const CRPCCommand commands[] = { // category name actor (function) okSafeMode // --------------------- ------------------------ ----------------------- ---------- { "evo", "quorum", &quorum, false, {} }, }; void RegisterQuorumsRPCCommands(CRPCTable &tableRPC) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) tableRPC.appendCommand(commands[vcidx].name, &commands[vcidx]); } <|endoftext|>
<commit_before>/******************************************************************************* * @file MainDialog_Event.cpp 2014\8\20 15:43:48 $ * @author 쵶<kuaidao@mogujie.com> * @brief ******************************************************************************/ #include "stdafx.h" #include "MainDialog.h" #include "Modules/ITcpClientModule.h" #include "Modules/ILoginModule.h" #include "Modules/IMiscModule.h" #include "Modules/IUserListModule.h" #include "Modules/ISessionModule.h" #include "Modules/ISysConfigModule.h" #include "ProtocolBuffer/IM.BaseDefine.pb.h" #include "utility/Multilingual.h" /******************************************************************************/ void MainDialog::OnClick(TNotifyUI& msg) { PTR_VOID(msg.pSender); if (msg.pSender == m_pbtnSysConfig) { //ϵͳ module::getSysConfigModule()->showSysConfigDialog(m_hWnd); } else if (msg.pSender == m_pbtnOnlineStatus) { CMenuWnd* pMenu = new CMenuWnd(m_hWnd); DuiLib::CPoint point = msg.ptMouse; ClientToScreen(m_hWnd, &point); STRINGorID xml(_T("menu\\lineStatus.xml")); pMenu->Init(NULL, xml, _T("xml"), point); } else if (msg.pSender == m_pbtnMyFace) { //show the detail of myself. module::getSysConfigModule()->asynNotifyObserver(module::KEY_SYSCONFIG_SHOW_USERDETAILDIALOG, module::getSysConfigModule()->userID()); } else if (msg.pSender == m_pbtnClose || msg.pSender == m_pbtnMinMize) { ShowWindow(false); return; } __super::OnClick(msg); } void MainDialog::MKOForTcpClientModuleCallBack(const std::string& keyId, MKO_TUPLE_PARAM mkoParam) { if (module::KEY_TCPCLIENT_STATE == keyId) { //TCPϿ if (module::TCPCLIENT_STATE_DISCONNECT == module::getTcpClientModule()->getTcpClientNetState()) { LOG__(ERR, _T("TCPCLIENT_STATE_DISCONNECT:TCP Client link broken!!!")); //ͼҶȵ CString csTip = util::getMultilingual()->getStringById(_T("STRID_MAINDIALOG_TIP_DISCONNECT")); SetTrayTooltipText(csTip); UpdateLineStatus(IM::BaseDefine::UserStatType::USER_STATUS_OFFLINE); //ҵ module::getTcpClientModule()->shutdown(); if (!module::getLoginModule()->isOfflineByMyself()) module::getLoginModule()->relogin(FALSE); } } } void MainDialog::OnCopyData(IN COPYDATASTRUCT* pCopyData) { if (nullptr == pCopyData) { return; } module::getSessionModule()->asynNotifyObserver(module::KEY_SESSION_TRAY_COPYDATA, pCopyData->dwData); } void MainDialog::MKOForLoginModuleCallBack(const std::string& keyId, MKO_TUPLE_PARAM mkoParam) { if (module::KEY_LOGIN_RELOGINOK == keyId) { CString sText = util::getMultilingual()->getStringById(_T("STRID_GLOBAL_CAPTION_NAME")); #ifdef _DEBUG sText += _T("(Debug)"); #endif SetTrayTooltipText(sText); UpdateLineStatus(IM::BaseDefine::UserStatType::USER_STATUS_ONLINE); } else if (module::KEY_LOGIN_KICKOUT == keyId)//˻߳ˣԼ { Int32 nRes = std::get<MKO_INT>(mkoParam); LOG__(APP, _T("Offline by kickout,%d"), nRes); module::getTcpClientModule()->shutdown(); module::getLoginModule()->setOfflineByMyself(TRUE); CString strText = util::getMultilingual()->getStringById(_T("STRID_LOGINDIALOG_TIP_DUPLICATE_USER_KICKOUT")); if (IM::BaseDefine::KickReasonType::KICK_REASON_MOBILE_KICK == nRes) { strText = util::getMultilingual()->getStringById(_T("STRID_LOGINDIALOG_TIP_MOBILE_KICK")); } CString strCaption = util::getMultilingual()->getStringById(_T("STRID_LOGINDIALOG_TIP_CAPTION")); ::MessageBoxEx(m_hWnd, strText, strCaption, MB_OK, LANG_CHINESE); } } void MainDialog::OnMenuClicked(IN const CString& itemName, IN const CString& strLparam) { if (_T("exitMenuItem") == itemName) { module::getMiscModule()->quitTheApplication(); } else if (_T("LogDir") == itemName)//־Ŀ¼ { CString strLogDir = util::getParentAppPath() + _T("bin\\log\\ttlog.log"); if (PathFileExists(strLogDir)) { HINSTANCE hr = ShellExecute(NULL, _T("open"), _T("Explorer.exe"), _T("/select,") + strLogDir, NULL, SW_SHOWDEFAULT); if ((long)hr < 32) { DWORD dwLastError = ::GetLastError(); LOG__(ERR, _T("ShellExecute Failed GetLastError = %d") , dwLastError); } } } else if (_T("OnlineMenuItem") == itemName) { module::getLoginModule()->setOfflineByMyself(FALSE); module::getLoginModule()->relogin(TRUE); } else if (_T("OfflineMenuItem") == itemName) { LOG__(APP,_T("Offline by myself")); module::getTcpClientModule()->shutdown(); module::getLoginModule()->setOfflineByMyself(TRUE); } else if (_T("SysSettingMenuItem") == itemName) { //ϵͳ module::getSysConfigModule()->showSysConfigDialog(m_hWnd); } else if (_T("serverAddressSetting") == itemName) { module::getSysConfigModule()->showServerConfigDialog(m_hWnd); } else if (_T("UserDetailInfo") == itemName) { if (strLparam.IsEmpty()) { return; } std::string sid = util::cStringToString(strLparam); module::getSysConfigModule()->asynNotifyObserver(module::KEY_SYSCONFIG_SHOW_USERDETAILDIALOG, sid); } } void MainDialog::MKOForUserListModuleCallBack(const std::string& keyId, MKO_TUPLE_PARAM mkoParam) { if (module::KEY_USERLIST_DOWNAVATAR_SUCC == keyId) { std::shared_ptr<void> p = std::get<MKO_SHARED_VOIDPTR>(mkoParam); std::tuple<std::string, std::string>* pTuple = (std::tuple<std::string, std::string>*)p.get(); std::string& sId = std::get<1>(*pTuple); //ˢͷ module::UserInfoEntity myInfo; module::getUserListModule()->getMyInfo(myInfo); if (sId == myInfo.sId) { if (m_pbtnMyFace) m_pbtnMyFace->SetBkImage(util::stringToCString(myInfo.getAvatarPath())); } } } void MainDialog::MKOForSessionModuleCallBack(const std::string& keyId, MKO_TUPLE_PARAM mkoParam) { if (module::KEY_SESSION_TRAY_STARTEMOT == keyId) { StartNewMsgTrayEmot(); } else if (module::KEY_SESSION_TRAY_STOPEMOT == keyId) { StopNewMsgTrayEmot(); } } void MainDialog::StartNewMsgTrayEmot() { SetTimer(m_hWnd, TIMER_TRAYEMOT, 500, NULL); } void MainDialog::StopNewMsgTrayEmot() { KillTimer(m_hWnd, TIMER_TRAYEMOT); UpdateLineStatus(module::getUserListModule()->getMyLineStatus()); } /******************************************************************************/<commit_msg>dafo:online menu click bug<commit_after>/******************************************************************************* * @file MainDialog_Event.cpp 2014\8\20 15:43:48 $ * @author 쵶<kuaidao@mogujie.com> * @brief ******************************************************************************/ #include "stdafx.h" #include "MainDialog.h" #include "Modules/ITcpClientModule.h" #include "Modules/ILoginModule.h" #include "Modules/IMiscModule.h" #include "Modules/IUserListModule.h" #include "Modules/ISessionModule.h" #include "Modules/ISysConfigModule.h" #include "ProtocolBuffer/IM.BaseDefine.pb.h" #include "utility/Multilingual.h" /******************************************************************************/ void MainDialog::OnClick(TNotifyUI& msg) { PTR_VOID(msg.pSender); if (msg.pSender == m_pbtnSysConfig) { //ϵͳ module::getSysConfigModule()->showSysConfigDialog(m_hWnd); } else if (msg.pSender == m_pbtnOnlineStatus) { CMenuWnd* pMenu = new CMenuWnd(m_hWnd); DuiLib::CPoint point = msg.ptMouse; ClientToScreen(m_hWnd, &point); STRINGorID xml(_T("menu\\lineStatus.xml")); pMenu->Init(NULL, xml, _T("xml"), point); } else if (msg.pSender == m_pbtnMyFace) { //show the detail of myself. module::getSysConfigModule()->asynNotifyObserver(module::KEY_SYSCONFIG_SHOW_USERDETAILDIALOG, module::getSysConfigModule()->userID()); } else if (msg.pSender == m_pbtnClose || msg.pSender == m_pbtnMinMize) { ShowWindow(false); return; } __super::OnClick(msg); } void MainDialog::MKOForTcpClientModuleCallBack(const std::string& keyId, MKO_TUPLE_PARAM mkoParam) { if (module::KEY_TCPCLIENT_STATE == keyId) { //TCPϿ if (module::TCPCLIENT_STATE_DISCONNECT == module::getTcpClientModule()->getTcpClientNetState()) { LOG__(ERR, _T("TCPCLIENT_STATE_DISCONNECT:TCP Client link broken!!!")); //ͼҶȵ CString csTip = util::getMultilingual()->getStringById(_T("STRID_MAINDIALOG_TIP_DISCONNECT")); SetTrayTooltipText(csTip); UpdateLineStatus(IM::BaseDefine::UserStatType::USER_STATUS_OFFLINE); //ҵ module::getTcpClientModule()->shutdown(); if (!module::getLoginModule()->isOfflineByMyself()) module::getLoginModule()->relogin(FALSE); } } } void MainDialog::OnCopyData(IN COPYDATASTRUCT* pCopyData) { if (nullptr == pCopyData) { return; } module::getSessionModule()->asynNotifyObserver(module::KEY_SESSION_TRAY_COPYDATA, pCopyData->dwData); } void MainDialog::MKOForLoginModuleCallBack(const std::string& keyId, MKO_TUPLE_PARAM mkoParam) { if (module::KEY_LOGIN_RELOGINOK == keyId) { CString sText = util::getMultilingual()->getStringById(_T("STRID_GLOBAL_CAPTION_NAME")); #ifdef _DEBUG sText += _T("(Debug)"); #endif SetTrayTooltipText(sText); UpdateLineStatus(IM::BaseDefine::UserStatType::USER_STATUS_ONLINE); } else if (module::KEY_LOGIN_KICKOUT == keyId)//˻߳ˣԼ { Int32 nRes = std::get<MKO_INT>(mkoParam); LOG__(APP, _T("Offline by kickout,%d"), nRes); module::getTcpClientModule()->shutdown(); module::getLoginModule()->setOfflineByMyself(TRUE); CString strText = util::getMultilingual()->getStringById(_T("STRID_LOGINDIALOG_TIP_DUPLICATE_USER_KICKOUT")); if (IM::BaseDefine::KickReasonType::KICK_REASON_MOBILE_KICK == nRes) { strText = util::getMultilingual()->getStringById(_T("STRID_LOGINDIALOG_TIP_MOBILE_KICK")); } CString strCaption = util::getMultilingual()->getStringById(_T("STRID_LOGINDIALOG_TIP_CAPTION")); ::MessageBoxEx(m_hWnd, strText, strCaption, MB_OK, LANG_CHINESE); } } void MainDialog::OnMenuClicked(IN const CString& itemName, IN const CString& strLparam) { if (_T("exitMenuItem") == itemName) { module::getMiscModule()->quitTheApplication(); } else if (_T("LogDir") == itemName)//־Ŀ¼ { CString strLogDir = util::getParentAppPath() + _T("bin\\log\\ttlog.log"); if (PathFileExists(strLogDir)) { HINSTANCE hr = ShellExecute(NULL, _T("open"), _T("Explorer.exe"), _T("/select,") + strLogDir, NULL, SW_SHOWDEFAULT); if ((long)hr < 32) { DWORD dwLastError = ::GetLastError(); LOG__(ERR, _T("ShellExecute Failed GetLastError = %d") , dwLastError); } } } else if (_T("OnlineMenuItem") == itemName) { if (IM::BaseDefine::USER_STATUS_ONLINE == module::getUserListModule()->getMyLineStatus()) { LOG__(APP, _T("already online")); return; } module::getLoginModule()->setOfflineByMyself(FALSE); module::getLoginModule()->relogin(TRUE); } else if (_T("OfflineMenuItem") == itemName) { if (IM::BaseDefine::USER_STATUS_OFFLINE == module::getUserListModule()->getMyLineStatus()) { LOG__(APP, _T("already offline")); return; } LOG__(APP,_T("Offline by myself")); module::getTcpClientModule()->shutdown(); module::getLoginModule()->setOfflineByMyself(TRUE); } else if (_T("SysSettingMenuItem") == itemName) { //ϵͳ module::getSysConfigModule()->showSysConfigDialog(m_hWnd); } else if (_T("serverAddressSetting") == itemName) { module::getSysConfigModule()->showServerConfigDialog(m_hWnd); } else if (_T("UserDetailInfo") == itemName) { if (strLparam.IsEmpty()) { return; } std::string sid = util::cStringToString(strLparam); module::getSysConfigModule()->asynNotifyObserver(module::KEY_SYSCONFIG_SHOW_USERDETAILDIALOG, sid); } } void MainDialog::MKOForUserListModuleCallBack(const std::string& keyId, MKO_TUPLE_PARAM mkoParam) { if (module::KEY_USERLIST_DOWNAVATAR_SUCC == keyId) { std::shared_ptr<void> p = std::get<MKO_SHARED_VOIDPTR>(mkoParam); std::tuple<std::string, std::string>* pTuple = (std::tuple<std::string, std::string>*)p.get(); std::string& sId = std::get<1>(*pTuple); //ˢͷ module::UserInfoEntity myInfo; module::getUserListModule()->getMyInfo(myInfo); if (sId == myInfo.sId) { if (m_pbtnMyFace) m_pbtnMyFace->SetBkImage(util::stringToCString(myInfo.getAvatarPath())); } } } void MainDialog::MKOForSessionModuleCallBack(const std::string& keyId, MKO_TUPLE_PARAM mkoParam) { if (module::KEY_SESSION_TRAY_STARTEMOT == keyId) { StartNewMsgTrayEmot(); } else if (module::KEY_SESSION_TRAY_STOPEMOT == keyId) { StopNewMsgTrayEmot(); } } void MainDialog::StartNewMsgTrayEmot() { SetTimer(m_hWnd, TIMER_TRAYEMOT, 500, NULL); } void MainDialog::StopNewMsgTrayEmot() { KillTimer(m_hWnd, TIMER_TRAYEMOT); UpdateLineStatus(module::getUserListModule()->getMyLineStatus()); } /******************************************************************************/<|endoftext|>
<commit_before> // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_CAMERA_INTRINSICS_H #define OPENMVG_CAMERA_INTRINSICS_H #include "openMVG/numeric/numeric.h" #include "openMVG/cameras/Camera_Common.hpp" #include "openMVG/geometry/pose3.hpp" #include "openMVG/stl/hash.hpp" #include <vector> #include <cereal/cereal.hpp> // Serialization namespace openMVG { namespace cameras { /// Basis class for all intrinsic parameters of a camera /// Store the image size & define all basis optical modelization of a camera struct IntrinsicBase { unsigned int _w, _h; std::string _serialNumber; IntrinsicBase(unsigned int w = 0, unsigned int h = 0, std::string serialNumber = ""):_w(w), _h(h), _serialNumber(serialNumber) {} virtual ~IntrinsicBase() {} unsigned int w() const {return _w;} unsigned int h() const {return _h;} std::string serialNumber() const {return _serialNumber;} void setWidth(unsigned int w) { _w = w;} void setHeight(unsigned int h) { _h = h;} void setSerialNumber(const std::string& serialNumber) { _serialNumber = serialNumber;} // Operator == bool operator==(const IntrinsicBase& other) const { return _w == other._w && _h == other._h && _serialNumber == other._serialNumber && getType() == other.getType() && getParams() == other.getParams(); } /// Projection of a 3D point into the camera plane (Apply pose, disto (if any) and Intrinsics) Vec2 project( const geometry::Pose3 & pose, const Vec3 & pt3D) const { const Vec3 X = pose(pt3D); // apply pose if (this->have_disto()) // apply disto & intrinsics return this->cam2ima( this->add_disto(X.head<2>()/X(2)) ); else // apply intrinsics return this->cam2ima( X.head<2>()/X(2) ); } /// Compute the residual between the 3D projected point X and an image observation x Vec2 residual(const geometry::Pose3 & pose, const Vec3 & X, const Vec2 & x) const { const Vec2 proj = this->project(pose, X); return x - proj; } Mat2X residuals(const geometry::Pose3 & pose, const Mat3X & X, const Mat2X & x) const { assert(X.cols() == x.cols()); const std::size_t numPts = x.cols(); Mat2X residuals = Mat2X::Zero(2, numPts); for(std::size_t i = 0; i < numPts; ++i) { residuals.col(i) = residual(pose, X.col(i), x.col(i)); } return residuals; } // -- // Virtual members // -- /// Tell from which type the embed camera is virtual EINTRINSIC getType() const = 0; /// Data wrapper for non linear optimization (get data) virtual std::vector<double> getParams() const = 0; /// Data wrapper for non linear optimization (update from data) virtual bool updateFromParams(const std::vector<double> & params) = 0; /// Get bearing vector of p point (image coord) virtual Vec3 operator () (const Vec2& p) const = 0; /// Transform a point from the camera plane to the image plane virtual Vec2 cam2ima(const Vec2& p) const = 0; /// Transform a point from the image plane to the camera plane virtual Vec2 ima2cam(const Vec2& p) const = 0; /// Does the camera model handle a distortion field? virtual bool have_disto() const {return false;} /// Add the distortion field to a point (that is in normalized camera frame) virtual Vec2 add_disto(const Vec2& p) const = 0; /// Remove the distortion to a camera point (that is in normalized camera frame) virtual Vec2 remove_disto(const Vec2& p) const = 0; /// Return the un-distorted pixel (with removed distortion) virtual Vec2 get_ud_pixel(const Vec2& p) const = 0; /// Return the distorted pixel (with added distortion) virtual Vec2 get_d_pixel(const Vec2& p) const = 0; /// Normalize a given unit pixel error to the camera plane virtual double imagePlane_toCameraPlaneError(double value) const = 0; /// Return the intrinsic (interior & exterior) as a simplified projective projection virtual Mat34 get_projective_equivalent(const geometry::Pose3 & pose) const = 0; /// Serialization out template <class Archive> void save( Archive & ar) const { ar(cereal::make_nvp("width", _w)); ar(cereal::make_nvp("height", _h)); ar(cereal::make_nvp("serialNumber", _serialNumber)); } /// Serialization in template <class Archive> void load( Archive & ar) { ar(cereal::make_nvp("width", _w)); ar(cereal::make_nvp("height", _h)); try { // compatibility with older versions ar(cereal::make_nvp("serialNumber", _serialNumber)); } catch(cereal::Exception e) { // if it fails, just use empty string _serialNumber = ""; } } /// Generate an unique Hash from the camera parameters (used for grouping) virtual std::size_t hashValue() const { size_t seed = 0; stl::hash_combine(seed, static_cast<int>(this->getType())); stl::hash_combine(seed, _w); stl::hash_combine(seed, _h); stl::hash_combine(seed, _serialNumber); const std::vector<double> params = this->getParams(); for (size_t i=0; i < params.size(); ++i) stl::hash_combine(seed, params[i]); return seed; } }; /// Return the angle (degree) between two bearing vector rays static inline double AngleBetweenRay( const geometry::Pose3 & pose1, const IntrinsicBase * intrinsic1, const geometry::Pose3 & pose2, const IntrinsicBase * intrinsic2, const Vec2 & x1, const Vec2 & x2) { // x = (u, v, 1.0) // image coordinates // X = R.t() * K.inv() * x + C // Camera world point // getting the ray: // ray = X - C = R.t() * K.inv() * x const Vec3 ray1 = (pose1.rotation().transpose() * intrinsic1->operator()(x1)).normalized(); const Vec3 ray2 = (pose2.rotation().transpose() * intrinsic2->operator()(x2)).normalized(); const double mag = ray1.norm() * ray2.norm(); const double dotAngle = ray1.dot(ray2); return R2D(acos(clamp(dotAngle/mag, -1.0 + 1.e-8, 1.0 - 1.e-8))); } } // namespace cameras } // namespace openMVG #endif // #ifndef OPENMVG_CAMERA_INTRINSICS_H <commit_msg>[instrinsics] add missing const<commit_after> // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_CAMERA_INTRINSICS_H #define OPENMVG_CAMERA_INTRINSICS_H #include "openMVG/numeric/numeric.h" #include "openMVG/cameras/Camera_Common.hpp" #include "openMVG/geometry/pose3.hpp" #include "openMVG/stl/hash.hpp" #include <vector> #include <cereal/cereal.hpp> // Serialization namespace openMVG { namespace cameras { /// Basis class for all intrinsic parameters of a camera /// Store the image size & define all basis optical modelization of a camera struct IntrinsicBase { unsigned int _w, _h; std::string _serialNumber; IntrinsicBase(unsigned int w = 0, unsigned int h = 0, const std::string& serialNumber = ""):_w(w), _h(h), _serialNumber(serialNumber) {} virtual ~IntrinsicBase() {} unsigned int w() const {return _w;} unsigned int h() const {return _h;} std::string serialNumber() const {return _serialNumber;} void setWidth(unsigned int w) { _w = w;} void setHeight(unsigned int h) { _h = h;} void setSerialNumber(const std::string& serialNumber) { _serialNumber = serialNumber;} // Operator == bool operator==(const IntrinsicBase& other) const { return _w == other._w && _h == other._h && _serialNumber == other._serialNumber && getType() == other.getType() && getParams() == other.getParams(); } /// Projection of a 3D point into the camera plane (Apply pose, disto (if any) and Intrinsics) Vec2 project( const geometry::Pose3 & pose, const Vec3 & pt3D) const { const Vec3 X = pose(pt3D); // apply pose if (this->have_disto()) // apply disto & intrinsics return this->cam2ima( this->add_disto(X.head<2>()/X(2)) ); else // apply intrinsics return this->cam2ima( X.head<2>()/X(2) ); } /// Compute the residual between the 3D projected point X and an image observation x Vec2 residual(const geometry::Pose3 & pose, const Vec3 & X, const Vec2 & x) const { const Vec2 proj = this->project(pose, X); return x - proj; } Mat2X residuals(const geometry::Pose3 & pose, const Mat3X & X, const Mat2X & x) const { assert(X.cols() == x.cols()); const std::size_t numPts = x.cols(); Mat2X residuals = Mat2X::Zero(2, numPts); for(std::size_t i = 0; i < numPts; ++i) { residuals.col(i) = residual(pose, X.col(i), x.col(i)); } return residuals; } // -- // Virtual members // -- /// Tell from which type the embed camera is virtual EINTRINSIC getType() const = 0; /// Data wrapper for non linear optimization (get data) virtual std::vector<double> getParams() const = 0; /// Data wrapper for non linear optimization (update from data) virtual bool updateFromParams(const std::vector<double> & params) = 0; /// Get bearing vector of p point (image coord) virtual Vec3 operator () (const Vec2& p) const = 0; /// Transform a point from the camera plane to the image plane virtual Vec2 cam2ima(const Vec2& p) const = 0; /// Transform a point from the image plane to the camera plane virtual Vec2 ima2cam(const Vec2& p) const = 0; /// Does the camera model handle a distortion field? virtual bool have_disto() const {return false;} /// Add the distortion field to a point (that is in normalized camera frame) virtual Vec2 add_disto(const Vec2& p) const = 0; /// Remove the distortion to a camera point (that is in normalized camera frame) virtual Vec2 remove_disto(const Vec2& p) const = 0; /// Return the un-distorted pixel (with removed distortion) virtual Vec2 get_ud_pixel(const Vec2& p) const = 0; /// Return the distorted pixel (with added distortion) virtual Vec2 get_d_pixel(const Vec2& p) const = 0; /// Normalize a given unit pixel error to the camera plane virtual double imagePlane_toCameraPlaneError(double value) const = 0; /// Return the intrinsic (interior & exterior) as a simplified projective projection virtual Mat34 get_projective_equivalent(const geometry::Pose3 & pose) const = 0; /// Serialization out template <class Archive> void save( Archive & ar) const { ar(cereal::make_nvp("width", _w)); ar(cereal::make_nvp("height", _h)); ar(cereal::make_nvp("serialNumber", _serialNumber)); } /// Serialization in template <class Archive> void load( Archive & ar) { ar(cereal::make_nvp("width", _w)); ar(cereal::make_nvp("height", _h)); try { // compatibility with older versions ar(cereal::make_nvp("serialNumber", _serialNumber)); } catch(cereal::Exception e) { // if it fails, just use empty string _serialNumber = ""; } } /// Generate an unique Hash from the camera parameters (used for grouping) virtual std::size_t hashValue() const { size_t seed = 0; stl::hash_combine(seed, static_cast<int>(this->getType())); stl::hash_combine(seed, _w); stl::hash_combine(seed, _h); stl::hash_combine(seed, _serialNumber); const std::vector<double> params = this->getParams(); for (size_t i=0; i < params.size(); ++i) stl::hash_combine(seed, params[i]); return seed; } }; /// Return the angle (degree) between two bearing vector rays static inline double AngleBetweenRay( const geometry::Pose3 & pose1, const IntrinsicBase * intrinsic1, const geometry::Pose3 & pose2, const IntrinsicBase * intrinsic2, const Vec2 & x1, const Vec2 & x2) { // x = (u, v, 1.0) // image coordinates // X = R.t() * K.inv() * x + C // Camera world point // getting the ray: // ray = X - C = R.t() * K.inv() * x const Vec3 ray1 = (pose1.rotation().transpose() * intrinsic1->operator()(x1)).normalized(); const Vec3 ray2 = (pose2.rotation().transpose() * intrinsic2->operator()(x2)).normalized(); const double mag = ray1.norm() * ray2.norm(); const double dotAngle = ray1.dot(ray2); return R2D(acos(clamp(dotAngle/mag, -1.0 + 1.e-8, 1.0 - 1.e-8))); } } // namespace cameras } // namespace openMVG #endif // #ifndef OPENMVG_CAMERA_INTRINSICS_H <|endoftext|>
<commit_before>#include <openMVG/features/descriptor.hpp> #include <openMVG/sfm/sfm_data_io.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string/case_conv.hpp> #include <boost/progress.hpp> #include <iostream> #include <fstream> namespace openMVG { namespace voctree { template<class DescriptorT, class FileDescriptorT> size_t readDescFromFiles(const std::string &fileFullPath, std::vector<DescriptorT>& descriptors, std::vector<size_t> &numFeatures) { namespace bfs = boost::filesystem; std::map<IndexT, std::string> descriptorsFiles; getListOfDescriptorFiles(fileFullPath, descriptorsFiles); std::size_t numDescriptors = 0; // Allocate the memory by reading in a first time the files to get the number // of descriptors int bytesPerElement = 0; // Display infos and progress bar std::cout << "Pre-computing the memory needed..." << std::endl; boost::progress_display display(descriptorsFiles.size()); // Read all files and get the number of descriptors to load for(const auto &currentFile : descriptorsFiles) { // if it is the first one read the number of descriptors and the type of data (we are assuming the the feat are all the same...) // bytesPerElement could be 0 even after the first element (eg it has 0 descriptors...), so do it until we get the correct info if(bytesPerElement == 0) { getInfoBinFile(currentFile.second, DescriptorT::static_size, numDescriptors, bytesPerElement); } else { // get the file size in byte and estimate the number of features without opening the file numDescriptors += (bfs::file_size(currentFile.second) / bytesPerElement) / DescriptorT::static_size; } ++display; } std::cout << "Found " << numDescriptors << " descriptors overall, allocating memory..." << std::endl; if(bytesPerElement == 0) { std::cout << "WARNING: Empty descriptor file: " << fileFullPath << std::endl; return 0; } else { // Allocate the memory descriptors.reserve(numDescriptors); size_t numDescriptorsCheck = numDescriptors; // for later check numDescriptors = 0; // Read the descriptors std::cout << "Reading the descriptors..." << std::endl; display.restart(descriptorsFiles.size()); // Run through the path vector and read the descriptors for(const auto &currentFile : descriptorsFiles) { // Read the descriptors and append them in the vector features::loadDescsFromBinFile<DescriptorT, FileDescriptorT>(currentFile.second, descriptors, true); size_t result = descriptors.size(); // Add the number of descriptors from this file numFeatures.push_back(result - numDescriptors); // Update the overall counter numDescriptors = result; ++display; } BOOST_ASSERT(numDescriptors == numDescriptorsCheck); } // Return the result return numDescriptors; } } // namespace voctree } // namespace openMVG<commit_msg>code simplification: avoid unnecessary "else"<commit_after>#include <openMVG/features/descriptor.hpp> #include <openMVG/sfm/sfm_data_io.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string/case_conv.hpp> #include <boost/progress.hpp> #include <iostream> #include <fstream> namespace openMVG { namespace voctree { template<class DescriptorT, class FileDescriptorT> size_t readDescFromFiles(const std::string &fileFullPath, std::vector<DescriptorT>& descriptors, std::vector<size_t> &numFeatures) { namespace bfs = boost::filesystem; std::map<IndexT, std::string> descriptorsFiles; getListOfDescriptorFiles(fileFullPath, descriptorsFiles); std::size_t numDescriptors = 0; // Allocate the memory by reading in a first time the files to get the number // of descriptors int bytesPerElement = 0; // Display infos and progress bar std::cout << "Pre-computing the memory needed..." << std::endl; boost::progress_display display(descriptorsFiles.size()); // Read all files and get the number of descriptors to load for(const auto &currentFile : descriptorsFiles) { // if it is the first one read the number of descriptors and the type of data (we are assuming the the feat are all the same...) // bytesPerElement could be 0 even after the first element (eg it has 0 descriptors...), so do it until we get the correct info if(bytesPerElement == 0) { getInfoBinFile(currentFile.second, DescriptorT::static_size, numDescriptors, bytesPerElement); } else { // get the file size in byte and estimate the number of features without opening the file numDescriptors += (bfs::file_size(currentFile.second) / bytesPerElement) / DescriptorT::static_size; } ++display; } std::cout << "Found " << numDescriptors << " descriptors overall, allocating memory..." << std::endl; if(bytesPerElement == 0) { std::cout << "WARNING: Empty descriptor file: " << fileFullPath << std::endl; return 0; } // Allocate the memory descriptors.reserve(numDescriptors); size_t numDescriptorsCheck = numDescriptors; // for later check numDescriptors = 0; // Read the descriptors std::cout << "Reading the descriptors..." << std::endl; display.restart(descriptorsFiles.size()); // Run through the path vector and read the descriptors for(const auto &currentFile : descriptorsFiles) { // Read the descriptors and append them in the vector features::loadDescsFromBinFile<DescriptorT, FileDescriptorT>(currentFile.second, descriptors, true); size_t result = descriptors.size(); // Add the number of descriptors from this file numFeatures.push_back(result - numDescriptors); // Update the overall counter numDescriptors = result; ++display; } assert(numDescriptors == numDescriptorsCheck); // Return the result return numDescriptors; } } // namespace voctree } // namespace openMVG<|endoftext|>
<commit_before>/* * Copyright 2011, Blender Foundation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <Python.h> #include "CCL_api.h" #include "blender_sync.h" #include "blender_session.h" #include "util_foreach.h" #include "util_opengl.h" #include "util_path.h" CCL_NAMESPACE_BEGIN static PyObject *init_func(PyObject *self, PyObject *args) { const char *path, *user_path; if(!PyArg_ParseTuple(args, "ss", &path, &user_path)) return NULL; path_init(path, user_path); Py_RETURN_NONE; } static PyObject *create_func(PyObject *self, PyObject *args) { PyObject *pyengine, *pyuserpref, *pydata, *pyscene, *pyregion, *pyv3d, *pyrv3d; if(!PyArg_ParseTuple(args, "OOOOOOO", &pyengine, &pyuserpref, &pydata, &pyscene, &pyregion, &pyv3d, &pyrv3d)) return NULL; /* RNA */ PointerRNA engineptr; RNA_pointer_create(NULL, &RNA_RenderEngine, (void*)PyLong_AsVoidPtr(pyengine), &engineptr); BL::RenderEngine engine(engineptr); PointerRNA userprefptr; RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyuserpref), &userprefptr); BL::UserPreferences userpref(userprefptr); PointerRNA dataptr; RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pydata), &dataptr); BL::BlendData data(dataptr); PointerRNA sceneptr; RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr); BL::Scene scene(sceneptr); PointerRNA regionptr; RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyregion), &regionptr); BL::Region region(regionptr); PointerRNA v3dptr; RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyv3d), &v3dptr); BL::SpaceView3D v3d(v3dptr); PointerRNA rv3dptr; RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyrv3d), &rv3dptr); BL::RegionView3D rv3d(rv3dptr); /* create session */ BlenderSession *session; Py_BEGIN_ALLOW_THREADS if(rv3d) { /* interactive session */ int width = region.width(); int height = region.height(); session = new BlenderSession(engine, userpref, data, scene, v3d, rv3d, width, height); } else { /* offline session */ session = new BlenderSession(engine, userpref, data, scene); } Py_END_ALLOW_THREADS return PyLong_FromVoidPtr(session); } static PyObject *free_func(PyObject *self, PyObject *value) { delete (BlenderSession*)PyLong_AsVoidPtr(value); Py_RETURN_NONE; } static PyObject *render_func(PyObject *self, PyObject *value) { Py_BEGIN_ALLOW_THREADS BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(value); session->render(); Py_END_ALLOW_THREADS Py_RETURN_NONE; } static PyObject *draw_func(PyObject *self, PyObject *args) { PyObject *pysession, *pyv3d, *pyrv3d; if(!PyArg_ParseTuple(args, "OOO", &pysession, &pyv3d, &pyrv3d)) return NULL; BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession); if(PyLong_AsVoidPtr(pyrv3d)) { /* 3d view drawing */ int viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); session->draw(viewport[2], viewport[3]); } Py_RETURN_NONE; } static PyObject *sync_func(PyObject *self, PyObject *value) { Py_BEGIN_ALLOW_THREADS BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(value); session->synchronize(); Py_END_ALLOW_THREADS Py_RETURN_NONE; } static PyObject *available_devices_func(PyObject *self, PyObject *args) { vector<DeviceInfo>& devices = Device::available_devices(); PyObject *ret = PyTuple_New(devices.size()); for(size_t i = 0; i < devices.size(); i++) { DeviceInfo& device = devices[i]; PyTuple_SET_ITEM(ret, i, PyUnicode_FromString(device.description.c_str())); } return ret; } static PyMethodDef methods[] = { {"init", init_func, METH_VARARGS, ""}, {"create", create_func, METH_VARARGS, ""}, {"free", free_func, METH_O, ""}, {"render", render_func, METH_O, ""}, {"draw", draw_func, METH_VARARGS, ""}, {"sync", sync_func, METH_O, ""}, {"available_devices", available_devices_func, METH_NOARGS, ""}, {NULL, NULL, 0, NULL}, }; static struct PyModuleDef module = { PyModuleDef_HEAD_INIT, "_cycles", "Blender cycles render integration", -1, methods, NULL, NULL, NULL, NULL }; CCLDeviceInfo *compute_device_list(DeviceType type) { /* device list stored static */ static ccl::vector<CCLDeviceInfo> device_list; static ccl::DeviceType device_type = DEVICE_NONE; /* create device list if it's not already done */ if(type != device_type) { ccl::vector<DeviceInfo>& devices = ccl::Device::available_devices(); device_type = type; device_list.clear(); /* add devices */ int i = 0; foreach(DeviceInfo& info, devices) { if(info.type == type || (info.type == DEVICE_MULTI && info.multi_devices[0].type == type)) { CCLDeviceInfo cinfo = {info.id.c_str(), info.description.c_str(), i++}; device_list.push_back(cinfo); } } /* null terminate */ if(!device_list.empty()) { CCLDeviceInfo cinfo = {NULL, NULL, 0}; device_list.push_back(cinfo); } } return (device_list.empty())? NULL: &device_list[0]; } CCL_NAMESPACE_END void *CCL_python_module_init() { PyObject *mod = PyModule_Create(&ccl::module); #ifdef WITH_OSL PyModule_AddObject(mod, "with_osl", Py_True); Py_INCREF(Py_True); #else PyModule_AddObject(mod, "with_osl", Py_False); Py_INCREF(Py_False); #endif return (void*)mod; } CCLDeviceInfo *CCL_compute_device_list(int opencl) { ccl::DeviceType type = (opencl)? ccl::DEVICE_OPENCL: ccl::DEVICE_CUDA; return ccl::compute_device_list(type); } <commit_msg>code cleanup: quiet warnings for gcc's -Wundef, -Wmissing-declarations<commit_after>/* * Copyright 2011, Blender Foundation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <Python.h> #include "CCL_api.h" #include "blender_sync.h" #include "blender_session.h" #include "util_foreach.h" #include "util_opengl.h" #include "util_path.h" CCL_NAMESPACE_BEGIN static PyObject *init_func(PyObject *self, PyObject *args) { const char *path, *user_path; if(!PyArg_ParseTuple(args, "ss", &path, &user_path)) return NULL; path_init(path, user_path); Py_RETURN_NONE; } static PyObject *create_func(PyObject *self, PyObject *args) { PyObject *pyengine, *pyuserpref, *pydata, *pyscene, *pyregion, *pyv3d, *pyrv3d; if(!PyArg_ParseTuple(args, "OOOOOOO", &pyengine, &pyuserpref, &pydata, &pyscene, &pyregion, &pyv3d, &pyrv3d)) return NULL; /* RNA */ PointerRNA engineptr; RNA_pointer_create(NULL, &RNA_RenderEngine, (void*)PyLong_AsVoidPtr(pyengine), &engineptr); BL::RenderEngine engine(engineptr); PointerRNA userprefptr; RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyuserpref), &userprefptr); BL::UserPreferences userpref(userprefptr); PointerRNA dataptr; RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pydata), &dataptr); BL::BlendData data(dataptr); PointerRNA sceneptr; RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr); BL::Scene scene(sceneptr); PointerRNA regionptr; RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyregion), &regionptr); BL::Region region(regionptr); PointerRNA v3dptr; RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyv3d), &v3dptr); BL::SpaceView3D v3d(v3dptr); PointerRNA rv3dptr; RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyrv3d), &rv3dptr); BL::RegionView3D rv3d(rv3dptr); /* create session */ BlenderSession *session; Py_BEGIN_ALLOW_THREADS if(rv3d) { /* interactive session */ int width = region.width(); int height = region.height(); session = new BlenderSession(engine, userpref, data, scene, v3d, rv3d, width, height); } else { /* offline session */ session = new BlenderSession(engine, userpref, data, scene); } Py_END_ALLOW_THREADS return PyLong_FromVoidPtr(session); } static PyObject *free_func(PyObject *self, PyObject *value) { delete (BlenderSession*)PyLong_AsVoidPtr(value); Py_RETURN_NONE; } static PyObject *render_func(PyObject *self, PyObject *value) { Py_BEGIN_ALLOW_THREADS BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(value); session->render(); Py_END_ALLOW_THREADS Py_RETURN_NONE; } static PyObject *draw_func(PyObject *self, PyObject *args) { PyObject *pysession, *pyv3d, *pyrv3d; if(!PyArg_ParseTuple(args, "OOO", &pysession, &pyv3d, &pyrv3d)) return NULL; BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession); if(PyLong_AsVoidPtr(pyrv3d)) { /* 3d view drawing */ int viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); session->draw(viewport[2], viewport[3]); } Py_RETURN_NONE; } static PyObject *sync_func(PyObject *self, PyObject *value) { Py_BEGIN_ALLOW_THREADS BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(value); session->synchronize(); Py_END_ALLOW_THREADS Py_RETURN_NONE; } static PyObject *available_devices_func(PyObject *self, PyObject *args) { vector<DeviceInfo>& devices = Device::available_devices(); PyObject *ret = PyTuple_New(devices.size()); for(size_t i = 0; i < devices.size(); i++) { DeviceInfo& device = devices[i]; PyTuple_SET_ITEM(ret, i, PyUnicode_FromString(device.description.c_str())); } return ret; } static PyMethodDef methods[] = { {"init", init_func, METH_VARARGS, ""}, {"create", create_func, METH_VARARGS, ""}, {"free", free_func, METH_O, ""}, {"render", render_func, METH_O, ""}, {"draw", draw_func, METH_VARARGS, ""}, {"sync", sync_func, METH_O, ""}, {"available_devices", available_devices_func, METH_NOARGS, ""}, {NULL, NULL, 0, NULL}, }; static struct PyModuleDef module = { PyModuleDef_HEAD_INIT, "_cycles", "Blender cycles render integration", -1, methods, NULL, NULL, NULL, NULL }; static CCLDeviceInfo *compute_device_list(DeviceType type) { /* device list stored static */ static ccl::vector<CCLDeviceInfo> device_list; static ccl::DeviceType device_type = DEVICE_NONE; /* create device list if it's not already done */ if(type != device_type) { ccl::vector<DeviceInfo>& devices = ccl::Device::available_devices(); device_type = type; device_list.clear(); /* add devices */ int i = 0; foreach(DeviceInfo& info, devices) { if(info.type == type || (info.type == DEVICE_MULTI && info.multi_devices[0].type == type)) { CCLDeviceInfo cinfo = {info.id.c_str(), info.description.c_str(), i++}; device_list.push_back(cinfo); } } /* null terminate */ if(!device_list.empty()) { CCLDeviceInfo cinfo = {NULL, NULL, 0}; device_list.push_back(cinfo); } } return (device_list.empty())? NULL: &device_list[0]; } CCL_NAMESPACE_END void *CCL_python_module_init() { PyObject *mod = PyModule_Create(&ccl::module); #ifdef WITH_OSL PyModule_AddObject(mod, "with_osl", Py_True); Py_INCREF(Py_True); #else PyModule_AddObject(mod, "with_osl", Py_False); Py_INCREF(Py_False); #endif return (void*)mod; } CCLDeviceInfo *CCL_compute_device_list(int opencl) { ccl::DeviceType type = (opencl)? ccl::DEVICE_OPENCL: ccl::DEVICE_CUDA; return ccl::compute_device_list(type); } <|endoftext|>
<commit_before>// Copyright 2014 The Souper 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 "llvm/Support/MemoryBuffer.h" #include "souper/Parser/Parser.h" #include "souper/Tool/GetSolverFromArgs.h" using namespace llvm; using namespace souper; static cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input souper optimization>"), cl::init("-")); static llvm::cl::opt<bool> PrintCounterExample("print-counterexample", llvm::cl::desc("Print counterexample (default=true)"), llvm::cl::init(true)); int SolveInst(const MemoryBufferRef &MB, Solver *S) { InstContext IC; std::string ErrStr; ParsedReplacement Rep = ParseReplacement(IC, MB.getBufferIdentifier(), MB.getBuffer(), ErrStr); if (!ErrStr.empty()) { llvm::errs() << ErrStr << '\n'; return 1; } bool Valid; std::vector<std::pair<Inst *, APInt>> Models; if (std::error_code EC = S->isValid(Rep.PCs, Rep.Mapping, Valid, &Models)) { llvm::errs() << EC.message() << '\n'; return 1; } if (Valid) { llvm::outs() << "LGTM\n"; } else { llvm::outs() << "Invalid"; if (PrintCounterExample && !Models.empty()) { llvm::outs() << ", e.g.\n\n"; std::sort(Models.begin(), Models.end(), [](const std::pair<Inst *, APInt> &A, const std::pair<Inst *, APInt> &B) { return A.first->Name < B.first->Name; }); for (const auto &M : Models) { llvm::outs() << '%' << M.first->Name << " = " << M.second << '\n'; } } else { llvm::outs() << "\n"; } } return 0; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); std::unique_ptr<Solver> S = GetSolverFromArgs(); if (!S) { llvm::errs() << "Specify a solver\n"; return 1; } auto MB = MemoryBuffer::getFileOrSTDIN(InputFilename); if (!MB) { llvm::errs() << MB.getError().message() << '\n'; return 1; } return SolveInst((*MB)->getMemBufferRef(), S.get()); } <commit_msg>add option to echo the checked replacement<commit_after>// Copyright 2014 The Souper 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 "llvm/Support/MemoryBuffer.h" #include "souper/Parser/Parser.h" #include "souper/Tool/GetSolverFromArgs.h" using namespace llvm; using namespace souper; static cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input souper optimization>"), cl::init("-")); static cl::opt<bool> PrintCounterExample("print-counterexample", cl::desc("Print counterexample (default=true)"), cl::init(true)); static cl::opt<bool> PrintRepl("print-replacement", cl::desc("Print the replacement, if valid (default=false)"), cl::init(false)); int SolveInst(const MemoryBufferRef &MB, Solver *S) { InstContext IC; std::string ErrStr; ParsedReplacement Rep = ParseReplacement(IC, MB.getBufferIdentifier(), MB.getBuffer(), ErrStr); if (!ErrStr.empty()) { llvm::errs() << ErrStr << '\n'; return 1; } bool Valid; std::vector<std::pair<Inst *, APInt>> Models; if (std::error_code EC = S->isValid(Rep.PCs, Rep.Mapping, Valid, &Models)) { llvm::errs() << EC.message() << '\n'; return 1; } if (Valid) { llvm::outs() << "LGTM\n"; if (PrintRepl) PrintReplacement(llvm::outs(), Rep.PCs, Rep.Mapping); } else { llvm::outs() << "Invalid"; if (PrintCounterExample && !Models.empty()) { llvm::outs() << ", e.g.\n\n"; std::sort(Models.begin(), Models.end(), [](const std::pair<Inst *, APInt> &A, const std::pair<Inst *, APInt> &B) { return A.first->Name < B.first->Name; }); for (const auto &M : Models) { llvm::outs() << '%' << M.first->Name << " = " << M.second << '\n'; } } else { llvm::outs() << "\n"; } } return 0; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); std::unique_ptr<Solver> S = GetSolverFromArgs(); if (!S) { llvm::errs() << "Specify a solver\n"; return 1; } auto MB = MemoryBuffer::getFileOrSTDIN(InputFilename); if (!MB) { llvm::errs() << MB.getError().message() << '\n'; return 1; } return SolveInst((*MB)->getMemBufferRef(), S.get()); } <|endoftext|>
<commit_before>/* * This file is part of the CN24 semantic segmentation software, * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com). * * For licensing information, see the LICENSE file included with this project. */ /** * \file trainNetwork.cpp * \brief Trains a convolutional neural net for prediction. * * \author Clemens-Alexander Brust(ikosa dot de at gmail dot com) */ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <iomanip> #include <ctime> #include <cstring> #include <cn24.h> bool parseCommand(Conv::Net& net, Conv::Trainer& trainer, std::string& command); void help(); int main(int argc, char* argv[]) { bool DO_TEST = true; bool GRADIENT_CHECK = false; bool FROM_SCRIPT = false; #ifdef LAYERTIME const unsigned int BATCHSIZE = 1000; unsigned int TEST_EVERY = 1; const Conv::datum it_factor = 0.01; #else unsigned int BATCHSIZE = 4; const Conv::datum it_factor = 1; const Conv::datum loss_sampling_p = 0.25; #endif if (argc < 3) { LOGERROR << "USAGE: " << argv[0] << " <dataset config file> <net config file> {[script file]|gradient_check}"; LOGEND; return -1; } std::string script_fname; if (argc > 3 && std::string(argv[3]).compare("gradient_check") == 0) { GRADIENT_CHECK = true; } else if(argc > 3) { FROM_SCRIPT = true; script_fname = argv[3]; } std::string net_config_fname(argv[2]); std::string dataset_config_fname(argv[1]); Conv::System::Init(); // Open network and dataset configuration files std::ifstream net_config_file(net_config_fname, std::ios::in); std::ifstream dataset_config_file(dataset_config_fname, std::ios::in); if (!net_config_file.good()) { FATAL("Cannot open net configuration file!"); } net_config_fname = net_config_fname.substr(net_config_fname.rfind("/") + 1); if (!dataset_config_file.good()) { FATAL("Cannot open dataset configuration file!"); } dataset_config_fname = dataset_config_fname.substr(net_config_fname.rfind("/") + 1); // Parse network configuration file Conv::Factory* factory = new Conv::ConfigurableFactory(net_config_file, Conv::FCN); factory->InitOptimalSettings(); LOGDEBUG << "Optimal settings: " << factory->optimal_settings(); Conv::TrainerSettings settings = factory->optimal_settings(); settings.epoch_training_ratio = 1 * it_factor; settings.testing_ratio = 1 * it_factor; // Load dataset Conv::TensorStreamDataset* dataset = Conv::TensorStreamDataset::CreateFromConfiguration(dataset_config_file); unsigned int CLASSES = dataset->GetClasses(); // Assemble net Conv::Net net; int data_layer_id = 0; Conv::DatasetInputLayer* data_layer = nullptr; if (GRADIENT_CHECK) { Conv::Tensor* data_tensor = new Conv::Tensor(BATCHSIZE, dataset->GetWidth(), dataset->GetHeight(), dataset->GetInputMaps()); Conv::Tensor* weight_tensor = new Conv::Tensor(BATCHSIZE, dataset->GetWidth(), dataset->GetHeight(), 1); Conv::Tensor* label_tensor = new Conv::Tensor(BATCHSIZE, dataset->GetWidth(), dataset->GetHeight(), dataset->GetLabelMaps()); Conv::Tensor* helper_tensor = new Conv::Tensor(BATCHSIZE, dataset->GetWidth(), dataset->GetHeight(), 2); for (unsigned int b = 0; b < BATCHSIZE; b++) dataset->GetTestingSample(*data_tensor, *label_tensor, *weight_tensor, b, b); Conv::InputLayer* input_layer = new Conv::InputLayer(*data_tensor, *label_tensor, *helper_tensor, *weight_tensor); data_layer_id = net.AddLayer(input_layer); } else { data_layer = new Conv::DatasetInputLayer(*dataset, BATCHSIZE, loss_sampling_p, 983923); data_layer_id = net.AddLayer(data_layer); } int output_layer_id = factory->AddLayers(net, Conv::Connection(data_layer_id), CLASSES); LOGDEBUG << "Output layer id: " << output_layer_id; net.AddLayer(factory->CreateLossLayer(CLASSES), { Conv::Connection(output_layer_id), Conv::Connection(data_layer_id, 1), Conv::Connection(data_layer_id, 3), }); // Add appropriate statistics layer if (CLASSES == 1) { Conv::BinaryStatLayer* binary_stat_layer = new Conv::BinaryStatLayer(13, -1, 1); net.AddLayer(binary_stat_layer, { Conv::Connection(output_layer_id), Conv::Connection(data_layer_id, 1), Conv::Connection(data_layer_id, 3) }); } else { std::vector<std::string> class_names = dataset->GetClassNames(); Conv::ConfusionMatrixLayer* confusion_matrix_layer = new Conv::ConfusionMatrixLayer(class_names, CLASSES); net.AddLayer(confusion_matrix_layer, { Conv::Connection(output_layer_id), Conv::Connection(data_layer_id, 1), Conv::Connection(data_layer_id, 3) }); } // Initialize net with random weights net.InitializeWeights(); if (GRADIENT_CHECK) { Conv::GradientTester::TestGradient(net); } else { Conv::Trainer trainer(net, settings); if(FROM_SCRIPT) { LOGINFO << "Executing script: " << script_fname; std::ifstream script_file(script_fname, std::ios::in); if(!script_file.good()) { FATAL("Cannot open " << script_fname); } while (true) { std::string command; std::getline(script_file, command); if (!parseCommand(net, trainer, command) || script_file.eof()) break; } } else { LOGINFO << "Enter \"help\" for information on how to use this program"; while (true) { std::cout << "\n > " << std::flush; std::string command; std::getline(std::cin, command); if (!parseCommand(net, trainer, command)) break; } } } LOGINFO << "DONE!"; LOGEND; return 0; } bool parseCommand(Conv::Net& net, Conv::Trainer& trainer, std::string& command) { if (command.compare("q") == 0 || command.compare("quit") == 0) { return false; } else if (command.compare(0, 5, "train") == 0) { unsigned int epochs = 1; Conv::ParseCountIfPossible(command, "epochs", epochs); trainer.Train(epochs); LOGINFO << "Training complete."; } else if (command.compare(0, 4, "test") == 0) { unsigned int layerview = 0; Conv::ParseCountIfPossible(command, "view", layerview); net.SetLayerViewEnabled(layerview == 1); trainer.Test(); net.SetLayerViewEnabled(false); LOGINFO << "Testing complete."; } else if (command.compare(0, 4, "load") == 0) { std::string param_file_name; unsigned int last_layer = 0; Conv::ParseStringParamIfPossible(command, "file", param_file_name); Conv::ParseCountIfPossible(command, "last_layer", last_layer); if (param_file_name.length() == 0) { LOGERROR << "Filename needed!"; } else { std::ifstream param_file(param_file_name, std::ios::in | std::ios::binary); if (param_file.good()) { net.DeserializeParameters(param_file, last_layer); LOGINFO << "Loaded parameters from " << param_file_name; } else { LOGERROR << "Cannot open " << param_file_name; } param_file.close(); } } else if (command.compare(0, 4, "save") == 0) { std::string param_file_name; Conv::ParseStringParamIfPossible(command, "file", param_file_name); if (param_file_name.length() == 0) { LOGERROR << "Filename needed!"; } else { std::ofstream param_file(param_file_name, std::ios::out | std::ios::binary); if (param_file.good()) { net.SerializeParameters(param_file); LOGINFO << "Written parameters to " << param_file_name; } else { LOGERROR << "Cannot open " << param_file_name; } param_file.close(); } } else if (command.compare(0, 4, "help") == 0) { help(); } return true; } void help() { std::cout << "You can use the following commands:\n"; std::cout << " train [epochs=<n>]\n" << " Train the network for n epochs (default: 1)\n\n" << " test\n" << " Test the network\n\n" << " load file=<path> [last_layer=<l>]\n" << " Load parameters from a file for all layers up to l (default: all layers)\n\n" << " save file=<path>\n" << " Save parameters to a file\n"; } <commit_msg>Enhanced trainNetwork command set<commit_after>/* * This file is part of the CN24 semantic segmentation software, * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com). * * For licensing information, see the LICENSE file included with this project. */ /** * \file trainNetwork.cpp * \brief Trains a convolutional neural net for prediction. * * \author Clemens-Alexander Brust(ikosa dot de at gmail dot com) */ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <iomanip> #include <ctime> #include <cstring> #include <cn24.h> bool parseCommand(Conv::Net& net, Conv::Trainer& trainer, std::string& command); void help(); int main(int argc, char* argv[]) { bool DO_TEST = true; bool GRADIENT_CHECK = false; bool FROM_SCRIPT = false; #ifdef LAYERTIME const unsigned int BATCHSIZE = 1000; unsigned int TEST_EVERY = 1; const Conv::datum it_factor = 0.01; #else unsigned int BATCHSIZE = 4; const Conv::datum it_factor = 1; const Conv::datum loss_sampling_p = 0.25; #endif if (argc < 3) { LOGERROR << "USAGE: " << argv[0] << " <dataset config file> <net config file> {[script file]|gradient_check}"; LOGEND; return -1; } std::string script_fname; if (argc > 3 && std::string(argv[3]).compare("gradient_check") == 0) { GRADIENT_CHECK = true; } else if(argc > 3) { FROM_SCRIPT = true; script_fname = argv[3]; } std::string net_config_fname(argv[2]); std::string dataset_config_fname(argv[1]); Conv::System::Init(); // Open network and dataset configuration files std::ifstream net_config_file(net_config_fname, std::ios::in); std::ifstream dataset_config_file(dataset_config_fname, std::ios::in); if (!net_config_file.good()) { FATAL("Cannot open net configuration file!"); } net_config_fname = net_config_fname.substr(net_config_fname.rfind("/") + 1); if (!dataset_config_file.good()) { FATAL("Cannot open dataset configuration file!"); } dataset_config_fname = dataset_config_fname.substr(net_config_fname.rfind("/") + 1); // Parse network configuration file Conv::Factory* factory = new Conv::ConfigurableFactory(net_config_file, Conv::FCN); factory->InitOptimalSettings(); LOGDEBUG << "Optimal settings: " << factory->optimal_settings(); Conv::TrainerSettings settings = factory->optimal_settings(); settings.epoch_training_ratio = 1 * it_factor; settings.testing_ratio = 1 * it_factor; // Load dataset Conv::TensorStreamDataset* dataset = Conv::TensorStreamDataset::CreateFromConfiguration(dataset_config_file); unsigned int CLASSES = dataset->GetClasses(); // Assemble net Conv::Net net; int data_layer_id = 0; Conv::DatasetInputLayer* data_layer = nullptr; if (GRADIENT_CHECK) { Conv::Tensor* data_tensor = new Conv::Tensor(BATCHSIZE, dataset->GetWidth(), dataset->GetHeight(), dataset->GetInputMaps()); Conv::Tensor* weight_tensor = new Conv::Tensor(BATCHSIZE, dataset->GetWidth(), dataset->GetHeight(), 1); Conv::Tensor* label_tensor = new Conv::Tensor(BATCHSIZE, dataset->GetWidth(), dataset->GetHeight(), dataset->GetLabelMaps()); Conv::Tensor* helper_tensor = new Conv::Tensor(BATCHSIZE, dataset->GetWidth(), dataset->GetHeight(), 2); for (unsigned int b = 0; b < BATCHSIZE; b++) dataset->GetTestingSample(*data_tensor, *label_tensor, *weight_tensor, b, b); Conv::InputLayer* input_layer = new Conv::InputLayer(*data_tensor, *label_tensor, *helper_tensor, *weight_tensor); data_layer_id = net.AddLayer(input_layer); } else { data_layer = new Conv::DatasetInputLayer(*dataset, BATCHSIZE, loss_sampling_p, 983923); data_layer_id = net.AddLayer(data_layer); } int output_layer_id = factory->AddLayers(net, Conv::Connection(data_layer_id), CLASSES); LOGDEBUG << "Output layer id: " << output_layer_id; net.AddLayer(factory->CreateLossLayer(CLASSES), { Conv::Connection(output_layer_id), Conv::Connection(data_layer_id, 1), Conv::Connection(data_layer_id, 3), }); // Add appropriate statistics layer if (CLASSES == 1) { Conv::BinaryStatLayer* binary_stat_layer = new Conv::BinaryStatLayer(13, -1, 1); net.AddLayer(binary_stat_layer, { Conv::Connection(output_layer_id), Conv::Connection(data_layer_id, 1), Conv::Connection(data_layer_id, 3) }); } else { std::vector<std::string> class_names = dataset->GetClassNames(); Conv::ConfusionMatrixLayer* confusion_matrix_layer = new Conv::ConfusionMatrixLayer(class_names, CLASSES); net.AddLayer(confusion_matrix_layer, { Conv::Connection(output_layer_id), Conv::Connection(data_layer_id, 1), Conv::Connection(data_layer_id, 3) }); } // Initialize net with random weights net.InitializeWeights(); if (GRADIENT_CHECK) { Conv::GradientTester::TestGradient(net); } else { Conv::Trainer trainer(net, settings); if(FROM_SCRIPT) { LOGINFO << "Executing script: " << script_fname; std::ifstream script_file(script_fname, std::ios::in); if(!script_file.good()) { FATAL("Cannot open " << script_fname); } while (true) { std::string command; std::getline(script_file, command); if (!parseCommand(net, trainer, command) || script_file.eof()) break; } } else { LOGINFO << "Enter \"help\" for information on how to use this program"; while (true) { std::cout << "\n > " << std::flush; std::string command; std::getline(std::cin, command); if (!parseCommand(net, trainer, command)) break; } } } LOGINFO << "DONE!"; LOGEND; return 0; } bool parseCommand(Conv::Net& net, Conv::Trainer& trainer, std::string& command) { if (command.compare("q") == 0 || command.compare("quit") == 0) { return false; } else if (command.compare(0, 5, "train") == 0) { unsigned int epochs = 1; Conv::ParseCountIfPossible(command, "epochs", epochs); trainer.Train(epochs); LOGINFO << "Training complete."; } else if (command.compare(0, 4, "test") == 0) { unsigned int layerview = 0; Conv::ParseCountIfPossible(command, "view", layerview); net.SetLayerViewEnabled(layerview == 1); trainer.Test(); net.SetLayerViewEnabled(false); LOGINFO << "Testing complete."; } else if (command.compare(0, 4, "load") == 0) { std::string param_file_name; unsigned int last_layer = 0; Conv::ParseStringParamIfPossible(command, "file", param_file_name); Conv::ParseCountIfPossible(command, "last_layer", last_layer); if (param_file_name.length() == 0) { LOGERROR << "Filename needed!"; } else { std::ifstream param_file(param_file_name, std::ios::in | std::ios::binary); if (param_file.good()) { net.DeserializeParameters(param_file, last_layer); LOGINFO << "Loaded parameters from " << param_file_name; } else { LOGERROR << "Cannot open " << param_file_name; } param_file.close(); } } else if (command.compare(0, 4, "save") == 0) { std::string param_file_name; Conv::ParseStringParamIfPossible(command, "file", param_file_name); if (param_file_name.length() == 0) { LOGERROR << "Filename needed!"; } else { std::ofstream param_file(param_file_name, std::ios::out | std::ios::binary); if (param_file.good()) { net.SerializeParameters(param_file); LOGINFO << "Written parameters to " << param_file_name; } else { LOGERROR << "Cannot open " << param_file_name; } param_file.close(); } } else if (command.compare(0, 9, "set epoch") == 0) { unsigned int epoch = 0; Conv::ParseCountIfPossible(command, "epoch", epoch); LOGINFO << "Setting current epoch to " << epoch; } else if(command.compare(0, 5, "reset") == 0) { LOGINFO << "Resetting parameters"; net.InitializeWeights(); } else if (command.compare(0, 4, "help") == 0) { help(); } else { LOGWARN << "Unknown command: " << command; } return true; } void help() { std::cout << "You can use the following commands:\n"; std::cout << " train [epochs=<n>]\n" << " Train the network for n epochs (default: 1)\n\n" << " test\n" << " Test the network\n\n" << " set epoch=<epoch>\n" << " Sets the current epoch\n\n" << " reset\n" << " Reinitializes the nets parameters\n\n" << " load file=<path> [last_layer=<l>]\n" << " Load parameters from a file for all layers up to l (default: all layers)\n\n" << " save file=<path>\n" << " Save parameters to a file\n"; } <|endoftext|>
<commit_before>// @(#)root/tree:$Name: $:$Id: TSelector.cxx,v 1.32 2007/07/12 09:59:00 rdm Exp $ // Author: Rene Brun 05/02/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //////////////////////////////////////////////////////////////////////////// // // // A TSelector object is used by the TTree::Draw, TTree::Scan, // // TTree::Loop, TTree::Process to navigate in a TTree and make // // selections. It contains the following main methods: // // // // void TSelector::Init(TTree *t). Called every time a new TTree is // // attached. // // void TSelector::Begin(). This method is called before looping on the // // events in the Tree. The user can create his histograms in this // // function. When using PROOF Begin() is called on the client only. // // Histogram creation should preferable be done in SlaveBegin() in // // that case. // // void TSelector::SlaveBegin(). This method is called on each PROOF // // worker node. The user can create his histograms in this method. // // In local mode this method is called on the client too. // // // // Bool_t TSelector::Notify(). This method is called at the first entry // // of a new file in a chain. // // // // Bool_t TSelector::Process(Long64_t entry). This method is called // // to process an event. It is the user's responsability to read // // the corresponding entry in memory (may be just a partial read). // // Once the entry is in memory one can apply a selection and if the // // event is selected histograms can be filled. Processing stops // // when this function returns kFALSE. This function combines the // // next two functions in one, avoiding to have to maintain state // // in the class to communicate between these two funtions. // // See WARNING below about entry. // // This method is used by PROOF. // // Bool_t TSelector::ProcessCut(Long64_t entry). This method is called // // before processing entry. It is the user's responsability to read // // the corresponding entry in memory (may be just a partial read). // // The function returns kTRUE if the entry must be processed, // // kFALSE otherwise. This method is obsolete, use Process(). // // See WARNING below about entry. // // void TSelector::ProcessFill(Long64_t entry). This method is called // // for all selected events. User fills histograms in this function. // // This method is obsolete, use Process(). // // See WARNING below about entry. // // void TSelector::SlaveTerminate(). This method is called at the end of // // the loop on all PROOF worker nodes. In local mode this method is // // called on the client too. // // void TSelector::Terminate(). This method is called at the end of // // the loop on all events. When using PROOF Terminate() is call on // // the client only. Typically one performs the fits on the produced // // histograms or write the histograms to file in this method. // // // // WARNING when a selector is used with a TChain: // // in the Process, ProcessCut, ProcessFill function, you must use // // the pointer to the current Tree to call GetEntry(entry). // // entry is always the local entry number in the current tree. // // Assuming that fChain is the pointer to the TChain being processed, // // use fChain->GetTree()->GetEntry(entry); // // // //////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TSystem.h" #include "TTree.h" #include "TError.h" #include "TSelectorCint.h" #include "Api.h" #include "TClass.h" #include "TInterpreter.h" ClassImp(TSelector) //______________________________________________________________________________ TSelector::TSelector() : TObject() { // Default selector ctor. fStatus = 0; fAbort = kContinue; fObject = 0; fInput = 0; fOutput = new TSelectorList; fOutput->SetOwner(); } //______________________________________________________________________________ TSelector::~TSelector() { // Selector destructor. delete fOutput; } //______________________________________________________________________________ void TSelector::Abort(const char *why, EAbort what) { // Abort processing. If what = kAbortProcess, the Process() loop will be // aborted. If what = kAbortFile, the current file in a chain will be // aborted and the processing will continue with the next file, if there // is no next file then Process() will be aborted. Abort() can also be // called from Begin(), SlaveBegin(), Init() and Notify(). After abort // the SlaveTerminate() and Terminate() are always called. The abort flag // can be checked in these methods using GetAbort(). fAbort = what; TString mess = "Abort"; if (fAbort == kAbortProcess) mess = "AbortProcess"; else if (fAbort == kAbortFile) mess = "AbortFile"; Info(mess, why); } //______________________________________________________________________________ TSelector *TSelector::GetSelector(const char *filename) { // The code in filename is loaded (interpreted or compiled, see below), // filename must contain a valid class implementation derived from TSelector. // // If filename is of the form file.C, the file will be interpreted. // If filename is of the form file.C++, the file file.C will be compiled // and dynamically loaded. The corresponding binary file and shared // library will be deleted at the end of the function. // If filename is of the form file.C+, the file file.C will be compiled // and dynamically loaded. At next call, if file.C is older than file.o // and file.so, the file.C is not compiled, only file.so is loaded. // // The static function returns a pointer to a TSelector object // If the filename does not contain "." assume class is compiled in TString localname; Bool_t fromFile = kFALSE; if (strchr(filename, '.') != 0) { //Interpret/compile filename via CINT localname = ".L "; localname += filename; gROOT->ProcessLine(localname); fromFile = kTRUE; } //loop on all classes known to CINT to find the class on filename //that derives from TSelector const char *basename = gSystem->BaseName(filename); if (!basename) { ::Error("TSelector::GetSelector","unable to determine the classname for file %s", filename); return 0; } localname = basename; Bool_t isCompiled = !fromFile || localname.EndsWith("+"); if (localname.Index(".") != kNPOS) localname.Remove(localname.Index(".")); // if a file was not specified, try to load the class via the interpreter; // this returns 0 (== failure) in the case the class is already in memory // but does not have a dictionary, so we just raise a flag for better // diagnostic in the case the class is not found in the G__ClassInfo table. Bool_t autoloaderr = kFALSE; if (!fromFile && gInterpreter->AutoLoad(localname) != 1) autoloaderr = kTRUE; G__ClassInfo cl; Bool_t ok = kFALSE; while (cl.Next()) { if (localname == cl.Fullname()) { if (cl.IsBase("TSelector")) ok = kTRUE; break; } } if (!ok) { if (fromFile) { ::Error("TSelector::GetSelector", "file %s does not have a valid class deriving from TSelector", filename); } else { if (autoloaderr) ::Error("TSelector::GetSelector", "class %s could not be loaded", filename); else ::Error("TSelector::GetSelector", "class %s does not exist or does not derive from TSelector", filename); } return 0; } // we can now create an instance of the class TSelector *selector = (TSelector*)cl.New(); if (!selector || isCompiled) return selector; //interpreted selector: cannot be used as such //create a fake selector TSelectorCint *select = new TSelectorCint(); select->Build(selector, &cl); return select; } //______________________________________________________________________________ Bool_t TSelector::IsStandardDraw(const char *selec) { // Find out if this is a standard selection used for Draw actions // (either TSelectorDraw, TProofDraw or deriving from them). // Make sure we have a name if (!selec) { ::Info("TSelector::IsStandardDraw", "selector name undefined - do nothing"); return kFALSE; } Bool_t stdselec = kFALSE; if (!strchr(selec, '.')) { if (strstr(selec, "TSelectorDraw")) { stdselec = kTRUE; } else { TClass *cl = TClass::GetClass(selec); if (cl && (cl->InheritsFrom("TProofDraw") || cl->InheritsFrom("TSelectorDraw"))) stdselec = kTRUE; } } // We are done return stdselec; } <commit_msg>Remove reference to non-existent TTree::Loop function<commit_after>// @(#)root/tree:$Name: $:$Id: TSelector.cxx,v 1.33 2007/08/22 19:39:59 pcanal Exp $ // Author: Rene Brun 05/02/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //////////////////////////////////////////////////////////////////////////// // // // A TSelector object is used by the TTree::Draw, TTree::Scan, // // TTree::Process to navigate in a TTree and make selections. // // It contains the following main methods: // // // // void TSelector::Init(TTree *t). Called every time a new TTree is // // attached. // // void TSelector::Begin(). This method is called before looping on the // // events in the Tree. The user can create his histograms in this // // function. When using PROOF Begin() is called on the client only. // // Histogram creation should preferable be done in SlaveBegin() in // // that case. // // void TSelector::SlaveBegin(). This method is called on each PROOF // // worker node. The user can create his histograms in this method. // // In local mode this method is called on the client too. // // // // Bool_t TSelector::Notify(). This method is called at the first entry // // of a new file in a chain. // // // // Bool_t TSelector::Process(Long64_t entry). This method is called // // to process an event. It is the user's responsability to read // // the corresponding entry in memory (may be just a partial read). // // Once the entry is in memory one can apply a selection and if the // // event is selected histograms can be filled. Processing stops // // when this function returns kFALSE. This function combines the // // next two functions in one, avoiding to have to maintain state // // in the class to communicate between these two funtions. // // See WARNING below about entry. // // This method is used by PROOF. // // Bool_t TSelector::ProcessCut(Long64_t entry). This method is called // // before processing entry. It is the user's responsability to read // // the corresponding entry in memory (may be just a partial read). // // The function returns kTRUE if the entry must be processed, // // kFALSE otherwise. This method is obsolete, use Process(). // // See WARNING below about entry. // // void TSelector::ProcessFill(Long64_t entry). This method is called // // for all selected events. User fills histograms in this function. // // This method is obsolete, use Process(). // // See WARNING below about entry. // // void TSelector::SlaveTerminate(). This method is called at the end of // // the loop on all PROOF worker nodes. In local mode this method is // // called on the client too. // // void TSelector::Terminate(). This method is called at the end of // // the loop on all events. When using PROOF Terminate() is call on // // the client only. Typically one performs the fits on the produced // // histograms or write the histograms to file in this method. // // // // WARNING when a selector is used with a TChain: // // in the Process, ProcessCut, ProcessFill function, you must use // // the pointer to the current Tree to call GetEntry(entry). // // entry is always the local entry number in the current tree. // // Assuming that fChain is the pointer to the TChain being processed, // // use fChain->GetTree()->GetEntry(entry); // // // //////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TSystem.h" #include "TTree.h" #include "TError.h" #include "TSelectorCint.h" #include "Api.h" #include "TClass.h" #include "TInterpreter.h" ClassImp(TSelector) //______________________________________________________________________________ TSelector::TSelector() : TObject() { // Default selector ctor. fStatus = 0; fAbort = kContinue; fObject = 0; fInput = 0; fOutput = new TSelectorList; fOutput->SetOwner(); } //______________________________________________________________________________ TSelector::~TSelector() { // Selector destructor. delete fOutput; } //______________________________________________________________________________ void TSelector::Abort(const char *why, EAbort what) { // Abort processing. If what = kAbortProcess, the Process() loop will be // aborted. If what = kAbortFile, the current file in a chain will be // aborted and the processing will continue with the next file, if there // is no next file then Process() will be aborted. Abort() can also be // called from Begin(), SlaveBegin(), Init() and Notify(). After abort // the SlaveTerminate() and Terminate() are always called. The abort flag // can be checked in these methods using GetAbort(). fAbort = what; TString mess = "Abort"; if (fAbort == kAbortProcess) mess = "AbortProcess"; else if (fAbort == kAbortFile) mess = "AbortFile"; Info(mess, why); } //______________________________________________________________________________ TSelector *TSelector::GetSelector(const char *filename) { // The code in filename is loaded (interpreted or compiled, see below), // filename must contain a valid class implementation derived from TSelector. // // If filename is of the form file.C, the file will be interpreted. // If filename is of the form file.C++, the file file.C will be compiled // and dynamically loaded. The corresponding binary file and shared // library will be deleted at the end of the function. // If filename is of the form file.C+, the file file.C will be compiled // and dynamically loaded. At next call, if file.C is older than file.o // and file.so, the file.C is not compiled, only file.so is loaded. // // The static function returns a pointer to a TSelector object // If the filename does not contain "." assume class is compiled in TString localname; Bool_t fromFile = kFALSE; if (strchr(filename, '.') != 0) { //Interpret/compile filename via CINT localname = ".L "; localname += filename; gROOT->ProcessLine(localname); fromFile = kTRUE; } //loop on all classes known to CINT to find the class on filename //that derives from TSelector const char *basename = gSystem->BaseName(filename); if (!basename) { ::Error("TSelector::GetSelector","unable to determine the classname for file %s", filename); return 0; } localname = basename; Bool_t isCompiled = !fromFile || localname.EndsWith("+"); if (localname.Index(".") != kNPOS) localname.Remove(localname.Index(".")); // if a file was not specified, try to load the class via the interpreter; // this returns 0 (== failure) in the case the class is already in memory // but does not have a dictionary, so we just raise a flag for better // diagnostic in the case the class is not found in the G__ClassInfo table. Bool_t autoloaderr = kFALSE; if (!fromFile && gInterpreter->AutoLoad(localname) != 1) autoloaderr = kTRUE; G__ClassInfo cl; Bool_t ok = kFALSE; while (cl.Next()) { if (localname == cl.Fullname()) { if (cl.IsBase("TSelector")) ok = kTRUE; break; } } if (!ok) { if (fromFile) { ::Error("TSelector::GetSelector", "file %s does not have a valid class deriving from TSelector", filename); } else { if (autoloaderr) ::Error("TSelector::GetSelector", "class %s could not be loaded", filename); else ::Error("TSelector::GetSelector", "class %s does not exist or does not derive from TSelector", filename); } return 0; } // we can now create an instance of the class TSelector *selector = (TSelector*)cl.New(); if (!selector || isCompiled) return selector; //interpreted selector: cannot be used as such //create a fake selector TSelectorCint *select = new TSelectorCint(); select->Build(selector, &cl); return select; } //______________________________________________________________________________ Bool_t TSelector::IsStandardDraw(const char *selec) { // Find out if this is a standard selection used for Draw actions // (either TSelectorDraw, TProofDraw or deriving from them). // Make sure we have a name if (!selec) { ::Info("TSelector::IsStandardDraw", "selector name undefined - do nothing"); return kFALSE; } Bool_t stdselec = kFALSE; if (!strchr(selec, '.')) { if (strstr(selec, "TSelectorDraw")) { stdselec = kTRUE; } else { TClass *cl = TClass::GetClass(selec); if (cl && (cl->InheritsFrom("TProofDraw") || cl->InheritsFrom("TSelectorDraw"))) stdselec = kTRUE; } } // We are done return stdselec; } <|endoftext|>
<commit_before>/* Copyright 2013 Roman Kurbatov * * 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 "motorLever.h" #include <QtGui/QKeyEvent> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QStylePainter> #include <QtGui/QStyleOptionFocusRect> #else #include <QtWidgets/QStylePainter> #include <QtWidgets/QStyleOptionFocusRect> #endif #include <QDebug> #include <trikControl/powerMotor.h> using namespace trikGui; MotorLever::MotorLever(QString const &name, trikControl::PowerMotor *powerMotor, QWidget *parent) : QWidget(parent) , mPowerMotor(powerMotor) , mIsOn(false) , mMaxPower(100) , mMinPower(-100) , mPowerStep(10) , mPower(0) , mNameLabel(name) , mPowerLabel("0") , mOnOffLabel(tr("off")) { mPowerMotor->powerOff(); mPowerBar.setOrientation(Qt::Vertical); mPowerBar.setMinimum(mMinPower); mPowerBar.setMaximum(mMaxPower); mPowerBar.setValue(0); mPowerBar.setTextVisible(false); mNameLabel.setAlignment(Qt::AlignCenter); mPowerLabel.setAlignment(Qt::AlignCenter); mOnOffLabel.setAlignment(Qt::AlignCenter); mLayout.addWidget(&mNameLabel); mLayout.addWidget(&mPowerBar, 0, Qt::AlignCenter); mLayout.addWidget(&mPowerLabel); mLayout.addWidget(&mOnOffLabel); setLayout(&mLayout); setFocusPolicy(Qt::StrongFocus); } MotorLever::~MotorLever() { qDebug() << "Deleteing motor lever"; mPowerMotor->powerOff(); } void MotorLever::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Up: { setPower(mPower + mPowerStep); break; } case Qt::Key_Down: { setPower(mPower - mPowerStep); break; } case Qt::Key_Return: { turnOnOff(); break; } default: { QWidget::keyPressEvent(event); } } } void MotorLever::paintEvent(QPaintEvent *) { QStylePainter painter(this); if (hasFocus()) { QStyleOptionFocusRect option; option.initFrom(this); option.backgroundColor = palette().color(QPalette::Background); painter.drawPrimitive(QStyle::PE_FrameFocusRect, option); } } void MotorLever::setPower(int power) { mPower = power; mPowerBar.setValue(power); mPowerLabel.setText(QString::number(power)); if (mIsOn) { mPowerMotor->setPower(power); } } void MotorLever::turnOnOff() { mIsOn = !mIsOn; if (mIsOn) { mOnOffLabel.setText(tr("on")); mPowerMotor->setPower(mPower); } else { mOnOffLabel.setText(tr("off")); mPowerMotor->powerOff(); } } <commit_msg>avoid setting an out-of-range value<commit_after>/* Copyright 2013 Roman Kurbatov * * 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 "motorLever.h" #include <QtGui/QKeyEvent> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QStylePainter> #include <QtGui/QStyleOptionFocusRect> #else #include <QtWidgets/QStylePainter> #include <QtWidgets/QStyleOptionFocusRect> #endif #include <QDebug> #include <trikControl/powerMotor.h> using namespace trikGui; MotorLever::MotorLever(QString const &name, trikControl::PowerMotor *powerMotor, QWidget *parent) : QWidget(parent) , mPowerMotor(powerMotor) , mIsOn(false) , mMaxPower(100) , mMinPower(-100) , mPowerStep(10) , mPower(0) , mNameLabel(name) , mPowerLabel("0") , mOnOffLabel(tr("off")) { mPowerMotor->powerOff(); mPowerBar.setOrientation(Qt::Vertical); mPowerBar.setMinimum(mMinPower); mPowerBar.setMaximum(mMaxPower); mPowerBar.setValue(0); mPowerBar.setTextVisible(false); mNameLabel.setAlignment(Qt::AlignCenter); mPowerLabel.setAlignment(Qt::AlignCenter); mOnOffLabel.setAlignment(Qt::AlignCenter); mLayout.addWidget(&mNameLabel); mLayout.addWidget(&mPowerBar, 0, Qt::AlignCenter); mLayout.addWidget(&mPowerLabel); mLayout.addWidget(&mOnOffLabel); setLayout(&mLayout); setFocusPolicy(Qt::StrongFocus); } MotorLever::~MotorLever() { qDebug() << "Deleteing motor lever"; mPowerMotor->powerOff(); } void MotorLever::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Up: { setPower(mPower + mPowerStep); break; } case Qt::Key_Down: { setPower(mPower - mPowerStep); break; } case Qt::Key_Return: { turnOnOff(); break; } default: { QWidget::keyPressEvent(event); } } } void MotorLever::paintEvent(QPaintEvent *) { QStylePainter painter(this); if (hasFocus()) { QStyleOptionFocusRect option; option.initFrom(this); option.backgroundColor = palette().color(QPalette::Background); painter.drawPrimitive(QStyle::PE_FrameFocusRect, option); } } void MotorLever::setPower(int power) { if (power > mMaxPower || power < mMinPower) { return; } mPower = power; mPowerBar.setValue(power); mPowerLabel.setText(QString::number(power)); if (mIsOn) { mPowerMotor->setPower(power); } } void MotorLever::turnOnOff() { mIsOn = !mIsOn; if (mIsOn) { mOnOffLabel.setText(tr("on")); mPowerMotor->setPower(mPower); } else { mOnOffLabel.setText(tr("off")); mPowerMotor->powerOff(); } } <|endoftext|>
<commit_before>//(c) 2016 by Authors //This file is a part of ABruijn program. //Released under the BSD license (see LICENSE file) #include "multiplicity_inferer.h" #include <simplex.h> #include <variable.h> void MultiplicityInferer:: fixEdgesMultiplicity(const std::vector<GraphAlignment>& readAln) { this->estimateByCoverage(readAln); this->balanceGraph(); } void MultiplicityInferer:: estimateByCoverage(const std::vector<GraphAlignment>& readAln) { std::unordered_map<GraphEdge*, int64_t> edgesCoverage; //std::unordered_map<GraphEdge*, int64_t> numReads; for (auto& path : readAln) { for (size_t i = 0; i < path.size(); ++i) { if (0 < i && i < path.size() - 1) { edgesCoverage[path[i].edge] += path[i].edge->length(); //++numReads[path[i].edge]; } else { edgesCoverage[path[i].edge] += path[i].overlap.extRange(); //++numReads[path[i].edge]; } } } int64_t sumCov = 0; int64_t sumLength = 0; for (auto edgeCov : edgesCoverage) { sumCov += edgeCov.second; sumLength += edgeCov.first->length(); } int meanCoverage = (sumLength != 0) ? sumCov / sumLength : 1; Logger::get().debug() << "Mean edge coverage: " << meanCoverage; for (auto edge : _graph.iterEdges()) { //if (edge->isLooped() && // edge->length() < Constants::maximumJump) continue; GraphEdge* complEdge = _graph.complementPath({edge}).front(); float normCov = (edgesCoverage[edge] + edgesCoverage[complEdge]) / (2 * edge->length() + 1); float minMult = (!edge->isTip()) ? 1 : 0; int estMult = std::max(minMult, roundf(normCov / meanCoverage)); std::string match = estMult != edge->multiplicity ? "*" : " "; Logger::get().debug() << match << "\t" << edge->edgeId.signedId() << "\t" << edge->multiplicity << "\t" << estMult << "\t" << normCov << "\t" << (float)normCov / meanCoverage; edge->multiplicity = estMult; } } void MultiplicityInferer::balanceGraph() { const int TRUSTED_EDGE_LEN = 10000; auto trustedEdge = [](const GraphEdge* edge) { return edge->length() > TRUSTED_EDGE_LEN && edge->multiplicity == 1; }; using namespace optimization; Logger::get().info() << "Updating edges multiplicity"; //enumerating edges std::unordered_map<GraphEdge*, size_t> edgeToId; std::map<size_t, GraphEdge*> idToEdge; size_t numberEdges = 0; size_t numTrusted = 0; for (auto edge : _graph.iterEdges()) { if (edge->isLooped()) continue; if (trustedEdge(edge)) { ++numTrusted; continue; } if (!edgeToId.count(edge)) { GraphEdge* complEdge = _graph.complementPath({edge}).front(); edgeToId[edge] = numberEdges; edgeToId[complEdge] = numberEdges; idToEdge[numberEdges] = edge; ++numberEdges; } } //enumerating nodes std::unordered_map<GraphNode*, size_t> nodeToId; std::map<size_t, GraphNode*> idToNode; size_t numberNodes = 0; for (auto node : _graph.iterNodes()) { if (node->inEdges.empty() || node->outEdges.empty()) continue; if (node->neighbors().size() < 2) continue; if (!nodeToId.count(node)) { GraphNode* complNode = _graph.complementNode(node); nodeToId[complNode] = numberNodes; nodeToId[node] = numberNodes; idToNode[numberNodes] = node; ++numberNodes; } } Logger::get().debug() << "Processing graph with " << numberNodes << " nodes, " << numberEdges << " edges"; Logger::get().debug() << "Found " << numTrusted / 2 << " trusted edges"; //formulate linear programming Simplex simplex(""); size_t numVariables = numberEdges + numberNodes * 2; for (auto& idEdgePair : idToEdge) { pilal::Matrix eye(1, numVariables, 0); eye(idEdgePair.first) = 1; std::string varName = std::to_string(idEdgePair.second->edgeId.signedId()); simplex.add_variable(new Variable(&simplex, varName.c_str())); simplex.add_constraint(Constraint(eye, CT_MORE_EQUAL, (float)idEdgePair.second->multiplicity)); /*if (idEdgePair.second->length() > TRUSTED_EDGE_LEN && idEdgePair.second->multiplicity == 1) { simplex.add_constraint(Constraint(eye, CT_LESS_EQUAL, 1.0f)); }*/ } std::vector<std::vector<int>> incorporatedEquations; for (auto& idNodePair : idToNode) { size_t sourceId = numberEdges + idNodePair.first * 2; size_t sinkId = numberEdges + idNodePair.first * 2 + 1; //emergency source std::string sourceName = std::to_string(idNodePair.first) + "_source"; simplex.add_variable(new Variable(&simplex, sourceName.c_str())); pilal::Matrix sourceMat(1, numVariables, 0); sourceMat(sourceId) = 1; simplex.add_constraint(Constraint(sourceMat, CT_MORE_EQUAL, 0.0f)); //emergency sink std::string sinkName = std::to_string(idNodePair.first) + "_sink"; simplex.add_variable(new Variable(&simplex, sinkName.c_str())); pilal::Matrix sinkMat(1, numVariables, 0); sinkMat(sinkId) = 1; simplex.add_constraint(Constraint(sinkMat, CT_MORE_EQUAL, 0.0f)); //adding in/out edges into the problem std::vector<int> coefficients(numberEdges, 0); int degreeSum = 0; for (auto edge : idNodePair.second->inEdges) { if (!edge->isLooped()) { if (trustedEdge(edge)) { degreeSum -= 1; } else { coefficients[edgeToId[edge]] += 1; } } } for (auto edge : idNodePair.second->outEdges) { if (!edge->isLooped()) { if (trustedEdge(edge)) { degreeSum += 1; } else { coefficients[edgeToId[edge]] -= 1; } } } // //build the matrix with all equations and check if it's linearly independend pilal::Matrix problemMatrix(incorporatedEquations.size() + 1, numberEdges, 0); for (size_t column = 0; column < incorporatedEquations.size(); ++column) { for (size_t row = 0; row < numberEdges; ++row) { problemMatrix(column, row) = incorporatedEquations[column][row]; } } for (size_t row = 0; row < numberEdges; ++row) { problemMatrix(incorporatedEquations.size(), row) = coefficients[row]; } if (!problemMatrix.rows_linearly_independent()) continue; // pilal::Matrix coefMatrix(1, numVariables, 0); for (size_t i = 0; i < numberEdges; ++i) { coefMatrix(i) = coefficients[i]; } coefMatrix(sourceId) = 1; coefMatrix(sinkId) = -1; simplex.add_constraint(Constraint(coefMatrix, CT_EQUAL, (float)degreeSum)); incorporatedEquations.push_back(std::move(coefficients)); } pilal::Matrix costs(1, numVariables, 1.0f); /*for (auto& idEdgePair : idToEdge) { if (idEdgePair.second->length() > TRUSTED_EDGE_LEN) { costs(idEdgePair.first) = 10.0f; } }*/ for (size_t i = numberEdges; i < numVariables; ++i) costs(i) = 1000.0f; simplex.set_objective_function(ObjectiveFunction(OFT_MINIMIZE, costs)); simplex.solve(); if (!simplex.has_solutions() || simplex.must_be_fixed() || simplex.is_unlimited()) throw std::runtime_error("Error while solving LP"); //simplex.print_solution(); for (auto& edgeIdPair : edgeToId) { int inferredMult = simplex.get_solution()(edgeIdPair.second); if (edgeIdPair.first->multiplicity != inferredMult) { Logger::get().debug() << "Mult " << edgeIdPair.first->edgeId.signedId() << " " << edgeIdPair.first->multiplicity << " -> " << inferredMult; edgeIdPair.first->multiplicity = inferredMult; } } //show warning if the graph remained unbalanced int nodesAffected = 0; int sumSource = 0; int sumSink = 0; for (size_t i = 0; i < numberNodes; ++i) { int nodeSource = simplex.get_solution()(numberEdges + i * 2); int nodeSink = simplex.get_solution()(numberEdges + i * 2 + 1); sumSource += nodeSource; sumSink += nodeSink; if (nodeSource + nodeSink > 0) { ++nodesAffected; } } if (nodesAffected) { Logger::get().warning() << "Could not balance assembly graph in full: " << nodesAffected << " nodes remained, extra source: " << sumSource << " extra sink: " << sumSink; } } <commit_msg>estimating number of LP clusters<commit_after>//(c) 2016 by Authors //This file is a part of ABruijn program. //Released under the BSD license (see LICENSE file) #include "multiplicity_inferer.h" #include "../common/disjoint_set.h" #include <simplex.h> #include <variable.h> void MultiplicityInferer:: fixEdgesMultiplicity(const std::vector<GraphAlignment>& readAln) { this->estimateByCoverage(readAln); this->balanceGraph(); } void MultiplicityInferer:: estimateByCoverage(const std::vector<GraphAlignment>& readAln) { std::unordered_map<GraphEdge*, int64_t> edgesCoverage; //std::unordered_map<GraphEdge*, int64_t> numReads; for (auto& path : readAln) { for (size_t i = 0; i < path.size(); ++i) { if (0 < i && i < path.size() - 1) { edgesCoverage[path[i].edge] += path[i].edge->length(); //++numReads[path[i].edge]; } else { edgesCoverage[path[i].edge] += path[i].overlap.extRange(); //++numReads[path[i].edge]; } } } int64_t sumCov = 0; int64_t sumLength = 0; for (auto edgeCov : edgesCoverage) { sumCov += edgeCov.second; sumLength += edgeCov.first->length(); } int meanCoverage = (sumLength != 0) ? sumCov / sumLength : 1; Logger::get().debug() << "Mean edge coverage: " << meanCoverage; for (auto edge : _graph.iterEdges()) { //if (edge->isLooped() && // edge->length() < Constants::maximumJump) continue; GraphEdge* complEdge = _graph.complementPath({edge}).front(); float normCov = (edgesCoverage[edge] + edgesCoverage[complEdge]) / (2 * edge->length() + 1); float minMult = (!edge->isTip()) ? 1 : 0; int estMult = std::max(minMult, roundf(normCov / meanCoverage)); std::string match = estMult != edge->multiplicity ? "*" : " "; Logger::get().debug() << match << "\t" << edge->edgeId.signedId() << "\t" << edge->multiplicity << "\t" << estMult << "\t" << normCov << "\t" << (float)normCov / meanCoverage; edge->multiplicity = estMult; } } void MultiplicityInferer::balanceGraph() { const int TRUSTED_EDGE_LEN = 10000; auto trustedEdge = [](const GraphEdge* edge) { return edge->length() > TRUSTED_EDGE_LEN && edge->multiplicity == 1; }; using namespace optimization; Logger::get().info() << "Updating edges multiplicity"; //enumerating edges std::unordered_map<GraphEdge*, size_t> edgeToId; std::unordered_map<GraphEdge*, SetNode<GraphEdge*>*> edgeClusters; std::map<size_t, GraphEdge*> idToEdge; size_t numberEdges = 0; size_t numTrusted = 0; for (auto edge : _graph.iterEdges()) { if (edge->isLooped()) continue; if (trustedEdge(edge)) { ++numTrusted; continue; } edgeClusters[edge] = new SetNode<GraphEdge*>(edge); if (!edgeToId.count(edge)) { GraphEdge* complEdge = _graph.complementPath({edge}).front(); edgeToId[edge] = numberEdges; edgeToId[complEdge] = numberEdges; idToEdge[numberEdges] = edge; ++numberEdges; } } //enumerating nodes std::unordered_map<GraphNode*, size_t> nodeToId; std::map<size_t, GraphNode*> idToNode; size_t numberNodes = 0; for (auto node : _graph.iterNodes()) { if (node->inEdges.empty() || node->outEdges.empty()) continue; if (node->neighbors().size() < 2) continue; for (auto& inEdge : node->inEdges) { if (trustedEdge(inEdge) || inEdge->isLooped()) continue; for (auto& outEdge : node->outEdges) { if (trustedEdge(outEdge) || outEdge->isLooped()) continue; unionSet(edgeClusters[inEdge], edgeClusters[outEdge]); } } if (!nodeToId.count(node)) { GraphNode* complNode = _graph.complementNode(node); nodeToId[complNode] = numberNodes; nodeToId[node] = numberNodes; idToNode[numberNodes] = node; ++numberNodes; } } Logger::get().debug() << "Processing graph with " << numberNodes << " nodes, " << numberEdges << " edges"; Logger::get().debug() << "Found " << numTrusted / 2 << " trusted edges"; std::unordered_set<SetNode<GraphEdge*>*> clusters; for (auto nodePair : edgeClusters) clusters.insert(findSet(nodePair.second)); Logger::get().debug() << "Clusters: " << clusters.size(); //formulate linear programming Simplex simplex(""); size_t numVariables = numberEdges + numberNodes * 2; for (auto& idEdgePair : idToEdge) { pilal::Matrix eye(1, numVariables, 0); eye(idEdgePair.first) = 1; std::string varName = std::to_string(idEdgePair.second->edgeId.signedId()); simplex.add_variable(new Variable(&simplex, varName.c_str())); simplex.add_constraint(Constraint(eye, CT_MORE_EQUAL, (float)idEdgePair.second->multiplicity)); /*if (idEdgePair.second->length() > TRUSTED_EDGE_LEN && idEdgePair.second->multiplicity == 1) { simplex.add_constraint(Constraint(eye, CT_LESS_EQUAL, 1.0f)); }*/ } std::vector<std::vector<int>> incorporatedEquations; for (auto& idNodePair : idToNode) { size_t sourceId = numberEdges + idNodePair.first * 2; size_t sinkId = numberEdges + idNodePair.first * 2 + 1; //emergency source std::string sourceName = std::to_string(idNodePair.first) + "_source"; simplex.add_variable(new Variable(&simplex, sourceName.c_str())); pilal::Matrix sourceMat(1, numVariables, 0); sourceMat(sourceId) = 1; simplex.add_constraint(Constraint(sourceMat, CT_MORE_EQUAL, 0.0f)); //emergency sink std::string sinkName = std::to_string(idNodePair.first) + "_sink"; simplex.add_variable(new Variable(&simplex, sinkName.c_str())); pilal::Matrix sinkMat(1, numVariables, 0); sinkMat(sinkId) = 1; simplex.add_constraint(Constraint(sinkMat, CT_MORE_EQUAL, 0.0f)); //adding in/out edges into the problem std::vector<int> coefficients(numberEdges, 0); int degreeSum = 0; for (auto edge : idNodePair.second->inEdges) { if (!edge->isLooped()) { if (trustedEdge(edge)) { degreeSum -= 1; } else { coefficients[edgeToId[edge]] += 1; } } } for (auto edge : idNodePair.second->outEdges) { if (!edge->isLooped()) { if (trustedEdge(edge)) { degreeSum += 1; } else { coefficients[edgeToId[edge]] -= 1; } } } // //build the matrix with all equations and check if it's linearly independend pilal::Matrix problemMatrix(incorporatedEquations.size() + 1, numberEdges, 0); for (size_t column = 0; column < incorporatedEquations.size(); ++column) { for (size_t row = 0; row < numberEdges; ++row) { problemMatrix(column, row) = incorporatedEquations[column][row]; } } for (size_t row = 0; row < numberEdges; ++row) { problemMatrix(incorporatedEquations.size(), row) = coefficients[row]; } if (!problemMatrix.rows_linearly_independent()) continue; // pilal::Matrix coefMatrix(1, numVariables, 0); for (size_t i = 0; i < numberEdges; ++i) { coefMatrix(i) = coefficients[i]; } coefMatrix(sourceId) = 1; coefMatrix(sinkId) = -1; simplex.add_constraint(Constraint(coefMatrix, CT_EQUAL, (float)degreeSum)); incorporatedEquations.push_back(std::move(coefficients)); } pilal::Matrix costs(1, numVariables, 1.0f); /*for (auto& idEdgePair : idToEdge) { if (idEdgePair.second->length() > TRUSTED_EDGE_LEN) { costs(idEdgePair.first) = 10.0f; } }*/ for (size_t i = numberEdges; i < numVariables; ++i) costs(i) = 1000.0f; simplex.set_objective_function(ObjectiveFunction(OFT_MINIMIZE, costs)); simplex.solve(); if (!simplex.has_solutions() || simplex.must_be_fixed() || simplex.is_unlimited()) throw std::runtime_error("Error while solving LP"); //simplex.print_solution(); for (auto& edgeIdPair : edgeToId) { int inferredMult = simplex.get_solution()(edgeIdPair.second); if (edgeIdPair.first->multiplicity != inferredMult) { Logger::get().debug() << "Mult " << edgeIdPair.first->edgeId.signedId() << " " << edgeIdPair.first->multiplicity << " -> " << inferredMult; edgeIdPair.first->multiplicity = inferredMult; } } //show warning if the graph remained unbalanced int nodesAffected = 0; int sumSource = 0; int sumSink = 0; for (size_t i = 0; i < numberNodes; ++i) { int nodeSource = simplex.get_solution()(numberEdges + i * 2); int nodeSink = simplex.get_solution()(numberEdges + i * 2 + 1); sumSource += nodeSource; sumSink += nodeSink; if (nodeSource + nodeSink > 0) { ++nodesAffected; } } if (nodesAffected) { Logger::get().warning() << "Could not balance assembly graph in full: " << nodesAffected << " nodes remained, extra source: " << sumSource << " extra sink: " << sumSink; } } <|endoftext|>
<commit_before>#include "ecdh.h" #include <openssl/ecdh.h> #include <openssl/objects.h> template <typename T, typename U> inline void CHECK_NE(T a, U b) { if (a == b) throw std::runtime_error("Something went wrong, can't be equal."); } namespace dsa { ECDH::ECDH(const char *curve) { int nid = OBJ_sn2nid(curve); if (nid == NID_undef) throw std::runtime_error("invalid curve name"); key = EC_KEY_new_by_curve_name(nid); if (!EC_KEY_generate_key(key)) throw std::runtime_error("failed to generate ecdh key"); group = EC_KEY_get0_group(key); } ECDH::~ECDH() { EC_KEY_free(key); } BufferPtr ECDH::get_private_key() const { const BIGNUM *priv = EC_KEY_get0_private_key(key); if (priv == nullptr) throw std::runtime_error("private key not set"); int size = BN_num_bytes(priv); uint8_t *out = new uint8_t[size]; if (size != BN_bn2bin(priv, out)) { delete[] out; throw std::runtime_error("private key couldn't be retrieved"); } return std::move(std::make_shared<Buffer>(out, size, size)); } BufferPtr ECDH::get_public_key() const { const EC_POINT *pub = EC_KEY_get0_public_key(key); if (pub == nullptr) throw std::runtime_error("Couldn't get public key"); size_t size; point_conversion_form_t form = EC_GROUP_get_point_conversion_form(group); size = EC_POINT_point2oct(group, pub, form, nullptr, 0, nullptr); if (size == 0) throw std::runtime_error("Couldn't get public key"); uint8_t *out = new uint8_t[size]; size_t r = EC_POINT_point2oct(group, pub, form, out, size, nullptr); if (r != size) { delete[] out; throw std::runtime_error("Couldn't get public key"); } return std::move(std::make_shared<Buffer>(out, size, size)); } bool ECDH::is_key_valid_for_curve(BIGNUM *private_key) { if (group == nullptr) throw std::runtime_error("group cannot be null"); if (private_key == nullptr) throw std::runtime_error("private key cannot be null"); if (BN_cmp(private_key, BN_value_one()) < 0) return false; BIGNUM *order = BN_new(); if (order == nullptr) throw std::runtime_error("something went wrong, order can't be null"); bool result = EC_GROUP_get_order(group, order, nullptr) && BN_cmp(private_key, order) < 0; BN_free(order); return result; } void ECDH::set_private_key_hex(const char *data) { BIGNUM *priv = BN_new(); BN_hex2bn(&priv, data); if (!is_key_valid_for_curve(priv)) throw std::runtime_error("invalid key for curve"); int result = EC_KEY_set_private_key(key, priv); BN_free(priv); if (!result) throw std::runtime_error("failed to convert BN to private key"); // To avoid inconsistency, clear the current public key in-case computing // the new one fails for some reason. EC_KEY_set_public_key(key, nullptr); const BIGNUM *priv_key = EC_KEY_get0_private_key(key); CHECK_NE(priv_key, nullptr); EC_POINT *pub = EC_POINT_new(group); CHECK_NE(pub, nullptr); if (!EC_POINT_mul(group, pub, priv_key, nullptr, nullptr, nullptr)) { EC_POINT_free(pub); throw std::runtime_error("Failed to generate ecdh public key"); } if (!EC_KEY_set_public_key(key, pub)) { EC_POINT_free(pub); return throw std::runtime_error("Failed to set generated public key"); } EC_POINT_free(pub); } BufferPtr ECDH::compute_secret(Buffer& public_key) const { EC_POINT *pub = EC_POINT_new(group); int r = EC_POINT_oct2point(group, pub, public_key.data(), public_key.size(), nullptr); if (!r || pub == nullptr) throw std::runtime_error("secret couldn't be computed with given key"); // NOTE: field_size is in bits int field_size = EC_GROUP_get_degree(group); size_t size = ((size_t)field_size + 7) / 8; uint8_t *out = new uint8_t[size]; r = ECDH_compute_key(out, size, pub, key, nullptr); EC_POINT_free(pub); if (!r) { delete[] out; throw std::runtime_error("secret couldn't be computed with given key"); } return std::move(std::make_shared<Buffer>(out, size, size)); } } // namespace dsa <commit_msg>improved typing<commit_after>#include "ecdh.h" #include <openssl/ecdh.h> #include <openssl/objects.h> template<typename T, typename U> inline void CHECK_NE(T a, U b) { if (a == b) throw std::runtime_error("Something went wrong, can't be equal."); } namespace dsa { ECDH::ECDH(const char *curve) { int nid = OBJ_sn2nid(curve); if (nid == NID_undef) throw std::runtime_error("invalid curve name"); key = EC_KEY_new_by_curve_name(nid); if (EC_KEY_generate_key(key) == 0) throw std::runtime_error("failed to generate ecdh key"); group = EC_KEY_get0_group(key); } ECDH::~ECDH() { EC_KEY_free(key); } BufferPtr ECDH::get_private_key() const { const BIGNUM *priv = EC_KEY_get0_private_key(key); if (priv == nullptr) throw std::runtime_error("private key not set"); int size = BN_num_bytes(priv); auto *out = new uint8_t[size]; if (size != BN_bn2bin(priv, out)) { delete[] out; throw std::runtime_error("private key couldn't be retrieved"); } return std::move(std::make_shared<Buffer>(out, size, size)); } BufferPtr ECDH::get_public_key() const { const EC_POINT *pub = EC_KEY_get0_public_key(key); if (pub == nullptr) throw std::runtime_error("Couldn't get public key"); size_t size; point_conversion_form_t form = EC_GROUP_get_point_conversion_form(group); size = EC_POINT_point2oct(group, pub, form, nullptr, 0, nullptr); if (size == 0) throw std::runtime_error("Couldn't get public key"); auto *out = new uint8_t[size]; size_t r = EC_POINT_point2oct(group, pub, form, out, size, nullptr); if (r != size) { delete[] out; throw std::runtime_error("Couldn't get public key"); } return std::move(std::make_shared<Buffer>(out, size, size)); } bool ECDH::is_key_valid_for_curve(BIGNUM *private_key) { if (group == nullptr) throw std::runtime_error("group cannot be null"); if (private_key == nullptr) throw std::runtime_error("private key cannot be null"); if (BN_cmp(private_key, BN_value_one()) < 0) return false; BIGNUM *order = BN_new(); if (order == nullptr) throw std::runtime_error("something went wrong, order can't be null"); bool result = (EC_GROUP_get_order(group, order, nullptr) == 0) && (BN_cmp(private_key, order) < 0); BN_free(order); return result; } void ECDH::set_private_key_hex(const char *data) { BIGNUM *priv = BN_new(); BN_hex2bn(&priv, data); if (!is_key_valid_for_curve(priv)) throw std::runtime_error("invalid key for curve"); int result = EC_KEY_set_private_key(key, priv); BN_free(priv); if (result == 0) throw std::runtime_error("failed to convert BN to private key"); // To avoid inconsistency, clear the current public key in-case computing // the new one fails for some reason. EC_KEY_set_public_key(key, nullptr); const BIGNUM *priv_key = EC_KEY_get0_private_key(key); CHECK_NE(priv_key, nullptr); EC_POINT *pub = EC_POINT_new(group); CHECK_NE(pub, nullptr); if (EC_POINT_mul(group, pub, priv_key, nullptr, nullptr, nullptr) == 0) { EC_POINT_free(pub); throw std::runtime_error("Failed to generate ecdh public key"); } if (EC_KEY_set_public_key(key, pub) == 0) { EC_POINT_free(pub); return throw std::runtime_error("Failed to set generated public key"); } EC_POINT_free(pub); } BufferPtr ECDH::compute_secret(Buffer &public_key) const { EC_POINT *pub = EC_POINT_new(group); int r = EC_POINT_oct2point(group, pub, public_key.data(), public_key.size(), nullptr); if ((r != 0) || pub == nullptr) throw std::runtime_error("secret couldn't be computed with given key"); // NOTE: field_size is in bits int field_size = EC_GROUP_get_degree(group); size_t size = ((size_t) field_size + 7) / 8; auto *out = new uint8_t[size]; r = ECDH_compute_key(out, size, pub, key, nullptr); EC_POINT_free(pub); if (r == 0) { delete[] out; throw std::runtime_error("secret couldn't be computed with given key"); } return std::move(std::make_shared<Buffer>(out, size, size)); } } // namespace dsa <|endoftext|>
<commit_before>/* * Anonymous pipe pooling, to speed to istream_pipe. * * author: Max Kellermann <mk@cm4all.com> */ #include "pipe_stock.hxx" #include "stock/Stock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "io/UniqueFileDescriptor.hxx" #include "gerrno.h" #include <assert.h> #include <unistd.h> #include <fcntl.h> struct PipeStockItem final : HeapStockItem { UniqueFileDescriptor fds[2]; explicit PipeStockItem(CreateStockItem c) :HeapStockItem(c) { } /* virtual methods from class StockItem */ bool Borrow(gcc_unused void *ctx) override; bool Release(gcc_unused void *ctx) override; }; /* * stock class * */ static void pipe_stock_create(gcc_unused void *ctx, CreateStockItem c, gcc_unused void *info, gcc_unused struct pool &caller_pool, gcc_unused CancellablePointer &cancel_ptr) { auto *item = new PipeStockItem(c); int ret = UniqueFileDescriptor::CreatePipeNonBlock(item->fds[0], item->fds[1]); if (ret < 0) { GError *error = new_error_errno_msg("pipe() failed"); item->InvokeCreateError(error); return; } item->InvokeCreateSuccess(); } bool PipeStockItem::Borrow(gcc_unused void *ctx) { assert(fds[0].IsValid()); assert(fds[1].IsValid()); return true; } bool PipeStockItem::Release(gcc_unused void *ctx) { assert(fds[0].IsValid()); assert(fds[1].IsValid()); return true; } static constexpr StockClass pipe_stock_class = { .create = pipe_stock_create, }; /* * interface * */ Stock * pipe_stock_new(EventLoop &event_loop) { return new Stock(event_loop, pipe_stock_class, nullptr, "pipe", 0, 64); } void pipe_stock_free(Stock *stock) { delete stock; } void pipe_stock_item_get(StockItem *_item, FileDescriptor fds[2]) { auto *item = (PipeStockItem *)_item; fds[0] = item->fds[0].ToFileDescriptor(); fds[1] = item->fds[1].ToFileDescriptor(); } <commit_msg>pipe_stock: UniqueFileDescriptor::CreatePipeNonBlock() returns bool<commit_after>/* * Anonymous pipe pooling, to speed to istream_pipe. * * author: Max Kellermann <mk@cm4all.com> */ #include "pipe_stock.hxx" #include "stock/Stock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "io/UniqueFileDescriptor.hxx" #include "gerrno.h" #include <assert.h> #include <unistd.h> #include <fcntl.h> struct PipeStockItem final : HeapStockItem { UniqueFileDescriptor fds[2]; explicit PipeStockItem(CreateStockItem c) :HeapStockItem(c) { } /* virtual methods from class StockItem */ bool Borrow(gcc_unused void *ctx) override; bool Release(gcc_unused void *ctx) override; }; /* * stock class * */ static void pipe_stock_create(gcc_unused void *ctx, CreateStockItem c, gcc_unused void *info, gcc_unused struct pool &caller_pool, gcc_unused CancellablePointer &cancel_ptr) { auto *item = new PipeStockItem(c); if (!UniqueFileDescriptor::CreatePipeNonBlock(item->fds[0], item->fds[1])) { GError *error = new_error_errno_msg("pipe() failed"); item->InvokeCreateError(error); return; } item->InvokeCreateSuccess(); } bool PipeStockItem::Borrow(gcc_unused void *ctx) { assert(fds[0].IsValid()); assert(fds[1].IsValid()); return true; } bool PipeStockItem::Release(gcc_unused void *ctx) { assert(fds[0].IsValid()); assert(fds[1].IsValid()); return true; } static constexpr StockClass pipe_stock_class = { .create = pipe_stock_create, }; /* * interface * */ Stock * pipe_stock_new(EventLoop &event_loop) { return new Stock(event_loop, pipe_stock_class, nullptr, "pipe", 0, 64); } void pipe_stock_free(Stock *stock) { delete stock; } void pipe_stock_item_get(StockItem *_item, FileDescriptor fds[2]) { auto *item = (PipeStockItem *)_item; fds[0] = item->fds[0].ToFileDescriptor(); fds[1] = item->fds[1].ToFileDescriptor(); } <|endoftext|>
<commit_before>#define UNICODE #include <windows.h> #include <ole2.h> #include <oaidl.h> #include <objbase.h> #include <AtlBase.h> #include <AtlConv.h> #include <iostream> #include <string> #include <vector> #include <stdlib.h> #include "dictationbridge-core/master/master.h" #pragma comment(lib, "ole32.lib") #pragma comment(lib, "oleacc.lib") #define ERR(x, msg) do { \ if(x != S_OK) {\ printf(msg "\n");\ printf("%x\n", res);\ exit(1);\ }\ } while(0) std::string wideToString(wchar_t const * text, unsigned int length) { auto tmp = new char[length*2+1]; auto resultingLen = WideCharToMultiByte(CP_UTF8, NULL, text, length, tmp, length*2, NULL, NULL); tmp[resultingLen] = '\0'; std::string ret(tmp); delete[] tmp; return ret; } std::string BSTRToString(BSTR text) { unsigned int len = SysStringLen(text); return wideToString(text, len); } DISPID id; DISPPARAMS params; VARIANTARG args[2]; IDispatch *jfw = nullptr; void initSpeak() { CLSID JFWClass; auto res = CLSIDFromProgID(L"FreedomSci.JawsApi", &JFWClass); ERR(res, "Couldn't get Jaws interface ID"); res = CoCreateInstance(JFWClass, NULL, CLSCTX_ALL, __uuidof(IDispatch), (void**)&jfw); ERR(res, "Couldn't create Jaws interface"); /* Setup to call jaws. IDL is: HRESULT SayString( [in] BSTR StringToSpeak, [in, optional, defaultvalue(-1)] VARIANT_BOOL bFlush, [out, retval] VARIANT_BOOL* vbSuccess); */ LPOLESTR name = L"SayString"; args[1].vt = VT_BSTR; args[0].vt = VT_BOOL; args[0].boolVal = 0; params.rgvarg = args; params.rgdispidNamedArgs = NULL; params.cArgs = 2; params.cNamedArgs = 0; res = jfw->GetIDsOfNames(IID_NULL, &name, 1, LOCALE_SYSTEM_DEFAULT, &id); ERR(res, "Couldn't get SayString"); } void speak(wchar_t const * text) { auto s = SysAllocString(text); args[1].bstrVal = s; jfw->Invoke(id, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &params, NULL, NULL, NULL); //Temporary, for debugging. auto tmp = BSTRToString(s); printf(&tmp[0]); printf("\n"); SysFreeString(s); } void WINAPI textCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) { speak(text); } void WINAPI textDeletedCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) { int len = wcslen(text); int neededLen = len + strlen("Deleted "); wchar_t* tmp = new wchar_t[neededLen+1]; wcscpy(tmp, L"Deleted "); int offset = strlen("Deleted "); for(int i = 0; i < len; i++) tmp[i+offset] = text[i]; tmp[neededLen] = 0; speak(tmp); delete[] tmp; } //These are string constants for the microphone status, as well as the status itself: //The pointer below is set to the last one we saw. const char* MICROPHONE_OFF = "Dragon's microphone is off;"; const char* MICROPHONE_ON = "Normal mode: You can dictate and use voice"; const char* MICROPHONE_SLEEPING = "The microphone is asleep;"; const char* microphoneState = nullptr; void announceMicrophoneState(const char* state) { if(state == MICROPHONE_ON) speak(L"Microphone on."); else if(state == MICROPHONE_OFF) speak(L"Microphone off."); else if(state == MICROPHONE_SLEEPING) speak(L"Microphone sleeping."); else speak(L"Microphone in unknown state."); } wchar_t processNameBuffer[1024] = {0}; void CALLBACK nameChanged(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) { //First, is it coming from natspeak.exe? DWORD procId; GetWindowThreadProcessId(hwnd, &procId); auto procHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procId); //We can't recover from this failing, so abort. if(procHandle == NULL) return; DWORD len = 1024; auto res = QueryFullProcessImageName(procHandle, 0, processNameBuffer, &len); CloseHandle(procHandle); if(res == 0) return; auto processName = wideToString(processNameBuffer, (unsigned int) len); if(processName.find("dragonbar.exe") == std::string::npos && processName.find("natspeak.exe") == std::string::npos) return; //Attempt to get the new text. IAccessible* acc = nullptr; VARIANT child; HRESULT hres = AccessibleObjectFromEvent(hwnd, idObject, idChild, &acc, &child); if(hres != S_OK || acc == nullptr) return; BSTR nameBSTR; hres = acc->get_accName(child, &nameBSTR); acc->Release(); if(hres != S_OK) return; auto name = BSTRToString(nameBSTR); SysFreeString(nameBSTR); const char* possibles[] = {MICROPHONE_ON, MICROPHONE_OFF, MICROPHONE_SLEEPING}; const char* newState = microphoneState; for(int i = 0; i < 3; i++) { if(name.find(possibles[i]) != std::string::npos) { newState = possibles[i]; break; } } if(newState != microphoneState) { announceMicrophoneState(newState); microphoneState = newState; } } int CALLBACK WinMain(_In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) { HRESULT res; res = OleInitialize(NULL); ERR(res, "Couldn't initialize OLE"); initSpeak(); auto started = DBMaster_Start(); if(!started) { printf("Couldn't start DictationBridge-core\n"); return 1; } DBMaster_SetTextInsertedCallback(textCallback); DBMaster_SetTextDeletedCallback(textDeletedCallback); if(SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, nameChanged, 0, 0, WINEVENT_OUTOFCONTEXT) == 0) { printf("Couldn't register to receive events\n"); return 1; } MSG msg; while(GetMessage(&msg, NULL, NULL, NULL) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } DBMaster_Stop(); OleUninitialize(); return 0; } <commit_msg>New line and new paragraph support.<commit_after>#define UNICODE #include <windows.h> #include <ole2.h> #include <oaidl.h> #include <objbase.h> #include <AtlBase.h> #include <AtlConv.h> #include <iostream> #include <string> #include <vector> #include <stdlib.h> #include "dictationbridge-core/master/master.h" #pragma comment(lib, "ole32.lib") #pragma comment(lib, "oleacc.lib") #define ERR(x, msg) do { \ if(x != S_OK) {\ printf(msg "\n");\ printf("%x\n", res);\ exit(1);\ }\ } while(0) std::string wideToString(wchar_t const * text, unsigned int length) { auto tmp = new char[length*2+1]; auto resultingLen = WideCharToMultiByte(CP_UTF8, NULL, text, length, tmp, length*2, NULL, NULL); tmp[resultingLen] = '\0'; std::string ret(tmp); delete[] tmp; return ret; } std::string BSTRToString(BSTR text) { unsigned int len = SysStringLen(text); return wideToString(text, len); } DISPID id; DISPPARAMS params; VARIANTARG args[2]; IDispatch *jfw = nullptr; void initSpeak() { CLSID JFWClass; auto res = CLSIDFromProgID(L"FreedomSci.JawsApi", &JFWClass); ERR(res, "Couldn't get Jaws interface ID"); res = CoCreateInstance(JFWClass, NULL, CLSCTX_ALL, __uuidof(IDispatch), (void**)&jfw); ERR(res, "Couldn't create Jaws interface"); /* Setup to call jaws. IDL is: HRESULT SayString( [in] BSTR StringToSpeak, [in, optional, defaultvalue(-1)] VARIANT_BOOL bFlush, [out, retval] VARIANT_BOOL* vbSuccess); */ LPOLESTR name = L"SayString"; args[1].vt = VT_BSTR; args[0].vt = VT_BOOL; args[0].boolVal = 0; params.rgvarg = args; params.rgdispidNamedArgs = NULL; params.cArgs = 2; params.cNamedArgs = 0; res = jfw->GetIDsOfNames(IID_NULL, &name, 1, LOCALE_SYSTEM_DEFAULT, &id); ERR(res, "Couldn't get SayString"); } void speak(wchar_t const * text) { auto s = SysAllocString(text); args[1].bstrVal = s; jfw->Invoke(id, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &params, NULL, NULL, NULL); //Temporary, for debugging. auto tmp = BSTRToString(s); printf(&tmp[0]); printf("\n"); SysFreeString(s); } void WINAPI textCallback(HWND hwnd, DWORD startPosition, LPCWSTR textUnprocessed) { //We need to replace \r with nothing. int len = wcslen(textUnprocessed); wchar_t* text = new wchar_t[len+1]; int copied = 0; for(int i = 0; i < len; i++) { if(textUnprocessed[i] != L'\r') { text[copied] = textUnprocessed[i]; copied += 1; } } text[copied+1] = 0; if(wcscmp(text, L"\n\n") == 0 || wcscmp(text, L"") == 0 //new paragraph in word. ) { speak(L"New paragraph."); } else if(wcscmp(text, L"\n") == 0) { speak(L"New line."); } else { speak(text); } } void WINAPI textDeletedCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) { int len = wcslen(text); int neededLen = len + strlen("Deleted "); wchar_t* tmp = new wchar_t[neededLen+1]; wcscpy(tmp, L"Deleted "); int offset = strlen("Deleted "); for(int i = 0; i < len; i++) tmp[i+offset] = text[i]; tmp[neededLen] = 0; speak(tmp); delete[] tmp; } //These are string constants for the microphone status, as well as the status itself: //The pointer below is set to the last one we saw. const char* MICROPHONE_OFF = "Dragon's microphone is off;"; const char* MICROPHONE_ON = "Normal mode: You can dictate and use voice"; const char* MICROPHONE_SLEEPING = "The microphone is asleep;"; const char* microphoneState = nullptr; void announceMicrophoneState(const char* state) { if(state == MICROPHONE_ON) speak(L"Microphone on."); else if(state == MICROPHONE_OFF) speak(L"Microphone off."); else if(state == MICROPHONE_SLEEPING) speak(L"Microphone sleeping."); else speak(L"Microphone in unknown state."); } wchar_t processNameBuffer[1024] = {0}; void CALLBACK nameChanged(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) { //First, is it coming from natspeak.exe? DWORD procId; GetWindowThreadProcessId(hwnd, &procId); auto procHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procId); //We can't recover from this failing, so abort. if(procHandle == NULL) return; DWORD len = 1024; auto res = QueryFullProcessImageName(procHandle, 0, processNameBuffer, &len); CloseHandle(procHandle); if(res == 0) return; auto processName = wideToString(processNameBuffer, (unsigned int) len); if(processName.find("dragonbar.exe") == std::string::npos && processName.find("natspeak.exe") == std::string::npos) return; //Attempt to get the new text. IAccessible* acc = nullptr; VARIANT child; HRESULT hres = AccessibleObjectFromEvent(hwnd, idObject, idChild, &acc, &child); if(hres != S_OK || acc == nullptr) return; BSTR nameBSTR; hres = acc->get_accName(child, &nameBSTR); acc->Release(); if(hres != S_OK) return; auto name = BSTRToString(nameBSTR); SysFreeString(nameBSTR); const char* possibles[] = {MICROPHONE_ON, MICROPHONE_OFF, MICROPHONE_SLEEPING}; const char* newState = microphoneState; for(int i = 0; i < 3; i++) { if(name.find(possibles[i]) != std::string::npos) { newState = possibles[i]; break; } } if(newState != microphoneState) { announceMicrophoneState(newState); microphoneState = newState; } } int CALLBACK WinMain(_In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) { HRESULT res; res = OleInitialize(NULL); ERR(res, "Couldn't initialize OLE"); initSpeak(); auto started = DBMaster_Start(); if(!started) { printf("Couldn't start DictationBridge-core\n"); return 1; } DBMaster_SetTextInsertedCallback(textCallback); DBMaster_SetTextDeletedCallback(textDeletedCallback); if(SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, nameChanged, 0, 0, WINEVENT_OUTOFCONTEXT) == 0) { printf("Couldn't register to receive events\n"); return 1; } MSG msg; while(GetMessage(&msg, NULL, NULL, NULL) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } DBMaster_Stop(); OleUninitialize(); return 0; } <|endoftext|>
<commit_before>#include <bits/stdc++.h> using namespace std; int main() { int a,b,c; scanf("%d %d %d",&a,&b,&c); printf("%d\n",(max(abs(b-c),abs(a-b))-1)); return 0; } <commit_msg>Update Skocimis.cpp<commit_after>#include <bits/stdc++.h> using namespace std; int main() { int a,b,c; scanf("%d %d %d",&a,&b,&c); printf("%d\n",(max(abs(b-c),abs(a-b))-1)); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <sstream> #include <chrono> namespace wrp { #if !defined(WRP_PRODUCT_NAME) #define WRP_PRODUCT_NAME "UNKNOWN PRODUCT" #endif class log{ private: const decltype(std::chrono::system_clock::now()) start; const std::string object_name; const void* object_address; static int nesting_counter; public: typedef std::chrono::duration<double> unit; std::stringstream buffer; explicit log(const std::string object_name_ = "", const void* object_address_ = 0) : start(std::chrono::system_clock::now()) , object_name(object_name_) , object_address(object_address_) { ++nesting_counter; } ~log(){ using std::chrono::duration_cast; auto end = std::chrono::system_clock::now(); std::string indent; for(auto n = nesting_counter; n; --n) indent += " "; std::cout << indent << "[" WRP_PRODUCT_NAME "] " << object_name << " " << object_address << "\n" << indent << "start: " << duration_cast<unit>(start.time_since_epoch()).count() << "\n" << indent << "end : " << duration_cast<unit>(end.time_since_epoch()).count() << "\n" << indent << "dt : " << duration_cast<unit>((end - start)).count() << "\n" ; std::string b; while(std::getline(buffer, b)) std::cout << indent << b << "\n"; std::cout << std::flush; --nesting_counter; } auto operator<<(const bool v) -> decltype(buffer<<v) { return buffer << v; } auto operator<<(const char* v) -> decltype(buffer<<v) { return buffer << v; } auto operator<<(std::string& v) -> decltype(buffer<<v) { return buffer << v; } auto operator<<(int& v) -> decltype(buffer<<v){ return buffer << v; } }; int log::nesting_counter = -1; } <commit_msg>ネストが生じた際のログ出力がニンゲンフレンドリーじゃない気がしたので修正<commit_after>#include <iostream> #include <string> #include <sstream> #include <chrono> #include <boost/range/algorithm.hpp> namespace wrp { #if !defined(WRP_PRODUCT_NAME) #define WRP_PRODUCT_NAME "UNKNOWN PRODUCT" #endif class log{ private: const decltype(std::chrono::system_clock::now()) start; const std::string object_name; const void* object_address; std::string indent; static int nesting_counter; public: typedef std::chrono::duration<double> unit; std::stringstream buffer; explicit log(const std::string object_name_ = "", const void* object_address_ = 0) : start(std::chrono::system_clock::now()) , object_name(object_name_) , object_address(object_address_) { ++nesting_counter; indent.resize(2 * nesting_counter); boost::fill(indent, ' '); std::cout << indent << "[" WRP_PRODUCT_NAME "] " << object_name << " " << object_address << "\n" << indent << "start: " << std::chrono::duration_cast<unit>(start.time_since_epoch()).count() << std::endl ; } ~log(){ auto end = std::chrono::system_clock::now(); std::string b; while(std::getline(buffer, b)) std::cout << indent << b << "\n"; std::cout << indent << "end : " << std::chrono::duration_cast<unit>(end.time_since_epoch()).count() << "\n" << indent << "dt : " << std::chrono::duration_cast<unit>((end - start)).count() << std::endl ; --nesting_counter; } auto operator<<(const bool v) -> decltype(buffer<<v) { return buffer << v; } auto operator<<(const char* v) -> decltype(buffer<<v) { return buffer << v; } auto operator<<(std::string& v) -> decltype(buffer<<v) { return buffer << v; } auto operator<<(int& v) -> decltype(buffer<<v){ return buffer << v; } }; int log::nesting_counter = -1; } <|endoftext|>
<commit_before>/*********************************************************************************************************************** * MainView.cpp * * Created on: Jan 10, 2011 * Author: Dimitar Asenov **********************************************************************************************************************/ #include "views/MainView.h" #include "Scene.h" #include "Core/headers/global.h" #include <QtGui/QWheelEvent> #include <QtGui/QPrinter> #include <QtSvg/QSvgGenerator> namespace Visualization { MainView::MainView(Scene *scene) : View(scene, NULL), miniMap(new MiniMap(scene, this)), scaleLevel(SCALING_FACTOR) { setRenderHint(QPainter::Antialiasing); setRenderHint(QPainter::TextAntialiasing); setTransformationAnchor(QGraphicsView::AnchorUnderMouse); setMiniMapSize(MINIMAP_DEFAULT_WIDTH, MINIMAP_DEFAULT_HEIGHT); } MainView::~MainView() { SAFE_DELETE(miniMap); } void MainView::setMiniMapSize(int width, int height) { if ( miniMap ) { miniMap->resize(width, height); miniMap->sceneRectChanged(scene()->sceneRect()); } } bool MainView::event( QEvent *event ) { switch (event->type()) { case QEvent::KeyPress : { QKeyEvent *k = (QKeyEvent *)event; keyPressEvent(k); if (k->key() == Qt::Key_Backtab || k->key() == Qt::Key_Tab ) event->accept(); return true; } break; case QEvent::KeyRelease : { QKeyEvent *k = (QKeyEvent *)event; keyReleaseEvent(k); if (k->key() == Qt::Key_Backtab || k->key() == Qt::Key_Tab ) event->accept(); return true; } break; default: return View::event( event ); } } void MainView::resizeEvent(QResizeEvent *event) { View::resizeEvent(event); if ( miniMap ) { miniMap->updatePosition(); miniMap->visibleRectChanged(); } } void MainView::wheelEvent(QWheelEvent *event) { if ( event->delta() > 0 ) scaleLevel--; else scaleLevel++; if ( scaleLevel <= 0 ) scaleLevel = 1; qreal scaleFactor = SCALING_FACTOR / (qreal) scaleLevel; setTransform(QTransform::fromScale(scaleFactor, scaleFactor)); if ( miniMap ) miniMap->visibleRectChanged(); } void MainView::scrollContentsBy(int dx, int dy) { View::scrollContentsBy(dx, dy); if ( miniMap ) miniMap->visibleRectChanged(); } void MainView::keyPressEvent(QKeyEvent *event) { if ( (event->modifiers() & Qt::ControlModifier || event->modifiers() & Qt::ShiftModifier) && event->key() == Qt::Key_Print) { event->accept(); QPrinter printer; printer.setOutputFormat(QPrinter::PdfFormat); printer.setFullPage(true); printer.setResolution(300); QSvgGenerator svggen; svggen.setResolution(90); if (event->modifiers() & Qt::ShiftModifier) { // Print scene printer.setOutputFileName("screenshot-scene.pdf"); printer.setPaperSize(QSize(scene()->sceneRect().width(), scene()->sceneRect().height()), QPrinter::Point); QPainter painter(&printer); scene()->render( &painter ); svggen.setFileName("screenshot-scene.svg"); svggen.setSize(QSize(scene()->sceneRect().width(), scene()->sceneRect().height())); QPainter svgPainter(&svggen); scene()->render(&svgPainter); } else { // Print view printer.setOutputFileName("screenshot-view.pdf"); printer.setPaperSize(QSize(viewport()->rect().width(), viewport()->rect().height()), QPrinter::Point); QPainter painter(&printer); render(&painter); svggen.setFileName("screenshot-view.svg"); svggen.setSize(QSize(viewport()->rect().width(), viewport()->rect().height())); QPainter svgPainter(&svggen); render(&svgPainter); } } else View::keyPressEvent(event); } } <commit_msg>NEW: Added screenshot in png format.<commit_after>/*********************************************************************************************************************** * MainView.cpp * * Created on: Jan 10, 2011 * Author: Dimitar Asenov **********************************************************************************************************************/ #include "views/MainView.h" #include "Scene.h" #include "Core/headers/global.h" #include <QtGui/QWheelEvent> #include <QtGui/QPrinter> #include <QtSvg/QSvgGenerator> namespace Visualization { MainView::MainView(Scene *scene) : View(scene, NULL), miniMap(new MiniMap(scene, this)), scaleLevel(SCALING_FACTOR) { setRenderHint(QPainter::Antialiasing); setRenderHint(QPainter::TextAntialiasing); setTransformationAnchor(QGraphicsView::AnchorUnderMouse); setMiniMapSize(MINIMAP_DEFAULT_WIDTH, MINIMAP_DEFAULT_HEIGHT); } MainView::~MainView() { SAFE_DELETE(miniMap); } void MainView::setMiniMapSize(int width, int height) { if ( miniMap ) { miniMap->resize(width, height); miniMap->sceneRectChanged(scene()->sceneRect()); } } bool MainView::event( QEvent *event ) { switch (event->type()) { case QEvent::KeyPress : { QKeyEvent *k = (QKeyEvent *)event; keyPressEvent(k); if (k->key() == Qt::Key_Backtab || k->key() == Qt::Key_Tab ) event->accept(); return true; } break; case QEvent::KeyRelease : { QKeyEvent *k = (QKeyEvent *)event; keyReleaseEvent(k); if (k->key() == Qt::Key_Backtab || k->key() == Qt::Key_Tab ) event->accept(); return true; } break; default: return View::event( event ); } } void MainView::resizeEvent(QResizeEvent *event) { View::resizeEvent(event); if ( miniMap ) { miniMap->updatePosition(); miniMap->visibleRectChanged(); } } void MainView::wheelEvent(QWheelEvent *event) { if ( event->delta() > 0 ) scaleLevel--; else scaleLevel++; if ( scaleLevel <= 0 ) scaleLevel = 1; qreal scaleFactor = SCALING_FACTOR / (qreal) scaleLevel; setTransform(QTransform::fromScale(scaleFactor, scaleFactor)); if ( miniMap ) miniMap->visibleRectChanged(); } void MainView::scrollContentsBy(int dx, int dy) { View::scrollContentsBy(dx, dy); if ( miniMap ) miniMap->visibleRectChanged(); } void MainView::keyPressEvent(QKeyEvent *event) { if ( (event->modifiers() & Qt::ControlModifier || event->modifiers() & Qt::ShiftModifier) && event->key() == Qt::Key_Print) { event->accept(); QPrinter printer; printer.setOutputFormat(QPrinter::PdfFormat); printer.setFullPage(true); printer.setResolution(300); QSvgGenerator svggen; svggen.setResolution(90); if (event->modifiers() & Qt::ShiftModifier) { // Print scene printer.setOutputFileName("screenshot-scene.pdf"); printer.setPaperSize(scene()->sceneRect().size().toSize(), QPrinter::Point); QPainter painter(&printer); painter.setRenderHint(QPainter::Antialiasing); scene()->render( &painter ); svggen.setFileName("screenshot-scene.svg"); svggen.setSize(scene()->sceneRect().size().toSize()); QPainter svgPainter(&svggen); svgPainter.setRenderHint(QPainter::Antialiasing); scene()->render(&svgPainter); QImage image(2 * scene()->sceneRect().size().toSize(), QImage::Format_ARGB32_Premultiplied); QPainter pmapPainter(&image); pmapPainter.setRenderHint(QPainter::Antialiasing); //pmapPainter.scale(2,2); scene()->render(&pmapPainter); image.save("screenshot-scene.png"); } else { // Print view printer.setOutputFileName("screenshot-view.pdf"); printer.setPaperSize(viewport()->rect().size(), QPrinter::Point); QPainter painter(&printer); painter.setRenderHint(QPainter::Antialiasing); render(&painter); svggen.setFileName("screenshot-view.svg"); svggen.setSize(viewport()->rect().size()); QPainter svgPainter(&svggen); svgPainter.setRenderHint(QPainter::Antialiasing); render(&svgPainter); QImage image(2 * viewport()->rect().size(), QImage::Format_ARGB32_Premultiplied); QPainter pmapPainter(&image); pmapPainter.setRenderHint(QPainter::Antialiasing); render(&pmapPainter); image.save("screenshot-view.png"); } } else View::keyPressEvent(event); } } <|endoftext|>
<commit_before>/* * Copyright 2017, Andrej Kislovskij * * This is PUBLIC DOMAIN software so use at your own risk as it comes * with no warranties. This code is yours to share, use and modify without * any restrictions or obligations. * * For more information see conwrap/LICENSE or refer refer to http://unlicense.org * * Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij) */ #pragma once #include <atomic> #include <conwrap/ProcessorProxy.hpp> #include <functional> #include <memory> #include <thread> #include "slim/ContainerBase.hpp" #include "slim/log/log.hpp" namespace slim { template <class ProducerType, class ConsumerType> class Scheduler { public: Scheduler(std::unique_ptr<ProducerType> pr, std::unique_ptr<ConsumerType> cn) : producerPtr{std::move(pr)} , consumerPtr{std::move(cn)} , monitorThread {[&]{ // starting a single consumer thread for processing PCM data LOG(DEBUG) << LABELS{"slim"} << "Scheduler monitor thread was started (id=" << std::this_thread::get_id() << ")"; while (!monitorFinish) { std::this_thread::sleep_for(std::chrono::milliseconds{100}); if (requestTaskLater) { requestTaskLater = false; processorProxyPtr->process([&] { processTask(); }); } } LOG(DEBUG) << LABELS{"slim"} << "Scheduler monitor thread was stopped (id=" << std::this_thread::get_id() << ")"; }} { LOG(DEBUG) << LABELS{"slim"} << "Scheduler object was created (id=" << this << ")"; } // using Rule Of Zero ~Scheduler() { // signalling monitor thread to stop and joining it monitorFinish = true; if (monitorThread.joinable()) { monitorThread.join(); } LOG(DEBUG) << LABELS{"slim"} << "Scheduler object was deleted (id=" << this << ")"; } Scheduler(const Scheduler&) = delete; // non-copyable Scheduler& operator=(const Scheduler&) = delete; // non-assignable Scheduler(Scheduler&& rhs) = delete; // non-movable Scheduler& operator=(Scheduler&& rhs) = delete; // non-move-assignable void setProcessorProxy(conwrap::ProcessorProxy<ContainerBase>* p) { processorProxyPtr = p; producerPtr->setProcessorProxy(p); consumerPtr->setProcessorProxy(p); } void start() { producerPtr->start(); consumerPtr->start(); // asking monitor thread to submit a new task requestTaskLater = true; LOG(DEBUG) << LABELS{"slim"} << "Streaming was started"; } void stop(bool gracefully = true) { producerPtr->stop(); consumerPtr->stop(); LOG(DEBUG) << LABELS{"slim"} << "Streaming was stopped"; } protected: void processTask() { bool available; // TODO: calculate total chunks per processing quantum // processing up to max(count) chunks within one event-loop quantum for (unsigned int count{0}; (available = producerPtr->produceChunk(*consumerPtr)) && count < 5; count++) {} // if there is more PCM data to be processed if (available) { processorProxyPtr->process([&] { processTask(); }); } else if (producerPtr->isRunning()) { // requesting monitoring thread to submit a new task later, which will allow event-loop to progress requestTaskLater = true; } } private: std::unique_ptr<ProducerType> producerPtr; std::unique_ptr<ConsumerType> consumerPtr; std::thread monitorThread; std::atomic<bool> monitorFinish{false}; std::atomic<bool> requestTaskLater{false}; conwrap::ProcessorProxy<ContainerBase>* processorProxyPtr{nullptr}; }; } <commit_msg>Using a safer approach<commit_after>/* * Copyright 2017, Andrej Kislovskij * * This is PUBLIC DOMAIN software so use at your own risk as it comes * with no warranties. This code is yours to share, use and modify without * any restrictions or obligations. * * For more information see conwrap/LICENSE or refer refer to http://unlicense.org * * Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij) */ #pragma once #include <atomic> #include <conwrap/ProcessorProxy.hpp> #include <functional> #include <memory> #include <thread> #include "slim/Consumer.hpp" #include "slim/ContainerBase.hpp" #include "slim/log/log.hpp" #include "slim/Producer.hpp" namespace slim { class Scheduler { public: Scheduler(std::unique_ptr<Producer> pr, std::unique_ptr<Consumer> cn) : producerPtr{std::move(pr)} , consumerPtr{std::move(cn)} { LOG(DEBUG) << LABELS{"slim"} << "Scheduler object was created (id=" << this << ")"; } // using Rule Of Zero ~Scheduler() { LOG(DEBUG) << LABELS{"slim"} << "Scheduler object was deleted (id=" << this << ")"; } Scheduler(const Scheduler&) = delete; // non-copyable Scheduler& operator=(const Scheduler&) = delete; // non-assignable Scheduler(Scheduler&& rhs) = delete; // non-movable Scheduler& operator=(Scheduler&& rhs) = delete; // non-move-assignable void setProcessorProxy(conwrap::ProcessorProxy<ContainerBase>* p) { processorProxyPtr = p; producerPtr->setProcessorProxy(p); consumerPtr->setProcessorProxy(p); } void start() { producerPtr->start(); consumerPtr->start(); // starting scheduler monitor thread monitorThread = [&] { LOG(DEBUG) << LABELS{"slim"} << "Scheduler monitor thread was started (id=" << std::this_thread::get_id() << ")"; while (!monitorFinish) { std::this_thread::sleep_for(std::chrono::milliseconds{100}); if (requestTaskLater) { requestTaskLater = false; processorProxyPtr->process([&] { processTask(); }); } } LOG(DEBUG) << LABELS{"slim"} << "Scheduler monitor thread was stopped (id=" << std::this_thread::get_id() << ")"; }; // asking monitor thread to submit a new task requestTaskLater = true; LOG(DEBUG) << LABELS{"slim"} << "Streaming was started"; } void stop(bool gracefully = true) { producerPtr->stop(); consumerPtr->stop(); // signalling monitor thread to stop and joining it monitorFinish = true; if (monitorThread.joinable()) { monitorThread.join(); } LOG(DEBUG) << LABELS{"slim"} << "Streaming was stopped"; } protected: void processTask() { bool available; // TODO: calculate total chunks per processing quantum // processing up to max(count) chunks within one event-loop quantum for (unsigned int count{0}; (available = producerPtr->produceChunk(*consumerPtr)) && count < 5; count++) {} // if there is more PCM data to be processed if (available) { processorProxyPtr->process([&] { processTask(); }); } else if (producerPtr->isRunning()) { // requesting monitoring thread to submit a new task later, which will allow event-loop to progress requestTaskLater = true; } } private: std::unique_ptr<Producer> producerPtr; std::unique_ptr<Consumer> consumerPtr; std::thread monitorThread; std::atomic<bool> monitorFinish{false}; std::atomic<bool> requestTaskLater{false}; conwrap::ProcessorProxy<ContainerBase>* processorProxyPtr{nullptr}; }; } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2010-2011 Razor team * Authors: * Alexander Sokoloff <sokoloff.a@gmail.com> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "xdgdirs.h" #include <stdlib.h> #include <QDir> #include <QDebug> static const QString userDirectoryString[8] = { "Desktop", "Download", "Templates", "Publicshare", "Documents", "Music", "Pictures", "Videos" }; // Helper functions prototypes void fixBashShortcuts(QString &s); QString xdgSingleDir(const QString &envVar, const QString &def, bool createDir); QStringList xdgDirList(const QString &envVar, const QString &postfix); /************************************************ Helper func. ************************************************/ void fixBashShortcuts(QString &s) { if (s.startsWith('~')) s = QString(getenv("HOME")) + (s).mid(1); } /************************************************ Helper func. ************************************************/ QString xdgSingleDir(const QString &envVar, const QString &def, bool createDir) { #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QString s(getenv(envVar.toAscii())); #else QString s(getenv(envVar.toLatin1())); #endif if (!s.isEmpty()) fixBashShortcuts(s); else s = QString("%1/%2").arg(getenv("HOME"), def); QDir d(s); if (createDir && !d.exists()) { if (!d.mkpath(".")) qWarning() << QString("Can't create %1 directory.").arg(d.absolutePath()); } return d.absolutePath(); } /************************************************ Helper func. ************************************************/ QStringList xdgDirList(const QString &envVar, const QString &postfix) { #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QStringList dirs = QString(getenv(envVar.toAscii())).split(':', QString::SkipEmptyParts); #else QStringList dirs = QString(getenv(envVar.toLatin1())).split(':', QString::SkipEmptyParts); #endif for (QStringList::Iterator i=dirs.begin(); i!=dirs.end(); ++i) { fixBashShortcuts((*i)); if (!(*i).isEmpty()) { if (!(*i).endsWith(QLatin1Char('/'))) *i += "/"; *i += postfix; } } return dirs; } /************************************************ ************************************************/ QString XdgDirs::userDir(XdgDirs::UserDirectory dir) { // possible values for UserDirectory if (dir < 0 || dir > 7) return QString(); QString folderName = userDirectoryString[dir]; QString fallback; if (getenv("HOME") == NULL) return QString("/tmp"); else if (dir == XdgDirs::Desktop) fallback = QString("%1/%2").arg(getenv("HOME")).arg("Desktop"); else fallback = QString(getenv("HOME")); QString configDir(configHome()); QFile configFile(configDir + "/user-dirs.dirs"); if (!configFile.exists()) return fallback; if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) return fallback; QString userDirVar("XDG_" + folderName.toUpper() + "_DIR"); QTextStream in(&configFile); QString line; while (!in.atEnd()) { line = in.readLine(); if (line.contains(userDirVar)) { configFile.close(); // get path between quotes line = line.section('"', 1, 1); line.replace("$HOME", "~"); fixBashShortcuts(line); return line; } } configFile.close(); return fallback; } /************************************************ ************************************************/ bool XdgDirs::setUserDir(XdgDirs::UserDirectory dir, const QString& value, bool createDir) { // possible values for UserDirectory if (dir < 0 || dir > 7) return false; if (!(value.startsWith("$HOME") || value.startsWith("~/") || value.startsWith(QString(getenv("HOME"))))) return false; QString folderName = userDirectoryString[dir]; QString configDir(configHome()); QFile configFile(configDir + "/user-dirs.dirs"); // create the file if doesn't exist and opens it if (!configFile.open(QIODevice::ReadWrite | QIODevice::Text)) return false; QTextStream stream(&configFile); QVector<QString> lines; QString line; bool foundVar = false; while (!stream.atEnd()) { line = stream.readLine(); if (line.indexOf("XDG_" + folderName.toUpper() + "_DIR") == 0) { foundVar = true; QString path = line.section('"', 1, 1); line.replace(path, value); lines.append(line); } else if (line.indexOf("XDG_") == 0) { lines.append(line); } } stream.reset(); configFile.resize(0); if (!foundVar) stream << QString("XDG_%1_DIR=\"%2\"\n").arg(folderName.toUpper()).arg(value); for (QVector<QString>::iterator i = lines.begin(); i != lines.end(); ++i) stream << *i << "\n"; configFile.close(); if (createDir) { QString path = QString(value).replace("$HOME", "~"); fixBashShortcuts(path); QDir().mkpath(path); } return true; } /************************************************ ************************************************/ QString XdgDirs::dataHome(bool createDir) { return xdgSingleDir("XDG_DATA_HOME", ".local/share", createDir); } /************************************************ ************************************************/ QString XdgDirs::configHome(bool createDir) { return xdgSingleDir("XDG_CONFIG_HOME", ".config", createDir); } /************************************************ ************************************************/ QStringList XdgDirs::dataDirs(const QString &postfix) { QStringList dirs = xdgDirList("XDG_DATA_DIRS", postfix); if (dirs.isEmpty()) { dirs << "/usr/local/share/" + postfix; dirs << "/usr/share/" + postfix; } return dirs; } /************************************************ ************************************************/ QStringList XdgDirs::configDirs(const QString &postfix) { QStringList dirs = xdgDirList("XDG_CONFIG_DIRS", postfix); if (dirs.isEmpty()) { dirs << "/etc/xdg" << postfix; } return dirs; } /************************************************ ************************************************/ QString XdgDirs::cacheHome(bool createDir) { return xdgSingleDir("XDG_CACHE_HOME", ".cache", createDir); } /************************************************ ************************************************/ QString XdgDirs::runtimeDir() { QString result(getenv("XDG_RUNTIME_DIR")); fixBashShortcuts(result); return result; } /************************************************ ************************************************/ QString XdgDirs::autostartHome(bool createDir) { QDir dir(QString("%1/autostart").arg(configHome(createDir))); if (createDir && !dir.exists()) { if (!dir.mkpath(".")) qWarning() << QString("Can't create %1 directory.").arg(dir.absolutePath()); } return dir.absolutePath(); } /************************************************ ************************************************/ QStringList XdgDirs::autostartDirs(const QString &postfix) { QStringList dirs; foreach(QString dir, configDirs()) dirs << QString("%1/autostart").arg(dir) + postfix; return dirs; } <commit_msg>Fix XdgDirs::dataDirs() postfix handling<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2010-2011 Razor team * Authors: * Alexander Sokoloff <sokoloff.a@gmail.com> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "xdgdirs.h" #include <stdlib.h> #include <QDir> #include <QStringBuilder> // for the % operator #include <QDebug> static const QString userDirectoryString[8] = { "Desktop", "Download", "Templates", "Publicshare", "Documents", "Music", "Pictures", "Videos" }; // Helper functions prototypes void fixBashShortcuts(QString &s); QString xdgSingleDir(const QString &envVar, const QString &def, bool createDir); QStringList xdgDirList(const QString &envVar, const QString &postfix); /************************************************ Helper func. ************************************************/ void fixBashShortcuts(QString &s) { if (s.startsWith('~')) s = QString(getenv("HOME")) + (s).mid(1); } /************************************************ Helper func. ************************************************/ QString xdgSingleDir(const QString &envVar, const QString &def, bool createDir) { #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QString s(getenv(envVar.toAscii())); #else QString s(getenv(envVar.toLatin1())); #endif if (!s.isEmpty()) fixBashShortcuts(s); else s = QString("%1/%2").arg(getenv("HOME"), def); QDir d(s); if (createDir && !d.exists()) { if (!d.mkpath(".")) qWarning() << QString("Can't create %1 directory.").arg(d.absolutePath()); } return d.absolutePath(); } /************************************************ Helper func. ************************************************/ QStringList xdgDirList(const QString &envVar, const QString &postfix) { #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QStringList dirs = QString(getenv(envVar.toAscii())).split(':', QString::SkipEmptyParts); #else QStringList dirs = QString(getenv(envVar.toLatin1())).split(':', QString::SkipEmptyParts); #endif for (QStringList::Iterator i=dirs.begin(); i!=dirs.end(); ++i) { fixBashShortcuts((*i)); if (!(*i).isEmpty()) { if (!(*i).endsWith(QLatin1Char('/'))) *i += "/"; *i += postfix; } } return dirs; } /************************************************ ************************************************/ QString XdgDirs::userDir(XdgDirs::UserDirectory dir) { // possible values for UserDirectory if (dir < 0 || dir > 7) return QString(); QString folderName = userDirectoryString[dir]; QString fallback; if (getenv("HOME") == NULL) return QString("/tmp"); else if (dir == XdgDirs::Desktop) fallback = QString("%1/%2").arg(getenv("HOME")).arg("Desktop"); else fallback = QString(getenv("HOME")); QString configDir(configHome()); QFile configFile(configDir + "/user-dirs.dirs"); if (!configFile.exists()) return fallback; if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) return fallback; QString userDirVar("XDG_" + folderName.toUpper() + "_DIR"); QTextStream in(&configFile); QString line; while (!in.atEnd()) { line = in.readLine(); if (line.contains(userDirVar)) { configFile.close(); // get path between quotes line = line.section('"', 1, 1); line.replace("$HOME", "~"); fixBashShortcuts(line); return line; } } configFile.close(); return fallback; } /************************************************ ************************************************/ bool XdgDirs::setUserDir(XdgDirs::UserDirectory dir, const QString& value, bool createDir) { // possible values for UserDirectory if (dir < 0 || dir > 7) return false; if (!(value.startsWith("$HOME") || value.startsWith("~/") || value.startsWith(QString(getenv("HOME"))))) return false; QString folderName = userDirectoryString[dir]; QString configDir(configHome()); QFile configFile(configDir + "/user-dirs.dirs"); // create the file if doesn't exist and opens it if (!configFile.open(QIODevice::ReadWrite | QIODevice::Text)) return false; QTextStream stream(&configFile); QVector<QString> lines; QString line; bool foundVar = false; while (!stream.atEnd()) { line = stream.readLine(); if (line.indexOf("XDG_" + folderName.toUpper() + "_DIR") == 0) { foundVar = true; QString path = line.section('"', 1, 1); line.replace(path, value); lines.append(line); } else if (line.indexOf("XDG_") == 0) { lines.append(line); } } stream.reset(); configFile.resize(0); if (!foundVar) stream << QString("XDG_%1_DIR=\"%2\"\n").arg(folderName.toUpper()).arg(value); for (QVector<QString>::iterator i = lines.begin(); i != lines.end(); ++i) stream << *i << "\n"; configFile.close(); if (createDir) { QString path = QString(value).replace("$HOME", "~"); fixBashShortcuts(path); QDir().mkpath(path); } return true; } /************************************************ ************************************************/ QString XdgDirs::dataHome(bool createDir) { return xdgSingleDir("XDG_DATA_HOME", ".local/share", createDir); } /************************************************ ************************************************/ QString XdgDirs::configHome(bool createDir) { return xdgSingleDir("XDG_CONFIG_HOME", ".config", createDir); } /************************************************ ************************************************/ QStringList XdgDirs::dataDirs(const QString &postfix) { QStringList dirs = xdgDirList("XDG_DATA_DIRS", postfix); if (dirs.isEmpty()) { dirs << "/usr/local/share/" + postfix; dirs << "/usr/share/" + postfix; } return dirs; } /************************************************ ************************************************/ QStringList XdgDirs::configDirs(const QString &postfix) { QStringList dirs = xdgDirList("XDG_CONFIG_DIRS", postfix); if (dirs.isEmpty()) { dirs << QLatin1String("/etc/xdg") % postfix; } return dirs; } /************************************************ ************************************************/ QString XdgDirs::cacheHome(bool createDir) { return xdgSingleDir("XDG_CACHE_HOME", ".cache", createDir); } /************************************************ ************************************************/ QString XdgDirs::runtimeDir() { QString result(getenv("XDG_RUNTIME_DIR")); fixBashShortcuts(result); return result; } /************************************************ ************************************************/ QString XdgDirs::autostartHome(bool createDir) { QDir dir(QString("%1/autostart").arg(configHome(createDir))); if (createDir && !dir.exists()) { if (!dir.mkpath(".")) qWarning() << QString("Can't create %1 directory.").arg(dir.absolutePath()); } return dir.absolutePath(); } /************************************************ ************************************************/ QStringList XdgDirs::autostartDirs(const QString &postfix) { QStringList dirs; foreach(QString dir, configDirs()) dirs << QString("%1/autostart").arg(dir) + postfix; return dirs; } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. 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. */ #include <iostream> #include <QtGui> #include <boost/range/join.hpp> #include <boost/foreach.hpp> #include <boost/thread.hpp> #include <Interface/Application/ModuleWidget.h> #include <Interface/Application/Connection.h> #include <Interface/Application/Port.h> #include <Interface/Application/PositionProvider.h> #include <Interface/Application/GuiLogger.h> #include <Interface/Application/ModuleLogWindow.h> #include <Interface/Modules/Factory/ModuleDialogFactory.h> //TODO: BAD, or will we have some sort of Application global anyway? #include <Interface/Application/SCIRunMainWindow.h> #include <Dataflow/Network/Module.h> using namespace SCIRun::Gui; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Core::Logging; QPointF ProxyWidgetPosition::currentPosition() const { return widget_->pos() + offset_; } namespace { //TODO move to separate header QColor to_color(const std::string& str) { if (str == "red") return Qt::red; if (str == "blue") return Qt::blue; if (str == "darkGreen") return Qt::darkGreen; if (str == "cyan") return Qt::cyan; if (str == "magenta") return Qt::magenta; if (str == "white") return Qt::white; if (str == "yellow") return Qt::yellow; if (str == "darkYellow") return Qt::darkYellow; else return Qt::black; } QAction* separatorAction(QWidget* parent) { auto sep = new QAction(parent); sep->setSeparator(true); return sep; } QAction* disabled(QAction* action) { action->setEnabled(false); return action; } } namespace SCIRun { namespace Gui { class ModuleActionsMenu { public: ModuleActionsMenu(ModuleWidget* parent, const std::string& moduleId) { menu_ = new QMenu("Actions", parent); //TODO: hook up disabled actions menu_->addActions(QList<QAction*>() << disabled(new QAction("ID: " + QString::fromStdString(moduleId), parent)) << separatorAction(parent) << disabled(new QAction("Execute", parent)) << disabled(new QAction("Help", parent)) << disabled(new QAction("Notes", parent)) << disabled(new QAction("Duplicate", parent)) << disabled(new QAction("Replace With->(TODO)", parent)) << new QAction("Show Log", parent) << disabled(new QAction("Make Sub-Network", parent)) << separatorAction(parent) << new QAction("Destroy", parent)); } QMenu* getMenu() { return menu_; } QAction* getAction(const char* name) const { BOOST_FOREACH(QAction* action, menu_->actions()) { if (action->text().contains(name)) return action; } return 0; } private: QMenu* menu_; }; }} ModuleWidget::ModuleWidget(const QString& name, SCIRun::Dataflow::Networks::ModuleHandle theModule, QWidget* parent /* = 0 */) : QFrame(parent), moduleId_(theModule->get_id()), theModule_(theModule), inputPortLayout_(0), outputPortLayout_(0) { setupUi(this); titleLabel_->setText("<b><h3>" + name + "</h3></b>"); progressBar_->setMaximum(100); progressBar_->setMinimum(0); progressBar_->setValue(0); addPortLayouts(); addPorts(*theModule); //TODO: this code should be used to set the correct sizes. int pixelWidth = titleLabel_->fontMetrics().width(titleLabel_->text()); //std::cout << "label width for " << name.toStdString() << " is " << pixelWidth << std::endl; //std::cout << "\tand my frame size is " << width() << std::endl; //std::cout << "\tand label sizehint width is: " << titleLabel_->sizeHint().width() << std::endl; int extraWidth = pixelWidth - 240; if (extraWidth > 0) { resize(width() + extraWidth + 30, height()); //std::cout << "increasing width by " << extraWidth + 30 << std::endl; } connect(optionsButton_, SIGNAL(clicked()), this, SLOT(showOptionsDialog())); makeOptionsDialog(); setupModuleActions(); logWindow_ = new ModuleLogWindow(QString::fromStdString(moduleId_), SCIRunMainWindow::Instance()); connect(logButton2_, SIGNAL(clicked()), logWindow_, SLOT(show())); connect(logButton2_, SIGNAL(clicked()), logWindow_, SLOT(raise())); connect(actionsMenu_->getAction("Show Log"), SIGNAL(triggered()), logWindow_, SLOT(show())); connect(actionsMenu_->getAction("Show Log"), SIGNAL(triggered()), logWindow_, SLOT(raise())); connect(logWindow_, SIGNAL(messageReceived(const QColor&)), this, SLOT(setLogButtonColor(const QColor&))); //TODO: doh, how do i destroy myself? //connect(actionsMenu_->getAction("Destroy"), SIGNAL(triggered()), this, SIGNAL(removeModule(const std::string&))); LoggerHandle logger(new ModuleLogger(logWindow_)); theModule_->setLogger(logger); } void ModuleWidget::setLogButtonColor(const QColor& color) { logButton2_->setStyleSheet( QString("* { background-color: rgb(%1,%2,%3) }") .arg(color.red()) .arg(color.green()) .arg(color.blue())); } void ModuleWidget::setupModuleActions() { actionsMenu_.reset(new ModuleActionsMenu(this, moduleId_)); moduleActionButton_->setMenu(actionsMenu_->getMenu()); } void ModuleWidget::addPortLayouts() { verticalLayout->setContentsMargins(5,0,5,0); } void ModuleWidget::addPorts(const SCIRun::Dataflow::Networks::ModuleInfoProvider& moduleInfoProvider) { const std::string moduleId = moduleInfoProvider.get_id(); for (size_t i = 0; i < moduleInfoProvider.num_input_ports(); ++i) { InputPortHandle port = moduleInfoProvider.get_input_port(i); InputPortWidget* w = new InputPortWidget(QString::fromStdString(port->get_portname()), to_color(port->get_colorname()), QString::fromStdString(moduleId), i, this); hookUpSignals(w); connect(this, SIGNAL(connectionAdded(const SCIRun::Dataflow::Networks::ConnectionDescription&)), w, SLOT(MakeTheConnection(const SCIRun::Dataflow::Networks::ConnectionDescription&))); addPort(w); } for (size_t i = 0; i < moduleInfoProvider.num_output_ports(); ++i) { OutputPortHandle port = moduleInfoProvider.get_output_port(i); OutputPortWidget* w = new OutputPortWidget(QString::fromStdString(port->get_portname()), to_color(port->get_colorname()), QString::fromStdString(moduleId), i, this); hookUpSignals(w); addPort(w); } optionsButton_->setVisible(moduleInfoProvider.has_ui()); } void ModuleWidget::hookUpSignals(PortWidget* port) const { connect(port, SIGNAL(needConnection(const SCIRun::Dataflow::Networks::ConnectionDescription&)), this, SIGNAL(needConnection(const SCIRun::Dataflow::Networks::ConnectionDescription&))); connect(port, SIGNAL(connectionDeleted(const SCIRun::Dataflow::Networks::ConnectionId&)), this, SIGNAL(connectionDeleted(const SCIRun::Dataflow::Networks::ConnectionId&))); } void ModuleWidget::addPort(OutputPortWidget* port) { if (!outputPortLayout_) { //TODO--extract method outputPortLayout_ = new QHBoxLayout; outputPortLayout_->setSpacing(3); outputPortLayout_->setAlignment(Qt::AlignLeft); verticalLayout->insertLayout(-1, outputPortLayout_); } outputPortLayout_->addWidget(port); outputPorts_.push_back(port); } void ModuleWidget::addPort(InputPortWidget* port) { if (!inputPortLayout_) { inputPortLayout_ = new QHBoxLayout; inputPortLayout_->setSpacing(3); inputPortLayout_->setAlignment(Qt::AlignLeft); verticalLayout->insertLayout(0, inputPortLayout_); } inputPortLayout_->addWidget(port); inputPorts_.push_back(port); } ModuleWidget::~ModuleWidget() { Q_FOREACH (PortWidget* p, boost::join(inputPorts_, outputPorts_)) p->deleteConnections(); GuiLogger::Instance().log("Module deleted."); dialog_.reset(); theModule_->setLogger(LoggerHandle()); Q_EMIT removeModule(moduleId_); } void ModuleWidget::trackConnections() { Q_FOREACH (PortWidget* p, boost::join(inputPorts_, outputPorts_)) p->trackConnections(); } QPointF ModuleWidget::inputPortPosition() const { if (positionProvider_) return positionProvider_->currentPosition() + QPointF(20,10); return pos(); } QPointF ModuleWidget::outputPortPosition() const { if (positionProvider_) return positionProvider_->currentPosition() + QPointF(20, height() - 10); return pos(); } double ModuleWidget::percentComplete() const { return progressBar_->value() / 100.0; } void ModuleWidget::setPercentComplete(double p) { if (0 <= p && p <= 1) { progressBar_->setValue(100 * p); } } void ModuleWidget::ModuleExecutionRunner::operator()() { const int numIncrements = 20; const int increment = /*module_->executionTime_*/100 / numIncrements; module_->theModule_->do_execute(); for (int i = 0; i < numIncrements; ++i) { boost::this_thread::sleep(boost::posix_time::milliseconds(increment)); module_->setPercentComplete(i / (double)numIncrements); } module_->setPercentComplete(1); } void ModuleWidget::execute() { { ModuleExecutionRunner runner(this); runner(); } Q_EMIT moduleExecuted(); } void ModuleWidget::setExecutionTime(int milliseconds) { //executionTime_ = milliseconds; setPercentComplete(0); } boost::shared_ptr<ModuleDialogFactory> ModuleWidget::dialogFactory_; void ModuleWidget::makeOptionsDialog() { if (!dialog_) { if (!dialogFactory_) dialogFactory_.reset(new ModuleDialogFactory(SCIRunMainWindow::Instance())); dialog_.reset(dialogFactory_->makeDialog(moduleId_, theModule_->get_state(), 0)); dialog_->pull(); connect(dialog_.get(), SIGNAL(executionTimeChanged(int)), this, SLOT(setExecutionTime(int))); connect(dialog_.get(), SIGNAL(executeButtonPressed()), this, SLOT(execute())); connect(this, SIGNAL(moduleExecuted()), dialog_.get(), SLOT(moduleExecuted())); } } void ModuleWidget::showOptionsDialog() { makeOptionsDialog(); dialog_->show(); } <commit_msg>Add some more pixels in windows.<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. 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. */ #include <iostream> #include <QtGui> #include <boost/range/join.hpp> #include <boost/foreach.hpp> #include <boost/thread.hpp> #include <Interface/Application/ModuleWidget.h> #include <Interface/Application/Connection.h> #include <Interface/Application/Port.h> #include <Interface/Application/PositionProvider.h> #include <Interface/Application/GuiLogger.h> #include <Interface/Application/ModuleLogWindow.h> #include <Interface/Modules/Factory/ModuleDialogFactory.h> //TODO: BAD, or will we have some sort of Application global anyway? #include <Interface/Application/SCIRunMainWindow.h> #include <Dataflow/Network/Module.h> using namespace SCIRun::Gui; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Core::Logging; QPointF ProxyWidgetPosition::currentPosition() const { return widget_->pos() + offset_; } namespace { //TODO move to separate header QColor to_color(const std::string& str) { if (str == "red") return Qt::red; if (str == "blue") return Qt::blue; if (str == "darkGreen") return Qt::darkGreen; if (str == "cyan") return Qt::cyan; if (str == "magenta") return Qt::magenta; if (str == "white") return Qt::white; if (str == "yellow") return Qt::yellow; if (str == "darkYellow") return Qt::darkYellow; else return Qt::black; } QAction* separatorAction(QWidget* parent) { auto sep = new QAction(parent); sep->setSeparator(true); return sep; } QAction* disabled(QAction* action) { action->setEnabled(false); return action; } } namespace SCIRun { namespace Gui { class ModuleActionsMenu { public: ModuleActionsMenu(ModuleWidget* parent, const std::string& moduleId) { menu_ = new QMenu("Actions", parent); //TODO: hook up disabled actions menu_->addActions(QList<QAction*>() << disabled(new QAction("ID: " + QString::fromStdString(moduleId), parent)) << separatorAction(parent) << disabled(new QAction("Execute", parent)) << disabled(new QAction("Help", parent)) << disabled(new QAction("Notes", parent)) << disabled(new QAction("Duplicate", parent)) << disabled(new QAction("Replace With->(TODO)", parent)) << new QAction("Show Log", parent) << disabled(new QAction("Make Sub-Network", parent)) << separatorAction(parent) << new QAction("Destroy", parent)); } QMenu* getMenu() { return menu_; } QAction* getAction(const char* name) const { BOOST_FOREACH(QAction* action, menu_->actions()) { if (action->text().contains(name)) return action; } return 0; } private: QMenu* menu_; }; }} namespace { #ifdef WIN32 const int moduleWidthThreshold = 220; const int extraModuleWidth = 40; #else const int moduleWidthThreshold = 240; const int extraModuleWidth = 30; #endif } ModuleWidget::ModuleWidget(const QString& name, SCIRun::Dataflow::Networks::ModuleHandle theModule, QWidget* parent /* = 0 */) : QFrame(parent), moduleId_(theModule->get_id()), theModule_(theModule), inputPortLayout_(0), outputPortLayout_(0) { setupUi(this); titleLabel_->setText("<b><h3>" + name + "</h3></b>"); progressBar_->setMaximum(100); progressBar_->setMinimum(0); progressBar_->setValue(0); addPortLayouts(); addPorts(*theModule); int pixelWidth = titleLabel_->fontMetrics().width(titleLabel_->text()); int extraWidth = pixelWidth - moduleWidthThreshold; if (extraWidth > 0) { resize(width() + extraWidth + extraModuleWidth, height()); } connect(optionsButton_, SIGNAL(clicked()), this, SLOT(showOptionsDialog())); makeOptionsDialog(); setupModuleActions(); logWindow_ = new ModuleLogWindow(QString::fromStdString(moduleId_), SCIRunMainWindow::Instance()); connect(logButton2_, SIGNAL(clicked()), logWindow_, SLOT(show())); connect(logButton2_, SIGNAL(clicked()), logWindow_, SLOT(raise())); connect(actionsMenu_->getAction("Show Log"), SIGNAL(triggered()), logWindow_, SLOT(show())); connect(actionsMenu_->getAction("Show Log"), SIGNAL(triggered()), logWindow_, SLOT(raise())); connect(logWindow_, SIGNAL(messageReceived(const QColor&)), this, SLOT(setLogButtonColor(const QColor&))); //TODO: doh, how do i destroy myself? //connect(actionsMenu_->getAction("Destroy"), SIGNAL(triggered()), this, SIGNAL(removeModule(const std::string&))); LoggerHandle logger(new ModuleLogger(logWindow_)); theModule_->setLogger(logger); } void ModuleWidget::setLogButtonColor(const QColor& color) { logButton2_->setStyleSheet( QString("* { background-color: rgb(%1,%2,%3) }") .arg(color.red()) .arg(color.green()) .arg(color.blue())); } void ModuleWidget::setupModuleActions() { actionsMenu_.reset(new ModuleActionsMenu(this, moduleId_)); moduleActionButton_->setMenu(actionsMenu_->getMenu()); } void ModuleWidget::addPortLayouts() { verticalLayout->setContentsMargins(5,0,5,0); } void ModuleWidget::addPorts(const SCIRun::Dataflow::Networks::ModuleInfoProvider& moduleInfoProvider) { const std::string moduleId = moduleInfoProvider.get_id(); for (size_t i = 0; i < moduleInfoProvider.num_input_ports(); ++i) { InputPortHandle port = moduleInfoProvider.get_input_port(i); InputPortWidget* w = new InputPortWidget(QString::fromStdString(port->get_portname()), to_color(port->get_colorname()), QString::fromStdString(moduleId), i, this); hookUpSignals(w); connect(this, SIGNAL(connectionAdded(const SCIRun::Dataflow::Networks::ConnectionDescription&)), w, SLOT(MakeTheConnection(const SCIRun::Dataflow::Networks::ConnectionDescription&))); addPort(w); } for (size_t i = 0; i < moduleInfoProvider.num_output_ports(); ++i) { OutputPortHandle port = moduleInfoProvider.get_output_port(i); OutputPortWidget* w = new OutputPortWidget(QString::fromStdString(port->get_portname()), to_color(port->get_colorname()), QString::fromStdString(moduleId), i, this); hookUpSignals(w); addPort(w); } optionsButton_->setVisible(moduleInfoProvider.has_ui()); } void ModuleWidget::hookUpSignals(PortWidget* port) const { connect(port, SIGNAL(needConnection(const SCIRun::Dataflow::Networks::ConnectionDescription&)), this, SIGNAL(needConnection(const SCIRun::Dataflow::Networks::ConnectionDescription&))); connect(port, SIGNAL(connectionDeleted(const SCIRun::Dataflow::Networks::ConnectionId&)), this, SIGNAL(connectionDeleted(const SCIRun::Dataflow::Networks::ConnectionId&))); } void ModuleWidget::addPort(OutputPortWidget* port) { if (!outputPortLayout_) { //TODO--extract method outputPortLayout_ = new QHBoxLayout; outputPortLayout_->setSpacing(3); outputPortLayout_->setAlignment(Qt::AlignLeft); verticalLayout->insertLayout(-1, outputPortLayout_); } outputPortLayout_->addWidget(port); outputPorts_.push_back(port); } void ModuleWidget::addPort(InputPortWidget* port) { if (!inputPortLayout_) { inputPortLayout_ = new QHBoxLayout; inputPortLayout_->setSpacing(3); inputPortLayout_->setAlignment(Qt::AlignLeft); verticalLayout->insertLayout(0, inputPortLayout_); } inputPortLayout_->addWidget(port); inputPorts_.push_back(port); } ModuleWidget::~ModuleWidget() { Q_FOREACH (PortWidget* p, boost::join(inputPorts_, outputPorts_)) p->deleteConnections(); GuiLogger::Instance().log("Module deleted."); dialog_.reset(); theModule_->setLogger(LoggerHandle()); Q_EMIT removeModule(moduleId_); } void ModuleWidget::trackConnections() { Q_FOREACH (PortWidget* p, boost::join(inputPorts_, outputPorts_)) p->trackConnections(); } QPointF ModuleWidget::inputPortPosition() const { if (positionProvider_) return positionProvider_->currentPosition() + QPointF(20,10); return pos(); } QPointF ModuleWidget::outputPortPosition() const { if (positionProvider_) return positionProvider_->currentPosition() + QPointF(20, height() - 10); return pos(); } double ModuleWidget::percentComplete() const { return progressBar_->value() / 100.0; } void ModuleWidget::setPercentComplete(double p) { if (0 <= p && p <= 1) { progressBar_->setValue(100 * p); } } void ModuleWidget::ModuleExecutionRunner::operator()() { const int numIncrements = 20; const int increment = /*module_->executionTime_*/100 / numIncrements; module_->theModule_->do_execute(); for (int i = 0; i < numIncrements; ++i) { boost::this_thread::sleep(boost::posix_time::milliseconds(increment)); module_->setPercentComplete(i / (double)numIncrements); } module_->setPercentComplete(1); } void ModuleWidget::execute() { { ModuleExecutionRunner runner(this); runner(); } Q_EMIT moduleExecuted(); } void ModuleWidget::setExecutionTime(int milliseconds) { //executionTime_ = milliseconds; setPercentComplete(0); } boost::shared_ptr<ModuleDialogFactory> ModuleWidget::dialogFactory_; void ModuleWidget::makeOptionsDialog() { if (!dialog_) { if (!dialogFactory_) dialogFactory_.reset(new ModuleDialogFactory(SCIRunMainWindow::Instance())); dialog_.reset(dialogFactory_->makeDialog(moduleId_, theModule_->get_state(), 0)); dialog_->pull(); connect(dialog_.get(), SIGNAL(executionTimeChanged(int)), this, SLOT(setExecutionTime(int))); connect(dialog_.get(), SIGNAL(executeButtonPressed()), this, SLOT(execute())); connect(this, SIGNAL(moduleExecuted()), dialog_.get(), SLOT(moduleExecuted())); } } void ModuleWidget::showOptionsDialog() { makeOptionsDialog(); dialog_->show(); } <|endoftext|>
<commit_before>/* -*- mode: c++; indent-tabs-mode: nil; tab-width: 2 -*- * * $Id: item.h,v 1.1 2006/10/09 07:07:59 $ * * Copyright 2006-2007 FLWOR Foundation. * Author: David Graf, Donald Kossmann, Tim Kraska * */ #include "store/api/item.h" #include "errors/error_factory.h" #include "system/zorba_engine.h" #include "runtime/core/item_iterator.h" #include "api/serialization/serializer.h" #include "system/globalenv.h" #include "types/typesystem.h" namespace xqp { bool Item::isNumeric() const { TypeSystem::xqtref_t type = GENV_TYPESYSTEM.create_type(getType(), TypeSystem::QUANT_ONE); return GENV_TYPESYSTEM.is_numeric(*type); } xqp_string Item::show() const { return std::string ( typeid ( *this ).name() ) + ": 'show' not implemented!"; } /* end class Item */ void Item::serializeXML( ostream& os ) { serializer *ser; ser = ZORBA_FOR_CURRENT_THREAD()->getItemSerializer(); ser->serialize(this, os); } /* begin class AtomicItem */ Item_t AtomicItem::getAtomizationValue() const { Item* lItem = const_cast<AtomicItem *>(this); return lItem; } Iterator_t AtomicItem::getTypedValue() const { PlanIter_t planIter = new SingletonIterator(ZORBA_FOR_CURRENT_THREAD()->GetCurrentLocation(), this->getAtomizationValue()); return new PlanWrapper ( planIter ); } /* end class AtomicItem */ } <commit_msg>Moved code from item.h to item.cpp.<commit_after>/* -*- mode: c++; indent-tabs-mode: nil; tab-width: 2 -*- * * $Id: item.h,v 1.1 2006/10/09 07:07:59 $ * * Copyright 2006-2007 FLWOR Foundation. * Author: David Graf, Donald Kossmann, Tim Kraska * */ #include "store/api/item.h" #include "errors/error_factory.h" #include "system/zorba_engine.h" #include "runtime/core/item_iterator.h" #include "api/serialization/serializer.h" #include "system/globalenv.h" #include "types/typesystem.h" #include "util/Assert.h" namespace xqp { /** * Get a hash value computed from the value of this item. * * @return The hash value */ uint32_t Item::hash() const { ZORBA_ASSERT(false); return 0; }; /* ------------------- Methods for AtomicValues ------------------------------ */ /** * getXValue functions: * @return value of type X * * Assuming that the item is an AtomicValue of a particular kind X, return the value * of the item. Implementations of X, e.g., a specific DoubleValue implementation, will override * its specific getXValue method (i.e., getDoubleValue) and not change any of the other methods. * Implementations of the seven kinds of nodes should not override the definition of these * methods. */ /** Accessor for xs:base64Binary */ xqp_base64Binary Item::getBase64Binary() const { ZORBA_ASSERT(false); return NULL; } /** Accessor for xs:boolean */ bool Item::getBooleanValue() const { ZORBA_ASSERT(false); return false; } /** Accessor for xs:decimal, xs:(nonPositive | negative | nonNegativeInteger | positive)integer, * xs:(unsigned)long, xs:(unsigned)int, xs:(unsigned)short, xs:(unsigned)byte */ xqp_decimal Item::getDecimalValue() const { ZORBA_ASSERT(false); return 0; } /** Accessor for xs:int */ xqp_int Item::getIntValue() const { ZORBA_ASSERT(false); return 0; } /** Accessor for xs:(nonPositive | negative | nonNegativeInteger | positive)integer, * xs:(unsigned)long, xs:(unsigned)int, xs:(unsigned)short, xs:(unsigned)byte */ xqp_integer Item::getIntegerValue() const { ZORBA_ASSERT(false); return 0; } /** Accessor for xs:long */ xqp_long Item::getLongValue() const { ZORBA_ASSERT(false); return 0; } /** Accessor for xs:short */ xqp_short Item::getShortValue() const { ZORBA_ASSERT(false); return 0; } /** Accessor for xs:nonNegativeInteager, xs:positiveInteger */ xqp_uinteger Item::getUnsignedIntegerValue() const { ZORBA_ASSERT(false); return 0; } /** Accessor for xs:unsignedChar, xs:unsignedByte */ xqp_ubyte Item::getUnsignedByteValue() const { ZORBA_ASSERT(false); return 0; } xqp_byte Item::getByteValue() const { ZORBA_ASSERT(false); return 0; } /** Accessor for xs:date */ xqp_date Item::getDateValue() const { ZORBA_ASSERT(false); return xqp_date(); } /** Accessor for xs:dateTime */ xqp_dateTime Item::getDateTimeValue() const { ZORBA_ASSERT(false); return xqp_dateTime(); } /** Accessor for xs:double */ xqp_double Item::getDoubleValue() const { ZORBA_ASSERT(false); return 0; } /** Accessor for xs:duration */ xqp_duration Item::getDurationValue() const { ZORBA_ASSERT(false); return xqp_duration(); } /** Accessor for xs:ENTITIES, xs:IDREFS, xs:NMTOKENS */ std::vector<xqp_string> Item::getStringVectorValue() const { ZORBA_ASSERT(false); return std::vector<xqp_string>(); } /** Accessor for xs:float */ xqp_float Item::getFloatValue() const { ZORBA_ASSERT(false); return 0; } /** Accessor for xs:gDay */ xqp_gDay Item::getGDayValue() const { ZORBA_ASSERT(false); return xqp_gDay(); } /** Accessor for xs:gMonth */ xqp_gMonth Item::getGMonthValue() const { ZORBA_ASSERT(false); return xqp_gMonth(); } /** Accessor for xs:gMonthDay */ xqp_gMonthDay Item::getGMonthDayValue() const { ZORBA_ASSERT(false); return xqp_gMonthDay(); } /** Accessor for xs:gYear */ xqp_gYear Item::getGYearValue() const { ZORBA_ASSERT(false); return xqp_gYear(); } /** Accessor for xs:gYearMonth */ xqp_gYearMonth Item::getGYearMonthValue() const { ZORBA_ASSERT(false); return xqp_gYearMonth(); } /** Accessor for xs:hexBinary */ xqp_hexBinary Item::getHexBinaryValue() const { ZORBA_ASSERT(false); return xqp_hexBinary(); } /** Accessor for xs:nonNegativeIntegerValue, xs:positiveInteger, xs:unsignedInt */ xqp_uint Item::getUnsignedIntValue() const { ZORBA_ASSERT(false); return 0; } /** Accessor for xs:time */ xqp_time Item::getTimeValue() const { ZORBA_ASSERT(false); return xqp_time(); } /** Accessor for xs:unsignedLong */ xqp_ulong Item::getUnsignedLongValue() const { ZORBA_ASSERT(false); return 0; } /** Accessor for xs:unsignedShort */ xqp_ushort Item::getUnsignedShortValue() const { ZORBA_ASSERT(false); return 0; } /** * Helper method for numeric atomic items * @return true, if containing number is not-a-number (possible for floating-point numbers) */ bool Item::isNaN() const { ZORBA_ASSERT(false); return false; } /** * Helper method for numeric atomic items * @return true, if containing numbers represents -INF or +INF */ bool Item::isPosOrNegInf() const { ZORBA_ASSERT(false); return false; } /* ------------------- Methods for Nodes ------------------------------------- */ /** * getNodeProperty functions - Accessor of XDM (see XDM specification, Section 5) * @return value of node property * * Assuming that the item is a node, return the properties of that particular node. * Since all these properties are defined on all seven kinds of nodes (documents, elements, * attributes, etc.), the implementations of all seven kinds of nodes must override these * methods. Implementations of atomic values should keep the default (error) implementation * of these methods. */ /** Accessor for element node * @return attribute* */ Iterator_t Item::getAttributes() const { ZORBA_ASSERT(false); return NULL; } /** Accessor for document node, element node, attribute node, * processing instruction node, comment node, text node * @return uri? */ xqp_string Item::getBaseURI() const { ZORBA_ASSERT(false); return ""; } /** Accessor for document node, element node * @return node* */ Iterator_t Item::getChildren() const { ZORBA_ASSERT(false); return NULL; } /** Accessor for document node * @return uri? */ xqp_string Item::getDocumentURI() const { ZORBA_ASSERT(false); return ""; } /** Accessor for attribute node * @return isId: Used for attribute items (defines the attribute an id?) */ bool Item::isId() const { ZORBA_ASSERT(false); return false; } /** Accessor for attribute node * @return isIdrefs Used for attribute (defines the attribute an idref?)) */ bool Item::isIdrefs() const { ZORBA_ASSERT(false); return false; } /** Accessor for element node * @return returns prefix namespace pairs */ void Item::getNamespaceBindings(NsBindings& bindings) const { ZORBA_ASSERT(false); } /** Accessor for element node * @return boolean? */ bool Item::getNilled() const { ZORBA_ASSERT(false); return false; } /** Accessor for document node, element node, attribute node, namespace node, * processing instruction node, comment node, text node * @return TypeCode of the current node */ NodeKind Item::getNodeKind() const { ZORBA_ASSERT(false); return StoreConsts::elementNode; } /** Accessor for element node, attribute node * @return qname? */ Item_t Item::getNodeName() const { ZORBA_ASSERT(false); return NULL; } /** Accessor for element node, attribute node, namespace node, processing instruction node, * comment node, text node * @return node? */ Item_t Item::getParent() const { ZORBA_ASSERT(false); return NULL; } /** Accessor for document node, element node, attribute node, namespace node, * processing instruction node, comment node, text node * * @return typedValue? */ Iterator_t Item::getTypedValue() const { ZORBA_ASSERT(false); return NULL; } /** Accessor for xs:qname, namespace node * @return namespace uri */ xqp_string Item::getNamespace() const { ZORBA_ASSERT(false); return ""; } /** Accessor for xs:qname, namespace node * @return namespace prefix */ xqp_string Item::getPrefix() const { ZORBA_ASSERT(false); return ""; } /** Accessor for xs:qname * @return namespace local name */ xqp_string Item::getLocalName() const { ZORBA_ASSERT(false); return ""; } /** Accessor for document node * @return unparsed entity public id */ xqp_string Item::getUnparsedEntityPublicId() const { ZORBA_ASSERT(false); return ""; } /** Accessor for document node * @return unparsed entity system id */ xqp_string Item::getUnparsedEntitySystemId() const { ZORBA_ASSERT(false); return ""; } /** * Accessor for processing instruction node * @return target of the PI */ xqp_string Item::getTarget() const { ZORBA_ASSERT(false); return ""; } /** * Helper method with is used to return a StringValue of an Item * by pointer instead of rchandle */ xqpStringStore* Item::getStringValueP() { ZORBA_ASSERT(false); return 0; } bool Item::isNumeric() const { TypeSystem::xqtref_t type = GENV_TYPESYSTEM.create_type(getType(), TypeSystem::QUANT_ONE); return GENV_TYPESYSTEM.is_numeric(*type); } xqp_string Item::show() const { return std::string ( typeid ( *this ).name() ) + ": 'show' not implemented!"; } /* end class Item */ void Item::serializeXML( ostream& os ) { serializer *ser; ser = ZORBA_FOR_CURRENT_THREAD()->getItemSerializer(); ser->serialize(this, os); } /* begin class AtomicItem */ Item_t AtomicItem::getAtomizationValue() const { Item* lItem = const_cast<AtomicItem *>(this); return lItem; } Iterator_t AtomicItem::getTypedValue() const { PlanIter_t planIter = new SingletonIterator(ZORBA_FOR_CURRENT_THREAD()->GetCurrentLocation(), this->getAtomizationValue()); return new PlanWrapper ( planIter ); } /* end class AtomicItem */ } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright RTK Consortium * * 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.txt * * 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 "rtkCudaParkerShortScanImageFilter.h" #include "rtkCudaParkerShortScanImageFilter.hcu" namespace rtk { CudaParkerShortScanImageFilter ::CudaParkerShortScanImageFilter() {} CudaParkerShortScanImageFilter ::~CudaParkerShortScanImageFilter() {} void CudaParkerShortScanImageFilter ::GPUGenerateData() { // Put the two data pointers at the same location float * inBuffer = *static_cast<float **>(this->GetInput()->GetCudaDataManager()->GetGPUBufferPointer()); inBuffer += this->GetInput()->ComputeOffset(this->GetInput()->GetRequestedRegion().GetIndex()); float * outBuffer = *static_cast<float **>(this->GetOutput()->GetCudaDataManager()->GetGPUBufferPointer()); outBuffer += this->GetOutput()->ComputeOffset(this->GetOutput()->GetRequestedRegion().GetIndex()); if (!m_IsShortScan) { if (outBuffer != inBuffer) { size_t count = this->GetOutput()->GetRequestedRegion().GetSize(0); count *= sizeof(ImageType::PixelType); for (unsigned int k = 0; k < this->GetOutput()->GetRequestedRegion().GetSize(2); k++) { for (unsigned int j = 0; j < this->GetOutput()->GetRequestedRegion().GetSize(1); j++) { cudaMemcpy(outBuffer, inBuffer, count, cudaMemcpyDeviceToDevice); inBuffer += this->GetInput()->GetBufferedRegion().GetSize(0); outBuffer += this->GetOutput()->GetBufferedRegion().GetSize(0); } inBuffer += (this->GetInput()->GetBufferedRegion().GetSize(1) - this->GetInput()->GetRequestedRegion().GetSize(1)) * this->GetInput()->GetBufferedRegion().GetSize(0); outBuffer += (this->GetOutput()->GetBufferedRegion().GetSize(1) - this->GetOutput()->GetRequestedRegion().GetSize(1)) * this->GetOutput()->GetBufferedRegion().GetSize(0); } } return; } // check for enough data const int geomStart = this->GetInput()->GetBufferedRegion().GetIndex()[2]; double sox = this->GetGeometry()->GetSourceOffsetsX()[geomStart]; double sid = this->GetGeometry()->GetSourceToIsocenterDistances()[geomStart]; float proj_orig = this->GetInput()->GetOrigin()[0]; float proj_row = this->GetInput()->GetDirection()[0][0] * this->GetInput()->GetSpacing()[0]; float proj_col = this->GetInput()->GetDirection()[0][1] * this->GetInput()->GetSpacing()[1]; int proj_idx[2]; proj_idx[0] = this->GetInput()->GetRequestedRegion().GetIndex()[0]; proj_idx[1] = this->GetInput()->GetRequestedRegion().GetIndex()[1]; int proj_size[3]; proj_size[0] = this->GetInput()->GetRequestedRegion().GetSize()[0]; proj_size[1] = this->GetInput()->GetRequestedRegion().GetSize()[1]; proj_size[2] = this->GetInput()->GetRequestedRegion().GetSize()[2]; int proj_size_buf_in[2]; proj_size_buf_in[0] = this->GetInput()->GetBufferedRegion().GetSize()[0]; proj_size_buf_in[1] = this->GetInput()->GetBufferedRegion().GetSize()[1]; int proj_size_buf_out[2]; proj_size_buf_out[0] = this->GetOutput()->GetBufferedRegion().GetSize()[0]; proj_size_buf_out[1] = this->GetOutput()->GetBufferedRegion().GetSize()[1]; // 2D matrix (numgeom * 3values) in one block for memcpy! // for each geometry, the following structure is used: // 0: sdd // 1: projection offset x // 2: gantry angle int geomIdx = this->GetInput()->GetRequestedRegion().GetIndex()[2]; float * geomMatrix = new float[proj_size[2] * 5]; if (geomMatrix == nullptr) itkExceptionMacro(<< "Couldn't allocate geomMatrix"); for (int g = 0; g < proj_size[2]; ++g) { geomMatrix[g * 5 + 0] = this->GetGeometry()->GetSourceToDetectorDistances()[g + geomIdx]; geomMatrix[g * 5 + 1] = this->GetGeometry()->GetSourceOffsetsX()[g + geomIdx]; geomMatrix[g * 5 + 2] = this->GetGeometry()->GetProjectionOffsetsX()[g + geomIdx]; geomMatrix[g * 5 + 3] = this->GetGeometry()->GetSourceToIsocenterDistances()[g + geomIdx]; geomMatrix[g * 5 + 4] = this->GetGeometry()->GetGantryAngles()[g + geomIdx]; } CUDA_parker_weight(proj_idx, proj_size, proj_size_buf_in, proj_size_buf_out, inBuffer, outBuffer, geomMatrix, m_Delta, m_FirstAngle, proj_orig, proj_row, proj_col); delete[] geomMatrix; } } // namespace rtk <commit_msg>COMP: fix warnings triggered by unused variables<commit_after>/*========================================================================= * * Copyright RTK Consortium * * 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.txt * * 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 "rtkCudaParkerShortScanImageFilter.h" #include "rtkCudaParkerShortScanImageFilter.hcu" namespace rtk { CudaParkerShortScanImageFilter ::CudaParkerShortScanImageFilter() {} CudaParkerShortScanImageFilter ::~CudaParkerShortScanImageFilter() {} void CudaParkerShortScanImageFilter ::GPUGenerateData() { // Put the two data pointers at the same location float * inBuffer = *static_cast<float **>(this->GetInput()->GetCudaDataManager()->GetGPUBufferPointer()); inBuffer += this->GetInput()->ComputeOffset(this->GetInput()->GetRequestedRegion().GetIndex()); float * outBuffer = *static_cast<float **>(this->GetOutput()->GetCudaDataManager()->GetGPUBufferPointer()); outBuffer += this->GetOutput()->ComputeOffset(this->GetOutput()->GetRequestedRegion().GetIndex()); if (!m_IsShortScan) { if (outBuffer != inBuffer) { size_t count = this->GetOutput()->GetRequestedRegion().GetSize(0); count *= sizeof(ImageType::PixelType); for (unsigned int k = 0; k < this->GetOutput()->GetRequestedRegion().GetSize(2); k++) { for (unsigned int j = 0; j < this->GetOutput()->GetRequestedRegion().GetSize(1); j++) { cudaMemcpy(outBuffer, inBuffer, count, cudaMemcpyDeviceToDevice); inBuffer += this->GetInput()->GetBufferedRegion().GetSize(0); outBuffer += this->GetOutput()->GetBufferedRegion().GetSize(0); } inBuffer += (this->GetInput()->GetBufferedRegion().GetSize(1) - this->GetInput()->GetRequestedRegion().GetSize(1)) * this->GetInput()->GetBufferedRegion().GetSize(0); outBuffer += (this->GetOutput()->GetBufferedRegion().GetSize(1) - this->GetOutput()->GetRequestedRegion().GetSize(1)) * this->GetOutput()->GetBufferedRegion().GetSize(0); } } return; } // check for enough data const int geomStart = this->GetInput()->GetBufferedRegion().GetIndex()[2]; float proj_orig = this->GetInput()->GetOrigin()[0]; float proj_row = this->GetInput()->GetDirection()[0][0] * this->GetInput()->GetSpacing()[0]; float proj_col = this->GetInput()->GetDirection()[0][1] * this->GetInput()->GetSpacing()[1]; int proj_idx[2]; proj_idx[0] = this->GetInput()->GetRequestedRegion().GetIndex()[0]; proj_idx[1] = this->GetInput()->GetRequestedRegion().GetIndex()[1]; int proj_size[3]; proj_size[0] = this->GetInput()->GetRequestedRegion().GetSize()[0]; proj_size[1] = this->GetInput()->GetRequestedRegion().GetSize()[1]; proj_size[2] = this->GetInput()->GetRequestedRegion().GetSize()[2]; int proj_size_buf_in[2]; proj_size_buf_in[0] = this->GetInput()->GetBufferedRegion().GetSize()[0]; proj_size_buf_in[1] = this->GetInput()->GetBufferedRegion().GetSize()[1]; int proj_size_buf_out[2]; proj_size_buf_out[0] = this->GetOutput()->GetBufferedRegion().GetSize()[0]; proj_size_buf_out[1] = this->GetOutput()->GetBufferedRegion().GetSize()[1]; // 2D matrix (numgeom * 3values) in one block for memcpy! // for each geometry, the following structure is used: // 0: sdd // 1: projection offset x // 2: gantry angle int geomIdx = this->GetInput()->GetRequestedRegion().GetIndex()[2]; float * geomMatrix = new float[proj_size[2] * 5]; if (geomMatrix == nullptr) itkExceptionMacro(<< "Couldn't allocate geomMatrix"); for (int g = 0; g < proj_size[2]; ++g) { geomMatrix[g * 5 + 0] = this->GetGeometry()->GetSourceToDetectorDistances()[g + geomIdx]; geomMatrix[g * 5 + 1] = this->GetGeometry()->GetSourceOffsetsX()[g + geomIdx]; geomMatrix[g * 5 + 2] = this->GetGeometry()->GetProjectionOffsetsX()[g + geomIdx]; geomMatrix[g * 5 + 3] = this->GetGeometry()->GetSourceToIsocenterDistances()[g + geomIdx]; geomMatrix[g * 5 + 4] = this->GetGeometry()->GetGantryAngles()[g + geomIdx]; } CUDA_parker_weight(proj_idx, proj_size, proj_size_buf_in, proj_size_buf_out, inBuffer, outBuffer, geomMatrix, m_Delta, m_FirstAngle, proj_orig, proj_row, proj_col); delete[] geomMatrix; } } // namespace rtk <|endoftext|>
<commit_before>#ifndef __STRICT_FSTREAM_HPP #define __STRICT_FSTREAM_HPP #include <cassert> #include <fstream> #include <cstring> #include <string> /** * This namespace defines wrappers for std::ifstream, std::ofstream, and * std::fstream objects. The wrappers perform the following steps: * - check the open modes make sense * - check that the call to open() is successful * - (for input streams) check that the opened file is peek-able * - turn on the badbit in the exception mask */ namespace strict_fstream { /// Overload of error-reporting function, to enable use with VS. /// Ref: http://stackoverflow.com/a/901316/717706 static std::string strerror() { std::string buff(80, '\0'); #ifdef _WIN32 if (strerror_s(&buff[0], buff.size(), errno) != 0) { buff = "Unknown error"; } #elif (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE // XSI-compliant strerror_r() if (strerror_r(errno, &buff[0], buff.size()) != 0) { buff = "Unknown error"; } #else // GNU-specific strerror_r() auto p = strerror_r(errno, &buff[0], buff.size()); std::string tmp(p, std::strlen(p)); std::swap(buff, tmp); #endif buff.resize(buff.find('\0')); return buff; } /// Exception class thrown by failed operations. class Exception : public std::exception { public: Exception(const std::string& msg) : _msg(msg) {} const char * what() const noexcept { return _msg.c_str(); } private: std::string _msg; }; // class Exception namespace detail { struct static_method_holder { static std::string mode_to_string(std::ios_base::openmode mode) { static const int n_modes = 6; static const std::ios_base::openmode mode_val_v[n_modes] = { std::ios_base::in, std::ios_base::out, std::ios_base::app, std::ios_base::ate, std::ios_base::trunc, std::ios_base::binary }; static const char * mode_name_v[n_modes] = { "in", "out", "app", "ate", "trunc", "binary" }; std::string res; for (int i = 0; i < n_modes; ++i) { if (mode & mode_val_v[i]) { res += (! res.empty()? "|" : ""); res += mode_name_v[i]; } } if (res.empty()) res = "none"; return res; } static void check_mode(const std::string& filename, std::ios_base::openmode mode) { if ((mode & std::ios_base::trunc) && ! (mode & std::ios_base::out)) { throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and not out"); } else if ((mode & std::ios_base::app) && ! (mode & std::ios_base::out)) { throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: app and not out"); } else if ((mode & std::ios_base::trunc) && (mode & std::ios_base::app)) { throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and app"); } } static void check_open(std::ios * s_p, const std::string& filename, std::ios_base::openmode mode) { if (s_p->fail()) { throw Exception(std::string("strict_fstream: open('") + filename + "'," + mode_to_string(mode) + "): open failed: " + strerror()); } } static void check_peek(std::istream * is_p, const std::string& filename, std::ios_base::openmode mode) { bool peek_failed = true; try { is_p->peek(); peek_failed = is_p->fail(); } catch (std::ios_base::failure e) {} if (peek_failed) { throw Exception(std::string("strict_fstream: open('") + filename + "'," + mode_to_string(mode) + "): peek failed: " + strerror()); } is_p->clear(); } }; // struct static_method_holder } // namespace detail class ifstream : public std::ifstream { public: ifstream() = default; ifstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) { open(filename, mode); } void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) { mode |= std::ios_base::in; exceptions(std::ios_base::badbit); detail::static_method_holder::check_mode(filename, mode); std::ifstream::open(filename, mode); detail::static_method_holder::check_open(this, filename, mode); detail::static_method_holder::check_peek(this, filename, mode); } }; // class ifstream class ofstream : public std::ofstream { public: ofstream() = default; ofstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out) { open(filename, mode); } void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out) { mode |= std::ios_base::out; exceptions(std::ios_base::badbit); detail::static_method_holder::check_mode(filename, mode); std::ofstream::open(filename, mode); detail::static_method_holder::check_open(this, filename, mode); } }; // class ofstream class fstream : public std::fstream { public: fstream() = default; fstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) { open(filename, mode); } void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) { if (! (mode & std::ios_base::out)) mode |= std::ios_base::in; exceptions(std::ios_base::badbit); detail::static_method_holder::check_mode(filename, mode); std::fstream::open(filename, mode); detail::static_method_holder::check_open(this, filename, mode); detail::static_method_holder::check_peek(this, filename, mode); } }; // class fstream } // namespace strict_fstream #endif <commit_msg>Update strict_fstream.hpp for Apple and CpuArch for intrinsic flags fix for macOS<commit_after>#ifndef __STRICT_FSTREAM_HPP #define __STRICT_FSTREAM_HPP #include <cassert> #include <fstream> #include <cstring> #include <string> /** * This namespace defines wrappers for std::ifstream, std::ofstream, and * std::fstream objects. The wrappers perform the following steps: * - check the open modes make sense * - check that the call to open() is successful * - (for input streams) check that the opened file is peek-able * - turn on the badbit in the exception mask */ namespace strict_fstream { /// Overload of error-reporting function, to enable use with VS. /// Ref: http://stackoverflow.com/a/901316/717706 static std::string strerror() { size_t maxSize = 255; std::string buff(maxSize, '\0'); #ifdef _WIN32 if (strerror_s(&buff[0], buff.size(), errno) != 0) { buff = "Unknown error"; } #elif ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE) || defined(__APPLE__) // XSI-compliant strerror_r() if (strerror_r(errno, &buff[0], buff.size()) != 0) { buff = "Unknown error"; } #else // GNU-specific strerror_r() auto p = strerror_r(errno, &buff[0], buff.size()); maxSize = std::strlen(p); std::string tmp(p, maxSize); std::swap(buff, tmp); #endif size_t pos = buff.find('\0'); if (pos != std::string::npos) { buff.resize(buff.find('\0')); } else { buff[maxSize-1]='\0'; } return buff; } /// Exception class thrown by failed operations. class Exception : public std::exception { public: Exception(const std::string& msg) : _msg(msg) {} const char * what() const noexcept { return _msg.c_str(); } private: std::string _msg; }; // class Exception namespace detail { struct static_method_holder { static std::string mode_to_string(std::ios_base::openmode mode) { static const int n_modes = 6; static const std::ios_base::openmode mode_val_v[n_modes] = { std::ios_base::in, std::ios_base::out, std::ios_base::app, std::ios_base::ate, std::ios_base::trunc, std::ios_base::binary }; static const char * mode_name_v[n_modes] = { "in", "out", "app", "ate", "trunc", "binary" }; std::string res; for (int i = 0; i < n_modes; ++i) { if (mode & mode_val_v[i]) { res += (! res.empty()? "|" : ""); res += mode_name_v[i]; } } if (res.empty()) res = "none"; return res; } static void check_mode(const std::string& filename, std::ios_base::openmode mode) { if ((mode & std::ios_base::trunc) && ! (mode & std::ios_base::out)) { throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and not out"); } else if ((mode & std::ios_base::app) && ! (mode & std::ios_base::out)) { throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: app and not out"); } else if ((mode & std::ios_base::trunc) && (mode & std::ios_base::app)) { throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and app"); } } static void check_open(std::ios * s_p, const std::string& filename, std::ios_base::openmode mode) { if (s_p->fail()) { throw Exception(std::string("strict_fstream: open('") + filename + "'," + mode_to_string(mode) + "): open failed: " + strerror()); } } static void check_peek(std::istream * is_p, const std::string& filename, std::ios_base::openmode mode) { bool peek_failed = true; try { is_p->peek(); peek_failed = is_p->fail(); } catch (std::ios_base::failure e) {} if (peek_failed) { throw Exception(std::string("strict_fstream: open('") + filename + "'," + mode_to_string(mode) + "): peek failed: " + strerror()); } is_p->clear(); } }; // struct static_method_holder } // namespace detail class ifstream : public std::ifstream { public: ifstream() = default; ifstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) { open(filename, mode); } void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) { mode |= std::ios_base::in; exceptions(std::ios_base::badbit); detail::static_method_holder::check_mode(filename, mode); std::ifstream::open(filename, mode); detail::static_method_holder::check_open(this, filename, mode); detail::static_method_holder::check_peek(this, filename, mode); } }; // class ifstream class ofstream : public std::ofstream { public: ofstream() = default; ofstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out) { open(filename, mode); } void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out) { mode |= std::ios_base::out; exceptions(std::ios_base::badbit); detail::static_method_holder::check_mode(filename, mode); std::ofstream::open(filename, mode); detail::static_method_holder::check_open(this, filename, mode); } }; // class ofstream class fstream : public std::fstream { public: fstream() = default; fstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) { open(filename, mode); } void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) { if (! (mode & std::ios_base::out)) mode |= std::ios_base::in; exceptions(std::ios_base::badbit); detail::static_method_holder::check_mode(filename, mode); std::fstream::open(filename, mode); detail::static_method_holder::check_open(this, filename, mode); detail::static_method_holder::check_peek(this, filename, mode); } }; // class fstream } // namespace strict_fstream #endif <|endoftext|>
<commit_before>#include <iostream> #include "headings.h" #include "libaps.h" #include "constants.h" #include <concol.h> using namespace std; enum MODE {DRAM, EPROM}; MODE get_mode() { cout << concol::RED << "Programming options:" << concol::RESET << endl; cout << "1) Upload DRAM image" << endl; cout << "2) Update EPROM image" << endl << endl; cout << "Choose option [1]: "; char input; cin.get(input); switch (input) { case '1': default: return DRAM; break; case '2': return EPROM; break; } } int get_device_id() { cout << "Choose device ID [0]: "; int device_id = 0; cin >> device_id; return device_id; } vector<uint32_t> read_bit_file(string fileName) { std::ifstream FID (fileName, std::ios::in|std::ios::binary); if (!FID.is_open()){ throw runtime_error("Unable to open file."); } //Get the file size in bytes FID.seekg(0, std::ios::end); size_t fileSize = FID.tellg(); FILE_LOG(logDEBUG1) << "Bitfile is " << fileSize << " bytes"; FID.seekg(0, std::ios::beg); //Copy over the file data to the data vector vector<uint32_t> packedData; packedData.resize(fileSize/4); FID.read(reinterpret_cast<char *>(packedData.data()), fileSize); //Convert to big endian byte order - basically because it will be byte-swapped again when the packet is serialized for (auto & packet : packedData) { packet = htonl(packet); } cout << "Bit file is " << packedData.size() << " 32-bit words long" << endl; return packedData; } int write_image(string deviceSerial, string fileName) { vector<uint32_t> data; try { data = read_bit_file(fileName); } catch (std::exception &e) { cout << concol::RED << "Unable to open file." << concol::RESET << endl; return -1; } write_flash(deviceSerial.c_str(), EPROM_USER_IMAGE_ADDR, data.data(), data.size()); //verify the write vector<uint32_t> buffer(256); uint32_t numWords = 256; cout << "Verifying:" << endl; for (size_t ct=0; ct < data.size(); ct+=256) { if (ct % 1000 == 0) { cout << "\r" << 100*ct/data.size() << "%" << flush; } if (std::distance(data.begin() + ct, data.end()) < 256) { numWords = std::distance(data.begin() + ct, data.end()); } read_flash(deviceSerial.c_str(), EPROM_USER_IMAGE_ADDR + 4*ct, numWords, buffer.data()); if (!std::equal(buffer.begin(), buffer.begin()+numWords, data.begin()+ct)) { cout << endl << "Mismatched data at offset " << hexn<6> << ct << endl; return -2; } } cout << "\r100%" << endl; return reset(deviceSerial.c_str(), static_cast<int>(APS_RESET_MODE_STAT::RECONFIG_EPROM)); } int main (int argc, char* argv[]) { concol::concolinit(); cout << concol::RED << "BBN AP2 Programming Executable" << concol::RESET << endl; int dbgLevel = 4; set_logging_level(dbgLevel); string bitFile(argv[1]); cout << concol::RED << "Attempting to initialize libaps" << concol::RESET << endl; init(); set_log("stdout"); int numDevices = get_numDevices(); cout << concol::RED << numDevices << " APS device" << (numDevices > 1 ? "s": "") << " found" << concol::RESET << endl; if (numDevices < 1) return 0; cout << concol::RED << "Attempting to get serials" << concol::RESET << endl; const char ** serialBuffer = new const char*[numDevices]; get_deviceSerials(serialBuffer); for (int cnt=0; cnt < numDevices; cnt++) { cout << concol::RED << "Device " << cnt << " serial #: " << serialBuffer[cnt] << concol::RESET << endl; } string deviceSerial; if (numDevices == 1) { deviceSerial = string(serialBuffer[0]); } else { deviceSerial = string(serialBuffer[get_device_id()]); } connect_APS(deviceSerial.c_str()); MODE mode = get_mode(); switch (mode) { case EPROM: cout << concol::RED << "Reprogramming EPROM image" << concol::RESET << endl; write_image(deviceSerial, bitFile); break; case DRAM: cout << concol::RED << "Reprogramming DRAM image" << concol::RESET << endl; program_FPGA(deviceSerial.c_str(), bitFile.c_str()); break; } disconnect_APS(deviceSerial.c_str()); delete[] serialBuffer; cout << concol::RED << "Finished!" << concol::RESET << endl; return 0; } <commit_msg>Fix skipping of second prompt<commit_after>#include <iostream> #include "headings.h" #include "libaps.h" #include "constants.h" #include <concol.h> using namespace std; enum MODE {DRAM, EPROM}; MODE get_mode() { cout << concol::RED << "Programming options:" << concol::RESET << endl; cout << "1) Upload DRAM image" << endl; cout << "2) Update EPROM image" << endl << endl; cout << "Choose option [1]: "; char input; cin.get(input); switch (input) { case '1': default: return DRAM; break; case '2': return EPROM; break; } } int get_device_id() { cout << "Choose device ID [0]: "; int device_id = 0; cin >> device_id; cin.clear(); cin.ignore(INT_MAX, '\n'); return device_id; } vector<uint32_t> read_bit_file(string fileName) { std::ifstream FID (fileName, std::ios::in|std::ios::binary); if (!FID.is_open()){ throw runtime_error("Unable to open file."); } //Get the file size in bytes FID.seekg(0, std::ios::end); size_t fileSize = FID.tellg(); FILE_LOG(logDEBUG1) << "Bitfile is " << fileSize << " bytes"; FID.seekg(0, std::ios::beg); //Copy over the file data to the data vector vector<uint32_t> packedData; packedData.resize(fileSize/4); FID.read(reinterpret_cast<char *>(packedData.data()), fileSize); //Convert to big endian byte order - basically because it will be byte-swapped again when the packet is serialized for (auto & packet : packedData) { packet = htonl(packet); } cout << "Bit file is " << packedData.size() << " 32-bit words long" << endl; return packedData; } int write_image(string deviceSerial, string fileName) { vector<uint32_t> data; try { data = read_bit_file(fileName); } catch (std::exception &e) { cout << concol::RED << "Unable to open file." << concol::RESET << endl; return -1; } write_flash(deviceSerial.c_str(), EPROM_USER_IMAGE_ADDR, data.data(), data.size()); //verify the write vector<uint32_t> buffer(256); uint32_t numWords = 256; cout << "Verifying:" << endl; for (size_t ct=0; ct < data.size(); ct+=256) { if (ct % 1000 == 0) { cout << "\r" << 100*ct/data.size() << "%" << flush; } if (std::distance(data.begin() + ct, data.end()) < 256) { numWords = std::distance(data.begin() + ct, data.end()); } read_flash(deviceSerial.c_str(), EPROM_USER_IMAGE_ADDR + 4*ct, numWords, buffer.data()); if (!std::equal(buffer.begin(), buffer.begin()+numWords, data.begin()+ct)) { cout << endl << "Mismatched data at offset " << hexn<6> << ct << endl; return -2; } } cout << "\r100%" << endl; return reset(deviceSerial.c_str(), static_cast<int>(APS_RESET_MODE_STAT::RECONFIG_EPROM)); } int main (int argc, char* argv[]) { concol::concolinit(); cout << concol::RED << "BBN AP2 Programming Executable" << concol::RESET << endl; int dbgLevel = 4; set_logging_level(dbgLevel); string bitFile(argv[1]); cout << concol::RED << "Attempting to initialize libaps" << concol::RESET << endl; init(); set_log("stdout"); int numDevices = get_numDevices(); cout << concol::RED << numDevices << " APS device" << (numDevices > 1 ? "s": "") << " found" << concol::RESET << endl; if (numDevices < 1) return 0; cout << concol::RED << "Attempting to get serials" << concol::RESET << endl; const char ** serialBuffer = new const char*[numDevices]; get_deviceSerials(serialBuffer); for (int cnt=0; cnt < numDevices; cnt++) { cout << concol::RED << "Device " << cnt << " serial #: " << serialBuffer[cnt] << concol::RESET << endl; } string deviceSerial; if (numDevices == 1) { deviceSerial = string(serialBuffer[0]); } else { deviceSerial = string(serialBuffer[get_device_id()]); } connect_APS(deviceSerial.c_str()); MODE mode = get_mode(); switch (mode) { case EPROM: cout << concol::RED << "Reprogramming EPROM image" << concol::RESET << endl; write_image(deviceSerial, bitFile); break; case DRAM: cout << concol::RED << "Reprogramming DRAM image" << concol::RESET << endl; program_FPGA(deviceSerial.c_str(), bitFile.c_str()); break; } disconnect_APS(deviceSerial.c_str()); delete[] serialBuffer; cout << concol::RED << "Finished!" << concol::RESET << endl; return 0; } <|endoftext|>
<commit_before>#include "Dual_Constraint_Group.hxx" #include "write_vector.hxx" #include "../set_stream_precision.hxx" void write_free_var_matrix( const boost::filesystem::path &output_dir, const std::vector<size_t> &indices, const size_t &dual_objectives_b_size, const std::vector<Dual_Constraint_Group> &dual_constraint_groups) { auto block_index(indices.begin()); for(auto &group : dual_constraint_groups) { size_t block_size(group.constraint_matrix.Height()); const boost::filesystem::path output_path( output_dir / ("free_var_matrix." + std::to_string(*block_index))); boost::filesystem::ofstream output_stream(output_path); set_stream_precision(output_stream); output_stream << block_size << " " << dual_objectives_b_size << "\n"; for(size_t row = 0; row < block_size; ++row) for(size_t column = 0; column < dual_objectives_b_size; ++column) { output_stream << group.constraint_matrix(row, column) << "\n"; } if(!output_stream.good()) { throw std::runtime_error("Error when writing to: " + output_path.string()); } ++block_index; } } <commit_msg>Write free_var_matrix_*.json<commit_after>#include "Dual_Constraint_Group.hxx" #include "write_vector.hxx" #include "../set_stream_precision.hxx" void write_free_var_matrix( const boost::filesystem::path &output_dir, const std::vector<size_t> &indices, const size_t &dual_objectives_b_size, const std::vector<Dual_Constraint_Group> &dual_constraint_groups) { auto block_index(indices.begin()); for(auto &group : dual_constraint_groups) { size_t block_size(group.constraint_matrix.Height()); const boost::filesystem::path output_path( output_dir / ("free_var_matrix_" + std::to_string(*block_index) + ".json")); boost::filesystem::ofstream output_stream(output_path); set_stream_precision(output_stream); output_stream << "[\n"; for(size_t row = 0; row < block_size; ++row) { if(row != 0) { output_stream << ",\n"; } output_stream << " [\n"; for(size_t column = 0; column < dual_objectives_b_size; ++column) { if(column != 0) { output_stream << ",\n"; } output_stream << " \"" << group.constraint_matrix(row, column) << "\""; } output_stream << "\n ]"; } output_stream << "\n]\n"; if(!output_stream.good()) { throw std::runtime_error("Error when writing to: " + output_path.string()); } ++block_index; } } <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/evaluation/CrossValidation.h> #include <shogun/machine/Machine.h> #include <shogun/evaluation/Evaluation.h> #include <shogun/evaluation/SplittingStrategy.h> #include <shogun/base/Parameter.h> #include <shogun/mathematics/Statistics.h> using namespace shogun; CCrossValidation::CCrossValidation() { init(); } CCrossValidation::~CCrossValidation() { SG_UNREF(m_machine); SG_UNREF(m_features); SG_UNREF(m_labels); SG_UNREF(m_splitting_strategy); SG_UNREF(m_evaluation_criterium); } CCrossValidation::CCrossValidation(CMachine* machine, CFeatures* features, CLabels* labels, CSplittingStrategy* splitting_strategy, CEvaluation* evaluation_criterium) { init(); m_machine=machine; m_features=features; m_labels=labels; m_splitting_strategy=splitting_strategy; m_evaluation_criterium=evaluation_criterium; SG_REF(m_machine); SG_REF(m_features); SG_REF(m_labels); SG_REF(m_splitting_strategy); SG_REF(m_evaluation_criterium); } void CCrossValidation::init() { m_machine=NULL; m_features=NULL; m_labels=NULL; m_splitting_strategy=NULL; m_evaluation_criterium=NULL; m_num_runs=1; m_conf_int_alpha=0; m_parameters->add((CSGObject**) &m_machine, "machine", "Used learning machine"); m_parameters->add((CSGObject**) &m_features, "features", "Used features"); m_parameters->add((CSGObject**) &m_labels, "labels", "Used labels"); m_parameters->add((CSGObject**) &m_splitting_strategy, "splitting_strategy", "Used splitting strategy"); m_parameters->add((CSGObject**) &m_evaluation_criterium, "evaluation_criterium", "Used evaluation criterium"); m_parameters->add(&m_num_runs, "num_runs", "Number of repetitions"); m_parameters->add(&m_conf_int_alpha, "conf_int_alpha", "alpha-value of confidence " "interval"); } Parameter* CCrossValidation::get_machine_parameters() const { return m_machine->m_parameters; } CrossValidationResult CCrossValidation::evaluate() { SGVector<float64_t> results(m_num_runs); for (index_t i=0; i<m_num_runs; ++i) results.vector[i]=evaluate_one_run(); /* construct evaluation result */ CrossValidationResult result; result.has_conf_int=m_conf_int_alpha!=0; result.conf_int_alpha=m_conf_int_alpha; if (result.has_conf_int) { result.conf_int_alpha=m_conf_int_alpha; result.mean=CStatistics::confidence_intervals_mean(results, result.conf_int_alpha, result.conf_int_low, result.conf_int_up); } else { result.mean=CStatistics::mean(results); result.conf_int_low=0; result.conf_int_up=0; } SG_FREE(results.vector); return result; } void CCrossValidation::set_conf_int_alpha(float64_t conf_int_alpha) { if (conf_int_alpha<0||conf_int_alpha>=1) { SG_ERROR("%f is an illegal alpha-value for confidence interval of " "cross-validation\n", conf_int_alpha); } m_conf_int_alpha=conf_int_alpha; } void CCrossValidation::set_num_runs(int32_t num_runs) { if (num_runs<1) SG_ERROR("%d is an illegal number of repetitions\n", num_runs); m_num_runs=num_runs; } float64_t CCrossValidation::evaluate_one_run() { index_t num_subsets=m_splitting_strategy->get_num_subsets(); float64_t* results=SG_MALLOC(float64_t, num_subsets); /* set labels to machine */ m_machine->set_labels(m_labels); /* do actual cross-validation */ for (index_t i=0; i<num_subsets; ++i) { /* set feature subset for training */ SGVector<index_t> inverse_subset_indices= m_splitting_strategy->generate_subset_inverse(i); m_features->set_subset(new CSubset(inverse_subset_indices)); /* set label subset for training (copy data before) */ SGVector<index_t> inverse_subset_indices_copy( inverse_subset_indices.vlen); memcpy(inverse_subset_indices_copy.vector, inverse_subset_indices.vector, inverse_subset_indices.vlen*sizeof(index_t)); m_labels->set_subset(new CSubset(inverse_subset_indices_copy)); /* train machine on training features */ m_machine->train(m_features); /* set feature subset for testing (subset method that stores pointer) */ SGVector<index_t> subset_indices= m_splitting_strategy->generate_subset_indices(i); m_features->set_subset(new CSubset(subset_indices)); /* apply machine to test features */ CLabels* result_labels=m_machine->apply(m_features); SG_REF(result_labels); /* set label subset for testing (copy data before) */ SGVector<index_t> subset_indices_copy(subset_indices.vlen); memcpy(subset_indices_copy.vector, subset_indices.vector, subset_indices.vlen*sizeof(index_t)); m_labels->set_subset(new CSubset(subset_indices_copy)); /* evaluate */ results[i]=m_evaluation_criterium->evaluate(result_labels, m_labels); /* clean up, reset subsets */ SG_UNREF(result_labels); m_features->remove_subset(); m_labels->remove_subset(); } /* build arithmetic mean of results */ float64_t mean=CStatistics::mean(SGVector<float64_t>(results, num_subsets)); /* clean up */ SG_FREE(results); return mean; } <commit_msg>tell machine to store model before starting x-validation<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/evaluation/CrossValidation.h> #include <shogun/machine/Machine.h> #include <shogun/evaluation/Evaluation.h> #include <shogun/evaluation/SplittingStrategy.h> #include <shogun/base/Parameter.h> #include <shogun/mathematics/Statistics.h> using namespace shogun; CCrossValidation::CCrossValidation() { init(); } CCrossValidation::~CCrossValidation() { SG_UNREF(m_machine); SG_UNREF(m_features); SG_UNREF(m_labels); SG_UNREF(m_splitting_strategy); SG_UNREF(m_evaluation_criterium); } CCrossValidation::CCrossValidation(CMachine* machine, CFeatures* features, CLabels* labels, CSplittingStrategy* splitting_strategy, CEvaluation* evaluation_criterium) { init(); m_machine=machine; m_features=features; m_labels=labels; m_splitting_strategy=splitting_strategy; m_evaluation_criterium=evaluation_criterium; SG_REF(m_machine); SG_REF(m_features); SG_REF(m_labels); SG_REF(m_splitting_strategy); SG_REF(m_evaluation_criterium); } void CCrossValidation::init() { m_machine=NULL; m_features=NULL; m_labels=NULL; m_splitting_strategy=NULL; m_evaluation_criterium=NULL; m_num_runs=1; m_conf_int_alpha=0; m_parameters->add((CSGObject**) &m_machine, "machine", "Used learning machine"); m_parameters->add((CSGObject**) &m_features, "features", "Used features"); m_parameters->add((CSGObject**) &m_labels, "labels", "Used labels"); m_parameters->add((CSGObject**) &m_splitting_strategy, "splitting_strategy", "Used splitting strategy"); m_parameters->add((CSGObject**) &m_evaluation_criterium, "evaluation_criterium", "Used evaluation criterium"); m_parameters->add(&m_num_runs, "num_runs", "Number of repetitions"); m_parameters->add(&m_conf_int_alpha, "conf_int_alpha", "alpha-value of confidence " "interval"); } Parameter* CCrossValidation::get_machine_parameters() const { return m_machine->m_parameters; } CrossValidationResult CCrossValidation::evaluate() { SGVector<float64_t> results(m_num_runs); for (index_t i=0; i<m_num_runs; ++i) results.vector[i]=evaluate_one_run(); /* construct evaluation result */ CrossValidationResult result; result.has_conf_int=m_conf_int_alpha!=0; result.conf_int_alpha=m_conf_int_alpha; if (result.has_conf_int) { result.conf_int_alpha=m_conf_int_alpha; result.mean=CStatistics::confidence_intervals_mean(results, result.conf_int_alpha, result.conf_int_low, result.conf_int_up); } else { result.mean=CStatistics::mean(results); result.conf_int_low=0; result.conf_int_up=0; } SG_FREE(results.vector); return result; } void CCrossValidation::set_conf_int_alpha(float64_t conf_int_alpha) { if (conf_int_alpha<0||conf_int_alpha>=1) { SG_ERROR("%f is an illegal alpha-value for confidence interval of " "cross-validation\n", conf_int_alpha); } m_conf_int_alpha=conf_int_alpha; } void CCrossValidation::set_num_runs(int32_t num_runs) { if (num_runs<1) SG_ERROR("%d is an illegal number of repetitions\n", num_runs); m_num_runs=num_runs; } float64_t CCrossValidation::evaluate_one_run() { index_t num_subsets=m_splitting_strategy->get_num_subsets(); float64_t* results=SG_MALLOC(float64_t, num_subsets); /* set labels to machine */ m_machine->set_labels(m_labels); /* tell machine to store model internally * (otherwise changing subset of features will kaboom the classifier) */ m_machine->set_store_model_features(true); /* do actual cross-validation */ for (index_t i=0; i<num_subsets; ++i) { /* set feature subset for training */ SGVector<index_t> inverse_subset_indices= m_splitting_strategy->generate_subset_inverse(i); m_features->set_subset(new CSubset(inverse_subset_indices)); /* set label subset for training (copy data before) */ SGVector<index_t> inverse_subset_indices_copy( inverse_subset_indices.vlen); memcpy(inverse_subset_indices_copy.vector, inverse_subset_indices.vector, inverse_subset_indices.vlen*sizeof(index_t)); m_labels->set_subset(new CSubset(inverse_subset_indices_copy)); /* train machine on training features */ m_machine->train(m_features); /* set feature subset for testing (subset method that stores pointer) */ SGVector<index_t> subset_indices= m_splitting_strategy->generate_subset_indices(i); m_features->set_subset(new CSubset(subset_indices)); /* apply machine to test features */ CLabels* result_labels=m_machine->apply(m_features); SG_REF(result_labels); /* set label subset for testing (copy data before) */ SGVector<index_t> subset_indices_copy(subset_indices.vlen); memcpy(subset_indices_copy.vector, subset_indices.vector, subset_indices.vlen*sizeof(index_t)); m_labels->set_subset(new CSubset(subset_indices_copy)); /* evaluate */ results[i]=m_evaluation_criterium->evaluate(result_labels, m_labels); /* clean up, reset subsets */ SG_UNREF(result_labels); m_features->remove_subset(); m_labels->remove_subset(); } /* build arithmetic mean of results */ float64_t mean=CStatistics::mean(SGVector<float64_t>(results, num_subsets)); /* clean up */ SG_FREE(results); return mean; } <|endoftext|>
<commit_before>// Copyright (c) 2016-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/syscoin-config.h> #endif #include <chainparams.h> #include <chainparamsbase.h> #include <logging.h> #include <util/system.h> #include <util/translation.h> #include <wallet/wallettool.h> #include <functional> const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; static void SetupWalletToolArgs() { SetupHelpOptions(gArgs); SetupChainParamsBaseOptions(); gArgs.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); gArgs.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS); gArgs.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); gArgs.AddArg("info", "Get wallet info", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); gArgs.AddArg("create", "Create new wallet file", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); } static bool WalletAppInit(int argc, char* argv[]) { SetupWalletToolArgs(); std::string error_message; if (!gArgs.ParseParameters(argc, argv, error_message)) { tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message); return false; } if (argc < 2 || HelpRequested(gArgs)) { std::string usage = strprintf("%s syscoin-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n\n" + "syscoin-wallet is an offline tool for creating and interacting with Syscoin Core wallet files.\n" + "By default syscoin-wallet will act on wallets in the default mainnet wallet directory in the datadir.\n" + "To change the target wallet, use the -datadir, -wallet and -testnet/-regtest arguments.\n\n" + "Usage:\n" + " syscoin-wallet [options] <command>\n\n" + gArgs.GetHelpMessage(); tfm::format(std::cout, "%s", usage); return false; } // check for printtoconsole, allow -debug LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", gArgs.GetBoolArg("-debug", false)); if (!CheckDataDirOption()) { tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "")); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) SelectParams(gArgs.GetChainName()); return true; } int main(int argc, char* argv[]) { #ifdef WIN32 util::WinCmdLineArgs winArgs; std::tie(argc, argv) = winArgs.get(); #endif SetupEnvironment(); RandomInit(); try { if (!WalletAppInit(argc, argv)) return EXIT_FAILURE; } catch (const std::exception& e) { PrintExceptionContinue(&e, "WalletAppInit()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "WalletAppInit()"); return EXIT_FAILURE; } std::string method {}; for(int i = 1; i < argc; ++i) { if (!IsSwitchChar(argv[i][0])) { if (!method.empty()) { tfm::format(std::cerr, "Error: two methods provided (%s and %s). Only one method should be provided.\n", method, argv[i]); return EXIT_FAILURE; } method = argv[i]; } } if (method.empty()) { tfm::format(std::cerr, "No method provided. Run `syscoin-wallet -help` for valid methods.\n"); return EXIT_FAILURE; } // A name must be provided when creating a file if (method == "create" && !gArgs.IsArgSet("-wallet")) { tfm::format(std::cerr, "Wallet name must be provided when creating a new wallet.\n"); return EXIT_FAILURE; } std::string name = gArgs.GetArg("-wallet", ""); ECCVerifyHandle globalVerifyHandle; ECC_Start(); if (!WalletTool::ExecuteWalletToolFunc(method, name)) return EXIT_FAILURE; ECC_Stop(); return EXIT_SUCCESS; } <commit_msg>bitcoin-wallet: Use PACKAGE_NAME in usage help<commit_after>// Copyright (c) 2016-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/syscoin-config.h> #endif #include <chainparams.h> #include <chainparamsbase.h> #include <logging.h> #include <util/system.h> #include <util/translation.h> #include <wallet/wallettool.h> #include <functional> const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; static void SetupWalletToolArgs() { SetupHelpOptions(gArgs); SetupChainParamsBaseOptions(); gArgs.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); gArgs.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS); gArgs.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); gArgs.AddArg("info", "Get wallet info", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); gArgs.AddArg("create", "Create new wallet file", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); } static bool WalletAppInit(int argc, char* argv[]) { SetupWalletToolArgs(); std::string error_message; if (!gArgs.ParseParameters(argc, argv, error_message)) { tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message); return false; } if (argc < 2 || HelpRequested(gArgs)) { std::string usage = strprintf("%s syscoin-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n\n" + "syscoin-wallet is an offline tool for creating and interacting with " PACKAGE_NAME " wallet files.\n" + "By default syscoin-wallet will act on wallets in the default mainnet wallet directory in the datadir.\n" + "To change the target wallet, use the -datadir, -wallet and -testnet/-regtest arguments.\n\n" + "Usage:\n" + " syscoin-wallet [options] <command>\n\n" + gArgs.GetHelpMessage(); tfm::format(std::cout, "%s", usage); return false; } // check for printtoconsole, allow -debug LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", gArgs.GetBoolArg("-debug", false)); if (!CheckDataDirOption()) { tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "")); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) SelectParams(gArgs.GetChainName()); return true; } int main(int argc, char* argv[]) { #ifdef WIN32 util::WinCmdLineArgs winArgs; std::tie(argc, argv) = winArgs.get(); #endif SetupEnvironment(); RandomInit(); try { if (!WalletAppInit(argc, argv)) return EXIT_FAILURE; } catch (const std::exception& e) { PrintExceptionContinue(&e, "WalletAppInit()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "WalletAppInit()"); return EXIT_FAILURE; } std::string method {}; for(int i = 1; i < argc; ++i) { if (!IsSwitchChar(argv[i][0])) { if (!method.empty()) { tfm::format(std::cerr, "Error: two methods provided (%s and %s). Only one method should be provided.\n", method, argv[i]); return EXIT_FAILURE; } method = argv[i]; } } if (method.empty()) { tfm::format(std::cerr, "No method provided. Run `syscoin-wallet -help` for valid methods.\n"); return EXIT_FAILURE; } // A name must be provided when creating a file if (method == "create" && !gArgs.IsArgSet("-wallet")) { tfm::format(std::cerr, "Wallet name must be provided when creating a new wallet.\n"); return EXIT_FAILURE; } std::string name = gArgs.GetArg("-wallet", ""); ECCVerifyHandle globalVerifyHandle; ECC_Start(); if (!WalletTool::ExecuteWalletToolFunc(method, name)) return EXIT_FAILURE; ECC_Stop(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2012-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addrman.h" #include "test/test_bitcoin.h" #include <string> #include <boost/test/unit_test.hpp> #include "hash.h" #include "serialize.h" #include "streams.h" #include "net.h" #include "chainparams.h" using namespace std; class CAddrManSerializationMock : public CAddrMan { public: virtual void Serialize(CDataStream& s, int nType, int nVersionDummy) const = 0; }; class CAddrManUncorrupted : public CAddrManSerializationMock { public: void Serialize(CDataStream& s, int nType, int nVersionDummy) const { CAddrMan::Serialize(s, nType, nVersionDummy); } }; class CAddrManCorrupted : public CAddrManSerializationMock { public: void Serialize(CDataStream& s, int nType, int nVersionDummy) const { // Produces corrupt output that claims addrman has 20 addrs when it only has one addr. unsigned char nVersion = 1; s << nVersion; s << ((unsigned char)32); s << nKey; s << 10; // nNew s << 10; // nTried int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30); s << nUBuckets; CAddress addr = CAddress(CService("252.1.1.1", 7777)); CAddrInfo info = CAddrInfo(addr, CNetAddr("252.2.2.2")); s << info; } }; CDataStream AddrmanToStream(CAddrManSerializationMock& addrman) { CDataStream ssPeersIn(SER_DISK, CLIENT_VERSION); ssPeersIn << FLATDATA(Params().MessageStart()); ssPeersIn << addrman; std::string str = ssPeersIn.str(); vector<unsigned char> vchData(str.begin(), str.end()); return CDataStream(vchData, SER_DISK, CLIENT_VERSION); } BOOST_FIXTURE_TEST_SUITE(net_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(caddrdb_read) { CAddrManUncorrupted addrmanUncorrupted; CService addr1 = CService("250.7.1.1", 8333); CService addr2 = CService("250.7.2.2", 9999); CService addr3 = CService("250.7.3.3", 9999); // Add three addresses to new table. addrmanUncorrupted.Add(CAddress(addr1), CService("252.5.1.1", 8333)); addrmanUncorrupted.Add(CAddress(addr2), CService("252.5.1.1", 8333)); addrmanUncorrupted.Add(CAddress(addr3), CService("252.5.1.1", 8333)); // Test that the de-serialization does not throw an exception. CDataStream ssPeers1 = AddrmanToStream(addrmanUncorrupted); bool exceptionThrown = false; CAddrMan addrman1; BOOST_CHECK(addrman1.size() == 0); try { unsigned char pchMsgTmp[4]; ssPeers1 >> FLATDATA(pchMsgTmp); ssPeers1 >> addrman1; } catch (const std::exception& e) { exceptionThrown = true; } BOOST_CHECK(addrman1.size() == 3); BOOST_CHECK(exceptionThrown == false); // Test that CAddrDB::Read creates an addrman with the correct number of addrs. CDataStream ssPeers2 = AddrmanToStream(addrmanUncorrupted); CAddrMan addrman2; CAddrDB adb; BOOST_CHECK(addrman2.size() == 0); adb.Read(addrman2, ssPeers2); BOOST_CHECK(addrman2.size() == 3); } BOOST_AUTO_TEST_CASE(caddrdb_read_corrupted) { CAddrManCorrupted addrmanCorrupted; // Test that the de-serialization of corrupted addrman throws an exception. CDataStream ssPeers1 = AddrmanToStream(addrmanCorrupted); bool exceptionThrown = false; CAddrMan addrman1; BOOST_CHECK(addrman1.size() == 0); try { unsigned char pchMsgTmp[4]; ssPeers1 >> FLATDATA(pchMsgTmp); ssPeers1 >> addrman1; } catch (const std::exception& e) { exceptionThrown = true; } // Even through de-serialization failed adddrman is not left in a clean state. BOOST_CHECK(addrman1.size() == 1); BOOST_CHECK(exceptionThrown); // Test that CAddrDB::Read leaves addrman in a clean state if de-serialization fails. CDataStream ssPeers2 = AddrmanToStream(addrmanCorrupted); CAddrMan addrman2; CAddrDB adb; BOOST_CHECK(addrman2.size() == 0); adb.Read(addrman2, ssPeers2); BOOST_CHECK(addrman2.size() == 0); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Fix typo adddrman to addrman as requested in #8070<commit_after>// Copyright (c) 2012-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addrman.h" #include "test/test_bitcoin.h" #include <string> #include <boost/test/unit_test.hpp> #include "hash.h" #include "serialize.h" #include "streams.h" #include "net.h" #include "chainparams.h" using namespace std; class CAddrManSerializationMock : public CAddrMan { public: virtual void Serialize(CDataStream& s, int nType, int nVersionDummy) const = 0; }; class CAddrManUncorrupted : public CAddrManSerializationMock { public: void Serialize(CDataStream& s, int nType, int nVersionDummy) const { CAddrMan::Serialize(s, nType, nVersionDummy); } }; class CAddrManCorrupted : public CAddrManSerializationMock { public: void Serialize(CDataStream& s, int nType, int nVersionDummy) const { // Produces corrupt output that claims addrman has 20 addrs when it only has one addr. unsigned char nVersion = 1; s << nVersion; s << ((unsigned char)32); s << nKey; s << 10; // nNew s << 10; // nTried int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30); s << nUBuckets; CAddress addr = CAddress(CService("252.1.1.1", 7777)); CAddrInfo info = CAddrInfo(addr, CNetAddr("252.2.2.2")); s << info; } }; CDataStream AddrmanToStream(CAddrManSerializationMock& addrman) { CDataStream ssPeersIn(SER_DISK, CLIENT_VERSION); ssPeersIn << FLATDATA(Params().MessageStart()); ssPeersIn << addrman; std::string str = ssPeersIn.str(); vector<unsigned char> vchData(str.begin(), str.end()); return CDataStream(vchData, SER_DISK, CLIENT_VERSION); } BOOST_FIXTURE_TEST_SUITE(net_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(caddrdb_read) { CAddrManUncorrupted addrmanUncorrupted; CService addr1 = CService("250.7.1.1", 8333); CService addr2 = CService("250.7.2.2", 9999); CService addr3 = CService("250.7.3.3", 9999); // Add three addresses to new table. addrmanUncorrupted.Add(CAddress(addr1), CService("252.5.1.1", 8333)); addrmanUncorrupted.Add(CAddress(addr2), CService("252.5.1.1", 8333)); addrmanUncorrupted.Add(CAddress(addr3), CService("252.5.1.1", 8333)); // Test that the de-serialization does not throw an exception. CDataStream ssPeers1 = AddrmanToStream(addrmanUncorrupted); bool exceptionThrown = false; CAddrMan addrman1; BOOST_CHECK(addrman1.size() == 0); try { unsigned char pchMsgTmp[4]; ssPeers1 >> FLATDATA(pchMsgTmp); ssPeers1 >> addrman1; } catch (const std::exception& e) { exceptionThrown = true; } BOOST_CHECK(addrman1.size() == 3); BOOST_CHECK(exceptionThrown == false); // Test that CAddrDB::Read creates an addrman with the correct number of addrs. CDataStream ssPeers2 = AddrmanToStream(addrmanUncorrupted); CAddrMan addrman2; CAddrDB adb; BOOST_CHECK(addrman2.size() == 0); adb.Read(addrman2, ssPeers2); BOOST_CHECK(addrman2.size() == 3); } BOOST_AUTO_TEST_CASE(caddrdb_read_corrupted) { CAddrManCorrupted addrmanCorrupted; // Test that the de-serialization of corrupted addrman throws an exception. CDataStream ssPeers1 = AddrmanToStream(addrmanCorrupted); bool exceptionThrown = false; CAddrMan addrman1; BOOST_CHECK(addrman1.size() == 0); try { unsigned char pchMsgTmp[4]; ssPeers1 >> FLATDATA(pchMsgTmp); ssPeers1 >> addrman1; } catch (const std::exception& e) { exceptionThrown = true; } // Even through de-serialization failed addrman is not left in a clean state. BOOST_CHECK(addrman1.size() == 1); BOOST_CHECK(exceptionThrown); // Test that CAddrDB::Read leaves addrman in a clean state if de-serialization fails. CDataStream ssPeers2 = AddrmanToStream(addrmanCorrupted); CAddrMan addrman2; CAddrDB adb; BOOST_CHECK(addrman2.size() == 0); adb.Read(addrman2, ssPeers2); BOOST_CHECK(addrman2.size() == 0); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "../test.h" #include "jsmn/jsmn.h" static void GenStat(Stat* s, const char* json, const jsmntok_t* tokens, int count) { for (int i = 0; i < count; i++) switch (tokens[i].type) { case JSMN_OBJECT: s->memberCount += tokens[i].size; s->objectCount++; break; case JSMN_ARRAY: s->elementCount += tokens[i].size; s->arrayCount++; break; case JSMN_STRING: s->stringCount++; s->stringLength += tokens[i].end - tokens[i].start; break; case JSMN_PRIMITIVE: if (json[tokens[i].start] == 't') s->trueCount++; else if (json[tokens[i].start] == 'f') s->falseCount++; else if (json[tokens[i].start] == 'n') s->nullCount++; else s->numberCount++; break; default:; } } static void ParseNumbers(const char* json, const jsmntok_t* tokens, int count) { for (int i = 0; i < count; i++) if (tokens[i].type == JSMN_PRIMITIVE) { const char* s = json + tokens[i].start; if (*s != 't' && *s != 'f' && *s != 'n') atof(s); } } class JsmnParseResult : public ParseResultBase { public: JsmnParseResult() : json(), tokens() {} ~JsmnParseResult() { free(json); free(tokens); } char* json; jsmntok_t* tokens; int count; }; class JsmnTest : public TestBase { public: #if TEST_INFO virtual const char* GetName() const { return "jsmn (C)"; } virtual const char* GetFilename() const { return __FILE__; } #endif #if TEST_PARSE virtual ParseResultBase* Parse(const char* json, size_t length) const { JsmnParseResult* pr = new JsmnParseResult; jsmn_parser parser; jsmn_init(&parser); pr->count = jsmn_parse(&parser, json, length, NULL, 0); if (pr->count < 0) { printf("Error %d\n", pr->count); delete pr; return 0; } jsmn_init(&parser); pr->tokens = (jsmntok_t*)malloc(pr->count * sizeof(jsmntok_t)); int error = jsmn_parse(&parser, json, length, pr->tokens, pr->count); if (error < 0) { printf("Error %d\n", error); delete pr; return 0; } // need a copy of JSON in order to determine the types pr->json = strdup(json); // Since jsmn does not parse numbers, emulate here in order to compare with other parsers. ParseNumbers(json, pr->tokens, pr->count); return pr; } #endif #if TEST_STATISTICS virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const { const JsmnParseResult* pr = static_cast<const JsmnParseResult*>(parseResult); memset(stat, 0, sizeof(Stat)); GenStat(stat, pr->json, pr->tokens, pr->count); return true; } #endif #if TEST_CONFORMANCE virtual bool ParseDouble(const char* json, double* d) const { jsmn_parser parser; jsmn_init(&parser); jsmntok_t tokens[2]; int count = jsmn_parse(&parser, json, strlen(json), tokens, 2); if (count == 2 && tokens[0].type == JSMN_ARRAY && tokens[0].size == 1 && tokens[1].type == JSMN_PRIMITIVE) { *d = atof(json + tokens[1].start); return true; } return false; } virtual bool ParseString(const char* json, std::string& s) const { jsmn_parser parser; jsmn_init(&parser); jsmntok_t tokens[2]; int count = jsmn_parse(&parser, json, strlen(json), tokens, 2); if (count == 2 && tokens[0].type == JSMN_ARRAY && tokens[0].size == 1 && tokens[1].type == JSMN_PRIMITIVE) { s = std::string(json + tokens[1].start, json + tokens[1].end); return true; } return false; } #endif }; REGISTER_TEST(JsmnTest); <commit_msg>Fix jsmn string validation test<commit_after>#include "../test.h" #include "jsmn/jsmn.h" static void GenStat(Stat* s, const char* json, const jsmntok_t* tokens, int count) { for (int i = 0; i < count; i++) switch (tokens[i].type) { case JSMN_OBJECT: s->memberCount += tokens[i].size; s->objectCount++; break; case JSMN_ARRAY: s->elementCount += tokens[i].size; s->arrayCount++; break; case JSMN_STRING: s->stringCount++; s->stringLength += tokens[i].end - tokens[i].start; break; case JSMN_PRIMITIVE: if (json[tokens[i].start] == 't') s->trueCount++; else if (json[tokens[i].start] == 'f') s->falseCount++; else if (json[tokens[i].start] == 'n') s->nullCount++; else s->numberCount++; break; default:; } } static void ParseNumbers(const char* json, const jsmntok_t* tokens, int count) { for (int i = 0; i < count; i++) if (tokens[i].type == JSMN_PRIMITIVE) { const char* s = json + tokens[i].start; if (*s != 't' && *s != 'f' && *s != 'n') atof(s); } } class JsmnParseResult : public ParseResultBase { public: JsmnParseResult() : json(), tokens() {} ~JsmnParseResult() { free(json); free(tokens); } char* json; jsmntok_t* tokens; int count; }; class JsmnTest : public TestBase { public: #if TEST_INFO virtual const char* GetName() const { return "jsmn (C)"; } virtual const char* GetFilename() const { return __FILE__; } #endif #if TEST_PARSE virtual ParseResultBase* Parse(const char* json, size_t length) const { JsmnParseResult* pr = new JsmnParseResult; jsmn_parser parser; jsmn_init(&parser); pr->count = jsmn_parse(&parser, json, length, NULL, 0); if (pr->count < 0) { printf("Error %d\n", pr->count); delete pr; return 0; } jsmn_init(&parser); pr->tokens = (jsmntok_t*)malloc(pr->count * sizeof(jsmntok_t)); int error = jsmn_parse(&parser, json, length, pr->tokens, pr->count); if (error < 0) { printf("Error %d\n", error); delete pr; return 0; } // need a copy of JSON in order to determine the types pr->json = strdup(json); // Since jsmn does not parse numbers, emulate here in order to compare with other parsers. ParseNumbers(json, pr->tokens, pr->count); return pr; } #endif #if TEST_STATISTICS virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const { const JsmnParseResult* pr = static_cast<const JsmnParseResult*>(parseResult); memset(stat, 0, sizeof(Stat)); GenStat(stat, pr->json, pr->tokens, pr->count); return true; } #endif #if TEST_CONFORMANCE virtual bool ParseDouble(const char* json, double* d) const { jsmn_parser parser; jsmn_init(&parser); jsmntok_t tokens[2]; int count = jsmn_parse(&parser, json, strlen(json), tokens, 2); if (count == 2 && tokens[0].type == JSMN_ARRAY && tokens[0].size == 1 && tokens[1].type == JSMN_PRIMITIVE) { *d = atof(json + tokens[1].start); return true; } return false; } virtual bool ParseString(const char* json, std::string& s) const { jsmn_parser parser; jsmn_init(&parser); jsmntok_t tokens[2]; int count = jsmn_parse(&parser, json, strlen(json), tokens, 2); if (count == 2 && tokens[0].type == JSMN_ARRAY && tokens[0].size == 1 && tokens[1].type == JSMN_STRING) { s = std::string(json + tokens[1].start, json + tokens[1].end); return true; } return false; } #endif }; REGISTER_TEST(JsmnTest); <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QLibraryInfo> #include <QDir> #include <QProcess> #include <QDebug> class tst_examples : public QObject { Q_OBJECT public: tst_examples(); private slots: void examples_data(); void examples(); void namingConvention(); private: QString qmlruntime; QStringList excludedDirs; void namingConvention(const QDir &); QStringList findQmlFiles(const QDir &); }; tst_examples::tst_examples() { QString binaries = QLibraryInfo::location(QLibraryInfo::BinariesPath); #if defined(Q_WS_MAC) qmlruntime = QDir(binaries).absoluteFilePath("qml.app/Contents/MacOS/qml"); #elif defined(Q_WS_WIN) qmlruntime = QDir(binaries).absoluteFilePath("qml.exe"); #else qmlruntime = QDir(binaries).absoluteFilePath("qml"); #endif // Add directories you want excluded here excludedDirs << "examples/declarative/extending"; excludedDirs << "examples/declarative/plugins"; excludedDirs << "examples/declarative/proxywidgets"; excludedDirs << "examples/declarative/gestures"; } /* This tests that the demos and examples follow the naming convention required to have them tested by the examples() test. */ void tst_examples::namingConvention(const QDir &d) { for (int ii = 0; ii < excludedDirs.count(); ++ii) { QString s = QDir::toNativeSeparators(excludedDirs.at(ii)); if (d.absolutePath().endsWith(s)) return; } QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"), QDir::Files); bool seenQml = !files.isEmpty(); bool seenLowercase = false; foreach (const QString &file, files) { if (file.at(0).isLower()) seenLowercase = true; } if (!seenQml) { QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); namingConvention(sub); } } else if(!seenLowercase) { QTest::qFail(QString("Directory " + d.absolutePath() + " violates naming convention").toLatin1().constData(), __FILE__, __LINE__); } } void tst_examples::namingConvention() { QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath); QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath); namingConvention(QDir(examples)); namingConvention(QDir(demos)); } QStringList tst_examples::findQmlFiles(const QDir &d) { for (int ii = 0; ii < excludedDirs.count(); ++ii) { QString s = QDir::toNativeSeparators(excludedDirs.at(ii)); if (d.absolutePath().endsWith(s)) return QStringList(); } QStringList rv; QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"), QDir::Files); foreach (const QString &file, files) { if (file.at(0).isLower()) { rv << d.absoluteFilePath(file); } } QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); rv << findQmlFiles(sub); } return rv; } /* This test runs all the examples in the declarative UI source tree and ensures that they start and exit cleanly. Examples are any .qml files under the examples/ or demos/ directory that start with a lower case letter. */ void tst_examples::examples_data() { QTest::addColumn<QString>("file"); QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath); QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath); QString snippets = QLatin1String(SRCDIR) + "/../../../../doc/src/snippets/"; QStringList files; files << findQmlFiles(QDir(examples)); files << findQmlFiles(QDir(demos)); files << findQmlFiles(QDir(snippets)); foreach (const QString &file, files) QTest::newRow(file.toLatin1().constData()) << file; } void tst_examples::examples() { QFETCH(QString, file); QFileInfo fi(file); QFileInfo dir(fi.path()); QString script = SRCDIR "/data/"+dir.baseName()+"/"+fi.baseName(); QFileInfo testdata(script+".qml"); QStringList arguments; arguments << "-script" << (testdata.exists() ? script : QLatin1String(SRCDIR "/data/dummytest")) << "-scriptopts" << "play,testerror,exitoncomplete,exitonfailure" << file; #ifdef Q_WS_QWS arguments << "-qws"; #endif QProcess p; p.start(qmlruntime, arguments); QVERIFY(p.waitForFinished()); if (p.exitStatus() != QProcess::NormalExit || p.exitCode() != 0) qWarning() << p.readAllStandardOutput() << p.readAllStandardError(); QCOMPARE(p.exitStatus(), QProcess::NormalExit); QCOMPARE(p.exitCode(), 0); } QTEST_MAIN(tst_examples) #include "tst_examples.moc" <commit_msg>Fix declarative examples autotest, avoid using native separators<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QLibraryInfo> #include <QDir> #include <QProcess> #include <QDebug> class tst_examples : public QObject { Q_OBJECT public: tst_examples(); private slots: void examples_data(); void examples(); void namingConvention(); private: QString qmlruntime; QStringList excludedDirs; void namingConvention(const QDir &); QStringList findQmlFiles(const QDir &); }; tst_examples::tst_examples() { QString binaries = QLibraryInfo::location(QLibraryInfo::BinariesPath); #if defined(Q_WS_MAC) qmlruntime = QDir(binaries).absoluteFilePath("qml.app/Contents/MacOS/qml"); #elif defined(Q_WS_WIN) qmlruntime = QDir(binaries).absoluteFilePath("qml.exe"); #else qmlruntime = QDir(binaries).absoluteFilePath("qml"); #endif // Add directories you want excluded here excludedDirs << "examples/declarative/extending"; excludedDirs << "examples/declarative/plugins"; excludedDirs << "examples/declarative/proxywidgets"; excludedDirs << "examples/declarative/gestures"; } /* This tests that the demos and examples follow the naming convention required to have them tested by the examples() test. */ void tst_examples::namingConvention(const QDir &d) { for (int ii = 0; ii < excludedDirs.count(); ++ii) { QString s = excludedDirs.at(ii); if (d.absolutePath().endsWith(s)) return; } QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"), QDir::Files); bool seenQml = !files.isEmpty(); bool seenLowercase = false; foreach (const QString &file, files) { if (file.at(0).isLower()) seenLowercase = true; } if (!seenQml) { QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); namingConvention(sub); } } else if(!seenLowercase) { QTest::qFail(QString("Directory " + d.absolutePath() + " violates naming convention").toLatin1().constData(), __FILE__, __LINE__); } } void tst_examples::namingConvention() { QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath); QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath); namingConvention(QDir(examples)); namingConvention(QDir(demos)); } QStringList tst_examples::findQmlFiles(const QDir &d) { for (int ii = 0; ii < excludedDirs.count(); ++ii) { QString s = excludedDirs.at(ii); if (d.absolutePath().endsWith(s)) return QStringList(); } QStringList rv; QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"), QDir::Files); foreach (const QString &file, files) { if (file.at(0).isLower()) { rv << d.absoluteFilePath(file); } } QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); rv << findQmlFiles(sub); } return rv; } /* This test runs all the examples in the declarative UI source tree and ensures that they start and exit cleanly. Examples are any .qml files under the examples/ or demos/ directory that start with a lower case letter. */ void tst_examples::examples_data() { QTest::addColumn<QString>("file"); QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath); QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath); QString snippets = QLatin1String(SRCDIR) + "/../../../../doc/src/snippets/"; QStringList files; files << findQmlFiles(QDir(examples)); files << findQmlFiles(QDir(demos)); files << findQmlFiles(QDir(snippets)); foreach (const QString &file, files) QTest::newRow(file.toLatin1().constData()) << file; } void tst_examples::examples() { QFETCH(QString, file); QFileInfo fi(file); QFileInfo dir(fi.path()); QString script = SRCDIR "/data/"+dir.baseName()+"/"+fi.baseName(); QFileInfo testdata(script+".qml"); QStringList arguments; arguments << "-script" << (testdata.exists() ? script : QLatin1String(SRCDIR "/data/dummytest")) << "-scriptopts" << "play,testerror,exitoncomplete,exitonfailure" << file; #ifdef Q_WS_QWS arguments << "-qws"; #endif QProcess p; p.start(qmlruntime, arguments); QVERIFY(p.waitForFinished()); if (p.exitStatus() != QProcess::NormalExit || p.exitCode() != 0) qWarning() << p.readAllStandardOutput() << p.readAllStandardError(); QCOMPARE(p.exitStatus(), QProcess::NormalExit); QCOMPARE(p.exitCode(), 0); } QTEST_MAIN(tst_examples) #include "tst_examples.moc" <|endoftext|>
<commit_before>#include <cppunit/extensions/HelperMacros.h> #include "BEdge.hpp" class BEdgeTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(BEdgeTest); CPPUNIT_TEST(testPointGetters); CPPUNIT_TEST(testIsAPoint); CPPUNIT_TEST(testAreaPredicates); CPPUNIT_TEST(testProjComputation); CPPUNIT_TEST(testComparisonWithPoint); CPPUNIT_TEST_SUITE_END(); private: BEdge* simpleEdge; BEdge* pointEdge; BEdge* pointEdge2; BEdge* simpleEdge2; BEdge* longEdge; public: void setUp() { std::vector<double> x; BVect a(1, 10, x); BVect b(3, 8, x); BVect c(0, 0, x); BVect d(5, 7, x); BVect e(4, 6, x); simpleEdge = new BEdge(a, b); pointEdge = new BEdge(c); pointEdge2 = new BEdge(c, c); simpleEdge2 = new BEdge(d, e); longEdge = new BEdge(a, e); } void tearDown() { delete simpleEdge; delete pointEdge; delete pointEdge2; delete simpleEdge2; delete longEdge; } void testPointGetters() { CPPUNIT_ASSERT(simpleEdge->leftPoint().z1() == 1); CPPUNIT_ASSERT(simpleEdge->leftPoint().z2() == 10); CPPUNIT_ASSERT(simpleEdge->rightPoint().z1() == 3); CPPUNIT_ASSERT(simpleEdge->rightPoint().z2() == 8); CPPUNIT_ASSERT(pointEdge->leftPoint().z1() == 0); CPPUNIT_ASSERT(pointEdge->leftPoint().z2() == 0); CPPUNIT_ASSERT(pointEdge->rightPoint().z1() == 0); CPPUNIT_ASSERT(pointEdge->rightPoint().z2() == 0); CPPUNIT_ASSERT(pointEdge2->leftPoint().z1() == 0); CPPUNIT_ASSERT(pointEdge2->leftPoint().z2() == 0); CPPUNIT_ASSERT(pointEdge2->rightPoint().z1() == 0); CPPUNIT_ASSERT(pointEdge2->rightPoint().z2() == 0); } void testIsAPoint() { CPPUNIT_ASSERT(!simpleEdge->isAPoint()); CPPUNIT_ASSERT(pointEdge->isAPoint()); CPPUNIT_ASSERT(pointEdge2->isAPoint()); } void testAreaPredicates() { CPPUNIT_ASSERT(simpleEdge->isInA1AreaOf(*simpleEdge2)); CPPUNIT_ASSERT(!simpleEdge->isInA2AreaOf(*simpleEdge2)); CPPUNIT_ASSERT(!simpleEdge->isInA1AreaOf(*pointEdge)); CPPUNIT_ASSERT(!simpleEdge->isInA2AreaOf(*pointEdge)); CPPUNIT_ASSERT(!simpleEdge2->isInA1AreaOf(*simpleEdge)); CPPUNIT_ASSERT(simpleEdge2->isInA2AreaOf(*simpleEdge)); CPPUNIT_ASSERT(!simpleEdge2->isInA1AreaOf(*pointEdge)); CPPUNIT_ASSERT(!simpleEdge2->isInA2AreaOf(*pointEdge)); CPPUNIT_ASSERT(!pointEdge->isInA1AreaOf(*simpleEdge)); CPPUNIT_ASSERT(!pointEdge->isInA2AreaOf(*simpleEdge)); CPPUNIT_ASSERT(!pointEdge->isInA1AreaOf(*simpleEdge2)); CPPUNIT_ASSERT(!pointEdge->isInA2AreaOf(*simpleEdge2)); } void testProjComputation() { std::vector<double> x; BVect zero(0, 0, x); BVect a(0, 9, x); BVect b(3, 5, x); BVect c(2, 8, x); std::pair<double, double> pz = longEdge->computeLambdasWithPoint(zero); std::pair<double, double> pa = longEdge->computeLambdasWithPoint(a); std::pair<double, double> pb = longEdge->computeLambdasWithPoint(b); std::pair<double, double> pc = longEdge->computeLambdasWithPoint(c); CPPUNIT_ASSERT(pz.first == 1); CPPUNIT_ASSERT(pz.second == 0); CPPUNIT_ASSERT(pa.first == 1); CPPUNIT_ASSERT(pa.second == 0.75); CPPUNIT_ASSERT(pb.first == 1.0/3.0); CPPUNIT_ASSERT(pb.second == 0); CPPUNIT_ASSERT(pc.first == 2.0/3.0); CPPUNIT_ASSERT(pc.second == 0.5); } void testComparisonWithPoint() { std::vector<double> x; BVect zero(0, 0, x); BEdge bz(zero); BVect a(0, 9, x); BEdge ba(a); BVect b(3, 5, x); BEdge bb(b); BVect c(2, 8, x); BEdge bc(c); BEdge left; BEdge right; DominanceStatus dsz = longEdge->compareWithPoint(bz, left, right); CPPUNIT_ASSERT(dsz == DominanceStatus::B_DOM_A); DominanceStatus dsa = longEdge->compareWithPoint(ba, left, right); CPPUNIT_ASSERT(dsa == DominanceStatus::B_PART_DOM_A); DominanceStatus dsb = longEdge->compareWithPoint(bb, left, right); CPPUNIT_ASSERT(dsb == DominanceStatus::B_PART_DOM_A); DominanceStatus dsc = longEdge->compareWithPoint(bc, left, right); CPPUNIT_ASSERT(dsc == DominanceStatus::B_PART_DOM_A); } }; CPPUNIT_TEST_SUITE_REGISTRATION(BEdgeTest); <commit_msg>BEdge : Complete test for comparisons with points<commit_after>#include <cppunit/extensions/HelperMacros.h> #include "BEdge.hpp" class BEdgeTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(BEdgeTest); CPPUNIT_TEST(testPointGetters); CPPUNIT_TEST(testIsAPoint); CPPUNIT_TEST(testAreaPredicates); CPPUNIT_TEST(testProjComputation); CPPUNIT_TEST(testComparisonWithPoint); CPPUNIT_TEST_SUITE_END(); private: BEdge* simpleEdge; BEdge* pointEdge; BEdge* pointEdge2; BEdge* simpleEdge2; BEdge* longEdge; public: void setUp() { std::vector<double> x; BVect a(1, 10, x); BVect b(3, 8, x); BVect c(0, 0, x); BVect d(5, 7, x); BVect e(4, 6, x); simpleEdge = new BEdge(a, b); pointEdge = new BEdge(c); pointEdge2 = new BEdge(c, c); simpleEdge2 = new BEdge(d, e); longEdge = new BEdge(a, e); } void tearDown() { delete simpleEdge; delete pointEdge; delete pointEdge2; delete simpleEdge2; delete longEdge; } void testPointGetters() { CPPUNIT_ASSERT(simpleEdge->leftPoint().z1() == 1); CPPUNIT_ASSERT(simpleEdge->leftPoint().z2() == 10); CPPUNIT_ASSERT(simpleEdge->rightPoint().z1() == 3); CPPUNIT_ASSERT(simpleEdge->rightPoint().z2() == 8); CPPUNIT_ASSERT(pointEdge->leftPoint().z1() == 0); CPPUNIT_ASSERT(pointEdge->leftPoint().z2() == 0); CPPUNIT_ASSERT(pointEdge->rightPoint().z1() == 0); CPPUNIT_ASSERT(pointEdge->rightPoint().z2() == 0); CPPUNIT_ASSERT(pointEdge2->leftPoint().z1() == 0); CPPUNIT_ASSERT(pointEdge2->leftPoint().z2() == 0); CPPUNIT_ASSERT(pointEdge2->rightPoint().z1() == 0); CPPUNIT_ASSERT(pointEdge2->rightPoint().z2() == 0); } void testIsAPoint() { CPPUNIT_ASSERT(!simpleEdge->isAPoint()); CPPUNIT_ASSERT(pointEdge->isAPoint()); CPPUNIT_ASSERT(pointEdge2->isAPoint()); } void testAreaPredicates() { CPPUNIT_ASSERT(simpleEdge->isInA1AreaOf(*simpleEdge2)); CPPUNIT_ASSERT(!simpleEdge->isInA2AreaOf(*simpleEdge2)); CPPUNIT_ASSERT(!simpleEdge->isInA1AreaOf(*pointEdge)); CPPUNIT_ASSERT(!simpleEdge->isInA2AreaOf(*pointEdge)); CPPUNIT_ASSERT(!simpleEdge2->isInA1AreaOf(*simpleEdge)); CPPUNIT_ASSERT(simpleEdge2->isInA2AreaOf(*simpleEdge)); CPPUNIT_ASSERT(!simpleEdge2->isInA1AreaOf(*pointEdge)); CPPUNIT_ASSERT(!simpleEdge2->isInA2AreaOf(*pointEdge)); CPPUNIT_ASSERT(!pointEdge->isInA1AreaOf(*simpleEdge)); CPPUNIT_ASSERT(!pointEdge->isInA2AreaOf(*simpleEdge)); CPPUNIT_ASSERT(!pointEdge->isInA1AreaOf(*simpleEdge2)); CPPUNIT_ASSERT(!pointEdge->isInA2AreaOf(*simpleEdge2)); } void testProjComputation() { std::vector<double> x; BVect zero(0, 0, x); BVect a(0, 9, x); BVect b(3, 5, x); BVect c(2, 8, x); std::pair<double, double> pz = longEdge->computeLambdasWithPoint(zero); std::pair<double, double> pa = longEdge->computeLambdasWithPoint(a); std::pair<double, double> pb = longEdge->computeLambdasWithPoint(b); std::pair<double, double> pc = longEdge->computeLambdasWithPoint(c); CPPUNIT_ASSERT(pz.first == 1); CPPUNIT_ASSERT(pz.second == 0); CPPUNIT_ASSERT(pa.first == 1); CPPUNIT_ASSERT(pa.second == 0.75); CPPUNIT_ASSERT(pb.first == 1.0/3.0); CPPUNIT_ASSERT(pb.second == 0); CPPUNIT_ASSERT(pc.first == 2.0/3.0); CPPUNIT_ASSERT(pc.second == 0.5); } void testComparisonWithPoint() { std::vector<double> x; BVect zero(0, 0, x); BEdge bz(zero); BVect a(0, 9, x); BEdge ba(a); BVect b(3, 5, x); BEdge bb(b); BVect c(2, 8, x); BEdge bc(c); BEdge left; BEdge right; BVect aProj2(1.75, 9, x); BVect bProj1(3, (7.0 + 1.0/3.0), x); BVect cProj1(2, (8.0 + 2.0/3.0), x); BVect cProj2(2.5, 8, x); DominanceStatus dsz = longEdge->compareWithPoint(bz, left, right); CPPUNIT_ASSERT(dsz == DominanceStatus::B_DOM_A); DominanceStatus dsa = longEdge->compareWithPoint(ba, left, right); CPPUNIT_ASSERT(dsa == DominanceStatus::B_PART_DOM_A); CPPUNIT_ASSERT(right.rightPoint() == longEdge->rightPoint()); CPPUNIT_ASSERT(right.leftPoint() == aProj2); DominanceStatus dsb = longEdge->compareWithPoint(bb, left, right); CPPUNIT_ASSERT(dsb == DominanceStatus::B_PART_DOM_A); CPPUNIT_ASSERT(left.leftPoint() == longEdge->leftPoint()); CPPUNIT_ASSERT(left.rightPoint() == bProj1); DominanceStatus dsc = longEdge->compareWithPoint(bc, left, right); CPPUNIT_ASSERT(dsc == DominanceStatus::B_PART_DOM_A); CPPUNIT_ASSERT(left.leftPoint() == longEdge->leftPoint()); CPPUNIT_ASSERT(left.rightPoint() == cProj1); CPPUNIT_ASSERT(right.leftPoint() == cProj2); CPPUNIT_ASSERT(right.rightPoint() == longEdge->rightPoint()); } }; CPPUNIT_TEST_SUITE_REGISTRATION(BEdgeTest); <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // 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. //------------------------------------------------------------------------------ //RUN: cat %s | %cling 2>&1 | FileCheck %s #include <initializer_list> auto l {'a', 'b', '\''}; *(l.begin() + 2) // CHECK: (const char *) "'" <commit_msg>Do not rely on init_list intricacies.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // 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. //------------------------------------------------------------------------------ //RUN: cat %s | %cling 2>&1 | FileCheck %s #include <vector> std::vector<char> l {'a', 'b', '\''}; *(l.begin() + 2) // CHECK: (char) ''' <|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2007 Flavio Castelli <flavio.castelli@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "xesam2strigi.h" #include "query.h" #include "XesamQLParser.h" //#include "XesamQueryBuilder.h" #include "StrigiQueryBuilder.h" using std::string; using namespace Dijon; Xesam2Strigi::Xesam2Strigi () { m_query = 0; } Xesam2Strigi::~Xesam2Strigi () { if (m_query) { delete m_query; m_query = 0; } } bool Xesam2Strigi::parse (const string& xesam_query, Type query_type) { if (query_type == QueryLanguage) { XesamQLParser xesamQlParser; StrigiQueryBuilder strigiQueryBuilder; if (m_query) { delete m_query; m_query = 0; } if (!xesamQlParser.parse ( xesam_query, strigiQueryBuilder)) return false; m_query = new Strigi::Query (strigiQueryBuilder.get_query()); return true; } else if (query_type == UserLanguage) { } } bool Xesam2Strigi::parse_file (const string& xesam_query_file, Type query_type) { if (query_type == QueryLanguage) { XesamQLParser xesamQlParser; StrigiQueryBuilder strigiQueryBuilder; if (m_query) { delete m_query; m_query = 0; } if (!xesamQlParser.parse_file ( xesam_query_file, strigiQueryBuilder)) return false; m_query = new Strigi::Query (strigiQueryBuilder.get_query()); return true; } else if (query_type == UserLanguage) { } } Strigi::Query Xesam2Strigi::query() { if (m_query) return Strigi::Query(*m_query); else return Strigi::Query(); } <commit_msg>Updated Xesam2Strigi class: now it handles also Xesam userlanguage queries<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2007 Flavio Castelli <flavio.castelli@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "xesam2strigi.h" #include "query.h" #include "xesam_ul_driver.hh" #include "XesamQLParser.h" #include "StrigiQueryBuilder.h" using std::string; using namespace Dijon; Xesam2Strigi::Xesam2Strigi () { m_query = 0; } Xesam2Strigi::~Xesam2Strigi () { if (m_query) { delete m_query; m_query = 0; } } bool Xesam2Strigi::parse (const string& xesam_query, Type query_type) { if (query_type == QueryLanguage) { XesamQLParser xesamQlParser; StrigiQueryBuilder strigiQueryBuilder; if (m_query) { delete m_query; m_query = 0; } if (!xesamQlParser.parse ( xesam_query, strigiQueryBuilder)) return false; m_query = new Strigi::Query (strigiQueryBuilder.get_query()); return true; } else if (query_type == UserLanguage) { printf ("NOT YET IMPLEMENTED!\n"); return false; } // it won't happen return false; } bool Xesam2Strigi::parse_file (const string& xesam_query_file, Type query_type) { if (m_query) { delete m_query; m_query = 0; } if (query_type == QueryLanguage) { XesamQLParser xesamQlParser; StrigiQueryBuilder strigiQueryBuilder; if (!xesamQlParser.parse_file ( xesam_query_file, strigiQueryBuilder)) return false; m_query = new Strigi::Query (strigiQueryBuilder.get_query()); return true; } else if (query_type == UserLanguage) { XesamUlDriver driver; if (!driver.parseFile (xesam_query_file)) return false; m_query = new Strigi::Query (*driver.query()); return true; } // it won't happen return false; } Strigi::Query Xesam2Strigi::query() { if (m_query) return Strigi::Query(*m_query); else return Strigi::Query(); } <|endoftext|>
<commit_before>#include "acmacs-base/pybind11.hh" // chart #include "acmacs-chart-2/factory-import.hh" #include "acmacs-chart-2/factory-export.hh" #include "acmacs-chart-2/chart-modify.hh" // merge #include "acmacs-chart-2/merge.hh" // ====================================================================== inline void chart_relax(acmacs::chart::ChartModify& chart, size_t number_of_dimensions, size_t number_of_optimizations, const std::string& minimum_column_basis, bool dimension_annealing, bool rough, size_t number_of_best_distinct_projections_to_keep) { using namespace acmacs::chart; if (number_of_optimizations == 0) number_of_optimizations = 100; chart.relax(number_of_optimizations_t{number_of_optimizations}, MinimumColumnBasis{minimum_column_basis}, acmacs::number_of_dimensions_t{number_of_dimensions}, use_dimension_annealing_from_bool(dimension_annealing), optimization_options{optimization_precision{rough ? optimization_precision::rough : optimization_precision::fine}}); chart.projections_modify().sort(); } inline std::string chart_info(const acmacs::chart::ChartModify& chart, size_t max_number_of_projections_to_show, bool column_bases, bool tables, bool tables_for_sera, bool antigen_dates) { using namespace acmacs::chart; const unsigned inf{(column_bases ? info_data::column_bases : 0) // | (tables ? info_data::tables : 0) // | (tables_for_sera ? info_data::tables_for_sera : 0) // | (antigen_dates ? info_data::dates : 0)}; return chart.make_info(max_number_of_projections_to_show, inf); } // ---------------------------------------------------------------------- inline void py_chart(py::module_& mdl) { using namespace pybind11::literals; using namespace acmacs::chart; py::class_<ChartModify, std::shared_ptr<ChartModify>>(mdl, "Chart") // .def(py::init([](const std::string& filename) { return std::make_shared<ChartModify>(import_from_file(filename)); }), py::doc("imports chart from a file")) .def( "make_name", [](const ChartModify& chart) { return chart.make_name(std::nullopt); }, py::doc("returns name of the chart")) .def( "make_name", [](const ChartModify& chart, size_t projection_no) { return chart.make_name(projection_no); }, "projection_no"_a, py::doc("returns name of the chart with the stress of the passed projection")) .def("description", &Chart::description, py::doc("returns chart one line description")) .def("make_info", &chart_info, "max_number_of_projections_to_show"_a = 20, "column_bases"_a = true, "tables"_a = false, "tables_for_sera"_a = false, "antigen_dates"_a = false, py::doc("returns detailed chart description")) .def("number_of_antigens", &Chart::number_of_antigens) .def("number_of_sera", &Chart::number_of_sera) .def("number_of_projections", &Chart::number_of_projections) .def( "lineage", [](const ChartModify& chart) { return *chart.lineage(); }, py::doc("returns chart lineage: VICTORIA, YAMAGATA")) .def("relax", &chart_relax, "number_of_dimensions"_a = 2, "number_of_optimizations"_a = 0, "minimum_column_basis"_a = "none", "dimension_annealing"_a = false, "rough"_a = false, "number_of_best_distinct_projections_to_keep"_a = 5, py::doc{"makes one or more antigenic maps from random starting layouts, adds new projections, projections are sorted by stress"}) .def( "projection", [](ChartModify& chart, size_t projection_no) { return chart.projection_modify(projection_no); }, "projection_no"_a = 0) // ; py::class_<ProjectionModify, std::shared_ptr<ProjectionModify>>(mdl, "Projection") // .def("stress", [](const ProjectionModify& projection, bool recalculate) { return projection.stress(recalculate ? RecalculateStress::if_necessary : RecalculateStress::no); }, "recalculate"_a = false) // ; } // ====================================================================== inline void py_merge(py::module_& mdl) { using namespace pybind11::literals; using namespace acmacs::chart; mdl.def( "merge", [](std::shared_ptr<ChartModify> chart1, std::shared_ptr<ChartModify> chart2, const std::string& merge_type, const std::string& match, bool remove_distinct) { CommonAntigensSera::match_level_t match_level{CommonAntigensSera::match_level_t::automatic}; if (match == "auto" || match == "automatic") match_level = CommonAntigensSera::match_level_t::automatic; else if (match == "strict") match_level = CommonAntigensSera::match_level_t::strict; else if (match == "relaxed") match_level = CommonAntigensSera::match_level_t::relaxed; else if (match == "ignored") match_level = CommonAntigensSera::match_level_t::ignored; else throw std::invalid_argument{fmt::format("Unrecognized \"match\": \"{}\"", match)}; projection_merge_t merge_typ{projection_merge_t::type1}; if (merge_type == "type1" || merge_type == "tables-only") merge_typ = projection_merge_t::type1; else if (merge_type == "type2" || merge_type == "incremental") merge_typ = projection_merge_t::type2; else if (merge_type == "type3") merge_typ = projection_merge_t::type3; else if (merge_type == "type4") merge_typ = projection_merge_t::type4; else if (merge_type == "type5") merge_typ = projection_merge_t::type5; else throw std::invalid_argument{fmt::format("Unrecognized \"merge_type\": \"{}\"", merge_type)}; return merge(*chart1, *chart2, MergeSettings{match_level, merge_typ, remove_distinct}); }, // "chart1"_a, "chart2"_a, "type"_a, "match"_a = "auto", "remove_distinct"_a = false, // py::doc(R"(merges two charts type: "type1" ("tables-only"), "type2" ("incremental"), "type3", "type4", "type5" see https://github.com/acorg/acmacs-chart-2/blob/master/doc/merge-types.org match: "strict", "relaxed", "ignored", "automatic" ("auto") )")); py::class_<MergeReport>(mdl, "MergeReport") ; } // py_merge // ---------------------------------------------------------------------- // https://pybind11.readthedocs.io/en/latest/faq.html#how-can-i-reduce-the-build-time PYBIND11_MODULE(acmacs, mdl) { mdl.doc() = "Acmacs backend"; py_chart(mdl); py_merge(mdl); } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>acmacs python module<commit_after>#include "acmacs-base/pybind11.hh" // chart #include "acmacs-chart-2/factory-import.hh" #include "acmacs-chart-2/factory-export.hh" #include "acmacs-chart-2/chart-modify.hh" // merge #include "acmacs-chart-2/merge.hh" // ====================================================================== inline unsigned make_info_data(size_t max_number_of_projections_to_show, bool column_bases, bool tables, bool tables_for_sera, bool antigen_dates) { using namespace acmacs::chart; return (column_bases ? info_data::column_bases : 0) // | (tables ? info_data::tables : 0) // | (tables_for_sera ? info_data::tables_for_sera : 0) // | (antigen_dates ? info_data::dates : 0); } // ---------------------------------------------------------------------- inline acmacs::chart::ChartClone::clone_data clone_type(const std::string& type) { using namespace acmacs::chart; if (type == "titers") return ChartClone::clone_data::titers; else if (type == "projections") return ChartClone::clone_data::projections; else if (type == "plot_spec") return ChartClone::clone_data::plot_spec; else if (type == "projections_plot_spec") return ChartClone::clone_data::projections_plot_spec; else throw std::invalid_argument{fmt::format("Unrecognized clone \"type\": \"{}\"", type)}; } // ---------------------------------------------------------------------- inline void py_chart(py::module_& mdl) { using namespace pybind11::literals; using namespace acmacs::chart; py::class_<ChartModify, std::shared_ptr<ChartModify>>(mdl, "Chart") // .def(py::init([](const std::string& filename) { return std::make_shared<ChartModify>(import_from_file(filename)); }), py::doc("imports chart from a file")) .def( "clone", // [](ChartModify& chart, const std::string& type) { return std::make_shared<ChartClone>(chart, clone_type(type)); }, // "type"_a = "titers", // py::doc(R"(type: "titers", "projections", "plot_spec", "projections_plot_spec")")) // .def( "make_name", // [](const ChartModify& chart) { return chart.make_name(std::nullopt); }, // py::doc("returns name of the chart")) // .def( "make_name", // [](const ChartModify& chart, size_t projection_no) { return chart.make_name(projection_no); }, // "projection_no"_a, // py::doc("returns name of the chart with the stress of the passed projection")) // .def("description", // &Chart::description, // py::doc("returns chart one line description")) // .def( "make_info", // [](const ChartModify& chart, size_t max_number_of_projections_to_show, bool column_bases, bool tables, bool tables_for_sera, bool antigen_dates) { return chart.make_info(max_number_of_projections_to_show, make_info_data(max_number_of_projections_to_show, column_bases, tables, tables_for_sera, antigen_dates)); }, // "max_number_of_projections_to_show"_a = 20, "column_bases"_a = true, "tables"_a = false, "tables_for_sera"_a = false, "antigen_dates"_a = false, // py::doc("returns detailed chart description")) // .def("number_of_antigens", &Chart::number_of_antigens) .def("number_of_sera", &Chart::number_of_sera) .def("number_of_projections", &Chart::number_of_projections) .def( "lineage", // [](const ChartModify& chart) { return *chart.lineage(); }, // py::doc("returns chart lineage: VICTORIA, YAMAGATA")) // .def( "relax", // [](ChartModify& chart, size_t number_of_dimensions, size_t number_of_optimizations, const std::string& minimum_column_basis, bool dimension_annealing, bool rough, size_t number_of_best_distinct_projections_to_keep) { if (number_of_optimizations == 0) number_of_optimizations = 100; chart.relax(number_of_optimizations_t{number_of_optimizations}, MinimumColumnBasis{minimum_column_basis}, acmacs::number_of_dimensions_t{number_of_dimensions}, use_dimension_annealing_from_bool(dimension_annealing), optimization_options{optimization_precision{rough ? optimization_precision::rough : optimization_precision::fine}}); chart.projections_modify().sort(); }, // "number_of_dimensions"_a = 2, "number_of_optimizations"_a = 0, "minimum_column_basis"_a = "none", "dimension_annealing"_a = false, "rough"_a = false, "number_of_best_distinct_projections_to_keep"_a = 5, // py::doc{"makes one or more antigenic maps from random starting layouts, adds new projections, projections are sorted by stress"}) // .def( "projection", // [](ChartModify& chart, size_t projection_no) { return chart.projection_modify(projection_no); }, // "projection_no"_a = 0) // .def("remove_all_projections", // [](ChartModify& chart) { return chart.projections_modify().remove_all(); }) // ; // ---------------------------------------------------------------------- py::class_<ProjectionModify, std::shared_ptr<ProjectionModify>>(mdl, "Projection") // .def( "stress", // [](const ProjectionModify& projection, bool recalculate) { return projection.stress(recalculate ? RecalculateStress::if_necessary : RecalculateStress::no); }, // "recalculate"_a = false) // ; } // ====================================================================== inline void py_merge(py::module_& mdl) { using namespace pybind11::literals; using namespace acmacs::chart; mdl.def( "merge", [](std::shared_ptr<ChartModify> chart1, std::shared_ptr<ChartModify> chart2, const std::string& merge_type, const std::string& match, bool remove_distinct) { CommonAntigensSera::match_level_t match_level{CommonAntigensSera::match_level_t::automatic}; if (match == "auto" || match == "automatic") match_level = CommonAntigensSera::match_level_t::automatic; else if (match == "strict") match_level = CommonAntigensSera::match_level_t::strict; else if (match == "relaxed") match_level = CommonAntigensSera::match_level_t::relaxed; else if (match == "ignored") match_level = CommonAntigensSera::match_level_t::ignored; else throw std::invalid_argument{fmt::format("Unrecognized \"match\": \"{}\"", match)}; projection_merge_t merge_typ{projection_merge_t::type1}; if (merge_type == "type1" || merge_type == "tables-only") merge_typ = projection_merge_t::type1; else if (merge_type == "type2" || merge_type == "incremental") merge_typ = projection_merge_t::type2; else if (merge_type == "type3") merge_typ = projection_merge_t::type3; else if (merge_type == "type4") merge_typ = projection_merge_t::type4; else if (merge_type == "type5") merge_typ = projection_merge_t::type5; else throw std::invalid_argument{fmt::format("Unrecognized \"merge_type\": \"{}\"", merge_type)}; return merge(*chart1, *chart2, MergeSettings{match_level, merge_typ, remove_distinct}); }, // "chart1"_a, "chart2"_a, "type"_a, "match"_a = "auto", "remove_distinct"_a = false, // py::doc(R"(merges two charts type: "type1" ("tables-only"), "type2" ("incremental"), "type3", "type4", "type5" see https://github.com/acorg/acmacs-chart-2/blob/master/doc/merge-types.org match: "strict", "relaxed", "ignored", "automatic" ("auto") )")); py::class_<MergeReport>(mdl, "MergeReport") ; } // py_merge // ---------------------------------------------------------------------- // https://pybind11.readthedocs.io/en/latest/faq.html#how-can-i-reduce-the-build-time PYBIND11_MODULE(acmacs, mdl) { mdl.doc() = "Acmacs backend"; py_chart(mdl); py_merge(mdl); } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "malloc.hpp" namespace { bool init = false; size_t _used = 0; size_t _allocated = 0; struct malloc_header_chunk { size_t size; malloc_header_chunk* next; malloc_header_chunk* prev; size_t padding; }; struct fake_head { uint64_t size; malloc_header_chunk* next; malloc_header_chunk* prev; }; constexpr size_t ALIGNMENT = 16; constexpr bool aligned(size_t value){ return (value & (ALIGNMENT - 1)) == 0; } constexpr const uint64_t META_SIZE = sizeof(malloc_header_chunk); constexpr const uint64_t BLOCK_SIZE = 4096; constexpr const uint64_t MIN_BLOCKS = 4; constexpr const uint64_t MIN_SPLIT = ALIGNMENT == 8 ? 32 : 2 * ALIGNMENT; static_assert(aligned(sizeof(malloc_header_chunk)), "The header must be aligned"); static_assert(aligned(MIN_SPLIT), "The size of minimum split must guarantee alignment"); fake_head head; malloc_header_chunk* malloc_head = 0; //Insert new_block after current in the free list and update //all the necessary links void insert_after(malloc_header_chunk* current, malloc_header_chunk* new_block){ //Link the new block to its surroundings new_block->next = current->next; new_block->prev = current; //Link surroundings to the new block current->next->prev = new_block; current->next = new_block; } //Remove the given block from the free list //The node is directly marked as not free void remove(malloc_header_chunk* current){ //Unlink the node current->prev->next = current->next; current->next->prev = current->prev; //Make sure the node is clean current->prev = nullptr; current->next = nullptr; } bool expand_heap(malloc_header_chunk* current, size_t bytes = 0){ auto blocks = MIN_BLOCKS; if(bytes){ auto necessary_blocks = ((bytes + META_SIZE) / BLOCK_SIZE) + 1; if(necessary_blocks > blocks){ blocks = necessary_blocks; } } //Allocate a new block of memory auto old_end = brk_end(); auto brk_end = sbrk(blocks * BLOCK_SIZE); if(brk_end == old_end){ return false; } auto real_blocks = (brk_end - old_end) / BLOCK_SIZE; _allocated += real_blocks * BLOCK_SIZE; //Transform it into a malloc chunk auto header = reinterpret_cast<malloc_header_chunk*>(old_end); //Update the size header->size = real_blocks * BLOCK_SIZE - META_SIZE; //Insert the new block into the free list insert_after(current, header); return true; } void init_head(){ head.size = 0; head.next = nullptr; head.prev = nullptr; malloc_head = reinterpret_cast<malloc_header_chunk*>(&head); malloc_head->next = malloc_head; malloc_head->prev = malloc_head; expand_heap(malloc_head); init = true; } } //end of anonymous namespace void* malloc(size_t bytes){ if(!init){ init_head(); } auto current = malloc_head->next; //Try not to create too small blocks if(bytes < MIN_SPLIT){ bytes = MIN_SPLIT; } //Make sure that blocks will have the correct alignment at the end if(!aligned(bytes)){ bytes = ((bytes / ALIGNMENT) + 1) * ALIGNMENT; } while(true){ if(current == malloc_head){ //There are no blocks big enough to hold this request //So expand the heap expand_heap(current, bytes); } else if(current->size >= bytes){ //This block is big enough //Space necessary to hold a new block inside this one auto necessary_space = bytes + META_SIZE; //Is it worth splitting the block ? if(current->size > necessary_space + MIN_SPLIT + META_SIZE){ auto new_block_size = current->size - necessary_space; //Set the new size of the current block current->size = bytes; //Create a new block inside the current one auto new_block = reinterpret_cast<malloc_header_chunk*>( reinterpret_cast<uintptr_t>(current) + bytes + META_SIZE); //Update the size of the new block new_block->size = new_block_size; //Add the new block to the free list insert_after(current, new_block); //Remove the current block from the free list remove(current); break; } else { //Remove this node from the free list remove(current); break; } } current = current->next; } _used += current->size + META_SIZE; //Address of the start of the block auto block_start = reinterpret_cast<uintptr_t>(current) + sizeof(malloc_header_chunk); return reinterpret_cast<void*>(block_start); } void free(void* pointer){ //TODO } size_t brk_start(){ size_t value; asm volatile("mov rax, 7; int 50; mov %0, rax" : "=m" (value) : //No inputs : "rax"); return value; } size_t brk_end(){ size_t value; asm volatile("mov rax, 8; int 50; mov %0, rax" : "=m" (value) : //No inputs : "rax"); return value; } size_t sbrk(size_t inc){ size_t value; asm volatile("mov rax, 9; int 50; mov %0, rax" : "=m" (value) : "b" (inc) : "rax"); return value; } <commit_msg>Refactor<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "malloc.hpp" #define likely(x) __builtin_expect (!!(x), 1) #define unlikely(x) __builtin_expect (!!(x), 0) namespace { bool init = false; size_t _used = 0; size_t _allocated = 0; struct malloc_header_chunk { size_t size; malloc_header_chunk* next; malloc_header_chunk* prev; size_t padding; }; struct fake_head { uint64_t size; malloc_header_chunk* next; malloc_header_chunk* prev; }; constexpr size_t ALIGNMENT = 16; constexpr bool aligned(size_t value){ return (value & (ALIGNMENT - 1)) == 0; } constexpr const uint64_t META_SIZE = sizeof(malloc_header_chunk); constexpr const uint64_t BLOCK_SIZE = 4096; constexpr const uint64_t MIN_BLOCKS = 4; constexpr const uint64_t MIN_SPLIT = ALIGNMENT == 8 ? 32 : 2 * ALIGNMENT; static_assert(aligned(sizeof(malloc_header_chunk)), "The header must be aligned"); static_assert(aligned(MIN_SPLIT), "The size of minimum split must guarantee alignment"); fake_head head; malloc_header_chunk* malloc_head = 0; //Insert new_block after current in the free list and update //all the necessary links void insert_after(malloc_header_chunk* current, malloc_header_chunk* new_block){ //Link the new block to its surroundings new_block->next = current->next; new_block->prev = current; //Link surroundings to the new block current->next->prev = new_block; current->next = new_block; } //Remove the given block from the free list //The node is directly marked as not free void remove(malloc_header_chunk* current){ //Unlink the node current->prev->next = current->next; current->next->prev = current->prev; //Make sure the node is clean current->prev = nullptr; current->next = nullptr; } bool expand_heap(malloc_header_chunk* current, size_t bytes = 0){ auto blocks = MIN_BLOCKS; if(unlikely(bytes)){ auto necessary_blocks = ((bytes + META_SIZE) / BLOCK_SIZE) + 1; if(necessary_blocks > blocks){ blocks = necessary_blocks; } } //Allocate a new block of memory auto old_end = brk_end(); auto brk_end = sbrk(blocks * BLOCK_SIZE); if(brk_end == old_end){ return false; } auto real_blocks = (brk_end - old_end) / BLOCK_SIZE; _allocated += real_blocks * BLOCK_SIZE; //Transform it into a malloc chunk auto header = reinterpret_cast<malloc_header_chunk*>(old_end); //Update the size header->size = real_blocks * BLOCK_SIZE - META_SIZE; //Insert the new block into the free list insert_after(current, header); return true; } void init_head(){ head.size = 0; head.next = nullptr; head.prev = nullptr; malloc_head = reinterpret_cast<malloc_header_chunk*>(&head); malloc_head->next = malloc_head; malloc_head->prev = malloc_head; expand_heap(malloc_head); init = true; } } //end of anonymous namespace void* malloc(size_t bytes){ if(unlikely(!init)){ init_head(); } auto current = malloc_head->next; //Try not to create too small blocks if(bytes < MIN_SPLIT){ bytes = MIN_SPLIT; } //Make sure that blocks will have the correct alignment at the end if(!aligned(bytes)){ bytes = ((bytes / ALIGNMENT) + 1) * ALIGNMENT; } while(true){ if(current == malloc_head){ //There are no blocks big enough to hold this request //So expand the heap expand_heap(current, bytes); } else if(current->size >= bytes){ //This block is big enough //Space necessary to hold a new block inside this one auto necessary_space = bytes + META_SIZE; //Is it worth splitting the block ? if(current->size > necessary_space + MIN_SPLIT + META_SIZE){ auto new_block_size = current->size - necessary_space; //Set the new size of the current block current->size = bytes; //Create a new block inside the current one auto new_block = reinterpret_cast<malloc_header_chunk*>( reinterpret_cast<uintptr_t>(current) + bytes + META_SIZE); //Update the size of the new block new_block->size = new_block_size; //Add the new block to the free list insert_after(current, new_block); //Remove the current block from the free list remove(current); break; } else { //Remove this node from the free list remove(current); break; } } current = current->next; } _used += current->size + META_SIZE; //Address of the start of the block auto block_start = reinterpret_cast<uintptr_t>(current) + sizeof(malloc_header_chunk); return reinterpret_cast<void*>(block_start); } void free(void* pointer){ //TODO } size_t brk_start(){ size_t value; asm volatile("mov rax, 7; int 50; mov %0, rax" : "=m" (value) : //No inputs : "rax"); return value; } size_t brk_end(){ size_t value; asm volatile("mov rax, 8; int 50; mov %0, rax" : "=m" (value) : //No inputs : "rax"); return value; } size_t sbrk(size_t inc){ size_t value; asm volatile("mov rax, 9; int 50; mov %0, rax" : "=m" (value) : "b" (inc) : "rax"); return value; } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * http://lxqt.org * * Copyright: 2014 LXQt team * Authors: * Hong Jen Yee (PCMan) <pcman.tw@gmail.com> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include <LXQt/SingleApplication> #include <QCommandLineParser> #include "timeadmindialog.h" int main(int argc, char **argv) { LXQt::SingleApplication app(argc, argv); QCommandLineParser parser; parser.setApplicationDescription(QStringLiteral("LXQt Admin Time")); const QString VERINFO = QStringLiteral(LXQT_ADMIN_VERSION "\nliblxqt " LXQT_VERSION "\nQt " QT_VERSION_STR); app.setApplicationVersion(VERINFO); parser.addVersionOption(); parser.addHelpOption(); parser.process(app); TimeAdminDialog dlg; dlg.setWindowIcon(QIcon::fromTheme("preferences-system")); app.setActivationWindow(&dlg); dlg.show(); return app.exec(); } <commit_msg>lxqt-admin-time: set Qt::AA_UseHighDpiPixmaps to true<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * http://lxqt.org * * Copyright: 2014 LXQt team * Authors: * Hong Jen Yee (PCMan) <pcman.tw@gmail.com> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include <LXQt/SingleApplication> #include <QCommandLineParser> #include "timeadmindialog.h" int main(int argc, char **argv) { LXQt::SingleApplication app(argc, argv); app.setAttribute(Qt::AA_UseHighDpiPixmaps, true); QCommandLineParser parser; parser.setApplicationDescription(QStringLiteral("LXQt Admin Time")); const QString VERINFO = QStringLiteral(LXQT_ADMIN_VERSION "\nliblxqt " LXQT_VERSION "\nQt " QT_VERSION_STR); app.setApplicationVersion(VERINFO); parser.addVersionOption(); parser.addHelpOption(); parser.process(app); TimeAdminDialog dlg; dlg.setWindowIcon(QIcon::fromTheme("preferences-system")); app.setActivationWindow(&dlg); dlg.show(); return app.exec(); } <|endoftext|>
<commit_before>#include "logger.hpp" #include "shared_state.hpp" #include "thread_nexus.hpp" #include "thread_phase.hpp" #include "vm.hpp" #include "class/thread.hpp" #include "memory/managed.hpp" #include "util/atomic.hpp" #include "diagnostics/timing.hpp" #include <chrono> #include <cxxabi.h> #include <ostream> #include <string> #include <thread> #include <time.h> #ifdef USE_EXECINFO #include <execinfo.h> #endif namespace rubinius { void ThreadNexus::set_halt(STATE, VM* vm) { if(!halting_mutex_.try_lock()) { std::ostringstream msg; msg << "halting mutex is already locked: id: " << vm->thread_id(); Exception::raise_assertion_error(state, msg.str().c_str()); } halt_.store(vm->thread_id(), std::memory_order_release); } void ThreadNexus::managed_phase(STATE, VM* vm) { if(halt_ && halt_ != vm->thread_id()) { halting_mutex_.lock(); } lock(state, vm, [vm]{ vm->set_thread_phase(eManaged); }); } bool ThreadNexus::try_managed_phase(STATE, VM* vm) { if(halt_ && halt_ != vm->thread_id()) { halting_mutex_.lock(); } return try_lock(state, vm, [vm]{ vm->set_thread_phase(eManaged); }); } void ThreadNexus::unmanaged_phase(STATE, VM* vm) { vm->set_thread_phase(eUnmanaged); } void ThreadNexus::waiting_phase(STATE, VM* vm) { if(lock_ == vm->thread_id()) { std::ostringstream msg; msg << "waiting while holding process-critical lock: id: " << vm->thread_id(); Exception::raise_assertion_error(state, msg.str().c_str()); } vm->set_thread_phase(eWaiting); } // Only to be used when holding the ThreadNexus lock. void ThreadNexus::set_managed(STATE, VM* vm) { vm->set_thread_phase(eManaged); } void ThreadNexus::unlock(STATE, VM* vm) { if(lock_ != vm->thread_id()) { std::ostringstream msg; msg << "process-critical lock being unlocked by the wrong Thread: id: " << vm->thread_id(); Exception::raise_assertion_error(state, msg.str().c_str()); } waiting_condition_.notify_all(); lock_ = 0; } bool ThreadNexus::yielding_p(VM* vm) { int phase = static_cast<int>(vm->thread_phase()); return (phase & cYieldingPhase) == cYieldingPhase; } VM* ThreadNexus::new_vm(SharedState* shared, const char* name) { std::lock_guard<std::mutex> guard(threads_mutex_); uint32_t max_id = thread_ids_; uint32_t id = ++thread_ids_; if(id < max_id) { rubinius::bug("exceeded maximum number of threads"); } VM* vm = new VM(id, *shared, name); threads_.push_back(vm); return vm; } void ThreadNexus::delete_vm(VM* vm) { std::lock_guard<std::mutex> guard(threads_mutex_); threads_.remove(vm); } void ThreadNexus::after_fork_child(STATE) { new(&threads_mutex_) std::mutex; VM* current = state->vm(); while(!threads_.empty()) { VM* vm = threads_.back()->as_vm(); threads_.pop_back(); if(!vm) continue; switch(vm->kind()) { case memory::ManagedThread::eThread: { if(Thread* thread = vm->thread()) { if(!thread->nil_p()) { if(vm == current) { thread->current_fiber(state, thread->fiber()); continue; } thread->stopped(); } } vm->reset_parked(); vm->set_zombie(); break; } case memory::ManagedThread::eFiber: { if(Fiber* fiber = vm->fiber()) { fiber->status(Fiber::eDead); vm->set_canceled(); vm->set_zombie(); } break; } case memory::ManagedThread::eSystem: VM::discard(state, vm); break; } } threads_.push_back(current); state->shared().set_root_vm(current); } static const char* phase_name(VM* vm) { switch(vm->thread_phase()) { case ThreadNexus::eManaged: return "eManaged"; case ThreadNexus::eUnmanaged: return "eUnmanaged"; case ThreadNexus::eWaiting: return "eWaiting"; } return "cUnknown"; } void ThreadNexus::list_threads() { list_threads(logger::error); } void ThreadNexus::list_threads(logger::PrintFunction function) { for(ThreadList::iterator i = threads_.begin(); i != threads_.end(); ++i) { if(VM* other_vm = (*i)->as_vm()) { function("thread %d: %s, %s", other_vm->thread_id(), other_vm->name().c_str(), phase_name(other_vm)); } } } void ThreadNexus::detect_deadlock(STATE, uint64_t nanoseconds, VM* vm) { if(nanoseconds > ThreadNexus::cLockLimit) { logger::error("thread nexus: thread will not yield: %s, %s", vm->name().c_str(), phase_name(vm)); list_threads(logger::error); std::ostringstream msg; msg << "thread will not yield: " << vm->name().c_str() << phase_name(vm); Exception::raise_deadlock_error(state, msg.str().c_str()); } } void ThreadNexus::detect_deadlock(STATE, uint64_t nanoseconds) { if(nanoseconds > ThreadNexus::cLockLimit) { logger::error("thread nexus: unable to lock, possible deadlock"); list_threads(logger::error); Exception::raise_deadlock_error(state, "thread nexus: unable to lock, possible deadlock"); } } void ThreadNexus::each_thread(STATE, std::function<void (STATE, VM* vm)> process) { LockWaiting<std::mutex> guard(state, threads_mutex_); for(auto vm : threads_) { process(state, reinterpret_cast<VM*>(vm)); } } bool ThreadNexus::valid_thread_p(STATE, unsigned int thread_id) { bool valid = false; each_thread(state, [thread_id, &valid](STATE, VM* vm) { if(thread_id == vm->thread_id()) valid = true; }); return valid; } uint64_t ThreadNexus::wait() { static int i = 0; static int delay[] = { 133, 464, 254, 306, 549, 287, 358, 638, 496, 81, 472, 288, 131, 31, 435, 258, 221, 73, 537, 854 }; static int modulo = sizeof(delay) / sizeof(int); uint64_t ns = delay[i++ % modulo]; std::this_thread::sleep_for(std::chrono::nanoseconds(ns)); return ns; } void ThreadNexus::wait_for_all(STATE, VM* vm) { std::lock_guard<std::mutex> guard(threads_mutex_); uint64_t limit = 0; set_managed(state, vm); for(ThreadList::iterator i = threads_.begin(); i != threads_.end(); ++i) { if(VM* other_vm = (*i)->as_vm()) { if(vm == other_vm || yielding_p(other_vm)) continue; while(true) { if(yielding_p(other_vm)) { break; } limit += wait(); detect_deadlock(state, limit, other_vm); } } } } bool ThreadNexus::lock_owned_p(VM* vm) { return lock_ == vm->thread_id(); } bool ThreadNexus::try_lock(VM* vm) { uint32_t id = 0; return lock_.compare_exchange_strong(id, vm->thread_id()); } bool ThreadNexus::try_lock_wait(STATE, VM* vm) { uint64_t limit = 0; while(!try_lock(vm)) { if(lock_ == vm->thread_id()) { std::ostringstream msg; msg << "yielding while holding process-critical lock: id: " << vm->thread_id(); Exception::raise_assertion_error(state, msg.str().c_str()); } yield(state, vm); limit += wait(); detect_deadlock(state, limit); } return true; } static char* demangle(char* symbol, char* result, size_t size) { const char* pos = strstr(symbol, " _Z"); if(pos) { size_t sz = 0; char *cpp_name = 0; char* name = strdup(pos + 1); char* end = strstr(name, " + "); *end = 0; int status; if((cpp_name = abi::__cxa_demangle(name, cpp_name, &sz, &status))) { if(!status) { snprintf(result, size, "%.*s %s %s", int(pos - symbol), symbol, cpp_name, ++end); } free(cpp_name); } free(name); } else { strcpy(result, symbol); } return result; } #ifdef RBX_GC_STACK_CHECK #define RBX_ABORT_CALLSTACK_SIZE 128 #define RBX_ABORT_SYMBOL_SIZE 512 void ThreadNexus::check_stack(STATE, VM* vm) { void* callstack[RBX_ABORT_CALLSTACK_SIZE]; char symbol[RBX_ABORT_SYMBOL_SIZE]; int i, frames = backtrace(callstack, RBX_ABORT_CALLSTACK_SIZE); char** symbols = backtrace_symbols(callstack, frames); logger::debug("Backtrace for thread: %s", vm->name().c_str()); for(i = 0; i < frames; i++) { logger::debug("%s", demangle(symbols[i], symbol, RBX_ABORT_SYMBOL_SIZE)); } free(symbols); } #endif } <commit_msg>Emit the kind of thread for --gc-stack-check.<commit_after>#include "logger.hpp" #include "shared_state.hpp" #include "thread_nexus.hpp" #include "thread_phase.hpp" #include "vm.hpp" #include "class/thread.hpp" #include "memory/managed.hpp" #include "util/atomic.hpp" #include "diagnostics/timing.hpp" #include <chrono> #include <cxxabi.h> #include <ostream> #include <string> #include <thread> #include <time.h> #ifdef USE_EXECINFO #include <execinfo.h> #endif namespace rubinius { void ThreadNexus::set_halt(STATE, VM* vm) { if(!halting_mutex_.try_lock()) { std::ostringstream msg; msg << "halting mutex is already locked: id: " << vm->thread_id(); Exception::raise_assertion_error(state, msg.str().c_str()); } halt_.store(vm->thread_id(), std::memory_order_release); } void ThreadNexus::managed_phase(STATE, VM* vm) { if(halt_ && halt_ != vm->thread_id()) { halting_mutex_.lock(); } lock(state, vm, [vm]{ vm->set_thread_phase(eManaged); }); } bool ThreadNexus::try_managed_phase(STATE, VM* vm) { if(halt_ && halt_ != vm->thread_id()) { halting_mutex_.lock(); } return try_lock(state, vm, [vm]{ vm->set_thread_phase(eManaged); }); } void ThreadNexus::unmanaged_phase(STATE, VM* vm) { vm->set_thread_phase(eUnmanaged); } void ThreadNexus::waiting_phase(STATE, VM* vm) { if(lock_ == vm->thread_id()) { std::ostringstream msg; msg << "waiting while holding process-critical lock: id: " << vm->thread_id(); Exception::raise_assertion_error(state, msg.str().c_str()); } vm->set_thread_phase(eWaiting); } // Only to be used when holding the ThreadNexus lock. void ThreadNexus::set_managed(STATE, VM* vm) { vm->set_thread_phase(eManaged); } void ThreadNexus::unlock(STATE, VM* vm) { if(lock_ != vm->thread_id()) { std::ostringstream msg; msg << "process-critical lock being unlocked by the wrong Thread: id: " << vm->thread_id(); Exception::raise_assertion_error(state, msg.str().c_str()); } waiting_condition_.notify_all(); lock_ = 0; } bool ThreadNexus::yielding_p(VM* vm) { int phase = static_cast<int>(vm->thread_phase()); return (phase & cYieldingPhase) == cYieldingPhase; } VM* ThreadNexus::new_vm(SharedState* shared, const char* name) { std::lock_guard<std::mutex> guard(threads_mutex_); uint32_t max_id = thread_ids_; uint32_t id = ++thread_ids_; if(id < max_id) { rubinius::bug("exceeded maximum number of threads"); } VM* vm = new VM(id, *shared, name); threads_.push_back(vm); return vm; } void ThreadNexus::delete_vm(VM* vm) { std::lock_guard<std::mutex> guard(threads_mutex_); threads_.remove(vm); } void ThreadNexus::after_fork_child(STATE) { new(&threads_mutex_) std::mutex; VM* current = state->vm(); while(!threads_.empty()) { VM* vm = threads_.back()->as_vm(); threads_.pop_back(); if(!vm) continue; switch(vm->kind()) { case memory::ManagedThread::eThread: { if(Thread* thread = vm->thread()) { if(!thread->nil_p()) { if(vm == current) { thread->current_fiber(state, thread->fiber()); continue; } thread->stopped(); } } vm->reset_parked(); vm->set_zombie(); break; } case memory::ManagedThread::eFiber: { if(Fiber* fiber = vm->fiber()) { fiber->status(Fiber::eDead); vm->set_canceled(); vm->set_zombie(); } break; } case memory::ManagedThread::eSystem: VM::discard(state, vm); break; } } threads_.push_back(current); state->shared().set_root_vm(current); } static const char* phase_name(VM* vm) { switch(vm->thread_phase()) { case ThreadNexus::eManaged: return "eManaged"; case ThreadNexus::eUnmanaged: return "eUnmanaged"; case ThreadNexus::eWaiting: return "eWaiting"; } return "cUnknown"; } void ThreadNexus::list_threads() { list_threads(logger::error); } void ThreadNexus::list_threads(logger::PrintFunction function) { for(ThreadList::iterator i = threads_.begin(); i != threads_.end(); ++i) { if(VM* other_vm = (*i)->as_vm()) { function("thread %d: %s, %s", other_vm->thread_id(), other_vm->name().c_str(), phase_name(other_vm)); } } } void ThreadNexus::detect_deadlock(STATE, uint64_t nanoseconds, VM* vm) { if(nanoseconds > ThreadNexus::cLockLimit) { logger::error("thread nexus: thread will not yield: %s, %s", vm->name().c_str(), phase_name(vm)); list_threads(logger::error); std::ostringstream msg; msg << "thread will not yield: " << vm->name().c_str() << phase_name(vm); Exception::raise_deadlock_error(state, msg.str().c_str()); } } void ThreadNexus::detect_deadlock(STATE, uint64_t nanoseconds) { if(nanoseconds > ThreadNexus::cLockLimit) { logger::error("thread nexus: unable to lock, possible deadlock"); list_threads(logger::error); Exception::raise_deadlock_error(state, "thread nexus: unable to lock, possible deadlock"); } } void ThreadNexus::each_thread(STATE, std::function<void (STATE, VM* vm)> process) { LockWaiting<std::mutex> guard(state, threads_mutex_); for(auto vm : threads_) { process(state, reinterpret_cast<VM*>(vm)); } } bool ThreadNexus::valid_thread_p(STATE, unsigned int thread_id) { bool valid = false; each_thread(state, [thread_id, &valid](STATE, VM* vm) { if(thread_id == vm->thread_id()) valid = true; }); return valid; } uint64_t ThreadNexus::wait() { static int i = 0; static int delay[] = { 133, 464, 254, 306, 549, 287, 358, 638, 496, 81, 472, 288, 131, 31, 435, 258, 221, 73, 537, 854 }; static int modulo = sizeof(delay) / sizeof(int); uint64_t ns = delay[i++ % modulo]; std::this_thread::sleep_for(std::chrono::nanoseconds(ns)); return ns; } void ThreadNexus::wait_for_all(STATE, VM* vm) { std::lock_guard<std::mutex> guard(threads_mutex_); uint64_t limit = 0; set_managed(state, vm); for(ThreadList::iterator i = threads_.begin(); i != threads_.end(); ++i) { if(VM* other_vm = (*i)->as_vm()) { if(vm == other_vm || yielding_p(other_vm)) continue; while(true) { if(yielding_p(other_vm)) { break; } limit += wait(); detect_deadlock(state, limit, other_vm); } } } } bool ThreadNexus::lock_owned_p(VM* vm) { return lock_ == vm->thread_id(); } bool ThreadNexus::try_lock(VM* vm) { uint32_t id = 0; return lock_.compare_exchange_strong(id, vm->thread_id()); } bool ThreadNexus::try_lock_wait(STATE, VM* vm) { uint64_t limit = 0; while(!try_lock(vm)) { if(lock_ == vm->thread_id()) { std::ostringstream msg; msg << "yielding while holding process-critical lock: id: " << vm->thread_id(); Exception::raise_assertion_error(state, msg.str().c_str()); } yield(state, vm); limit += wait(); detect_deadlock(state, limit); } return true; } static char* demangle(char* symbol, char* result, size_t size) { const char* pos = strstr(symbol, " _Z"); if(pos) { size_t sz = 0; char *cpp_name = 0; char* name = strdup(pos + 1); char* end = strstr(name, " + "); *end = 0; int status; if((cpp_name = abi::__cxa_demangle(name, cpp_name, &sz, &status))) { if(!status) { snprintf(result, size, "%.*s %s %s", int(pos - symbol), symbol, cpp_name, ++end); } free(cpp_name); } free(name); } else { strcpy(result, symbol); } return result; } #ifdef RBX_GC_STACK_CHECK #define RBX_ABORT_CALLSTACK_SIZE 128 #define RBX_ABORT_SYMBOL_SIZE 512 void ThreadNexus::check_stack(STATE, VM* vm) { void* callstack[RBX_ABORT_CALLSTACK_SIZE]; char symbol[RBX_ABORT_SYMBOL_SIZE]; int i, frames = backtrace(callstack, RBX_ABORT_CALLSTACK_SIZE); char** symbols = backtrace_symbols(callstack, frames); logger::debug("Backtrace for %s: %s", vm->kind_name(), vm->name().c_str()); for(i = 0; i < frames; i++) { logger::debug("%s", demangle(symbols[i], symbol, RBX_ABORT_SYMBOL_SIZE)); } free(symbols); } #endif } <|endoftext|>
<commit_before>/* * Policies for TLS * (C) 2004-2010,2012 Jack Lloyd * * Released under the terms of the Botan license */ #include <botan/tls_policy.h> #include <botan/tls_ciphersuite.h> #include <botan/tls_magic.h> #include <botan/tls_exceptn.h> #include <botan/internal/stl_util.h> namespace Botan { namespace TLS { std::vector<std::string> Policy::allowed_ciphers() const { std::vector<std::string> allowed; allowed.push_back("AES-256"); allowed.push_back("AES-128"); allowed.push_back("3DES"); allowed.push_back("ARC4"); //allowed.push_back("Camellia"); //allowed.push_back("SEED"); return allowed; } std::vector<std::string> Policy::allowed_hashes() const { std::vector<std::string> allowed; allowed.push_back("SHA-512"); allowed.push_back("SHA-384"); allowed.push_back("SHA-256"); allowed.push_back("SHA-224"); allowed.push_back("SHA-1"); //allowed.push_back("MD5"); return allowed; } std::vector<std::string> Policy::allowed_key_exchange_methods() const { std::vector<std::string> allowed; allowed.push_back("SRP_SHA"); //allowed.push_back("ECDHE_PSK"); //allowed.push_back("DHE_PSK"); //allowed.push_back("PSK"); allowed.push_back("ECDH"); allowed.push_back("DH"); allowed.push_back("RSA"); return allowed; } std::vector<std::string> Policy::allowed_signature_methods() const { std::vector<std::string> allowed; allowed.push_back("ECDSA"); allowed.push_back("RSA"); allowed.push_back("DSA"); //allowed.push_back(""); return allowed; } std::vector<std::string> Policy::allowed_ecc_curves() const { std::vector<std::string> curves; curves.push_back("secp521r1"); curves.push_back("secp384r1"); curves.push_back("secp256r1"); curves.push_back("secp256k1"); curves.push_back("secp224r1"); curves.push_back("secp224k1"); curves.push_back("secp192r1"); curves.push_back("secp192k1"); curves.push_back("secp160r2"); curves.push_back("secp160r1"); curves.push_back("secp160k1"); return curves; } /* * Choose an ECC curve to use */ std::string Policy::choose_curve(const std::vector<std::string>& curve_names) const { const std::vector<std::string> our_curves = allowed_ecc_curves(); for(size_t i = 0; i != our_curves.size(); ++i) if(value_exists(curve_names, our_curves[i])) return our_curves[i]; return ""; // no shared curve } DL_Group Policy::dh_group() const { return DL_Group("modp/ietf/2048"); } /* * Return allowed compression algorithms */ std::vector<byte> Policy::compression() const { std::vector<byte> algs; algs.push_back(NO_COMPRESSION); return algs; } u32bit Policy::session_ticket_lifetime() const { return 86400; // 1 day } Protocol_Version Policy::min_version() const { return Protocol_Version::SSL_V3; } Protocol_Version Policy::pref_version() const { return Protocol_Version::TLS_V12; } namespace { class Ciphersuite_Preference_Ordering { public: Ciphersuite_Preference_Ordering(const std::vector<std::string>& ciphers, const std::vector<std::string>& hashes, const std::vector<std::string>& kex, const std::vector<std::string>& sigs) : m_ciphers(ciphers), m_hashes(hashes), m_kex(kex), m_sigs(sigs) {} bool operator()(const Ciphersuite& a, const Ciphersuite& b) const { if(a.kex_algo() != b.kex_algo()) { for(size_t i = 0; i != m_kex.size(); ++i) { if(a.kex_algo() == m_kex[i]) return true; if(b.kex_algo() == m_kex[i]) return false; } } if(a.cipher_algo() != b.cipher_algo()) { for(size_t i = 0; i != m_ciphers.size(); ++i) { if(a.cipher_algo() == m_ciphers[i]) return true; if(b.cipher_algo() == m_ciphers[i]) return false; } } if(a.cipher_keylen() != b.cipher_keylen()) { if(a.cipher_keylen() < b.cipher_keylen()) return false; if(a.cipher_keylen() > b.cipher_keylen()) return true; } if(a.sig_algo() != b.sig_algo()) { for(size_t i = 0; i != m_sigs.size(); ++i) { if(a.sig_algo() == m_sigs[i]) return true; if(b.sig_algo() == m_sigs[i]) return false; } } if(a.mac_algo() != b.mac_algo()) { for(size_t i = 0; i != m_hashes.size(); ++i) { if(a.mac_algo() == m_hashes[i]) return true; if(b.mac_algo() == m_hashes[i]) return false; } } return false; // equal (?!?) } private: std::vector<std::string> m_ciphers, m_hashes, m_kex, m_sigs; }; } std::vector<u16bit> ciphersuite_list(const Policy& policy, bool have_srp) { const std::vector<std::string> ciphers = policy.allowed_ciphers(); const std::vector<std::string> hashes = policy.allowed_hashes(); const std::vector<std::string> kex = policy.allowed_key_exchange_methods(); const std::vector<std::string> sigs = policy.allowed_signature_methods(); Ciphersuite_Preference_Ordering order(ciphers, hashes, kex, sigs); std::map<Ciphersuite, u16bit, Ciphersuite_Preference_Ordering> ciphersuites(order); for(size_t i = 0; i != 65536; ++i) { Ciphersuite suite = Ciphersuite::by_id(i); if(!suite.valid()) continue; // not a ciphersuite we know, skip if(!have_srp && suite.kex_algo() == "SRP_SHA") continue; if(!value_exists(kex, suite.kex_algo())) continue; // unsupported key exchange if(!value_exists(ciphers, suite.cipher_algo())) continue; // unsupported cipher if(!value_exists(hashes, suite.mac_algo())) continue; // unsupported MAC algo if(!value_exists(sigs, suite.sig_algo())) { // allow if it's an empty sig algo and we want to use PSK if(suite.sig_algo() != "" || !suite.psk_ciphersuite()) continue; } // OK, allow it: ciphersuites[suite] = i; } std::vector<u16bit> ciphersuite_codes; for(std::map<Ciphersuite, u16bit, Ciphersuite_Preference_Ordering>::iterator i = ciphersuites.begin(); i != ciphersuites.end(); ++i) { ciphersuite_codes.push_back(i->second); } return ciphersuite_codes; } } } <commit_msg>Use initialize lists here, much cleaner<commit_after>/* * Policies for TLS * (C) 2004-2010,2012 Jack Lloyd * * Released under the terms of the Botan license */ #include <botan/tls_policy.h> #include <botan/tls_ciphersuite.h> #include <botan/tls_magic.h> #include <botan/tls_exceptn.h> #include <botan/internal/stl_util.h> namespace Botan { namespace TLS { std::vector<std::string> Policy::allowed_ciphers() const { return std::vector<std::string>({ "AES-256", "AES-128", "3DES", "ARC4", //"Camellia-256", //"Camellia-128", //"SEED" }); } std::vector<std::string> Policy::allowed_hashes() const { return std::vector<std::string>({ "SHA-512", "SHA-384", "SHA-256", "SHA-224", "SHA-1", //"MD5", }); } std::vector<std::string> Policy::allowed_key_exchange_methods() const { return std::vector<std::string>({ "SRP_SHA", //"ECDHE_PSK", //"DHE_PSK", //"PSK", "ECDH", "DH", "RSA", }); } std::vector<std::string> Policy::allowed_signature_methods() const { return std::vector<std::string>({ "ECDSA", "RSA", "DSA", }); } std::vector<std::string> Policy::allowed_ecc_curves() const { return std::vector<std::string>({ "secp521r1", "secp384r1", "secp256r1", "secp256k1", "secp224r1", "secp224k1", "secp192r1", "secp192k1", "secp160r2", "secp160r1", "secp160k1", }); } /* * Choose an ECC curve to use */ std::string Policy::choose_curve(const std::vector<std::string>& curve_names) const { const std::vector<std::string> our_curves = allowed_ecc_curves(); for(size_t i = 0; i != our_curves.size(); ++i) if(value_exists(curve_names, our_curves[i])) return our_curves[i]; return ""; // no shared curve } DL_Group Policy::dh_group() const { return DL_Group("modp/ietf/2048"); } /* * Return allowed compression algorithms */ std::vector<byte> Policy::compression() const { std::vector<byte> algs; algs.push_back(NO_COMPRESSION); return algs; } u32bit Policy::session_ticket_lifetime() const { return 86400; // 1 day } Protocol_Version Policy::min_version() const { return Protocol_Version::SSL_V3; } Protocol_Version Policy::pref_version() const { return Protocol_Version::TLS_V12; } namespace { class Ciphersuite_Preference_Ordering { public: Ciphersuite_Preference_Ordering(const std::vector<std::string>& ciphers, const std::vector<std::string>& hashes, const std::vector<std::string>& kex, const std::vector<std::string>& sigs) : m_ciphers(ciphers), m_hashes(hashes), m_kex(kex), m_sigs(sigs) {} bool operator()(const Ciphersuite& a, const Ciphersuite& b) const { if(a.kex_algo() != b.kex_algo()) { for(size_t i = 0; i != m_kex.size(); ++i) { if(a.kex_algo() == m_kex[i]) return true; if(b.kex_algo() == m_kex[i]) return false; } } if(a.cipher_algo() != b.cipher_algo()) { for(size_t i = 0; i != m_ciphers.size(); ++i) { if(a.cipher_algo() == m_ciphers[i]) return true; if(b.cipher_algo() == m_ciphers[i]) return false; } } if(a.cipher_keylen() != b.cipher_keylen()) { if(a.cipher_keylen() < b.cipher_keylen()) return false; if(a.cipher_keylen() > b.cipher_keylen()) return true; } if(a.sig_algo() != b.sig_algo()) { for(size_t i = 0; i != m_sigs.size(); ++i) { if(a.sig_algo() == m_sigs[i]) return true; if(b.sig_algo() == m_sigs[i]) return false; } } if(a.mac_algo() != b.mac_algo()) { for(size_t i = 0; i != m_hashes.size(); ++i) { if(a.mac_algo() == m_hashes[i]) return true; if(b.mac_algo() == m_hashes[i]) return false; } } return false; // equal (?!?) } private: std::vector<std::string> m_ciphers, m_hashes, m_kex, m_sigs; }; } std::vector<u16bit> ciphersuite_list(const Policy& policy, bool have_srp) { const std::vector<std::string> ciphers = policy.allowed_ciphers(); const std::vector<std::string> hashes = policy.allowed_hashes(); const std::vector<std::string> kex = policy.allowed_key_exchange_methods(); const std::vector<std::string> sigs = policy.allowed_signature_methods(); Ciphersuite_Preference_Ordering order(ciphers, hashes, kex, sigs); std::map<Ciphersuite, u16bit, Ciphersuite_Preference_Ordering> ciphersuites(order); for(size_t i = 0; i != 65536; ++i) { Ciphersuite suite = Ciphersuite::by_id(i); if(!suite.valid()) continue; // not a ciphersuite we know, skip if(!have_srp && suite.kex_algo() == "SRP_SHA") continue; if(!value_exists(kex, suite.kex_algo())) continue; // unsupported key exchange if(!value_exists(ciphers, suite.cipher_algo())) continue; // unsupported cipher if(!value_exists(hashes, suite.mac_algo())) continue; // unsupported MAC algo if(!value_exists(sigs, suite.sig_algo())) { // allow if it's an empty sig algo and we want to use PSK if(suite.sig_algo() != "" || !suite.psk_ciphersuite()) continue; } // OK, allow it: ciphersuites[suite] = i; } std::vector<u16bit> ciphersuite_codes; for(std::map<Ciphersuite, u16bit, Ciphersuite_Preference_Ordering>::iterator i = ciphersuites.begin(); i != ciphersuites.end(); ++i) { ciphersuite_codes.push_back(i->second); } return ciphersuite_codes; } } } <|endoftext|>
<commit_before>// // Programmer: Alexander Morgan // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Sat Aug 8 12:24:49 PDT 2015 // Last Modified: Sat Dec 24 15:48:01 PST 2016 // Filename: tool-dissonant.cpp // URL: https://github.com/craigsapp/minHumdrum/blob/master/src/tool-dissonant.cpp // Syntax: C++11 // vim: ts=3 noexpandtab // // Description: Dissonance identification and labeling tool. // #include "tool-dissonant.h" #include "Convert.h" #include <algorithm> #include <cmath> using namespace std; namespace hum { // START_MERGE ///////////////////////////////// // // Tool_dissonant::Tool_dissonant -- Set the recognized options for the tool. // Tool_dissonant::Tool_dissonant(void) { define("r|raw=b", "print raw grid"); define("d|diatonic=b", "print diatonic grid"); define("D|no-dissonant=b", "don't do dissonance anaysis"); define("m|midi-pitch=b", "print midi-pitch grid"); define("b|base-40=b", "print base-40 grid"); define("l|metric-levels=b", "use metric levels in analysis"); define("k|kern=b", "print kern pitch grid"); define("debug=b", "print grid cell information"); define("e|exinterp=s:**data", "specify exinterp for **data spine"); define("c|colorize=b", "color dissonant notes"); } ///////////////////////////////// // // Tool_dissonant::run -- Do the main work of the tool. // bool Tool_dissonant::run(const string& indata, ostream& out) { HumdrumFile infile(indata); bool status = run(infile); if (hasAnyText()) { getAllText(out); } else { out << infile; } return status; } bool Tool_dissonant::run(HumdrumFile& infile, ostream& out) { int status = run(infile); if (hasAnyText()) { getAllText(out); } else { out << infile; } return status; } bool Tool_dissonant::run(HumdrumFile& infile) { NoteGrid grid(infile); if (getBoolean("debug")) { grid.printGridInfo(cerr); // return 1; } else if (getBoolean("raw")) { grid.printRawGrid(m_free_text); return 1; } else if (getBoolean("diatonic")) { grid.printDiatonicGrid(m_free_text); return 1; } else if (getBoolean("midi-pitch")) { grid.printMidiGrid(m_free_text); return 1; } else if (getBoolean("base-40")) { grid.printBase40Grid(m_free_text); return 1; } else if (getBoolean("kern")) { grid.printKernGrid(m_free_text); return 1; } diss2Q = false; diss7Q = false; diss4Q = false; vector<vector<string> > results; results.resize(grid.getVoiceCount()); for (int i=0; i<(int)results.size(); i++) { results[i].resize(infile.getLineCount()); } doAnalysis(results, grid, getBoolean("debug")); string exinterp = getString("exinterp"); vector<HTp> kernspines = infile.getKernSpineStartList(); infile.appendDataSpine(results.back(), "", exinterp); for (int i = (int)results.size()-1; i>0; i--) { int track = kernspines[i]->getTrack(); infile.insertDataSpineBefore(track, results[i-1], "", exinterp); } if (getBoolean("colorize")) { if (diss2Q) { infile.appendLine("!!!RDF**kern: @ = dissonant 2nd, marked note, color=\"#33bb00\""); } if (diss7Q) { infile.appendLine("!!!RDF**kern: + = dissonant 7th, marked note, color=\"#0099ff\""); } if (diss4Q) { infile.appendLine("!!!RDF**kern: N = dissonant 4th marked note, color=\"#bb3300\""); } } infile.createLinesFromTokens(); return true; } ////////////////////////////// // // Tool_dissonant::doAnalysis -- do a basic melodic analysis of all parts. // void Tool_dissonant::doAnalysis(vector<vector<string> >& results, NoteGrid& grid, bool debug) { for (int i=0; i<grid.getVoiceCount(); i++) { doAnalysisForVoice(results[i], grid, i, debug); } } ////////////////////////////// // // Tool_dissonant::doAnalysisForVoice -- do analysis for a single voice by // subtracting NoteCells to calculate the diatonic intervals. // void Tool_dissonant::doAnalysisForVoice(vector<string>& results, NoteGrid& grid, int vindex, bool debug) { vector<NoteCell*> attacks; grid.getNoteAndRestAttacks(attacks, vindex); if (debug) { cerr << "======================================================="; cerr << endl; cerr << "Note attacks for voice number " << grid.getVoiceCount()-vindex << ":" << endl; for (int i=0; i<(int)attacks.size(); i++) { attacks[i]->printNoteInfo(cerr); } } bool nodissonanceQ = getBoolean("no-dissonant"); bool colorizeQ = getBoolean("colorize"); HumNum durp; // duration of previous melodic note; HumNum dur; // duration of current note; HumNum durn; // duration of next melodic note; HumNum durnn; // duration of next next melodic note; double intp; // diatonic interval from previous melodic note double intn; // diatonic interval to next melodic note double levp; // metric level of the previous melodic note double lev; // metric level of the current note double levn; // metric level of the next melodic note int lineindex; // line in original Humdrum file content that contains note int sliceindex; // current timepoint in NoteGrid. vector<double> harmint(grid.getVoiceCount()); // harmonic intervals; bool dissonant; // true if note is dissonant with other sounding notes. char marking = '\0'; for (int i=1; i<(int)attacks.size() - 1; i++) { sliceindex = attacks[i]->getSliceIndex(); lineindex = attacks[i]->getLineIndex(); marking = '\0'; // calculate harmonic intervals: double lowestnote = 1000; double tpitch; for (int j=0; j<(int)harmint.size(); j++) { tpitch = grid.cell(j, sliceindex)->getAbsDiatonicPitch(); if (!Convert::isNaN(tpitch)) { if (tpitch < lowestnote) { lowestnote = tpitch; } } if (j == vindex) { harmint[j] = 0; } if (j < vindex) { harmint[j] = *grid.cell(vindex, sliceindex) - *grid.cell(j, sliceindex); } else { harmint[j] = *grid.cell(j, sliceindex) - *grid.cell(vindex, sliceindex); } } // check if current note is dissonant to another sounding note: dissonant = false; for (int j=0; j<(int)harmint.size(); j++) { if (j == vindex) { // don't compare to self continue; } if (Convert::isNaN(harmint[j])) { // rest, so ignore continue; } int value = (int)harmint[j]; if (value > 7) { value = value % 7; // remove octaves from interval } else if (value < -7) { value = -(-value % 7); // remove octaves from interval } if ((value == 1) || (value == -1)) { // forms a second with another sounding note dissonant = true; diss2Q = true; marking = '@'; results[lineindex] = "d2"; break; } else if ((value == 6) || (value == -6)) { // forms a seventh with another sounding note dissonant = true; diss7Q = true; marking = '+'; results[lineindex] = "d7"; break; } } double vpitch = grid.cell(vindex, sliceindex)->getAbsDiatonicPitch(); if (vpitch - lowestnote > 0) { if (int(vpitch - lowestnote) % 7 == 3) { diss4Q = true; marking = 'N'; results[lineindex] = "d4"; dissonant = true; } } // Don't label current note if not dissonant with other sounding notes. if (!dissonant) { if (!nodissonanceQ) { continue; } } if (colorizeQ && marking) { // mark note string text = *attacks[i]->getToken(); if (text.find(marking) == string::npos) { text += marking; attacks[i]->getToken()->setText(text); } } durp = attacks[i-1]->getDuration(); dur = attacks[i]->getDuration(); durn = attacks[i+1]->getDuration(); intp = *attacks[i] - *attacks[i-1]; intn = *attacks[i+1] - *attacks[i]; levp = attacks[i-1]->getMetricLevel(); lev = attacks[i]->getMetricLevel(); levn = attacks[i+1]->getMetricLevel(); if ((dur <= durp) && (lev >= levp) && (lev >= levn)) { // weak dissonances if (intp == -1) { // descending dissonances if (intn == -1) { results[lineindex] = "pd"; // downward passing tone } else if (intn == 1) { results[lineindex] = "nd"; // lower neighbor } else if (intn == 0) { results[lineindex] = "ad"; // descending anticipation } else if (intn > 1) { results[lineindex] = "ed"; // lower échappée } else if (intn == -2) { results[lineindex] = "scd"; // short descending nota cambiata } else if (intn < -2) { results[lineindex] = "ipd"; // incomplete posterior lower neighbor } } else if (intp == 1) { // ascending dissonances if (intn == 1) { results[lineindex] = "pu"; // rising passing tone } else if (intn == -1) { results[lineindex] = "nu"; // upper neighbor } else if (intn < -1) { results[lineindex] = "eu"; // upper échappée } else if (intn == 0) { results[lineindex] = "au"; // rising anticipation } else if (intn == 2) { results[lineindex] = "scu"; // short ascending nota cambiata } else if (intn > 2) { results[lineindex] = "ipu"; // incomplete posterior upper neighbor } } else if ((intp < -2) && (intn == 1)) { results[lineindex] = "iad"; // incomplete anterior lower neighbor } else if ((intp > 2) && (intn == -1)) { results[lineindex] = "iau"; // incomplete anterior upper neighbor } } // TODO: add check to see if results already has a result. if (i < ((int)attacks.size() - 2)) { // expand the analysis window double interval3 = *attacks[i+2] - *attacks[i+1]; HumNum durnn = attacks[i+2]->getDuration(); // dur of note after next double levnn = attacks[i+2]->getMetricLevel(); // lev of note after next if ((dur == durn) && (lev == 1) && (levn == 2) && (levnn == 0) && (intp == -1) && (intn == -1) && (interval3 == 1)) { results[lineindex] = "ci"; // chanson idiom } else if ((durp >= 2) && (dur == 1) && (lev < levn) && (intp == -1) && (intn == -1)) { results[lineindex] = "dq"; // dissonant third quarter } else if ((dur <= durp) && (lev >= levp) && (lev >= levn) && (intp == -1) && (intn == -2) && (interval3 == 1)) { results[lineindex] = "lcd"; // long descending nota cambiata } else if ((dur <= durp) && (lev >= levp) && (lev >= levn) && (intp == 1) && (intn == 2) && (interval3 == -1)) { results[lineindex] = "lcu"; // long ascending nota cambiata } } } } // END_MERGE } // end namespace hum <commit_msg>Remove "long-form" nota cambiata detection.<commit_after>// // Programmer: Alexander Morgan // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Sat Aug 8 12:24:49 PDT 2015 // Last Modified: Sat Dec 24 15:48:01 PST 2016 // Filename: tool-dissonant.cpp // URL: https://github.com/craigsapp/minHumdrum/blob/master/src/tool-dissonant.cpp // Syntax: C++11 // vim: ts=3 noexpandtab // // Description: Dissonance identification and labeling tool. // #include "tool-dissonant.h" #include "Convert.h" #include <algorithm> #include <cmath> using namespace std; namespace hum { // START_MERGE ///////////////////////////////// // // Tool_dissonant::Tool_dissonant -- Set the recognized options for the tool. // Tool_dissonant::Tool_dissonant(void) { define("r|raw=b", "print raw grid"); define("d|diatonic=b", "print diatonic grid"); define("D|no-dissonant=b", "don't do dissonance anaysis"); define("m|midi-pitch=b", "print midi-pitch grid"); define("b|base-40=b", "print base-40 grid"); define("l|metric-levels=b", "use metric levels in analysis"); define("k|kern=b", "print kern pitch grid"); define("debug=b", "print grid cell information"); define("e|exinterp=s:**data", "specify exinterp for **data spine"); define("c|colorize=b", "color dissonant notes"); } ///////////////////////////////// // // Tool_dissonant::run -- Do the main work of the tool. // bool Tool_dissonant::run(const string& indata, ostream& out) { HumdrumFile infile(indata); bool status = run(infile); if (hasAnyText()) { getAllText(out); } else { out << infile; } return status; } bool Tool_dissonant::run(HumdrumFile& infile, ostream& out) { int status = run(infile); if (hasAnyText()) { getAllText(out); } else { out << infile; } return status; } bool Tool_dissonant::run(HumdrumFile& infile) { NoteGrid grid(infile); if (getBoolean("debug")) { grid.printGridInfo(cerr); // return 1; } else if (getBoolean("raw")) { grid.printRawGrid(m_free_text); return 1; } else if (getBoolean("diatonic")) { grid.printDiatonicGrid(m_free_text); return 1; } else if (getBoolean("midi-pitch")) { grid.printMidiGrid(m_free_text); return 1; } else if (getBoolean("base-40")) { grid.printBase40Grid(m_free_text); return 1; } else if (getBoolean("kern")) { grid.printKernGrid(m_free_text); return 1; } diss2Q = false; diss7Q = false; diss4Q = false; vector<vector<string> > results; results.resize(grid.getVoiceCount()); for (int i=0; i<(int)results.size(); i++) { results[i].resize(infile.getLineCount()); } doAnalysis(results, grid, getBoolean("debug")); string exinterp = getString("exinterp"); vector<HTp> kernspines = infile.getKernSpineStartList(); infile.appendDataSpine(results.back(), "", exinterp); for (int i = (int)results.size()-1; i>0; i--) { int track = kernspines[i]->getTrack(); infile.insertDataSpineBefore(track, results[i-1], "", exinterp); } if (getBoolean("colorize")) { if (diss2Q) { infile.appendLine("!!!RDF**kern: @ = dissonant 2nd, marked note, color=\"#33bb00\""); } if (diss7Q) { infile.appendLine("!!!RDF**kern: + = dissonant 7th, marked note, color=\"#0099ff\""); } if (diss4Q) { infile.appendLine("!!!RDF**kern: N = dissonant 4th marked note, color=\"#bb3300\""); } } infile.createLinesFromTokens(); return true; } ////////////////////////////// // // Tool_dissonant::doAnalysis -- do a basic melodic analysis of all parts. // void Tool_dissonant::doAnalysis(vector<vector<string> >& results, NoteGrid& grid, bool debug) { for (int i=0; i<grid.getVoiceCount(); i++) { doAnalysisForVoice(results[i], grid, i, debug); } } ////////////////////////////// // // Tool_dissonant::doAnalysisForVoice -- do analysis for a single voice by // subtracting NoteCells to calculate the diatonic intervals. // void Tool_dissonant::doAnalysisForVoice(vector<string>& results, NoteGrid& grid, int vindex, bool debug) { vector<NoteCell*> attacks; grid.getNoteAndRestAttacks(attacks, vindex); if (debug) { cerr << "======================================================="; cerr << endl; cerr << "Note attacks for voice number " << grid.getVoiceCount()-vindex << ":" << endl; for (int i=0; i<(int)attacks.size(); i++) { attacks[i]->printNoteInfo(cerr); } } bool nodissonanceQ = getBoolean("no-dissonant"); bool colorizeQ = getBoolean("colorize"); HumNum durp; // duration of previous melodic note; HumNum dur; // duration of current note; HumNum durn; // duration of next melodic note; HumNum durnn; // duration of next next melodic note; double intp; // diatonic interval from previous melodic note double intn; // diatonic interval to next melodic note double levp; // metric level of the previous melodic note double lev; // metric level of the current note double levn; // metric level of the next melodic note int lineindex; // line in original Humdrum file content that contains note int sliceindex; // current timepoint in NoteGrid. vector<double> harmint(grid.getVoiceCount()); // harmonic intervals; bool dissonant; // true if note is dissonant with other sounding notes. char marking = '\0'; for (int i=1; i<(int)attacks.size() - 1; i++) { sliceindex = attacks[i]->getSliceIndex(); lineindex = attacks[i]->getLineIndex(); marking = '\0'; // calculate harmonic intervals: double lowestnote = 1000; double tpitch; for (int j=0; j<(int)harmint.size(); j++) { tpitch = grid.cell(j, sliceindex)->getAbsDiatonicPitch(); if (!Convert::isNaN(tpitch)) { if (tpitch < lowestnote) { lowestnote = tpitch; } } if (j == vindex) { harmint[j] = 0; } if (j < vindex) { harmint[j] = *grid.cell(vindex, sliceindex) - *grid.cell(j, sliceindex); } else { harmint[j] = *grid.cell(j, sliceindex) - *grid.cell(vindex, sliceindex); } } // check if current note is dissonant to another sounding note: dissonant = false; for (int j=0; j<(int)harmint.size(); j++) { if (j == vindex) { // don't compare to self continue; } if (Convert::isNaN(harmint[j])) { // rest, so ignore continue; } int value = (int)harmint[j]; if (value > 7) { value = value % 7; // remove octaves from interval } else if (value < -7) { value = -(-value % 7); // remove octaves from interval } if ((value == 1) || (value == -1)) { // forms a second with another sounding note dissonant = true; diss2Q = true; marking = '@'; results[lineindex] = "d2"; break; } else if ((value == 6) || (value == -6)) { // forms a seventh with another sounding note dissonant = true; diss7Q = true; marking = '+'; results[lineindex] = "d7"; break; } } double vpitch = grid.cell(vindex, sliceindex)->getAbsDiatonicPitch(); if (vpitch - lowestnote > 0) { if (int(vpitch - lowestnote) % 7 == 3) { diss4Q = true; marking = 'N'; results[lineindex] = "d4"; dissonant = true; } } // Don't label current note if not dissonant with other sounding notes. if (!dissonant) { if (!nodissonanceQ) { continue; } } if (colorizeQ && marking) { // mark note string text = *attacks[i]->getToken(); if (text.find(marking) == string::npos) { text += marking; attacks[i]->getToken()->setText(text); } } durp = attacks[i-1]->getDuration(); dur = attacks[i]->getDuration(); durn = attacks[i+1]->getDuration(); intp = *attacks[i] - *attacks[i-1]; intn = *attacks[i+1] - *attacks[i]; levp = attacks[i-1]->getMetricLevel(); lev = attacks[i]->getMetricLevel(); levn = attacks[i+1]->getMetricLevel(); if ((dur <= durp) && (lev >= levp) && (lev >= levn)) { // weak dissonances if (intp == -1) { // descending dissonances if (intn == -1) { results[lineindex] = "pd"; // downward passing tone } else if (intn == 1) { results[lineindex] = "nd"; // lower neighbor } else if (intn == 0) { results[lineindex] = "ad"; // descending anticipation } else if (intn > 1) { results[lineindex] = "ed"; // lower échappée } else if (intn == -2) { results[lineindex] = "cd"; // descending nota cambiata } else if (intn < -2) { results[lineindex] = "ipd"; // incomplete posterior lower neighbor } } else if (intp == 1) { // ascending dissonances if (intn == 1) { results[lineindex] = "pu"; // rising passing tone } else if (intn == -1) { results[lineindex] = "nu"; // upper neighbor } else if (intn < -1) { results[lineindex] = "eu"; // upper échappée } else if (intn == 0) { results[lineindex] = "au"; // rising anticipation } else if (intn == 2) { results[lineindex] = "cu"; // ascending nota cambiata } else if (intn > 2) { results[lineindex] = "ipu"; // incomplete posterior upper neighbor } } else if ((intp < -2) && (intn == 1)) { results[lineindex] = "iad"; // incomplete anterior lower neighbor } else if ((intp > 2) && (intn == -1)) { results[lineindex] = "iau"; // incomplete anterior upper neighbor } } else if ((durp >= 2) && (dur == 1) && (lev < levn) && (intp == -1) && (intn == -1)) { results[lineindex] = "dq"; // dissonant third quarter } else if (i < ((int)attacks.size() - 2)) { // expand the analysis window double interval3 = *attacks[i+2] - *attacks[i+1]; HumNum durnn = attacks[i+2]->getDuration(); // dur of note after next double levnn = attacks[i+2]->getMetricLevel(); // lev of note after next if ((dur == durn) && (lev == 1) && (levn == 2) && (levnn == 0) && (intp == -1) && (intn == -1) && (interval3 == 1)) { results[lineindex] = "ci"; // chanson idiom } } } } // END_MERGE } // end namespace hum <|endoftext|>
<commit_before>/// /// @file primecount.cpp /// @brief primecount C++ API /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <calculator.hpp> #include <ptypes.hpp> #include <pmath.hpp> #include <algorithm> #include <ctime> #include <iostream> #include <iomanip> #include <limits> #include <sstream> #include <string> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif using namespace std; namespace { int threads_ = primecount::MAX_THREADS; bool print_status_ = false; } namespace primecount { int64_t pi(int64_t x) { return pi(x, threads_); } int64_t pi(int64_t x, int threads) { return pi_deleglise_rivat(x, threads); } #ifdef HAVE_INT128_T int128_t pi(int128_t x) { return pi(x, threads_); } int128_t pi(int128_t x, int threads) { return pi_deleglise_rivat(x, threads); } #endif /// Alias for the fastest prime counting function in primecount. /// @param x integer or arithmetic expression like "10^12". /// @pre x <= primecount::max(). /// std::string pi(const std::string& x) { return pi(x, threads_); } /// Alias for the fastest prime counting function in primecount. /// @param x integer or arithmetic expression like "10^12". /// @pre x <= primecount::max(). /// std::string pi(const std::string& x, int threads) { maxint_t n = to_maxint(x); maxint_t pin = pi(n, threads); ostringstream oss; oss << pin; return oss.str(); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat(int64_t x) { return pi_deleglise_rivat(x, threads_); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat(int64_t x, int threads) { if (threads <= 1) return pi_deleglise_rivat3(x); return pi_deleglise_rivat_parallel3(x, threads); } #ifdef HAVE_INT128_T /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat(int128_t x) { return pi_deleglise_rivat(x, threads_); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi_deleglise_rivat((int64_t) x, threads); if (threads <= 1) return pi_deleglise_rivat4(x); else return pi_deleglise_rivat_parallel4(x, threads); } #endif /// Calculate the number of primes below x using Legendre's formula. /// Run time: O(x) operations, O(x^(1/2)) space. /// int64_t pi_legendre(int64_t x) { return pi_legendre(x, threads_); } /// Calculate the number of primes below x using Lehmer's formula. /// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space. /// int64_t pi_lehmer(int64_t x) { return pi_lehmer(x, threads_); } /// Calculate the number of primes below x using the /// Lagarias-Miller-Odlyzko algorithm. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo(int64_t x) { return pi_lmo(x, threads_); } /// Parallel implementation of the Lagarias-Miller-Odlyzko /// prime counting algorithm using OpenMP. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo(int64_t x, int threads) { if (threads <= 1) return pi_lmo5(x); return pi_lmo_parallel3(x, threads); } /// Calculate the number of primes below x using Meissel's formula. /// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space. /// int64_t pi_meissel(int64_t x) { return pi_meissel(x, threads_); } /// Calculate the number of primes below x using an optimized /// segmented sieve of Eratosthenes implementation. /// Run time: O(x log log x) operations, O(x^(1/2)) space. /// int64_t pi_primesieve(int64_t x) { return pi_primesieve(x, threads_); } /// Calculate the nth prime using a combination of an efficient prime /// counting function implementation and the sieve of Eratosthenes. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space. /// int64_t nth_prime(int64_t n) { return nth_prime(n, threads_); } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t phi(int64_t x, int64_t a) { return phi(x, a, threads_); } /// Returns the largest integer that can be used with /// pi(std::string x). The return type is a string as max may be a /// 128-bit integer which is not supported by all compilers. /// std::string max() { #ifdef HAVE_INT128_T return string("1") + string(27, '0'); #else ostringstream oss; oss << numeric_limits<int64_t>::max(); return oss.str(); #endif } /// Get the wall time in seconds. double get_wtime() { #ifdef _OPENMP return omp_get_wtime(); #else return static_cast<double>(std::clock()) / CLOCKS_PER_SEC; #endif } int validate_threads(int threads) { #ifdef _OPENMP if (threads == MAX_THREADS) threads = omp_get_max_threads(); return in_between(1, threads, omp_get_max_threads()); #else threads = 1; return threads; #endif } int validate_threads(int threads, int64_t sieve_limit, int64_t thread_threshold) { threads = validate_threads(threads); threads = (int) std::min((int64_t) threads, sieve_limit / thread_threshold); threads = std::max(1, threads); return threads; } void set_num_threads(int threads) { threads_ = validate_threads(threads); } int get_num_threads() { return validate_threads(threads_); } maxint_t to_maxint(const std::string& expr) { maxint_t n = calculator::eval<maxint_t>(expr); return n; } void print_percent(maxint_t s2_current, maxint_t s2_approx, double rsd) { int percent = get_percent(s2_current, s2_approx); int load_balance = (int) in_between(0, 100 - rsd + 0.5, 100); ostringstream oss; oss << "\r" << string(40,' '); oss << "\rStatus: " << percent << "%, "; oss << "Load balance: " << load_balance << "%"; cout << oss.str() << flush; } void print_result(const std::string& str, maxint_t res, double time) { cout << "\r" << string(40,' ') << "\r"; cout << "Status: 100%" << endl; cout << str << " = " << res << endl; print_seconds(get_wtime() - time); } void print_seconds(double seconds) { cout << "Seconds: " << fixed << setprecision(3) << seconds << endl; } void print_megabytes(std::size_t bytes) { double megabytes = bytes / (double) (1 << 20); cout << "memory usage = " << fixed << setprecision(3) << megabytes << " megabytes" << endl; } void set_print_status(bool print_status) { print_status_ = print_status; } bool print_status() { return print_status_; } } // namespace primecount <commit_msg>Improved S2 progress information<commit_after>/// /// @file primecount.cpp /// @brief primecount C++ API /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <calculator.hpp> #include <ptypes.hpp> #include <pmath.hpp> #include <algorithm> #include <ctime> #include <iostream> #include <iomanip> #include <limits> #include <sstream> #include <string> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif using namespace std; namespace { int threads_ = primecount::MAX_THREADS; bool print_status_ = false; } namespace primecount { int64_t pi(int64_t x) { return pi(x, threads_); } int64_t pi(int64_t x, int threads) { return pi_deleglise_rivat(x, threads); } #ifdef HAVE_INT128_T int128_t pi(int128_t x) { return pi(x, threads_); } int128_t pi(int128_t x, int threads) { return pi_deleglise_rivat(x, threads); } #endif /// Alias for the fastest prime counting function in primecount. /// @param x integer or arithmetic expression like "10^12". /// @pre x <= primecount::max(). /// std::string pi(const std::string& x) { return pi(x, threads_); } /// Alias for the fastest prime counting function in primecount. /// @param x integer or arithmetic expression like "10^12". /// @pre x <= primecount::max(). /// std::string pi(const std::string& x, int threads) { maxint_t n = to_maxint(x); maxint_t pin = pi(n, threads); ostringstream oss; oss << pin; return oss.str(); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat(int64_t x) { return pi_deleglise_rivat(x, threads_); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat(int64_t x, int threads) { if (threads <= 1) return pi_deleglise_rivat3(x); return pi_deleglise_rivat_parallel3(x, threads); } #ifdef HAVE_INT128_T /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat(int128_t x) { return pi_deleglise_rivat(x, threads_); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi_deleglise_rivat((int64_t) x, threads); if (threads <= 1) return pi_deleglise_rivat4(x); else return pi_deleglise_rivat_parallel4(x, threads); } #endif /// Calculate the number of primes below x using Legendre's formula. /// Run time: O(x) operations, O(x^(1/2)) space. /// int64_t pi_legendre(int64_t x) { return pi_legendre(x, threads_); } /// Calculate the number of primes below x using Lehmer's formula. /// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space. /// int64_t pi_lehmer(int64_t x) { return pi_lehmer(x, threads_); } /// Calculate the number of primes below x using the /// Lagarias-Miller-Odlyzko algorithm. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo(int64_t x) { return pi_lmo(x, threads_); } /// Parallel implementation of the Lagarias-Miller-Odlyzko /// prime counting algorithm using OpenMP. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo(int64_t x, int threads) { if (threads <= 1) return pi_lmo5(x); return pi_lmo_parallel3(x, threads); } /// Calculate the number of primes below x using Meissel's formula. /// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space. /// int64_t pi_meissel(int64_t x) { return pi_meissel(x, threads_); } /// Calculate the number of primes below x using an optimized /// segmented sieve of Eratosthenes implementation. /// Run time: O(x log log x) operations, O(x^(1/2)) space. /// int64_t pi_primesieve(int64_t x) { return pi_primesieve(x, threads_); } /// Calculate the nth prime using a combination of an efficient prime /// counting function implementation and the sieve of Eratosthenes. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space. /// int64_t nth_prime(int64_t n) { return nth_prime(n, threads_); } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t phi(int64_t x, int64_t a) { return phi(x, a, threads_); } /// Returns the largest integer that can be used with /// pi(std::string x). The return type is a string as max may be a /// 128-bit integer which is not supported by all compilers. /// std::string max() { #ifdef HAVE_INT128_T return string("1") + string(27, '0'); #else ostringstream oss; oss << numeric_limits<int64_t>::max(); return oss.str(); #endif } /// Get the wall time in seconds. double get_wtime() { #ifdef _OPENMP return omp_get_wtime(); #else return static_cast<double>(std::clock()) / CLOCKS_PER_SEC; #endif } int validate_threads(int threads) { #ifdef _OPENMP if (threads == MAX_THREADS) threads = omp_get_max_threads(); return in_between(1, threads, omp_get_max_threads()); #else threads = 1; return threads; #endif } int validate_threads(int threads, int64_t sieve_limit, int64_t thread_threshold) { threads = validate_threads(threads); threads = (int) std::min((int64_t) threads, sieve_limit / thread_threshold); threads = std::max(1, threads); return threads; } void set_num_threads(int threads) { threads_ = validate_threads(threads); } int get_num_threads() { return validate_threads(threads_); } maxint_t to_maxint(const std::string& expr) { maxint_t n = calculator::eval<maxint_t>(expr); return n; } void print_percent(maxint_t s2_current, maxint_t s2_approx, double rsd) { double percent = get_percent((double) s2_current, (double) s2_approx); double base = 0.95 + percent / 2000; double min = pow(base, 100.0); double max = pow(base, 0.0); percent = 100 - in_between(0, 100 * (pow(base, percent) - min) / (max - min), 100); int load_balance = (int) in_between(0, 100 - rsd + 0.5, 100); ostringstream oss; oss << "\r" << string(40,' ') << "\r"; oss << "Status: " << (int) percent << "%, "; oss << "Load balance: " << load_balance << "%"; cout << oss.str() << flush; } void print_result(const std::string& str, maxint_t res, double time) { cout << "\r" << string(40,' ') << "\r"; cout << "Status: 100%" << endl; cout << str << " = " << res << endl; print_seconds(get_wtime() - time); } void print_seconds(double seconds) { cout << "Seconds: " << fixed << setprecision(3) << seconds << endl; } void print_megabytes(std::size_t bytes) { double megabytes = bytes / (double) (1 << 20); cout << "memory usage = " << fixed << setprecision(3) << megabytes << " megabytes" << endl; } void set_print_status(bool print_status) { print_status_ = print_status; } bool print_status() { return print_status_; } } // namespace primecount <|endoftext|>
<commit_before>/// /// @file primecount.cpp /// @brief primecount C++ API /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <primecount.hpp> #include <calculator.hpp> #include <int128_t.hpp> #include <imath.hpp> #include <algorithm> #include <ctime> #include <cmath> #include <limits> #include <sstream> #include <string> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif #ifdef HAVE_MPI #include <mpi.h> namespace primecount { int mpi_num_procs() { int procs; MPI_Comm_size(MPI_COMM_WORLD, &procs); return procs; } int mpi_proc_id() { int proc_id; MPI_Comm_rank(MPI_COMM_WORLD, &proc_id); return proc_id; } int mpi_master_proc_id() { return 0; } bool is_mpi_master_proc() { return mpi_proc_id() == mpi_master_proc_id(); } } // namespace #endif using namespace std; namespace { #ifdef _OPENMP int threads_ = -1; #endif int status_precision_ = -1; double alpha_ = -1; // Below 10^7 the Deleglise-Rivat algorithm is slower than LMO const int deleglise_rivat_threshold = 10000000; } namespace primecount { int64_t pi(int64_t x) { return pi(x, get_num_threads()); } int64_t pi(int64_t x, int threads) { if (x < deleglise_rivat_threshold) return pi_lmo(x, threads); else return pi_deleglise_rivat(x, threads); } #ifdef HAVE_INT128_T int128_t pi(int128_t x) { return pi(x, get_num_threads()); } int128_t pi(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi((int64_t) x, threads); else return pi_deleglise_rivat(x, threads); } #endif /// Alias for the fastest prime counting function in primecount. /// @param x integer arithmetic expression e.g. "10^12". /// @pre x <= get_max_x(). /// string pi(const string& x) { return pi(x, get_num_threads()); } /// Alias for the fastest prime counting function in primecount. /// @param x integer arithmetic expression e.g. "10^12". /// @pre x <= get_max_x(). /// string pi(const string& x, int threads) { maxint_t pi_x = pi(to_maxint(x), threads); ostringstream oss; oss << pi_x; return oss.str(); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat(int64_t x) { return pi_deleglise_rivat(x, get_num_threads()); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat(int64_t x, int threads) { return pi_deleglise_rivat_parallel2(x, threads); } #ifdef HAVE_INT128_T /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat(int128_t x) { return pi_deleglise_rivat(x, get_num_threads()); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi_deleglise_rivat((int64_t) x, threads); else return pi_deleglise_rivat_parallel3(x, threads); } #endif /// Calculate the number of primes below x using Legendre's formula. /// Run time: O(x) operations, O(x^(1/2)) space. /// int64_t pi_legendre(int64_t x) { return pi_legendre(x, get_num_threads()); } /// Calculate the number of primes below x using Lehmer's formula. /// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space. /// int64_t pi_lehmer(int64_t x) { return pi_lehmer(x, get_num_threads()); } /// Calculate the number of primes below x using the /// Lagarias-Miller-Odlyzko algorithm. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo(int64_t x) { return pi_lmo(x, get_num_threads()); } /// Parallel implementation of the Lagarias-Miller-Odlyzko /// prime counting algorithm using OpenMP. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo(int64_t x, int threads) { return pi_lmo_parallel3(x, threads); } /// Calculate the number of primes below x using Meissel's formula. /// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space. /// int64_t pi_meissel(int64_t x) { return pi_meissel(x, get_num_threads()); } /// Calculate the number of primes below x using an optimized /// segmented sieve of Eratosthenes implementation. /// Run time: O(x log log x) operations, O(x^(1/2)) space. /// int64_t pi_primesieve(int64_t x) { return pi_primesieve(x, get_num_threads()); } /// Calculate the nth prime using a combination of the prime /// counting function and the sieve of Eratosthenes. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space. /// int64_t nth_prime(int64_t n) { return nth_prime(n, get_num_threads()); } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t phi(int64_t x, int64_t a) { return phi(x, a, get_num_threads()); } /// Returns the largest integer that can be used with /// pi(string x). The return type is a string as max can be a 128-bit /// integer which is not supported by all compilers. /// string get_max_x(double alpha) { ostringstream oss; #ifdef HAVE_INT128_T // primecount is limited by: // z < 2^62, with z = x^(2/3) / alpha // x^(2/3) / alpha < 2^62 // x < (2^62 * alpha)^(3/2) // safety buffer: use 61 instead of 62 double max_x = pow(pow(2.0, 61.0) * alpha, 3.0 / 2.0); oss << (int128_t) max_x; #else unused_param(alpha); oss << numeric_limits<int64_t>::max(); #endif return oss.str(); } /// Get the wall time in seconds. double get_wtime() { #ifdef _OPENMP return omp_get_wtime(); #else return (double) (std::clock() / CLOCKS_PER_SEC); #endif } int ideal_num_threads(int threads, int64_t sieve_limit, int64_t thread_threshold) { thread_threshold = max((int64_t) 1, thread_threshold); threads = (int) min((int64_t) threads, sieve_limit / thread_threshold); threads = max(1, threads); return threads; } void set_alpha(double alpha) { alpha_ = alpha; } double get_alpha() { return alpha_; } double get_alpha(maxint_t x, int64_t y) { // y = x13 * alpha, thus alpha = y / x13 double x13 = (double) iroot<3>(x); return (double) y / x13; } /// Calculate the Lagarias-Miller-Odlyzko alpha tuning factor. /// alpha = a log(x)^2 + b log(x) + c /// a, b and c are constants that should be determined empirically. /// @see ../doc/alpha-factor-tuning.pdf /// double get_alpha_lmo(maxint_t x) { double alpha = get_alpha(); // use default alpha if no command-line alpha provided if (alpha < 1) { double a = 0.00156512; double b = -0.0261411; double c = 0.990948; double logx = log((double) x); alpha = a * pow(logx, 2) + b * logx + c; } return in_between(1, alpha, iroot<6>(x)); } /// Calculate the Deleglise-Rivat alpha tuning factor. /// alpha = a log(x)^3 + b log(x)^2 + c log(x) + d /// a, b, c and d are constants that should be determined empirically. /// @see ../doc/alpha-tuning-factor.pdf /// double get_alpha_deleglise_rivat(maxint_t x) { double alpha = get_alpha(); double x2 = (double) x; // use default alpha if no command-line alpha provided if (alpha < 1) { if (x2 <= 1e21) { double a = 0.000711339; double b = -0.0160586; double c = 0.123034; double d = 0.802942; double logx = log(x2); alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d; } else { // Because of CPU cache misses sieving (S2_hard(x) and P2(x)) // becomes the main bottleneck above 10^21 . Hence we use a // different alpha formula when x > 10^21 which returns a larger // alpha which reduces sieving but increases S2_easy(x) work. double a = 0.00149066; double b = -0.0375705; double c = 0.282139; double d = 0.591972; double logx = log(x2); alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d; } } return in_between(1, alpha, iroot<6>(x)); } void set_num_threads(int threads) { #ifdef _OPENMP threads_ = in_between(1, threads, omp_get_max_threads()); #else unused_param(threads); #endif } int get_num_threads() { #ifdef _OPENMP if (threads_ != -1) return threads_; else return max(1, omp_get_max_threads()); #else return 1; #endif } void set_status_precision(int precision) { status_precision_ = in_between(0, precision, 5); } int get_status_precision(maxint_t x) { // use default precision when no command-line precision provided if (status_precision_ < 0) { if ((double) x >= 1e23) return 2; if ((double) x >= 1e21) return 1; } return (status_precision_ > 0) ? status_precision_ : 0; } maxint_t to_maxint(const string& expr) { maxint_t n = calculator::eval<maxint_t>(expr); return n; } /// Get the primecount version number, in the form “i.j”. string primecount_version() { return PRIMECOUNT_VERSION; } } // namespace <commit_msg>Fix time measuring<commit_after>/// /// @file primecount.cpp /// @brief primecount C++ API /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <primecount.hpp> #include <calculator.hpp> #include <int128_t.hpp> #include <imath.hpp> #include <algorithm> #include <ctime> #include <cmath> #include <limits> #include <sstream> #include <string> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif #ifdef HAVE_MPI #include <mpi.h> namespace primecount { int mpi_num_procs() { int procs; MPI_Comm_size(MPI_COMM_WORLD, &procs); return procs; } int mpi_proc_id() { int proc_id; MPI_Comm_rank(MPI_COMM_WORLD, &proc_id); return proc_id; } int mpi_master_proc_id() { return 0; } bool is_mpi_master_proc() { return mpi_proc_id() == mpi_master_proc_id(); } } // namespace #endif using namespace std; namespace { #ifdef _OPENMP int threads_ = -1; #endif int status_precision_ = -1; double alpha_ = -1; // Below 10^7 the Deleglise-Rivat algorithm is slower than LMO const int deleglise_rivat_threshold = 10000000; } namespace primecount { int64_t pi(int64_t x) { return pi(x, get_num_threads()); } int64_t pi(int64_t x, int threads) { if (x < deleglise_rivat_threshold) return pi_lmo(x, threads); else return pi_deleglise_rivat(x, threads); } #ifdef HAVE_INT128_T int128_t pi(int128_t x) { return pi(x, get_num_threads()); } int128_t pi(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi((int64_t) x, threads); else return pi_deleglise_rivat(x, threads); } #endif /// Alias for the fastest prime counting function in primecount. /// @param x integer arithmetic expression e.g. "10^12". /// @pre x <= get_max_x(). /// string pi(const string& x) { return pi(x, get_num_threads()); } /// Alias for the fastest prime counting function in primecount. /// @param x integer arithmetic expression e.g. "10^12". /// @pre x <= get_max_x(). /// string pi(const string& x, int threads) { maxint_t pi_x = pi(to_maxint(x), threads); ostringstream oss; oss << pi_x; return oss.str(); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat(int64_t x) { return pi_deleglise_rivat(x, get_num_threads()); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat(int64_t x, int threads) { return pi_deleglise_rivat_parallel2(x, threads); } #ifdef HAVE_INT128_T /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat(int128_t x) { return pi_deleglise_rivat(x, get_num_threads()); } /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi_deleglise_rivat((int64_t) x, threads); else return pi_deleglise_rivat_parallel3(x, threads); } #endif /// Calculate the number of primes below x using Legendre's formula. /// Run time: O(x) operations, O(x^(1/2)) space. /// int64_t pi_legendre(int64_t x) { return pi_legendre(x, get_num_threads()); } /// Calculate the number of primes below x using Lehmer's formula. /// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space. /// int64_t pi_lehmer(int64_t x) { return pi_lehmer(x, get_num_threads()); } /// Calculate the number of primes below x using the /// Lagarias-Miller-Odlyzko algorithm. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo(int64_t x) { return pi_lmo(x, get_num_threads()); } /// Parallel implementation of the Lagarias-Miller-Odlyzko /// prime counting algorithm using OpenMP. /// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space. /// int64_t pi_lmo(int64_t x, int threads) { return pi_lmo_parallel3(x, threads); } /// Calculate the number of primes below x using Meissel's formula. /// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space. /// int64_t pi_meissel(int64_t x) { return pi_meissel(x, get_num_threads()); } /// Calculate the number of primes below x using an optimized /// segmented sieve of Eratosthenes implementation. /// Run time: O(x log log x) operations, O(x^(1/2)) space. /// int64_t pi_primesieve(int64_t x) { return pi_primesieve(x, get_num_threads()); } /// Calculate the nth prime using a combination of the prime /// counting function and the sieve of Eratosthenes. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space. /// int64_t nth_prime(int64_t n) { return nth_prime(n, get_num_threads()); } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t phi(int64_t x, int64_t a) { return phi(x, a, get_num_threads()); } /// Returns the largest integer that can be used with /// pi(string x). The return type is a string as max can be a 128-bit /// integer which is not supported by all compilers. /// string get_max_x(double alpha) { ostringstream oss; #ifdef HAVE_INT128_T // primecount is limited by: // z < 2^62, with z = x^(2/3) / alpha // x^(2/3) / alpha < 2^62 // x < (2^62 * alpha)^(3/2) // safety buffer: use 61 instead of 62 double max_x = pow(pow(2.0, 61.0) * alpha, 3.0 / 2.0); oss << (int128_t) max_x; #else unused_param(alpha); oss << numeric_limits<int64_t>::max(); #endif return oss.str(); } /// Get the wall time in seconds. double get_wtime() { #ifdef _OPENMP return omp_get_wtime(); #else return (double) std::clock() / CLOCKS_PER_SEC; #endif } int ideal_num_threads(int threads, int64_t sieve_limit, int64_t thread_threshold) { thread_threshold = max((int64_t) 1, thread_threshold); threads = (int) min((int64_t) threads, sieve_limit / thread_threshold); threads = max(1, threads); return threads; } void set_alpha(double alpha) { alpha_ = alpha; } double get_alpha() { return alpha_; } double get_alpha(maxint_t x, int64_t y) { // y = x13 * alpha, thus alpha = y / x13 double x13 = (double) iroot<3>(x); return (double) y / x13; } /// Calculate the Lagarias-Miller-Odlyzko alpha tuning factor. /// alpha = a log(x)^2 + b log(x) + c /// a, b and c are constants that should be determined empirically. /// @see ../doc/alpha-factor-tuning.pdf /// double get_alpha_lmo(maxint_t x) { double alpha = get_alpha(); // use default alpha if no command-line alpha provided if (alpha < 1) { double a = 0.00156512; double b = -0.0261411; double c = 0.990948; double logx = log((double) x); alpha = a * pow(logx, 2) + b * logx + c; } return in_between(1, alpha, iroot<6>(x)); } /// Calculate the Deleglise-Rivat alpha tuning factor. /// alpha = a log(x)^3 + b log(x)^2 + c log(x) + d /// a, b, c and d are constants that should be determined empirically. /// @see ../doc/alpha-tuning-factor.pdf /// double get_alpha_deleglise_rivat(maxint_t x) { double alpha = get_alpha(); double x2 = (double) x; // use default alpha if no command-line alpha provided if (alpha < 1) { if (x2 <= 1e21) { double a = 0.000711339; double b = -0.0160586; double c = 0.123034; double d = 0.802942; double logx = log(x2); alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d; } else { // Because of CPU cache misses sieving (S2_hard(x) and P2(x)) // becomes the main bottleneck above 10^21 . Hence we use a // different alpha formula when x > 10^21 which returns a larger // alpha which reduces sieving but increases S2_easy(x) work. double a = 0.00149066; double b = -0.0375705; double c = 0.282139; double d = 0.591972; double logx = log(x2); alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d; } } return in_between(1, alpha, iroot<6>(x)); } void set_num_threads(int threads) { #ifdef _OPENMP threads_ = in_between(1, threads, omp_get_max_threads()); #else unused_param(threads); #endif } int get_num_threads() { #ifdef _OPENMP if (threads_ != -1) return threads_; else return max(1, omp_get_max_threads()); #else return 1; #endif } void set_status_precision(int precision) { status_precision_ = in_between(0, precision, 5); } int get_status_precision(maxint_t x) { // use default precision when no command-line precision provided if (status_precision_ < 0) { if ((double) x >= 1e23) return 2; if ((double) x >= 1e21) return 1; } return (status_precision_ > 0) ? status_precision_ : 0; } maxint_t to_maxint(const string& expr) { maxint_t n = calculator::eval<maxint_t>(expr); return n; } /// Get the primecount version number, in the form “i.j”. string primecount_version() { return PRIMECOUNT_VERSION; } } // namespace <|endoftext|>
<commit_before>/* * Copyright 2016 WebAssembly Community Group participants * * 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. */ // // A WebAssembly optimizer, loads code, optionally runs passes on it, // then writes it. // #include <memory> #include "pass.h" #include "support/command-line.h" #include "support/file.h" #include "wasm-printing.h" #include "wasm-s-parser.h" #include "wasm-validator.h" #include "wasm-io.h" #include "wasm-interpreter.h" #include "wasm-binary.h" #include "shell-interface.h" #include "optimization-options.h" #include "execution-results.h" #include "fuzzing.h" #include "js-wrapper.h" #include "spec-wrapper.h" using namespace wasm; // runs a command and returns its output TODO: portability, return code checking std::string runCommand(std::string command) { #ifdef __linux__ std::string output; const int MAX_BUFFER = 1024; char buffer[MAX_BUFFER]; FILE *stream = popen(command.c_str(), "r"); while (fgets(buffer, MAX_BUFFER, stream) != NULL) { output.append(buffer); } pclose(stream); return output; #else Fatal() << "TODO: portability for wasm-opt runCommand"; #endif } // // main // int main(int argc, const char* argv[]) { Name entry; bool emitBinary = true; bool debugInfo = false; bool converge = false; bool fuzzExecBefore = false; bool fuzzExecAfter = false; bool fuzzBinary = false; std::string extraFuzzCommand; bool translateToFuzz = false; bool fuzzPasses = false; std::string emitJSWrapper; std::string emitSpecWrapper; std::string inputSourceMapFilename; std::string outputSourceMapFilename; std::string outputSourceMapUrl; OptimizationOptions options("wasm-opt", "Read, write, and optimize files"); options .add("--output", "-o", "Output file (stdout if not specified)", Options::Arguments::One, [](Options* o, const std::string& argument) { o->extra["output"] = argument; Colors::disable(); }) .add("--emit-text", "-S", "Emit text instead of binary for the output file", Options::Arguments::Zero, [&](Options *o, const std::string& argument) { emitBinary = false; }) .add("--debuginfo", "-g", "Emit names section and debug info", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { debugInfo = true; }) .add("--converge", "-c", "Run passes to convergence, continuing while binary size decreases", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { converge = true; }) .add("--fuzz-exec-before", "-feh", "Execute functions before optimization, helping fuzzing find bugs", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { fuzzExecBefore = true; }) .add("--fuzz-exec", "-fe", "Execute functions before and after optimization, helping fuzzing find bugs", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { fuzzExecBefore = fuzzExecAfter = true; }) .add("--fuzz-binary", "-fb", "Convert to binary and back after optimizations and before fuzz-exec, helping fuzzing find binary format bugs", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { fuzzBinary = true; }) .add("--extra-fuzz-command", "-efc", "An extra command to run on the output before and after optimizing. The output is compared between the two, and an error occurs if they are not equal", Options::Arguments::One, [&](Options *o, const std::string& arguments) { extraFuzzCommand = arguments; }) .add("--translate-to-fuzz", "-ttf", "Translate the input into a valid wasm module *somehow*, useful for fuzzing", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { translateToFuzz = true; }) .add("--fuzz-passes", "-fp", "Pick a random set of passes to run, useful for fuzzing. this depends on translate-to-fuzz (it picks the passes from the input)", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { fuzzPasses = true; }) .add("--emit-js-wrapper", "-ejw", "Emit a JavaScript wrapper file that can run the wasm with some test values, useful for fuzzing", Options::Arguments::One, [&](Options *o, const std::string& arguments) { emitJSWrapper = arguments; }) .add("--emit-spec-wrapper", "-esw", "Emit a wasm spec interpreter wrapper file that can run the wasm with some test values, useful for fuzzing", Options::Arguments::One, [&](Options *o, const std::string& arguments) { emitSpecWrapper = arguments; }) .add("--input-source-map", "-ism", "Consume source map from the specified file", Options::Arguments::One, [&inputSourceMapFilename](Options *o, const std::string& argument) { inputSourceMapFilename = argument; }) .add("--output-source-map", "-osm", "Emit source map to the specified file", Options::Arguments::One, [&outputSourceMapFilename](Options *o, const std::string& argument) { outputSourceMapFilename = argument; }) .add("--output-source-map-url", "-osu", "Emit specified string as source map URL", Options::Arguments::One, [&outputSourceMapUrl](Options *o, const std::string& argument) { outputSourceMapUrl = argument; }) .add_positional("INFILE", Options::Arguments::One, [](Options* o, const std::string& argument) { o->extra["infile"] = argument; }); options.parse(argc, argv); Module wasm; if (options.debug) std::cerr << "reading...\n"; if (!translateToFuzz) { ModuleReader reader; reader.setDebug(options.debug); try { reader.read(options.extra["infile"], wasm, inputSourceMapFilename); } catch (ParseException& p) { p.dump(std::cerr); std::cerr << '\n'; Fatal() << "error in parsing input"; } catch (MapParseException& p) { p.dump(std::cerr); std::cerr << '\n'; Fatal() << "error in parsing wasm source map"; } catch (std::bad_alloc&) { Fatal() << "error in building module, std::bad_alloc (possibly invalid request for silly amounts of memory)"; } if (options.passOptions.validate) { if (!WasmValidator().validate(wasm, options.getFeatures())) { WasmPrinter::printModule(&wasm); Fatal() << "error in validating input"; } } } else { // translate-to-fuzz TranslateToFuzzReader reader(wasm, options.extra["infile"]); if (fuzzPasses) { reader.pickPasses(options); } reader.build(options.getFeatures()); if (options.passOptions.validate) { if (!WasmValidator().validate(wasm, options.getFeatures())) { WasmPrinter::printModule(&wasm); std::cerr << "translate-to-fuzz must always generate a valid module"; abort(); } } } if (emitJSWrapper.size() > 0) { // As the code will run in JS, we must legalize it. PassRunner runner(&wasm); runner.add("legalize-js-interface"); runner.run(); } ExecutionResults results; if (fuzzExecBefore) { results.get(wasm); } if (emitJSWrapper.size() > 0) { std::ofstream outfile; outfile.open(emitJSWrapper, std::ofstream::out); outfile << generateJSWrapper(wasm); outfile.close(); } if (emitSpecWrapper.size() > 0) { std::ofstream outfile; outfile.open(emitSpecWrapper, std::ofstream::out); outfile << generateSpecWrapper(wasm); outfile.close(); } std::string firstOutput; if (extraFuzzCommand.size() > 0 && options.extra.count("output") > 0) { if (options.debug) std::cerr << "writing binary before opts, for extra fuzz command..." << std::endl; ModuleWriter writer; writer.setDebug(options.debug); writer.setBinary(emitBinary); writer.setDebugInfo(debugInfo); writer.write(wasm, options.extra["output"]); firstOutput = runCommand(extraFuzzCommand); std::cout << "[extra-fuzz-command first output:]\n" << firstOutput << '\n'; } Module* curr = &wasm; Module other; if (fuzzExecAfter && fuzzBinary) { BufferWithRandomAccess buffer(false); // write the binary WasmBinaryWriter writer(&wasm, buffer, false); writer.write(); // read the binary auto input = buffer.getAsChars(); WasmBinaryBuilder parser(other, input, false); parser.read(); if (options.passOptions.validate) { bool valid = WasmValidator().validate(other, options.getFeatures()); if (!valid) { WasmPrinter::printModule(&other); } assert(valid); } curr = &other; } if (options.runningPasses()) { if (options.debug) std::cerr << "running passes...\n"; auto runPasses = [&]() { options.runPasses(*curr); if (options.passOptions.validate) { bool valid = WasmValidator().validate(*curr, options.getFeatures()); if (!valid) { WasmPrinter::printModule(&*curr); } assert(valid); } }; runPasses(); if (converge) { // Keep on running passes to convergence, defined as binary // size no longer decreasing. auto getSize = [&]() { BufferWithRandomAccess buffer; WasmBinaryWriter writer(curr, buffer); writer.write(); return buffer.size(); }; auto lastSize = getSize(); while (1) { if (options.debug) std::cerr << "running iteration for convergence (" << lastSize << ")...\n"; runPasses(); auto currSize = getSize(); if (currSize >= lastSize) break; lastSize = currSize; } } } if (fuzzExecAfter) { results.check(*curr); } if (options.extra.count("output") > 0) { if (options.debug) std::cerr << "writing..." << std::endl; ModuleWriter writer; writer.setDebug(options.debug); writer.setBinary(emitBinary); writer.setDebugInfo(debugInfo); if (outputSourceMapFilename.size()) { writer.setSourceMapFilename(outputSourceMapFilename); writer.setSourceMapUrl(outputSourceMapUrl); } writer.write(*curr, options.extra["output"]); if (extraFuzzCommand.size() > 0) { auto secondOutput = runCommand(extraFuzzCommand); std::cout << "[extra-fuzz-command second output:]\n" << firstOutput << '\n'; if (firstOutput != secondOutput) { std::cerr << "extra fuzz command output differs\n"; abort(); } } } } <commit_msg>if no output is specified to wasm-opt, warn that we are emitting nothing (#1908)<commit_after>/* * Copyright 2016 WebAssembly Community Group participants * * 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. */ // // A WebAssembly optimizer, loads code, optionally runs passes on it, // then writes it. // #include <memory> #include "pass.h" #include "support/command-line.h" #include "support/file.h" #include "wasm-printing.h" #include "wasm-s-parser.h" #include "wasm-validator.h" #include "wasm-io.h" #include "wasm-interpreter.h" #include "wasm-binary.h" #include "shell-interface.h" #include "optimization-options.h" #include "execution-results.h" #include "fuzzing.h" #include "js-wrapper.h" #include "spec-wrapper.h" using namespace wasm; // runs a command and returns its output TODO: portability, return code checking std::string runCommand(std::string command) { #ifdef __linux__ std::string output; const int MAX_BUFFER = 1024; char buffer[MAX_BUFFER]; FILE *stream = popen(command.c_str(), "r"); while (fgets(buffer, MAX_BUFFER, stream) != NULL) { output.append(buffer); } pclose(stream); return output; #else Fatal() << "TODO: portability for wasm-opt runCommand"; #endif } // // main // int main(int argc, const char* argv[]) { Name entry; bool emitBinary = true; bool debugInfo = false; bool converge = false; bool fuzzExecBefore = false; bool fuzzExecAfter = false; bool fuzzBinary = false; std::string extraFuzzCommand; bool translateToFuzz = false; bool fuzzPasses = false; std::string emitJSWrapper; std::string emitSpecWrapper; std::string inputSourceMapFilename; std::string outputSourceMapFilename; std::string outputSourceMapUrl; OptimizationOptions options("wasm-opt", "Read, write, and optimize files"); options .add("--output", "-o", "Output file (stdout if not specified)", Options::Arguments::One, [](Options* o, const std::string& argument) { o->extra["output"] = argument; Colors::disable(); }) .add("--emit-text", "-S", "Emit text instead of binary for the output file", Options::Arguments::Zero, [&](Options *o, const std::string& argument) { emitBinary = false; }) .add("--debuginfo", "-g", "Emit names section and debug info", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { debugInfo = true; }) .add("--converge", "-c", "Run passes to convergence, continuing while binary size decreases", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { converge = true; }) .add("--fuzz-exec-before", "-feh", "Execute functions before optimization, helping fuzzing find bugs", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { fuzzExecBefore = true; }) .add("--fuzz-exec", "-fe", "Execute functions before and after optimization, helping fuzzing find bugs", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { fuzzExecBefore = fuzzExecAfter = true; }) .add("--fuzz-binary", "-fb", "Convert to binary and back after optimizations and before fuzz-exec, helping fuzzing find binary format bugs", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { fuzzBinary = true; }) .add("--extra-fuzz-command", "-efc", "An extra command to run on the output before and after optimizing. The output is compared between the two, and an error occurs if they are not equal", Options::Arguments::One, [&](Options *o, const std::string& arguments) { extraFuzzCommand = arguments; }) .add("--translate-to-fuzz", "-ttf", "Translate the input into a valid wasm module *somehow*, useful for fuzzing", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { translateToFuzz = true; }) .add("--fuzz-passes", "-fp", "Pick a random set of passes to run, useful for fuzzing. this depends on translate-to-fuzz (it picks the passes from the input)", Options::Arguments::Zero, [&](Options *o, const std::string& arguments) { fuzzPasses = true; }) .add("--emit-js-wrapper", "-ejw", "Emit a JavaScript wrapper file that can run the wasm with some test values, useful for fuzzing", Options::Arguments::One, [&](Options *o, const std::string& arguments) { emitJSWrapper = arguments; }) .add("--emit-spec-wrapper", "-esw", "Emit a wasm spec interpreter wrapper file that can run the wasm with some test values, useful for fuzzing", Options::Arguments::One, [&](Options *o, const std::string& arguments) { emitSpecWrapper = arguments; }) .add("--input-source-map", "-ism", "Consume source map from the specified file", Options::Arguments::One, [&inputSourceMapFilename](Options *o, const std::string& argument) { inputSourceMapFilename = argument; }) .add("--output-source-map", "-osm", "Emit source map to the specified file", Options::Arguments::One, [&outputSourceMapFilename](Options *o, const std::string& argument) { outputSourceMapFilename = argument; }) .add("--output-source-map-url", "-osu", "Emit specified string as source map URL", Options::Arguments::One, [&outputSourceMapUrl](Options *o, const std::string& argument) { outputSourceMapUrl = argument; }) .add_positional("INFILE", Options::Arguments::One, [](Options* o, const std::string& argument) { o->extra["infile"] = argument; }); options.parse(argc, argv); Module wasm; if (options.debug) std::cerr << "reading...\n"; if (!translateToFuzz) { ModuleReader reader; reader.setDebug(options.debug); try { reader.read(options.extra["infile"], wasm, inputSourceMapFilename); } catch (ParseException& p) { p.dump(std::cerr); std::cerr << '\n'; Fatal() << "error in parsing input"; } catch (MapParseException& p) { p.dump(std::cerr); std::cerr << '\n'; Fatal() << "error in parsing wasm source map"; } catch (std::bad_alloc&) { Fatal() << "error in building module, std::bad_alloc (possibly invalid request for silly amounts of memory)"; } if (options.passOptions.validate) { if (!WasmValidator().validate(wasm, options.getFeatures())) { WasmPrinter::printModule(&wasm); Fatal() << "error in validating input"; } } } else { // translate-to-fuzz TranslateToFuzzReader reader(wasm, options.extra["infile"]); if (fuzzPasses) { reader.pickPasses(options); } reader.build(options.getFeatures()); if (options.passOptions.validate) { if (!WasmValidator().validate(wasm, options.getFeatures())) { WasmPrinter::printModule(&wasm); std::cerr << "translate-to-fuzz must always generate a valid module"; abort(); } } } if (emitJSWrapper.size() > 0) { // As the code will run in JS, we must legalize it. PassRunner runner(&wasm); runner.add("legalize-js-interface"); runner.run(); } ExecutionResults results; if (fuzzExecBefore) { results.get(wasm); } if (emitJSWrapper.size() > 0) { std::ofstream outfile; outfile.open(emitJSWrapper, std::ofstream::out); outfile << generateJSWrapper(wasm); outfile.close(); } if (emitSpecWrapper.size() > 0) { std::ofstream outfile; outfile.open(emitSpecWrapper, std::ofstream::out); outfile << generateSpecWrapper(wasm); outfile.close(); } std::string firstOutput; if (extraFuzzCommand.size() > 0 && options.extra.count("output") > 0) { if (options.debug) std::cerr << "writing binary before opts, for extra fuzz command..." << std::endl; ModuleWriter writer; writer.setDebug(options.debug); writer.setBinary(emitBinary); writer.setDebugInfo(debugInfo); writer.write(wasm, options.extra["output"]); firstOutput = runCommand(extraFuzzCommand); std::cout << "[extra-fuzz-command first output:]\n" << firstOutput << '\n'; } Module* curr = &wasm; Module other; if (fuzzExecAfter && fuzzBinary) { BufferWithRandomAccess buffer(false); // write the binary WasmBinaryWriter writer(&wasm, buffer, false); writer.write(); // read the binary auto input = buffer.getAsChars(); WasmBinaryBuilder parser(other, input, false); parser.read(); if (options.passOptions.validate) { bool valid = WasmValidator().validate(other, options.getFeatures()); if (!valid) { WasmPrinter::printModule(&other); } assert(valid); } curr = &other; } if (options.runningPasses()) { if (options.debug) std::cerr << "running passes...\n"; auto runPasses = [&]() { options.runPasses(*curr); if (options.passOptions.validate) { bool valid = WasmValidator().validate(*curr, options.getFeatures()); if (!valid) { WasmPrinter::printModule(&*curr); } assert(valid); } }; runPasses(); if (converge) { // Keep on running passes to convergence, defined as binary // size no longer decreasing. auto getSize = [&]() { BufferWithRandomAccess buffer; WasmBinaryWriter writer(curr, buffer); writer.write(); return buffer.size(); }; auto lastSize = getSize(); while (1) { if (options.debug) std::cerr << "running iteration for convergence (" << lastSize << ")...\n"; runPasses(); auto currSize = getSize(); if (currSize >= lastSize) break; lastSize = currSize; } } } if (fuzzExecAfter) { results.check(*curr); } if (options.extra.count("output") == 0) { std::cerr << "(no output file specified, not emitting output)\n"; } else { if (options.debug) std::cerr << "writing..." << std::endl; ModuleWriter writer; writer.setDebug(options.debug); writer.setBinary(emitBinary); writer.setDebugInfo(debugInfo); if (outputSourceMapFilename.size()) { writer.setSourceMapFilename(outputSourceMapFilename); writer.setSourceMapUrl(outputSourceMapUrl); } writer.write(*curr, options.extra["output"]); if (extraFuzzCommand.size() > 0) { auto secondOutput = runCommand(extraFuzzCommand); std::cout << "[extra-fuzz-command second output:]\n" << firstOutput << '\n'; if (firstOutput != secondOutput) { std::cerr << "extra fuzz command output differs\n"; abort(); } } } } <|endoftext|>
<commit_before>#ifndef _INPUSTREAM_HXX_ #define _INPUSTREAM_HXX_ #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_ #include <com/sun/star/io/XSeekable.hpp> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_ #include <com/sun/star/ucb/XContentProvider.hpp> #endif namespace chelp { // forward declaration class XInputStream_impl : public cppu::OWeakObject, public com::sun::star::io::XInputStream, public com::sun::star::io::XSeekable { public: XInputStream_impl( const rtl::OUString& aUncPath ); virtual ~XInputStream_impl(); /** * Returns an error code as given by filerror.hxx */ bool SAL_CALL CtorSuccess(); virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type& rType ) throw( com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( void ) throw( com::sun::star::uno::RuntimeException); virtual void SAL_CALL release( void ) throw( com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL readBytes( com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL readSomeBytes( com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException); virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL available( void ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL closeInput( void ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL seek( sal_Int64 location ) throw( com::sun::star::lang::IllegalArgumentException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual sal_Int64 SAL_CALL getPosition( void ) throw( com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual sal_Int64 SAL_CALL getLength( void ) throw( com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); private: bool m_bIsOpen; osl::File m_aFile; }; } // end namespace XInputStream_impl #endif <commit_msg>#92924#: exception specifications<commit_after>#ifndef _INPUSTREAM_HXX_ #define _INPUSTREAM_HXX_ #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_ #include <com/sun/star/io/XSeekable.hpp> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_ #include <com/sun/star/ucb/XContentProvider.hpp> #endif namespace chelp { // forward declaration class XInputStream_impl : public cppu::OWeakObject, public com::sun::star::io::XInputStream, public com::sun::star::io::XSeekable { public: XInputStream_impl( const rtl::OUString& aUncPath ); virtual ~XInputStream_impl(); /** * Returns an error code as given by filerror.hxx */ bool SAL_CALL CtorSuccess(); virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type& rType ) throw( com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( void ) throw(); virtual void SAL_CALL release( void ) throw(); virtual sal_Int32 SAL_CALL readBytes( com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL readSomeBytes( com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException); virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL available( void ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL closeInput( void ) throw( com::sun::star::io::NotConnectedException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL seek( sal_Int64 location ) throw( com::sun::star::lang::IllegalArgumentException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual sal_Int64 SAL_CALL getPosition( void ) throw( com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); virtual sal_Int64 SAL_CALL getLength( void ) throw( com::sun::star::io::IOException, com::sun::star::uno::RuntimeException ); private: bool m_bIsOpen; osl::File m_aFile; }; } // end namespace XInputStream_impl #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PageHeaderFooterContext.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:25:45 $ * * 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_xmloff.hxx" // INCLUDE --------------------------------------------------------------- #ifndef _XMLOFF_PAGEPHEADERFOOTERCONTEXT_HXX #include "PageHeaderFooterContext.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX #include "PagePropertySetContext.hxx" #endif using namespace com::sun::star; using ::xmloff::token::IsXMLToken; using ::xmloff::token::XML_HEADER_FOOTER_PROPERTIES; //------------------------------------------------------------------ PageHeaderFooterContext::PageHeaderFooterContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>&, ::std::vector< XMLPropertyState > & rTempProperties, const UniReference < SvXMLImportPropertyMapper > &rTempMap, sal_Int32 nStart, sal_Int32 nEnd, const sal_Bool bTempHeader ) : SvXMLImportContext( rImport, nPrfx, rLName ), rProperties(rTempProperties), nStartIndex(nStart), nEndIndex(nEnd), rMap(rTempMap) { bHeader = bTempHeader; } PageHeaderFooterContext::~PageHeaderFooterContext() { } SvXMLImportContext *PageHeaderFooterContext::CreateChildContext( USHORT nPrefix, const rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( XML_NAMESPACE_STYLE == nPrefix && IsXMLToken( rLName, XML_HEADER_FOOTER_PROPERTIES ) ) { PageContextType aType = Header; if (!bHeader) aType = Footer; pContext = new PagePropertySetContext( GetImport(), nPrefix, rLName, xAttrList, XML_TYPE_PROP_HEADER_FOOTER, rProperties, rMap, nStartIndex, nEndIndex, aType); } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void PageHeaderFooterContext::EndElement() { } <commit_msg>INTEGRATION: CWS changefileheader (1.9.162); FILE MERGED 2008/04/01 13:04:57 thb 1.9.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:18 rt 1.9.162.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PageHeaderFooterContext.cxx,v $ * $Revision: 1.10 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" // INCLUDE --------------------------------------------------------------- #ifndef _XMLOFF_PAGEPHEADERFOOTERCONTEXT_HXX #include "PageHeaderFooterContext.hxx" #endif #include "xmlnmspe.hxx" #include <xmloff/xmltoken.hxx> #include "PagePropertySetContext.hxx" using namespace com::sun::star; using ::xmloff::token::IsXMLToken; using ::xmloff::token::XML_HEADER_FOOTER_PROPERTIES; //------------------------------------------------------------------ PageHeaderFooterContext::PageHeaderFooterContext( SvXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>&, ::std::vector< XMLPropertyState > & rTempProperties, const UniReference < SvXMLImportPropertyMapper > &rTempMap, sal_Int32 nStart, sal_Int32 nEnd, const sal_Bool bTempHeader ) : SvXMLImportContext( rImport, nPrfx, rLName ), rProperties(rTempProperties), nStartIndex(nStart), nEndIndex(nEnd), rMap(rTempMap) { bHeader = bTempHeader; } PageHeaderFooterContext::~PageHeaderFooterContext() { } SvXMLImportContext *PageHeaderFooterContext::CreateChildContext( USHORT nPrefix, const rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( XML_NAMESPACE_STYLE == nPrefix && IsXMLToken( rLName, XML_HEADER_FOOTER_PROPERTIES ) ) { PageContextType aType = Header; if (!bHeader) aType = Footer; pContext = new PagePropertySetContext( GetImport(), nPrefix, rLName, xAttrList, XML_TYPE_PROP_HEADER_FOOTER, rProperties, rMap, nStartIndex, nEndIndex, aType); } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void PageHeaderFooterContext::EndElement() { } <|endoftext|>
<commit_before>#pragma once #include <algorithm> #include <iostream> #include <array> #include <utki/debug.hpp> #include "vector3.hpp" namespace r4{ template <typename T> class vector2; template <typename T> class vector3; /** * @brief 4x4 matrix template class. * Note, that this matrix class stores elements in row-major order. */ template <typename T> class matrix3 : public std::array<vector3<T>, 3>{ typedef std::array<vector3<T>, 3> base_type; public: /** * @brief Default constructor. * NOTE: it does not initialize the matrix with any values. * Matrix elements are undefined after the matrix is created with this constructor. */ matrix3()noexcept{} /** * @brief Construct initialized matrix. * Creates a matrix and initializes its rows with the given values. * @param row0 - 0th row of the matrix. * @param row1 - 1st row of the matrix. * @param row2 - 2nd row of the matrix. */ matrix3( const vector3<T>& row0, const vector3<T>& row1, const vector3<T>& row2 )noexcept : std::array<vector3<T>, 3>{{row0, row1, row2}} {} matrix3(const matrix3&) = default; matrix3& operator=(const matrix3&) = default; /** * @brief Convert to different element type. * @return matrix3 with converted element type. */ template <typename TT> matrix3<TT> to()noexcept{ return matrix3<TT>{ this->row(0).template to<TT>(), this->row(1).template to<TT>(), this->row(2).template to<TT>() }; } /** * @brief Transform vector by matrix. * Multiply vector V by this matrix M from the right (M * V). * i.e. transform vector with this transformation matrix. * @param vec - vector to transform. * @return Transformed vector. */ vector2<T> operator*(const vector2<T>& vec)const noexcept; /** * @brief Transform vector by matrix. * Multiply vector V by this matrix M from the right (M * V). * i.e. transform vector with this transformation matrix. * @param vec - vector to transform. * @return Transformed vector. */ vector3<T> operator*(const vector3<T>& vec)const noexcept; /** * @brief Get matrix row. * @param index - row index to get, must be from 0 to 2. * @return reference to vector3 representing the row of this matrix. */ vector3<T>& row(unsigned index)noexcept{ ASSERT(index < 3) return this->operator[](index); } /** * @brief Get constant matrix row. * @param index - row index to get, must be from 0 to 2. * @return constant reference to vector3 representing the row of this matrix. */ const vector3<T>& row(unsigned index)const noexcept{ ASSERT(index < 3) return this->operator[](index); } /** * @brief Get matrix column. * Constructs and returns a vector3 representing the requested matrix column. * @param index - column index to get, must be from 0 to 2; * @return vector3 representing the requested matrix column. */ vector3<T> col(unsigned index)const noexcept{ return vector3<T>{ this->row(0)[index], this->row(1)[index], this->row(2)[index] }; } /** * @brief Transpose matrix. */ matrix3& transpose()noexcept{ std::swap(this->operator[](1)[0], this->operator[](0)[1]); std::swap(this->operator[](2)[0], this->operator[](0)[2]); std::swap(this->operator[](2)[1], this->operator[](1)[2]); return *this; } /** * @brief Multiply by matrix from the right. * Calculate result of this matrix M multiplied by another matrix K from the right (M * K). * @param matr - matrix to multiply by (matrix K). * @return New matrix as a result of matrices product. */ matrix3 operator*(const matrix3& matr)const noexcept{ return matrix3{ vector3<T>{this->row(0) * matr.col(0), this->row(0) * matr.col(1), this->row(0) * matr.col(2)}, vector3<T>{this->row(1) * matr.col(0), this->row(1) * matr.col(1), this->row(1) * matr.col(2)}, vector3<T>{this->row(2) * matr.col(0), this->row(2) * matr.col(1), this->row(2) * matr.col(2)} }; } /** * @brief Multiply by matrix from the right. * Multiply this matrix M by another matrix K from the right (M = M * K). * @return reference to this matrix object. */ matrix3& operator*=(const matrix3& matr)noexcept{ return this->operator=(this->operator*(matr)); } /** * @brief Multiply by matrix from the right. * Multiply this matrix M by another matrix K from the right (M = M * K). * This is the same as operator*=(). * @param matr - matrix to multiply by. * @return reference to this matrix object. */ matrix3& right_multiply(const matrix3& matr)noexcept{ return this->operator*=(matr); } /** * @brief Multiply by matrix from the left. * Multiply this matrix M by another matrix K from the left (M = K * M). * @param matr - matrix to multiply by. * @return reference to this matrix object. */ matrix3& left_multiply(const matrix3& matr)noexcept{ return this->operator=(matr.operator*(*this)); } /** * @brief Initialize this matrix with identity matrix. */ matrix3& set_identity()noexcept{ this->row(0) = {1, 0, 0}; this->row(1) = {0, 1, 0}; this->row(2) = {0, 0, 1}; return (*this); } /** * @brief Multiply current matrix by scale matrix. * Multiplies this matrix M by scale matrix S from the right (M = M * S). * @param x - scaling factor in x direction. * @param y - scaling factor in y direction. * @return reference to this matrix instance. */ matrix3& scale(T x, T y)noexcept{ // update 0th column this->operator[](0)[0] *= x; this->operator[](1)[0] *= x; this->operator[](2)[0] *= x; // update 1st column this->operator[](0)[1] *= y; this->operator[](1)[1] *= y; this->operator[](2)[1] *= y; // NOTE: 2nd column remains unchanged return (*this); } /** * @brief Multiply current matrix by scale matrix. * Multiplies this matrix M by scale matrix S from the right (M = M * S). * @param s - scaling factor to be applied in all 3 directions (x, y and z). * @return reference to this matrix instance. */ matrix3& scale(T s)noexcept{ return this->scale(s, s, s); } /** * @brief Multiply current matrix by scale matrix. * Multiplies this matrix M by scale matrix S from the right (M = M * S). * @param s - vector of scaling factors in x and y directions, scaling factor in z direction is 1. * @return reference to this matrix instance. */ matrix3& scale(const vector2<T>& s)noexcept; /** * @brief Multiply this matrix by translation matrix. * Multiplies this matrix M by translation matrix T from the right (M = M * T). * @param x - x component of translation vector. * @param y - y component of translation vector. * @return reference to this matrix object. */ matrix3& translate(T x, T y)noexcept{ //NOTE: 0th and 1st columns remain unchanged //calculate 2nd column this->c2 = this->c0 * x + this->c1 * y + this->c2; return (*this); } /** * @brief Multiply this matrix by translation matrix. * Multiplies this matrix M by translation matrix T from the right (M = M * T). * @param t - translation vector. * @return reference to this matrix object. */ matrix3& translate(const vector2<T>& t)noexcept; /** * @brief Multiply this matrix by rotation matrix. * Multiplies this matrix M by rotation matrix R from the right (M = M * R). * Positive direction of rotation is counter-clockwise. * @param rot - the angle of rotation in radians. * @return reference to this matrix object. */ matrix3& rotate(T rot)noexcept; friend std::ostream& operator<<(std::ostream& s, const matrix3<T>& mat){ s << "\n"; s << "\t/" << mat[0][0] << " " << mat[0][1] << " " << mat[0][2] << "\\" << std::endl; s << "\t|" << mat[1][0] << " " << mat[1][1] << " " << mat[1][2] << "|" << std::endl; s << "\t\\" << mat[2][0] << " " << mat[2][1] << " " << mat[2][2] << "/"; return s; }; }; } #include "vector2.hpp" #include "vector3.hpp" namespace r4{ template <class T> vector2<T> matrix3<T>::operator*(const vector2<T>& vec)const noexcept{ // TRACE_ALWAYS(<< "this->row(1) = " << this->row(1) << " vec = " << vec << std::endl) return vector2<T>( this->row(0) * vec, this->row(1) * vec ); } template <class T> vector3<T> matrix3<T>::operator*(const vector3<T>& vec)const noexcept{ return vector3<T>( this->row(0) * vec, this->row(1) * vec, this->row(2) * vec ); } template <class T> matrix3<T>& matrix3<T>::scale(const vector2<T>& s)noexcept{ return this->scale(s.x, s.y); } template <class T> matrix3<T>& matrix3<T>::translate(const vector2<T>& t)noexcept{ return this->translate(t.x, t.y); } typedef matrix3<float> mat3f; static_assert(sizeof(mat3f) == sizeof(float) * 3 * 3, "size mismatch"); typedef matrix3<double> mat3d; static_assert(sizeof(mat3d) == sizeof(double) * 3 * 3, "size mismatch"); } <commit_msg>stuff<commit_after>#pragma once #include <algorithm> #include <iostream> #include <array> #include <utki/debug.hpp> #include "vector3.hpp" namespace r4{ template <typename T> class vector2; template <typename T> class vector3; /** * @brief 4x4 matrix template class. * Note, that this matrix class stores elements in row-major order. */ template <typename T> class matrix3 : public std::array<vector3<T>, 3>{ typedef std::array<vector3<T>, 3> base_type; public: /** * @brief Default constructor. * NOTE: it does not initialize the matrix with any values. * Matrix elements are undefined after the matrix is created with this constructor. */ matrix3()noexcept{} /** * @brief Construct initialized matrix. * Creates a matrix and initializes its rows with the given values. * @param row0 - 0th row of the matrix. * @param row1 - 1st row of the matrix. * @param row2 - 2nd row of the matrix. */ matrix3( const vector3<T>& row0, const vector3<T>& row1, const vector3<T>& row2 )noexcept : std::array<vector3<T>, 3>{{row0, row1, row2}} {} matrix3(const matrix3&) = default; matrix3& operator=(const matrix3&) = default; /** * @brief Convert to different element type. * @return matrix3 with converted element type. */ template <typename TT> matrix3<TT> to()noexcept{ return matrix3<TT>{ this->row(0).template to<TT>(), this->row(1).template to<TT>(), this->row(2).template to<TT>() }; } /** * @brief Transform vector by matrix. * Multiply vector V by this matrix M from the right (M * V). * i.e. transform vector with this transformation matrix. * @param vec - vector to transform. * @return Transformed vector. */ vector2<T> operator*(const vector2<T>& vec)const noexcept; /** * @brief Transform vector by matrix. * Multiply vector V by this matrix M from the right (M * V). * i.e. transform vector with this transformation matrix. * @param vec - vector to transform. * @return Transformed vector. */ vector3<T> operator*(const vector3<T>& vec)const noexcept; /** * @brief Get matrix row. * @param index - row index to get, must be from 0 to 2. * @return reference to vector3 representing the row of this matrix. */ vector3<T>& row(unsigned index)noexcept{ ASSERT(index < 3) return this->operator[](index); } /** * @brief Get constant matrix row. * @param index - row index to get, must be from 0 to 2. * @return constant reference to vector3 representing the row of this matrix. */ const vector3<T>& row(unsigned index)const noexcept{ ASSERT(index < 3) return this->operator[](index); } /** * @brief Get matrix column. * Constructs and returns a vector3 representing the requested matrix column. * @param index - column index to get, must be from 0 to 2; * @return vector3 representing the requested matrix column. */ vector3<T> col(unsigned index)const noexcept{ return vector3<T>{ this->row(0)[index], this->row(1)[index], this->row(2)[index] }; } /** * @brief Transpose matrix. */ matrix3& transpose()noexcept{ std::swap(this->operator[](1)[0], this->operator[](0)[1]); std::swap(this->operator[](2)[0], this->operator[](0)[2]); std::swap(this->operator[](2)[1], this->operator[](1)[2]); return *this; } /** * @brief Multiply by matrix from the right. * Calculate result of this matrix M multiplied by another matrix K from the right (M * K). * @param matr - matrix to multiply by (matrix K). * @return New matrix as a result of matrices product. */ matrix3 operator*(const matrix3& matr)const noexcept{ return matrix3{ vector3<T>{this->row(0) * matr.col(0), this->row(0) * matr.col(1), this->row(0) * matr.col(2)}, vector3<T>{this->row(1) * matr.col(0), this->row(1) * matr.col(1), this->row(1) * matr.col(2)}, vector3<T>{this->row(2) * matr.col(0), this->row(2) * matr.col(1), this->row(2) * matr.col(2)} }; } /** * @brief Multiply by matrix from the right. * Multiply this matrix M by another matrix K from the right (M = M * K). * @return reference to this matrix object. */ matrix3& operator*=(const matrix3& matr)noexcept{ return this->operator=(this->operator*(matr)); } /** * @brief Multiply by matrix from the right. * Multiply this matrix M by another matrix K from the right (M = M * K). * This is the same as operator*=(). * @param matr - matrix to multiply by. * @return reference to this matrix object. */ matrix3& right_multiply(const matrix3& matr)noexcept{ return this->operator*=(matr); } /** * @brief Multiply by matrix from the left. * Multiply this matrix M by another matrix K from the left (M = K * M). * @param matr - matrix to multiply by. * @return reference to this matrix object. */ matrix3& left_multiply(const matrix3& matr)noexcept{ return this->operator=(matr.operator*(*this)); } /** * @brief Initialize this matrix with identity matrix. */ matrix3& set_identity()noexcept{ this->row(0) = {1, 0, 0}; this->row(1) = {0, 1, 0}; this->row(2) = {0, 0, 1}; return (*this); } /** * @brief Multiply current matrix by scale matrix. * Multiplies this matrix M by scale matrix S from the right (M = M * S). * @param x - scaling factor in x direction. * @param y - scaling factor in y direction. * @return reference to this matrix instance. */ matrix3& scale(T x, T y)noexcept{ // multiply this matrix from the right by the scale matrix: // / x 0 0 \ // this = this * | 0 y 0 | // \ 0 0 1 / // update 0th column this->operator[](0)[0] *= x; this->operator[](1)[0] *= x; this->operator[](2)[0] *= x; // update 1st column this->operator[](0)[1] *= y; this->operator[](1)[1] *= y; this->operator[](2)[1] *= y; // NOTE: 2nd column remains unchanged return (*this); } /** * @brief Multiply current matrix by scale matrix. * Multiplies this matrix M by scale matrix S from the right (M = M * S). * @param s - scaling factor to be applied in all 3 directions (x, y and z). * @return reference to this matrix instance. */ matrix3& scale(T s)noexcept{ return this->scale(s, s, s); } /** * @brief Multiply current matrix by scale matrix. * Multiplies this matrix M by scale matrix S from the right (M = M * S). * @param s - vector of scaling factors in x and y directions, scaling factor in z direction is 1. * @return reference to this matrix instance. */ matrix3& scale(const vector2<T>& s)noexcept; /** * @brief Multiply this matrix by translation matrix. * Multiplies this matrix M by translation matrix T from the right (M = M * T). * @param x - x component of translation vector. * @param y - y component of translation vector. * @return reference to this matrix object. */ matrix3& translate(T x, T y)noexcept{ //NOTE: 0th and 1st columns remain unchanged //calculate 2nd column this->c2 = this->c0 * x + this->c1 * y + this->c2; return (*this); } /** * @brief Multiply this matrix by translation matrix. * Multiplies this matrix M by translation matrix T from the right (M = M * T). * @param t - translation vector. * @return reference to this matrix object. */ matrix3& translate(const vector2<T>& t)noexcept; /** * @brief Multiply this matrix by rotation matrix. * Multiplies this matrix M by rotation matrix R from the right (M = M * R). * Positive direction of rotation is counter-clockwise. * @param rot - the angle of rotation in radians. * @return reference to this matrix object. */ matrix3& rotate(T rot)noexcept; friend std::ostream& operator<<(std::ostream& s, const matrix3<T>& mat){ s << "\n"; s << "\t/" << mat[0][0] << " " << mat[0][1] << " " << mat[0][2] << "\\" << std::endl; s << "\t|" << mat[1][0] << " " << mat[1][1] << " " << mat[1][2] << "|" << std::endl; s << "\t\\" << mat[2][0] << " " << mat[2][1] << " " << mat[2][2] << "/"; return s; }; }; } #include "vector2.hpp" #include "vector3.hpp" namespace r4{ template <class T> vector2<T> matrix3<T>::operator*(const vector2<T>& vec)const noexcept{ // TRACE_ALWAYS(<< "this->row(1) = " << this->row(1) << " vec = " << vec << std::endl) return vector2<T>( this->row(0) * vec, this->row(1) * vec ); } template <class T> vector3<T> matrix3<T>::operator*(const vector3<T>& vec)const noexcept{ return vector3<T>( this->row(0) * vec, this->row(1) * vec, this->row(2) * vec ); } template <class T> matrix3<T>& matrix3<T>::scale(const vector2<T>& s)noexcept{ return this->scale(s.x, s.y); } template <class T> matrix3<T>& matrix3<T>::translate(const vector2<T>& t)noexcept{ return this->translate(t.x, t.y); } typedef matrix3<float> mat3f; static_assert(sizeof(mat3f) == sizeof(float) * 3 * 3, "size mismatch"); typedef matrix3<double> mat3d; static_assert(sizeof(mat3d) == sizeof(double) * 3 * 3, "size mismatch"); } <|endoftext|>
<commit_before>/*===================================================================== PIXHAWK Micro Air Vehicle Flying Robotics Toolkit (c) 2009, 2010 PIXHAWK PROJECT <http://pixhawk.ethz.ch> This file is part of the PIXHAWK project PIXHAWK 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. PIXHAWK 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 PIXHAWK. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /** * @file * @brief Waypoint list widget * * @author Lorenz Meier <mavteam@student.ethz.ch> * @author Benjamin Knecht <mavteam@student.ethz.ch> * @author Petri Tanskanen <mavteam@student.ethz.ch> * */ #include "WaypointList.h" #include "ui_WaypointList.h" #include <UASInterface.h> #include <UASManager.h> #include <QDebug> #include <QFileDialog> WaypointList::WaypointList(QWidget *parent, UASInterface* uas) : QWidget(parent), uas(NULL), m_ui(new Ui::WaypointList) { m_ui->setupUi(this); listLayout = new QVBoxLayout(m_ui->listWidget); listLayout->setSpacing(6); listLayout->setMargin(0); listLayout->setAlignment(Qt::AlignTop); m_ui->listWidget->setLayout(listLayout); wpViews = QMap<Waypoint*, WaypointView*>(); this->uas = NULL; // ADD WAYPOINT // Connect add action, set right button icon and connect action to this class connect(m_ui->addButton, SIGNAL(clicked()), m_ui->actionAddWaypoint, SIGNAL(triggered())); connect(m_ui->actionAddWaypoint, SIGNAL(triggered()), this, SLOT(add())); // SEND WAYPOINTS connect(m_ui->transmitButton, SIGNAL(clicked()), this, SLOT(transmit())); // REQUEST WAYPOINTS connect(m_ui->readButton, SIGNAL(clicked()), this, SLOT(read())); // SAVE/LOAD WAYPOINTS connect(m_ui->saveButton, SIGNAL(clicked()), this, SLOT(saveWaypoints())); connect(m_ui->loadButton, SIGNAL(clicked()), this, SLOT(loadWaypoints())); connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setUAS(UASInterface*))); // STATUS LABEL updateStatusLabel(""); // SET UAS AFTER ALL SIGNALS/SLOTS ARE CONNECTED setUAS(uas); } WaypointList::~WaypointList() { delete m_ui; } void WaypointList::updateStatusLabel(const QString &string) { m_ui->statusLabel->setText(string); } void WaypointList::setUAS(UASInterface* uas) { if (this->uas == NULL && uas != NULL) { this->uas = uas; connect(&uas->getWaypointManager(), SIGNAL(updateStatusString(const QString &)), this, SLOT(updateStatusLabel(const QString &))); connect(&uas->getWaypointManager(), SIGNAL(waypointUpdated(int,quint16,double,double,double,double,bool,bool,double,int)), this, SLOT(setWaypoint(int,quint16,double,double,double,double,bool,bool,double,int))); connect(&uas->getWaypointManager(), SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointChanged(quint16))); connect(this, SIGNAL(sendWaypoints(const QVector<Waypoint*> &)), &uas->getWaypointManager(), SLOT(sendWaypoints(const QVector<Waypoint*> &))); connect(this, SIGNAL(requestWaypoints()), &uas->getWaypointManager(), SLOT(requestWaypoints())); connect(this, SIGNAL(clearWaypointList()), &uas->getWaypointManager(), SLOT(clearWaypointList())); } } void WaypointList::setWaypoint(int uasId, quint16 id, double x, double y, double z, double yaw, bool autocontinue, bool current, double orbit, int holdTime) { if (uasId == this->uas->getUASID()) { Waypoint* wp = new Waypoint(id, x, y, z, yaw, autocontinue, current, orbit, holdTime); addWaypoint(wp); } } void WaypointList::waypointReached(UASInterface* uas, quint16 waypointId) { Q_UNUSED(uas); qDebug() << "Waypoint reached: " << waypointId; updateStatusLabel(QString("Waypoint %1 reached.").arg(waypointId)); } void WaypointList::currentWaypointChanged(quint16 seq) { if (seq < waypoints.size()) { for(int i = 0; i < waypoints.size(); i++) { WaypointView* widget = wpViews.find(waypoints[i]).value(); if (waypoints[i]->getId() == seq) { waypoints[i]->setCurrent(true); widget->setCurrent(true); } else { waypoints[i]->setCurrent(false); widget->setCurrent(false); } } redrawList(); } } void WaypointList::read() { while(waypoints.size()>0) { removeWaypoint(waypoints[0]); } emit requestWaypoints(); } void WaypointList::transmit() { emit sendWaypoints(waypoints); //emit requestWaypoints(); FIXME } void WaypointList::add() { // Only add waypoints if UAS is present if (uas) { if (waypoints.size() > 0) { addWaypoint(new Waypoint(waypoints.size(), 1.1, 1.1, -0.6, 0.0, true, false, 0.1, 2000)); } else { addWaypoint(new Waypoint(waypoints.size(), 1.1, 1.1, -0.6, 0.0, true, true, 0.1, 2000)); } } } void WaypointList::addWaypoint(Waypoint* wp) { waypoints.push_back(wp); if (!wpViews.contains(wp)) { WaypointView* wpview = new WaypointView(wp, this); wpViews.insert(wp, wpview); listLayout->addWidget(wpViews.value(wp)); connect(wpview, SIGNAL(moveDownWaypoint(Waypoint*)), this, SLOT(moveDown(Waypoint*))); connect(wpview, SIGNAL(moveUpWaypoint(Waypoint*)), this, SLOT(moveUp(Waypoint*))); connect(wpview, SIGNAL(removeWaypoint(Waypoint*)), this, SLOT(removeWaypoint(Waypoint*))); connect(wpview, SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointChanged(quint16))); } } void WaypointList::redrawList() { // Clear list layout if (!wpViews.empty()) { QMapIterator<Waypoint*,WaypointView*> viewIt(wpViews); viewIt.toFront(); while(viewIt.hasNext()) { viewIt.next(); listLayout->removeWidget(viewIt.value()); } // Re-add waypoints for(int i = 0; i < waypoints.size(); i++) { listLayout->addWidget(wpViews.value(waypoints[i])); } } } void WaypointList::moveUp(Waypoint* wp) { int id = wp->getId(); if (waypoints.size() > 1 && waypoints.size() > id) { Waypoint* temp = waypoints[id]; if (id > 0) { waypoints[id] = waypoints[id-1]; waypoints[id-1] = temp; waypoints[id-1]->setId(id-1); waypoints[id]->setId(id); } else { waypoints[id] = waypoints[waypoints.size()-1]; waypoints[waypoints.size()-1] = temp; waypoints[waypoints.size()-1]->setId(waypoints.size()-1); waypoints[id]->setId(id); } redrawList(); } } void WaypointList::moveDown(Waypoint* wp) { int id = wp->getId(); if (waypoints.size() > 1 && waypoints.size() > id) { Waypoint* temp = waypoints[id]; if (id != waypoints.size()-1) { waypoints[id] = waypoints[id+1]; waypoints[id+1] = temp; waypoints[id+1]->setId(id+1); waypoints[id]->setId(id); } else { waypoints[id] = waypoints[0]; waypoints[0] = temp; waypoints[0]->setId(0); waypoints[id]->setId(id); } redrawList(); } } void WaypointList::removeWaypoint(Waypoint* wp) { // Delete from list if (wp != NULL) { waypoints.remove(wp->getId()); for(int i = wp->getId(); i < waypoints.size(); i++) { waypoints[i]->setId(i); } // Remove from view WaypointView* widget = wpViews.find(wp).value(); wpViews.remove(wp); widget->hide(); listLayout->removeWidget(widget); delete wp; } } void WaypointList::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::LanguageChange: m_ui->retranslateUi(this); break; default: break; } } void WaypointList::saveWaypoints() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "./waypoints.txt", tr("Waypoint File (*.txt)")); QFile file(fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return; QTextStream in(&file); for (int i = 0; i < waypoints.size(); i++) { Waypoint* wp = waypoints[i]; in << "\t" << wp->getId() << "\t" << wp->getX() << "\t" << wp->getY() << "\t" << wp->getZ() << "\t" << wp->getYaw() << "\t" << wp->getAutoContinue() << "\t" << wp->getCurrent() << wp->getOrbit() << "\t" << wp->getHoldTime() << "\n"; in.flush(); } file.close(); } void WaypointList::loadWaypoints() { QString fileName = QFileDialog::getOpenFileName(this, tr("Load File"), ".", tr("Waypoint File (*.txt)")); QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; while(waypoints.size()>0) { removeWaypoint(waypoints[0]); } QTextStream in(&file); while (!in.atEnd()) { QStringList wpParams = in.readLine().split("\t"); if (wpParams.size() == 10) addWaypoint(new Waypoint(wpParams[1].toInt(), wpParams[2].toDouble(), wpParams[3].toDouble(), wpParams[4].toDouble(), wpParams[5].toDouble(), (wpParams[6].toInt() == 1 ? true : false), (wpParams[7].toInt() == 1 ? true : false), wpParams[8].toDouble(), wpParams[9].toInt())); } file.close(); } <commit_msg>fixed waypoint loading even more<commit_after>/*===================================================================== PIXHAWK Micro Air Vehicle Flying Robotics Toolkit (c) 2009, 2010 PIXHAWK PROJECT <http://pixhawk.ethz.ch> This file is part of the PIXHAWK project PIXHAWK 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. PIXHAWK 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 PIXHAWK. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /** * @file * @brief Waypoint list widget * * @author Lorenz Meier <mavteam@student.ethz.ch> * @author Benjamin Knecht <mavteam@student.ethz.ch> * @author Petri Tanskanen <mavteam@student.ethz.ch> * */ #include "WaypointList.h" #include "ui_WaypointList.h" #include <UASInterface.h> #include <UASManager.h> #include <QDebug> #include <QFileDialog> WaypointList::WaypointList(QWidget *parent, UASInterface* uas) : QWidget(parent), uas(NULL), m_ui(new Ui::WaypointList) { m_ui->setupUi(this); listLayout = new QVBoxLayout(m_ui->listWidget); listLayout->setSpacing(6); listLayout->setMargin(0); listLayout->setAlignment(Qt::AlignTop); m_ui->listWidget->setLayout(listLayout); wpViews = QMap<Waypoint*, WaypointView*>(); this->uas = NULL; // ADD WAYPOINT // Connect add action, set right button icon and connect action to this class connect(m_ui->addButton, SIGNAL(clicked()), m_ui->actionAddWaypoint, SIGNAL(triggered())); connect(m_ui->actionAddWaypoint, SIGNAL(triggered()), this, SLOT(add())); // SEND WAYPOINTS connect(m_ui->transmitButton, SIGNAL(clicked()), this, SLOT(transmit())); // REQUEST WAYPOINTS connect(m_ui->readButton, SIGNAL(clicked()), this, SLOT(read())); // SAVE/LOAD WAYPOINTS connect(m_ui->saveButton, SIGNAL(clicked()), this, SLOT(saveWaypoints())); connect(m_ui->loadButton, SIGNAL(clicked()), this, SLOT(loadWaypoints())); connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setUAS(UASInterface*))); // STATUS LABEL updateStatusLabel(""); // SET UAS AFTER ALL SIGNALS/SLOTS ARE CONNECTED setUAS(uas); } WaypointList::~WaypointList() { delete m_ui; } void WaypointList::updateStatusLabel(const QString &string) { m_ui->statusLabel->setText(string); } void WaypointList::setUAS(UASInterface* uas) { if (this->uas == NULL && uas != NULL) { this->uas = uas; connect(&uas->getWaypointManager(), SIGNAL(updateStatusString(const QString &)), this, SLOT(updateStatusLabel(const QString &))); connect(&uas->getWaypointManager(), SIGNAL(waypointUpdated(int,quint16,double,double,double,double,bool,bool,double,int)), this, SLOT(setWaypoint(int,quint16,double,double,double,double,bool,bool,double,int))); connect(&uas->getWaypointManager(), SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointChanged(quint16))); connect(this, SIGNAL(sendWaypoints(const QVector<Waypoint*> &)), &uas->getWaypointManager(), SLOT(sendWaypoints(const QVector<Waypoint*> &))); connect(this, SIGNAL(requestWaypoints()), &uas->getWaypointManager(), SLOT(requestWaypoints())); connect(this, SIGNAL(clearWaypointList()), &uas->getWaypointManager(), SLOT(clearWaypointList())); } } void WaypointList::setWaypoint(int uasId, quint16 id, double x, double y, double z, double yaw, bool autocontinue, bool current, double orbit, int holdTime) { if (uasId == this->uas->getUASID()) { Waypoint* wp = new Waypoint(id, x, y, z, yaw, autocontinue, current, orbit, holdTime); addWaypoint(wp); } } void WaypointList::waypointReached(UASInterface* uas, quint16 waypointId) { Q_UNUSED(uas); qDebug() << "Waypoint reached: " << waypointId; updateStatusLabel(QString("Waypoint %1 reached.").arg(waypointId)); } void WaypointList::currentWaypointChanged(quint16 seq) { if (seq < waypoints.size()) { for(int i = 0; i < waypoints.size(); i++) { WaypointView* widget = wpViews.find(waypoints[i]).value(); if (waypoints[i]->getId() == seq) { waypoints[i]->setCurrent(true); widget->setCurrent(true); } else { waypoints[i]->setCurrent(false); widget->setCurrent(false); } } redrawList(); } } void WaypointList::read() { while(waypoints.size()>0) { removeWaypoint(waypoints[0]); } emit requestWaypoints(); } void WaypointList::transmit() { emit sendWaypoints(waypoints); //emit requestWaypoints(); FIXME } void WaypointList::add() { // Only add waypoints if UAS is present if (uas) { if (waypoints.size() > 0) { addWaypoint(new Waypoint(waypoints.size(), 1.1, 1.1, -0.6, 0.0, true, false, 0.1, 2000)); } else { addWaypoint(new Waypoint(waypoints.size(), 1.1, 1.1, -0.6, 0.0, true, true, 0.1, 2000)); } } } void WaypointList::addWaypoint(Waypoint* wp) { waypoints.push_back(wp); if (!wpViews.contains(wp)) { WaypointView* wpview = new WaypointView(wp, this); wpViews.insert(wp, wpview); listLayout->addWidget(wpViews.value(wp)); connect(wpview, SIGNAL(moveDownWaypoint(Waypoint*)), this, SLOT(moveDown(Waypoint*))); connect(wpview, SIGNAL(moveUpWaypoint(Waypoint*)), this, SLOT(moveUp(Waypoint*))); connect(wpview, SIGNAL(removeWaypoint(Waypoint*)), this, SLOT(removeWaypoint(Waypoint*))); connect(wpview, SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointChanged(quint16))); } } void WaypointList::redrawList() { // Clear list layout if (!wpViews.empty()) { QMapIterator<Waypoint*,WaypointView*> viewIt(wpViews); viewIt.toFront(); while(viewIt.hasNext()) { viewIt.next(); listLayout->removeWidget(viewIt.value()); } // Re-add waypoints for(int i = 0; i < waypoints.size(); i++) { listLayout->addWidget(wpViews.value(waypoints[i])); } } } void WaypointList::moveUp(Waypoint* wp) { int id = wp->getId(); if (waypoints.size() > 1 && waypoints.size() > id) { Waypoint* temp = waypoints[id]; if (id > 0) { waypoints[id] = waypoints[id-1]; waypoints[id-1] = temp; waypoints[id-1]->setId(id-1); waypoints[id]->setId(id); } else { waypoints[id] = waypoints[waypoints.size()-1]; waypoints[waypoints.size()-1] = temp; waypoints[waypoints.size()-1]->setId(waypoints.size()-1); waypoints[id]->setId(id); } redrawList(); } } void WaypointList::moveDown(Waypoint* wp) { int id = wp->getId(); if (waypoints.size() > 1 && waypoints.size() > id) { Waypoint* temp = waypoints[id]; if (id != waypoints.size()-1) { waypoints[id] = waypoints[id+1]; waypoints[id+1] = temp; waypoints[id+1]->setId(id+1); waypoints[id]->setId(id); } else { waypoints[id] = waypoints[0]; waypoints[0] = temp; waypoints[0]->setId(0); waypoints[id]->setId(id); } redrawList(); } } void WaypointList::removeWaypoint(Waypoint* wp) { // Delete from list if (wp != NULL) { waypoints.remove(wp->getId()); for(int i = wp->getId(); i < waypoints.size(); i++) { waypoints[i]->setId(i); } // Remove from view WaypointView* widget = wpViews.find(wp).value(); wpViews.remove(wp); widget->hide(); listLayout->removeWidget(widget); delete wp; } } void WaypointList::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::LanguageChange: m_ui->retranslateUi(this); break; default: break; } } void WaypointList::saveWaypoints() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "./waypoints.txt", tr("Waypoint File (*.txt)")); QFile file(fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return; QTextStream in(&file); for (int i = 0; i < waypoints.size(); i++) { Waypoint* wp = waypoints[i]; in << "\t" << wp->getId() << "\t" << wp->getX() << "\t" << wp->getY() << "\t" << wp->getZ() << "\t" << wp->getYaw() << "\t" << wp->getAutoContinue() << "\t" << wp->getCurrent() << "\t" << wp->getOrbit() << "\t" << wp->getHoldTime() << "\n"; in.flush(); } file.close(); } void WaypointList::loadWaypoints() { QString fileName = QFileDialog::getOpenFileName(this, tr("Load File"), ".", tr("Waypoint File (*.txt)")); QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; while(waypoints.size()>0) { removeWaypoint(waypoints[0]); } QTextStream in(&file); while (!in.atEnd()) { QStringList wpParams = in.readLine().split("\t"); if (wpParams.size() == 10) addWaypoint(new Waypoint(wpParams[1].toInt(), wpParams[2].toDouble(), wpParams[3].toDouble(), wpParams[4].toDouble(), wpParams[5].toDouble(), (wpParams[6].toInt() == 1 ? true : false), (wpParams[7].toInt() == 1 ? true : false), wpParams[8].toDouble(), wpParams[9].toInt())); } file.close(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia 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 (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "chordsdetectionbeats.h" #include "essentiamath.h" using namespace std; namespace essentia { namespace standard { const char* ChordsDetectionBeats::name = "ChordsDetectionBeats"; const char* ChordsDetectionBeats::description = DOC("This algorithm takes the ChordsDetection algorithm from Essentia, and tries to enhance it by using a Beat Tracker for in between estimation.\n" "\n" "Note:\n" " - This algorithm assumes that input pcps have been computed with framesize = 2*hopsize\n" "\n" "Quality: experimental (prone to errors, algorithm needs improvement)\n" "\n" "References:\n" " [1] E. Gómez, \"Tonal Description of Polyphonic Audio for Music Content\n" " Processing,\" INFORMS Journal on Computing, vol. 18, no. 3, pp. 294–304,\n" " 2006.\n\n" " [2] D. Temperley, \"What's key for key? The Krumhansl-Schmuckler\n" " key-finding algorithm reconsidered\", Music Perception vol. 17, no. 1,\n" " pp. 65-100, 1999."); void ChordsDetectionBeats::configure() { Real wsize = parameter("windowSize").toReal(); _sampleRate = parameter("sampleRate").toReal(); _hopSize = parameter("hopSize").toInt(); // NB: this assumes that frameSize = hopSize * 2, so that we don't have to // require frameSize as well as parameter. _numFramesWindow = int((wsize * _sampleRate) / _hopSize) - 1; // wsize = 1.0 , hopSize = 512 --> 85 } void ChordsDetectionBeats::compute() { const vector<vector<Real> >& hpcp = _pcp.get(); vector<string>& chords = _chords.get(); vector<Real>& strength = _strength.get(); const vector<Real>& ticks = _ticks.get(); string key; string scale; Real firstToSecondRelativeStrength; Real str; // strength chords.reserve(int(hpcp.size()/_numFramesWindow)); // 1478/85 = 17 //out << "chords.reserve(int(hpcp.size()/_numFramesWindow)); = " << int(hpcp.size()/_numFramesWindow) << endl; strength.reserve(int(hpcp.size()/_numFramesWindow)); //cout << "int(hpcp.size() = " << (int)hpcp.size() << endl; // for (int j=0; j<ticks.size(); j++) { // cout << "tick " << j << " " << ticks[j] << endl; // } if(ticks.size() < 2) { throw EssentiaException("Ticks vector should contain at least 2 elements."); } Real diffTicks = 0.0f; int numFramesTick = 0; int initFrame = 0; int frameStart=0; int frameEnd=0; //cout << "ticks.size() = "<<ticks.size()<< "from 0 to "<< ticks.size()-1 << ", ticks[size-1]"<<ticks[ticks.size()-1]<< endl; //cout << "hpcp.size() = length of chords output array in the previous version of the code = " <<hpcp.size()<< endl; for (int i = 0; i < ticks.size()-1; ++i){ diffTicks = ticks[i+1] - ticks[i]; numFramesTick = int((diffTicks * _sampleRate) / _hopSize); frameStart = int((ticks[i] * _sampleRate) / _hopSize); frameEnd = frameStart + numFramesTick-1; if (frameEnd > hpcp.size()-1) break; vector<Real> hpcpMedian = medianFrames(hpcp, frameStart, frameEnd); normalize(hpcpMedian); _chordsAlgo->input("pcp").set(hpcpMedian); _chordsAlgo->output("key").set(key); _chordsAlgo->output("scale").set(scale); _chordsAlgo->output("strength").set(str); _chordsAlgo->output("firstToSecondRelativeStrength").set(firstToSecondRelativeStrength); _chordsAlgo->compute(); if (scale == "minor") { chords.push_back(key + 'm'); } else { chords.push_back(key); } strength.push_back(str); } // for }//method } // namespace standard } // namespace essentia #include "poolstorage.h" namespace essentia { namespace streaming { const char* ChordsDetectionBeats::name = standard::ChordsDetectionBeats::name; const char* ChordsDetectionBeats::description = standard::ChordsDetectionBeats::description; ChordsDetectionBeats::ChordsDetectionBeats() : AlgorithmComposite() { declareInput(_pcp, "pcp", "the pitch class profile from which to detect the chord"); declareOutput(_chords, 1, "chords", "the resulting chords, from A to G"); declareOutput(_strength, 1, "strength", "the strength of the chord"); _chordsAlgo = standard::AlgorithmFactory::create("Key"); _chordsAlgo->configure("profileType", "tonictriad", "usePolyphony", false); _poolStorage = new PoolStorage<vector<Real> >(&_pool, "internal.hpcp"); // FIXME: this is just a temporary hack... // the correct way to do this is to have the algorithm output the chords // continuously while processing, which requires a FrameCutter for vectors // Need to set the buffer type to multiple frames as all the chords // are output all at once _chords.setBufferType(BufferUsage::forMultipleFrames); _strength.setBufferType(BufferUsage::forMultipleFrames); attach(_pcp, _poolStorage->input("data")); } ChordsDetectionBeats::~ChordsDetectionBeats() { delete _chordsAlgo; delete _poolStorage; } void ChordsDetectionBeats::configure() { Real wsize = parameter("windowSize").toReal(); Real sampleRate = parameter("sampleRate").toReal(); int hopSize = parameter("hopSize").toInt(); // NB: this assumes that frameSize = hopSize * 2, so that we don't have to // require frameSize as well as parameter. _numFramesWindow = int((wsize * sampleRate) / hopSize) - 1; } AlgorithmStatus ChordsDetectionBeats::process() { if (!shouldStop()) return PASS; const vector<vector<Real> >& hpcp = _pool.value<vector<vector<Real> > >("internal.hpcp"); string key; string scale; Real strength; Real firstToSecondRelativeStrength; // This is very strange, because we jump by a single frame each time, not by // the defined windowSize. Is that the expected behavior or is it a bug? // eaylon: windowSize is not intended for advancing, but for searching // nwack: maybe it could be a smart idea to jump from 1 beat to another instead // of a fixed amount a time (arbitrary frame size) for (int i=0; i<(int)hpcp.size(); i++) { int indexStart = max(0, i - _numFramesWindow/2); int indexEnd = min(i + _numFramesWindow/2, (int)hpcp.size()); //vector<Real> hpcpAverage = medianFrames(hpcp, indexStart, indexEnd); vector<Real> hpcpAverage = meanFrames(hpcp, indexStart, indexEnd); normalize(hpcpAverage); _chordsAlgo->input("pcp").set(hpcpAverage); _chordsAlgo->output("key").set(key); _chordsAlgo->output("scale").set(scale); _chordsAlgo->output("strength").set(strength); _chordsAlgo->output("firstToSecondRelativeStrength").set(firstToSecondRelativeStrength); _chordsAlgo->compute(); if (scale == "minor") { _chords.push(key + 'm'); } else { _chords.push(key); } _strength.push(strength); } return FINISHED; } void ChordsDetectionBeats::reset() { AlgorithmComposite::reset(); _chordsAlgo->reset(); } } // namespace streaming } // namespace essentia <commit_msg>Just cleaned some comments<commit_after>/* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia 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 (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "chordsdetectionbeats.h" #include "essentiamath.h" using namespace std; namespace essentia { namespace standard { const char* ChordsDetectionBeats::name = "ChordsDetectionBeats"; const char* ChordsDetectionBeats::description = DOC("This algorithm takes the ChordsDetection algorithm from Essentia, and tries to enhance it by using a Beat Tracker for in between estimation.\n" "\n" "Note:\n" " - This algorithm assumes that input pcps have been computed with framesize = 2*hopsize\n" "\n" "Quality: experimental (prone to errors, algorithm needs improvement)\n" "\n" "References:\n" " [1] E. Gómez, \"Tonal Description of Polyphonic Audio for Music Content\n" " Processing,\" INFORMS Journal on Computing, vol. 18, no. 3, pp. 294–304,\n" " 2006.\n\n" " [2] D. Temperley, \"What's key for key? The Krumhansl-Schmuckler\n" " key-finding algorithm reconsidered\", Music Perception vol. 17, no. 1,\n" " pp. 65-100, 1999."); void ChordsDetectionBeats::configure() { Real wsize = parameter("windowSize").toReal(); _sampleRate = parameter("sampleRate").toReal(); _hopSize = parameter("hopSize").toInt(); // NB: this assumes that frameSize = hopSize * 2, so that we don't have to // require frameSize as well as parameter. _numFramesWindow = int((wsize * _sampleRate) / _hopSize) - 1; // wsize = 1.0 , hopSize = 512 --> 85 } void ChordsDetectionBeats::compute() { const vector<vector<Real> >& hpcp = _pcp.get(); vector<string>& chords = _chords.get(); vector<Real>& strength = _strength.get(); const vector<Real>& ticks = _ticks.get(); string key; string scale; Real firstToSecondRelativeStrength; Real str; // strength chords.reserve(int(hpcp.size()/_numFramesWindow)); strength.reserve(int(hpcp.size()/_numFramesWindow)); if(ticks.size() < 2) { throw EssentiaException("Ticks vector should contain at least 2 elements."); } Real diffTicks = 0.0f; int numFramesTick = 0; int initFrame = 0; int frameStart=0; int frameEnd=0; for (int i = 0; i < ticks.size()-1; ++i){ diffTicks = ticks[i+1] - ticks[i]; numFramesTick = int((diffTicks * _sampleRate) / _hopSize); frameStart = int((ticks[i] * _sampleRate) / _hopSize); frameEnd = frameStart + numFramesTick-1; if (frameEnd > hpcp.size()-1) break; vector<Real> hpcpMedian = medianFrames(hpcp, frameStart, frameEnd); normalize(hpcpMedian); _chordsAlgo->input("pcp").set(hpcpMedian); _chordsAlgo->output("key").set(key); _chordsAlgo->output("scale").set(scale); _chordsAlgo->output("strength").set(str); _chordsAlgo->output("firstToSecondRelativeStrength").set(firstToSecondRelativeStrength); _chordsAlgo->compute(); if (scale == "minor") { chords.push_back(key + 'm'); } else { chords.push_back(key); } strength.push_back(str); } // for }//method } // namespace standard } // namespace essentia #include "poolstorage.h" namespace essentia { namespace streaming { const char* ChordsDetectionBeats::name = standard::ChordsDetectionBeats::name; const char* ChordsDetectionBeats::description = standard::ChordsDetectionBeats::description; ChordsDetectionBeats::ChordsDetectionBeats() : AlgorithmComposite() { declareInput(_pcp, "pcp", "the pitch class profile from which to detect the chord"); declareOutput(_chords, 1, "chords", "the resulting chords, from A to G"); declareOutput(_strength, 1, "strength", "the strength of the chord"); _chordsAlgo = standard::AlgorithmFactory::create("Key"); _chordsAlgo->configure("profileType", "tonictriad", "usePolyphony", false); _poolStorage = new PoolStorage<vector<Real> >(&_pool, "internal.hpcp"); // FIXME: this is just a temporary hack... // the correct way to do this is to have the algorithm output the chords // continuously while processing, which requires a FrameCutter for vectors // Need to set the buffer type to multiple frames as all the chords // are output all at once _chords.setBufferType(BufferUsage::forMultipleFrames); _strength.setBufferType(BufferUsage::forMultipleFrames); attach(_pcp, _poolStorage->input("data")); } ChordsDetectionBeats::~ChordsDetectionBeats() { delete _chordsAlgo; delete _poolStorage; } void ChordsDetectionBeats::configure() { Real wsize = parameter("windowSize").toReal(); Real sampleRate = parameter("sampleRate").toReal(); int hopSize = parameter("hopSize").toInt(); // NB: this assumes that frameSize = hopSize * 2, so that we don't have to // require frameSize as well as parameter. _numFramesWindow = int((wsize * sampleRate) / hopSize) - 1; } AlgorithmStatus ChordsDetectionBeats::process() { if (!shouldStop()) return PASS; const vector<vector<Real> >& hpcp = _pool.value<vector<vector<Real> > >("internal.hpcp"); string key; string scale; Real strength; Real firstToSecondRelativeStrength; // This is very strange, because we jump by a single frame each time, not by // the defined windowSize. Is that the expected behavior or is it a bug? // eaylon: windowSize is not intended for advancing, but for searching // nwack: maybe it could be a smart idea to jump from 1 beat to another instead // of a fixed amount a time (arbitrary frame size) for (int i=0; i<(int)hpcp.size(); i++) { int indexStart = max(0, i - _numFramesWindow/2); int indexEnd = min(i + _numFramesWindow/2, (int)hpcp.size()); vector<Real> hpcpAverage = meanFrames(hpcp, indexStart, indexEnd); normalize(hpcpAverage); _chordsAlgo->input("pcp").set(hpcpAverage); _chordsAlgo->output("key").set(key); _chordsAlgo->output("scale").set(scale); _chordsAlgo->output("strength").set(strength); _chordsAlgo->output("firstToSecondRelativeStrength").set(firstToSecondRelativeStrength); _chordsAlgo->compute(); if (scale == "minor") { _chords.push(key + 'm'); } else { _chords.push(key); } _strength.push(strength); } return FINISHED; } void ChordsDetectionBeats::reset() { AlgorithmComposite::reset(); _chordsAlgo->reset(); } } // namespace streaming } // namespace essentia <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkGeoProjection.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 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkGeoProjection.h" #include "vtkObjectFactory.h" #include <sstream> #include <string> #include <map> #include <vector> #include "vtk_libproj4.h" vtkStandardNewMacro(vtkGeoProjection); static int vtkGeoProjectionNumProj = -1; //----------------------------------------------------------------------------- class vtkGeoProjection::vtkInternals { public: const char* GetKeyAt(int index) { if (static_cast<int>(this->OptionalParameters.size()) > index) { std::map< std::string, std::string >::iterator iter = this->OptionalParameters.begin(); int nbIter = index; while(nbIter > 0) { nbIter--; iter++; } return iter->first.c_str(); } return NULL; } const char* GetValueAt(int index) { if (static_cast<int>(this->OptionalParameters.size()) > index) { std::map< std::string, std::string >::iterator iter = this->OptionalParameters.begin(); int nbIter = index; while(nbIter > 0) { nbIter--; iter++; } return iter->second.c_str(); } return NULL; } std::map< std::string, std::string > OptionalParameters; }; //----------------------------------------------------------------------------- int vtkGeoProjection::GetNumberOfProjections() { if ( vtkGeoProjectionNumProj < 0 ) { vtkGeoProjectionNumProj = 0; for ( const PJ_LIST* pj = pj_get_list_ref(); pj && pj->id; ++ pj ) ++ vtkGeoProjectionNumProj; } return vtkGeoProjectionNumProj; } //----------------------------------------------------------------------------- const char* vtkGeoProjection::GetProjectionName( int projection ) { if ( projection < 0 || projection >= vtkGeoProjection::GetNumberOfProjections() ) return 0; return pj_get_list_ref()[projection].id; } //----------------------------------------------------------------------------- const char* vtkGeoProjection::GetProjectionDescription( int projection ) { if ( projection < 0 || projection >= vtkGeoProjection::GetNumberOfProjections() ) return 0; return pj_get_list_ref()[projection].descr[0]; } //----------------------------------------------------------------------------- vtkGeoProjection::vtkGeoProjection() { this->Name = NULL; this->SetName( "latlong" ); this->CentralMeridian = 0.; this->Projection = NULL; this->ProjectionMTime = 0; this->Internals = new vtkInternals(); } //----------------------------------------------------------------------------- vtkGeoProjection::~vtkGeoProjection() { this->SetName( 0 ); if ( this->Projection ) { pj_free( this->Projection ); } delete this->Internals; this->Internals = NULL; } //----------------------------------------------------------------------------- void vtkGeoProjection::PrintSelf( ostream& os, vtkIndent indent ) { this->Superclass::PrintSelf( os, indent ); os << indent << "Name: " << this->Name << "\n"; os << indent << "CentralMeridian: " << this->CentralMeridian << "\n"; os << indent << "Projection: " << this->Projection << "\n"; os << indent << "Optional parameters:\n"; for(int i=0;i<this->GetNumberOfOptionalParameters();i++) { os << indent << " - " << this->GetOptionalParameterKey(i) << " = " << this->GetOptionalParameterValue(i) << "\n"; } } //----------------------------------------------------------------------------- int vtkGeoProjection::GetIndex() { int i = 0; for ( const PJ_LIST* proj = pj_get_list_ref(); proj && proj->id; ++ proj, ++ i ) { if ( ! strcmp( proj->id, this->Name ) ) { return i; } } return -1; } //----------------------------------------------------------------------------- const char* vtkGeoProjection::GetDescription() { this->UpdateProjection(); if ( ! this->Projection ) { return 0; } return this->Projection->descr; } //----------------------------------------------------------------------------- projPJ vtkGeoProjection::GetProjection() { this->UpdateProjection(); return this->Projection; } //----------------------------------------------------------------------------- int vtkGeoProjection::UpdateProjection() { if ( this->GetMTime() <= this->ProjectionMTime ) { return 0; } if ( this->Projection ) { pj_free( this->Projection ); this->Projection = 0; } if ( ! this->Name || ! strlen( this->Name ) ) { return 1; } if ( ! strcmp ( this->Name, "latlong" ) ) { // latlong is "null" projection. return 0; } int argSize = 3 + this->GetNumberOfOptionalParameters(); const char** pjArgs = new const char*[argSize]; std::string projSpec( "+proj=" ); projSpec += this->Name; std::string ellpsSpec( "+ellps=clrk66" ); std::string meridSpec; std::ostringstream os; os << "+lon_0=" << this->CentralMeridian; meridSpec = os.str(); pjArgs[0] = projSpec.c_str(); pjArgs[1] = ellpsSpec.c_str(); pjArgs[2] = meridSpec.c_str(); // Add optional parameters std::vector<std::string> stringHolder; // Keep string ref in memory for(int i=0; i < this->GetNumberOfOptionalParameters(); i++) { std::ostringstream param; param << "+" << this->GetOptionalParameterKey(i); param << "=" << this->GetOptionalParameterValue(i); stringHolder.push_back(param.str()); pjArgs[3+i] = stringHolder[i].c_str(); } this->Projection = pj_init( argSize, const_cast<char**>( pjArgs ) ); delete[] pjArgs; this->ProjectionMTime = this->GetMTime(); if ( this->Projection ) { return 0; } return 1; } //----------------------------------------------------------------------------- void vtkGeoProjection::SetOptionalParameter(const char* key, const char* value) { if(key != NULL && value != NULL) { this->Internals->OptionalParameters[key] = value; this->Modified(); } else { vtkErrorMacro("Invalid Optional Parameter Key/Value pair. None can be NULL"); } } //----------------------------------------------------------------------------- void vtkGeoProjection::RemoveOptionalParameter(const char* key) { this->Internals->OptionalParameters.erase(key); this->Modified(); } //----------------------------------------------------------------------------- int vtkGeoProjection::GetNumberOfOptionalParameters() { return static_cast<int>(this->Internals->OptionalParameters.size()); } //----------------------------------------------------------------------------- const char* vtkGeoProjection::GetOptionalParameterKey(int index) { return this->Internals->GetKeyAt(index); } //----------------------------------------------------------------------------- const char* vtkGeoProjection::GetOptionalParameterValue(int index) { return this->Internals->GetValueAt(index); } //----------------------------------------------------------------------------- void vtkGeoProjection::ClearOptionalParameters() { this->Internals->OptionalParameters.clear(); this->Modified(); } <commit_msg>BUG: push_back may cause pointers to become invalid<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkGeoProjection.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 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkGeoProjection.h" #include "vtkObjectFactory.h" #include <sstream> #include <string> #include <map> #include <vector> #include "vtk_libproj4.h" vtkStandardNewMacro(vtkGeoProjection); static int vtkGeoProjectionNumProj = -1; //----------------------------------------------------------------------------- class vtkGeoProjection::vtkInternals { public: const char* GetKeyAt(int index) { if (static_cast<int>(this->OptionalParameters.size()) > index) { std::map< std::string, std::string >::iterator iter = this->OptionalParameters.begin(); int nbIter = index; while(nbIter > 0) { nbIter--; iter++; } return iter->first.c_str(); } return NULL; } const char* GetValueAt(int index) { if (static_cast<int>(this->OptionalParameters.size()) > index) { std::map< std::string, std::string >::iterator iter = this->OptionalParameters.begin(); int nbIter = index; while(nbIter > 0) { nbIter--; iter++; } return iter->second.c_str(); } return NULL; } std::map< std::string, std::string > OptionalParameters; }; //----------------------------------------------------------------------------- int vtkGeoProjection::GetNumberOfProjections() { if ( vtkGeoProjectionNumProj < 0 ) { vtkGeoProjectionNumProj = 0; for ( const PJ_LIST* pj = pj_get_list_ref(); pj && pj->id; ++ pj ) ++ vtkGeoProjectionNumProj; } return vtkGeoProjectionNumProj; } //----------------------------------------------------------------------------- const char* vtkGeoProjection::GetProjectionName( int projection ) { if ( projection < 0 || projection >= vtkGeoProjection::GetNumberOfProjections() ) return 0; return pj_get_list_ref()[projection].id; } //----------------------------------------------------------------------------- const char* vtkGeoProjection::GetProjectionDescription( int projection ) { if ( projection < 0 || projection >= vtkGeoProjection::GetNumberOfProjections() ) return 0; return pj_get_list_ref()[projection].descr[0]; } //----------------------------------------------------------------------------- vtkGeoProjection::vtkGeoProjection() { this->Name = NULL; this->SetName( "latlong" ); this->CentralMeridian = 0.; this->Projection = NULL; this->ProjectionMTime = 0; this->Internals = new vtkInternals(); } //----------------------------------------------------------------------------- vtkGeoProjection::~vtkGeoProjection() { this->SetName( 0 ); if ( this->Projection ) { pj_free( this->Projection ); } delete this->Internals; this->Internals = NULL; } //----------------------------------------------------------------------------- void vtkGeoProjection::PrintSelf( ostream& os, vtkIndent indent ) { this->Superclass::PrintSelf( os, indent ); os << indent << "Name: " << this->Name << "\n"; os << indent << "CentralMeridian: " << this->CentralMeridian << "\n"; os << indent << "Projection: " << this->Projection << "\n"; os << indent << "Optional parameters:\n"; for(int i=0;i<this->GetNumberOfOptionalParameters();i++) { os << indent << " - " << this->GetOptionalParameterKey(i) << " = " << this->GetOptionalParameterValue(i) << "\n"; } } //----------------------------------------------------------------------------- int vtkGeoProjection::GetIndex() { int i = 0; for ( const PJ_LIST* proj = pj_get_list_ref(); proj && proj->id; ++ proj, ++ i ) { if ( ! strcmp( proj->id, this->Name ) ) { return i; } } return -1; } //----------------------------------------------------------------------------- const char* vtkGeoProjection::GetDescription() { this->UpdateProjection(); if ( ! this->Projection ) { return 0; } return this->Projection->descr; } //----------------------------------------------------------------------------- projPJ vtkGeoProjection::GetProjection() { this->UpdateProjection(); return this->Projection; } //----------------------------------------------------------------------------- int vtkGeoProjection::UpdateProjection() { if ( this->GetMTime() <= this->ProjectionMTime ) { return 0; } if ( this->Projection ) { pj_free( this->Projection ); this->Projection = 0; } if ( ! this->Name || ! strlen( this->Name ) ) { return 1; } if ( ! strcmp ( this->Name, "latlong" ) ) { // latlong is "null" projection. return 0; } int argSize = 3 + this->GetNumberOfOptionalParameters(); const char** pjArgs = new const char*[argSize]; std::string projSpec( "+proj=" ); projSpec += this->Name; std::string ellpsSpec( "+ellps=clrk66" ); std::string meridSpec; std::ostringstream os; os << "+lon_0=" << this->CentralMeridian; meridSpec = os.str(); pjArgs[0] = projSpec.c_str(); pjArgs[1] = ellpsSpec.c_str(); pjArgs[2] = meridSpec.c_str(); // Add optional parameters std::vector<std::string> stringHolder( this->GetNumberOfOptionalParameters()); // Keep string ref in memory for(int i=0; i < this->GetNumberOfOptionalParameters(); i++) { std::ostringstream param; param << "+" << this->GetOptionalParameterKey(i); param << "=" << this->GetOptionalParameterValue(i); stringHolder[i] = param.str(); pjArgs[3+i] = stringHolder[i].c_str(); } this->Projection = pj_init( argSize, const_cast<char**>( pjArgs ) ); delete[] pjArgs; this->ProjectionMTime = this->GetMTime(); if ( this->Projection ) { return 0; } return 1; } //----------------------------------------------------------------------------- void vtkGeoProjection::SetOptionalParameter(const char* key, const char* value) { if(key != NULL && value != NULL) { this->Internals->OptionalParameters[key] = value; this->Modified(); } else { vtkErrorMacro("Invalid Optional Parameter Key/Value pair. None can be NULL"); } } //----------------------------------------------------------------------------- void vtkGeoProjection::RemoveOptionalParameter(const char* key) { this->Internals->OptionalParameters.erase(key); this->Modified(); } //----------------------------------------------------------------------------- int vtkGeoProjection::GetNumberOfOptionalParameters() { return static_cast<int>(this->Internals->OptionalParameters.size()); } //----------------------------------------------------------------------------- const char* vtkGeoProjection::GetOptionalParameterKey(int index) { return this->Internals->GetKeyAt(index); } //----------------------------------------------------------------------------- const char* vtkGeoProjection::GetOptionalParameterValue(int index) { return this->Internals->GetValueAt(index); } //----------------------------------------------------------------------------- void vtkGeoProjection::ClearOptionalParameters() { this->Internals->OptionalParameters.clear(); this->Modified(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- standard modules used ---------------------------------------------------- #include "TestRunner.h" // this is just included to test the definition of the setupRunner function #include "SetupRunner.h" #if defined(__linux__) && !defined(gettimes) HRTESTTIME gettimes() { struct tms tt; return times(&tt); } #endif int main (int ac, const char **av) { TestRunner runner; setupRunner(runner); runner.run (ac, av); return runner.getNumberOfFailures(); } <commit_msg>moved foundation_test to revised and migrated to autotools<commit_after>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- standard modules used ---------------------------------------------------- #include "TestRunner.h" // this is just included to test the definition of the setupRunner function #include "SetupRunner.h" #if !defined(WIN32) && !defined(gettimes) HRTESTTIME gettimes() { struct tms tt; return times(&tt); } #endif int main (int ac, const char **av) { TestRunner runner; setupRunner(runner); runner.run (ac, av); return runner.getNumberOfFailures(); } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. // Unit tests for resolveviewvisitor. #include <vespa/log/log.h> LOG_SETUP("resolveviewvisitor_test"); #include <vespa/searchlib/fef/test/indexenvironment.h> #include <vespa/searchcore/proton/matching/querynodes.h> #include <vespa/searchcore/proton/matching/resolveviewvisitor.h> #include <vespa/searchcore/proton/matching/viewresolver.h> #include <vespa/searchlib/query/tree/node.h> #include <vespa/searchlib/query/tree/querybuilder.h> #include <vespa/vespalib/testkit/testapp.h> #include <string> namespace fef_test = search::fef::test; using search::fef::FieldInfo; using search::fef::FieldType; using search::fef::test::IndexEnvironment; using search::query::Node; using search::query::QueryBuilder; using std::string; using namespace proton::matching; using CollectionType = FieldInfo::CollectionType; namespace { const string term = "term"; const string view = "view"; const string field1 = "field1"; const string field2 = "field2"; const uint32_t id = 1; const search::query::Weight weight(2); ViewResolver getResolver(const string &test_view) { ViewResolver resolver; resolver.add(test_view, field1); resolver.add(test_view, field2); return resolver; } struct Fixture { IndexEnvironment index_environment; Fixture() { index_environment.getFields().push_back(FieldInfo( FieldType::INDEX, CollectionType::SINGLE, field1, 0)); index_environment.getFields().push_back(FieldInfo( FieldType::INDEX, CollectionType::SINGLE, field2, 1)); } }; TEST_F("requireThatFieldsResolveToThemselves", Fixture) { ViewResolver resolver = getResolver(view); QueryBuilder<ProtonNodeTypes> builder; ProtonTermData &base = builder.addStringTerm(term, field1, id, weight); Node::UP node = builder.build(); ResolveViewVisitor visitor(resolver, f.index_environment); node->accept(visitor); EXPECT_EQUAL(1u, base.numFields()); EXPECT_EQUAL(field1, base.field(0).field_name); } void checkResolveAlias(const string &view_name, const string &alias, const Fixture &f) { ViewResolver resolver = getResolver(view_name); QueryBuilder<ProtonNodeTypes> builder; ProtonTermData &base = builder.addStringTerm(term, alias, id, weight); Node::UP node = builder.build(); ResolveViewVisitor visitor(resolver, f.index_environment); node->accept(visitor); ASSERT_EQUAL(2u, base.numFields()); EXPECT_EQUAL(field1, base.field(0).field_name); EXPECT_EQUAL(field2, base.field(1).field_name); } TEST_F("requireThatViewsCanResolveToMultipleFields", Fixture) { checkResolveAlias(view, view, f); } TEST_F("requireThatEmptyViewResolvesAsDefault", Fixture) { const string default_view = "default"; const string empty_view = ""; checkResolveAlias(default_view, empty_view, f); } TEST_F("requireThatWeCanForceFilterField", Fixture) { ViewResolver resolver = getResolver(view); f.index_environment.getFields().back().setFilter(true); ResolveViewVisitor visitor(resolver, f.index_environment); { // use filter field settings from index environment QueryBuilder<ProtonNodeTypes> builder; ProtonStringTerm &sterm = builder.addStringTerm(term, view, id, weight); Node::UP node = builder.build(); node->accept(visitor); ASSERT_EQUAL(2u, sterm.numFields()); EXPECT_TRUE(!sterm.field(0).filter_field); EXPECT_TRUE(sterm.field(1).filter_field); } { // force filter on all fields QueryBuilder<ProtonNodeTypes> builder; ProtonStringTerm &sterm = builder.addStringTerm(term, view, id, weight); sterm.setPositionData(false); // force filter Node::UP node = builder.build(); node->accept(visitor); ASSERT_EQUAL(2u, sterm.numFields()); EXPECT_TRUE(sterm.field(0).filter_field); EXPECT_TRUE(sterm.field(1).filter_field); } } TEST_F("require that equiv nodes resolve view from children", Fixture) { ViewResolver resolver; resolver.add(view, field1); QueryBuilder<ProtonNodeTypes> builder; ProtonTermData &base = builder.addEquiv(2, id, weight); builder.addStringTerm(term, view, 42, weight); builder.addStringTerm(term, field2, 43, weight); Node::UP node = builder.build(); ResolveViewVisitor visitor(resolver, f.index_environment); node->accept(visitor); ASSERT_EQUAL(2u, base.numFields()); EXPECT_EQUAL(field1, base.field(0).field_name); EXPECT_EQUAL(field2, base.field(1).field_name); } } // namespace TEST_MAIN() { TEST_RUN_ALL(); } <commit_msg>add test for view resolving of same element children<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. // Unit tests for resolveviewvisitor. #include <vespa/log/log.h> LOG_SETUP("resolveviewvisitor_test"); #include <vespa/searchlib/fef/test/indexenvironment.h> #include <vespa/searchcore/proton/matching/querynodes.h> #include <vespa/searchcore/proton/matching/resolveviewvisitor.h> #include <vespa/searchcore/proton/matching/viewresolver.h> #include <vespa/searchlib/query/tree/node.h> #include <vespa/searchlib/query/tree/querybuilder.h> #include <vespa/vespalib/testkit/testapp.h> #include <string> namespace fef_test = search::fef::test; using search::fef::FieldInfo; using search::fef::FieldType; using search::fef::test::IndexEnvironment; using search::query::Node; using search::query::QueryBuilder; using std::string; using namespace proton::matching; using CollectionType = FieldInfo::CollectionType; namespace { const string term = "term"; const string view = "view"; const string field1 = "field1"; const string field2 = "field2"; const uint32_t id = 1; const search::query::Weight weight(2); ViewResolver getResolver(const string &test_view) { ViewResolver resolver; resolver.add(test_view, field1); resolver.add(test_view, field2); return resolver; } struct Fixture { IndexEnvironment index_environment; Fixture() { index_environment.getFields().push_back(FieldInfo( FieldType::INDEX, CollectionType::SINGLE, field1, 0)); index_environment.getFields().push_back(FieldInfo( FieldType::INDEX, CollectionType::SINGLE, field2, 1)); } }; TEST_F("requireThatFieldsResolveToThemselves", Fixture) { ViewResolver resolver = getResolver(view); QueryBuilder<ProtonNodeTypes> builder; ProtonTermData &base = builder.addStringTerm(term, field1, id, weight); Node::UP node = builder.build(); ResolveViewVisitor visitor(resolver, f.index_environment); node->accept(visitor); EXPECT_EQUAL(1u, base.numFields()); EXPECT_EQUAL(field1, base.field(0).field_name); } void checkResolveAlias(const string &view_name, const string &alias, const Fixture &f) { ViewResolver resolver = getResolver(view_name); QueryBuilder<ProtonNodeTypes> builder; ProtonTermData &base = builder.addStringTerm(term, alias, id, weight); Node::UP node = builder.build(); ResolveViewVisitor visitor(resolver, f.index_environment); node->accept(visitor); ASSERT_EQUAL(2u, base.numFields()); EXPECT_EQUAL(field1, base.field(0).field_name); EXPECT_EQUAL(field2, base.field(1).field_name); } TEST_F("requireThatViewsCanResolveToMultipleFields", Fixture) { checkResolveAlias(view, view, f); } TEST_F("requireThatEmptyViewResolvesAsDefault", Fixture) { const string default_view = "default"; const string empty_view = ""; checkResolveAlias(default_view, empty_view, f); } TEST_F("requireThatWeCanForceFilterField", Fixture) { ViewResolver resolver = getResolver(view); f.index_environment.getFields().back().setFilter(true); ResolveViewVisitor visitor(resolver, f.index_environment); { // use filter field settings from index environment QueryBuilder<ProtonNodeTypes> builder; ProtonStringTerm &sterm = builder.addStringTerm(term, view, id, weight); Node::UP node = builder.build(); node->accept(visitor); ASSERT_EQUAL(2u, sterm.numFields()); EXPECT_TRUE(!sterm.field(0).filter_field); EXPECT_TRUE(sterm.field(1).filter_field); } { // force filter on all fields QueryBuilder<ProtonNodeTypes> builder; ProtonStringTerm &sterm = builder.addStringTerm(term, view, id, weight); sterm.setPositionData(false); // force filter Node::UP node = builder.build(); node->accept(visitor); ASSERT_EQUAL(2u, sterm.numFields()); EXPECT_TRUE(sterm.field(0).filter_field); EXPECT_TRUE(sterm.field(1).filter_field); } } TEST_F("require that equiv nodes resolve view from children", Fixture) { ViewResolver resolver; resolver.add(view, field1); QueryBuilder<ProtonNodeTypes> builder; ProtonTermData &base = builder.addEquiv(2, id, weight); builder.addStringTerm(term, view, 42, weight); builder.addStringTerm(term, field2, 43, weight); Node::UP node = builder.build(); ResolveViewVisitor visitor(resolver, f.index_environment); node->accept(visitor); ASSERT_EQUAL(2u, base.numFields()); EXPECT_EQUAL(field1, base.field(0).field_name); EXPECT_EQUAL(field2, base.field(1).field_name); } TEST_F("require that view is resolved for SameElement children", Fixture) { ViewResolver resolver; resolver.add(view, field1); QueryBuilder<ProtonNodeTypes> builder; builder.addSameElement(2, ""); ProtonStringTerm &my_term = builder.addStringTerm(term, view, 42, weight); builder.addStringTerm(term, field2, 43, weight); Node::UP node = builder.build(); ResolveViewVisitor visitor(resolver, f.index_environment); node->accept(visitor); ASSERT_EQUAL(1u, my_term.numFields()); EXPECT_EQUAL(field1, my_term.field(0).field_name); } } // namespace TEST_MAIN() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "nodemanager.h" #include "datasetcollection.h" #include "plain_dataset.h" #include "engine_base.h" #include <vespa/config/common/exceptions.h> #include <set> #include <vespa/log/log.h> LOG_SETUP(".search.nodemanager"); void FastS_NodeManager::configure(std::unique_ptr<PartitionsConfig> cfg) { LOG(config, "configuring datasetcollection from '%s'", _configUri.getConfigId().c_str()); SetPartMap(*cfg, 2000); _componentConfig.addConfig( vespalib::ComponentConfigProducer::Config("fdispatch.nodemanager", _fetcher->getGeneration(), "will not update generation unless config has changed")); } class AdminBadEngines { std::set<vespalib::string> _bad; public: void addAdminBad(const vespalib::string &name) { _bad.insert(name); } bool isAdminBad(const vespalib::string &name) const { return _bad.find(name) != _bad.end(); } }; class CollectAdminBadEngines { AdminBadEngines &_adminBadEngines; public: CollectAdminBadEngines(AdminBadEngines &adminBadEngines) : _adminBadEngines(adminBadEngines) { } void operator()(FastS_EngineBase* engine) { if (engine->isAdminBad()) { _adminBadEngines.addAdminBad(engine->GetName()); } } }; class PropagateAdminBadEngines { const AdminBadEngines &_adminBadEngines; public: PropagateAdminBadEngines(const AdminBadEngines &adminBadEngines) : _adminBadEngines(adminBadEngines) { } void operator()(FastS_EngineBase* engine) { if (_adminBadEngines.isAdminBad(engine->GetName())) { engine->MarkBad(FastS_EngineBase::BAD_ADMIN); } } }; FastS_NodeManager::FastS_NodeManager(vespalib::SimpleComponentConfigProducer &componentConfig, FastS_AppContext *appCtx, uint32_t partition) : _componentConfig(componentConfig), _managerLock(), _configLock(), _appCtx(appCtx), _mldPartit(partition), _mldDocStamp(0), _mldDocStampMin(0), _gencnt(0), _queryPerf(), _fetcher(), _configUri(config::ConfigUri::createEmpty()), _lastPartMap(NULL), _datasetCollection(NULL), _oldDSCList(NULL), _tempFail(false), _failed(false), _hasDsc(false), _checkTempFailScheduled(false), _shutdown(false) { _datasetCollection = new FastS_DataSetCollection(_appCtx); FastS_assert(_datasetCollection != NULL); _datasetCollection->Configure(NULL, 0); FastOS_Time now; now.SetNow(); _mldDocStamp = now.GetSeconds(); _mldDocStampMin = _mldDocStamp; } FastS_NodeManager::~FastS_NodeManager() { free(_lastPartMap); FastS_assert(_datasetCollection != NULL); _datasetCollection->subRef(); } void FastS_NodeManager::CheckTempFail() { bool tempfail; _checkTempFailScheduled = false; tempfail = false; { std::lock_guard<std::mutex> mangerGuard(_managerLock); FastS_DataSetCollection *dsc = PeekDataSetCollection(); for (unsigned int i = 0; i < dsc->GetMaxNumDataSets(); i++) { FastS_DataSetBase *ds; FastS_PlainDataSet *ds_plain; if ((ds = dsc->PeekDataSet(i)) != NULL && (ds_plain = ds->GetPlainDataSet()) != NULL && ds_plain->GetTempFail()) { tempfail = true; break; } } } _tempFail = tempfail; } void FastS_NodeManager::SubscribePartMap(const config::ConfigUri & configUri) { vespalib::string configId(configUri.getConfigId()); LOG(debug, "loading new datasetcollection from %s", configId.c_str()); try { _configUri = configUri; _fetcher.reset(new config::ConfigFetcher(_configUri.getContext())); _fetcher->subscribe<PartitionsConfig>(configId, this); _fetcher->start(); if (_gencnt == 0) { throw new config::InvalidConfigException("failure during initial configuration: bad partition map"); } } catch (std::exception &ex) { LOG(error, "Runtime exception: %s", (const char *) ex.what()); EV_STOPPING("", "bad partitions config"); exit(1); } } uint32_t FastS_NodeManager::SetPartMap(const PartitionsConfig& partmap, unsigned int waitms) { std::lock_guard<std::mutex> configGuard(_configLock); FastS_DataSetCollDesc *configDesc = new FastS_DataSetCollDesc(); if (!configDesc->ReadConfig(partmap)) { LOG(error, "NodeManager::SetPartMap: Failed to load configuration"); delete configDesc; return 0; } int retval = SetCollDesc(configDesc, waitms); return retval; } uint32_t FastS_NodeManager::SetCollDesc(FastS_DataSetCollDesc *configDesc, unsigned int waitms) { FastS_DataSetCollection *newCollection; uint32_t gencnt; if (_shutdown) return 0; AdminBadEngines adminBad; { CollectAdminBadEngines adminBadCollect(adminBad); FastS_DataSetCollection *dsc = GetDataSetCollection(); for (uint32_t i = 0; i < dsc->GetMaxNumDataSets(); i++) { FastS_DataSetBase *ds; FastS_PlainDataSet *ds_plain; if ((ds = dsc->PeekDataSet(i)) == NULL || (ds_plain = ds->GetPlainDataSet()) == NULL) continue; ds_plain->ForEachEngine(adminBadCollect); } dsc->subRef(); } newCollection = new FastS_DataSetCollection(_appCtx); if (!newCollection->Configure(configDesc, _gencnt + 1)) { LOG(error, "NodeManager::SetPartMap: Inconsistent configuration"); newCollection->subRef(); return 0; } { PropagateAdminBadEngines adminBadPropagate(adminBad); for (uint32_t i = 0; i < newCollection->GetMaxNumDataSets(); i++) { FastS_DataSetBase *ds; FastS_PlainDataSet *ds_plain; if ((ds = newCollection->PeekDataSet(i)) == NULL || (ds_plain = ds->GetPlainDataSet()) == NULL) continue; ds_plain->ForEachEngine(adminBadPropagate); } } if (waitms > 0) { FastOS_Time last; unsigned int rwait; bool allup; last.SetNow(); while (1) { allup = newCollection->AreEnginesReady(); rwait = (unsigned int) last.MilliSecsToNow(); if (rwait >= waitms || allup) break; FastOS_Thread::Sleep(100); }; if (allup) { LOG(debug, "All new engines up after %d ms", rwait); } else { LOG(debug, "Some new engines still down after %d ms", rwait); } } gencnt = SetDataSetCollection(newCollection); ScheduleCheckTempFail(FastS_NoID32()); return gencnt; } /** * When calling this method, a single reference on the 'dsc' parameter * is passed to the monitor object. * * @return generation count, or 0 on fail. * @param dsc new dataset collection. A single reference is passed * to the monitor when this method is invoked. **/ uint32_t FastS_NodeManager::SetDataSetCollection(FastS_DataSetCollection *dsc) { if (dsc == NULL) return 0; uint32_t gencnt = 0; FastS_DataSetCollection *old_dsc = NULL; if (!dsc->IsValid()) { LOG(error, "NodeManager::SetDataSetCollection: Inconsistent configuration"); dsc->subRef(); } else { { std::lock_guard<std::mutex> managerGuard(_managerLock); _gencnt++; gencnt = _gencnt; old_dsc = _datasetCollection; _datasetCollection = dsc; // put old config on service list FastS_assert(old_dsc != NULL); if (!old_dsc->IsLastRef()) { old_dsc->_nextOld = _oldDSCList; _oldDSCList = old_dsc; old_dsc = NULL; } _hasDsc = true; } if (old_dsc != NULL) old_dsc->subRef(); } return gencnt; } FastS_DataSetCollection * FastS_NodeManager::GetDataSetCollection() { FastS_DataSetCollection *ret; std::lock_guard<std::mutex> managerGuard(_managerLock); ret = _datasetCollection; FastS_assert(ret != NULL); ret->addRef(); return ret; } void FastS_NodeManager::ShutdownConfig() { FastS_DataSetCollection *dsc; FastS_DataSetCollection *old_dsc; { std::lock_guard<std::mutex> configGuard(_configLock); std::lock_guard<std::mutex> managerGuard(_managerLock); _shutdown = true; // disallow SetPartMap dsc = _datasetCollection; _datasetCollection = new FastS_DataSetCollection(_appCtx); _datasetCollection->Configure(NULL, 0); old_dsc = _oldDSCList; _oldDSCList = NULL; } dsc->AbortQueryQueues(); dsc->subRef(); while (old_dsc != NULL) { dsc = old_dsc; old_dsc = old_dsc->_nextOld; dsc->_nextOld = NULL; dsc->AbortQueryQueues(); dsc->subRef(); } } uint32_t FastS_NodeManager::GetTotalPartitions() { uint32_t ret; ret = 0; std::lock_guard<std::mutex> managerGuard(_managerLock); FastS_DataSetCollection *dsc = PeekDataSetCollection(); for (unsigned int i = 0; i < dsc->GetMaxNumDataSets(); i++) { FastS_DataSetBase *ds; FastS_PlainDataSet *ds_plain; if ((ds = dsc->PeekDataSet(i)) != NULL && (ds_plain = ds->GetPlainDataSet()) != NULL) ret += ds_plain->GetPartitions(); } return ret; } ChildInfo FastS_NodeManager::getChildInfo() { ChildInfo r; r.activeDocs.valid = true; FastS_DataSetCollection *dsc = GetDataSetCollection(); for (unsigned int i = 0; i < dsc->GetMaxNumDataSets(); i++) { FastS_DataSetBase *ds; FastS_PlainDataSet *ds_plain; if ((ds = dsc->PeekDataSet(i)) == NULL || (ds_plain = ds->GetPlainDataSet()) == NULL) continue; r.maxNodes += ds_plain->_partMap._childmaxnodesSinceReload; r.activeNodes += ds_plain->_partMap._childnodes; r.maxParts += ds_plain->_partMap._childmaxpartsSinceReload; r.activeParts += ds_plain->_partMap._childparts; PossCount rowActive = ds_plain->getActiveDocs(); if (rowActive.valid) { r.activeDocs.count += rowActive.count; } else { r.activeDocs.valid = false; } } dsc->subRef(); return r; } void FastS_NodeManager::logPerformance(vespalib::Executor &executor) { _queryPerf.reset(); FastS_DataSetCollection *dsc = GetDataSetCollection(); for (unsigned int i = 0; i < dsc->GetMaxNumDataSets(); i++) { if (dsc->PeekDataSet(i) != NULL) { dsc->PeekDataSet(i)->addPerformance(_queryPerf); } } dsc->subRef(); executor.execute(_queryPerf.make_log_task()); } void FastS_NodeManager::CheckEvents(FastS_TimeKeeper *timeKeeper) { // CHECK SCHEDULED OPERATIONS if (_checkTempFailScheduled) CheckTempFail(); // CHECK QUERY QUEUES FastS_DataSetCollection *dsc = GetDataSetCollection(); dsc->CheckQueryQueues(timeKeeper); dsc->subRef(); // check old query queues and discard old configs FastS_DataSetCollection *old_dsc; FastS_DataSetCollection *prev = NULL; FastS_DataSetCollection *tmp; { std::lock_guard<std::mutex> managerGuard(_managerLock); old_dsc = _oldDSCList; } while (old_dsc != NULL) { if (old_dsc->IsLastRef()) { if (prev == NULL) { std::unique_lock<std::mutex> managerGuard(_managerLock); if (_oldDSCList == old_dsc) { _oldDSCList = old_dsc->_nextOld; } else { prev = _oldDSCList; managerGuard.unlock(); while (prev->_nextOld != old_dsc) prev = prev->_nextOld; prev->_nextOld = old_dsc->_nextOld; } } else { prev->_nextOld = old_dsc->_nextOld; } tmp = old_dsc; old_dsc = old_dsc->_nextOld; tmp->subRef(); } else { old_dsc->CheckQueryQueues(timeKeeper); prev = old_dsc; old_dsc = old_dsc->_nextOld; } } } uint32_t FastS_NodeManager::GetMldDocstamp() { if (!_hasDsc) return 0; return _mldDocStamp; } <commit_msg>Increase timeout waiting for engines to be up when switching to new data set collection.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "nodemanager.h" #include "datasetcollection.h" #include "plain_dataset.h" #include "engine_base.h" #include <vespa/config/common/exceptions.h> #include <set> #include <vespa/log/log.h> LOG_SETUP(".search.nodemanager"); void FastS_NodeManager::configure(std::unique_ptr<PartitionsConfig> cfg) { LOG(config, "configuring datasetcollection from '%s'", _configUri.getConfigId().c_str()); SetPartMap(*cfg, 20000); _componentConfig.addConfig( vespalib::ComponentConfigProducer::Config("fdispatch.nodemanager", _fetcher->getGeneration(), "will not update generation unless config has changed")); } class AdminBadEngines { std::set<vespalib::string> _bad; public: void addAdminBad(const vespalib::string &name) { _bad.insert(name); } bool isAdminBad(const vespalib::string &name) const { return _bad.find(name) != _bad.end(); } }; class CollectAdminBadEngines { AdminBadEngines &_adminBadEngines; public: CollectAdminBadEngines(AdminBadEngines &adminBadEngines) : _adminBadEngines(adminBadEngines) { } void operator()(FastS_EngineBase* engine) { if (engine->isAdminBad()) { _adminBadEngines.addAdminBad(engine->GetName()); } } }; class PropagateAdminBadEngines { const AdminBadEngines &_adminBadEngines; public: PropagateAdminBadEngines(const AdminBadEngines &adminBadEngines) : _adminBadEngines(adminBadEngines) { } void operator()(FastS_EngineBase* engine) { if (_adminBadEngines.isAdminBad(engine->GetName())) { engine->MarkBad(FastS_EngineBase::BAD_ADMIN); } } }; FastS_NodeManager::FastS_NodeManager(vespalib::SimpleComponentConfigProducer &componentConfig, FastS_AppContext *appCtx, uint32_t partition) : _componentConfig(componentConfig), _managerLock(), _configLock(), _appCtx(appCtx), _mldPartit(partition), _mldDocStamp(0), _mldDocStampMin(0), _gencnt(0), _queryPerf(), _fetcher(), _configUri(config::ConfigUri::createEmpty()), _lastPartMap(NULL), _datasetCollection(NULL), _oldDSCList(NULL), _tempFail(false), _failed(false), _hasDsc(false), _checkTempFailScheduled(false), _shutdown(false) { _datasetCollection = new FastS_DataSetCollection(_appCtx); FastS_assert(_datasetCollection != NULL); _datasetCollection->Configure(NULL, 0); FastOS_Time now; now.SetNow(); _mldDocStamp = now.GetSeconds(); _mldDocStampMin = _mldDocStamp; } FastS_NodeManager::~FastS_NodeManager() { free(_lastPartMap); FastS_assert(_datasetCollection != NULL); _datasetCollection->subRef(); } void FastS_NodeManager::CheckTempFail() { bool tempfail; _checkTempFailScheduled = false; tempfail = false; { std::lock_guard<std::mutex> mangerGuard(_managerLock); FastS_DataSetCollection *dsc = PeekDataSetCollection(); for (unsigned int i = 0; i < dsc->GetMaxNumDataSets(); i++) { FastS_DataSetBase *ds; FastS_PlainDataSet *ds_plain; if ((ds = dsc->PeekDataSet(i)) != NULL && (ds_plain = ds->GetPlainDataSet()) != NULL && ds_plain->GetTempFail()) { tempfail = true; break; } } } _tempFail = tempfail; } void FastS_NodeManager::SubscribePartMap(const config::ConfigUri & configUri) { vespalib::string configId(configUri.getConfigId()); LOG(debug, "loading new datasetcollection from %s", configId.c_str()); try { _configUri = configUri; _fetcher.reset(new config::ConfigFetcher(_configUri.getContext())); _fetcher->subscribe<PartitionsConfig>(configId, this); _fetcher->start(); if (_gencnt == 0) { throw new config::InvalidConfigException("failure during initial configuration: bad partition map"); } } catch (std::exception &ex) { LOG(error, "Runtime exception: %s", (const char *) ex.what()); EV_STOPPING("", "bad partitions config"); exit(1); } } uint32_t FastS_NodeManager::SetPartMap(const PartitionsConfig& partmap, unsigned int waitms) { std::lock_guard<std::mutex> configGuard(_configLock); FastS_DataSetCollDesc *configDesc = new FastS_DataSetCollDesc(); if (!configDesc->ReadConfig(partmap)) { LOG(error, "NodeManager::SetPartMap: Failed to load configuration"); delete configDesc; return 0; } int retval = SetCollDesc(configDesc, waitms); return retval; } uint32_t FastS_NodeManager::SetCollDesc(FastS_DataSetCollDesc *configDesc, unsigned int waitms) { FastS_DataSetCollection *newCollection; uint32_t gencnt; if (_shutdown) return 0; AdminBadEngines adminBad; { CollectAdminBadEngines adminBadCollect(adminBad); FastS_DataSetCollection *dsc = GetDataSetCollection(); for (uint32_t i = 0; i < dsc->GetMaxNumDataSets(); i++) { FastS_DataSetBase *ds; FastS_PlainDataSet *ds_plain; if ((ds = dsc->PeekDataSet(i)) == NULL || (ds_plain = ds->GetPlainDataSet()) == NULL) continue; ds_plain->ForEachEngine(adminBadCollect); } dsc->subRef(); } newCollection = new FastS_DataSetCollection(_appCtx); if (!newCollection->Configure(configDesc, _gencnt + 1)) { LOG(error, "NodeManager::SetPartMap: Inconsistent configuration"); newCollection->subRef(); return 0; } { PropagateAdminBadEngines adminBadPropagate(adminBad); for (uint32_t i = 0; i < newCollection->GetMaxNumDataSets(); i++) { FastS_DataSetBase *ds; FastS_PlainDataSet *ds_plain; if ((ds = newCollection->PeekDataSet(i)) == NULL || (ds_plain = ds->GetPlainDataSet()) == NULL) continue; ds_plain->ForEachEngine(adminBadPropagate); } } if (waitms > 0) { FastOS_Time last; unsigned int rwait; bool allup; last.SetNow(); while (1) { allup = newCollection->AreEnginesReady(); rwait = (unsigned int) last.MilliSecsToNow(); if (rwait >= waitms || allup) break; FastOS_Thread::Sleep(100); }; if (allup) { LOG(debug, "All new engines up after %d ms", rwait); } else { LOG(debug, "Some new engines still down after %d ms", rwait); } } gencnt = SetDataSetCollection(newCollection); ScheduleCheckTempFail(FastS_NoID32()); return gencnt; } /** * When calling this method, a single reference on the 'dsc' parameter * is passed to the monitor object. * * @return generation count, or 0 on fail. * @param dsc new dataset collection. A single reference is passed * to the monitor when this method is invoked. **/ uint32_t FastS_NodeManager::SetDataSetCollection(FastS_DataSetCollection *dsc) { if (dsc == NULL) return 0; uint32_t gencnt = 0; FastS_DataSetCollection *old_dsc = NULL; if (!dsc->IsValid()) { LOG(error, "NodeManager::SetDataSetCollection: Inconsistent configuration"); dsc->subRef(); } else { { std::lock_guard<std::mutex> managerGuard(_managerLock); _gencnt++; gencnt = _gencnt; old_dsc = _datasetCollection; _datasetCollection = dsc; // put old config on service list FastS_assert(old_dsc != NULL); if (!old_dsc->IsLastRef()) { old_dsc->_nextOld = _oldDSCList; _oldDSCList = old_dsc; old_dsc = NULL; } _hasDsc = true; } if (old_dsc != NULL) old_dsc->subRef(); } return gencnt; } FastS_DataSetCollection * FastS_NodeManager::GetDataSetCollection() { FastS_DataSetCollection *ret; std::lock_guard<std::mutex> managerGuard(_managerLock); ret = _datasetCollection; FastS_assert(ret != NULL); ret->addRef(); return ret; } void FastS_NodeManager::ShutdownConfig() { FastS_DataSetCollection *dsc; FastS_DataSetCollection *old_dsc; { std::lock_guard<std::mutex> configGuard(_configLock); std::lock_guard<std::mutex> managerGuard(_managerLock); _shutdown = true; // disallow SetPartMap dsc = _datasetCollection; _datasetCollection = new FastS_DataSetCollection(_appCtx); _datasetCollection->Configure(NULL, 0); old_dsc = _oldDSCList; _oldDSCList = NULL; } dsc->AbortQueryQueues(); dsc->subRef(); while (old_dsc != NULL) { dsc = old_dsc; old_dsc = old_dsc->_nextOld; dsc->_nextOld = NULL; dsc->AbortQueryQueues(); dsc->subRef(); } } uint32_t FastS_NodeManager::GetTotalPartitions() { uint32_t ret; ret = 0; std::lock_guard<std::mutex> managerGuard(_managerLock); FastS_DataSetCollection *dsc = PeekDataSetCollection(); for (unsigned int i = 0; i < dsc->GetMaxNumDataSets(); i++) { FastS_DataSetBase *ds; FastS_PlainDataSet *ds_plain; if ((ds = dsc->PeekDataSet(i)) != NULL && (ds_plain = ds->GetPlainDataSet()) != NULL) ret += ds_plain->GetPartitions(); } return ret; } ChildInfo FastS_NodeManager::getChildInfo() { ChildInfo r; r.activeDocs.valid = true; FastS_DataSetCollection *dsc = GetDataSetCollection(); for (unsigned int i = 0; i < dsc->GetMaxNumDataSets(); i++) { FastS_DataSetBase *ds; FastS_PlainDataSet *ds_plain; if ((ds = dsc->PeekDataSet(i)) == NULL || (ds_plain = ds->GetPlainDataSet()) == NULL) continue; r.maxNodes += ds_plain->_partMap._childmaxnodesSinceReload; r.activeNodes += ds_plain->_partMap._childnodes; r.maxParts += ds_plain->_partMap._childmaxpartsSinceReload; r.activeParts += ds_plain->_partMap._childparts; PossCount rowActive = ds_plain->getActiveDocs(); if (rowActive.valid) { r.activeDocs.count += rowActive.count; } else { r.activeDocs.valid = false; } } dsc->subRef(); return r; } void FastS_NodeManager::logPerformance(vespalib::Executor &executor) { _queryPerf.reset(); FastS_DataSetCollection *dsc = GetDataSetCollection(); for (unsigned int i = 0; i < dsc->GetMaxNumDataSets(); i++) { if (dsc->PeekDataSet(i) != NULL) { dsc->PeekDataSet(i)->addPerformance(_queryPerf); } } dsc->subRef(); executor.execute(_queryPerf.make_log_task()); } void FastS_NodeManager::CheckEvents(FastS_TimeKeeper *timeKeeper) { // CHECK SCHEDULED OPERATIONS if (_checkTempFailScheduled) CheckTempFail(); // CHECK QUERY QUEUES FastS_DataSetCollection *dsc = GetDataSetCollection(); dsc->CheckQueryQueues(timeKeeper); dsc->subRef(); // check old query queues and discard old configs FastS_DataSetCollection *old_dsc; FastS_DataSetCollection *prev = NULL; FastS_DataSetCollection *tmp; { std::lock_guard<std::mutex> managerGuard(_managerLock); old_dsc = _oldDSCList; } while (old_dsc != NULL) { if (old_dsc->IsLastRef()) { if (prev == NULL) { std::unique_lock<std::mutex> managerGuard(_managerLock); if (_oldDSCList == old_dsc) { _oldDSCList = old_dsc->_nextOld; } else { prev = _oldDSCList; managerGuard.unlock(); while (prev->_nextOld != old_dsc) prev = prev->_nextOld; prev->_nextOld = old_dsc->_nextOld; } } else { prev->_nextOld = old_dsc->_nextOld; } tmp = old_dsc; old_dsc = old_dsc->_nextOld; tmp->subRef(); } else { old_dsc->CheckQueryQueues(timeKeeper); prev = old_dsc; old_dsc = old_dsc->_nextOld; } } } uint32_t FastS_NodeManager::GetMldDocstamp() { if (!_hasDsc) return 0; return _mldDocStamp; } <|endoftext|>
<commit_before>//============================================================================ // Name : Shader.cpp // Author : Duarte Peixinho // Version : // Copyright : ;) // Description : Shader //============================================================================ #include <Pyros3D/Materials/Shaders/Shaders.h> #include <stdlib.h> #include <Pyros3D/Other/PyrosGL.h> namespace p3d { Shader::Shader() { vertexID = fragmentID = geometryID = shaderProgram = currentMaterials = 0; } Shader::~Shader() {} std::string Shader::LoadFileSource(const char *filename) { std::string shaderSource; std::ifstream t(filename); std::string str; if (t.fail()) { echo("ERROR: Shader File does not exist or you don't have permission to open it."); return std::string("\n\n/*\n * INCLUDE ERROR\n * COULDN'T INCLUDE FILE ")+filename+std::string("\n *\n */\n\n"); } std::string line; std::string pragma_include_ppc("#pragma include"); std::string include_ppc("#include"); while (std::getline(t, line)) { std::istringstream iss(line); size_t foundInclude = line.find(pragma_include_ppc); uint32 includeSentenceSize = pragma_include_ppc.size(); if (foundInclude == std::string::npos) { foundInclude = line.find(include_ppc); includeSentenceSize = include_ppc.size(); } if (foundInclude != std::string::npos) { std::string fileToInclude = line.substr(includeSentenceSize+1, line.size()); int initPos = fileToInclude.find_first_of("\""); int finalPos = fileToInclude.find_last_of("\""); std::string filePath = fileToInclude.substr(initPos+1, finalPos-1); shaderSource+=LoadFileSource(filePath.c_str()); std::getline(t, line); } shaderSource+=line; shaderSource+="\n"; } return shaderSource; } void Shader::LoadShaderFile(const char* filename) { shaderString = LoadFileSource(filename); } void Shader::LoadShaderText(const std::string &text) { shaderString = text; } bool Shader::CompileShader(const uint32 type, std::string definitions, std::string *output) { std::string LOG; std::string shaderType; uint32 shader; switch (type) { case ShaderType::VertexShader: vertexID = shader = glCreateShader(GL_VERTEX_SHADER); shaderType = "Vertex Shader"; break; case ShaderType::FragmentShader: fragmentID = shader = glCreateShader(GL_FRAGMENT_SHADER); shaderType = "Fragment Shader"; break; case ShaderType::GeometryShader: //geometryID = shader = glCreateShader(GL_GEOMETRY_SHADER); shaderType = "Geometry Shader"; break; } std::string finalShaderString = (std::string(definitions) + std::string(" ") + shaderString); uint32 len = finalShaderString.length(); // batatas because is a good example :P const char *batatas = finalShaderString.c_str(); GLCHECKER(glShaderSource(shader, 1, (const GLchar**)&batatas, (const GLint *)&len)); GLCHECKER(glCompileShader(shader)); GLint result, length = 0; GLCHECKER(glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length)); if (length > 1) { char* log = (char*)malloc(length); GLCHECKER(glGetShaderInfoLog(shader, length, &result, log)); GLCHECKER(glGetShaderiv(shader, GL_COMPILE_STATUS, &result)); LOG = std::string(log); echo(std::string(shaderType.c_str() + std::string((result == GL_FALSE ? " COMPILATION ERROR:" + LOG : ": " + LOG)))); if (output != NULL) *output = LOG; if (result == GL_FALSE) return false; } if (shaderProgram == 0) shaderProgram = (uint32)glCreateProgram(); // Attach shader GLCHECKER(glAttachShader(shaderProgram, shader)); return true; } bool Shader::LinkProgram(std::string *output) const { // Link Program GLCHECKER(glLinkProgram(shaderProgram)); GLint result, length = 0; std::string LOG; // Get Linkage error GLCHECKER(glGetProgramiv(shaderProgram, GL_LINK_STATUS, &result)); if (result == GL_FALSE) { GLCHECKER(glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH, &length)); char* log = (char*)malloc(length); GLCHECKER(glGetProgramInfoLog(shaderProgram, length, &result, log)); LOG = std::string(log); echo(std::string(std::string("SHADER PROGRAM LINK ERROR: ") + LOG)); if (output != NULL) *output = LOG; free(log); return false; } return true; } const uint32 &Shader::ShaderProgram() const { return shaderProgram; } void Shader::DeleteShader() { if (glIsProgram(shaderProgram)) { if (glIsShader(vertexID)) { GLCHECKER(glDetachShader(shaderProgram, vertexID)); GLCHECKER(glDeleteShader(vertexID)); // std::cout << "Shader Destroyed: " << shader << std::endl; } if (glIsShader(fragmentID)) { GLCHECKER(glDetachShader(shaderProgram, fragmentID)); GLCHECKER(glDeleteShader(fragmentID)); // std::cout << "Shader Destroyed: " << shader << std::endl; } //if (glIsShader(geometryID)) { // glDetachShader(shaderProgram, geometryID); // glDeleteShader(geometryID); // // std::cout << "Shader Destroyed: " << shader << std::endl; // } // else std::cout << "Shader Not Found: " << shader << std::endl; } // else std::cout << "Shader Program Object Not Found: " << shaderProgram << std::endl; if (glIsProgram(shaderProgram)) { GLCHECKER(glDeleteProgram(shaderProgram)); // std::cout << "Shader Program Destroyed: " << *shaderProgram << std::endl; shaderProgram = 0; } // else std::cout << "Shader Program Object Not Found: " << *shaderProgram << std::endl; } // Get positions const int32 Shader::GetUniformLocation(const uint32 program, const std::string &name) { return glGetUniformLocation(program, name.c_str()); } const int32 Shader::GetAttributeLocation(const uint32 program, const std::string &name) { return glGetAttribLocation(program, name.c_str()); } void Shader::SendUniform(const Uniform &uniform, const int32 Handle) { if (Handle > -1 && uniform.ElementCount > 0) switch (uniform.Type) { case Uniforms::DataType::Int: { GLCHECKER(glUniform1iv(Handle, uniform.ElementCount, (GLint*)&uniform.Value[0])); break; } case Uniforms::DataType::Float: { GLCHECKER(glUniform1fv(Handle, uniform.ElementCount, (f32*)&uniform.Value[0])); break; } case Uniforms::DataType::Vec2: { GLCHECKER(glUniform2fv(Handle, uniform.ElementCount, (f32*)&uniform.Value[0])); break; } case Uniforms::DataType::Vec3: { GLCHECKER(glUniform3fv(Handle, uniform.ElementCount, (f32*)&uniform.Value[0])); break; } case Uniforms::DataType::Vec4: { GLCHECKER(glUniform4fv(Handle, uniform.ElementCount, (f32*)&uniform.Value[0])); break; } case Uniforms::DataType::Matrix: { GLCHECKER(glUniformMatrix4fv(Handle, uniform.ElementCount, false, (f32*)&uniform.Value[0])); break; } } } void Shader::SendUniform(const Uniform &uniform, void* data, const int32 Handle, const uint32 elementCount) { if (Handle > -1 && elementCount > 0) { switch (uniform.Type) { case Uniforms::DataType::Int: { GLCHECKER(glUniform1iv(Handle, elementCount, (GLint*)((int32*)data))); break; } case Uniforms::DataType::Float: { GLCHECKER(glUniform1fv(Handle, elementCount, (f32*)data)); break; } case Uniforms::DataType::Vec2: { GLCHECKER(glUniform2fv(Handle, elementCount, (f32*)data)); break; } case Uniforms::DataType::Vec3: { GLCHECKER(glUniform3fv(Handle, elementCount, (f32*)data)); break; } case Uniforms::DataType::Vec4: { GLCHECKER(glUniform4fv(Handle, elementCount, (f32*)data)); break; } case Uniforms::DataType::Matrix: { GLCHECKER(glUniformMatrix4fv(Handle, elementCount, false, (f32*)data)); break; } } } } } <commit_msg>Added support for " and ' on glsl #includes<commit_after>//============================================================================ // Name : Shader.cpp // Author : Duarte Peixinho // Version : // Copyright : ;) // Description : Shader //============================================================================ #include <Pyros3D/Materials/Shaders/Shaders.h> #include <stdlib.h> #include <Pyros3D/Other/PyrosGL.h> namespace p3d { Shader::Shader() { vertexID = fragmentID = geometryID = shaderProgram = currentMaterials = 0; } Shader::~Shader() {} std::string Shader::LoadFileSource(const char *filename) { std::string shaderSource; std::ifstream t(filename); std::string str; if (t.fail()) { echo("ERROR: Shader File does not exist or you don't have permission to open it."); return std::string("\n\n/*\n * SHADER ERROR\n * COULDN'T OPEN/INCLUDE FILE ")+filename+std::string("\n *\n */\n\n"); } std::string line; std::string pragma_include_ppc("#pragma include"); std::string include_ppc("#include"); while (std::getline(t, line)) { std::istringstream iss(line); size_t foundInclude = line.find(pragma_include_ppc); uint32 includeSentenceSize = pragma_include_ppc.size(); if (foundInclude == std::string::npos) { foundInclude = line.find(include_ppc); includeSentenceSize = include_ppc.size(); } if (foundInclude != std::string::npos) { if (line.find_first_of("'")!=std::string::npos) { std::string fileToInclude = line.substr(line.find_first_of("'")+1, line.find_last_of("'")-(line.find_first_of("'")+1)); shaderSource+=LoadFileSource(fileToInclude.c_str()); continue; } if (line.find_first_of("\"")!=std::string::npos) { std::string fileToInclude = line.substr(line.find_first_of("\"")+1, line.find_last_of("\"")-(line.find_first_of("\"")+1)); shaderSource+=LoadFileSource(fileToInclude.c_str()); continue; } } shaderSource+=line; shaderSource+="\n"; } return shaderSource; } void Shader::LoadShaderFile(const char* filename) { shaderString = LoadFileSource(filename); } void Shader::LoadShaderText(const std::string &text) { shaderString = text; } bool Shader::CompileShader(const uint32 type, std::string definitions, std::string *output) { std::string LOG; std::string shaderType; uint32 shader; switch (type) { case ShaderType::VertexShader: vertexID = shader = glCreateShader(GL_VERTEX_SHADER); shaderType = "Vertex Shader"; break; case ShaderType::FragmentShader: fragmentID = shader = glCreateShader(GL_FRAGMENT_SHADER); shaderType = "Fragment Shader"; break; case ShaderType::GeometryShader: //geometryID = shader = glCreateShader(GL_GEOMETRY_SHADER); shaderType = "Geometry Shader"; break; } std::string finalShaderString = (std::string(definitions) + std::string(" ") + shaderString); uint32 len = finalShaderString.length(); // batatas because is a good example :P const char *batatas = finalShaderString.c_str(); GLCHECKER(glShaderSource(shader, 1, (const GLchar**)&batatas, (const GLint *)&len)); GLCHECKER(glCompileShader(shader)); GLint result, length = 0; GLCHECKER(glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length)); if (length > 1) { char* log = (char*)malloc(length); GLCHECKER(glGetShaderInfoLog(shader, length, &result, log)); GLCHECKER(glGetShaderiv(shader, GL_COMPILE_STATUS, &result)); LOG = std::string(log); echo(std::string(shaderType.c_str() + std::string((result == GL_FALSE ? " COMPILATION ERROR:" + LOG : ": " + LOG)))); if (output != NULL) *output = LOG; if (result == GL_FALSE) return false; } if (shaderProgram == 0) shaderProgram = (uint32)glCreateProgram(); // Attach shader GLCHECKER(glAttachShader(shaderProgram, shader)); return true; } bool Shader::LinkProgram(std::string *output) const { // Link Program GLCHECKER(glLinkProgram(shaderProgram)); GLint result, length = 0; std::string LOG; // Get Linkage error GLCHECKER(glGetProgramiv(shaderProgram, GL_LINK_STATUS, &result)); if (result == GL_FALSE) { GLCHECKER(glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH, &length)); char* log = (char*)malloc(length); GLCHECKER(glGetProgramInfoLog(shaderProgram, length, &result, log)); LOG = std::string(log); echo(std::string(std::string("SHADER PROGRAM LINK ERROR: ") + LOG)); if (output != NULL) *output = LOG; free(log); return false; } return true; } const uint32 &Shader::ShaderProgram() const { return shaderProgram; } void Shader::DeleteShader() { if (glIsProgram(shaderProgram)) { if (glIsShader(vertexID)) { GLCHECKER(glDetachShader(shaderProgram, vertexID)); GLCHECKER(glDeleteShader(vertexID)); // std::cout << "Shader Destroyed: " << shader << std::endl; } if (glIsShader(fragmentID)) { GLCHECKER(glDetachShader(shaderProgram, fragmentID)); GLCHECKER(glDeleteShader(fragmentID)); // std::cout << "Shader Destroyed: " << shader << std::endl; } //if (glIsShader(geometryID)) { // glDetachShader(shaderProgram, geometryID); // glDeleteShader(geometryID); // // std::cout << "Shader Destroyed: " << shader << std::endl; // } // else std::cout << "Shader Not Found: " << shader << std::endl; } // else std::cout << "Shader Program Object Not Found: " << shaderProgram << std::endl; if (glIsProgram(shaderProgram)) { GLCHECKER(glDeleteProgram(shaderProgram)); // std::cout << "Shader Program Destroyed: " << *shaderProgram << std::endl; shaderProgram = 0; } // else std::cout << "Shader Program Object Not Found: " << *shaderProgram << std::endl; } // Get positions const int32 Shader::GetUniformLocation(const uint32 program, const std::string &name) { return glGetUniformLocation(program, name.c_str()); } const int32 Shader::GetAttributeLocation(const uint32 program, const std::string &name) { return glGetAttribLocation(program, name.c_str()); } void Shader::SendUniform(const Uniform &uniform, const int32 Handle) { if (Handle > -1 && uniform.ElementCount > 0) switch (uniform.Type) { case Uniforms::DataType::Int: { GLCHECKER(glUniform1iv(Handle, uniform.ElementCount, (GLint*)&uniform.Value[0])); break; } case Uniforms::DataType::Float: { GLCHECKER(glUniform1fv(Handle, uniform.ElementCount, (f32*)&uniform.Value[0])); break; } case Uniforms::DataType::Vec2: { GLCHECKER(glUniform2fv(Handle, uniform.ElementCount, (f32*)&uniform.Value[0])); break; } case Uniforms::DataType::Vec3: { GLCHECKER(glUniform3fv(Handle, uniform.ElementCount, (f32*)&uniform.Value[0])); break; } case Uniforms::DataType::Vec4: { GLCHECKER(glUniform4fv(Handle, uniform.ElementCount, (f32*)&uniform.Value[0])); break; } case Uniforms::DataType::Matrix: { GLCHECKER(glUniformMatrix4fv(Handle, uniform.ElementCount, false, (f32*)&uniform.Value[0])); break; } } } void Shader::SendUniform(const Uniform &uniform, void* data, const int32 Handle, const uint32 elementCount) { if (Handle > -1 && elementCount > 0) { switch (uniform.Type) { case Uniforms::DataType::Int: { GLCHECKER(glUniform1iv(Handle, elementCount, (GLint*)((int32*)data))); break; } case Uniforms::DataType::Float: { GLCHECKER(glUniform1fv(Handle, elementCount, (f32*)data)); break; } case Uniforms::DataType::Vec2: { GLCHECKER(glUniform2fv(Handle, elementCount, (f32*)data)); break; } case Uniforms::DataType::Vec3: { GLCHECKER(glUniform3fv(Handle, elementCount, (f32*)data)); break; } case Uniforms::DataType::Vec4: { GLCHECKER(glUniform4fv(Handle, elementCount, (f32*)data)); break; } case Uniforms::DataType::Matrix: { GLCHECKER(glUniformMatrix4fv(Handle, elementCount, false, (f32*)data)); break; } } } } } <|endoftext|>
<commit_before>/*************************************** ** Tsunagari Tile Engine ** ** bitrecord.cpp ** ** Copyright 2011-2014 Michael Reiley ** ** Copyright 2011-2016 Paul Merrill ** ***************************************/ // ********** // 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 "bitrecord.h" BitRecord::BitRecord(size_t length) : states(vector<char>(length)) {} char& BitRecord::operator[] (size_t idx) { return states[idx]; } vector<size_t> BitRecord::diff(const BitRecord& other) { vector<size_t> changes; for (size_t i = 0; i < states.size(); i++) { if (states[i] != other.states[i]) { changes.push_back(i); } } return changes; } <commit_msg>Bitrecord: Resize vector on construction<commit_after>/*************************************** ** Tsunagari Tile Engine ** ** bitrecord.cpp ** ** Copyright 2011-2014 Michael Reiley ** ** Copyright 2011-2016 Paul Merrill ** ***************************************/ // ********** // 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 "bitrecord.h" BitRecord::BitRecord(size_t length) { states.resize(length); } char& BitRecord::operator[] (size_t idx) { return states[idx]; } vector<size_t> BitRecord::diff(const BitRecord& other) { vector<size_t> changes; for (size_t i = 0; i < states.size(); i++) { if (states[i] != other.states[i]) { changes.push_back(i); } } return changes; } <|endoftext|>
<commit_before>#pragma once #include <boost/algorithm/string.hpp> #include "config.hpp" namespace blackhole { namespace formatter { namespace string { static const char VARIADIC_KEY_PREFIX[] = "..."; struct pattern_parser_t { static config_t parse(const std::string& input_pattern) { auto current = input_pattern.begin(); auto end = input_pattern.end(); std::string pattern; pattern.reserve(input_pattern.length()); std::vector<std::string> keys; while(current != end) { if (begin_key(current, end)) { current += 2; pattern.push_back('%'); std::string key; while (current != end) { if (end_key(current, end)) { break; } else { key.push_back(*current); } current++; } if (boost::starts_with(key, VARIADIC_KEY_PREFIX)) { handle_variadic_key(&key); } keys.push_back(key); } else { pattern.push_back(*current); } current++; } return { pattern, keys }; } private: static inline bool begin_key(std::string::const_iterator it, std::string::const_iterator end) { return (*it == '%') && (it + 1 != end) && (*(it + 1) == '('); } static inline bool end_key(std::string::const_iterator it, std::string::const_iterator end) { return (*it == ')') && (it + 1 != end) && (*(it + 1) == 's'); } static void handle_variadic_key(std::string* key) { for (auto it = key->begin() + 3; it != key->end(); ++it) { char ch = *it; switch (ch) { case 'L': *it = '0'; break; default: *it = '0'; } } } }; } // namespace string } // namespace formatter } // namespace blackhole <commit_msg>Once more pattern parsing refactoring.<commit_after>#pragma once #include <boost/algorithm/string.hpp> #include "config.hpp" namespace blackhole { namespace formatter { namespace string { static const char VARIADIC_KEY_PREFIX[] = "..."; struct pattern_parser_t { static config_t parse(const std::string& input_pattern) { auto current = input_pattern.begin(); auto end = input_pattern.end(); std::string pattern; pattern.reserve(input_pattern.length()); std::vector<std::string> keys; while(current != end) { if (begin_key(current, end)) { pattern.push_back('%'); keys.push_back(extract_key(current, end)); } else { pattern.push_back(*current); } current++; } return { pattern, keys }; } private: static inline bool begin_key(std::string::const_iterator it, std::string::const_iterator end) { return (*it == '%') && (it + 1 != end) && (*(it + 1) == '('); } static inline bool end_key(std::string::const_iterator it, std::string::const_iterator end) { return (*it == ')') && (it + 1 != end) && (*(it + 1) == 's'); } static inline std::string extract_key(std::string::const_iterator& it, std::string::const_iterator end) { it += 2; std::string key; while (it != end) { if (end_key(it, end)) { break; } else { key.push_back(*it); } it++; } if (boost::starts_with(key, VARIADIC_KEY_PREFIX)) { handle_variadic_key(&key); } return key; } static void handle_variadic_key(std::string* key) { for (auto it = key->begin() + 3; it != key->end(); ++it) { char ch = *it; switch (ch) { case 'L': *it = '0'; break; default: *it = '0'; } } } }; } // namespace string } // namespace formatter } // namespace blackhole <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 <algorithm> #include "compiler/rewriter/tools/udf_graph.h" #include "compiler/api/compiler_api.h" #include "compiler/api/compilercb.h" #include "compiler/expression/expr_base.h" #include "compiler/expression/fo_expr.h" #include "compiler/expression/function_item_expr.h" #include "compiler/expression/expr_iter.h" #include "compiler/rewriter/framework/rewriter_context.h" #include "compiler/rewriter/framework/rewriter.h" #include "functions/udf.h" #include "types/typeops.h" #include "zorbautils/indent.h" namespace zorba { /******************************************************************************* ********************************************************************************/ UDFGraph::UDFGraph(expr* e) : theExpr(e), theNodes(32, false), theRoot(NULL), theVisitId(0) { if (e != NULL) build(e); } /******************************************************************************* ********************************************************************************/ UDFGraph::~UDFGraph() { UDFMap::iterator ite = theNodes.begin(); UDFMap::iterator end = theNodes.end(); for (; ite != end; ++ite) { delete (*ite).second; } } /******************************************************************************* ********************************************************************************/ void UDFGraph::build(const expr* e) { user_function* dummy = NULL; theRoot = new UDFNode(NULL); theNodes.insert(dummy, theRoot); std::vector<user_function*> callChain; callChain.push_back(NULL); build(e, callChain); } /******************************************************************************* ********************************************************************************/ void UDFGraph::build(const expr* curExpr, std::vector<user_function*>& callChain) { expr_kind_t kind = curExpr->get_expr_kind(); if (kind == fo_expr_kind || kind == function_item_expr_kind) { user_function* udf = NULL; if (kind == fo_expr_kind) { const fo_expr* fo = static_cast<const fo_expr*>(curExpr); udf = dynamic_cast<user_function*>(fo->get_func()); } else { const function_item_expr* fi = static_cast<const function_item_expr*>(curExpr); udf = dynamic_cast<user_function*>(fi->get_function()); } if (udf != NULL) { if (std::find(callChain.begin(), callChain.end(), udf) == callChain.end()) { bool found = theNodes.find(udf); addEdge(callChain.back(), udf); callChain.push_back(udf); // If this is the first time we see the current udf, do a recursive // call on its body expr. if (!found && udf->getBody()) { build(udf->getBody(), callChain); } callChain.pop_back(); } } } ExprConstIterator iter(curExpr); while (!iter.done()) { build(iter.get_expr(), callChain); iter.next(); } } /******************************************************************************* ********************************************************************************/ void UDFGraph::addEdge(user_function* caller, user_function* callee) { UDFNode* callerNode = NULL; UDFNode* calleeNode = NULL; if (!theNodes.get(caller, callerNode)) { callerNode = new UDFNode(caller); theNodes.insert(caller, callerNode); } if (!theNodes.get(callee, calleeNode)) { calleeNode = new UDFNode(callee); theNodes.insert(callee, calleeNode); } callerNode->theChildren.push_back(calleeNode); calleeNode->theParents.push_back(callerNode); } /******************************************************************************* ********************************************************************************/ void UDFGraph::optimizeUDFs(CompilerCB* ccb) { optimizeUDFs(ccb, theRoot, ++theVisitId); } void UDFGraph::optimizeUDFs(CompilerCB* ccb, UDFNode* node, ulong visit) { if (node->theVisitId == visit) return; node->theVisitId = visit; for (ulong i = 0; i < node->theChildren.size(); ++i) { optimizeUDFs(ccb, node->theChildren[i], visit); } if (node == theRoot) return; user_function* udf = node->theUDF; expr_t body = udf->getBody(); while (true) { RewriterContext rctx(ccb, body); GENV_COMPILERSUBSYS.getDefaultOptimizingRewriter()->rewrite(rctx); body = rctx.getRoot(); #if 1 xqtref_t bodyType = body->get_return_type(); xqtref_t declaredType = udf->getSignature().return_type(); if ( !TypeOps::is_equal(*bodyType, *declaredType) && TypeOps::is_subtype(*bodyType, *declaredType)) { udf->getSignature().return_type() = bodyType; if (!udf->isLeaf()) continue; } #endif udf->setBody(body); udf->setOptimized(true); break; } if (ccb->theConfig.optimize_cb != NULL) { if (udf->getName()) { ccb->theConfig.optimize_cb(body, udf->getName()->getStringValue()->c_str()); } else { ccb->theConfig.optimize_cb(body, "inline function"); } } } /******************************************************************************* ********************************************************************************/ void UDFGraph::inferDeterminism() { inferDeterminism(theRoot, ++theVisitId); } bool UDFGraph::inferDeterminism(UDFNode* node, ulong visit) { if (node->theVisitId == visit) return node->theUDF->isDeterministic(); node->theVisitId = visit; bool deterministic = true; for (ulong i = 0; i < node->theChildren.size(); ++i) { if (inferDeterminism(node->theChildren[i], visit) == false) deterministic = false; } if (node != theRoot) { if (deterministic) { deterministic = !node->theUDF->getBody()->is_nondeterministic(); } node->theUDF->setDeterministic(deterministic); } return deterministic; } /******************************************************************************* ********************************************************************************/ void UDFGraph::display(std::ostream& o) { display(o, theRoot); o << std::endl << std::endl; } void UDFGraph::display(std::ostream& o, UDFNode* node) { if (node == theRoot) o << indent << "Root Node" << std::endl; else o << indent << node->theUDF->getName()->show() << std::endl; o << inc_indent; for (ulong i = 0; i < node->theChildren.size(); ++i) { display(o, node->theChildren[i]); } o << dec_indent; } } <commit_msg>Fix for SF bug #3013820 - eval_spec_ex_3 crashing when using plan serializer.<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 <algorithm> #include "compiler/rewriter/tools/udf_graph.h" #include "compiler/api/compiler_api.h" #include "compiler/api/compilercb.h" #include "compiler/expression/expr_base.h" #include "compiler/expression/fo_expr.h" #include "compiler/expression/function_item_expr.h" #include "compiler/expression/expr_iter.h" #include "compiler/rewriter/framework/rewriter_context.h" #include "compiler/rewriter/framework/rewriter.h" #include "functions/udf.h" #include "types/typeops.h" #include "zorbautils/indent.h" namespace zorba { /******************************************************************************* ********************************************************************************/ UDFGraph::UDFGraph(expr* e) : theExpr(e), theNodes(32, false), theRoot(NULL), theVisitId(0) { if (e != NULL) build(e); } /******************************************************************************* ********************************************************************************/ UDFGraph::~UDFGraph() { UDFMap::iterator ite = theNodes.begin(); UDFMap::iterator end = theNodes.end(); for (; ite != end; ++ite) { delete (*ite).second; } } /******************************************************************************* ********************************************************************************/ void UDFGraph::build(const expr* e) { user_function* dummy = NULL; theRoot = new UDFNode(NULL); theNodes.insert(dummy, theRoot); std::vector<user_function*> callChain; callChain.push_back(NULL); build(e, callChain); } /******************************************************************************* ********************************************************************************/ void UDFGraph::build(const expr* curExpr, std::vector<user_function*>& callChain) { expr_kind_t kind = curExpr->get_expr_kind(); if (kind == fo_expr_kind || kind == function_item_expr_kind) { user_function* udf = NULL; if (kind == fo_expr_kind) { const fo_expr* fo = static_cast<const fo_expr*>(curExpr); udf = dynamic_cast<user_function*>(fo->get_func()); } else { const function_item_expr* fi = static_cast<const function_item_expr*>(curExpr); udf = dynamic_cast<user_function*>(fi->get_function()); } if (udf != NULL) { if (std::find(callChain.begin(), callChain.end(), udf) == callChain.end()) { bool found = theNodes.find(udf); addEdge(callChain.back(), udf); callChain.push_back(udf); // If this is the first time we see the current udf, do a recursive // call on its body expr. if (!found && udf->getBody()) { build(udf->getBody(), callChain); } callChain.pop_back(); } } } ExprConstIterator iter(curExpr); while (!iter.done()) { build(iter.get_expr(), callChain); iter.next(); } } /******************************************************************************* ********************************************************************************/ void UDFGraph::addEdge(user_function* caller, user_function* callee) { UDFNode* callerNode = NULL; UDFNode* calleeNode = NULL; if (!theNodes.get(caller, callerNode)) { callerNode = new UDFNode(caller); theNodes.insert(caller, callerNode); } if (!theNodes.get(callee, calleeNode)) { calleeNode = new UDFNode(callee); theNodes.insert(callee, calleeNode); } callerNode->theChildren.push_back(calleeNode); calleeNode->theParents.push_back(callerNode); } /******************************************************************************* ********************************************************************************/ void UDFGraph::optimizeUDFs(CompilerCB* ccb) { optimizeUDFs(ccb, theRoot, ++theVisitId); } void UDFGraph::optimizeUDFs(CompilerCB* ccb, UDFNode* node, ulong visit) { if (node->theVisitId == visit) return; node->theVisitId = visit; for (ulong i = 0; i < node->theChildren.size(); ++i) { optimizeUDFs(ccb, node->theChildren[i], visit); } if (node == theRoot) return; user_function* udf = node->theUDF; expr_t body = udf->getBody(); while (body != NULL) // was while (true), the body can be NULL when using Plan Serialization { RewriterContext rctx(ccb, body); GENV_COMPILERSUBSYS.getDefaultOptimizingRewriter()->rewrite(rctx); body = rctx.getRoot(); #if 1 xqtref_t bodyType = body->get_return_type(); xqtref_t declaredType = udf->getSignature().return_type(); if ( !TypeOps::is_equal(*bodyType, *declaredType) && TypeOps::is_subtype(*bodyType, *declaredType)) { udf->getSignature().return_type() = bodyType; if (!udf->isLeaf()) continue; } #endif udf->setBody(body); udf->setOptimized(true); break; } if (ccb->theConfig.optimize_cb != NULL) { if (udf->getName()) { ccb->theConfig.optimize_cb(body, udf->getName()->getStringValue()->c_str()); } else { ccb->theConfig.optimize_cb(body, "inline function"); } } } /******************************************************************************* ********************************************************************************/ void UDFGraph::inferDeterminism() { inferDeterminism(theRoot, ++theVisitId); } bool UDFGraph::inferDeterminism(UDFNode* node, ulong visit) { if (node->theVisitId == visit) return node->theUDF->isDeterministic(); node->theVisitId = visit; bool deterministic = true; for (ulong i = 0; i < node->theChildren.size(); ++i) { if (inferDeterminism(node->theChildren[i], visit) == false) deterministic = false; } if (node != theRoot) { if (deterministic) { if (node->theUDF->getBody() != NULL) // Body can be NULL when using Plan Serialization. In this case nondeterministic is already computed deterministic = !node->theUDF->getBody()->is_nondeterministic(); else deterministic = node->theUDF->isDeterministic(); } node->theUDF->setDeterministic(deterministic); } return deterministic; } /******************************************************************************* ********************************************************************************/ void UDFGraph::display(std::ostream& o) { display(o, theRoot); o << std::endl << std::endl; } void UDFGraph::display(std::ostream& o, UDFNode* node) { if (node == theRoot) o << indent << "Root Node" << std::endl; else o << indent << node->theUDF->getName()->show() << std::endl; o << inc_indent; for (ulong i = 0; i < node->theChildren.size(); ++i) { display(o, node->theChildren[i]); } o << dec_indent; } } <|endoftext|>
<commit_before>// Copyright 2012 Google Inc. All Rights Reserved. #include "class_linker.h" #include "dex_verifier.h" #include "object.h" #include "object_utils.h" #include "runtime_support_llvm.h" #include "thread.h" #include <stdint.h> namespace art { //---------------------------------------------------------------------------- // Thread //---------------------------------------------------------------------------- Thread* art_get_current_thread_from_code() { return Thread::Current(); } void art_set_current_thread_from_code(void* thread_object_addr) { UNIMPLEMENTED(WARNING); } void art_lock_object_from_code(Object* object) { UNIMPLEMENTED(WARNING); } void art_unlock_object_from_code(Object* object) { UNIMPLEMENTED(WARNING); } void art_test_suspend_from_code() { UNIMPLEMENTED(WARNING); } void art_push_shadow_frame_from_code(void* new_shadow_frame) { Thread* thread = Thread::Current(); thread->PushSirt( static_cast<StackIndirectReferenceTable*>(new_shadow_frame) ); } void art_pop_shadow_frame_from_code() { Thread* thread = Thread::Current(); thread->PopSirt(); } //---------------------------------------------------------------------------- // Exception //---------------------------------------------------------------------------- static std::string MethodNameFromIndex(const Method* method, uint32_t ref, verifier::VerifyErrorRefType ref_type, bool access) { CHECK_EQ(static_cast<int>(ref_type), static_cast<int>(verifier::VERIFY_ERROR_REF_METHOD)); ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache()); const DexFile::MethodId& id = dex_file.GetMethodId(ref); std::string class_name( PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(id)) ); const char* method_name = dex_file.StringDataByIdx(id.name_idx_); if (!access) { return class_name + "." + method_name; } std::string result; result += "tried to access method "; result += class_name + "." + method_name + ":" + dex_file.CreateMethodSignature(id.proto_idx_, NULL); result += " from class "; result += PrettyDescriptor(method->GetDeclaringClass()); return result; } bool art_is_exception_pending_from_code() { return Thread::Current()->IsExceptionPending(); } void art_throw_div_zero_from_code() { Thread* thread = Thread::Current(); thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero"); } void art_throw_array_bounds_from_code(int32_t length, int32_t index) { Thread* thread = Thread::Current(); thread->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;", "length=%d; index=%d", length, index); } void art_throw_no_such_method_from_code(int32_t method_idx) { Thread* thread = Thread::Current(); // We need the calling method as context for the method_idx Frame frame = thread->GetTopOfStack(); frame.Next(); Method* method = frame.GetMethod(); thread->ThrowNewException("Ljava/lang/NoSuchMethodError;", MethodNameFromIndex(method, method_idx, verifier::VERIFY_ERROR_REF_METHOD, false).c_str()); } void art_throw_null_pointer_exception_from_code() { Thread* thread = Thread::Current(); thread->ThrowNewException("Ljava/lang/NullPointerException;", NULL); } void art_throw_stack_overflow_from_code(void*) { Thread* thread = Thread::Current(); thread->ThrowNewExceptionF("Ljava/lang/StackOverflowError;", "stack size %zdkb; default stack size: %zdkb", thread->GetStackSize() / KB, Runtime::Current()->GetDefaultStackSize() / KB); } void art_throw_exception_from_code(Object* exception) { Thread* thread = Thread::Current(); thread->SetException(static_cast<Throwable*>(exception)); } int32_t art_find_catch_block_from_code(Object* exception, int32_t dex_pc) { Class* exception_type = exception->GetClass(); Method* current_method = Thread::Current()->GetCurrentMethod(); MethodHelper mh(current_method); const DexFile::CodeItem* code_item = mh.GetCodeItem(); int iter_index = 0; // Iterate over the catch handlers associated with dex_pc for (CatchHandlerIterator it(*code_item, dex_pc); it.HasNext(); it.Next()) { uint16_t iter_type_idx = it.GetHandlerTypeIndex(); // Catch all case if (iter_type_idx == DexFile::kDexNoIndex16) { return iter_index; } // Does this catch exception type apply? Class* iter_exception_type = mh.GetDexCacheResolvedType(iter_type_idx); if (iter_exception_type == NULL) { // The verifier should take care of resolving all exception classes early LOG(WARNING) << "Unresolved exception class when finding catch block: " << mh.GetTypeDescriptorFromTypeIdx(iter_type_idx); } else if (iter_exception_type->IsAssignableFrom(exception_type)) { return iter_index; } ++iter_index; } // Handler not found return -1; } //---------------------------------------------------------------------------- // Object Space //---------------------------------------------------------------------------- Object* art_alloc_object_from_code(uint32_t type_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_alloc_object_from_code_with_access_check(uint32_t type_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_alloc_array_from_code(uint32_t type_idx, Object* referrer, uint32_t length) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_alloc_array_from_code_with_access_check(uint32_t type_idx, Object* referrer, uint32_t length) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_check_and_alloc_array_from_code(uint32_t type_idx, Object* referrer, uint32_t length) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_check_and_alloc_array_from_code_with_access_check(uint32_t type_idx, Object* referrer, uint32_t length) { UNIMPLEMENTED(WARNING); return NULL; } void art_find_instance_field_from_code(uint32_t field_idx, Object* referrer) { UNIMPLEMENTED(WARNING); } void art_find_static_field_from_code(uint32_t field_idx, Object* referrer) { UNIMPLEMENTED(WARNING); } Object* art_find_interface_method_from_code(uint32_t method_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_initialize_static_storage_from_code(uint32_t type_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_initialize_type_from_code(uint32_t type_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_initialize_type_and_verify_access_from_code(uint32_t type_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_resolve_string_from_code(Object* referrer, uint32_t string_idx) { UNIMPLEMENTED(WARNING); return NULL; } int32_t art_set32_static_from_code(uint32_t field_idx, Object* referrer, int32_t new_value) { UNIMPLEMENTED(WARNING); return -1; } int32_t art_set64_static_from_code(uint32_t field_idx, Object* referrer, int64_t new_value) { UNIMPLEMENTED(WARNING); return -1; } int32_t art_set_obj_static_from_code(uint32_t field_idx, Object* referrer, Object* new_value) { UNIMPLEMENTED(WARNING); return -1; } int32_t art_get32_static_from_code(uint32_t field_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return 0; } int64_t art_get64_static_from_code(uint32_t field_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return 0; } Object* art_get_obj_static_from_code(uint32_t field_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } int32_t art_set32_instance_from_code(uint32_t field_idx, Object* referrer, Object* object, uint32_t new_value) { UNIMPLEMENTED(WARNING); return -1; } int32_t art_set64_instance_from_code(uint32_t field_idx, Object* referrer, Object* object, int64_t new_value) { UNIMPLEMENTED(WARNING); return -1; } int32_t art_set_obj_instance_from_code(uint32_t field_idx, Object* referrer, Object* object, Object* new_value) { UNIMPLEMENTED(WARNING); return -1; } int32_t art_get32_instance_from_code(uint32_t field_idx, Object* referrer, Object* object) { UNIMPLEMENTED(WARNING); return 0; } int64_t art_get64_instance_from_code(uint32_t field_idx, Object* referrer, Object* object) { UNIMPLEMENTED(WARNING); return 0; } Object* art_get_obj_instance_from_code(uint32_t field_idx, Object* referrer, Object* object) { UNIMPLEMENTED(WARNING); return NULL; } //---------------------------------------------------------------------------- // RTTI //---------------------------------------------------------------------------- int32_t art_is_assignable_from_code(Object* dest_type, Object* src_type) { return 0; } void art_check_cast_from_code(Object* dest_type, Object* src_type) { } //---------------------------------------------------------------------------- // Runtime Support Function Lookup Callback //---------------------------------------------------------------------------- void* art_find_runtime_support_func(void* context, char const* name) { struct func_entry_t { char const* name; size_t name_len; void* addr; }; static struct func_entry_t const tab[] = { #define DEF(NAME, ADDR) \ { NAME, sizeof(NAME) - 1, (void *)(&(ADDR)) }, DEF("art_push_shadow_frame_from_code", art_push_shadow_frame_from_code) DEF("art_pop_shadow_frame_from_code", art_pop_shadow_frame_from_code) DEF("art_is_exception_pending_from_code", art_is_exception_pending_from_code) DEF("art_throw_div_zero_from_code", art_throw_div_zero_from_code) DEF("art_throw_array_bounds_from_code", art_throw_array_bounds_from_code) DEF("art_throw_no_such_method_from_code", art_throw_no_such_method_from_code) DEF("art_throw_null_pointer_exception_from_code", art_throw_null_pointer_exception_from_code) DEF("art_throw_stack_overflow_from_code", art_throw_stack_overflow_from_code) DEF("art_throw_exception_from_code", art_throw_exception_from_code) DEF("art_find_catch_block_from_code", art_find_catch_block_from_code) DEF("art_test_suspend_from_code", art_test_suspend_from_code) DEF("art_set_current_thread_from_code", art_set_current_thread_from_code) DEF("printf", printf) DEF("scanf", scanf) DEF("__isoc99_scanf", scanf) DEF("rand", rand) DEF("time", time) DEF("srand", srand) #undef DEF }; static size_t const tab_size = sizeof(tab) / sizeof(struct func_entry_t); // Note: Since our table is small, we are using trivial O(n) searching // function. For bigger table, it will be better to use binary // search or hash function. size_t i; size_t name_len = strlen(name); for (i = 0; i < tab_size; ++i) { if (name_len == tab[i].name_len && strcmp(name, tab[i].name) == 0) { return tab[i].addr; } } LOG(FATAL) << "Error: Can't find symbol " << name; return 0; } } // namespace art <commit_msg>Create the runtime support table from the function list.<commit_after>// Copyright 2012 Google Inc. All Rights Reserved. #include "class_linker.h" #include "dex_verifier.h" #include "object.h" #include "object_utils.h" #include "runtime_support_llvm.h" #include "thread.h" #include <stdint.h> namespace art { //---------------------------------------------------------------------------- // Thread //---------------------------------------------------------------------------- Thread* art_get_current_thread_from_code() { return Thread::Current(); } void art_set_current_thread_from_code(void* thread_object_addr) { UNIMPLEMENTED(WARNING); } void art_lock_object_from_code(Object* object) { UNIMPLEMENTED(WARNING); } void art_unlock_object_from_code(Object* object) { UNIMPLEMENTED(WARNING); } void art_test_suspend_from_code() { UNIMPLEMENTED(WARNING); } void art_push_shadow_frame_from_code(void* new_shadow_frame) { Thread* thread = Thread::Current(); thread->PushSirt( static_cast<StackIndirectReferenceTable*>(new_shadow_frame) ); } void art_pop_shadow_frame_from_code() { Thread* thread = Thread::Current(); thread->PopSirt(); } //---------------------------------------------------------------------------- // Exception //---------------------------------------------------------------------------- static std::string MethodNameFromIndex(const Method* method, uint32_t ref, verifier::VerifyErrorRefType ref_type, bool access) { CHECK_EQ(static_cast<int>(ref_type), static_cast<int>(verifier::VERIFY_ERROR_REF_METHOD)); ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache()); const DexFile::MethodId& id = dex_file.GetMethodId(ref); std::string class_name( PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(id)) ); const char* method_name = dex_file.StringDataByIdx(id.name_idx_); if (!access) { return class_name + "." + method_name; } std::string result; result += "tried to access method "; result += class_name + "." + method_name + ":" + dex_file.CreateMethodSignature(id.proto_idx_, NULL); result += " from class "; result += PrettyDescriptor(method->GetDeclaringClass()); return result; } bool art_is_exception_pending_from_code() { return Thread::Current()->IsExceptionPending(); } void art_throw_div_zero_from_code() { Thread* thread = Thread::Current(); thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero"); } void art_throw_array_bounds_from_code(int32_t length, int32_t index) { Thread* thread = Thread::Current(); thread->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;", "length=%d; index=%d", length, index); } void art_throw_no_such_method_from_code(int32_t method_idx) { Thread* thread = Thread::Current(); // We need the calling method as context for the method_idx Frame frame = thread->GetTopOfStack(); frame.Next(); Method* method = frame.GetMethod(); thread->ThrowNewException("Ljava/lang/NoSuchMethodError;", MethodNameFromIndex(method, method_idx, verifier::VERIFY_ERROR_REF_METHOD, false).c_str()); } void art_throw_null_pointer_exception_from_code() { Thread* thread = Thread::Current(); thread->ThrowNewException("Ljava/lang/NullPointerException;", NULL); } void art_throw_stack_overflow_from_code(void*) { Thread* thread = Thread::Current(); thread->ThrowNewExceptionF("Ljava/lang/StackOverflowError;", "stack size %zdkb; default stack size: %zdkb", thread->GetStackSize() / KB, Runtime::Current()->GetDefaultStackSize() / KB); } void art_throw_exception_from_code(Object* exception) { Thread* thread = Thread::Current(); thread->SetException(static_cast<Throwable*>(exception)); } int32_t art_find_catch_block_from_code(Object* exception, int32_t dex_pc) { Class* exception_type = exception->GetClass(); Method* current_method = Thread::Current()->GetCurrentMethod(); MethodHelper mh(current_method); const DexFile::CodeItem* code_item = mh.GetCodeItem(); int iter_index = 0; // Iterate over the catch handlers associated with dex_pc for (CatchHandlerIterator it(*code_item, dex_pc); it.HasNext(); it.Next()) { uint16_t iter_type_idx = it.GetHandlerTypeIndex(); // Catch all case if (iter_type_idx == DexFile::kDexNoIndex16) { return iter_index; } // Does this catch exception type apply? Class* iter_exception_type = mh.GetDexCacheResolvedType(iter_type_idx); if (iter_exception_type == NULL) { // The verifier should take care of resolving all exception classes early LOG(WARNING) << "Unresolved exception class when finding catch block: " << mh.GetTypeDescriptorFromTypeIdx(iter_type_idx); } else if (iter_exception_type->IsAssignableFrom(exception_type)) { return iter_index; } ++iter_index; } // Handler not found return -1; } //---------------------------------------------------------------------------- // Object Space //---------------------------------------------------------------------------- Object* art_alloc_object_from_code(uint32_t type_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_alloc_object_from_code_with_access_check(uint32_t type_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_alloc_array_from_code(uint32_t type_idx, Object* referrer, uint32_t length) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_alloc_array_from_code_with_access_check(uint32_t type_idx, Object* referrer, uint32_t length) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_check_and_alloc_array_from_code(uint32_t type_idx, Object* referrer, uint32_t length) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_check_and_alloc_array_from_code_with_access_check(uint32_t type_idx, Object* referrer, uint32_t length) { UNIMPLEMENTED(WARNING); return NULL; } void art_find_instance_field_from_code(uint32_t field_idx, Object* referrer) { UNIMPLEMENTED(WARNING); } void art_find_static_field_from_code(uint32_t field_idx, Object* referrer) { UNIMPLEMENTED(WARNING); } Object* art_find_interface_method_from_code(uint32_t method_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_initialize_static_storage_from_code(uint32_t type_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_initialize_type_from_code(uint32_t type_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_initialize_type_and_verify_access_from_code(uint32_t type_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } Object* art_resolve_string_from_code(Object* referrer, uint32_t string_idx) { UNIMPLEMENTED(WARNING); return NULL; } int32_t art_set32_static_from_code(uint32_t field_idx, Object* referrer, int32_t new_value) { UNIMPLEMENTED(WARNING); return -1; } int32_t art_set64_static_from_code(uint32_t field_idx, Object* referrer, int64_t new_value) { UNIMPLEMENTED(WARNING); return -1; } int32_t art_set_obj_static_from_code(uint32_t field_idx, Object* referrer, Object* new_value) { UNIMPLEMENTED(WARNING); return -1; } int32_t art_get32_static_from_code(uint32_t field_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return 0; } int64_t art_get64_static_from_code(uint32_t field_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return 0; } Object* art_get_obj_static_from_code(uint32_t field_idx, Object* referrer) { UNIMPLEMENTED(WARNING); return NULL; } int32_t art_set32_instance_from_code(uint32_t field_idx, Object* referrer, Object* object, uint32_t new_value) { UNIMPLEMENTED(WARNING); return -1; } int32_t art_set64_instance_from_code(uint32_t field_idx, Object* referrer, Object* object, int64_t new_value) { UNIMPLEMENTED(WARNING); return -1; } int32_t art_set_obj_instance_from_code(uint32_t field_idx, Object* referrer, Object* object, Object* new_value) { UNIMPLEMENTED(WARNING); return -1; } int32_t art_get32_instance_from_code(uint32_t field_idx, Object* referrer, Object* object) { UNIMPLEMENTED(WARNING); return 0; } int64_t art_get64_instance_from_code(uint32_t field_idx, Object* referrer, Object* object) { UNIMPLEMENTED(WARNING); return 0; } Object* art_get_obj_instance_from_code(uint32_t field_idx, Object* referrer, Object* object) { UNIMPLEMENTED(WARNING); return NULL; } //---------------------------------------------------------------------------- // RTTI //---------------------------------------------------------------------------- int32_t art_is_assignable_from_code(Object* dest_type, Object* src_type) { return 0; } void art_check_cast_from_code(Object* dest_type, Object* src_type) { } //---------------------------------------------------------------------------- // Runtime Support Function Lookup Callback //---------------------------------------------------------------------------- void* art_find_runtime_support_func(void* context, char const* name) { struct func_entry_t { char const* name; size_t name_len; void* addr; }; static struct func_entry_t const tab[] = { #define DEFINE_ENTRY(ID, NAME) \ { #NAME, sizeof(#NAME) - 1, reinterpret_cast<void*>(NAME) }, #include "runtime_support_func_list.h" RUNTIME_SUPPORT_FUNC_LIST(DEFINE_ENTRY) #undef RUNTIME_SUPPORT_FUNC_LIST #undef DEFINE_ENTRY }; static size_t const tab_size = sizeof(tab) / sizeof(struct func_entry_t); // Note: Since our table is small, we are using trivial O(n) searching // function. For bigger table, it will be better to use binary // search or hash function. size_t i; size_t name_len = strlen(name); for (i = 0; i < tab_size; ++i) { if (name_len == tab[i].name_len && strcmp(name, tab[i].name) == 0) { return tab[i].addr; } } LOG(FATAL) << "Error: Can't find symbol " << name; return 0; } } // namespace art <|endoftext|>
<commit_before>// -*-Mode: C++;-*- // * BeginRiceCopyright ***************************************************** // // $HeadURL$ // $Id$ // // -------------------------------------------------------------------------- // Part of HPCToolkit (hpctoolkit.org) // // Information about sources of support for research and development of // HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. // -------------------------------------------------------------------------- // // Copyright ((c)) 2002-2018, Rice University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // $HeadURL$ // // Purpose: // [The purpose of this file] // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** #ifndef ParallelAnalysis_hpp #define ParallelAnalysis_hpp //**************************** MPI Include Files **************************** #include <mpi.h> //************************* System Include Files **************************** #include <iostream> #include <string> #include <vector> #include <cstring> // for memset() #include <stdint.h> //*************************** User Include Files **************************** #include <include/uint.h> #include <lib/prof/CallPath-Profile.hpp> #include <lib/support/Unique.hpp> //*************************** Forward Declarations ************************** //*************************************************************************** // PackedMetrics: a packable matrix //*************************************************************************** namespace ParallelAnalysis { class PackedMetrics : public Unique // prevent copying { public: // [mBegId, mEndId) PackedMetrics(uint numNodes, uint mBegId, uint mEndId, uint mDrvdBegId, uint mDrvdEndId) : m_numNodes(numNodes), m_numMetrics(mEndId - mBegId), m_mBegId(mBegId), m_mEndId(mEndId), m_mDrvdBegId(mDrvdBegId), m_mDrvdEndId(mDrvdEndId) { size_t sz = dataSize(); m_packedData = new double[sz]; // initialize first (unused) row to avoid bogus valgrind warnings memset(m_packedData, 0, (m_numHdr + m_numMetrics) * sizeof(double)); m_packedData[m_numNodesIdx] = (double)m_numNodes; m_packedData[m_mBegIdIdx] = (double)m_mBegId; m_packedData[m_mEndIdIdx] = (double)m_mEndId; } // PackedMetrics(double* packedMatrix) { } ~PackedMetrics() { delete[] m_packedData; } // 0 based indexing (row-major layout) double idx(uint idxNodes, uint idxMetrics) const { return m_packedData[m_numHdr + (m_numMetrics * idxNodes) + idxMetrics]; } double& idx(uint idxNodes, uint idxMetrics) { return m_packedData[m_numHdr + (m_numMetrics * idxNodes) + idxMetrics]; } uint numNodes() const { return m_numNodes; } uint numMetrics() const { return m_numMetrics; } uint mBegId() const { return m_mBegId; } uint mEndId() const { return m_mEndId; } uint mDrvdBegId() const { return m_mDrvdBegId; } uint mDrvdEndId() const { return m_mDrvdEndId; } bool verify() const { return (m_numNodes == (uint)m_packedData[m_numNodesIdx] && m_mBegId == (uint)m_packedData[m_mBegIdIdx] && m_mEndId == (uint)m_packedData[m_mEndIdIdx]); } double* data() const { return m_packedData; } // dataSize: size in terms of elements uint dataSize() const { return (m_numNodes * m_numMetrics) + m_numHdr; } private: static const uint m_numHdr = 4; static const uint m_numNodesIdx = 0; static const uint m_mBegIdIdx = 1; static const uint m_mEndIdIdx = 2; uint m_numNodes; // rows uint m_numMetrics; // columns uint m_mBegId, m_mEndId; // [ ) uint m_mDrvdBegId, m_mDrvdEndId; // [ ) double* m_packedData; // use row-major layout }; } // namespace ParallelAnalysis //*************************************************************************** // reduce/broadcast //*************************************************************************** namespace ParallelAnalysis { // ------------------------------------------------------------------------ // mergeNonLocal: merge profile on rank_y into profile on rank_x // ------------------------------------------------------------------------ void packSend(Prof::CallPath::Profile* profile, int dest, int myRank, MPI_Comm comm = MPI_COMM_WORLD); void mergeNonLocal(Prof::CallPath::Profile* profile, int rank_x, int rank_y, int myRank, MPI_Comm comm = MPI_COMM_WORLD); void packSend(std::pair<Prof::CallPath::Profile*, ParallelAnalysis::PackedMetrics*> data, int dest, int myRank, MPI_Comm comm = MPI_COMM_WORLD); void mergeNonLocal(std::pair<Prof::CallPath::Profile*, ParallelAnalysis::PackedMetrics*> data, int rank_x, int rank_y, int myRank, MPI_Comm comm = MPI_COMM_WORLD); void packSend(StringSet *stringSet, int dest, int myRank, MPI_Comm comm = MPI_COMM_WORLD); void mergeNonLocal(StringSet *stringSet, int rank_x, int rank_y, int myRank, MPI_Comm comm = MPI_COMM_WORLD); // ------------------------------------------------------------------------ // reduce: Uses a tree-based reduction to reduce the profile at every // rank into a canonical profile at the tree's root, rank 0. Assumes // 0-based ranks. // // T: Prof::CallPath::Profile* // T: std::pair<Prof::CallPath::Profile*, ParallelAnalysis::PackedMetrics*> // ------------------------------------------------------------------------ template<typename T> void reduce(T object, int myRank, int numRanks, MPI_Comm comm = MPI_COMM_WORLD) { int lchild = 2 * myRank + 1; if (lchild < numRanks) { packSend(object, lchild, myRank); int rchild = 2 * myRank + 2; if (rchild < numRanks) { packSend(object, rchild, myRank); } } if (myRank > 0) { int parent = (myRank - 1) / 2; packSend(object, parent, myRank); } } // ------------------------------------------------------------------------ // broadcast: Broadcast the profile at the tree's root (rank 0) to every // other rank. Assumes 0-based ranks. // ------------------------------------------------------------------------ void broadcast(Prof::CallPath::Profile*& profile, int myRank, MPI_Comm comm = MPI_COMM_WORLD); void broadcast(StringSet &stringSet, int myRank, MPI_Comm comm = MPI_COMM_WORLD); // ------------------------------------------------------------------------ // pack/unpack a profile to/from a buffer // ------------------------------------------------------------------------ void packProfile(const Prof::CallPath::Profile& profile, uint8_t** buffer, size_t* bufferSz); Prof::CallPath::Profile* unpackProfile(uint8_t* buffer, size_t bufferSz); // ------------------------------------------------------------------------ // pack/unpack a metrics from/to a profile // ------------------------------------------------------------------------ // packMetrics: pack the given metric values from 'profile' into // 'packedMetrics' void packMetrics(const Prof::CallPath::Profile& profile, ParallelAnalysis::PackedMetrics& packedMetrics); // unpackMetrics: unpack 'packedMetrics' into profile and apply metric update void unpackMetrics(Prof::CallPath::Profile& profile, const ParallelAnalysis::PackedMetrics& packedMetrics); } // namespace ParallelAnalysis //*************************************************************************** #endif // ParallelAnalysis_hpp <commit_msg>Use recvMerge where appropriate.<commit_after>// -*-Mode: C++;-*- // * BeginRiceCopyright ***************************************************** // // $HeadURL$ // $Id$ // // -------------------------------------------------------------------------- // Part of HPCToolkit (hpctoolkit.org) // // Information about sources of support for research and development of // HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. // -------------------------------------------------------------------------- // // Copyright ((c)) 2002-2018, Rice University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // $HeadURL$ // // Purpose: // [The purpose of this file] // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** #ifndef ParallelAnalysis_hpp #define ParallelAnalysis_hpp //**************************** MPI Include Files **************************** #include <mpi.h> //************************* System Include Files **************************** #include <iostream> #include <string> #include <vector> #include <cstring> // for memset() #include <stdint.h> //*************************** User Include Files **************************** #include <include/uint.h> #include <lib/prof/CallPath-Profile.hpp> #include <lib/support/Unique.hpp> //*************************** Forward Declarations ************************** //*************************************************************************** // PackedMetrics: a packable matrix //*************************************************************************** namespace ParallelAnalysis { class PackedMetrics : public Unique // prevent copying { public: // [mBegId, mEndId) PackedMetrics(uint numNodes, uint mBegId, uint mEndId, uint mDrvdBegId, uint mDrvdEndId) : m_numNodes(numNodes), m_numMetrics(mEndId - mBegId), m_mBegId(mBegId), m_mEndId(mEndId), m_mDrvdBegId(mDrvdBegId), m_mDrvdEndId(mDrvdEndId) { size_t sz = dataSize(); m_packedData = new double[sz]; // initialize first (unused) row to avoid bogus valgrind warnings memset(m_packedData, 0, (m_numHdr + m_numMetrics) * sizeof(double)); m_packedData[m_numNodesIdx] = (double)m_numNodes; m_packedData[m_mBegIdIdx] = (double)m_mBegId; m_packedData[m_mEndIdIdx] = (double)m_mEndId; } // PackedMetrics(double* packedMatrix) { } ~PackedMetrics() { delete[] m_packedData; } // 0 based indexing (row-major layout) double idx(uint idxNodes, uint idxMetrics) const { return m_packedData[m_numHdr + (m_numMetrics * idxNodes) + idxMetrics]; } double& idx(uint idxNodes, uint idxMetrics) { return m_packedData[m_numHdr + (m_numMetrics * idxNodes) + idxMetrics]; } uint numNodes() const { return m_numNodes; } uint numMetrics() const { return m_numMetrics; } uint mBegId() const { return m_mBegId; } uint mEndId() const { return m_mEndId; } uint mDrvdBegId() const { return m_mDrvdBegId; } uint mDrvdEndId() const { return m_mDrvdEndId; } bool verify() const { return (m_numNodes == (uint)m_packedData[m_numNodesIdx] && m_mBegId == (uint)m_packedData[m_mBegIdIdx] && m_mEndId == (uint)m_packedData[m_mEndIdIdx]); } double* data() const { return m_packedData; } // dataSize: size in terms of elements uint dataSize() const { return (m_numNodes * m_numMetrics) + m_numHdr; } private: static const uint m_numHdr = 4; static const uint m_numNodesIdx = 0; static const uint m_mBegIdIdx = 1; static const uint m_mEndIdIdx = 2; uint m_numNodes; // rows uint m_numMetrics; // columns uint m_mBegId, m_mEndId; // [ ) uint m_mDrvdBegId, m_mDrvdEndId; // [ ) double* m_packedData; // use row-major layout }; } // namespace ParallelAnalysis //*************************************************************************** // reduce/broadcast //*************************************************************************** namespace ParallelAnalysis { // ------------------------------------------------------------------------ // mergeNonLocal: merge profile on rank_y into profile on rank_x // ------------------------------------------------------------------------ void packSend(Prof::CallPath::Profile* profile, int dest, int myRank, MPI_Comm comm = MPI_COMM_WORLD); void mergeNonLocal(Prof::CallPath::Profile* profile, int rank_x, int rank_y, int myRank, MPI_Comm comm = MPI_COMM_WORLD); void packSend(std::pair<Prof::CallPath::Profile*, ParallelAnalysis::PackedMetrics*> data, int dest, int myRank, MPI_Comm comm = MPI_COMM_WORLD); void mergeNonLocal(std::pair<Prof::CallPath::Profile*, ParallelAnalysis::PackedMetrics*> data, int rank_x, int rank_y, int myRank, MPI_Comm comm = MPI_COMM_WORLD); void packSend(StringSet *stringSet, int dest, int myRank, MPI_Comm comm = MPI_COMM_WORLD); void mergeNonLocal(StringSet *stringSet, int rank_x, int rank_y, int myRank, MPI_Comm comm = MPI_COMM_WORLD); // ------------------------------------------------------------------------ // reduce: Uses a tree-based reduction to reduce the profile at every // rank into a canonical profile at the tree's root, rank 0. Assumes // 0-based ranks. // // T: Prof::CallPath::Profile* // T: std::pair<Prof::CallPath::Profile*, ParallelAnalysis::PackedMetrics*> // ------------------------------------------------------------------------ template<typename T> void reduce(T object, int myRank, int numRanks, MPI_Comm comm = MPI_COMM_WORLD) { int lchild = 2 * myRank + 1; if (lchild < numRanks) { recvMerge(object, lchild, myRank); int rchild = 2 * myRank + 2; if (rchild < numRanks) { recvMerge(object, rchild, myRank); } } if (myRank > 0) { int parent = (myRank - 1) / 2; packSend(object, parent, myRank); } } // ------------------------------------------------------------------------ // broadcast: Broadcast the profile at the tree's root (rank 0) to every // other rank. Assumes 0-based ranks. // ------------------------------------------------------------------------ void broadcast(Prof::CallPath::Profile*& profile, int myRank, MPI_Comm comm = MPI_COMM_WORLD); void broadcast(StringSet &stringSet, int myRank, MPI_Comm comm = MPI_COMM_WORLD); // ------------------------------------------------------------------------ // pack/unpack a profile to/from a buffer // ------------------------------------------------------------------------ void packProfile(const Prof::CallPath::Profile& profile, uint8_t** buffer, size_t* bufferSz); Prof::CallPath::Profile* unpackProfile(uint8_t* buffer, size_t bufferSz); // ------------------------------------------------------------------------ // pack/unpack a metrics from/to a profile // ------------------------------------------------------------------------ // packMetrics: pack the given metric values from 'profile' into // 'packedMetrics' void packMetrics(const Prof::CallPath::Profile& profile, ParallelAnalysis::PackedMetrics& packedMetrics); // unpackMetrics: unpack 'packedMetrics' into profile and apply metric update void unpackMetrics(Prof::CallPath::Profile& profile, const ParallelAnalysis::PackedMetrics& packedMetrics); } // namespace ParallelAnalysis //*************************************************************************** #endif // ParallelAnalysis_hpp <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGuiBaseApplication.cpp created: 7/2/2008 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGuiBaseApplication.h" #include <stdlib.h> #include <string.h> #include <limits.h> // setup default-default path #ifndef CEGUI_SAMPLE_DATAPATH #define CEGUI_SAMPLE_DATAPATH "../datafiles" #endif /*********************************************************************** Static / Const data *************************************************************************/ const char CEGuiBaseApplication::DATAPATH_VAR_NAME[] = "CEGUI_SAMPLE_DATAPATH"; /*********************************************************************** Return env var value that tells us where data should be *************************************************************************/ const char* CEGuiBaseApplication::getDataPathPrefix() const { static char dataPathPrefix[PATH_MAX]; char* envDataPath = 0; // get data path from environment var envDataPath = getenv(DATAPATH_VAR_NAME); // set data path prefix / base directory. This will // be either from an environment variable, or from // a compiled in default based on original configure // options if (envDataPath != 0) strcpy(dataPathPrefix, envDataPath); else strcpy(dataPathPrefix, CEGUI_SAMPLE_DATAPATH); return dataPathPrefix; } <commit_msg>MOD: Change Sample base applciation so that on tha Mac it successfully fetches the path of the datafiles directory within the app bundles Resources (now we don't have to rely on working directory being unmodified).<commit_after>/*********************************************************************** filename: CEGuiBaseApplication.cpp created: 7/2/2008 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGuiBaseApplication.h" #include <stdlib.h> #include <string.h> #include <limits.h> // setup default-default path #ifndef CEGUI_SAMPLE_DATAPATH #define CEGUI_SAMPLE_DATAPATH "../datafiles" #endif /*********************************************************************** Static / Const data *************************************************************************/ const char CEGuiBaseApplication::DATAPATH_VAR_NAME[] = "CEGUI_SAMPLE_DATAPATH"; /*********************************************************************** Return env var value that tells us where data should be *************************************************************************/ const char* CEGuiBaseApplication::getDataPathPrefix() const { static char dataPathPrefix[PATH_MAX]; #ifdef __APPLE__ CFURLRef datafilesURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("datafiles"), 0, 0); CFURLGetFileSystemRepresentation(datafilesURL, true, reinterpret_cast<UInt8*>(dataPathPrefix), PATH_MAX); CFRelease(datafilesURL); #else char* envDataPath = 0; // get data path from environment var envDataPath = getenv(DATAPATH_VAR_NAME); // set data path prefix / base directory. This will // be either from an environment variable, or from // a compiled in default based on original configure // options if (envDataPath != 0) strcpy(dataPathPrefix, envDataPath); else strcpy(dataPathPrefix, CEGUI_SAMPLE_DATAPATH); #endif return dataPathPrefix; } <|endoftext|>
<commit_before>#include "./video_recorder.h" #include <QTimer> #include <QLoggingCategory> #include "./graphics/gl.h" QLoggingCategory videoRecorderChan("VideoRecorder"); VideoRecorder::VideoRecorder(double fps) : fps(fps) { } VideoRecorder::~VideoRecorder() { qCInfo(videoRecorderChan) << "Destructor"; if (isRecording) stopRecording(); disconnect(videoTimer.get(), &QTimer::timeout, this, &VideoRecorder::updateVideoTimer); } void VideoRecorder::initialize(Graphics::Gl *gl) { this->gl = gl; } void VideoRecorder::resize(int width, int height) { stopRecording(); // mpeg supports even frame sizes only! videoWidth = (width % 2 == 0) ? width : width - 1; videoHeight = (height % 2 == 0) ? height : height - 1; } void VideoRecorder::createNewVideo(std::string filename) { qCInfo(videoRecorderChan) << "Create recorder" << filename.c_str(); if (videoRecorder.get()) { videoRecorder->stopRecording(); } pixelBuffer.resize(videoWidth * videoHeight * 3); videoRecorder = std::make_unique<FFMPEGRecorder>(videoWidth, videoHeight, 1, true, filename, fps); videoRecorder->startRecording(); videoTimer = std::make_unique<QTimer>(this); connect(videoTimer.get(), &QTimer::timeout, this, &VideoRecorder::updateVideoTimer); } void VideoRecorder::startRecording() { isRecording = true; videoTimer->start(40); } void VideoRecorder::stopRecording() { if (!isRecording) return; isRecording = false; videoTimer->stop(); } void VideoRecorder::updateVideoTimer() { videoRecorder->queueFrame(pixelBuffer.data()); } void VideoRecorder::captureVideoFrame() { if (videoRecorder && isRecording) { gl->glReadPixels(0, 0, videoWidth, videoHeight, GL_RGB, GL_UNSIGNED_BYTE, pixelBuffer.data()); } } bool VideoRecorder::getIsRecording() { return isRecording; } <commit_msg>Don't disconnect if there has never been a timer instance.<commit_after>#include "./video_recorder.h" #include <QTimer> #include <QLoggingCategory> #include "./graphics/gl.h" QLoggingCategory videoRecorderChan("VideoRecorder"); VideoRecorder::VideoRecorder(double fps) : fps(fps) { } VideoRecorder::~VideoRecorder() { qCInfo(videoRecorderChan) << "Destructor"; if (isRecording) stopRecording(); if (videoTimer.get()) disconnect(videoTimer.get(), &QTimer::timeout, this, &VideoRecorder::updateVideoTimer); } void VideoRecorder::initialize(Graphics::Gl *gl) { this->gl = gl; } void VideoRecorder::resize(int width, int height) { stopRecording(); // mpeg supports even frame sizes only! videoWidth = (width % 2 == 0) ? width : width - 1; videoHeight = (height % 2 == 0) ? height : height - 1; } void VideoRecorder::createNewVideo(std::string filename) { qCInfo(videoRecorderChan) << "Create recorder" << filename.c_str(); if (videoRecorder.get()) { videoRecorder->stopRecording(); } pixelBuffer.resize(videoWidth * videoHeight * 3); videoRecorder = std::make_unique<FFMPEGRecorder>(videoWidth, videoHeight, 1, true, filename, fps); videoRecorder->startRecording(); videoTimer = std::make_unique<QTimer>(this); connect(videoTimer.get(), &QTimer::timeout, this, &VideoRecorder::updateVideoTimer); } void VideoRecorder::startRecording() { isRecording = true; videoTimer->start(40); } void VideoRecorder::stopRecording() { if (!isRecording) return; isRecording = false; videoTimer->stop(); } void VideoRecorder::updateVideoTimer() { videoRecorder->queueFrame(pixelBuffer.data()); } void VideoRecorder::captureVideoFrame() { if (videoRecorder && isRecording) { gl->glReadPixels(0, 0, videoWidth, videoHeight, GL_RGB, GL_UNSIGNED_BYTE, pixelBuffer.data()); } } bool VideoRecorder::getIsRecording() { return isRecording; } <|endoftext|>
<commit_before>#pragma once #include <string> #include <vector> #include <boost/asio.hpp> namespace elasticsearch { namespace defaults { typedef boost::asio::ip::tcp::endpoint endpoint_type; const endpoint_type endpoint(boost::asio::ip::address_v4(), 9200); } // namespace defaults struct settings_t { typedef boost::asio::ip::tcp::endpoint endpoint_type; std::string index; std::string type; std::vector<endpoint_type> endpoints; struct sniffer_t { struct { bool start; bool error; } when; long timeout; long invertal; } sniffer; int connections; int retries; long timeout; settings_t() : index("logs-%Y.%m.%d"), type("log"), endpoints(std::vector<endpoint_type>({ defaults::endpoint })), sniffer({{ true, true }, 10, 60000 }), connections(20), retries(3), timeout(1000) {} }; } // namespace elasticsearch <commit_msg>[Elasticsearch] Currently there is no attributes substitution.<commit_after>#pragma once #include <string> #include <vector> #include <boost/asio.hpp> namespace elasticsearch { namespace defaults { typedef boost::asio::ip::tcp::endpoint endpoint_type; const endpoint_type endpoint(boost::asio::ip::address_v4(), 9200); } // namespace defaults struct settings_t { typedef boost::asio::ip::tcp::endpoint endpoint_type; std::string index; std::string type; std::vector<endpoint_type> endpoints; struct sniffer_t { struct { bool start; bool error; } when; long timeout; long invertal; } sniffer; int connections; int retries; long timeout; settings_t() : index("logs"), type("log"), endpoints(std::vector<endpoint_type>({ defaults::endpoint })), sniffer({{ true, true }, 10, 60000 }), connections(20), retries(3), timeout(1000) {} }; } // namespace elasticsearch <|endoftext|>
<commit_before>/* Q Light Controller Plus audioeditor.cpp Copyright (c) Massimo Callegari 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.txt 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 <QFileDialog> #include <QLineEdit> #include <QSettings> #include <QLabel> #include <QDebug> #include <QUrl> #include "audioplugincache.h" #include "speeddialwidget.h" #include "audiodecoder.h" #include "audioeditor.h" #include "audio.h" #include "doc.h" AudioEditor::AudioEditor(QWidget* parent, Audio *audio, Doc* doc) : QWidget(parent) , m_doc(doc) , m_audio(audio) , m_speedDials(NULL) { Q_ASSERT(doc != NULL); Q_ASSERT(audio != NULL); setupUi(this); m_nameEdit->setText(m_audio->name()); m_nameEdit->setSelection(0, m_nameEdit->text().length()); m_fadeInEdit->setText(Function::speedToString(audio->fadeInSpeed())); m_fadeOutEdit->setText(Function::speedToString(audio->fadeOutSpeed())); connect(m_nameEdit, SIGNAL(textEdited(const QString&)), this, SLOT(slotNameEdited(const QString&))); connect(m_fileButton, SIGNAL(clicked()), this, SLOT(slotSourceFileClicked())); connect(m_speedDialButton, SIGNAL(toggled(bool)), this, SLOT(slotSpeedDialToggle(bool))); connect(m_fadeInEdit, SIGNAL(returnPressed()), this, SLOT(slotFadeInEdited())); connect(m_fadeOutEdit, SIGNAL(returnPressed()), this, SLOT(slotFadeOutEdited())); connect(m_previewButton, SIGNAL(toggled(bool)), this, SLOT(slotPreviewToggled(bool))); AudioDecoder *adec = m_audio->getAudioDecoder(); m_filenameLabel->setText(m_audio->getSourceFileName()); if (adec != NULL) { AudioParameters ap = adec->audioParameters(); m_durationLabel->setText(Function::speedToString(m_audio->totalDuration())); m_srateLabel->setText(QString("%1 Hz").arg(ap.sampleRate())); m_channelsLabel->setText(QString("%1").arg(ap.channels())); m_bitrateLabel->setText(QString("%1 kb/s").arg(adec->bitrate())); } QList<AudioDeviceInfo> devList = m_doc->audioPluginCache()->audioDevicesList(); QSettings settings; QString outputName; int i = 0, selIdx = 0; m_audioDevCombo->addItem(tr("Default device"), "__qlcplusdefault__"); if (m_audio->audioDevice().isEmpty()) { QVariant var = settings.value(SETTINGS_AUDIO_OUTPUT_DEVICE); if (var.isValid() == true) outputName = var.toString(); } else outputName = m_audio->audioDevice(); foreach( AudioDeviceInfo info, devList) { if (info.capabilities & AUDIO_CAP_OUTPUT) { m_audioDevCombo->addItem(info.deviceName, info.privateName); if (info.privateName == outputName) selIdx = i; i++; } } m_audioDevCombo->setCurrentIndex(selIdx); connect(m_audioDevCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(slotAudioDeviceChanged(int))); if(m_audio->runOrder() == Audio::Loop) m_loopCheck->setChecked(true); else m_singleCheck->setChecked(true); connect(m_loopCheck, SIGNAL(clicked()), this, SLOT(slotLoopCheckClicked())); connect(m_singleCheck, SIGNAL(clicked()), this, SLOT(slotSingleShotCheckClicked())); // Set focus to the editor m_nameEdit->setFocus(); } AudioEditor::~AudioEditor() { m_audio->stop(functionParent()); } void AudioEditor::slotNameEdited(const QString& text) { m_audio->setName(text); m_doc->setModified(); } void AudioEditor::slotSourceFileClicked() { QString fn; /* Create a file open dialog */ QFileDialog dialog(this); dialog.setWindowTitle(tr("Open Audio File")); dialog.setAcceptMode(QFileDialog::AcceptOpen); /* Append file filters to the dialog */ QStringList extList = m_doc->audioPluginCache()->getSupportedFormats(); QStringList filters; qDebug() << Q_FUNC_INFO << "Extensions: " << extList.join(" "); filters << tr("Audio Files (%1)").arg(extList.join(" ")); #if defined(WIN32) || defined(Q_OS_WIN) filters << tr("All Files (*.*)"); #else filters << tr("All Files (*)"); #endif dialog.setNameFilters(filters); /* Append useful URLs to the dialog */ QList <QUrl> sidebar; sidebar.append(QUrl::fromLocalFile(QDir::homePath())); sidebar.append(QUrl::fromLocalFile(QDir::rootPath())); dialog.setSidebarUrls(sidebar); /* Get file name */ if (dialog.exec() != QDialog::Accepted) return; fn = dialog.selectedFiles().first(); if (fn.isEmpty() == true) return; if (m_audio->isRunning()) m_audio->stopAndWait(); m_audio->setSourceFileName(fn); m_filenameLabel->setText(m_audio->getSourceFileName()); AudioDecoder *adec = m_audio->getAudioDecoder(); if (adec != NULL) { AudioParameters ap = adec->audioParameters(); m_durationLabel->setText(Function::speedToString(m_audio->totalDuration())); m_srateLabel->setText(QString("%1 Hz").arg(ap.sampleRate())); m_channelsLabel->setText(QString("%1").arg(ap.channels())); m_bitrateLabel->setText(QString("%1 kb/s").arg(adec->bitrate())); } } void AudioEditor::slotFadeInEdited() { uint newValue; QString text = m_fadeInEdit->text(); newValue = Function::stringToSpeed(text); m_fadeInEdit->setText(Function::speedToString(newValue)); m_audio->setFadeInSpeed(newValue); m_doc->setModified(); } void AudioEditor::slotFadeOutEdited() { uint newValue; QString text = m_fadeOutEdit->text(); newValue = Function::stringToSpeed(text); m_fadeOutEdit->setText(Function::speedToString(newValue)); m_audio->setFadeOutSpeed(newValue); m_doc->setModified(); } void AudioEditor::slotAudioDeviceChanged(int idx) { QString audioDev = m_audioDevCombo->itemData(idx).toString(); qDebug() << "New audio device selected:" << audioDev; if (audioDev == "__qlcplusdefault__") m_audio->setAudioDevice(QString()); else m_audio->setAudioDevice(audioDev); } void AudioEditor::slotPreviewToggled(bool state) { if (state == true) { m_audio->start(m_doc->masterTimer(), functionParent()); connect(m_audio, SIGNAL(stopped(quint32)), this, SLOT(slotPreviewStopped(quint32))); } else m_audio->stop(functionParent()); } void AudioEditor::slotPreviewStopped(quint32 id) { if (id == m_audio->id()) m_previewButton->setChecked(false); } void AudioEditor::slotSingleShotCheckClicked() { m_audio->setRunOrder(Audio::SingleShot); } void AudioEditor::slotLoopCheckClicked() { m_audio->setRunOrder(Audio::Loop); } FunctionParent AudioEditor::functionParent() const { return FunctionParent::master(); } /************************************************************************ * Speed dials ************************************************************************/ void AudioEditor::createSpeedDials() { if (m_speedDials != NULL) return; m_speedDials = new SpeedDialWidget(this); m_speedDials->setAttribute(Qt::WA_DeleteOnClose); m_speedDials->setWindowTitle(m_audio->name()); m_speedDials->setFadeInSpeed(m_audio->fadeInSpeed()); m_speedDials->setFadeOutSpeed(m_audio->fadeOutSpeed()); m_speedDials->setDurationEnabled(false); m_speedDials->setDurationVisible(false); connect(m_speedDials, SIGNAL(fadeInChanged(int)), this, SLOT(slotFadeInDialChanged(int))); connect(m_speedDials, SIGNAL(fadeOutChanged(int)), this, SLOT(slotFadeOutDialChanged(int))); connect(m_speedDials, SIGNAL(destroyed(QObject*)), this, SLOT(slotDialDestroyed(QObject*))); m_speedDials->show(); } void AudioEditor::slotSpeedDialToggle(bool state) { if (state == true) createSpeedDials(); else { if (m_speedDials != NULL) m_speedDials->deleteLater(); m_speedDials = NULL; } } void AudioEditor::slotFadeInDialChanged(int ms) { m_fadeInEdit->setText(Function::speedToString(ms)); m_audio->setFadeInSpeed(ms); } void AudioEditor::slotFadeOutDialChanged(int ms) { m_fadeOutEdit->setText(Function::speedToString(ms)); m_audio->setFadeOutSpeed(ms); } void AudioEditor::slotDialDestroyed(QObject *) { m_speedDialButton->setChecked(false); } <commit_msg>Fix wrong index in m_audioDevCombo. Assuming that Default device has index = 0 discovered devices ara added starting on index = 1.<commit_after>/* Q Light Controller Plus audioeditor.cpp Copyright (c) Massimo Callegari 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.txt 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 <QFileDialog> #include <QLineEdit> #include <QSettings> #include <QLabel> #include <QDebug> #include <QUrl> #include "audioplugincache.h" #include "speeddialwidget.h" #include "audiodecoder.h" #include "audioeditor.h" #include "audio.h" #include "doc.h" AudioEditor::AudioEditor(QWidget* parent, Audio *audio, Doc* doc) : QWidget(parent) , m_doc(doc) , m_audio(audio) , m_speedDials(NULL) { Q_ASSERT(doc != NULL); Q_ASSERT(audio != NULL); setupUi(this); m_nameEdit->setText(m_audio->name()); m_nameEdit->setSelection(0, m_nameEdit->text().length()); m_fadeInEdit->setText(Function::speedToString(audio->fadeInSpeed())); m_fadeOutEdit->setText(Function::speedToString(audio->fadeOutSpeed())); connect(m_nameEdit, SIGNAL(textEdited(const QString&)), this, SLOT(slotNameEdited(const QString&))); connect(m_fileButton, SIGNAL(clicked()), this, SLOT(slotSourceFileClicked())); connect(m_speedDialButton, SIGNAL(toggled(bool)), this, SLOT(slotSpeedDialToggle(bool))); connect(m_fadeInEdit, SIGNAL(returnPressed()), this, SLOT(slotFadeInEdited())); connect(m_fadeOutEdit, SIGNAL(returnPressed()), this, SLOT(slotFadeOutEdited())); connect(m_previewButton, SIGNAL(toggled(bool)), this, SLOT(slotPreviewToggled(bool))); AudioDecoder *adec = m_audio->getAudioDecoder(); m_filenameLabel->setText(m_audio->getSourceFileName()); if (adec != NULL) { AudioParameters ap = adec->audioParameters(); m_durationLabel->setText(Function::speedToString(m_audio->totalDuration())); m_srateLabel->setText(QString("%1 Hz").arg(ap.sampleRate())); m_channelsLabel->setText(QString("%1").arg(ap.channels())); m_bitrateLabel->setText(QString("%1 kb/s").arg(adec->bitrate())); } QList<AudioDeviceInfo> devList = m_doc->audioPluginCache()->audioDevicesList(); QSettings settings; QString outputName; int i = 1, selIdx = 1; m_audioDevCombo->addItem(tr("Default device"), "__qlcplusdefault__"); if (m_audio->audioDevice().isEmpty()) { QVariant var = settings.value(SETTINGS_AUDIO_OUTPUT_DEVICE); if (var.isValid() == true) outputName = var.toString(); } else outputName = m_audio->audioDevice(); foreach( AudioDeviceInfo info, devList) { if (info.capabilities & AUDIO_CAP_OUTPUT) { m_audioDevCombo->addItem(info.deviceName, info.privateName); if (info.privateName == outputName) selIdx = i; i++; } } m_audioDevCombo->setCurrentIndex(selIdx); connect(m_audioDevCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(slotAudioDeviceChanged(int))); if(m_audio->runOrder() == Audio::Loop) m_loopCheck->setChecked(true); else m_singleCheck->setChecked(true); connect(m_loopCheck, SIGNAL(clicked()), this, SLOT(slotLoopCheckClicked())); connect(m_singleCheck, SIGNAL(clicked()), this, SLOT(slotSingleShotCheckClicked())); // Set focus to the editor m_nameEdit->setFocus(); } AudioEditor::~AudioEditor() { m_audio->stop(functionParent()); } void AudioEditor::slotNameEdited(const QString& text) { m_audio->setName(text); m_doc->setModified(); } void AudioEditor::slotSourceFileClicked() { QString fn; /* Create a file open dialog */ QFileDialog dialog(this); dialog.setWindowTitle(tr("Open Audio File")); dialog.setAcceptMode(QFileDialog::AcceptOpen); /* Append file filters to the dialog */ QStringList extList = m_doc->audioPluginCache()->getSupportedFormats(); QStringList filters; qDebug() << Q_FUNC_INFO << "Extensions: " << extList.join(" "); filters << tr("Audio Files (%1)").arg(extList.join(" ")); #if defined(WIN32) || defined(Q_OS_WIN) filters << tr("All Files (*.*)"); #else filters << tr("All Files (*)"); #endif dialog.setNameFilters(filters); /* Append useful URLs to the dialog */ QList <QUrl> sidebar; sidebar.append(QUrl::fromLocalFile(QDir::homePath())); sidebar.append(QUrl::fromLocalFile(QDir::rootPath())); dialog.setSidebarUrls(sidebar); /* Get file name */ if (dialog.exec() != QDialog::Accepted) return; fn = dialog.selectedFiles().first(); if (fn.isEmpty() == true) return; if (m_audio->isRunning()) m_audio->stopAndWait(); m_audio->setSourceFileName(fn); m_filenameLabel->setText(m_audio->getSourceFileName()); AudioDecoder *adec = m_audio->getAudioDecoder(); if (adec != NULL) { AudioParameters ap = adec->audioParameters(); m_durationLabel->setText(Function::speedToString(m_audio->totalDuration())); m_srateLabel->setText(QString("%1 Hz").arg(ap.sampleRate())); m_channelsLabel->setText(QString("%1").arg(ap.channels())); m_bitrateLabel->setText(QString("%1 kb/s").arg(adec->bitrate())); } } void AudioEditor::slotFadeInEdited() { uint newValue; QString text = m_fadeInEdit->text(); newValue = Function::stringToSpeed(text); m_fadeInEdit->setText(Function::speedToString(newValue)); m_audio->setFadeInSpeed(newValue); m_doc->setModified(); } void AudioEditor::slotFadeOutEdited() { uint newValue; QString text = m_fadeOutEdit->text(); newValue = Function::stringToSpeed(text); m_fadeOutEdit->setText(Function::speedToString(newValue)); m_audio->setFadeOutSpeed(newValue); m_doc->setModified(); } void AudioEditor::slotAudioDeviceChanged(int idx) { QString audioDev = m_audioDevCombo->itemData(idx).toString(); qDebug() << "New audio device selected:" << audioDev; if (audioDev == "__qlcplusdefault__") m_audio->setAudioDevice(QString()); else m_audio->setAudioDevice(audioDev); } void AudioEditor::slotPreviewToggled(bool state) { if (state == true) { m_audio->start(m_doc->masterTimer(), functionParent()); connect(m_audio, SIGNAL(stopped(quint32)), this, SLOT(slotPreviewStopped(quint32))); } else m_audio->stop(functionParent()); } void AudioEditor::slotPreviewStopped(quint32 id) { if (id == m_audio->id()) m_previewButton->setChecked(false); } void AudioEditor::slotSingleShotCheckClicked() { m_audio->setRunOrder(Audio::SingleShot); } void AudioEditor::slotLoopCheckClicked() { m_audio->setRunOrder(Audio::Loop); } FunctionParent AudioEditor::functionParent() const { return FunctionParent::master(); } /************************************************************************ * Speed dials ************************************************************************/ void AudioEditor::createSpeedDials() { if (m_speedDials != NULL) return; m_speedDials = new SpeedDialWidget(this); m_speedDials->setAttribute(Qt::WA_DeleteOnClose); m_speedDials->setWindowTitle(m_audio->name()); m_speedDials->setFadeInSpeed(m_audio->fadeInSpeed()); m_speedDials->setFadeOutSpeed(m_audio->fadeOutSpeed()); m_speedDials->setDurationEnabled(false); m_speedDials->setDurationVisible(false); connect(m_speedDials, SIGNAL(fadeInChanged(int)), this, SLOT(slotFadeInDialChanged(int))); connect(m_speedDials, SIGNAL(fadeOutChanged(int)), this, SLOT(slotFadeOutDialChanged(int))); connect(m_speedDials, SIGNAL(destroyed(QObject*)), this, SLOT(slotDialDestroyed(QObject*))); m_speedDials->show(); } void AudioEditor::slotSpeedDialToggle(bool state) { if (state == true) createSpeedDials(); else { if (m_speedDials != NULL) m_speedDials->deleteLater(); m_speedDials = NULL; } } void AudioEditor::slotFadeInDialChanged(int ms) { m_fadeInEdit->setText(Function::speedToString(ms)); m_audio->setFadeInSpeed(ms); } void AudioEditor::slotFadeOutDialChanged(int ms) { m_fadeOutEdit->setText(Function::speedToString(ms)); m_audio->setFadeOutSpeed(ms); } void AudioEditor::slotDialDestroyed(QObject *) { m_speedDialButton->setChecked(false); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // File contains modifications by: The Gulden developers // All modifications: // Copyright (c) 2016-2019 The Gulden developers // Authored by: Malcolm MacLeod (mmacleod@gmx.com) // Distributed under the GULDEN software license, see the accompanying // file COPYING #include "crypter.h" #include "crypto/sha512.h" #include "script/script.h" #include "script/standard.h" #include "util.h" #include <string> #include <vector> #include <cryptopp/config.h> #include <cryptopp/aes.h> #include <cryptopp/modes.h> int CCrypter::BytesToKeySHA512AES(const std::vector<unsigned char>& chSalt, const SecureString& strKeyData, int count, unsigned char *key,unsigned char *iv) const { // This mimics the behavior of openssl's EVP_BytesToKey with an aes256cbc // cipher and sha512 message digest. Because sha512's output size (64b) is // greater than the aes256 block size (16b) + aes256 key size (32b), // there's no need to process more than once (D_0). if(!count || !key || !iv) return 0; unsigned char buf[CSHA512::OUTPUT_SIZE]; CSHA512 di; di.Write((const unsigned char*)strKeyData.c_str(), strKeyData.size()); if(chSalt.size()) di.Write(&chSalt[0], chSalt.size()); di.Finalize(buf); for(int i = 0; i != count - 1; i++) di.Reset().Write(buf, sizeof(buf)).Finalize(buf); memcpy(key, buf, WALLET_CRYPTO_KEY_SIZE); memcpy(iv, buf + WALLET_CRYPTO_KEY_SIZE, WALLET_CRYPTO_IV_SIZE); memory_cleanse(buf, sizeof(buf)); return WALLET_CRYPTO_KEY_SIZE; } bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod) { if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE) return false; int i = 0; if (nDerivationMethod == 0) i = BytesToKeySHA512AES(chSalt, strKeyData, nRounds, vchKey.data(), vchIV.data()); if (i != (int)WALLET_CRYPTO_KEY_SIZE) { memory_cleanse(vchKey.data(), vchKey.size()); memory_cleanse(vchIV.data(), vchIV.size()); return false; } fKeySet = true; return true; } bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV) { if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_IV_SIZE) return false; memcpy(vchKey.data(), chNewKey.data(), chNewKey.size()); memcpy(vchIV.data(), chNewIV.data(), chNewIV.size()); fKeySet = true; return true; } bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext) const { if (!fKeySet) return false; // max ciphertext len for a n bytes of plaintext is // n + AES_BLOCKSIZE bytes vchCiphertext.resize(vchPlaintext.size() + CryptoPP::AES::BLOCKSIZE); //fixme: (SIGMA) CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption enc; //PAD? enc.SetKeyWithIV(vchKey.data(), vchKey.size(), vchIV.data()); enc.ProcessData(&vchCiphertext[0], &vchPlaintext[0], vchPlaintext.size()); //size_t nLen = enc.Encrypt(, ); //if(nLen < vchPlaintext.size()) //return false; //vchCiphertext.resize(nLen); return true; } bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) const { if (!fKeySet) return false; // plaintext will always be equal to or lesser than length of ciphertext int nLen = vchCiphertext.size(); vchPlaintext.resize(nLen); //fixme: (SIGMA) CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption dec; //PAD? dec.SetKeyWithIV(vchKey.data(), vchKey.size(), vchIV.data()); dec.ProcessData(&vchPlaintext[0], &vchCiphertext[0], vchCiphertext.size()); //if(nLen == 0) //return false; //vchPlaintext.resize(nLen); return true; } bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const std::vector<unsigned char>& nIV, std::vector<unsigned char> &vchCiphertext) { assert(nIV.size() == WALLET_CRYPTO_IV_SIZE); CCrypter cKeyCrypter; if(!cKeyCrypter.SetKey(vMasterKey, nIV)) return false; return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext); } bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext) { std::vector<unsigned char> chIV(WALLET_CRYPTO_IV_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_IV_SIZE); return EncryptSecret(vMasterKey, vchPlaintext, chIV, vchCiphertext); } bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const std::vector<unsigned char>& nIV, CKeyingMaterial& vchPlaintext) { assert(nIV.size() == WALLET_CRYPTO_IV_SIZE); CCrypter cKeyCrypter; if(!cKeyCrypter.SetKey(vMasterKey, nIV)) return false; return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext)); } bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext) { std::vector<unsigned char> chIV(WALLET_CRYPTO_IV_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_IV_SIZE); return DecryptSecret(vMasterKey, vchCiphertext, chIV, vchPlaintext); } static bool DecryptKey(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCryptedSecret, const CPubKey& vchPubKey, CKey& key) { CKeyingMaterial vchSecret; if(!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); return key.VerifyPubKey(vchPubKey); } bool CCryptoKeyStore::SetCrypted() { LOCK(cs_KeyStore); if (fUseCrypto) return true; if (!mapKeys.empty()) return false; fUseCrypto = true; return true; } bool CCryptoKeyStore::Lock() { if (!SetCrypted()) return false; { LOCK(cs_KeyStore); vMasterKey.clear(); } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn, bool& needsWriteToDisk) { needsWriteToDisk = false; { LOCK(cs_KeyStore); if (!SetCrypted()) return false; bool keyPass = false; bool keyFail = false; bool KeyNone = true; CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin(); for (; mi != mapCryptedKeys.end(); ++mi) { KeyNone = false; const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CKey key; if (!DecryptKey(vMasterKeyIn, vchCryptedSecret, vchPubKey, key)) { keyFail = true; break; } keyPass = true; if (fDecryptionThoroughlyChecked) break; } if (keyPass && keyFail) { LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n"); assert(false); } if (!KeyNone && (keyFail || !keyPass)) return false; vMasterKey = vMasterKeyIn; fDecryptionThoroughlyChecked = true; } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey &pubkey) { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::AddKeyPubKey(key, pubkey); if (IsLocked()) return false; std::vector<unsigned char> vchCryptedSecret; CKeyingMaterial vchSecret(key.begin(), key.end()); if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(pubkey, vchCryptedSecret)) return false; } return true; } bool CCryptoKeyStore::AddKeyPubKey(int64_t HDKeyIndex, const CPubKey &pubkey) { // For HD we don't encrypt anything here - as the public key we need access to anyway, and the index is not special info - we derive the private key when we need it. { LOCK(cs_KeyStore); return CBasicKeyStore::AddKeyPubKey(HDKeyIndex, pubkey); } } bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; mapCryptedKeys[vchPubKey.GetID()] = std::pair(vchPubKey, vchCryptedSecret); } return true; } bool CCryptoKeyStore::GetKey(const CKeyID &address, std::vector<unsigned char>& encryptedKeyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return false; CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { encryptedKeyOut = (*mi).second.second; return true; } } return false; } bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::GetKey(address, keyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; return DecryptKey(vMasterKey, vchCryptedSecret, vchPubKey, keyOut); } } return false; } bool CCryptoKeyStore::GetKey(const CKeyID &address, int64_t& HDKeyIndex) const { // For HD we don't encrypt anything here - as the public key we need access to anyway, and the index is not special info - we derive the private key when we need it. { LOCK(cs_KeyStore); return CBasicKeyStore::GetKey(address, HDKeyIndex); } } bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::GetPubKey(address, vchPubKeyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { vchPubKeyOut = (*mi).second.first; return true; } // Check for watch-only pubkeys return CBasicKeyStore::GetPubKey(address, vchPubKeyOut); } return false; } bool CCryptoKeyStore::EncryptKeys(const CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!mapCryptedKeys.empty() || IsCrypted()) return false; fUseCrypto = true; for(KeyMap::value_type& mKey : mapKeys) { const CKey &key = mKey.second; CPubKey vchPubKey = key.GetPubKey(); CKeyingMaterial vchSecret(key.begin(), key.end()); std::vector<unsigned char> vchCryptedSecret; if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; } mapKeys.clear(); } return true; } <commit_msg>CORE: Fix wallet crypter to work with cryptopp<commit_after>// Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // File contains modifications by: The Gulden developers // All modifications: // Copyright (c) 2016-2019 The Gulden developers // Authored by: Malcolm MacLeod (mmacleod@gmx.com) // Distributed under the GULDEN software license, see the accompanying // file COPYING #include "crypter.h" #include "crypto/sha512.h" #include "script/script.h" #include "script/standard.h" #include "util.h" #include <string> #include <vector> #include <cryptopp/config.h> #include <cryptopp/aes.h> #include <cryptopp/modes.h> #include <cryptopp/filters.h> int CCrypter::BytesToKeySHA512AES(const std::vector<unsigned char>& chSalt, const SecureString& strKeyData, int count, unsigned char *key,unsigned char *iv) const { // This mimics the behavior of openssl's EVP_BytesToKey with an aes256cbc // cipher and sha512 message digest. Because sha512's output size (64b) is // greater than the aes256 block size (16b) + aes256 key size (32b), // there's no need to process more than once (D_0). if(!count || !key || !iv) return 0; unsigned char buf[CSHA512::OUTPUT_SIZE]; CSHA512 di; di.Write((const unsigned char*)strKeyData.c_str(), strKeyData.size()); if(chSalt.size()) di.Write(&chSalt[0], chSalt.size()); di.Finalize(buf); for(int i = 0; i != count - 1; i++) di.Reset().Write(buf, sizeof(buf)).Finalize(buf); memcpy(key, buf, WALLET_CRYPTO_KEY_SIZE); memcpy(iv, buf + WALLET_CRYPTO_KEY_SIZE, WALLET_CRYPTO_IV_SIZE); memory_cleanse(buf, sizeof(buf)); return WALLET_CRYPTO_KEY_SIZE; } bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod) { if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE) return false; int i = 0; if (nDerivationMethod == 0) i = BytesToKeySHA512AES(chSalt, strKeyData, nRounds, vchKey.data(), vchIV.data()); if (i != (int)WALLET_CRYPTO_KEY_SIZE) { memory_cleanse(vchKey.data(), vchKey.size()); memory_cleanse(vchIV.data(), vchIV.size()); return false; } fKeySet = true; return true; } bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV) { if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_IV_SIZE) return false; memcpy(vchKey.data(), chNewKey.data(), chNewKey.size()); memcpy(vchIV.data(), chNewIV.data(), chNewIV.size()); fKeySet = true; return true; } bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext) const { if (!fKeySet) return false; // max ciphertext len for a n bytes of plaintext is // n + AES_BLOCKSIZE bytes //vchCiphertext.resize(vchPlaintext.size() + CryptoPP::AES::BLOCKSIZE); CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption enc; enc.SetKeyWithIV(vchKey.data(), vchKey.size(), vchIV.data()); try { CryptoPP::ArraySource s(&vchPlaintext[0], vchPlaintext.size(), true, new CryptoPP::StreamTransformationFilter(enc, new CryptoPP::VectorSink(vchCiphertext))); } catch(...) { return false; } return true; } bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) const { if (!fKeySet) return false; // plaintext will always be equal to or lesser than length of ciphertext int nLen = vchCiphertext.size(); vchPlaintext.resize(nLen); CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption dec; dec.SetKeyWithIV(vchKey.data(), vchKey.size(), vchIV.data()); try { auto sink = new CryptoPP::ArraySink(&vchPlaintext[0], vchPlaintext.size()); CryptoPP::VectorSource s(vchCiphertext, true, new CryptoPP::StreamTransformationFilter(dec, sink)); // Trim plaintext to original length vchPlaintext.resize(sink->TotalPutLength()); } catch(...) { return false; } return true; } bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const std::vector<unsigned char>& nIV, std::vector<unsigned char> &vchCiphertext) { assert(nIV.size() == WALLET_CRYPTO_IV_SIZE); CCrypter cKeyCrypter; if(!cKeyCrypter.SetKey(vMasterKey, nIV)) return false; return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext); } bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext) { std::vector<unsigned char> chIV(WALLET_CRYPTO_IV_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_IV_SIZE); return EncryptSecret(vMasterKey, vchPlaintext, chIV, vchCiphertext); } bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const std::vector<unsigned char>& nIV, CKeyingMaterial& vchPlaintext) { assert(nIV.size() == WALLET_CRYPTO_IV_SIZE); CCrypter cKeyCrypter; if(!cKeyCrypter.SetKey(vMasterKey, nIV)) return false; return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext)); } bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext) { std::vector<unsigned char> chIV(WALLET_CRYPTO_IV_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_IV_SIZE); return DecryptSecret(vMasterKey, vchCiphertext, chIV, vchPlaintext); } static bool DecryptKey(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCryptedSecret, const CPubKey& vchPubKey, CKey& key) { CKeyingMaterial vchSecret; if(!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); return key.VerifyPubKey(vchPubKey); } bool CCryptoKeyStore::SetCrypted() { LOCK(cs_KeyStore); if (fUseCrypto) return true; if (!mapKeys.empty()) return false; fUseCrypto = true; return true; } bool CCryptoKeyStore::Lock() { if (!SetCrypted()) return false; { LOCK(cs_KeyStore); vMasterKey.clear(); } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn, bool& needsWriteToDisk) { needsWriteToDisk = false; { LOCK(cs_KeyStore); if (!SetCrypted()) return false; bool keyPass = false; bool keyFail = false; bool KeyNone = true; CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin(); for (; mi != mapCryptedKeys.end(); ++mi) { KeyNone = false; const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CKey key; if (!DecryptKey(vMasterKeyIn, vchCryptedSecret, vchPubKey, key)) { keyFail = true; break; } keyPass = true; if (fDecryptionThoroughlyChecked) break; } if (keyPass && keyFail) { LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n"); assert(false); } if (!KeyNone && (keyFail || !keyPass)) return false; vMasterKey = vMasterKeyIn; fDecryptionThoroughlyChecked = true; } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey &pubkey) { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::AddKeyPubKey(key, pubkey); if (IsLocked()) return false; std::vector<unsigned char> vchCryptedSecret; CKeyingMaterial vchSecret(key.begin(), key.end()); if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(pubkey, vchCryptedSecret)) return false; } return true; } bool CCryptoKeyStore::AddKeyPubKey(int64_t HDKeyIndex, const CPubKey &pubkey) { // For HD we don't encrypt anything here - as the public key we need access to anyway, and the index is not special info - we derive the private key when we need it. { LOCK(cs_KeyStore); return CBasicKeyStore::AddKeyPubKey(HDKeyIndex, pubkey); } } bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; mapCryptedKeys[vchPubKey.GetID()] = std::pair(vchPubKey, vchCryptedSecret); } return true; } bool CCryptoKeyStore::GetKey(const CKeyID &address, std::vector<unsigned char>& encryptedKeyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return false; CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { encryptedKeyOut = (*mi).second.second; return true; } } return false; } bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::GetKey(address, keyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; return DecryptKey(vMasterKey, vchCryptedSecret, vchPubKey, keyOut); } } return false; } bool CCryptoKeyStore::GetKey(const CKeyID &address, int64_t& HDKeyIndex) const { // For HD we don't encrypt anything here - as the public key we need access to anyway, and the index is not special info - we derive the private key when we need it. { LOCK(cs_KeyStore); return CBasicKeyStore::GetKey(address, HDKeyIndex); } } bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::GetPubKey(address, vchPubKeyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { vchPubKeyOut = (*mi).second.first; return true; } // Check for watch-only pubkeys return CBasicKeyStore::GetPubKey(address, vchPubKeyOut); } return false; } bool CCryptoKeyStore::EncryptKeys(const CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!mapCryptedKeys.empty() || IsCrypted()) return false; fUseCrypto = true; for(KeyMap::value_type& mKey : mapKeys) { const CKey &key = mKey.second; CPubKey vchPubKey = key.GetPubKey(); CKeyingMaterial vchSecret(key.begin(), key.end()); std::vector<unsigned char> vchCryptedSecret; if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; } mapKeys.clear(); } return true; } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/datastructures/volume/volume.h> #include <inviwo/core/datastructures/volume/volumedisk.h> #include <inviwo/core/datastructures/volume/volumeram.h> #include <inviwo/core/util/tooltiphelper.h> namespace inviwo { Volume::Volume(size3_t dimensions, const DataFormatBase* format) : Data<VolumeRepresentation>(format), StructuredGridEntity<3>(dimensions), dataMap_(format) {} Volume::Volume(const Volume& rhs) : Data<VolumeRepresentation>(rhs), StructuredGridEntity<3>(rhs), dataMap_(rhs.dataMap_) {} Volume::Volume(std::shared_ptr<VolumeRepresentation> in) : Data<VolumeRepresentation>(in->getDataFormat()) , StructuredGridEntity<3>(in->getDimensions()) , dataMap_(in->getDataFormat()) { addRepresentation(in); } Volume& Volume::operator=(const Volume& that) { if (this != &that) { Data<VolumeRepresentation>::operator=(that); StructuredGridEntity<3>::operator=(that); dataMap_ = that.dataMap_; } return *this; } Volume* Volume::clone() const { return new Volume(*this); } Volume::~Volume() {} std::string Volume::getDataInfo() const { ToolTipHelper t("Volume"); t.tableTop(); t.row("Format", getDataFormat()->getString()); t.row("Dimension", toString(getDimensions())); t.row("Data Range", toString(dataMap_.dataRange)); t.row("Value Range", toString(dataMap_.valueRange)); if (hasRepresentation<VolumeRAM>()) { auto volumeRAM = getRepresentation<VolumeRAM>(); if (volumeRAM->hasHistograms()) { auto histograms = volumeRAM->getHistograms(); for (size_t i = 0; i < histograms->size(); ++i) { std::stringstream ss; ss << "Channel " << i << " Min: " << (*histograms)[i].stats_.min << " Mean: " << (*histograms)[i].stats_.mean << " Max: " << (*histograms)[i].stats_.max << " Std: " << (*histograms)[i].stats_.standardDeviation; t.row("Stats", ss.str()); std::stringstream ss2; ss2 << "(1: " << (*histograms)[i].stats_.percentiles[1] << ", 25: " << (*histograms)[i].stats_.percentiles[25] << ", 50: " << (*histograms)[i].stats_.percentiles[50] << ", 75: " << (*histograms)[i].stats_.percentiles[75] << ", 99: " << (*histograms)[i].stats_.percentiles[99] << ")"; t.row("Percentiles", ss2.str()); } } } t.tableBottom(); return t; } size3_t Volume::getDimensions() const { if (hasRepresentations() && lastValidRepresentation_) { return lastValidRepresentation_->getDimensions(); } return StructuredGridEntity<3>::getDimensions(); } void Volume::setDimensions(const size3_t& dim) { StructuredGridEntity<3>::setDimensions(dim); if (lastValidRepresentation_) { // Resize last valid representation lastValidRepresentation_->setDimensions(dim); removeOtherRepresentations(lastValidRepresentation_.get()); } } void Volume::setOffset(const vec3& offset) { SpatialEntity<3>::setOffset(Vector<3, float>(offset)); } vec3 Volume::getOffset() const { return SpatialEntity<3>::getOffset(); } mat3 Volume::getBasis() const { return SpatialEntity<3>::getBasis(); } void Volume::setBasis(const mat3& basis) { SpatialEntity<3>::setBasis(Matrix<3, float>(basis)); } mat4 Volume::getModelMatrix() const { return SpatialEntity<3>::getModelMatrix(); } void Volume::setModelMatrix(const mat4& mat) { SpatialEntity<3>::setModelMatrix(Matrix<4, float>(mat)); } mat4 Volume::getWorldMatrix() const { return SpatialEntity<3>::getWorldMatrix(); } void Volume::setWorldMatrix(const mat4& mat) { SpatialEntity<3>::setWorldMatrix(Matrix<4, float>(mat)); } std::shared_ptr<VolumeRepresentation> Volume::createDefaultRepresentation() const { return createVolumeRAM(getDimensions(), getDataFormat()); } float Volume::getWorldSpaceGradientSpacing() const { mat3 textureToWorld = mat3(getCoordinateTransformer().getTextureToWorldMatrix()); // Find the maximum distance we can go from the center of a voxel without ending up outside the voxel // Shorten each basis to the distance from one voxel to the next mat3 voxelSpaceBasis; for (int dim = 0; dim < 3; ++dim) { voxelSpaceBasis[dim] = textureToWorld[dim]/static_cast<float>(getDimensions()[dim]); } // Find the distance three of the sides of a voxel // Project x-axis onto the y-axis. // Distance from that point to the x-axis will be the shortest distance vec3 distanceToSide; // Project x onto y axis, x onto z axis and y onto z axis vec3 xOntoY = voxelSpaceBasis[1]*glm::dot(voxelSpaceBasis[0], voxelSpaceBasis[1]); vec3 xOntoZ = voxelSpaceBasis[2]*glm::dot(voxelSpaceBasis[0], voxelSpaceBasis[2]); vec3 yOntoZ = voxelSpaceBasis[2]*glm::dot(voxelSpaceBasis[1], voxelSpaceBasis[2]); distanceToSide[0] = glm::distance(voxelSpaceBasis[0], xOntoY); distanceToSide[1] = glm::distance(voxelSpaceBasis[0], xOntoZ); distanceToSide[2] = glm::distance(voxelSpaceBasis[1], yOntoZ); // From the center of the voxel we can go half of the minimum distance without going outside float minimumDistance = 0.5f*std::min(distanceToSide[0], std::min(distanceToSide[1], distanceToSide[2])); // Return the minimum distance we can travel along each basis return minimumDistance; } inviwo::uvec3 Volume::COLOR_CODE = uvec3(188, 101, 101); const std::string Volume::CLASS_IDENTIFIER = "org.inviwo.Volume"; const StructuredCameraCoordinateTransformer<3>& Volume::getCoordinateTransformer( const Camera& camera) const { return StructuredGridEntity<3>::getCoordinateTransformer(camera); } } // namespace<commit_msg>Include fix<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/datastructures/volume/volume.h> #include <inviwo/core/datastructures/volume/volumedisk.h> #include <inviwo/core/datastructures/volume/volumeram.h> #include <inviwo/core/datastructures/volume/volumeramprecision.h> #include <inviwo/core/util/tooltiphelper.h> namespace inviwo { Volume::Volume(size3_t dimensions, const DataFormatBase* format) : Data<VolumeRepresentation>(format), StructuredGridEntity<3>(dimensions), dataMap_(format) {} Volume::Volume(const Volume& rhs) : Data<VolumeRepresentation>(rhs), StructuredGridEntity<3>(rhs), dataMap_(rhs.dataMap_) {} Volume::Volume(std::shared_ptr<VolumeRepresentation> in) : Data<VolumeRepresentation>(in->getDataFormat()) , StructuredGridEntity<3>(in->getDimensions()) , dataMap_(in->getDataFormat()) { addRepresentation(in); } Volume& Volume::operator=(const Volume& that) { if (this != &that) { Data<VolumeRepresentation>::operator=(that); StructuredGridEntity<3>::operator=(that); dataMap_ = that.dataMap_; } return *this; } Volume* Volume::clone() const { return new Volume(*this); } Volume::~Volume() {} std::string Volume::getDataInfo() const { ToolTipHelper t("Volume"); t.tableTop(); t.row("Format", getDataFormat()->getString()); t.row("Dimension", toString(getDimensions())); t.row("Data Range", toString(dataMap_.dataRange)); t.row("Value Range", toString(dataMap_.valueRange)); if (hasRepresentation<VolumeRAM>()) { auto volumeRAM = getRepresentation<VolumeRAM>(); if (volumeRAM->hasHistograms()) { auto histograms = volumeRAM->getHistograms(); for (size_t i = 0; i < histograms->size(); ++i) { std::stringstream ss; ss << "Channel " << i << " Min: " << (*histograms)[i].stats_.min << " Mean: " << (*histograms)[i].stats_.mean << " Max: " << (*histograms)[i].stats_.max << " Std: " << (*histograms)[i].stats_.standardDeviation; t.row("Stats", ss.str()); std::stringstream ss2; ss2 << "(1: " << (*histograms)[i].stats_.percentiles[1] << ", 25: " << (*histograms)[i].stats_.percentiles[25] << ", 50: " << (*histograms)[i].stats_.percentiles[50] << ", 75: " << (*histograms)[i].stats_.percentiles[75] << ", 99: " << (*histograms)[i].stats_.percentiles[99] << ")"; t.row("Percentiles", ss2.str()); } } } t.tableBottom(); return t; } size3_t Volume::getDimensions() const { if (hasRepresentations() && lastValidRepresentation_) { return lastValidRepresentation_->getDimensions(); } return StructuredGridEntity<3>::getDimensions(); } void Volume::setDimensions(const size3_t& dim) { StructuredGridEntity<3>::setDimensions(dim); if (lastValidRepresentation_) { // Resize last valid representation lastValidRepresentation_->setDimensions(dim); removeOtherRepresentations(lastValidRepresentation_.get()); } } void Volume::setOffset(const vec3& offset) { SpatialEntity<3>::setOffset(Vector<3, float>(offset)); } vec3 Volume::getOffset() const { return SpatialEntity<3>::getOffset(); } mat3 Volume::getBasis() const { return SpatialEntity<3>::getBasis(); } void Volume::setBasis(const mat3& basis) { SpatialEntity<3>::setBasis(Matrix<3, float>(basis)); } mat4 Volume::getModelMatrix() const { return SpatialEntity<3>::getModelMatrix(); } void Volume::setModelMatrix(const mat4& mat) { SpatialEntity<3>::setModelMatrix(Matrix<4, float>(mat)); } mat4 Volume::getWorldMatrix() const { return SpatialEntity<3>::getWorldMatrix(); } void Volume::setWorldMatrix(const mat4& mat) { SpatialEntity<3>::setWorldMatrix(Matrix<4, float>(mat)); } std::shared_ptr<VolumeRepresentation> Volume::createDefaultRepresentation() const { return createVolumeRAM(getDimensions(), getDataFormat()); } float Volume::getWorldSpaceGradientSpacing() const { mat3 textureToWorld = mat3(getCoordinateTransformer().getTextureToWorldMatrix()); // Find the maximum distance we can go from the center of a voxel without ending up outside the voxel // Shorten each basis to the distance from one voxel to the next mat3 voxelSpaceBasis; for (int dim = 0; dim < 3; ++dim) { voxelSpaceBasis[dim] = textureToWorld[dim]/static_cast<float>(getDimensions()[dim]); } // Find the distance three of the sides of a voxel // Project x-axis onto the y-axis. // Distance from that point to the x-axis will be the shortest distance vec3 distanceToSide; // Project x onto y axis, x onto z axis and y onto z axis vec3 xOntoY = voxelSpaceBasis[1]*glm::dot(voxelSpaceBasis[0], voxelSpaceBasis[1]); vec3 xOntoZ = voxelSpaceBasis[2]*glm::dot(voxelSpaceBasis[0], voxelSpaceBasis[2]); vec3 yOntoZ = voxelSpaceBasis[2]*glm::dot(voxelSpaceBasis[1], voxelSpaceBasis[2]); distanceToSide[0] = glm::distance(voxelSpaceBasis[0], xOntoY); distanceToSide[1] = glm::distance(voxelSpaceBasis[0], xOntoZ); distanceToSide[2] = glm::distance(voxelSpaceBasis[1], yOntoZ); // From the center of the voxel we can go half of the minimum distance without going outside float minimumDistance = 0.5f*std::min(distanceToSide[0], std::min(distanceToSide[1], distanceToSide[2])); // Return the minimum distance we can travel along each basis return minimumDistance; } inviwo::uvec3 Volume::COLOR_CODE = uvec3(188, 101, 101); const std::string Volume::CLASS_IDENTIFIER = "org.inviwo.Volume"; const StructuredCameraCoordinateTransformer<3>& Volume::getCoordinateTransformer( const Camera& camera) const { return StructuredGridEntity<3>::getCoordinateTransformer(camera); } } // namespace<|endoftext|>
<commit_before>/* Copyright 2014 Peter Goodman, all rights reserved. */ #define GRANARY_INTERNAL #include "granary/base/option.h" #include "granary/base/string.h" #include "granary/breakpoint.h" #include "granary/logging.h" namespace granary { namespace { enum { MAX_NUM_OPTIONS = 32, MAX_OPTIONS_LENGTH = 1024 - 1 }; // Linked list of registered options. Option *OPTIONS = nullptr; bool OPTIONS_INITIALIZED = false; // Copy of the option string. static int OPTION_STRING_LENGTH = 0; static char OPTION_STRING[MAX_OPTIONS_LENGTH + 1] = {'\0'}; static const char *OPTION_NAMES[MAX_NUM_OPTIONS] = {nullptr}; static const char *OPTION_VALUES[MAX_NUM_OPTIONS] = {nullptr}; // Copy a substring into the main options string. static int CopyStringIntoOptions(int offset, const char *string) { for (; offset < MAX_OPTIONS_LENGTH && *string; ++string) { OPTION_STRING[offset++] = *string; } return offset; } // Finalize the option string. static void TerminateOptionString(int length) { GRANARY_ASSERT(MAX_OPTIONS_LENGTH > length); OPTION_STRING[length] = '\0'; OPTION_STRING_LENGTH = length; } // Check that a character is a valid option character. static bool IsValidOptionChar(char ch) { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('_' == ch); } // Check that a character is a valid option character. static bool IsValidValueChar(char ch) { return ' ' < ch && ch <= '~' && '[' != ch && ']' != ch; } // Format an option string into a more amenable internal format. This is a sort // of pre-processing step to distinguish options from values. static void ProcessOptionString(void) { char *ch(&OPTION_STRING[0]); char * const max_ch(&OPTION_STRING[OPTION_STRING_LENGTH]); unsigned num_options(0); enum { IN_OPTION, IN_VALUE, IN_LITERAL_VALUE, SEEN_EQUAL, SEEN_DASH, ELSEWHERE } state = ELSEWHERE; for (; ch < max_ch; ++ch) { switch (state) { case IN_OPTION: { const char ch_val = *ch; // Terminate the option name. if (!IsValidOptionChar(ch_val)) { state = ELSEWHERE; *ch = '\0'; } // We've seen an equal, which mean's we're moving into the // beginning of a value. if ('=' == ch_val) { state = SEEN_EQUAL; } break; } case IN_VALUE: if (!IsValidValueChar(*ch)) { state = ELSEWHERE; *ch = '\0'; } break; case IN_LITERAL_VALUE: if (']' == *ch) { state = ELSEWHERE; *ch = '\0'; } else if (' ' != *ch) { GRANARY_ASSERT(IsValidValueChar(*ch)); } break; case SEEN_EQUAL: if ('[' == *ch) { // E.g. `--tools=[bbcount:pgo]`. *ch = '\0'; state = IN_LITERAL_VALUE; OPTION_VALUES[num_options - 1] = ch + 1; } else if (IsValidValueChar(*ch)) { // E.g. `--tools=bbcount`. state = IN_VALUE; OPTION_VALUES[num_options - 1] = ch; } else { // E.g. `--tools=`. state = ELSEWHERE; } break; case SEEN_DASH: if ('-' == *ch) { state = IN_OPTION; GRANARY_ASSERT(MAX_NUM_OPTIONS > num_options); OPTION_VALUES[num_options] = ""; // Default to positional. OPTION_NAMES[num_options++] = ch + 1; } else { state = ELSEWHERE; } *ch = '\0'; break; case ELSEWHERE: if ('-' == *ch) { state = SEEN_DASH; } *ch = '\0'; break; } } } // Returns a pointer to the value for an option name, or a nullptr if the option // name was not found (or if it was specified but had no value). const char *FindValueForName(const char *name) { for (int i(0); i < MAX_NUM_OPTIONS && OPTION_NAMES[i]; ++i) { if (StringsMatch(OPTION_NAMES[i], name)) { return OPTION_VALUES[i]; } } return nullptr; } // Process the pending options. Pending options represent internal Granary // options. static void ProcessPendingOptions(void) { for (auto option : OptionIterator(OPTIONS)) { option->parse(option); } } } // namespace // Initialize the options from an environment variable. void InitOptions(const char *env) { TerminateOptionString(CopyStringIntoOptions(0, env)); ProcessOptionString(); OPTIONS_INITIALIZED = true; ProcessPendingOptions(); } // Initialize the options from the command-line arguments. void InitOptions(int argc, const char **argv) { int offset(0); int arg(1); for (const char *sep(""); arg < argc; ++arg, sep = " ") { offset = CopyStringIntoOptions(offset, sep); offset = CopyStringIntoOptions(offset, argv[arg]); } TerminateOptionString(offset); ProcessOptionString(); OPTIONS_INITIALIZED = true; ProcessPendingOptions(); } namespace { enum { LINE_LENGTH = 80, TAB_LENGTH = 8, BUFFER_MAX_LENGTH = LINE_LENGTH - TAB_LENGTH }; // Perform line buffering of the document string. static const char *BufferDocString(char *buff, const char *docstring) { auto last_stop = buff; auto docstring_last_stop = docstring; auto docstring_stop = docstring + BUFFER_MAX_LENGTH; for (; docstring < docstring_stop && *docstring; ) { if (' ' == *docstring) { last_stop = buff; docstring_last_stop = docstring + 1; } else if ('\n' == *docstring) { last_stop = buff; docstring_last_stop = docstring + 1; break; } *buff++ = *docstring++; } if (docstring < docstring_stop && !*docstring) { *buff = '\0'; return docstring; } else { *last_stop = '\0'; return docstring_last_stop; } } } // namespace // Works for --help option: print out each options along with their document. void PrintAllOptions(void) { Log(LogOutput, "Usage for user space: granary.out clients-and-tools-and" "-args\n\n"); char line_buff[LINE_LENGTH]; for (auto option : OptionIterator(OPTIONS)) { Log(LogOutput, "--\033[1m%s\033[m", option->name); auto docstring = option->docstring; do { docstring = BufferDocString(line_buff, docstring); Log(LogOutput, "\n %s", line_buff); } while (*docstring); Log(LogOutput, "\n"); } } namespace detail { // Initialize an option. void RegisterOption(Option *option) { if (OPTIONS_INITIALIZED) { option->parse(option); // Client/tool options. } if (!option->next) { option->next = OPTIONS; OPTIONS = option; } } // Parse an option that is a string. void ParseStringOption(Option *option) { auto value = FindValueForName(option->name); if (value) { *reinterpret_cast<const char **>(option->value) = value; } } // Parse an option that will be interpreted as a boolean value. void ParseBoolOption(Option *option) { auto value = FindValueForName(option->name); if (value) { switch (*value) { case '1': case 'y': case 'Y': case 't': case 'T': case '\0': *reinterpret_cast<bool *>(option->value) = true; break; case '0': case 'n': case 'N': case 'f': case 'F': *reinterpret_cast<bool *>(option->value) = false; break; default: break; } } } // Parse an option that will be interpreted as an unsigned integer but stored // as a signed integer. void ParsePositiveIntOption(Option *option) { auto value = FindValueForName(option->name); if (value) { int int_value(0); DeFormat(value, "%u", reinterpret_cast<unsigned *>(&int_value)); if (0 < int_value) { *reinterpret_cast<int *>(option->value) = int_value; } } } } // namespace detail } // namespace granary <commit_msg>Okay, that's it for useless busy work. Make it so that the option printer displays one thing in stand-alone mode, another in takeover mode, and will generate a compiler error (for the time being) in kernel mode.<commit_after>/* Copyright 2014 Peter Goodman, all rights reserved. */ #define GRANARY_INTERNAL #include "granary/base/option.h" #include "granary/base/string.h" #include "granary/breakpoint.h" #include "granary/logging.h" namespace granary { namespace { enum { MAX_NUM_OPTIONS = 32, MAX_OPTIONS_LENGTH = 1024 - 1 }; // Linked list of registered options. Option *OPTIONS = nullptr; bool OPTIONS_INITIALIZED = false; // Copy of the option string. static int OPTION_STRING_LENGTH = 0; static char OPTION_STRING[MAX_OPTIONS_LENGTH + 1] = {'\0'}; static const char *OPTION_NAMES[MAX_NUM_OPTIONS] = {nullptr}; static const char *OPTION_VALUES[MAX_NUM_OPTIONS] = {nullptr}; // Copy a substring into the main options string. static int CopyStringIntoOptions(int offset, const char *string) { for (; offset < MAX_OPTIONS_LENGTH && *string; ++string) { OPTION_STRING[offset++] = *string; } return offset; } // Finalize the option string. static void TerminateOptionString(int length) { GRANARY_ASSERT(MAX_OPTIONS_LENGTH > length); OPTION_STRING[length] = '\0'; OPTION_STRING_LENGTH = length; } // Check that a character is a valid option character. static bool IsValidOptionChar(char ch) { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('_' == ch); } // Check that a character is a valid option character. static bool IsValidValueChar(char ch) { return ' ' < ch && ch <= '~' && '[' != ch && ']' != ch; } // Format an option string into a more amenable internal format. This is a sort // of pre-processing step to distinguish options from values. static void ProcessOptionString(void) { char *ch(&OPTION_STRING[0]); char * const max_ch(&OPTION_STRING[OPTION_STRING_LENGTH]); unsigned num_options(0); enum { IN_OPTION, IN_VALUE, IN_LITERAL_VALUE, SEEN_EQUAL, SEEN_DASH, ELSEWHERE } state = ELSEWHERE; for (; ch < max_ch; ++ch) { switch (state) { case IN_OPTION: { const char ch_val = *ch; // Terminate the option name. if (!IsValidOptionChar(ch_val)) { state = ELSEWHERE; *ch = '\0'; } // We've seen an equal, which mean's we're moving into the // beginning of a value. if ('=' == ch_val) { state = SEEN_EQUAL; } break; } case IN_VALUE: if (!IsValidValueChar(*ch)) { state = ELSEWHERE; *ch = '\0'; } break; case IN_LITERAL_VALUE: if (']' == *ch) { state = ELSEWHERE; *ch = '\0'; } else if (' ' != *ch) { GRANARY_ASSERT(IsValidValueChar(*ch)); } break; case SEEN_EQUAL: if ('[' == *ch) { // E.g. `--tools=[bbcount:pgo]`. *ch = '\0'; state = IN_LITERAL_VALUE; OPTION_VALUES[num_options - 1] = ch + 1; } else if (IsValidValueChar(*ch)) { // E.g. `--tools=bbcount`. state = IN_VALUE; OPTION_VALUES[num_options - 1] = ch; } else { // E.g. `--tools=`. state = ELSEWHERE; } break; case SEEN_DASH: if ('-' == *ch) { state = IN_OPTION; GRANARY_ASSERT(MAX_NUM_OPTIONS > num_options); OPTION_VALUES[num_options] = ""; // Default to positional. OPTION_NAMES[num_options++] = ch + 1; } else { state = ELSEWHERE; } *ch = '\0'; break; case ELSEWHERE: if ('-' == *ch) { state = SEEN_DASH; } *ch = '\0'; break; } } } // Returns a pointer to the value for an option name, or a nullptr if the option // name was not found (or if it was specified but had no value). const char *FindValueForName(const char *name) { for (int i(0); i < MAX_NUM_OPTIONS && OPTION_NAMES[i]; ++i) { if (StringsMatch(OPTION_NAMES[i], name)) { return OPTION_VALUES[i]; } } return nullptr; } // Process the pending options. Pending options represent internal Granary // options. static void ProcessPendingOptions(void) { for (auto option : OptionIterator(OPTIONS)) { option->parse(option); } } } // namespace // Initialize the options from an environment variable. void InitOptions(const char *env) { TerminateOptionString(CopyStringIntoOptions(0, env)); ProcessOptionString(); OPTIONS_INITIALIZED = true; ProcessPendingOptions(); } // Initialize the options from the command-line arguments. void InitOptions(int argc, const char **argv) { int offset(0); int arg(1); for (const char *sep(""); arg < argc; ++arg, sep = " ") { offset = CopyStringIntoOptions(offset, sep); offset = CopyStringIntoOptions(offset, argv[arg]); } TerminateOptionString(offset); ProcessOptionString(); OPTIONS_INITIALIZED = true; ProcessPendingOptions(); } namespace { enum { LINE_LENGTH = 80, TAB_LENGTH = 8, BUFFER_MAX_LENGTH = LINE_LENGTH - TAB_LENGTH }; // Perform line buffering of the document string. static const char *BufferDocString(char *buff, const char *docstring) { auto last_stop = buff; auto docstring_last_stop = docstring; auto docstring_stop = docstring + BUFFER_MAX_LENGTH; for (; docstring < docstring_stop && *docstring; ) { if (' ' == *docstring) { last_stop = buff; docstring_last_stop = docstring + 1; } else if ('\n' == *docstring) { last_stop = buff; docstring_last_stop = docstring + 1; break; } *buff++ = *docstring++; } if (docstring < docstring_stop && !*docstring) { *buff = '\0'; return docstring; } else { *last_stop = '\0'; return docstring_last_stop; } } } // namespace // Works for --help option: print out each options along with their document. void PrintAllOptions(void) { #ifdef GRANARY_WHERE_user # ifdef GRANARY_STANDALONE Log(LogOutput, "Usage for user space: granary.out <options>\n\n"); # else Log(LogOutput, "Usage for user space: grr <options> -- <executable>\n\n"); # endif // GRANARY_STANDALONE #else # error "Option printing is not well-defined for kernel space." #endif char line_buff[LINE_LENGTH]; for (auto option : OptionIterator(OPTIONS)) { Log(LogOutput, "--\033[1m%s\033[m", option->name); auto docstring = option->docstring; do { docstring = BufferDocString(line_buff, docstring); Log(LogOutput, "\n %s", line_buff); } while (*docstring); Log(LogOutput, "\n"); } } namespace detail { // Initialize an option. void RegisterOption(Option *option) { if (OPTIONS_INITIALIZED) { option->parse(option); // Client/tool options. } if (!option->next) { option->next = OPTIONS; OPTIONS = option; } } // Parse an option that is a string. void ParseStringOption(Option *option) { auto value = FindValueForName(option->name); if (value) { *reinterpret_cast<const char **>(option->value) = value; } } // Parse an option that will be interpreted as a boolean value. void ParseBoolOption(Option *option) { auto value = FindValueForName(option->name); if (value) { switch (*value) { case '1': case 'y': case 'Y': case 't': case 'T': case '\0': *reinterpret_cast<bool *>(option->value) = true; break; case '0': case 'n': case 'N': case 'f': case 'F': *reinterpret_cast<bool *>(option->value) = false; break; default: break; } } } // Parse an option that will be interpreted as an unsigned integer but stored // as a signed integer. void ParsePositiveIntOption(Option *option) { auto value = FindValueForName(option->name); if (value) { int int_value(0); DeFormat(value, "%u", reinterpret_cast<unsigned *>(&int_value)); if (0 < int_value) { *reinterpret_cast<int *>(option->value) = int_value; } } } } // namespace detail } // namespace granary <|endoftext|>
<commit_before>// // Copyright (c) 2017 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ExtensionBehavior.cpp: Extension name enumeration and data structures for storing extension // behavior. #include "compiler/translator/ExtensionBehavior.h" #include "common/debug.h" #define LIST_EXTENSIONS(OP) \ OP(ARB_texture_rectangle) \ OP(ARM_shader_framebuffer_fetch) \ OP(EXT_blend_func_extended) \ OP(EXT_draw_buffers) \ OP(EXT_frag_depth) \ OP(EXT_shader_framebuffer_fetch) \ OP(EXT_shader_texture_lod) \ OP(EXT_YUV_target) \ OP(NV_EGL_stream_consumer_external) \ OP(NV_shader_framebuffer_fetch) \ OP(OES_EGL_image_external) \ OP(OES_EGL_image_external_essl3) \ OP(OES_geometry_shader) \ OP(OES_standard_derivatives) \ OP(OVR_multiview) namespace sh { #define RETURN_EXTENSION_NAME_CASE(ext) \ case TExtension::ext: \ return "GL_" #ext; const char *GetExtensionNameString(TExtension extension) { switch (extension) { LIST_EXTENSIONS(RETURN_EXTENSION_NAME_CASE) default: UNREACHABLE(); return ""; } } #define RETURN_EXTENSION_IF_NAME_MATCHES(ext) \ if (strcmp(extWithoutGLPrefix, #ext) == 0) \ { \ return TExtension::ext; \ } TExtension GetExtensionByName(const char *extension) { // If first characters of the extension don't equal "GL_", early out. if (strncmp(extension, "GL_", 3) != 0) { return TExtension::UNDEFINED; } const char *extWithoutGLPrefix = extension + 3; LIST_EXTENSIONS(RETURN_EXTENSION_IF_NAME_MATCHES) return TExtension::UNDEFINED; } const char *GetBehaviorString(TBehavior b) { switch (b) { case EBhRequire: return "require"; case EBhEnable: return "enable"; case EBhWarn: return "warn"; case EBhDisable: return "disable"; default: return nullptr; } } bool IsExtensionEnabled(const TExtensionBehavior &extBehavior, TExtension extension) { ASSERT(extension != TExtension::UNDEFINED); auto iter = extBehavior.find(extension); return iter != extBehavior.end() && (iter->second == EBhEnable || iter->second == EBhRequire); } } // namespace sh <commit_msg>Include string.h for strncmp in ExtensionBehavior.cpp<commit_after>// // Copyright (c) 2017 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ExtensionBehavior.cpp: Extension name enumeration and data structures for storing extension // behavior. #include "compiler/translator/ExtensionBehavior.h" #include "common/debug.h" #include <string.h> #define LIST_EXTENSIONS(OP) \ OP(ARB_texture_rectangle) \ OP(ARM_shader_framebuffer_fetch) \ OP(EXT_blend_func_extended) \ OP(EXT_draw_buffers) \ OP(EXT_frag_depth) \ OP(EXT_shader_framebuffer_fetch) \ OP(EXT_shader_texture_lod) \ OP(EXT_YUV_target) \ OP(NV_EGL_stream_consumer_external) \ OP(NV_shader_framebuffer_fetch) \ OP(OES_EGL_image_external) \ OP(OES_EGL_image_external_essl3) \ OP(OES_geometry_shader) \ OP(OES_standard_derivatives) \ OP(OVR_multiview) namespace sh { #define RETURN_EXTENSION_NAME_CASE(ext) \ case TExtension::ext: \ return "GL_" #ext; const char *GetExtensionNameString(TExtension extension) { switch (extension) { LIST_EXTENSIONS(RETURN_EXTENSION_NAME_CASE) default: UNREACHABLE(); return ""; } } #define RETURN_EXTENSION_IF_NAME_MATCHES(ext) \ if (strcmp(extWithoutGLPrefix, #ext) == 0) \ { \ return TExtension::ext; \ } TExtension GetExtensionByName(const char *extension) { // If first characters of the extension don't equal "GL_", early out. if (strncmp(extension, "GL_", 3) != 0) { return TExtension::UNDEFINED; } const char *extWithoutGLPrefix = extension + 3; LIST_EXTENSIONS(RETURN_EXTENSION_IF_NAME_MATCHES) return TExtension::UNDEFINED; } const char *GetBehaviorString(TBehavior b) { switch (b) { case EBhRequire: return "require"; case EBhEnable: return "enable"; case EBhWarn: return "warn"; case EBhDisable: return "disable"; default: return nullptr; } } bool IsExtensionEnabled(const TExtensionBehavior &extBehavior, TExtension extension) { ASSERT(extension != TExtension::UNDEFINED); auto iter = extBehavior.find(extension); return iter != extBehavior.end() && (iter->second == EBhEnable || iter->second == EBhRequire); } } // namespace sh <|endoftext|>
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004, 2005 darkbits Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * 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. */ /* * For comments regarding functions please see the header file. */ #include "guichan/widgets/button.hpp" #include "guichan/exception.hpp" #include "guichan/mouseinput.hpp" namespace gcn { Button::Button() { mAlignment = Graphics::CENTER; addMouseListener(this); addKeyListener(this); adjustSize(); setBorderSize(1); } Button::Button(const std::string& caption) { mCaption = caption; mAlignment = Graphics::CENTER; setFocusable(true); adjustSize(); setBorderSize(1); mMouseDown = false; mKeyDown = false; addMouseListener(this); addKeyListener(this); } void Button::setCaption(const std::string& caption) { mCaption = caption; } const std::string& Button::getCaption() const { return mCaption; } void Button::setAlignment(unsigned int alignment) { mAlignment = alignment; } unsigned int Button::getAlignment() const { return mAlignment; } void Button::draw(Graphics* graphics) { Color faceColor = getBaseColor(); Color highlightColor, shadowColor; int alpha = getBaseColor().a; if (isPressed()) { faceColor = faceColor - 0x303030; faceColor.a = alpha; highlightColor = faceColor - 0x303030; highlightColor.a = alpha; shadowColor = faceColor + 0x303030; shadowColor.a = alpha; } else { highlightColor = faceColor + 0x303030; highlightColor.a = alpha; shadowColor = faceColor - 0x303030; shadowColor.a = alpha; } graphics->setColor(faceColor); graphics->fillRectangle(Rectangle(1, 1, getDimension().width-1, getHeight() - 1)); graphics->setColor(highlightColor); graphics->drawLine(0, 0, getWidth() - 1, 0); graphics->drawLine(0, 1, 0, getHeight() - 1); graphics->setColor(shadowColor); graphics->drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 1); graphics->drawLine(1, getHeight() - 1, getWidth() - 1, getHeight() - 1); graphics->setColor(getForegroundColor()); int textX; int textY = getHeight() / 2 - getFont()->getHeight() / 2; switch (getAlignment()) { case Graphics::LEFT: textX = 4; break; case Graphics::CENTER: textX = getWidth() / 2; break; case Graphics::RIGHT: textX = getWidth() - 4; break; default: throw GCN_EXCEPTION("Unknown alignment."); } graphics->setFont(getFont()); if (isPressed()) { graphics->drawText(getCaption(), textX + 1, textY + 1, getAlignment()); } else { graphics->drawText(getCaption(), textX, textY, getAlignment()); if (hasFocus()) { graphics->drawRectangle(Rectangle(2, 2, getWidth() - 4, getHeight() - 4)); } } } void Button::drawBorder(Graphics* graphics) { Color faceColor = getBaseColor(); Color highlightColor, shadowColor; int alpha = getBaseColor().a; int width = getWidth() + getBorderSize() * 2 - 1; int height = getHeight() + getBorderSize() * 2 - 1; highlightColor = faceColor + 0x303030; highlightColor.a = alpha; shadowColor = faceColor - 0x303030; shadowColor.a = alpha; unsigned int i; for (i = 0; i < getBorderSize(); ++i) { graphics->setColor(shadowColor); graphics->drawLine(i,i, width - i, i); graphics->drawLine(i,i + 1, i, height - i - 1); graphics->setColor(highlightColor); graphics->drawLine(width - i,i + 1, width - i, height - i); graphics->drawLine(i,height - i, width - i - 1, height - i); } } void Button::adjustSize() { setWidth(getFont()->getWidth(mCaption) + 8); setHeight(getFont()->getHeight() + 8); } bool Button::isPressed() const { return (hasMouse() && mMouseDown) || mKeyDown; } void Button::mouseClick(int x, int y, int button, int count) { if (button == MouseInput::LEFT) { generateAction(); } } void Button::mousePress(int x, int y, int button) { if (button == MouseInput::LEFT && hasMouse()) { mMouseDown = true; } } void Button::mouseRelease(int x, int y, int button) { if (button == MouseInput::LEFT) { mMouseDown = false; } } void Button::keyPress(const Key& key) { if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE) { mKeyDown = true; } mMouseDown = false; } void Button::keyRelease(const Key& key) { if ((key.getValue() == Key::ENTER || key.getValue() == Key::SPACE) && mKeyDown) { mKeyDown = false; generateAction(); } } void Button::lostFocus() { mMouseDown = false; mKeyDown = false; } } <commit_msg>Fixed initialisation of button member variables in Button().<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004, 2005 darkbits Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * 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. */ /* * For comments regarding functions please see the header file. */ #include "guichan/widgets/button.hpp" #include "guichan/exception.hpp" #include "guichan/mouseinput.hpp" namespace gcn { Button::Button() { mAlignment = Graphics::CENTER; setFocusable(true); adjustSize(); setBorderSize(1); mMouseDown = false; mKeyDown = false; addMouseListener(this); addKeyListener(this); } Button::Button(const std::string& caption) { mCaption = caption; mAlignment = Graphics::CENTER; setFocusable(true); adjustSize(); setBorderSize(1); mMouseDown = false; mKeyDown = false; addMouseListener(this); addKeyListener(this); } void Button::setCaption(const std::string& caption) { mCaption = caption; } const std::string& Button::getCaption() const { return mCaption; } void Button::setAlignment(unsigned int alignment) { mAlignment = alignment; } unsigned int Button::getAlignment() const { return mAlignment; } void Button::draw(Graphics* graphics) { Color faceColor = getBaseColor(); Color highlightColor, shadowColor; int alpha = getBaseColor().a; if (isPressed()) { faceColor = faceColor - 0x303030; faceColor.a = alpha; highlightColor = faceColor - 0x303030; highlightColor.a = alpha; shadowColor = faceColor + 0x303030; shadowColor.a = alpha; } else { highlightColor = faceColor + 0x303030; highlightColor.a = alpha; shadowColor = faceColor - 0x303030; shadowColor.a = alpha; } graphics->setColor(faceColor); graphics->fillRectangle(Rectangle(1, 1, getDimension().width-1, getHeight() - 1)); graphics->setColor(highlightColor); graphics->drawLine(0, 0, getWidth() - 1, 0); graphics->drawLine(0, 1, 0, getHeight() - 1); graphics->setColor(shadowColor); graphics->drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 1); graphics->drawLine(1, getHeight() - 1, getWidth() - 1, getHeight() - 1); graphics->setColor(getForegroundColor()); int textX; int textY = getHeight() / 2 - getFont()->getHeight() / 2; switch (getAlignment()) { case Graphics::LEFT: textX = 4; break; case Graphics::CENTER: textX = getWidth() / 2; break; case Graphics::RIGHT: textX = getWidth() - 4; break; default: throw GCN_EXCEPTION("Unknown alignment."); } graphics->setFont(getFont()); if (isPressed()) { graphics->drawText(getCaption(), textX + 1, textY + 1, getAlignment()); } else { graphics->drawText(getCaption(), textX, textY, getAlignment()); if (hasFocus()) { graphics->drawRectangle(Rectangle(2, 2, getWidth() - 4, getHeight() - 4)); } } } void Button::drawBorder(Graphics* graphics) { Color faceColor = getBaseColor(); Color highlightColor, shadowColor; int alpha = getBaseColor().a; int width = getWidth() + getBorderSize() * 2 - 1; int height = getHeight() + getBorderSize() * 2 - 1; highlightColor = faceColor + 0x303030; highlightColor.a = alpha; shadowColor = faceColor - 0x303030; shadowColor.a = alpha; unsigned int i; for (i = 0; i < getBorderSize(); ++i) { graphics->setColor(shadowColor); graphics->drawLine(i,i, width - i, i); graphics->drawLine(i,i + 1, i, height - i - 1); graphics->setColor(highlightColor); graphics->drawLine(width - i,i + 1, width - i, height - i); graphics->drawLine(i,height - i, width - i - 1, height - i); } } void Button::adjustSize() { setWidth(getFont()->getWidth(mCaption) + 8); setHeight(getFont()->getHeight() + 8); } bool Button::isPressed() const { return (hasMouse() && mMouseDown) || mKeyDown; } void Button::mouseClick(int x, int y, int button, int count) { if (button == MouseInput::LEFT) { generateAction(); } } void Button::mousePress(int x, int y, int button) { if (button == MouseInput::LEFT && hasMouse()) { mMouseDown = true; } } void Button::mouseRelease(int x, int y, int button) { if (button == MouseInput::LEFT) { mMouseDown = false; } } void Button::keyPress(const Key& key) { if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE) { mKeyDown = true; } mMouseDown = false; } void Button::keyRelease(const Key& key) { if ((key.getValue() == Key::ENTER || key.getValue() == Key::SPACE) && mKeyDown) { mKeyDown = false; generateAction(); } } void Button::lostFocus() { mMouseDown = false; mKeyDown = false; } } <|endoftext|>
<commit_before>/* * SessionThemes.cpp * * Copyright (C) 2018 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionThemes.hpp" #include <boost/bind.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/FilePath.hpp> #include <core/json/JsonRpc.hpp> #include <core/system/System.hpp> #include <core/http/Request.hpp> #include <core/http/Response.hpp> #include <session/SessionModuleContext.hpp> #include <r/RRoutines.hpp> #include <r/RSexp.hpp> #include <fstream> #include <map> #include <regex> #include <string> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace themes { namespace { const std::string kDefaultThemeLocation = "/theme/default/"; const std::string kGlobalCustomThemeLocation = "/theme/custom/global/"; const std::string kLocalCustomThemeLocation = "/theme/custom/local/"; // A map from the name of the theme to the location of the file and a boolean representing // whether or not the theme is dark. typedef std::map<std::string, std::pair<std::string, bool> > ThemeMap; bool strIsTrue(const std::string& toConvert) { return std::regex_match( std::string(toConvert), std::regex("(?:1|t(?:rue)?))", std::regex_constants::icase)); } bool strIsFalse(const std::string& toConvert) { return std::regex_match( std::string(toConvert), std::regex("(?:0|f(?:alse)?))", std::regex_constants::icase)); } /** * @brief Gets themes in the specified location. * * @param location The location in which to look for themes. * @param themeMap The map which will contain all found themes after the call. * @param urlPrefix The URL prefix for the theme. Must end with "/" */ void getThemesInLocation( const rstudio::core::FilePath& location, ThemeMap& themeMap, const std::string& urlPrefix = "") { using rstudio::core::FilePath; if (location.isDirectory()) { std::vector<FilePath> locationChildren; location.children(&locationChildren); for (const FilePath& themeFile: locationChildren) { if (themeFile.hasExtensionLowerCase(".rstheme")) { const std::string k_themeFileStr = themeFile.canonicalPath(); std::ifstream themeIFStream(k_themeFileStr); std::string themeContents( (std::istreambuf_iterator<char>(themeIFStream)), (std::istreambuf_iterator<char>())); themeIFStream.close(); std::smatch matches; std::regex_search( themeContents, matches, std::regex("rs-theme-name\\s*:\\s*([^\\*]+?)\\s*(?:\\*|$)")); // If there's no name specified,use the name of the file std::string name; if (matches.size() < 2) { name = themeFile.stem(); } else { // If there's at least one name specified, get the first one. name = matches[1]; } // Find out if the theme is dark or not. std::regex_search( themeContents, matches, std::regex("rs-theme-is-dark\\s*:\\s*([^\\*]+?)\\s*(?:\\*|$)")); bool isDark = false; if (matches.size() >= 2) { isDark = strIsTrue(matches[1]); } if ((matches.size() < 2) || (!isDark && !strIsFalse(matches[1]))) { // TODO: warning / logging about using default isDark value. } themeMap[name] = std::tuple<std::string, bool>(urlPrefix + themeFile.filename(), isDark); } } } } FilePath getDefaultThemePath() { return session::options().rResourcesPath().childPath("themes"); } FilePath getGlobalCustomThemePath() { using rstudio::core::FilePath; const char* kGlobalPathAlt = std::getenv("RS_THEME_GLOBAL_HOME"); if (kGlobalPathAlt) { return FilePath(kGlobalPathAlt); } #ifdef _WIN32 return core::system::systemSettingsPath("RStudio\\themes", false); #else return FilePath("/etc/rstudio/themes/"); #endif } FilePath getLocalCustomThemePath() { using rstudio::core::FilePath; const char* kLocalPathAlt = std::getenv("RS_THEME_LOCAL_HOME"); if (kLocalPathAlt) { return FilePath(kLocalPathAlt); } #ifdef _WIN32 return core::system::userHomePath().childPath(".R\\rstudio\\themes"); #else return core::system::userHomePath().childPath(".R/rstudio/themes/"); #endif } void getAllThemes(ThemeMap& themeMap) { // Intentionally get global themes before getting user specific themes so that user specific // themes will override global ones. getThemesInLocation(getDefaultThemePath(), themeMap, kDefaultThemeLocation); getThemesInLocation(getGlobalCustomThemePath(), themeMap, kGlobalCustomThemeLocation); getThemesInLocation(getLocalCustomThemePath(), themeMap, kLocalCustomThemeLocation); } /** * @brief Gets the list of all RStudio editor themes. * * @return The list of all RStudio editor themes. */ SEXP rs_getThemes() { ThemeMap themeMap; getAllThemes(themeMap); // Convert to an R list. rstudio::r::sexp::Protect protect; rstudio::r::sexp::ListBuilder themeListBuilder(&protect); for (auto theme: themeMap) { rstudio::r::sexp::ListBuilder themeDetailsListBuilder(&protect); themeDetailsListBuilder.add("url", theme.second.first); themeDetailsListBuilder.add("isDark", theme.second.second); themeListBuilder.add(theme.first, themeDetailsListBuilder); } return rstudio::r::sexp::create(themeListBuilder, &protect); } FilePath getDefaultTheme(const http::Request& request) { std::string isDarkStr = request.queryParamValue("dark"); bool isDark = strIsTrue(isDarkStr); if (!isDark && !strIsFalse(isDarkStr)) { // TODO: Error/warning/logging // Note that this should be considered an internal error, since the request is generated // by the client and without user input. } if (isDark) { return getDefaultThemePath().childPath("tomorrow_night.rstheme"); } else { return getDefaultThemePath().childPath("textmate.rstheme"); } } void handleDefaultThemeRequest(const http::Request& request, http::Response* pResponse) { std::string fileName = http::util::pathAfterPrefix(request, kDefaultThemeLocation); pResponse->setCacheableFile(getDefaultThemePath().childPath(fileName), request); pResponse->setContentType("text/css"); } void handleGlobalCustomThemeRequest(const http::Request& request, http::Response* pResponse) { // Note: we probably want to return a warning code instead of success so the client has the // ability to pop up a warning dialog or something to the user. std::string fileName = http::util::pathAfterPrefix(request, kGlobalCustomThemeLocation); FilePath requestedTheme = getGlobalCustomThemePath().childPath(fileName); pResponse->setCacheableFile( requestedTheme.exists() ? requestedTheme : getDefaultTheme(request), request); pResponse->setContentType("text/css"); } void handleLocalCustomThemeRequest(const http::Request& request, http::Response* pResponse) { // Note: we probably want to return a warning code instead of success so the client has the // ability to pop up a warning dialog or something to the user. std::string fileName = http::util::pathAfterPrefix(request, kLocalCustomThemeLocation); FilePath requestedTheme = getLocalCustomThemePath().childPath(fileName); pResponse->setCacheableFile( requestedTheme.exists() ? requestedTheme : getDefaultTheme(request), request); pResponse->setContentType("text/css"); } /** * Gets the list of all the avialble themes for the client. */ Error getThemes(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { ThemeMap themes; getAllThemes(themes); // Convert the theme to a json array. json::Array jsonThemeArray; for (auto theme: themes) { json::Object jsonTheme; jsonTheme["name"] = theme.first; jsonTheme["url"] = theme.second.first; jsonTheme["isDark"] = theme.second.second; jsonThemeArray.push_back(jsonTheme); } pResponse->setResult(jsonThemeArray); return Success(); } } // anonymous namespace Error initialize() { using boost::bind; using namespace module_context; RS_REGISTER_CALL_METHOD(rs_getThemes, 0); ExecBlock initBlock; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionThemes.R")) (bind(registerRpcMethod, "get_themes", getThemes)) (bind(registerUriHandler, kDefaultThemeLocation, handleDefaultThemeRequest)) (bind(registerUriHandler, kGlobalCustomThemeLocation, handleGlobalCustomThemeRequest)) (bind(registerUriHandler, kLocalCustomThemeLocation, handleLocalCustomThemeRequest)); return initBlock.execute(); } } // namespace themes } // namespace modules } // namespace session } // namespace rstudio <commit_msg>clean up code.<commit_after>/* * SessionThemes.cpp * * Copyright (C) 2018 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionThemes.hpp" #include <boost/bind.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/FilePath.hpp> #include <core/json/JsonRpc.hpp> #include <core/system/System.hpp> #include <core/http/Request.hpp> #include <core/http/Response.hpp> #include <session/SessionModuleContext.hpp> #include <r/RRoutines.hpp> #include <r/RSexp.hpp> #include <fstream> #include <map> #include <regex> #include <string> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace themes { namespace { const std::string kDefaultThemeLocation = "/theme/default/"; const std::string kGlobalCustomThemeLocation = "/theme/custom/global/"; const std::string kLocalCustomThemeLocation = "/theme/custom/local/"; // A map from the name of the theme to the location of the file and a boolean representing // whether or not the theme is dark. typedef std::map<std::string, std::pair<std::string, bool> > ThemeMap; /// @brief Determines whether a string can be evaluated to logical "true". A return value of false /// does not indicate that the string can be evaluted to logical "false". /// /// @param toConvert The string to convert to boolean. /// /// @return True if the string matches 1, TRUE, true, or any case variant of true; false otherwise. bool strIsTrue(const std::string& toConvert) { return std::regex_match( std::string(toConvert), std::regex("(?:1|t(?:rue)?))", std::regex_constants::icase)); } /// @brief Determines whether a string can be evaluated to logical "false". A return value of true /// does not indicate that the string can be evaluted to logical "true". /// /// @param toConvert The string to convert to boolean. /// /// @return True if the string matches 0, FALSE, false, or any case variant of false; true /// otherwise. bool strIsFalse(const std::string& toConvert) { return std::regex_match( std::string(toConvert), std::regex("(?:0|f(?:alse)?))", std::regex_constants::icase)); } /** * @brief Gets themes in the specified location. * * @param location The location in which to look for themes. * @param themeMap The map which will contain all found themes after the call. * @param urlPrefix The URL prefix for the theme. Must end with "/" */ void getThemesInLocation( const rstudio::core::FilePath& location, ThemeMap& themeMap, const std::string& urlPrefix = "") { using rstudio::core::FilePath; if (location.isDirectory()) { std::vector<FilePath> locationChildren; location.children(&locationChildren); for (const FilePath& themeFile: locationChildren) { if (themeFile.hasExtensionLowerCase(".rstheme")) { const std::string k_themeFileStr = themeFile.canonicalPath(); std::ifstream themeIFStream(k_themeFileStr); std::string themeContents( (std::istreambuf_iterator<char>(themeIFStream)), (std::istreambuf_iterator<char>())); themeIFStream.close(); std::smatch matches; std::regex_search( themeContents, matches, std::regex("rs-theme-name\\s*:\\s*([^\\*]+?)\\s*(?:\\*|$)")); // If there's no name specified,use the name of the file std::string name; if (matches.size() < 2) { name = themeFile.stem(); } else { // If there's at least one name specified, get the first one. name = matches[1]; } // Find out if the theme is dark or not. std::regex_search( themeContents, matches, std::regex("rs-theme-is-dark\\s*:\\s*([^\\*]+?)\\s*(?:\\*|$)")); bool isDark = false; if (matches.size() >= 2) { isDark = strIsTrue(matches[1]); } if ((matches.size() < 2) || (!isDark && !strIsFalse(matches[1]))) { // TODO: warning / logging about using default isDark value. } themeMap[name] = std::tuple<std::string, bool>(urlPrefix + themeFile.filename(), isDark); } } } } /** * @brief Gets the location of themes that are installed with RStudio. * * @return The location of themes that are installed with RStudio. */ FilePath getDefaultThemePath() { return session::options().rResourcesPath().childPath("themes"); } /** * @brief Gets the location of custom themes that are installed for all users. * * @return The location of custom themes that are installed for all users. */ FilePath getGlobalCustomThemePath() { using rstudio::core::FilePath; const char* kGlobalPathAlt = std::getenv("RS_THEME_GLOBAL_HOME"); if (kGlobalPathAlt) { return FilePath(kGlobalPathAlt); } #ifdef _WIN32 return core::system::systemSettingsPath("RStudio\\themes", false); #else return FilePath("/etc/rstudio/themes/"); #endif } /** * @brief Gets the location of custom themes that are installed for the current user. * * @return The location of custom themes that are installed for the current user. */ FilePath getLocalCustomThemePath() { using rstudio::core::FilePath; const char* kLocalPathAlt = std::getenv("RS_THEME_LOCAL_HOME"); if (kLocalPathAlt) { return FilePath(kLocalPathAlt); } #ifdef _WIN32 return core::system::userHomePath().childPath(".R\\rstudio\\themes"); #else return core::system::userHomePath().childPath(".R/rstudio/themes/"); #endif } /** * @brief Gets a map of all available themes, keyed by the unique name of the theme. If a theme is * found in multiple locations, the theme in the most specific folder will be given * precedence. * * @return The map of all available themes. */ ThemeMap getAllThemes() { // Intentionally get global themes before getting user specific themes so that user specific // themes will override global ones. ThemeMap themeMap; getThemesInLocation(getDefaultThemePath(), themeMap, kDefaultThemeLocation); getThemesInLocation(getGlobalCustomThemePath(), themeMap, kGlobalCustomThemeLocation); getThemesInLocation(getLocalCustomThemePath(), themeMap, kLocalCustomThemeLocation); return themeMap; } /** * @brief Gets the list of all RStudio editor themes. * * @return The list of all RStudio editor themes. */ SEXP rs_getThemes() { ThemeMap themeMap = getAllThemes(); // Convert to an R list. rstudio::r::sexp::Protect protect; rstudio::r::sexp::ListBuilder themeListBuilder(&protect); for (auto theme: themeMap) { rstudio::r::sexp::ListBuilder themeDetailsListBuilder(&protect); themeDetailsListBuilder.add("url", theme.second.first); themeDetailsListBuilder.add("isDark", theme.second.second); themeListBuilder.add(theme.first, themeDetailsListBuilder); } return rstudio::r::sexp::create(themeListBuilder, &protect); } /** * @brief Gets the default theme based on the request from the client. * * @param request The request from the client. * * @return The default theme. "Tomorrow Night" if the request is for a dark theme; "Textmate" if * the request is for a light theme. */ FilePath getDefaultTheme(const http::Request& request) { std::string isDarkStr = request.queryParamValue("dark"); bool isDark = strIsTrue(isDarkStr); if (!isDark && !strIsFalse(isDarkStr)) { // TODO: Error/warning/logging // Note that this should be considered an internal error, since the request is generated // by the client and without user input. } if (isDark) { return getDefaultThemePath().childPath("tomorrow_night.rstheme"); } else { return getDefaultThemePath().childPath("textmate.rstheme"); } } /** * @brief Gets a theme that is installed with RStudio. * * @param request The HTTP request from the client. * @param pResponse The HTTP response, which will contain the theme CSS. */ void handleDefaultThemeRequest(const http::Request& request, http::Response* pResponse) { std::string fileName = http::util::pathAfterPrefix(request, kDefaultThemeLocation); pResponse->setCacheableFile(getDefaultThemePath().childPath(fileName), request); pResponse->setContentType("text/css"); } /** * @brief Gets a custom theme that is installed for all users. * * @param request The HTTP request from the client. * @param pResponse The HTTP response, which will contain the theme CSS. */ void handleGlobalCustomThemeRequest(const http::Request& request, http::Response* pResponse) { // Note: we probably want to return a warning code instead of success so the client has the // ability to pop up a warning dialog or something to the user. std::string fileName = http::util::pathAfterPrefix(request, kGlobalCustomThemeLocation); FilePath requestedTheme = getGlobalCustomThemePath().childPath(fileName); pResponse->setCacheableFile( requestedTheme.exists() ? requestedTheme : getDefaultTheme(request), request); pResponse->setContentType("text/css"); } /** * @brief Gets a custom theme that is installed for all users. * * @param request The HTTP request from the client. * @param pResponse The HTTP response, which will contain the theme CSS. */ void handleLocalCustomThemeRequest(const http::Request& request, http::Response* pResponse) { // Note: we probably want to return a warning code instead of success so the client has the // ability to pop up a warning dialog or something to the user. std::string fileName = http::util::pathAfterPrefix(request, kLocalCustomThemeLocation); FilePath requestedTheme = getLocalCustomThemePath().childPath(fileName); pResponse->setCacheableFile( requestedTheme.exists() ? requestedTheme : getDefaultTheme(request), request); pResponse->setContentType("text/css"); } /** * @brief Gets the list of all the avialble themes for the client. * * @param request The JSON request from the client. * @param pResponse The JSON response, which will contain the list of themes. * * @return The error that occurred, if any; otherwise Success(). */ Error getThemes(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { ThemeMap themes = getAllThemes(); // Convert the theme to a json array. json::Array jsonThemeArray; for (auto theme: themes) { json::Object jsonTheme; jsonTheme["name"] = theme.first; jsonTheme["url"] = theme.second.first; jsonTheme["isDark"] = theme.second.second; jsonThemeArray.push_back(jsonTheme); } pResponse->setResult(jsonThemeArray); return Success(); } } // anonymous namespace Error initialize() { using boost::bind; using namespace module_context; RS_REGISTER_CALL_METHOD(rs_getThemes, 0); ExecBlock initBlock; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionThemes.R")) (bind(registerRpcMethod, "get_themes", getThemes)) (bind(registerUriHandler, kDefaultThemeLocation, handleDefaultThemeRequest)) (bind(registerUriHandler, kGlobalCustomThemeLocation, handleGlobalCustomThemeRequest)) (bind(registerUriHandler, kLocalCustomThemeLocation, handleLocalCustomThemeRequest)); return initBlock.execute(); } } // namespace themes } // namespace modules } // namespace session } // namespace rstudio <|endoftext|>
<commit_before>/* * http_ep_server_test.cpp - Kurento Media Server * * Copyright (C) 2013 Kurento * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define BOOST_TEST_MODULE http_ep_server #include <boost/test/unit_test.hpp> #include <gst/gst.h> #include <libsoup/soup.h> #include <KmsHttpEPServer.h> #include <kmshttpendpointaction.h> #define GST_CAT_DEFAULT _http_endpoint_server_test_ GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "http_endpoint_server_test" #define MAX_REGISTERED_HTTP_END_POINTS 10 #define HTTP_GET "GET" #define DEFAULT_PORT 9091 #define DEFAULT_HOST "localhost" static KmsHttpEPServer *httpepserver; static GMainLoop *loop = NULL; static GSList *urls = NULL; static SoupSession *session; static guint urls_registered = 0; static guint signal_count = 0; static guint counted = 0; static SoupKnownStatusCode expected_200 = SOUP_STATUS_OK; static SoupKnownStatusCode expected_404 = SOUP_STATUS_NOT_FOUND; BOOST_AUTO_TEST_SUITE (http_ep_server_test) static void register_http_end_points() { const gchar *url; gint i; for (i = 0; i < MAX_REGISTERED_HTTP_END_POINTS; i++) { GstElement *httpep = gst_element_factory_make ("httpendpoint", NULL); BOOST_CHECK ( httpep != NULL ); GST_DEBUG ("Registering %s", GST_ELEMENT_NAME (httpep) ); url = kms_http_ep_server_register_end_point (httpepserver, httpep); BOOST_CHECK (url != NULL); if (url == NULL) continue; /* Leave the last reference to http end point server */ g_object_unref (G_OBJECT (httpep) ); GST_DEBUG ("Registered url: %s", url); urls = g_slist_prepend (urls, (gpointer *) g_strdup (url) ); } urls_registered = g_slist_length (urls); } static void http_req_callback (SoupSession *session, SoupMessage *msg, gpointer data) { SoupKnownStatusCode *expected = (SoupKnownStatusCode *) data; guint status_code; gchar *method; SoupURI *uri; g_object_get (G_OBJECT (msg), "method", &method, "status-code", &status_code, "uri", &uri, NULL); GST_DEBUG ("%s %s status code: %d, expected %d", method, soup_uri_get_path (uri), status_code, *expected); BOOST_CHECK_EQUAL (*expected, status_code); if (*expected == expected_404 && ++counted == urls_registered) g_main_loop_quit (loop); soup_uri_free (uri); g_free (method); } static void send_get_request (const gchar *uri, gpointer data) { SoupMessage *msg; gchar *url; url = g_strdup_printf ("http://%s:%d%s", DEFAULT_HOST, DEFAULT_PORT, uri); GST_INFO ("Send " HTTP_GET " %s", url); msg = soup_message_new (HTTP_GET, url); soup_session_queue_message (session, msg, (SoupSessionCallback) http_req_callback, data); g_free (url); } static gboolean checking_registered_urls (gpointer data) { GST_DEBUG ("Sending GET request to all urls registered"); g_slist_foreach (urls, (GFunc) send_get_request, data); return FALSE; } static void url_removed_cb (KmsHttpEPServer *server, const gchar *url, gpointer data) { GST_DEBUG ("URL %s removed", url); if (++signal_count == urls_registered) { /* Testing removed URLs */ g_idle_add ( (GSourceFunc) checking_registered_urls, &expected_404); } } static void action_requested_cb (KmsHttpEPServer *server, const gchar *uri, KmsHttpEndPointAction action, gpointer data) { GST_DEBUG ("Action %d requested on %s", action, uri); BOOST_CHECK ( action == KMS_HTTP_END_POINT_ACTION_GET ); BOOST_CHECK (kms_http_ep_server_unregister_end_point (httpepserver, uri) ); } static void http_server_start_cb (KmsHttpEPServer *self, GError *err) { if (err != NULL) { GST_ERROR ("%s, code %d", err->message, err->code); return; } register_http_end_points(); g_idle_add ( (GSourceFunc) checking_registered_urls, &expected_200); } BOOST_AUTO_TEST_CASE ( register_http_end_point_test ) { gchar *env; env = g_strdup ("GST_PLUGIN_PATH=./plugins"); putenv (env); gst_init (NULL, NULL); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); loop = g_main_loop_new (NULL, FALSE); session = soup_session_async_new(); /* Start Http End Point Server */ httpepserver = kms_http_ep_server_new (KMS_HTTP_EP_SERVER_PORT, DEFAULT_PORT, KMS_HTTP_EP_SERVER_INTERFACE, DEFAULT_HOST, NULL); g_signal_connect (httpepserver, "url-removed", G_CALLBACK (url_removed_cb), NULL); g_signal_connect (httpepserver, "action-requested", G_CALLBACK (action_requested_cb), NULL); kms_http_ep_server_start (httpepserver, http_server_start_cb); g_main_loop_run (loop); BOOST_CHECK_EQUAL (signal_count, urls_registered); GST_DEBUG ("Test finished"); /* Stop Http End Point Server and destroy it */ kms_http_ep_server_stop (httpepserver); /* check for missed unrefs before exiting */ BOOST_CHECK ( G_OBJECT (httpepserver)->ref_count == 1 ); g_object_unref (G_OBJECT (httpepserver) ); g_object_unref (G_OBJECT (session) ); g_slist_free_full (urls, g_free); g_free (env); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Add test to check there is not memory leaks unregistering pending GET requests<commit_after>/* * http_ep_server_test.cpp - Kurento Media Server * * Copyright (C) 2013 Kurento * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define BOOST_TEST_MODULE http_ep_server #include <boost/test/unit_test.hpp> #include <gst/gst.h> #include <libsoup/soup.h> #include <KmsHttpEPServer.h> #include <kmshttpendpointaction.h> #define GST_CAT_DEFAULT _http_endpoint_server_test_ GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "http_endpoint_server_test" #define MAX_REGISTERED_HTTP_END_POINTS 10 #define HTTP_GET "GET" #define DEFAULT_PORT 9091 #define DEFAULT_HOST "localhost" static KmsHttpEPServer *httpepserver; static SoupSession *session; static GMainLoop *loop; static GSList *urls; static guint urls_registered; static guint signal_count; static guint counted; static SoupKnownStatusCode expected_200 = SOUP_STATUS_OK; static SoupKnownStatusCode expected_404 = SOUP_STATUS_NOT_FOUND; SoupSessionCallback session_cb; BOOST_AUTO_TEST_SUITE (http_ep_server_test) static void init_global_variables() { loop = NULL; urls = NULL; urls_registered = 0; signal_count = 0; counted = 0; } static void register_http_end_points() { const gchar *url; gint i; for (i = 0; i < MAX_REGISTERED_HTTP_END_POINTS; i++) { GstElement *httpep = gst_element_factory_make ("httpendpoint", NULL); BOOST_CHECK ( httpep != NULL ); GST_DEBUG ("Registering %s", GST_ELEMENT_NAME (httpep) ); url = kms_http_ep_server_register_end_point (httpepserver, httpep); BOOST_CHECK (url != NULL); if (url == NULL) continue; /* Leave the last reference to http end point server */ g_object_unref (G_OBJECT (httpep) ); GST_DEBUG ("Registered url: %s", url); urls = g_slist_prepend (urls, (gpointer *) g_strdup (url) ); } urls_registered = g_slist_length (urls); } static void http_req_callback (SoupSession *session, SoupMessage *msg, gpointer data) { SoupKnownStatusCode *expected = (SoupKnownStatusCode *) data; guint status_code; gchar *method; SoupURI *uri; g_object_get (G_OBJECT (msg), "method", &method, "status-code", &status_code, "uri", &uri, NULL); GST_DEBUG ("%s %s status code: %d, expected %d", method, soup_uri_get_path (uri), status_code, *expected); BOOST_CHECK_EQUAL (*expected, status_code); if (*expected == expected_404 && ++counted == urls_registered) g_main_loop_quit (loop); soup_uri_free (uri); g_free (method); } static void send_get_request (const gchar *uri, gpointer data) { SoupMessage *msg; gchar *url; url = g_strdup_printf ("http://%s:%d%s", DEFAULT_HOST, DEFAULT_PORT, uri); GST_INFO ("Send " HTTP_GET " %s", url); msg = soup_message_new (HTTP_GET, url); soup_session_queue_message (session, msg, session_cb, data); g_free (url); } static gboolean checking_registered_urls (gpointer data) { GST_DEBUG ("Sending GET request to all urls registered"); g_slist_foreach (urls, (GFunc) send_get_request, data); return FALSE; } static void url_removed_cb (KmsHttpEPServer *server, const gchar *url, gpointer data) { GST_DEBUG ("URL %s removed", url); if (++signal_count == urls_registered) { /* Testing removed URLs */ g_idle_add ( (GSourceFunc) checking_registered_urls, &expected_404); } } static void action_requested_cb (KmsHttpEPServer *server, const gchar *uri, KmsHttpEndPointAction action, gpointer data) { GST_DEBUG ("Action %d requested on %s", action, uri); BOOST_CHECK ( action == KMS_HTTP_END_POINT_ACTION_GET ); BOOST_CHECK (kms_http_ep_server_unregister_end_point (httpepserver, uri) ); } static void http_server_start_cb (KmsHttpEPServer *self, GError *err) { if (err != NULL) { GST_ERROR ("%s, code %d", err->message, err->code); return; } register_http_end_points(); session_cb = http_req_callback; g_idle_add ( (GSourceFunc) checking_registered_urls, &expected_200); } BOOST_AUTO_TEST_CASE ( register_http_end_point_test ) { gchar *env; env = g_strdup ("GST_PLUGIN_PATH=./plugins"); putenv (env); gst_init (NULL, NULL); init_global_variables(); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); loop = g_main_loop_new (NULL, FALSE); session = soup_session_async_new(); /* Start Http End Point Server */ httpepserver = kms_http_ep_server_new (KMS_HTTP_EP_SERVER_PORT, DEFAULT_PORT, KMS_HTTP_EP_SERVER_INTERFACE, DEFAULT_HOST, NULL); g_signal_connect (httpepserver, "url-removed", G_CALLBACK (url_removed_cb), NULL); g_signal_connect (httpepserver, "action-requested", G_CALLBACK (action_requested_cb), NULL); kms_http_ep_server_start (httpepserver, http_server_start_cb); g_main_loop_run (loop); BOOST_CHECK_EQUAL (signal_count, urls_registered); GST_DEBUG ("Test finished"); /* Stop Http End Point Server and destroy it */ kms_http_ep_server_stop (httpepserver); /* check for missed unrefs before exiting */ BOOST_CHECK ( G_OBJECT (httpepserver)->ref_count == 1 ); g_object_unref (G_OBJECT (httpepserver) ); g_object_unref (G_OBJECT (session) ); g_slist_free_full (urls, g_free); g_free (env); } /********************************************/ /* Functions and variables used for tests 2 */ /********************************************/ static void t2_http_req_callback (SoupSession *session, SoupMessage *msg, gpointer data) { SoupKnownStatusCode *expected = (SoupKnownStatusCode *) data; guint status_code; gchar *method; SoupURI *uri; g_object_get (G_OBJECT (msg), "method", &method, "status-code", &status_code, "uri", &uri, NULL); GST_DEBUG ("%s %s status code: %d, expected %d", method, soup_uri_get_path (uri), status_code, *expected); BOOST_CHECK_EQUAL (*expected, status_code); if (++counted == urls_registered) g_main_loop_quit (loop); soup_uri_free (uri); g_free (method); } static void t2_action_requested_cb (KmsHttpEPServer *server, const gchar *uri, KmsHttpEndPointAction action, gpointer data) { GST_DEBUG ("Action %d requested on %s", action, uri); /* We unregister httpendpoints when they have already a pending request */ /* so as to check we don't miss memory leaks */ BOOST_CHECK (kms_http_ep_server_unregister_end_point (httpepserver, uri) ); } static void t2_url_removed_cb (KmsHttpEPServer *server, const gchar *url, gpointer data) { GST_DEBUG ("URL %s removed", url); } static void t2_http_server_start_cb (KmsHttpEPServer *self, GError *err) { if (err != NULL) { GST_ERROR ("%s, code %d", err->message, err->code); return; } register_http_end_points(); session_cb = t2_http_req_callback; g_idle_add ( (GSourceFunc) checking_registered_urls, &expected_200); } BOOST_AUTO_TEST_CASE ( locked_get_request_http_end_point_test ) { gchar *env; env = g_strdup ("GST_PLUGIN_PATH=./plugins"); putenv (env); gst_init (NULL, NULL); init_global_variables(); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); loop = g_main_loop_new (NULL, FALSE); session = soup_session_async_new(); /* Start Http End Point Server */ httpepserver = kms_http_ep_server_new (KMS_HTTP_EP_SERVER_PORT, DEFAULT_PORT, KMS_HTTP_EP_SERVER_INTERFACE, DEFAULT_HOST, NULL); g_signal_connect (httpepserver, "url-removed", G_CALLBACK (t2_url_removed_cb), NULL); g_signal_connect (httpepserver, "action-requested", G_CALLBACK (t2_action_requested_cb), NULL); kms_http_ep_server_start (httpepserver, t2_http_server_start_cb); g_main_loop_run (loop); GST_DEBUG ("Test finished"); /* Stop Http End Point Server and destroy it */ kms_http_ep_server_stop (httpepserver); /* check for missed unrefs before exiting */ BOOST_CHECK ( G_OBJECT (httpepserver)->ref_count == 1 ); g_object_unref (G_OBJECT (httpepserver) ); g_object_unref (G_OBJECT (session) ); g_slist_free_full (urls, g_free); g_free (env); } BOOST_AUTO_TEST_SUITE_END()<|endoftext|>
<commit_before>#ifndef REMAPFILTERBASE_HPP #define REMAPFILTERBASE_HPP #include "bridge.h" #include "Vector.hpp" #include "KeyCode.hpp" namespace org_pqrs_Karabiner { namespace RemapFilter { class RemapFilterBase { public: RemapFilterBase(unsigned int type) : type_(type) {} virtual ~RemapFilterBase(void) {} typedef unsigned int FilterValue; DECLARE_VECTOR(FilterValue); class FilterValueWithDataType { public: FilterValueWithDataType(void) : datatype(BRIDGE_DATATYPE_NONE), value(0) {} FilterValueWithDataType(unsigned int d, unsigned int v) : datatype(d), value(v) {} unsigned int datatype; unsigned int value; }; DECLARE_VECTOR(FilterValueWithDataType); virtual void initialize(const unsigned int* vec, size_t length) = 0; virtual bool isblocked(void) = 0; unsigned int get_type(void) const { return type_; } private: unsigned int type_; }; typedef RemapFilterBase* RemapFilterBasePointer; DECLARE_VECTOR(RemapFilterBasePointer); } } #endif <commit_msg>add #include<commit_after>#ifndef REMAPFILTERBASE_HPP #define REMAPFILTERBASE_HPP #include "bridge.h" #include "IOLogWrapper.hpp" #include "KeyCode.hpp" #include "Vector.hpp" namespace org_pqrs_Karabiner { namespace RemapFilter { class RemapFilterBase { public: RemapFilterBase(unsigned int type) : type_(type) {} virtual ~RemapFilterBase(void) {} typedef unsigned int FilterValue; DECLARE_VECTOR(FilterValue); class FilterValueWithDataType { public: FilterValueWithDataType(void) : datatype(BRIDGE_DATATYPE_NONE), value(0) {} FilterValueWithDataType(unsigned int d, unsigned int v) : datatype(d), value(v) {} unsigned int datatype; unsigned int value; }; DECLARE_VECTOR(FilterValueWithDataType); virtual void initialize(const unsigned int* vec, size_t length) = 0; virtual bool isblocked(void) = 0; unsigned int get_type(void) const { return type_; } private: unsigned int type_; }; typedef RemapFilterBase* RemapFilterBasePointer; DECLARE_VECTOR(RemapFilterBasePointer); } } #endif <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2017-2019 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/properties/propertypresetmanager.h> #include <inviwo/core/properties/property.h> #include <inviwo/core/properties/compositeproperty.h> #include <inviwo/core/metadata/containermetadata.h> #include <inviwo/core/util/stdextensions.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/network/networklock.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/properties/propertyfactory.h> #include <inviwo/core/metadata/metadatafactory.h> namespace inviwo { PropertyPresetManager::PropertyPresetManager(InviwoApplication* app) : app_{app} { loadApplicationPresets(); } bool PropertyPresetManager::loadPreset(const std::string& name, Property* property, PropertyPresetType type) const { auto apply = [this](Property* p, const std::string& data) { NetworkLock lock(p); std::stringstream ss; ss << data; auto d = app_->getWorkspaceManager()->createWorkspaceDeserializer(ss, ""); // We deserialize into a clone here and link it to the original to only set value not // identifiers and such. auto temp = std::unique_ptr<Property>(p->clone()); temp->deserialize(d); p->set(temp.get()); }; switch (type) { case PropertyPresetType::Property: { auto pmap = getPropertyPresets(property); auto it = std::find_if(pmap.begin(), pmap.end(), [&](const auto& pair) { return pair.first == name; }); if (it != pmap.end()) { apply(property, it->second); return true; } break; } case PropertyPresetType::Workspace: { auto it = std::find_if(workspacePresets_.begin(), workspacePresets_.end(), [&](const auto& item) { return item.name == name; }); if (it != workspacePresets_.end() && it->classIdentifier == property->getClassIdentifier()) { apply(property, it->data); return true; } break; } case PropertyPresetType::Application: { auto it = std::find_if(appPresets_.begin(), appPresets_.end(), [&](const auto& item) { return item.name == name; }); if (it != appPresets_.end() && it->classIdentifier == property->getClassIdentifier()) { apply(property, it->data); return true; } break; } default: break; } return false; } void PropertyPresetManager::savePreset(const std::string& name, Property* property, PropertyPresetType type) { if (!property) return; Serializer serializer(""); { auto reset = scopedSerializationModeAll(property); property->serialize(serializer); } std::stringstream ss; serializer.writeFile(ss); switch (type) { case PropertyPresetType::Property: { auto& pmap = getPropertyPresets(property); pmap[name] = ss.str(); break; } case PropertyPresetType::Workspace: { auto it = std::find_if(workspacePresets_.begin(), workspacePresets_.end(), [&](const auto& item) { return item.name == name; }); if (it != workspacePresets_.end()) { it->classIdentifier = property->getClassIdentifier(); it->data = ss.str(); } else { workspacePresets_.emplace_back(property->getClassIdentifier(), name, ss.str()); } break; } case PropertyPresetType::Application: { auto it = std::find_if(appPresets_.begin(), appPresets_.end(), [&](const auto& item) { return item.name == name; }); if (it != appPresets_.end()) { it->classIdentifier = property->getClassIdentifier(); it->data = ss.str(); } else { appPresets_.emplace_back(property->getClassIdentifier(), name, ss.str()); } saveApplicationPresets(); break; } default: break; } } bool PropertyPresetManager::removePreset(const std::string& name, PropertyPresetType type, Property* property) { switch (type) { case PropertyPresetType::Property: { if (!property) return false; auto& pmap = getPropertyPresets(property); return pmap.erase(name) > 0; } case PropertyPresetType::Workspace: { return util::erase_remove_if(workspacePresets_, [&](const auto& item) { return item.name == name; }) > 0; } case PropertyPresetType::Application: { auto removed = util::erase_remove_if( appPresets_, [&](const auto& item) { return item.name == name; }); saveApplicationPresets(); return removed > 0; } default: return false; } } void PropertyPresetManager::appendPropertyPresets(Property* target, Property* source) { auto& pmap = getPropertyPresets(target); for (auto item : getPropertyPresets(source)) { pmap[item.first] = item.second; } } inviwo::util::OnScopeExit PropertyPresetManager::scopedSerializationModeAll(Property* property) { std::vector<std::pair<Property*, PropertySerializationMode>> toReset; std::function<void(Property*)> setPSM = [&](Property* p) { if (p->getSerializationMode() != PropertySerializationMode::All) { toReset.emplace_back(p, p->getSerializationMode()); p->setSerializationMode(PropertySerializationMode::All); } if (auto comp = dynamic_cast<CompositeProperty*>(p)) { for (auto child : comp->getProperties()) { setPSM(child); } } }; setPSM(property); return util::OnScopeExit{[toReset]() { for (auto item : toReset) { item.first->setSerializationMode(item.second); } }}; } std::vector<std::string> PropertyPresetManager::getAvailablePresets( Property* property, PropertyPresetTypes types) const { std::vector<std::string> result; if (types & PropertyPresetType::Property) { auto pmap = getPropertyPresets(property); std::transform(pmap.begin(), pmap.end(), std::back_inserter(result), [&](const auto& pair) { return pair.first; }); } if (types & PropertyPresetType::Workspace) { for (auto& item : workspacePresets_) { if (item.classIdentifier == property->getClassIdentifier()) { result.push_back(item.name); } } } if (types & PropertyPresetType::Application) { for (auto& item : appPresets_) { if (item.classIdentifier == property->getClassIdentifier()) { result.push_back(item.name); } } } return result; } void PropertyPresetManager::loadApplicationPresets() { std::string filename = filesystem::getPath(PathType::Settings, "/PropertyPresets.ivs"); if (filesystem::fileExists(filename)) { try { Deserializer d(filename); d.deserialize("PropertyPresets", appPresets_, "Preset"); } catch (AbortException& e) { LogError(e.getMessage()); } catch (std::exception& e) { LogError(e.what()); } } } void PropertyPresetManager::saveApplicationPresets() { try { Serializer s(filesystem::getPath(PathType::Settings, "/PropertyPresets.ivs", true)); s.serialize("PropertyPresets", appPresets_, "Preset"); s.writeFile(); } catch (const std::exception& e) { LogWarn("Could not write application presets: " << e.what()); } } void PropertyPresetManager::clearPropertyPresets(Property* property) { if (!property) return; auto& pmap = getPropertyPresets(property); pmap.clear(); } void PropertyPresetManager::clearWorkspacePresets() { workspacePresets_.clear(); } void PropertyPresetManager::loadWorkspacePresets(Deserializer& d) { workspacePresets_.clear(); d.deserialize("PropertyPresets", workspacePresets_, "Preset"); } void PropertyPresetManager::saveWorkspacePresets(Serializer& s) { s.serialize("PropertyPresets", workspacePresets_, "Preset"); } PropertyPresetManager::Preset::Preset() = default; PropertyPresetManager::Preset::Preset(std::string id, std::string n, std::string d) : classIdentifier(id), name(n), data(d) {} PropertyPresetManager::Preset::~Preset() = default; void PropertyPresetManager::Preset::serialize(Serializer& s) const { s.serialize("classIdentifier", classIdentifier); s.serialize("name", name); s.serialize("data", data); } void PropertyPresetManager::Preset::deserialize(Deserializer& d) { d.deserialize("classIdentifier", classIdentifier); d.deserialize("name", name); d.deserialize("data", data); } std::map<std::string, std::string>& PropertyPresetManager::getPropertyPresets(Property* property) { using MT = StdUnorderedMapMetaData<std::string, std::string>; return property->createMetaData<MT>("SavedState")->getMap(); } } // namespace inviwo <commit_msg>Core: PropertyPresetManager: Fix for applying present on SerializationMode::None<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2017-2019 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/properties/propertypresetmanager.h> #include <inviwo/core/properties/property.h> #include <inviwo/core/properties/compositeproperty.h> #include <inviwo/core/metadata/containermetadata.h> #include <inviwo/core/util/stdextensions.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/network/networklock.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/properties/propertyfactory.h> #include <inviwo/core/metadata/metadatafactory.h> namespace inviwo { PropertyPresetManager::PropertyPresetManager(InviwoApplication* app) : app_{app} { loadApplicationPresets(); } bool PropertyPresetManager::loadPreset(const std::string& name, Property* property, PropertyPresetType type) const { auto apply = [this](Property* p, const std::string& data) { NetworkLock lock(p); std::stringstream ss; ss << data; auto d = app_->getWorkspaceManager()->createWorkspaceDeserializer(ss, ""); // We deserialize into a clone here and link it to the original to only set value not // identifiers and such. auto temp = std::unique_ptr<Property>(p->clone()); auto reset = scopedSerializationModeAll(temp); temp->deserialize(d); p->set(temp.get()); }; switch (type) { case PropertyPresetType::Property: { auto pmap = getPropertyPresets(property); auto it = std::find_if(pmap.begin(), pmap.end(), [&](const auto& pair) { return pair.first == name; }); if (it != pmap.end()) { apply(property, it->second); return true; } break; } case PropertyPresetType::Workspace: { auto it = std::find_if(workspacePresets_.begin(), workspacePresets_.end(), [&](const auto& item) { return item.name == name; }); if (it != workspacePresets_.end() && it->classIdentifier == property->getClassIdentifier()) { apply(property, it->data); return true; } break; } case PropertyPresetType::Application: { auto it = std::find_if(appPresets_.begin(), appPresets_.end(), [&](const auto& item) { return item.name == name; }); if (it != appPresets_.end() && it->classIdentifier == property->getClassIdentifier()) { apply(property, it->data); return true; } break; } default: break; } return false; } void PropertyPresetManager::savePreset(const std::string& name, Property* property, PropertyPresetType type) { if (!property) return; Serializer serializer(""); { auto reset = scopedSerializationModeAll(property); property->serialize(serializer); } std::stringstream ss; serializer.writeFile(ss); switch (type) { case PropertyPresetType::Property: { auto& pmap = getPropertyPresets(property); pmap[name] = ss.str(); break; } case PropertyPresetType::Workspace: { auto it = std::find_if(workspacePresets_.begin(), workspacePresets_.end(), [&](const auto& item) { return item.name == name; }); if (it != workspacePresets_.end()) { it->classIdentifier = property->getClassIdentifier(); it->data = ss.str(); } else { workspacePresets_.emplace_back(property->getClassIdentifier(), name, ss.str()); } break; } case PropertyPresetType::Application: { auto it = std::find_if(appPresets_.begin(), appPresets_.end(), [&](const auto& item) { return item.name == name; }); if (it != appPresets_.end()) { it->classIdentifier = property->getClassIdentifier(); it->data = ss.str(); } else { appPresets_.emplace_back(property->getClassIdentifier(), name, ss.str()); } saveApplicationPresets(); break; } default: break; } } bool PropertyPresetManager::removePreset(const std::string& name, PropertyPresetType type, Property* property) { switch (type) { case PropertyPresetType::Property: { if (!property) return false; auto& pmap = getPropertyPresets(property); return pmap.erase(name) > 0; } case PropertyPresetType::Workspace: { return util::erase_remove_if(workspacePresets_, [&](const auto& item) { return item.name == name; }) > 0; } case PropertyPresetType::Application: { auto removed = util::erase_remove_if( appPresets_, [&](const auto& item) { return item.name == name; }); saveApplicationPresets(); return removed > 0; } default: return false; } } void PropertyPresetManager::appendPropertyPresets(Property* target, Property* source) { auto& pmap = getPropertyPresets(target); for (auto item : getPropertyPresets(source)) { pmap[item.first] = item.second; } } inviwo::util::OnScopeExit PropertyPresetManager::scopedSerializationModeAll(Property* property) { std::vector<std::pair<Property*, PropertySerializationMode>> toReset; std::function<void(Property*)> setPSM = [&](Property* p) { if (p->getSerializationMode() != PropertySerializationMode::All) { toReset.emplace_back(p, p->getSerializationMode()); p->setSerializationMode(PropertySerializationMode::All); } if (auto comp = dynamic_cast<CompositeProperty*>(p)) { for (auto child : comp->getProperties()) { setPSM(child); } } }; setPSM(property); return util::OnScopeExit{[toReset]() { for (auto item : toReset) { item.first->setSerializationMode(item.second); } }}; } std::vector<std::string> PropertyPresetManager::getAvailablePresets( Property* property, PropertyPresetTypes types) const { std::vector<std::string> result; if (types & PropertyPresetType::Property) { auto pmap = getPropertyPresets(property); std::transform(pmap.begin(), pmap.end(), std::back_inserter(result), [&](const auto& pair) { return pair.first; }); } if (types & PropertyPresetType::Workspace) { for (auto& item : workspacePresets_) { if (item.classIdentifier == property->getClassIdentifier()) { result.push_back(item.name); } } } if (types & PropertyPresetType::Application) { for (auto& item : appPresets_) { if (item.classIdentifier == property->getClassIdentifier()) { result.push_back(item.name); } } } return result; } void PropertyPresetManager::loadApplicationPresets() { std::string filename = filesystem::getPath(PathType::Settings, "/PropertyPresets.ivs"); if (filesystem::fileExists(filename)) { try { Deserializer d(filename); d.deserialize("PropertyPresets", appPresets_, "Preset"); } catch (AbortException& e) { LogError(e.getMessage()); } catch (std::exception& e) { LogError(e.what()); } } } void PropertyPresetManager::saveApplicationPresets() { try { Serializer s(filesystem::getPath(PathType::Settings, "/PropertyPresets.ivs", true)); s.serialize("PropertyPresets", appPresets_, "Preset"); s.writeFile(); } catch (const std::exception& e) { LogWarn("Could not write application presets: " << e.what()); } } void PropertyPresetManager::clearPropertyPresets(Property* property) { if (!property) return; auto& pmap = getPropertyPresets(property); pmap.clear(); } void PropertyPresetManager::clearWorkspacePresets() { workspacePresets_.clear(); } void PropertyPresetManager::loadWorkspacePresets(Deserializer& d) { workspacePresets_.clear(); d.deserialize("PropertyPresets", workspacePresets_, "Preset"); } void PropertyPresetManager::saveWorkspacePresets(Serializer& s) { s.serialize("PropertyPresets", workspacePresets_, "Preset"); } PropertyPresetManager::Preset::Preset() = default; PropertyPresetManager::Preset::Preset(std::string id, std::string n, std::string d) : classIdentifier(id), name(n), data(d) {} PropertyPresetManager::Preset::~Preset() = default; void PropertyPresetManager::Preset::serialize(Serializer& s) const { s.serialize("classIdentifier", classIdentifier); s.serialize("name", name); s.serialize("data", data); } void PropertyPresetManager::Preset::deserialize(Deserializer& d) { d.deserialize("classIdentifier", classIdentifier); d.deserialize("name", name); d.deserialize("data", data); } std::map<std::string, std::string>& PropertyPresetManager::getPropertyPresets(Property* property) { using MT = StdUnorderedMapMetaData<std::string, std::string>; return property->createMetaData<MT>("SavedState")->getMap(); } } // namespace inviwo <|endoftext|>
<commit_before>#include <ros/ros.h> #include <rosbag/bag.h> #include <rosbag/view.h> #include <boost/foreach.hpp> #include <lightsfm/vector2d.hpp> #include <lightsfm/angle.hpp> #include <upo_msgs/PersonPoseArrayUPO.h> #include <nav_msgs/Odometry.h> #include <vector> #include <tf/transform_listener.h> #include <teresa_wsbs/Info.h> #include <animated_marker_msgs/AnimatedMarkerArray.h> #include <fstream> #define foreach BOOST_FOREACH std::vector<double> distance_to_target; std::vector<double> target_force; utils::Vector2d robot_position; utils::Vector2d target_position; std::vector<utils::Vector2d> people_position; std::vector<utils::Vector2d> people_velocity; std::ofstream out_stream; bool calculateMetrics(int trajectory_index, double time) { bool valid_trajectory = distance_to_target.size()>0 && target_force.size()>0; if (!valid_trajectory) { return false; } out_stream<<trajectory_index<<" "<<time; if (distance_to_target.size()>0) { double d=0; for (unsigned i=0;i<distance_to_target.size();i++) { d+=distance_to_target[i]; } d /= (double) distance_to_target.size(); ROS_INFO("Average distance to target: %f m",d); out_stream<<" "<<d; distance_to_target.clear(); } else { out_stream<<" Inf"; } if (target_force.size()>0) { double f=0; for (unsigned i=0;i<target_force.size();i++) { f+=target_force[i]; } f /= (double) target_force.size(); out_stream<<" "<<f; ROS_INFO("Average Target Group Force: %f",f); target_force.clear(); } else { out_stream<<" Inf"; } out_stream<<"\n"; return true; } void readPeople(const upo_msgs::PersonPoseArrayUPO::ConstPtr& people_ptr) { // TODO: Update people_position and people_velocity } void readTarget(animated_marker_msgs::AnimatedMarkerArray::ConstPtr& marker_array_ptr) { target_position.set(marker_array_ptr->markers[0].pose.position.x,marker_array_ptr->markers[0].pose.position.y); distance_to_target.push_back((robot_position-target_position).norm()); } void readOdom(const nav_msgs::Odometry::ConstPtr& odom) { robot_position.set(odom->pose.pose.position.x,odom->pose.pose.position.y); } void readInfo(const teresa_wsbs::Info::ConstPtr& info) { if (!info->target_detected || info->status!=5) { return; } utils::Vector2d f(info->target_group_force.x,info->target_group_force.y); target_force.push_back(f.norm()); } int main(int argc, char** argv) { ros::init(argc, argv, "wsbs_stats"); ros::NodeHandle n; ros::NodeHandle pn("~"); std::string bag_name, people_topic; std::string out_file; bool trajectory_running=false; unsigned trajectory_counter=0; double lambda; double initial_time; pn.param<std::string>("bag_name",bag_name,"/home/ignacio/baseline.bag"); // Bag name pn.param<std::string>("people_topic",people_topic,"/people/navigation"); pn.param<std::string>("out_file",out_file,"/home/ignacio/results.txt"); pn.param<double>("lambda",lambda,0.4); std::vector<std::string> topics; topics.push_back(people_topic); topics.push_back("/odom"); topics.push_back("/wsbs/controller/info"); topics.push_back("/clicked_point"); topics.push_back("/wsbs/markers/target"); out_stream.open (out_file); out_stream<<"Trajectory index Time Average Distance to Target Average Target Social Force\n"; rosbag::Bag bag; ROS_INFO("Opening bag %s...",bag_name.c_str()); bag.open(bag_name,rosbag::bagmode::Read); ROS_INFO("Processing bag %s...",bag_name.c_str()); rosbag::View view(bag, rosbag::TopicQuery(topics)); foreach(rosbag::MessageInstance const m, view) { //ROS_INFO("Reading %s at time %f s. ",m.getTopic().c_str(),m.getTime().toSec()); if (m.getTopic().compare(people_topic)==0) { upo_msgs::PersonPoseArrayUPO::ConstPtr people_ptr = m.instantiate<upo_msgs::PersonPoseArrayUPO>(); readPeople(people_ptr); } else if (m.getTopic().compare("/odom")==0) { nav_msgs::Odometry::ConstPtr odom_ptr = m.instantiate<nav_msgs::Odometry>(); readOdom(odom_ptr); } else if (m.getTopic().compare("/wsbs/controller/info")==0) { teresa_wsbs::Info::ConstPtr info_ptr = m.instantiate<teresa_wsbs::Info>(); readInfo(info_ptr); } else if (m.getTopic().compare("/wsbs/markers/target")==0) { animated_marker_msgs::AnimatedMarkerArray::ConstPtr marker_array_ptr = m.instantiate<animated_marker_msgs::AnimatedMarkerArray>(); readTarget(marker_array_ptr); } else if (m.getTopic().compare("/clicked_point")==0) { trajectory_running = !trajectory_running; if (trajectory_running) { trajectory_counter++; initial_time = m.getTime().toSec(); ROS_INFO("Trajectory N. %d begins at time %f s",trajectory_counter,m.getTime().toSec()); } else { ROS_INFO("Trajectory N. %d finishes at time %f s",trajectory_counter,m.getTime().toSec()); bool valid =calculateMetrics(trajectory_counter, m.getTime().toSec()-initial_time); if (!valid) { ROS_INFO("Invalid trajectory"); trajectory_counter--; } } } } out_stream.close(); return 0; } <commit_msg>Performance metrics<commit_after>#include <ros/ros.h> #include <rosbag/bag.h> #include <rosbag/view.h> #include <boost/foreach.hpp> #include <lightsfm/vector2d.hpp> #include <lightsfm/angle.hpp> #include <lightpomcp/Random.hpp> #include <upo_msgs/PersonPoseArrayUPO.h> #include <nav_msgs/Odometry.h> #include <vector> #include <tf/transform_listener.h> #include <teresa_wsbs/Info.h> #include <animated_marker_msgs/AnimatedMarkerArray.h> #include <fstream> #define foreach BOOST_FOREACH std::vector<double> distance_to_target; std::vector<double> target_force; utils::Vector2d robot_position; utils::Vector2d target_position; utils::Angle target_yaw; std::vector<utils::Vector2d> people_position; std::vector<utils::Angle> people_yaw; std::vector<double> confort; std::ofstream out_stream; double lambda; double robot_area_radius; int confort_particles; // return true if x is in inside the intimate distance(*factor) of person p with yaw bool intimateDistance(const utils::Vector2d& x, const utils::Vector2d& p, const utils::Angle& yaw, double factor=1.0) { utils::Vector2d n = (p - x).normalized(); utils::Vector2d e(yaw.cos(),yaw.sin()); double cos_phi = -n.dot(e); double w = lambda + (1-lambda)*(1+cos_phi)*0.5; w *= factor; double dis = (p-x).norm(); return dis < w; } double calculateConfort() { utils::Vector2d x; double squared_robot_area_radius = robot_area_radius*robot_area_radius; double score=0; for (int i = 0; i< confort_particles; i++) { // Select a random particle in the robot area do { x.set(utils::RANDOM()*robot_area_radius, utils::RANDOM()*robot_area_radius); } while (x[0]*x[0] + x[1]*x[1] > squared_robot_area_radius); unsigned quadrant = utils::RANDOM(4); if (quadrant==2 || quadrant==3) { x.setX(-x[0]); } if (quadrant==1 || quadrant==2) { x.setY(-x[1]); } x+=robot_position; bool tooCloseToSomebody=false; for (unsigned j=0;j<people_position.size();j++) { if (intimateDistance(x,people_position[j],people_yaw[j])) { tooCloseToSomebody=true; break; } } if (tooCloseToSomebody) { continue; } if (intimateDistance(x,target_position,target_yaw,3.0)) { score += 1.0; } else if ((x - target_position).norm() < 3.0) { score += 0.5; } } score /= (double)confort_particles; return score; } bool calculateMetrics(int trajectory_index, double time) { bool valid_trajectory = distance_to_target.size()>0 && target_force.size()>0; if (!valid_trajectory) { return false; } out_stream<<trajectory_index<<"\t"<<time; if (distance_to_target.size()>0) { double d=0; for (unsigned i=0;i<distance_to_target.size();i++) { d+=distance_to_target[i]; } d /= (double) distance_to_target.size(); ROS_INFO("Average distance to target: %f m",d); out_stream<<"\t"<<d; distance_to_target.clear(); } else { out_stream<<"\tInf"; } if (target_force.size()>0) { double f=0; for (unsigned i=0;i<target_force.size();i++) { f+=target_force[i]; } f /= (double) target_force.size(); out_stream<<"\t"<<f; ROS_INFO("Average Target Group Force: %f",f); target_force.clear(); } else { out_stream<<"\tInf"; } if (confort.size()>0) { double average_confort=0; for (unsigned i=0;i<confort.size();i++) { average_confort+=confort[i]; } average_confort /= (double) confort.size(); out_stream<<"\t"<<average_confort; ROS_INFO("Average confort: %f",average_confort); confort.clear(); } else { out_stream<<"\t0"; } out_stream<<"\n"; return true; } void readPeople(const upo_msgs::PersonPoseArrayUPO::ConstPtr& people_ptr) { people_position.resize(people_ptr->personPoses.size()); people_yaw.resize(people_ptr->personPoses.size()); for (unsigned i=0; i< people_ptr->personPoses.size(); i++) { people_position[i].set(people_ptr->personPoses[i].position.x,people_ptr->personPoses[i].position.y); people_yaw[i] = utils::Angle::fromRadian(tf::getYaw(people_ptr->personPoses[i].orientation)); } } void readTarget(animated_marker_msgs::AnimatedMarkerArray::ConstPtr& marker_array_ptr) { target_position.set(marker_array_ptr->markers[0].pose.position.x,marker_array_ptr->markers[0].pose.position.y); target_yaw = utils::Angle::fromRadian(tf::getYaw(marker_array_ptr->markers[0].pose.orientation)); target_yaw += utils::Angle::fromRadian(M_PI*0.5); distance_to_target.push_back((robot_position-target_position).norm()); confort.push_back(calculateConfort()); } void readOdom(const nav_msgs::Odometry::ConstPtr& odom) { robot_position.set(odom->pose.pose.position.x,odom->pose.pose.position.y); } void readInfo(const teresa_wsbs::Info::ConstPtr& info) { if (!info->target_detected || info->status!=5) { return; } utils::Vector2d f(info->target_group_force.x,info->target_group_force.y); target_force.push_back(f.norm()); } int main(int argc, char** argv) { ros::init(argc, argv, "wsbs_stats"); ros::NodeHandle n; ros::NodeHandle pn("~"); std::string bag_name, people_topic; std::string out_file; bool trajectory_running=false; unsigned trajectory_counter=0; double initial_time; pn.param<std::string>("bag_name",bag_name,"/home/ignacio/baseline.bag"); // Bag name pn.param<std::string>("people_topic",people_topic,"/people/navigation"); pn.param<std::string>("out_file",out_file,"/home/ignacio/results.txt"); pn.param<double>("robot_area_radius",robot_area_radius,0.5); pn.param<int>("confort_particles",confort_particles,1000); pn.param<double>("lambda",lambda,0.4); std::vector<std::string> topics; topics.push_back(people_topic); topics.push_back("/odom"); topics.push_back("/wsbs/controller/info"); topics.push_back("/clicked_point"); topics.push_back("/wsbs/markers/target"); out_stream.open (out_file); out_stream<<"Trajectory index\tTime\tAverage Distance to Target\tAverage Target Social Force\tConfort\n"; rosbag::Bag bag; ROS_INFO("Opening bag %s...",bag_name.c_str()); bag.open(bag_name,rosbag::bagmode::Read); ROS_INFO("Processing bag %s...",bag_name.c_str()); rosbag::View view(bag, rosbag::TopicQuery(topics)); foreach(rosbag::MessageInstance const m, view) { //ROS_INFO("Reading %s at time %f s. ",m.getTopic().c_str(),m.getTime().toSec()); if (m.getTopic().compare(people_topic)==0) { upo_msgs::PersonPoseArrayUPO::ConstPtr people_ptr = m.instantiate<upo_msgs::PersonPoseArrayUPO>(); readPeople(people_ptr); } else if (m.getTopic().compare("/odom")==0) { nav_msgs::Odometry::ConstPtr odom_ptr = m.instantiate<nav_msgs::Odometry>(); readOdom(odom_ptr); } else if (m.getTopic().compare("/wsbs/controller/info")==0) { teresa_wsbs::Info::ConstPtr info_ptr = m.instantiate<teresa_wsbs::Info>(); readInfo(info_ptr); } else if (m.getTopic().compare("/wsbs/markers/target")==0) { animated_marker_msgs::AnimatedMarkerArray::ConstPtr marker_array_ptr = m.instantiate<animated_marker_msgs::AnimatedMarkerArray>(); readTarget(marker_array_ptr); } else if (m.getTopic().compare("/clicked_point")==0) { trajectory_running = !trajectory_running; if (trajectory_running) { trajectory_counter++; initial_time = m.getTime().toSec(); ROS_INFO("Trajectory N. %d begins at time %f s",trajectory_counter,m.getTime().toSec()); } else { ROS_INFO("Trajectory N. %d finishes at time %f s",trajectory_counter,m.getTime().toSec()); bool valid =calculateMetrics(trajectory_counter, m.getTime().toSec()-initial_time); if (!valid) { ROS_INFO("Invalid trajectory"); trajectory_counter--; } } } } out_stream.close(); return 0; } <|endoftext|>
<commit_before>/* * SessionReticulate.cpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionReticulate.hpp" #include <boost/bind.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <r/RExec.hpp> #include <session/SessionModuleContext.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace reticulate { bool isReplActive() { bool active = false; Error error = r::exec::RFunction("reticulate::py_repl_active").call(&active); if (error) LOG_ERROR(error); return active; } Error initialize() { using namespace module_context; ExecBlock initBlock; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionReticulate.R")); return initBlock.execute(); } } // end namespace reticulate } // end namespace modules } // end namespace session } // end namespace rstudio <commit_msg>use three colons<commit_after>/* * SessionReticulate.cpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionReticulate.hpp" #include <boost/bind.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <r/RExec.hpp> #include <session/SessionModuleContext.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace reticulate { bool isReplActive() { bool active = false; Error error = r::exec::RFunction("reticulate:::py_repl_active").call(&active); if (error) LOG_ERROR(error); return active; } Error initialize() { using namespace module_context; ExecBlock initBlock; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionReticulate.R")); return initBlock.execute(); } } // end namespace reticulate } // end namespace modules } // end namespace session } // end namespace rstudio <|endoftext|>
<commit_before>// // Copyright 2014 DreamWorks Animation LLC. // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "../far/topologyRefinerFactory.h" #include "../far/topologyRefiner.h" #include "../vtr/level.h" #include <cstdio> #ifdef _MSC_VER #define snprintf _snprintf #endif namespace OpenSubdiv { namespace OPENSUBDIV_VERSION { namespace Far { // // Methods for the Factory base class -- general enough to warrant including in // the base class rather than the subclass template (and so replicated for each // usage) // // bool TopologyRefinerFactoryBase::prepareComponentTopologySizing(TopologyRefiner& refiner) { Vtr::internal::Level& baseLevel = refiner.getLevel(0); // // At minimum we require face-vertices (the total count of which can be determined // from the offsets accumulated during sizing pass) and we need to resize members // related to them to be populated during assignment: // int vCount = baseLevel.getNumVertices(); int fCount = baseLevel.getNumFaces(); assert((vCount > 0) && (fCount > 0)); // Make sure no face was defined that would lead to a valence overflow -- the max // valence has been initialized with the maximum number of face-vertices: if (baseLevel.getMaxValence() > Vtr::VALENCE_LIMIT) { char msg[1024]; snprintf(msg, 1024, "Invalid topology specified : face with %d vertices > %d max.", baseLevel.getMaxValence(), Vtr::VALENCE_LIMIT); Warning(msg); return false; } int fVertCount = baseLevel.getNumFaceVertices(fCount - 1) + baseLevel.getOffsetOfFaceVertices(fCount - 1); if ((refiner.GetSchemeType() == Sdc::SCHEME_LOOP) && (fVertCount != (3 * fCount))) { char msg[1024]; snprintf(msg, 1024, "Invalid topology specified : non-triangular faces not supported by Loop scheme."); Warning(msg); return false; } baseLevel.resizeFaceVertices(fVertCount); assert(baseLevel.getNumFaceVerticesTotal() > 0); // // If edges were sized, all other topological relations must be sized with it, in // which case we allocate those members to be populated. Otherwise, sizing of the // other topology members is deferred until the face-vertices are assigned and the // resulting relationships determined: // int eCount = baseLevel.getNumEdges(); if (eCount > 0) { baseLevel.resizeFaceEdges(baseLevel.getNumFaceVerticesTotal()); baseLevel.resizeEdgeVertices(); baseLevel.resizeEdgeFaces( baseLevel.getNumEdgeFaces(eCount-1) + baseLevel.getOffsetOfEdgeFaces(eCount-1)); baseLevel.resizeVertexFaces(baseLevel.getNumVertexFaces(vCount-1) + baseLevel.getOffsetOfVertexFaces(vCount-1)); baseLevel.resizeVertexEdges(baseLevel.getNumVertexEdges(vCount-1) + baseLevel.getOffsetOfVertexEdges(vCount-1)); assert(baseLevel.getNumFaceEdgesTotal() > 0); assert(baseLevel.getNumEdgeVerticesTotal() > 0); assert(baseLevel.getNumEdgeFacesTotal() > 0); assert(baseLevel.getNumVertexFacesTotal() > 0); assert(baseLevel.getNumVertexEdgesTotal() > 0); } return true; } bool TopologyRefinerFactoryBase::prepareComponentTopologyAssignment(TopologyRefiner& refiner, bool fullValidation, TopologyCallback callback, void const * callbackData) { Vtr::internal::Level& baseLevel = refiner.getLevel(0); bool completeMissingTopology = (baseLevel.getNumEdges() == 0); if (completeMissingTopology) { if (not baseLevel.completeTopologyFromFaceVertices()) { char msg[1024]; snprintf(msg, 1024, "Invalid topology detected : vertex with valence %d > %d max.", baseLevel.getMaxValence(), Vtr::VALENCE_LIMIT); Warning(msg); return false; } } else { if (baseLevel.getMaxValence() == 0) { char msg[1024]; snprintf(msg, 1024, "Invalid topology detected : maximum valence not assigned."); Warning(msg); return false; } } if (fullValidation) { if (not baseLevel.validateTopology(callback, callbackData)) { char msg[1024]; snprintf(msg, 1024, completeMissingTopology ? "Invalid topology detected as completed from partial specification." : "Invalid topology detected as fully specified."); Warning(msg); return false; } } // Now that we have a valid base level, initialize the Refiner's component inventory: refiner.initializeInventory(); return true; } bool TopologyRefinerFactoryBase::prepareComponentTagsAndSharpness(TopologyRefiner& refiner) { // // This method combines the initialization of internal component tags with the sharpening // of edges and vertices according to the given boundary interpolation rule in the Options. // Since both involve traversing the edge and vertex lists and noting the presence of // boundaries -- best to do both at once... // Vtr::internal::Level& baseLevel = refiner.getLevel(0); Sdc::Options options = refiner.GetSchemeOptions(); Sdc::Crease creasing(options); bool makeBoundaryFacesHoles = (options.GetVtxBoundaryInterpolation() == Sdc::Options::VTX_BOUNDARY_NONE); bool sharpenCornerVerts = (options.GetVtxBoundaryInterpolation() == Sdc::Options::VTX_BOUNDARY_EDGE_AND_CORNER); bool sharpenNonManFeatures = true; //(options.GetNonManifoldInterpolation() == Sdc::Options::NON_MANIFOLD_SHARP); // // Process the Edge tags first, as Vertex tags (notably the Rule) are dependent on // properties of their incident edges. // for (Vtr::Index eIndex = 0; eIndex < baseLevel.getNumEdges(); ++eIndex) { Vtr::internal::Level::ETag& eTag = baseLevel.getEdgeTag(eIndex); float& eSharpness = baseLevel.getEdgeSharpness(eIndex); eTag._boundary = (baseLevel.getNumEdgeFaces(eIndex) < 2); if (eTag._boundary || (eTag._nonManifold && sharpenNonManFeatures)) { eSharpness = Sdc::Crease::SHARPNESS_INFINITE; } eTag._infSharp = Sdc::Crease::IsInfinite(eSharpness); eTag._semiSharp = Sdc::Crease::IsSharp(eSharpness) && !eTag._infSharp; } // // Process the Vertex tags now -- for some tags (semi-sharp and its rule) we need // to inspect all incident edges: // int schemeRegularInteriorValence = Sdc::SchemeTypeTraits::GetRegularVertexValence(refiner.GetSchemeType()); int schemeRegularBoundaryValence = schemeRegularInteriorValence / 2; for (Vtr::Index vIndex = 0; vIndex < baseLevel.getNumVertices(); ++vIndex) { Vtr::internal::Level::VTag& vTag = baseLevel.getVertexTag(vIndex); float& vSharpness = baseLevel.getVertexSharpness(vIndex); Vtr::ConstIndexArray vEdges = baseLevel.getVertexEdges(vIndex); Vtr::ConstIndexArray vFaces = baseLevel.getVertexFaces(vIndex); // // Take inventory of properties of incident edges that affect this vertex: // int boundaryEdgeCount = 0; int infSharpEdgeCount = 0; int semiSharpEdgeCount = 0; int nonManifoldEdgeCount = 0; for (int i = 0; i < vEdges.size(); ++i) { Vtr::internal::Level::ETag const& eTag = baseLevel.getEdgeTag(vEdges[i]); boundaryEdgeCount += eTag._boundary; infSharpEdgeCount += eTag._infSharp; semiSharpEdgeCount += eTag._semiSharp; nonManifoldEdgeCount += eTag._nonManifold; } int sharpEdgeCount = infSharpEdgeCount + semiSharpEdgeCount; // // Sharpen the vertex before using it in conjunction with incident edge // properties to determine the semi-sharp tag and rule: // bool isTopologicalCorner = (vFaces.size() == 1) && (vEdges.size() == 2); bool isSharpenedCorner = isTopologicalCorner && sharpenCornerVerts; if (isSharpenedCorner) { vSharpness = Sdc::Crease::SHARPNESS_INFINITE; } else if (vTag._nonManifold && sharpenNonManFeatures) { // // We avoid sharpening non-manifold vertices when they occur on interior // non-manifold creases, i.e. a pair of opposing non-manifold edges with // more than two incident faces. In these cases there are more incident // faces than edges (1 more for each additional "fin") and no boundaries. // if (not ((nonManifoldEdgeCount == 2) && (boundaryEdgeCount == 0) && (vFaces.size() > vEdges.size()))) { vSharpness = Sdc::Crease::SHARPNESS_INFINITE; } } vTag._infSharp = Sdc::Crease::IsInfinite(vSharpness); vTag._semiSharp = Sdc::Crease::IsSemiSharp(vSharpness); vTag._semiSharpEdges = (semiSharpEdgeCount > 0); vTag._rule = (Vtr::internal::Level::VTag::VTagSize)creasing.DetermineVertexVertexRule(vSharpness, sharpEdgeCount); // // Assign topological tags -- note that the "xordinary" tag is not strictly // correct (or relevant) if non-manifold: // vTag._boundary = (boundaryEdgeCount > 0); vTag._corner = isSharpenedCorner; if (vTag._corner) { vTag._xordinary = false; } else if (vTag._boundary) { vTag._xordinary = (vFaces.size() != schemeRegularBoundaryValence); } else { vTag._xordinary = (vFaces.size() != schemeRegularInteriorValence); } vTag._incomplete = 0; // // Having just decided if a vertex is on a boundary, and with its incident faces // available, mark incident faces as holes. // if (makeBoundaryFacesHoles && vTag._boundary) { for (int i = 0; i < vFaces.size(); ++i) { baseLevel.getFaceTag(vFaces[i])._hole = true; // Don't forget this -- but it will eventually move to the Level refiner._hasHoles = true; } } } return true; } bool TopologyRefinerFactoryBase::prepareFaceVaryingChannels(TopologyRefiner& refiner) { Vtr::internal::Level& baseLevel = refiner.getLevel(0); int regVertexValence = Sdc::SchemeTypeTraits::GetRegularVertexValence(refiner.GetSchemeType()); int regBoundaryValence = regVertexValence / 2; for (int channel=0; channel<refiner.GetNumFVarChannels(); ++channel) { baseLevel.completeFVarChannelTopology(channel, regBoundaryValence); } return true; } } // end namespace Far } // end namespace OPENSUBDIV_VERSION } // end namespace OpenSubdiv <commit_msg>Retains boundary faces of bilinear scheme mesh with VTX_BOUNDARY_NONE<commit_after>// // Copyright 2014 DreamWorks Animation LLC. // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "../far/topologyRefinerFactory.h" #include "../far/topologyRefiner.h" #include "../sdc/types.h" #include "../vtr/level.h" #include <cstdio> #ifdef _MSC_VER #define snprintf _snprintf #endif namespace OpenSubdiv { namespace OPENSUBDIV_VERSION { namespace Far { // // Methods for the Factory base class -- general enough to warrant including in // the base class rather than the subclass template (and so replicated for each // usage) // // bool TopologyRefinerFactoryBase::prepareComponentTopologySizing(TopologyRefiner& refiner) { Vtr::internal::Level& baseLevel = refiner.getLevel(0); // // At minimum we require face-vertices (the total count of which can be determined // from the offsets accumulated during sizing pass) and we need to resize members // related to them to be populated during assignment: // int vCount = baseLevel.getNumVertices(); int fCount = baseLevel.getNumFaces(); assert((vCount > 0) && (fCount > 0)); // Make sure no face was defined that would lead to a valence overflow -- the max // valence has been initialized with the maximum number of face-vertices: if (baseLevel.getMaxValence() > Vtr::VALENCE_LIMIT) { char msg[1024]; snprintf(msg, 1024, "Invalid topology specified : face with %d vertices > %d max.", baseLevel.getMaxValence(), Vtr::VALENCE_LIMIT); Warning(msg); return false; } int fVertCount = baseLevel.getNumFaceVertices(fCount - 1) + baseLevel.getOffsetOfFaceVertices(fCount - 1); if ((refiner.GetSchemeType() == Sdc::SCHEME_LOOP) && (fVertCount != (3 * fCount))) { char msg[1024]; snprintf(msg, 1024, "Invalid topology specified : non-triangular faces not supported by Loop scheme."); Warning(msg); return false; } baseLevel.resizeFaceVertices(fVertCount); assert(baseLevel.getNumFaceVerticesTotal() > 0); // // If edges were sized, all other topological relations must be sized with it, in // which case we allocate those members to be populated. Otherwise, sizing of the // other topology members is deferred until the face-vertices are assigned and the // resulting relationships determined: // int eCount = baseLevel.getNumEdges(); if (eCount > 0) { baseLevel.resizeFaceEdges(baseLevel.getNumFaceVerticesTotal()); baseLevel.resizeEdgeVertices(); baseLevel.resizeEdgeFaces( baseLevel.getNumEdgeFaces(eCount-1) + baseLevel.getOffsetOfEdgeFaces(eCount-1)); baseLevel.resizeVertexFaces(baseLevel.getNumVertexFaces(vCount-1) + baseLevel.getOffsetOfVertexFaces(vCount-1)); baseLevel.resizeVertexEdges(baseLevel.getNumVertexEdges(vCount-1) + baseLevel.getOffsetOfVertexEdges(vCount-1)); assert(baseLevel.getNumFaceEdgesTotal() > 0); assert(baseLevel.getNumEdgeVerticesTotal() > 0); assert(baseLevel.getNumEdgeFacesTotal() > 0); assert(baseLevel.getNumVertexFacesTotal() > 0); assert(baseLevel.getNumVertexEdgesTotal() > 0); } return true; } bool TopologyRefinerFactoryBase::prepareComponentTopologyAssignment(TopologyRefiner& refiner, bool fullValidation, TopologyCallback callback, void const * callbackData) { Vtr::internal::Level& baseLevel = refiner.getLevel(0); bool completeMissingTopology = (baseLevel.getNumEdges() == 0); if (completeMissingTopology) { if (not baseLevel.completeTopologyFromFaceVertices()) { char msg[1024]; snprintf(msg, 1024, "Invalid topology detected : vertex with valence %d > %d max.", baseLevel.getMaxValence(), Vtr::VALENCE_LIMIT); Warning(msg); return false; } } else { if (baseLevel.getMaxValence() == 0) { char msg[1024]; snprintf(msg, 1024, "Invalid topology detected : maximum valence not assigned."); Warning(msg); return false; } } if (fullValidation) { if (not baseLevel.validateTopology(callback, callbackData)) { char msg[1024]; snprintf(msg, 1024, completeMissingTopology ? "Invalid topology detected as completed from partial specification." : "Invalid topology detected as fully specified."); Warning(msg); return false; } } // Now that we have a valid base level, initialize the Refiner's component inventory: refiner.initializeInventory(); return true; } bool TopologyRefinerFactoryBase::prepareComponentTagsAndSharpness(TopologyRefiner& refiner) { // // This method combines the initialization of internal component tags with the sharpening // of edges and vertices according to the given boundary interpolation rule in the Options. // Since both involve traversing the edge and vertex lists and noting the presence of // boundaries -- best to do both at once... // Vtr::internal::Level& baseLevel = refiner.getLevel(0); Sdc::Options options = refiner.GetSchemeOptions(); Sdc::Crease creasing(options); bool makeBoundaryFacesHoles = (options.GetVtxBoundaryInterpolation() == Sdc::Options::VTX_BOUNDARY_NONE && Sdc::SchemeTypeTraits::GetLocalNeighborhoodSize(refiner.GetSchemeType()) > 0); bool sharpenCornerVerts = (options.GetVtxBoundaryInterpolation() == Sdc::Options::VTX_BOUNDARY_EDGE_AND_CORNER); bool sharpenNonManFeatures = true; //(options.GetNonManifoldInterpolation() == Sdc::Options::NON_MANIFOLD_SHARP); // // Process the Edge tags first, as Vertex tags (notably the Rule) are dependent on // properties of their incident edges. // for (Vtr::Index eIndex = 0; eIndex < baseLevel.getNumEdges(); ++eIndex) { Vtr::internal::Level::ETag& eTag = baseLevel.getEdgeTag(eIndex); float& eSharpness = baseLevel.getEdgeSharpness(eIndex); eTag._boundary = (baseLevel.getNumEdgeFaces(eIndex) < 2); if (eTag._boundary || (eTag._nonManifold && sharpenNonManFeatures)) { eSharpness = Sdc::Crease::SHARPNESS_INFINITE; } eTag._infSharp = Sdc::Crease::IsInfinite(eSharpness); eTag._semiSharp = Sdc::Crease::IsSharp(eSharpness) && !eTag._infSharp; } // // Process the Vertex tags now -- for some tags (semi-sharp and its rule) we need // to inspect all incident edges: // int schemeRegularInteriorValence = Sdc::SchemeTypeTraits::GetRegularVertexValence(refiner.GetSchemeType()); int schemeRegularBoundaryValence = schemeRegularInteriorValence / 2; for (Vtr::Index vIndex = 0; vIndex < baseLevel.getNumVertices(); ++vIndex) { Vtr::internal::Level::VTag& vTag = baseLevel.getVertexTag(vIndex); float& vSharpness = baseLevel.getVertexSharpness(vIndex); Vtr::ConstIndexArray vEdges = baseLevel.getVertexEdges(vIndex); Vtr::ConstIndexArray vFaces = baseLevel.getVertexFaces(vIndex); // // Take inventory of properties of incident edges that affect this vertex: // int boundaryEdgeCount = 0; int infSharpEdgeCount = 0; int semiSharpEdgeCount = 0; int nonManifoldEdgeCount = 0; for (int i = 0; i < vEdges.size(); ++i) { Vtr::internal::Level::ETag const& eTag = baseLevel.getEdgeTag(vEdges[i]); boundaryEdgeCount += eTag._boundary; infSharpEdgeCount += eTag._infSharp; semiSharpEdgeCount += eTag._semiSharp; nonManifoldEdgeCount += eTag._nonManifold; } int sharpEdgeCount = infSharpEdgeCount + semiSharpEdgeCount; // // Sharpen the vertex before using it in conjunction with incident edge // properties to determine the semi-sharp tag and rule: // bool isTopologicalCorner = (vFaces.size() == 1) && (vEdges.size() == 2); bool isSharpenedCorner = isTopologicalCorner && sharpenCornerVerts; if (isSharpenedCorner) { vSharpness = Sdc::Crease::SHARPNESS_INFINITE; } else if (vTag._nonManifold && sharpenNonManFeatures) { // // We avoid sharpening non-manifold vertices when they occur on interior // non-manifold creases, i.e. a pair of opposing non-manifold edges with // more than two incident faces. In these cases there are more incident // faces than edges (1 more for each additional "fin") and no boundaries. // if (not ((nonManifoldEdgeCount == 2) && (boundaryEdgeCount == 0) && (vFaces.size() > vEdges.size()))) { vSharpness = Sdc::Crease::SHARPNESS_INFINITE; } } vTag._infSharp = Sdc::Crease::IsInfinite(vSharpness); vTag._semiSharp = Sdc::Crease::IsSemiSharp(vSharpness); vTag._semiSharpEdges = (semiSharpEdgeCount > 0); vTag._rule = (Vtr::internal::Level::VTag::VTagSize)creasing.DetermineVertexVertexRule(vSharpness, sharpEdgeCount); // // Assign topological tags -- note that the "xordinary" tag is not strictly // correct (or relevant) if non-manifold: // vTag._boundary = (boundaryEdgeCount > 0); vTag._corner = isSharpenedCorner; if (vTag._corner) { vTag._xordinary = false; } else if (vTag._boundary) { vTag._xordinary = (vFaces.size() != schemeRegularBoundaryValence); } else { vTag._xordinary = (vFaces.size() != schemeRegularInteriorValence); } vTag._incomplete = 0; // // Having just decided if a vertex is on a boundary, and with its incident faces // available, mark incident faces as holes. // if (makeBoundaryFacesHoles && vTag._boundary) { for (int i = 0; i < vFaces.size(); ++i) { baseLevel.getFaceTag(vFaces[i])._hole = true; // Don't forget this -- but it will eventually move to the Level refiner._hasHoles = true; } } } return true; } bool TopologyRefinerFactoryBase::prepareFaceVaryingChannels(TopologyRefiner& refiner) { Vtr::internal::Level& baseLevel = refiner.getLevel(0); int regVertexValence = Sdc::SchemeTypeTraits::GetRegularVertexValence(refiner.GetSchemeType()); int regBoundaryValence = regVertexValence / 2; for (int channel=0; channel<refiner.GetNumFVarChannels(); ++channel) { baseLevel.completeFVarChannelTopology(channel, regBoundaryValence); } return true; } } // end namespace Far } // end namespace OPENSUBDIV_VERSION } // end namespace OpenSubdiv <|endoftext|>
<commit_before>/* <x0/server.hpp> * * This file is part of the x0 web server project and is released under LGPL-3. * * (c) 2009 Chrisitan Parpart <trapni@gentoo.org> */ #ifndef sw_x0_server_hpp #define sw_x0_server_hpp (1) #include <x0/datetime.hpp> #include <x0/settings.hpp> #include <x0/logger.hpp> #include <x0/signal.hpp> #include <x0/event_handler.hpp> #include <x0/http/request_handler.hpp> #include <x0/context.hpp> #include <x0/types.hpp> #include <x0/property.hpp> #include <x0/io/fileinfo_service.hpp> #include <x0/library.hpp> #include <x0/api.hpp> #include <x0/sysconfig.h> #include <boost/signals.hpp> #include <cstring> #include <string> #include <memory> #include <list> #include <map> #include <ev.h> namespace x0 { struct plugin; //! \addtogroup core //@{ enum context_mask { SERVER = 0x01, HOST = 0x02, PATH = 0x04 }; inline context_mask operator|(context_mask a, context_mask b) { return context_mask(int(a) | int(b)); } /** * \brief implements the x0 web server. * * \see connection, request, response, plugin * \see server::run(), server::stop() */ class server : public boost::noncopyable { private: typedef std::pair<plugin_ptr, library> plugin_value_t; typedef std::map<std::string, plugin_value_t> plugin_map_t; public: typedef x0::signal<void(connection *)> connection_hook; typedef x0::signal<void(request *)> request_parse_hook; typedef x0::signal<void(request *, response *)> request_post_hook; public: explicit server(struct ::ev_loop *loop = 0); ~server(); // {{{ service control void configure(const std::string& configfile); void start(); bool active() const; void run(); void pause(); void resume(); void reload(); void stop(); // }}} // {{{ signals raised on request in order connection_hook connection_open; //!< This hook is invoked once a new client has connected. request_parse_hook pre_process; //!< is called at the very beginning of a request. request_parse_hook resolve_document_root;//!< resolves document_root to use for this request. request_parse_hook resolve_entity; //!< maps the request URI into local physical path. request_handler generate_content; //!< generates response content for this request being processed. request_post_hook post_process; //!< gets invoked right before serializing headers request_post_hook request_done; //!< this hook is invoked once the request has been <b>fully</b> served to the client. connection_hook connection_close; //!< is called before a connection gets closed / or has been closed by remote point. // }}} // {{{ context management /** create server context data for given plugin. */ template<typename T> T *create_context(plugin *plug) { context_.set(plug, new T); return context_.get<T>(plug); } /** creates a virtual-host context for given plugin. */ template<typename T> T *create_context(plugin *plug, const std::string& vhost) { auto i = vhosts_.find(vhost); if (i == vhosts_.end()) vhosts_[vhost] = std::shared_ptr<x0::context>(new x0::context); vhosts_[vhost]->set(plug, new T); return vhosts_[vhost]->get<T>(plug); } void link_context(const std::string& master, const std::string& alias) { vhosts_[alias] = vhosts_[master]; } /** retrieve the server configuration context. */ x0::context *context() { return &context_; } /** retrieve server context data for given plugin * \param plug plugin data for which we want to retrieve the data for. */ template<typename T> T *context(plugin *plug) { return context_.get<T>(plug); } /** retrieve virtual-host context data for given plugin * \param plug plugin data for which we want to retrieve the data for. * \param vhostid virtual-host ID given to the host queried for the configuration. */ template<typename T> T *context(plugin *plug, const std::string& vhostid) { auto vhost = vhosts_.find(vhostid); if (vhost == vhosts_.end()) return NULL; auto ctx = *vhost->second; auto data = ctx.find(plug); if (data != ctx.end()) return static_cast<T *>(data->second); return NULL; } template<typename T> T *free_context(plugin *plug) { /// \todo free all contexts owned by given plugin return context_.free<T>(plug); } // }}} /** * retrieves reference to server currently loaded configuration. */ x0::settings& config(); /** * writes a log entry into the server's error log. */ void log(severity s, const char *msg, ...); template<typename... Args> inline void debug(int level, const char *msg, Args&&... args) { #if !defined(NDEBUG) if (level >= debug_level_) log(severity::debug, msg, args...); #endif } #if !defined(NDEBUG) int debug_level() const; void debug_level(int value); #endif /** * sets up a TCP/IP listener on given bind_address and port. * * If there is already a listener on this bind_address:port pair * then no error will be raised. */ listener *setup_listener(int port, const std::string& bind_address = "0::0"); /** * loads a plugin into the server. * * \see plugin, unload_plugin(), loaded_plugins() */ void load_plugin(const std::string& name); /** safely unloads a plugin. */ void unload_plugin(const std::string& name); /** retrieves a list of currently loaded plugins */ std::vector<std::string> loaded_plugins() const; struct ::ev_loop *loop() const; /** retrieves the current server time. */ const datetime& now() const; const std::list<listener *>& listeners() const; bool register_cvar_server(const std::string& key, std::function<void(const settings_value&)> callback, int priority = 0); bool register_cvar_host(const std::string& key, std::function<void(const settings_value&, const std::string&)> callback, int priority = 0); bool register_cvar_path(const std::string& key, std::function<void(const settings_value&, const std::string&, const std::string&)> callback, int priority = 0); private: long long getrlimit(int resource); long long setrlimit(int resource, long long max); listener *listener_by_port(int port); void setup_logging(const settings_value& cvar); void setup_resources(const settings_value& cvar); void setup_modules(const settings_value& cvar); void setup_fileinfo(const settings_value& cvar); void setup_error_documents(const settings_value& cvar); void setup_hosts(const settings_value& cvar); void setup_advertise(const settings_value& cvar); #if defined(WITH_SSL) static void gnutls_log(int level, const char *msg); #endif friend class connection; private: void handle_request(request *in, response *out); void loop_check(ev::check& w, int revents); x0::context context_; //!< server context std::map<std::string, std::shared_ptr<x0::context>> vhosts_; //!< vhost contexts std::list<listener *> listeners_; struct ::ev_loop *loop_; bool active_; x0::settings settings_; std::map<int, std::map<std::string, std::function<void(const settings_value&)>>> cvars_server_; std::map<int, std::map<std::string, std::function<void(const settings_value&, const std::string& hostid)>>> cvars_host_; std::map<int, std::map<std::string, std::function<void(const settings_value&, const std::string& hostid, const std::string& path)>>> cvars_path_; std::string configfile_; logger_ptr logger_; int debug_level_; bool colored_log_; plugin_map_t plugins_; datetime now_; ev::check loop_check_; public: value_property<int> max_connections; value_property<int> max_keep_alive_idle; value_property<int> max_read_idle; value_property<int> max_write_idle; value_property<bool> tcp_cork; value_property<bool> tcp_nodelay; value_property<std::string> tag; value_property<bool> advertise; fileinfo_service fileinfo; property<unsigned long long> max_fds; }; // {{{ inlines inline struct ::ev_loop *server::loop() const { return loop_; } inline const x0::datetime& server::now() const { return now_; } inline const std::list<listener *>& server::listeners() const { return listeners_; } #if !defined(NDEBUG) inline int server::debug_level() const { return debug_level_; } inline void server::debug_level(int value) { if (value < 0) value = 0; else if (value > 9) value = 9; debug_level_ = value; } #endif // }}} //@} } // namespace x0 #endif // vim:syntax=cpp <commit_msg>include cleanup<commit_after>/* <x0/server.hpp> * * This file is part of the x0 web server project and is released under LGPL-3. * * (c) 2009 Chrisitan Parpart <trapni@gentoo.org> */ #ifndef sw_x0_server_hpp #define sw_x0_server_hpp (1) #include <x0/datetime.hpp> #include <x0/settings.hpp> #include <x0/logger.hpp> #include <x0/signal.hpp> #include <x0/http/request_handler.hpp> #include <x0/context.hpp> #include <x0/types.hpp> #include <x0/property.hpp> #include <x0/io/fileinfo_service.hpp> #include <x0/library.hpp> #include <x0/api.hpp> #include <x0/sysconfig.h> #include <boost/signals.hpp> #include <cstring> #include <string> #include <memory> #include <list> #include <map> #include <ev.h> namespace x0 { struct plugin; //! \addtogroup core //@{ enum context_mask { SERVER = 0x01, HOST = 0x02, PATH = 0x04 }; inline context_mask operator|(context_mask a, context_mask b) { return context_mask(int(a) | int(b)); } /** * \brief implements the x0 web server. * * \see connection, request, response, plugin * \see server::run(), server::stop() */ class server : public boost::noncopyable { private: typedef std::pair<plugin_ptr, library> plugin_value_t; typedef std::map<std::string, plugin_value_t> plugin_map_t; public: typedef x0::signal<void(connection *)> connection_hook; typedef x0::signal<void(request *)> request_parse_hook; typedef x0::signal<void(request *, response *)> request_post_hook; public: explicit server(struct ::ev_loop *loop = 0); ~server(); // {{{ service control void configure(const std::string& configfile); void start(); bool active() const; void run(); void pause(); void resume(); void reload(); void stop(); // }}} // {{{ signals raised on request in order connection_hook connection_open; //!< This hook is invoked once a new client has connected. request_parse_hook pre_process; //!< is called at the very beginning of a request. request_parse_hook resolve_document_root;//!< resolves document_root to use for this request. request_parse_hook resolve_entity; //!< maps the request URI into local physical path. request_handler generate_content; //!< generates response content for this request being processed. request_post_hook post_process; //!< gets invoked right before serializing headers request_post_hook request_done; //!< this hook is invoked once the request has been <b>fully</b> served to the client. connection_hook connection_close; //!< is called before a connection gets closed / or has been closed by remote point. // }}} // {{{ context management /** create server context data for given plugin. */ template<typename T> T *create_context(plugin *plug) { context_.set(plug, new T); return context_.get<T>(plug); } /** creates a virtual-host context for given plugin. */ template<typename T> T *create_context(plugin *plug, const std::string& vhost) { auto i = vhosts_.find(vhost); if (i == vhosts_.end()) vhosts_[vhost] = std::shared_ptr<x0::context>(new x0::context); vhosts_[vhost]->set(plug, new T); return vhosts_[vhost]->get<T>(plug); } void link_context(const std::string& master, const std::string& alias) { vhosts_[alias] = vhosts_[master]; } /** retrieve the server configuration context. */ x0::context *context() { return &context_; } /** retrieve server context data for given plugin * \param plug plugin data for which we want to retrieve the data for. */ template<typename T> T *context(plugin *plug) { return context_.get<T>(plug); } /** retrieve virtual-host context data for given plugin * \param plug plugin data for which we want to retrieve the data for. * \param vhostid virtual-host ID given to the host queried for the configuration. */ template<typename T> T *context(plugin *plug, const std::string& vhostid) { auto vhost = vhosts_.find(vhostid); if (vhost == vhosts_.end()) return NULL; auto ctx = *vhost->second; auto data = ctx.find(plug); if (data != ctx.end()) return static_cast<T *>(data->second); return NULL; } template<typename T> T *free_context(plugin *plug) { /// \todo free all contexts owned by given plugin return context_.free<T>(plug); } // }}} /** * retrieves reference to server currently loaded configuration. */ x0::settings& config(); /** * writes a log entry into the server's error log. */ void log(severity s, const char *msg, ...); template<typename... Args> inline void debug(int level, const char *msg, Args&&... args) { #if !defined(NDEBUG) if (level >= debug_level_) log(severity::debug, msg, args...); #endif } #if !defined(NDEBUG) int debug_level() const; void debug_level(int value); #endif /** * sets up a TCP/IP listener on given bind_address and port. * * If there is already a listener on this bind_address:port pair * then no error will be raised. */ listener *setup_listener(int port, const std::string& bind_address = "0::0"); /** * loads a plugin into the server. * * \see plugin, unload_plugin(), loaded_plugins() */ void load_plugin(const std::string& name); /** safely unloads a plugin. */ void unload_plugin(const std::string& name); /** retrieves a list of currently loaded plugins */ std::vector<std::string> loaded_plugins() const; struct ::ev_loop *loop() const; /** retrieves the current server time. */ const datetime& now() const; const std::list<listener *>& listeners() const; bool register_cvar_server(const std::string& key, std::function<void(const settings_value&)> callback, int priority = 0); bool register_cvar_host(const std::string& key, std::function<void(const settings_value&, const std::string&)> callback, int priority = 0); bool register_cvar_path(const std::string& key, std::function<void(const settings_value&, const std::string&, const std::string&)> callback, int priority = 0); private: long long getrlimit(int resource); long long setrlimit(int resource, long long max); listener *listener_by_port(int port); void setup_logging(const settings_value& cvar); void setup_resources(const settings_value& cvar); void setup_modules(const settings_value& cvar); void setup_fileinfo(const settings_value& cvar); void setup_error_documents(const settings_value& cvar); void setup_hosts(const settings_value& cvar); void setup_advertise(const settings_value& cvar); #if defined(WITH_SSL) static void gnutls_log(int level, const char *msg); #endif friend class connection; private: void handle_request(request *in, response *out); void loop_check(ev::check& w, int revents); x0::context context_; //!< server context std::map<std::string, std::shared_ptr<x0::context>> vhosts_; //!< vhost contexts std::list<listener *> listeners_; struct ::ev_loop *loop_; bool active_; x0::settings settings_; std::map<int, std::map<std::string, std::function<void(const settings_value&)>>> cvars_server_; std::map<int, std::map<std::string, std::function<void(const settings_value&, const std::string& hostid)>>> cvars_host_; std::map<int, std::map<std::string, std::function<void(const settings_value&, const std::string& hostid, const std::string& path)>>> cvars_path_; std::string configfile_; logger_ptr logger_; int debug_level_; bool colored_log_; plugin_map_t plugins_; datetime now_; ev::check loop_check_; public: value_property<int> max_connections; value_property<int> max_keep_alive_idle; value_property<int> max_read_idle; value_property<int> max_write_idle; value_property<bool> tcp_cork; value_property<bool> tcp_nodelay; value_property<std::string> tag; value_property<bool> advertise; fileinfo_service fileinfo; property<unsigned long long> max_fds; }; // {{{ inlines inline struct ::ev_loop *server::loop() const { return loop_; } inline const x0::datetime& server::now() const { return now_; } inline const std::list<listener *>& server::listeners() const { return listeners_; } #if !defined(NDEBUG) inline int server::debug_level() const { return debug_level_; } inline void server::debug_level(int value) { if (value < 0) value = 0; else if (value > 9) value = 9; debug_level_ = value; } #endif // }}} //@} } // namespace x0 #endif // vim:syntax=cpp <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/client.h" #include "rpc/protocol.h" #include "guiinterface.h" #include "util.h" #include <set> #include <stdint.h> #include <univalue.h> class CRPCConvertParam { public: std::string methodName; //! method whose params want conversion int paramIdx; //! 0-based idx of param to convert }; // ***TODO*** static const CRPCConvertParam vRPCConvertParams[] = { {"stop", 0}, {"setmocktime", 0}, {"getaddednodeinfo", 0}, {"setgenerate", 0}, {"setgenerate", 1}, {"generate", 0}, {"getnetworkhashps", 0}, {"getnetworkhashps", 1}, {"delegatestake", 1}, {"delegatestake", 3}, {"delegatestake", 4}, {"delegatestake", 5}, {"rawdelegatestake", 1}, {"rawdelegatestake", 3}, {"rawdelegatestake", 4}, {"sendtoaddress", 1}, {"settxfee", 0}, {"getreceivedbyaddress", 1}, {"listreceivedbyshieldedaddress", 1}, {"getreceivedbylabel", 1}, {"listcoldutxos", 0}, {"listdelegators", 0}, { "getsaplingnotescount", 0}, {"listreceivedbyaddress", 0}, {"listreceivedbyaddress", 1}, {"listreceivedbyaddress", 2}, {"listreceivedbylabel", 0}, {"listreceivedbylabel", 1}, {"listreceivedbylabel", 2}, {"getbalance", 1}, {"getbalance", 2}, {"getbalance", 3}, {"getshieldedbalance", 1}, {"getshieldedbalance", 2}, { "rawshieldedsendmany", 1}, { "rawshieldedsendmany", 2}, { "rawshieldedsendmany", 3}, { "shieldedsendmany", 1}, { "shieldedsendmany", 2}, { "shieldedsendmany", 3}, {"getblockhash", 0}, { "waitforblockheight", 0 }, { "waitforblockheight", 1 }, { "waitforblock", 1 }, { "waitforblock", 2 }, { "waitfornewblock", 0 }, { "waitfornewblock", 1 }, {"listtransactions", 1}, {"listtransactions", 2}, {"listtransactions", 3}, {"listtransactions", 4}, {"listtransactions", 5}, {"walletpassphrase", 1}, {"walletpassphrase", 2}, {"getblocktemplate", 0}, {"listsinceblock", 1}, {"listsinceblock", 2}, {"sendmany", 1}, {"sendmany", 2}, {"addmultisigaddress", 0}, {"addmultisigaddress", 1}, {"createmultisig", 0}, {"createmultisig", 1}, {"listunspent", 0}, {"listunspent", 1}, {"listunspent", 2}, {"listunspent", 3}, { "listshieldedunspent", 0 }, { "listshieldedunspent", 1 }, { "listshieldedunspent", 2 }, { "listshieldedunspent", 3 }, {"logging", 0}, {"logging", 1}, {"getblock", 1}, {"getblockheader", 1}, {"gettransaction", 1}, {"getrawtransaction", 1}, {"createrawtransaction", 0}, {"createrawtransaction", 1}, {"createrawtransaction", 2}, {"fundrawtransaction", 1}, {"signrawtransaction", 1}, {"signrawtransaction", 2}, {"sendrawtransaction", 1}, {"sethdseed", 0}, {"gettxout", 1}, {"gettxout", 2}, {"lockunspent", 0}, {"lockunspent", 1}, {"importprivkey", 2}, {"importprivkey", 3}, {"importaddress", 2}, {"importaddress", 3}, {"importpubkey", 2}, { "exportsaplingkey", 1 }, { "importsaplingkey", 2 }, { "importsaplingviewingkey", 2 }, {"verifychain", 0}, {"verifychain", 1}, {"keypoolrefill", 0}, {"getrawmempool", 0}, {"estimatefee", 0}, {"estimatesmartfee", 0}, {"prioritisetransaction", 1}, {"prioritisetransaction", 2}, {"setban", 2}, {"setban", 3}, {"spork", 1}, {"preparebudget", 2}, {"preparebudget", 3}, {"preparebudget", 5}, {"submitbudget", 2}, {"submitbudget", 3}, {"submitbudget", 5}, {"submitbudget", 7}, // disabled until removal of the legacy 'masternode' command //{"startmasternode", 1}, {"startmasternode", 3}, {"mnvoteraw", 1}, {"mnvoteraw", 4}, {"setstakesplitthreshold", 0}, {"autocombinerewards", 0}, {"autocombinerewards", 1}, {"getzerocoinbalance", 0}, {"listmintedzerocoins", 0}, {"listmintedzerocoins", 1}, {"listspentzerocoins", 0}, {"listzerocoinamounts", 0}, {"mintzerocoin", 0}, {"mintzerocoin", 1}, {"spendzerocoin", 0}, {"spendrawzerocoin", 2}, {"spendzerocoinmints", 0}, {"importzerocoins", 0}, {"exportzerocoins", 0}, {"exportzerocoins", 1}, {"resetmintzerocoin", 0}, {"getspentzerocoinamount", 1}, {"generatemintlist", 0}, {"generatemintlist", 1}, {"searchdzpiv", 0}, {"searchdzpiv", 1}, {"searchdzpiv", 2}, {"getmintsvalues", 2}, {"enableautomintaddress", 0}, {"getblockindexstats", 0}, {"getblockindexstats", 1}, {"getblockindexstats", 2}, {"getserials", 0}, {"getserials", 1}, {"getserials", 2}, {"getfeeinfo", 0}, {"getsupplyinfo", 0}, }; class CRPCConvertTable { private: std::set<std::pair<std::string, int> > members; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.emplace(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx); } } static CRPCConvertTable rpcCvtTable; /** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) * as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal) { UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) throw std::runtime_error(std::string("Error parsing JSON:")+strVal); return jVal[0]; } /** Convert strings to command-specific RPC representation */ UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } <commit_msg>Unify the RPC convert params list for readability<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/client.h" #include "rpc/protocol.h" #include "guiinterface.h" #include "util.h" #include <set> #include <stdint.h> #include <univalue.h> class CRPCConvertParam { public: std::string methodName; //! method whose params want conversion int paramIdx; //! 0-based idx of param to convert }; // ***TODO*** static const CRPCConvertParam vRPCConvertParams[] = { { "stop", 0 }, { "setmocktime", 0 }, { "getaddednodeinfo", 0 }, { "setgenerate", 0 }, { "setgenerate", 1 }, { "generate", 0 }, { "getnetworkhashps", 0 }, { "getnetworkhashps", 1 }, { "delegatestake", 1 }, { "delegatestake", 3 }, { "delegatestake", 4 }, { "delegatestake", 5 }, { "rawdelegatestake", 1 }, { "rawdelegatestake", 3 }, { "rawdelegatestake", 4 }, { "sendtoaddress", 1 }, { "settxfee", 0 }, { "getreceivedbyaddress", 1 }, { "listreceivedbyshieldedaddress", 1 }, { "getreceivedbylabel", 1 }, { "listcoldutxos", 0 }, { "listdelegators", 0 }, { "getsaplingnotescount", 0 }, { "listreceivedbyaddress", 0 }, { "listreceivedbyaddress", 1 }, { "listreceivedbyaddress", 2 }, { "listreceivedbylabel", 0 }, { "listreceivedbylabel", 1 }, { "listreceivedbylabel", 2 }, { "getbalance", 1 }, { "getbalance", 2 }, { "getbalance", 3 }, { "getshieldedbalance", 1 }, { "getshieldedbalance", 2 }, { "rawshieldedsendmany", 1 }, { "rawshieldedsendmany", 2 }, { "rawshieldedsendmany", 3 }, { "shieldedsendmany", 1 }, { "shieldedsendmany", 2 }, { "shieldedsendmany", 3 }, { "getblockhash", 0 }, { "waitforblockheight", 0 }, { "waitforblockheight", 1 }, { "waitforblock", 1 }, { "waitforblock", 2 }, { "waitfornewblock", 0 }, { "waitfornewblock", 1 }, { "listtransactions", 1 }, { "listtransactions", 2 }, { "listtransactions", 3 }, { "listtransactions", 4 }, { "listtransactions", 5 }, { "walletpassphrase", 1 }, { "walletpassphrase", 2 }, { "getblocktemplate", 0 }, { "listsinceblock", 1 }, { "listsinceblock", 2 }, { "sendmany", 1 }, { "sendmany", 2 }, { "addmultisigaddress", 0 }, { "addmultisigaddress", 1 }, { "createmultisig", 0 }, { "createmultisig", 1 }, { "listunspent", 0 }, { "listunspent", 1 }, { "listunspent", 2 }, { "listunspent", 3 }, { "listshieldedunspent", 0 }, { "listshieldedunspent", 1 }, { "listshieldedunspent", 2 }, { "listshieldedunspent", 3 }, { "logging", 0 }, { "logging", 1 }, { "getblock", 1 }, { "getblockheader", 1 }, { "gettransaction", 1 }, { "getrawtransaction", 1 }, { "createrawtransaction", 0 }, { "createrawtransaction", 1 }, { "createrawtransaction", 2 }, { "fundrawtransaction", 1 }, { "signrawtransaction", 1 }, { "signrawtransaction", 2 }, { "sendrawtransaction", 1 }, { "sethdseed", 0 }, { "gettxout", 1 }, { "gettxout", 2 }, { "lockunspent", 0 }, { "lockunspent", 1 }, { "importprivkey", 2 }, { "importprivkey", 3 }, { "importaddress", 2 }, { "importaddress", 3 }, { "importpubkey", 2 }, { "exportsaplingkey", 1 }, { "importsaplingkey", 2 }, { "importsaplingviewingkey", 2 }, { "verifychain", 0 }, { "verifychain", 1 }, { "keypoolrefill", 0 }, { "getrawmempool", 0 }, { "estimatefee", 0 }, { "estimatesmartfee", 0 }, { "prioritisetransaction", 1 }, { "prioritisetransaction", 2 }, { "setban", 2 }, { "setban", 3 }, { "spork", 1 }, { "preparebudget", 2 }, { "preparebudget", 3 }, { "preparebudget", 5 }, { "submitbudget", 2 }, { "submitbudget", 3 }, { "submitbudget", 5 }, { "submitbudget", 7 }, // TODO: remove this and switch over to proper arg parsing in rpc/masternode.cpp for the second argument //{"startmasternode", 1}, { "startmasternode", 3 }, { "mnvoteraw", 1 }, { "mnvoteraw", 4 }, { "setstakesplitthreshold", 0 }, { "autocombinerewards", 0 }, { "autocombinerewards", 1 }, { "getzerocoinbalance", 0 }, { "listmintedzerocoins", 0 }, { "listmintedzerocoins", 1 }, { "listspentzerocoins", 0 }, { "listzerocoinamounts", 0 }, { "mintzerocoin", 0 }, { "mintzerocoin", 1 }, { "spendzerocoin", 0 }, { "spendrawzerocoin", 2 }, { "spendzerocoinmints", 0 }, { "importzerocoins", 0 }, { "exportzerocoins", 0 }, { "exportzerocoins", 1 }, { "resetmintzerocoin", 0 }, { "getspentzerocoinamount", 1 }, { "generatemintlist", 0 }, { "generatemintlist", 1 }, { "searchdzpiv", 0 }, { "searchdzpiv", 1 }, { "searchdzpiv", 2 }, { "getmintsvalues", 2 }, { "enableautomintaddress", 0 }, { "getblockindexstats", 0 }, { "getblockindexstats", 1 }, { "getblockindexstats", 2 }, { "getserials", 0 }, { "getserials", 1 }, { "getserials", 2 }, { "getfeeinfo", 0 }, { "getsupplyinfo", 0 }, }; class CRPCConvertTable { private: std::set<std::pair<std::string, int> > members; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.emplace(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx); } } static CRPCConvertTable rpcCvtTable; /** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) * as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal) { UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) throw std::runtime_error(std::string("Error parsing JSON:")+strVal); return jVal[0]; } /** Convert strings to command-specific RPC representation */ UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2015 Kim Kulling 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 <openddlparser/OpenDDLExport.h> #include <openddlparser/DDLNode.h> #include <openddlparser/Value.h> #include <sstream> BEGIN_ODDLPARSER_NS struct DDLNodeIterator { const DDLNode::DllNodeList &m_childs; size_t m_idx; DDLNodeIterator( const DDLNode::DllNodeList &childs ) : m_childs( childs ) , m_idx( 0 ) { // empty } ~DDLNodeIterator() { // empty } bool getNext( DDLNode **node ) { if( m_childs.size() > (m_idx+1) ) { m_idx++; *node = m_childs[ m_idx ]; return true; } return false; } }; OpenDDLExport::OpenDDLExport() :m_file( nullptr ) { } OpenDDLExport::~OpenDDLExport() { if( nullptr != m_file ) { ::fclose( m_file ); m_file = nullptr; } } bool OpenDDLExport::exportContext( Context *ctx, const std::string &filename ) { if( filename.empty() ) { return false; } if( ddl_nullptr == ctx ) { return false; } DDLNode *root( ctx->m_root ); if( nullptr == root ) { return true; } return handleNode( root ); } bool OpenDDLExport::handleNode( DDLNode *node ) { if( ddl_nullptr == node ) { return true; } const DDLNode::DllNodeList &childs = node->getChildNodeList(); if( childs.empty() ) { return true; } DDLNode *current( ddl_nullptr ); DDLNodeIterator it( childs ); std::string statement; bool success( true ); while( it.getNext( &current ) ) { if( ddl_nullptr != current ) { success |= writeNode( current, statement ); if( !handleNode( current ) ) { success != false; } } } return success; } bool OpenDDLExport::write( const std::string &statement ) { if (ddl_nullptr == m_file) { return false; } if ( !statement.empty()) { ::fwrite( statement.c_str(), sizeof( char ), statement.size(), m_file ); } return true; } bool OpenDDLExport::writeNode( DDLNode *node, std::string &statement ) { bool success( true ); if (node->hasProperties()) { success |= writeProperties( node, statement ); } return true; } bool OpenDDLExport::writeProperties( DDLNode *node, std::string &statement ) { if ( ddl_nullptr == node ) { return false; } Property *prop( node->getProperties() ); // if no properties are there, return if ( ddl_nullptr == prop ) { return true; } if ( ddl_nullptr != prop ) { // (attrib = "position", bla=2) statement = "("; bool first( true ); while ( ddl_nullptr != prop ) { if (!first) { statement += ", "; } else { first = false; } statement += std::string( prop->m_key->m_text.m_buffer ); statement += " = "; writeValue( prop->m_value, statement ); prop = prop->m_next; } statement += ")"; } return true; } bool OpenDDLExport::writeValue( Value *val, std::string &statement ) { if (ddl_nullptr == val) { return false; } switch ( val->m_type ) { case Value::ddl_bool: if ( true == val->getBool() ) { statement += "true"; } else { statement += "false"; } break; case Value::ddl_int8: { std::stringstream stream; const int i = static_cast<int>( val->getInt8() ); stream << i; statement += stream.str(); } break; case Value::ddl_int16: { std::stringstream stream; char buffer[ 256 ]; ::memset( buffer, '\0', 256 * sizeof( char ) ); sprintf( buffer, "%d", val->getInt16() ); statement += buffer; } break; case Value::ddl_int32: { std::stringstream stream; char buffer[ 256 ]; ::memset( buffer, '\0', 256 * sizeof( char ) ); const int i = static_cast< int >( val->getInt32() ); sprintf( buffer, "%d", i ); statement += buffer; } break; case Value::ddl_int64: { std::stringstream stream; const int i = static_cast< int >( val->getInt64() ); stream << i; statement += stream.str(); } break; case Value::ddl_unsigned_int8: { std::stringstream stream; const int i = static_cast< unsigned int >( val->getUnsignedInt8() ); stream << i; statement += stream.str(); } break; case Value::ddl_unsigned_int16: { std::stringstream stream; const int i = static_cast< unsigned int >( val->getUnsignedInt16() ); stream << i; statement += stream.str(); } break; case Value::ddl_unsigned_int32: { std::stringstream stream; const int i = static_cast< unsigned int >( val->getUnsignedInt32() ); stream << i; statement += stream.str(); } break; case Value::ddl_unsigned_int64: { std::stringstream stream; const int i = static_cast< unsigned int >( val->getUnsignedInt64() ); stream << i; statement += stream.str(); } break; case Value::ddl_half: break; case Value::ddl_float: break; case Value::ddl_double: break; case Value::ddl_string: break; case Value::ddl_ref: break; case Value::ddl_none: case Value::ddl_types_max: default: break; } return true; } END_ODDLPARSER_NS <commit_msg>Exporter: fix invalid assign of return value in case of an error.<commit_after>/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2015 Kim Kulling 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 <openddlparser/OpenDDLExport.h> #include <openddlparser/DDLNode.h> #include <openddlparser/Value.h> #include <sstream> BEGIN_ODDLPARSER_NS struct DDLNodeIterator { const DDLNode::DllNodeList &m_childs; size_t m_idx; DDLNodeIterator( const DDLNode::DllNodeList &childs ) : m_childs( childs ) , m_idx( 0 ) { // empty } ~DDLNodeIterator() { // empty } bool getNext( DDLNode **node ) { if( m_childs.size() > (m_idx+1) ) { m_idx++; *node = m_childs[ m_idx ]; return true; } return false; } }; OpenDDLExport::OpenDDLExport() :m_file( nullptr ) { } OpenDDLExport::~OpenDDLExport() { if( nullptr != m_file ) { ::fclose( m_file ); m_file = nullptr; } } bool OpenDDLExport::exportContext( Context *ctx, const std::string &filename ) { if( filename.empty() ) { return false; } if( ddl_nullptr == ctx ) { return false; } DDLNode *root( ctx->m_root ); if( nullptr == root ) { return true; } return handleNode( root ); } bool OpenDDLExport::handleNode( DDLNode *node ) { if( ddl_nullptr == node ) { return true; } const DDLNode::DllNodeList &childs = node->getChildNodeList(); if( childs.empty() ) { return true; } DDLNode *current( ddl_nullptr ); DDLNodeIterator it( childs ); std::string statement; bool success( true ); while( it.getNext( &current ) ) { if( ddl_nullptr != current ) { success |= writeNode( current, statement ); if( !handleNode( current ) ) { success = false; } } } return success; } bool OpenDDLExport::write( const std::string &statement ) { if (ddl_nullptr == m_file) { return false; } if ( !statement.empty()) { ::fwrite( statement.c_str(), sizeof( char ), statement.size(), m_file ); } return true; } bool OpenDDLExport::writeNode( DDLNode *node, std::string &statement ) { bool success( true ); if (node->hasProperties()) { success |= writeProperties( node, statement ); } return true; } bool OpenDDLExport::writeProperties( DDLNode *node, std::string &statement ) { if ( ddl_nullptr == node ) { return false; } Property *prop( node->getProperties() ); // if no properties are there, return if ( ddl_nullptr == prop ) { return true; } if ( ddl_nullptr != prop ) { // (attrib = "position", bla=2) statement = "("; bool first( true ); while ( ddl_nullptr != prop ) { if (!first) { statement += ", "; } else { first = false; } statement += std::string( prop->m_key->m_text.m_buffer ); statement += " = "; writeValue( prop->m_value, statement ); prop = prop->m_next; } statement += ")"; } return true; } bool OpenDDLExport::writeValue( Value *val, std::string &statement ) { if (ddl_nullptr == val) { return false; } switch ( val->m_type ) { case Value::ddl_bool: if ( true == val->getBool() ) { statement += "true"; } else { statement += "false"; } break; case Value::ddl_int8: { std::stringstream stream; const int i = static_cast<int>( val->getInt8() ); stream << i; statement += stream.str(); } break; case Value::ddl_int16: { std::stringstream stream; char buffer[ 256 ]; ::memset( buffer, '\0', 256 * sizeof( char ) ); sprintf( buffer, "%d", val->getInt16() ); statement += buffer; } break; case Value::ddl_int32: { std::stringstream stream; char buffer[ 256 ]; ::memset( buffer, '\0', 256 * sizeof( char ) ); const int i = static_cast< int >( val->getInt32() ); sprintf( buffer, "%d", i ); statement += buffer; } break; case Value::ddl_int64: { std::stringstream stream; const int i = static_cast< int >( val->getInt64() ); stream << i; statement += stream.str(); } break; case Value::ddl_unsigned_int8: { std::stringstream stream; const int i = static_cast< unsigned int >( val->getUnsignedInt8() ); stream << i; statement += stream.str(); } break; case Value::ddl_unsigned_int16: { std::stringstream stream; const int i = static_cast< unsigned int >( val->getUnsignedInt16() ); stream << i; statement += stream.str(); } break; case Value::ddl_unsigned_int32: { std::stringstream stream; const int i = static_cast< unsigned int >( val->getUnsignedInt32() ); stream << i; statement += stream.str(); } break; case Value::ddl_unsigned_int64: { std::stringstream stream; const int i = static_cast< unsigned int >( val->getUnsignedInt64() ); stream << i; statement += stream.str(); } break; case Value::ddl_half: break; case Value::ddl_float: break; case Value::ddl_double: break; case Value::ddl_string: break; case Value::ddl_ref: break; case Value::ddl_none: case Value::ddl_types_max: default: break; } return true; } END_ODDLPARSER_NS <|endoftext|>
<commit_before>/* Gobby - GTK-based collaborative text editor * Copyright (C) 2008-2014 Armin Burgmeier <armin@arbur.net> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "core/userjoin.hpp" #include <glibmm/main.h> #include <cstring> #include <libinfinity/common/inf-error.h> namespace { void retr_local_user_func(InfUser* user, gpointer user_data) { (*static_cast<InfUser**>(user_data)) = user; } std::vector<GParameter>::iterator find_name_param( std::vector<GParameter>& params) { for(std::vector<GParameter>::iterator iter = params.begin(); iter != params.end(); ++iter) { if(std::strcmp(iter->name, "name") == 0) return iter; } g_assert_not_reached(); return params.end(); } } Gobby::UserJoin::UserJoin(InfBrowser* browser, const InfBrowserIter* iter, InfSessionProxy* proxy, std::auto_ptr<ParameterProvider> param_provider): m_node(browser, iter), m_proxy(proxy), m_param_provider(param_provider), m_synchronization_complete_handler(0), m_request(NULL), m_retry_index(1), m_user(NULL), m_error(NULL) { g_object_ref(m_proxy); InfSession* session; g_object_get(G_OBJECT(proxy), "session", &session, NULL); if(inf_session_get_status(session) == INF_SESSION_SYNCHRONIZING) { // If not yet synchronized, wait for synchronization until // attempting userjoin m_synchronization_complete_handler = g_signal_connect_after( G_OBJECT(session), "synchronization-complete", G_CALLBACK(on_synchronization_complete_static), this); } else { // Delay this call to make sure we don't emit the // finished signal right inside the constructor. // TODO: This might not be a problem, since the caller // can just check for completion with the get_user() // and get_error() methods. Glib::signal_idle().connect( sigc::bind_return(sigc::mem_fun( *this, &UserJoin::attempt_user_join), false)); } g_object_unref(session); } Gobby::UserJoin::~UserJoin() { if(m_synchronization_complete_handler) { InfSession* session; g_object_get(G_OBJECT(m_proxy), "session", &session, NULL); g_signal_handler_disconnect( session, m_synchronization_complete_handler); g_object_unref(session); } if(m_request) { g_signal_handlers_disconnect_by_func( G_OBJECT(m_request), (gpointer)G_CALLBACK(on_user_join_finished_static), this); g_object_unref(m_request); // TODO: Keep watching the request, and when it finishes, make // the user unavailable. This should typically not be // necessary, because on the server side user join requests // finish immediately, and on the client side the only thing // that leads to the UserJoinInfo being deleted is when the // document is removed and we are unsubscribed from the // session, in which case we do not care about the user join // anymore anyway. // However, it would be good to handle this, just in case. } if(m_error != NULL) g_error_free(m_error); g_object_unref(m_proxy); } void Gobby::UserJoin::UserJoin::on_synchronization_complete() { // Disconnect signal handler, so that we don't get notified when // syncing this document in running state to another location // or server. InfSession* session; g_object_get(G_OBJECT(m_proxy), "session", &session, NULL); g_signal_handler_disconnect( session, m_synchronization_complete_handler); m_synchronization_complete_handler = 0; g_object_unref(session); // Attempt user join after synchronization attempt_user_join(); } void Gobby::UserJoin::on_user_join_finished(InfUser* user, const GError* error) { if(m_request != NULL) { g_signal_handlers_disconnect_by_func( G_OBJECT(m_request), (gpointer)G_CALLBACK(on_user_join_finished_static), this); g_object_unref(m_request); m_request = NULL; } if(error == NULL) { user_join_complete(user, error); } else if(error->domain == inf_user_error_quark() && error->code == INF_USER_ERROR_NAME_IN_USE) { // If name is in use retry with alternative user name ++m_retry_index; attempt_user_join(); } else { user_join_complete(user, error); } } void Gobby::UserJoin::attempt_user_join() { // Check if there is already a local user, for example for a // synced-in document. InfSession* session; g_object_get(G_OBJECT(m_proxy), "session", &session, NULL); InfUserTable* user_table = inf_session_get_user_table(session); InfUser* user = NULL; inf_user_table_foreach_local_user(user_table, retr_local_user_func, &user); g_object_unref(session); if(user != NULL) { user_join_complete(user, NULL); return; } // Next, check whether we are allowed to join a user if(m_node.get_browser() && m_node.get_browser_iter()) { InfBrowser* browser = m_node.get_browser(); const InfBrowserIter* iter = m_node.get_browser_iter(); const InfAclAccount* account = inf_browser_get_acl_local_account(browser); const InfAclAccountId acc_id = (account != NULL) ? account->id : 0; InfAclMask msk; inf_acl_mask_set1(&msk, INF_ACL_CAN_JOIN_USER); if(!inf_browser_check_acl(browser, iter, acc_id, &msk, NULL)) { GError* error = NULL; g_set_error( &error, inf_request_error_quark(), INF_REQUEST_ERROR_NOT_AUTHORIZED, "%s", inf_request_strerror( INF_REQUEST_ERROR_NOT_AUTHORIZED)); user_join_complete(NULL, error); g_error_free(error); return; } } // We are allowed, so attempt to join the user now. std::vector<GParameter> params = m_param_provider->get_user_join_parameters(); std::vector<GParameter>::iterator name_index = find_name_param(params); const gchar* name = g_value_get_string(&name_index->value); if(m_retry_index > 1) { gchar* new_name = g_strdup_printf( "%s %u", name, m_retry_index); g_value_take_string(&name_index->value, new_name); } GError* error = NULL; InfRequest* request = inf_session_proxy_join_user( m_proxy, params.size(), &params[0], on_user_join_finished_static, this); for(unsigned int i = 0; i < params.size(); ++i) g_value_unset(&params[i].value); if(request != NULL) { m_request = request; g_object_ref(m_request); } } void Gobby::UserJoin::user_join_complete(InfUser* user, const GError* error) { g_assert(m_request == NULL); g_assert(m_user == NULL && m_error == NULL); m_user = user; if(error) m_error = g_error_copy(error); m_signal_finished.emit(m_user, m_error); } <commit_msg>Fix use-after-free on unsuccessful user join<commit_after>/* Gobby - GTK-based collaborative text editor * Copyright (C) 2008-2014 Armin Burgmeier <armin@arbur.net> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "core/userjoin.hpp" #include <glibmm/main.h> #include <cstring> #include <libinfinity/common/inf-error.h> namespace { void retr_local_user_func(InfUser* user, gpointer user_data) { (*static_cast<InfUser**>(user_data)) = user; } std::vector<GParameter>::iterator find_name_param( std::vector<GParameter>& params) { for(std::vector<GParameter>::iterator iter = params.begin(); iter != params.end(); ++iter) { if(std::strcmp(iter->name, "name") == 0) return iter; } g_assert_not_reached(); return params.end(); } } Gobby::UserJoin::UserJoin(InfBrowser* browser, const InfBrowserIter* iter, InfSessionProxy* proxy, std::auto_ptr<ParameterProvider> param_provider): m_node(browser, iter), m_proxy(proxy), m_param_provider(param_provider), m_synchronization_complete_handler(0), m_request(NULL), m_retry_index(1), m_user(NULL), m_error(NULL) { g_object_ref(m_proxy); InfSession* session; g_object_get(G_OBJECT(proxy), "session", &session, NULL); if(inf_session_get_status(session) == INF_SESSION_SYNCHRONIZING) { // If not yet synchronized, wait for synchronization until // attempting userjoin m_synchronization_complete_handler = g_signal_connect_after( G_OBJECT(session), "synchronization-complete", G_CALLBACK(on_synchronization_complete_static), this); } else { // Delay this call to make sure we don't emit the // finished signal right inside the constructor. // TODO: This might not be a problem, since the caller // can just check for completion with the get_user() // and get_error() methods. Glib::signal_idle().connect( sigc::bind_return(sigc::mem_fun( *this, &UserJoin::attempt_user_join), false)); } g_object_unref(session); } Gobby::UserJoin::~UserJoin() { if(m_synchronization_complete_handler) { InfSession* session; g_object_get(G_OBJECT(m_proxy), "session", &session, NULL); g_signal_handler_disconnect( session, m_synchronization_complete_handler); g_object_unref(session); } if(m_request) { g_signal_handlers_disconnect_by_func( G_OBJECT(m_request), (gpointer)G_CALLBACK(on_user_join_finished_static), this); g_object_unref(m_request); // TODO: Keep watching the request, and when it finishes, make // the user unavailable. This should typically not be // necessary, because on the server side user join requests // finish immediately, and on the client side the only thing // that leads to the UserJoinInfo being deleted is when the // document is removed and we are unsubscribed from the // session, in which case we do not care about the user join // anymore anyway. // However, it would be good to handle this, just in case. } if(m_error != NULL) g_error_free(m_error); g_object_unref(m_proxy); } void Gobby::UserJoin::UserJoin::on_synchronization_complete() { // Disconnect signal handler, so that we don't get notified when // syncing this document in running state to another location // or server. InfSession* session; g_object_get(G_OBJECT(m_proxy), "session", &session, NULL); g_signal_handler_disconnect( session, m_synchronization_complete_handler); m_synchronization_complete_handler = 0; g_object_unref(session); // Attempt user join after synchronization attempt_user_join(); } void Gobby::UserJoin::on_user_join_finished(InfUser* user, const GError* error) { if(m_request != NULL) { g_signal_handlers_disconnect_by_func( G_OBJECT(m_request), (gpointer)G_CALLBACK(on_user_join_finished_static), this); g_object_unref(m_request); m_request = NULL; } if(error == NULL) { user_join_complete(user, error); } else if(error->domain == inf_user_error_quark() && error->code == INF_USER_ERROR_NAME_IN_USE) { // If name is in use retry with alternative user name ++m_retry_index; attempt_user_join(); } else { user_join_complete(user, error); } } void Gobby::UserJoin::attempt_user_join() { // Check if there is already a local user, for example for a // synced-in document. InfSession* session; g_object_get(G_OBJECT(m_proxy), "session", &session, NULL); InfUserTable* user_table = inf_session_get_user_table(session); InfUser* user = NULL; inf_user_table_foreach_local_user(user_table, retr_local_user_func, &user); g_object_unref(session); if(user != NULL) { user_join_complete(user, NULL); return; } // Next, check whether we are allowed to join a user if(m_node.get_browser() && m_node.get_browser_iter()) { InfBrowser* browser = m_node.get_browser(); const InfBrowserIter* iter = m_node.get_browser_iter(); const InfAclAccount* account = inf_browser_get_acl_local_account(browser); const InfAclAccountId acc_id = (account != NULL) ? account->id : 0; InfAclMask msk; inf_acl_mask_set1(&msk, INF_ACL_CAN_JOIN_USER); if(!inf_browser_check_acl(browser, iter, acc_id, &msk, NULL)) { GError* error = NULL; g_set_error( &error, inf_request_error_quark(), INF_REQUEST_ERROR_NOT_AUTHORIZED, "%s", inf_request_strerror( INF_REQUEST_ERROR_NOT_AUTHORIZED)); user_join_complete(NULL, error); g_error_free(error); return; } } // We are allowed, so attempt to join the user now. std::vector<GParameter> params = m_param_provider->get_user_join_parameters(); std::vector<GParameter>::iterator name_index = find_name_param(params); const gchar* name = g_value_get_string(&name_index->value); if(m_retry_index > 1) { gchar* new_name = g_strdup_printf( "%s %u", name, m_retry_index); g_value_take_string(&name_index->value, new_name); } GError* error = NULL; InfRequest* request = inf_session_proxy_join_user( m_proxy, params.size(), &params[0], on_user_join_finished_static, this); for(unsigned int i = 0; i < params.size(); ++i) g_value_unset(&params[i].value); if(request != NULL) { m_request = request; g_object_ref(m_request); } } void Gobby::UserJoin::user_join_complete(InfUser* user, const GError* error) { g_assert(m_request == NULL); g_assert(m_user == NULL && m_error == NULL); m_user = user; if(error) m_error = g_error_copy(error); m_signal_finished.emit(m_user, error); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. 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 end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.2 2000/02/06 07:47:58 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:07:46 twl * Initial checkin * * Revision 1.3 1999/11/08 20:45:02 rahul * Swat for adding in Product name and CVS comment log variable. * */ #ifndef PARSER_HPP #define PARSER_HPP class DTDHandler; class EntityResolver; class DocumentHandler; class ErrorHandler; class InputSource; /** * Basic interface for SAX (Simple API for XML) parsers. * * All SAX parsers must implement this basic interface: it allows * applications to register handlers for different types of events * and to initiate a parse from a URI, or a character stream. * * All SAX parsers must also implement a zero-argument constructor * (though other constructors are also allowed). * * SAX parsers are reusable but not re-entrant: the application * may reuse a parser object (possibly with a different input source) * once the first parse has completed successfully, but it may not * invoke the parse() methods recursively within a parse. * * $Log$ * Revision 1.2 2000/02/06 07:47:58 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:07:46 twl * Initial checkin * * Revision 1.3 1999/11/08 20:45:02 rahul * Swat for adding in Product name and CVS comment log variable. * * @see EntityResolver#EntityResolver * @see DTDHandler#DTDHandler * @see DocumentHandler#DocumentHandler * @see ErrorHandler#ErrorHandler * @see HandlerBase#HandlerBase * @see InputSource#InputSource */ #include <util/XML4CDefs.hpp> class SAX_EXPORT Parser { public: /** @name Constructors and Destructor */ // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- //@{ /** The default constructor */ Parser() { } /** The destructor */ virtual ~Parser() { } //@} //----------------------------------------------------------------------- // The parser interface //----------------------------------------------------------------------- /** @name The parser interfaces */ //@{ /** * Allow an application to register a custom entity resolver. * * If the application does not register an entity resolver, the * SAX parser will resolve system identifiers and open connections * to entities itself (this is the default behaviour implemented in * HandlerBase). * * Applications may register a new or different entity resolver * in the middle of a parse, and the SAX parser must begin using * the new resolver immediately. * * @param resolver The object for resolving entities. * @see EntityResolver#EntityResolver * @see HandlerBase#HandlerBase */ virtual void setEntityResolver(EntityResolver* const resolver) = 0; /** * Allow an application to register a DTD event handler. * * If the application does not register a DTD handler, all DTD * events reported by the SAX parser will be silently ignored (this * is the default behaviour implemented by HandlerBase). * * Applications may register a new or different handler in the middle * of a parse, and the SAX parser must begin using the new handler * immediately. * * @param handler The DTD handler. * @see DTDHandler#DTDHandler * @see HandlerBase#HandlerBase */ virtual void setDTDHandler(DTDHandler* const handler) = 0; /** * Allow an application to register a document event handler. * * If the application does not register a document handler, all * document events reported by the SAX parser will be silently * ignored (this is the default behaviour implemented by * HandlerBase). * * Applications may register a new or different handler in the * middle of a parse, and the SAX parser must begin using the new * handler immediately. * * @param handler The document handler. * @see DocumentHandler#DocumentHandler * @see HandlerBase#HandlerBase */ virtual void setDocumentHandler(DocumentHandler* const handler) = 0; /** * Allow an application to register an error event handler. * * If the application does not register an error event handler, * all error events reported by the SAX parser will be silently * ignored, except for fatalError, which will throw a SAXException * (this is the default behaviour implemented by HandlerBase). * * Applications may register a new or different handler in the * middle of a parse, and the SAX parser must begin using the new * handler immediately. * * @param handler The error handler. * @see ErrorHandler#ErrorHandler * @see SAXException#SAXException * @see HandlerBase#HandlerBase */ virtual void setErrorHandler(ErrorHandler* const handler) = 0; /** * Parse an XML document. * * The application can use this method to instruct the SAX parser * to begin parsing an XML document from any valid input * source (a character stream, a byte stream, or a URI). * * Applications may not invoke this method while a parse is in * progress (they should create a new Parser instead for each * additional XML document). Once a parse is complete, an * application may reuse the same Parser object, possibly with a * different input source. * * @param source The input source for the top-level of the * XML document. * @param reuseValidator Indicates whether the validator should be * reused, ignoring any external subset. If true, there * cannot be any internal subset. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @see InputSource#InputSource * @see #setEntityResolver * @see #setDTDHandler * @see #setDocumentHandler * @see #setErrorHandler */ virtual void parse ( const InputSource& source , const bool reuseValidator = false ) = 0; /** * Parse an XML document from a system identifier (URI). * * This method is a shortcut for the common case of reading a * document from a system identifier. It is the exact equivalent * of the following: * * parse(new URLInputSource(systemId)); * * If the system identifier is a URL, it must be fully resolved * by the application before it is passed to the parser. * * @param systemId The system identifier (URI). * @param reuseValidator Indicates whether the validator should be * reused, ignoring any external subset. If true, there * cannot be any internal subset. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @see #parse(InputSource) */ virtual void parse ( const XMLCh* const systemId , const bool reuseValidator = false ) = 0; virtual void parse ( const char* const systemId , const bool reuseValidator = false ) = 0; //@} private : /** @name Unimplemented constructors and operators */ //@{ /** The copy constructor, you cannot call this directly */ Parser(const Parser&); /** The assignment operator, you cannot call this directly */ void operator=(const Parser&); //@} }; #endif <commit_msg>Removed private function docs, added parse docs<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. 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 end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.3 2000/02/09 01:59:12 abagchi * Removed private function docs, added parse docs * * Revision 1.2 2000/02/06 07:47:58 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:07:46 twl * Initial checkin * * Revision 1.3 1999/11/08 20:45:02 rahul * Swat for adding in Product name and CVS comment log variable. * */ #ifndef PARSER_HPP #define PARSER_HPP class DTDHandler; class EntityResolver; class DocumentHandler; class ErrorHandler; class InputSource; /** * Basic interface for SAX (Simple API for XML) parsers. * * All SAX parsers must implement this basic interface: it allows * applications to register handlers for different types of events * and to initiate a parse from a URI, or a character stream. * * All SAX parsers must also implement a zero-argument constructor * (though other constructors are also allowed). * * SAX parsers are reusable but not re-entrant: the application * may reuse a parser object (possibly with a different input source) * once the first parse has completed successfully, but it may not * invoke the parse() methods recursively within a parse. * * $Log$ * Revision 1.3 2000/02/09 01:59:12 abagchi * Removed private function docs, added parse docs * * Revision 1.2 2000/02/06 07:47:58 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:07:46 twl * Initial checkin * * Revision 1.3 1999/11/08 20:45:02 rahul * Swat for adding in Product name and CVS comment log variable. * * @see EntityResolver#EntityResolver * @see DTDHandler#DTDHandler * @see DocumentHandler#DocumentHandler * @see ErrorHandler#ErrorHandler * @see HandlerBase#HandlerBase * @see InputSource#InputSource */ #include <util/XML4CDefs.hpp> class SAX_EXPORT Parser { public: /** @name Constructors and Destructor */ // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- //@{ /** The default constructor */ Parser() { } /** The destructor */ virtual ~Parser() { } //@} //----------------------------------------------------------------------- // The parser interface //----------------------------------------------------------------------- /** @name The parser interfaces */ //@{ /** * Allow an application to register a custom entity resolver. * * If the application does not register an entity resolver, the * SAX parser will resolve system identifiers and open connections * to entities itself (this is the default behaviour implemented in * HandlerBase). * * Applications may register a new or different entity resolver * in the middle of a parse, and the SAX parser must begin using * the new resolver immediately. * * @param resolver The object for resolving entities. * @see EntityResolver#EntityResolver * @see HandlerBase#HandlerBase */ virtual void setEntityResolver(EntityResolver* const resolver) = 0; /** * Allow an application to register a DTD event handler. * * If the application does not register a DTD handler, all DTD * events reported by the SAX parser will be silently ignored (this * is the default behaviour implemented by HandlerBase). * * Applications may register a new or different handler in the middle * of a parse, and the SAX parser must begin using the new handler * immediately. * * @param handler The DTD handler. * @see DTDHandler#DTDHandler * @see HandlerBase#HandlerBase */ virtual void setDTDHandler(DTDHandler* const handler) = 0; /** * Allow an application to register a document event handler. * * If the application does not register a document handler, all * document events reported by the SAX parser will be silently * ignored (this is the default behaviour implemented by * HandlerBase). * * Applications may register a new or different handler in the * middle of a parse, and the SAX parser must begin using the new * handler immediately. * * @param handler The document handler. * @see DocumentHandler#DocumentHandler * @see HandlerBase#HandlerBase */ virtual void setDocumentHandler(DocumentHandler* const handler) = 0; /** * Allow an application to register an error event handler. * * If the application does not register an error event handler, * all error events reported by the SAX parser will be silently * ignored, except for fatalError, which will throw a SAXException * (this is the default behaviour implemented by HandlerBase). * * Applications may register a new or different handler in the * middle of a parse, and the SAX parser must begin using the new * handler immediately. * * @param handler The error handler. * @see ErrorHandler#ErrorHandler * @see SAXException#SAXException * @see HandlerBase#HandlerBase */ virtual void setErrorHandler(ErrorHandler* const handler) = 0; /** * Parse an XML document. * * The application can use this method to instruct the SAX parser * to begin parsing an XML document from any valid input * source (a character stream, a byte stream, or a URI). * * Applications may not invoke this method while a parse is in * progress (they should create a new Parser instead for each * additional XML document). Once a parse is complete, an * application may reuse the same Parser object, possibly with a * different input source. * * @param source The input source for the top-level of the * XML document. * @param reuseValidator Indicates whether the validator should be * reused, ignoring any external subset. If true, there * cannot be any internal subset. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @see InputSource#InputSource * @see #setEntityResolver * @see #setDTDHandler * @see #setDocumentHandler * @see #setErrorHandler */ virtual void parse ( const InputSource& source , const bool reuseValidator = false ) = 0; /** * Parse an XML document from a system identifier (URI). * * This method is a shortcut for the common case of reading a * document from a system identifier. It is the exact equivalent * of the following: * * parse(new URLInputSource(systemId)); * * If the system identifier is a URL, it must be fully resolved * by the application before it is passed to the parser. * * @param systemId The system identifier (URI). * @param reuseValidator Indicates whether the validator should be * reused, ignoring any external subset. If true, there * cannot be any internal subset. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @see #parse(InputSource) */ virtual void parse ( const XMLCh* const systemId , const bool reuseValidator = false ) = 0; /** * Parse an XML document from a system identifier (URI). * * This method is a shortcut for the common case of reading a * document from a system identifier. It is the exact equivalent * of the following: * * parse(new URLInputSource(systemId)); * * If the system identifier is a URL, it must be fully resolved * by the application before it is passed to the parser. * * @param systemId The system identifier (URI). * @param reuseValidator Indicates whether the validator should be * reused, ignoring any external subset. If true, there * cannot be any internal subset. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @see #parse(InputSource) */ virtual void parse ( const char* const systemId , const bool reuseValidator = false ) = 0; //@} private : /* The copy constructor, you cannot call this directly */ Parser(const Parser&); /* The assignment operator, you cannot call this directly */ void operator=(const Parser&); }; #endif <|endoftext|>
<commit_before>/* * ElphelPHG - Elphel PHG cameras related developement * * Copyright (c) 2014 FOXEL SA - http://foxel.ch * Please read <http://foxel.ch/license> for more information. * * This file is part of the FOXEL project <http://foxel.ch>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Additional Terms: * * You are required to preserve legal notices and author attributions in * that material or in the Appropriate Legal Notices displayed by works * containing it. * * You are required to attribute the work as explained in the "Usage and * Attribution" section of <http://foxel.ch/license>. */ #include "sensorData.hpp" #include "xml.hpp" SensorData::SensorData(const char *path) { xmlData=new Xml(path); subCamera=get("subCamera"); channel=get("channel"); pixelSize=get("pixelSize"); radius=get("radius"); azimuth=get("azimuth"); height=get("height"); focalLength=get("focalLength"); entrancePupilForward=get("entrancePupilForward"); heading=get("heading"); elevation=get("elevation"); roll=get("roll"); px0=get("px0"); py0=get("py0"); distortionA=get("distortionA"); distortionB=get("distortionB"); distortionC=get("distortionC"); distortionA5=get("distortionA5"); distortionA6=get("distortionA6"); distortionA7=get("distortionA7"); distortionA8=get("distortionA8"); distortionRadius=get("distortionRadius"); pixelCorrectionHeight=get("pixelCorrectionHeight"); pixelCorrectionWidth=get("pixelCorrectionWidth"); pixelCorrectionDecimation=get("pixelCorrectionDecimation"); } double SensorData::get(const char *property) { std::string expr=std::string("/properties//")+property; return xmlData->getDouble(expr.c_str()); } <commit_msg>fix subcamera xml property name<commit_after>/* * ElphelPHG - Elphel PHG cameras related developement * * Copyright (c) 2014 FOXEL SA - http://foxel.ch * Please read <http://foxel.ch/license> for more information. * * This file is part of the FOXEL project <http://foxel.ch>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Additional Terms: * * You are required to preserve legal notices and author attributions in * that material or in the Appropriate Legal Notices displayed by works * containing it. * * You are required to attribute the work as explained in the "Usage and * Attribution" section of <http://foxel.ch/license>. */ #include "sensorData.hpp" #include "xml.hpp" SensorData::SensorData(const char *path) { xmlData=new Xml(path); subCamera=get("subcamera"); channel=get("channel"); pixelSize=get("pixelSize"); radius=get("radius"); azimuth=get("azimuth"); height=get("height"); focalLength=get("focalLength"); entrancePupilForward=get("entrancePupilForward"); heading=get("heading"); elevation=get("elevation"); roll=get("roll"); px0=get("px0"); py0=get("py0"); distortionA=get("distortionA"); distortionB=get("distortionB"); distortionC=get("distortionC"); distortionA5=get("distortionA5"); distortionA6=get("distortionA6"); distortionA7=get("distortionA7"); distortionA8=get("distortionA8"); distortionRadius=get("distortionRadius"); pixelCorrectionHeight=get("pixelCorrectionHeight"); pixelCorrectionWidth=get("pixelCorrectionWidth"); pixelCorrectionDecimation=get("pixelCorrectionDecimation"); } double SensorData::get(const char *property) { std::string expr=std::string("/properties//")+property; return xmlData->getDouble(expr.c_str()); } <|endoftext|>
<commit_before>/* wxWidgets about dialog */ #include <wx/aboutdlg.h> #include "wx/statline.h" #include "wx/generic/aboutdlgg.h" #include "fctsys.h" #include "common.h" extern wxString g_Main_Title; // Import program title /**********************************/ wxString SetMsg( const wxString& msg ) /**********************************/ /* add \n at the beginning of msg under Windows, and do nothing under other version of wxWidgets * Needed under wxWidgets 2.8 because wxGTK and wxMSW do not have the same behavior * Add Developer needs \n between names under wxMSW, and nothing under wxGTK * when displaying developer and others. * Perhaps depending on wxWidgets versions */ { wxString message; #if 1 /* Windows */ message = wxT( "\n" ); #endif message << msg; return message; } /**************************************************/ void InitKiCadAbout( wxAboutDialogInfo& info ) /**************************************************/ { /* Set name and title */ info.SetName( g_Main_Title ); /* Set description */ wxString description; /* KiCad build version */ description << ( _T( "Build: " ) ) << GetAboutBuildVersion(); /* Print for wxversion */ description << ( wxT( "\n\nwxWidgets " ) ) << wxMAJOR_VERSION << wxT( "." ) << wxMINOR_VERSION << wxT( "." ) << wxRELEASE_NUMBER /* Show Unicode or Ansi version */ #if wxUSE_UNICODE << ( wxT( " Unicode\n" ) ); # else << ( wxT( " Ansi\n" ) ); #endif #define FreeBSD /************************** * Check Operating System * **************************/ #if defined __WINDOWS__ description << ( wxT( "on Windows" ) ); /* Check for wxMAC */ # elif defined __WXMAC__ description << ( wxT( "on Macintosch" ) ); /* Linux 64 bits */ # elif defined _LP64 && __LINUX__ description << ( wxT( "on 64 Bits GNU/Linux" ) ); /* Linux 32 bits */ # elif defined __LINUX__ description << ( wxT( "on 32 Bits GNU/Linux" ) ); /* OpenBSD */ # elif defined __OpenBSD__ description << ( wxT ("on OpenBSD") ); /* FreeBSD */ # elif defined __FreeBSD__ description << ( wxT ("on FreeBSD") ); #endif /* Websites */ description << wxT( "\n\nKiCad on the web\n\n" ); description << wxT( "http://iut-tice.ujf-grenoble.fr/kicad \n" ); description << wxT( "http://kicad.sourceforge.net \n" ); description << wxT( "http://www.kicadlib.org" ); /* Set the complete about description */ info.SetDescription( description ); /* Set copyright dialog */ info.SetCopyright( _T( "(C) 1992-2009 KiCad Developers Team" ) ); /* Set license dialog */ info.SetLicence( wxString::FromAscii ( "The complete KiCad EDA Suite is released under the\n" "GNU General Public License version 2.\n" "See <http://www.gnu.org/licenses/> for more information." )); /* Add developers */ info.AddDeveloper( wxT( "Jean-Pierre Charras <jean-pierre.charras@inpg.fr>" ) ); info.AddDeveloper( SetMsg( wxT( "Dick Hollenbeck <dick@softplc.com>" ) ) ); info.AddDeveloper( SetMsg( wxT( "Jerry Jacobs <jerkejacobs@gmail.com>" ) ) ); info.AddDeveloper( SetMsg( wxT( "Jonas Diemer <diemer@gmx.de>" ) ) ); info.AddDeveloper( SetMsg( wxT( "KBool Library <http://boolean.klaasholwerda.nl/bool.html>" ) ) ); info.AddDeveloper( SetMsg( wxT( "Rok Markovic <rok@kanardia.eu>" ) ) ); info.AddDeveloper( SetMsg( wxT( "Tim Hanson <sideskate@gmail.com>" ) ) ); info.AddDeveloper( SetMsg( wxT( "Vesa Solonen <vesa.solonen@hut.fi>" ) ) ); info.AddDeveloper( SetMsg( wxT( "Wayne Stambaugh <stambaughw@verizon.net>" ) ) ); /* Add document writers*/ info.AddDocWriter( wxT( "Jean-Pierre Charras <jean-pierre.charras@inpg.fr>" ) ); info.AddDocWriter( SetMsg( wxT( "Igor Plyatov <plyatov@gmail.com>" ) ) ); /* Add translators */ info.AddTranslator( wxT( "Czech (CZ) Martin Kratoška <martin@ok1rr.com>" ) ); info.AddTranslator( SetMsg( wxT( "Dutch (NL) Jerry Jacobs <jerkejacobs@gmail.com>" ) ) ); info.AddTranslator( SetMsg( wxT( "French (FR) Jean-Pierre Charras <jean-pierre.charras@inpg.fr>" ) ) ); info.AddTranslator( SetMsg( wxT( "Polish (PL) Mateusz Skowroński <skowri@gmail.com>" ) ) ); info.AddTranslator( SetMsg( wxT( "Portuguese (PT) Renie Marquet <reniemarquet@uol.com.br>" ) ) ); info.AddTranslator( SetMsg( wxT( "Russian (RU) Igor Plyatov <plyatov@gmail.com>" ) ) ); info.AddTranslator( SetMsg( wxT( "Spanish (ES) Pedro Martin del Valle <pkicad@yahoo.es>" ) ) ); info.AddTranslator( SetMsg( wxT( "Spanish (ES) Iñigo Zuluaga <inigo_zuluaga@yahoo.es>" ) ) ); /* TODO are these all russian translators, placed them here now TODO TODO or else align them below other language maintainer with mail adres TODO*/ info.AddTranslator( SetMsg( wxT( "\n\nRemy Halvick" ) ) ); info.AddTranslator( SetMsg( wxT( "David Briscoe" ) ) ); info.AddTranslator( SetMsg( wxT( "Dominique Laigle" ) ) ); info.AddTranslator( SetMsg( wxT( "Paul Burke" ) ) ); /* Add programm credits for icons */ info.AddArtist( wxT( "Icons by Iñigo Zuluaga" ) ); info.AddArtist( wxT( "3D modules by Renie Marquet <reniemarquet@uol.com.br>" ) ); } <commit_msg>Added Cyril Frausti to artist for some of his 3d modules, mail adres added of Iñigo Zuluagaz<commit_after>/* wxWidgets about dialog */ #include <wx/aboutdlg.h> #include "wx/statline.h" #include "wx/generic/aboutdlgg.h" #include "fctsys.h" #include "common.h" extern wxString g_Main_Title; // Import program title /**********************************/ wxString SetMsg( const wxString& msg ) /**********************************/ /* add \n at the beginning of msg under Windows, and do nothing under other version of wxWidgets * Needed under wxWidgets 2.8 because wxGTK and wxMSW do not have the same behavior * Add Developer needs \n between names under wxMSW, and nothing under wxGTK * when displaying developer and others. * Perhaps depending on wxWidgets versions */ { wxString message; #if 1 /* Windows */ message = wxT( "\n" ); #endif message << msg; return message; } /**************************************************/ void InitKiCadAbout( wxAboutDialogInfo& info ) /**************************************************/ { /* Set name and title */ info.SetName( g_Main_Title ); /* Set description */ wxString description; /* KiCad build version */ description << ( _T( "Build: " ) ) << GetAboutBuildVersion(); /* Print for wxversion */ description << ( wxT( "\n\nwxWidgets " ) ) << wxMAJOR_VERSION << wxT( "." ) << wxMINOR_VERSION << wxT( "." ) << wxRELEASE_NUMBER /* Show Unicode or Ansi version */ #if wxUSE_UNICODE << ( wxT( " Unicode\n" ) ); # else << ( wxT( " Ansi\n" ) ); #endif /************************** * Check Operating System * **************************/ #if defined __WINDOWS__ description << ( wxT( "on Windows" ) ); /* Check for wxMAC */ # elif defined __WXMAC__ description << ( wxT( "on Macintosch" ) ); /* Linux 64 bits */ # elif defined _LP64 && __LINUX__ description << ( wxT( "on 64 Bits GNU/Linux" ) ); /* Linux 32 bits */ # elif defined __LINUX__ description << ( wxT( "on 32 Bits GNU/Linux" ) ); /* OpenBSD */ # elif defined __OpenBSD__ description << ( wxT ("on OpenBSD") ); /* FreeBSD */ # elif defined __FreeBSD__ description << ( wxT ("on FreeBSD") ); #endif /* Websites */ description << wxT( "\n\nKiCad on the web\n\n" ); description << wxT( "http://iut-tice.ujf-grenoble.fr/kicad \n" ); description << wxT( "http://kicad.sourceforge.net \n" ); description << wxT( "http://www.kicadlib.org" ); /* Set the complete about description */ info.SetDescription( description ); /* Set copyright dialog */ info.SetCopyright( _T( "(C) 1992-2009 KiCad Developers Team" ) ); /* Set license dialog */ info.SetLicence( wxString::FromAscii ( "The complete KiCad EDA Suite is released under the\n" "GNU General Public License version 2.\n" "See <http://www.gnu.org/licenses/> for more information." )); /* Add developers */ info.AddDeveloper( wxT( "Jean-Pierre Charras <jean-pierre.charras@inpg.fr>" ) ); info.AddDeveloper( SetMsg( wxT( "Dick Hollenbeck <dick@softplc.com>" ) ) ); info.AddDeveloper( SetMsg( wxT( "Jerry Jacobs <jerkejacobs@gmail.com>" ) ) ); info.AddDeveloper( SetMsg( wxT( "Jonas Diemer <diemer@gmx.de>" ) ) ); info.AddDeveloper( SetMsg( wxT( "KBool Library <http://boolean.klaasholwerda.nl/bool.html>" ) ) ); info.AddDeveloper( SetMsg( wxT( "Rok Markovic <rok@kanardia.eu>" ) ) ); info.AddDeveloper( SetMsg( wxT( "Tim Hanson <sideskate@gmail.com>" ) ) ); info.AddDeveloper( SetMsg( wxT( "Vesa Solonen <vesa.solonen@hut.fi>" ) ) ); info.AddDeveloper( SetMsg( wxT( "Wayne Stambaugh <stambaughw@verizon.net>" ) ) ); /* Add document writers*/ info.AddDocWriter( wxT( "Jean-Pierre Charras <jean-pierre.charras@inpg.fr>" ) ); info.AddDocWriter( SetMsg( wxT( "Igor Plyatov <plyatov@gmail.com>" ) ) ); /* Add translators */ info.AddTranslator( wxT( "Czech (CZ) Martin Kratoška <martin@ok1rr.com>" ) ); info.AddTranslator( SetMsg( wxT( "Dutch (NL) Jerry Jacobs <jerkejacobs@gmail.com>" ) ) ); info.AddTranslator( SetMsg( wxT( "French (FR) Jean-Pierre Charras <jean-pierre.charras@inpg.fr>" ) ) ); info.AddTranslator( SetMsg( wxT( "Polish (PL) Mateusz Skowroński <skowri@gmail.com>" ) ) ); info.AddTranslator( SetMsg( wxT( "Portuguese (PT) Renie Marquet <reniemarquet@uol.com.br>" ) ) ); info.AddTranslator( SetMsg( wxT( "Russian (RU) Igor Plyatov <plyatov@gmail.com>" ) ) ); info.AddTranslator( SetMsg( wxT( "Spanish (ES) Pedro Martin del Valle <pkicad@yahoo.es>" ) ) ); info.AddTranslator( SetMsg( wxT( "Spanish (ES) Iñigo Zuluaga <inigo_zuluaga@yahoo.es>" ) ) ); /* TODO are these all russian translators, placed them here now TODO TODO or else align them below other language maintainer with mail adres TODO*/ info.AddTranslator( SetMsg( wxT( "\nRemy Halvick" ) ) ); info.AddTranslator( SetMsg( wxT( "David Briscoe" ) ) ); info.AddTranslator( SetMsg( wxT( "Dominique Laigle" ) ) ); info.AddTranslator( SetMsg( wxT( "Paul Burke" ) ) ); /* Add programm credits for icons */ info.AddArtist( wxT( "Icons by Iñigo Zuluagaz <inigo_zuluaga@yahoo.es>" ) ); info.AddArtist( wxT( "3D modules by Renie Marquet <reniemarquet@uol.com.br>" ) ); info.AddArtist( wxT( "3D modules by Cyril Frausti <cyril.frausti@gmail.com>" ) ); } <|endoftext|>
<commit_before>#include <sstream> #include <fstream> #include <stdexcept> #include <cmath> #include "cvrp.h" #include "tsplib_format.h" namespace VrpSolver { unsigned int Cvrp::demand(unsigned int node_id) const { if ((1 > node_id) || (node_id > dimension_)) throw std::out_of_range("error: in Cvrp::demand"); return demands_[node_id]; } int Cvrp::distance(unsigned int from, unsigned int to) const { if ((1 > from) || (from > dimension_) || (1 > to) || (to > dimension_)) throw std::out_of_range("error: in Cvrp::distance"); const int index = (to > from) ? ((to-2)*(to-1)/2+(from-1)) : ((from-2)*(from-1)/2+(to-1)); return distances_[index]; } // 文字列strからtrim_char文字列に含まれている文字を削除 void trim(std::string& str, const std::string& trim_char) { size_t pos; while ((pos = str.find_first_of(trim_char)) != std::string::npos) str.erase(pos, 1); } // セミコロン以後の文字列(空白の直前まで)を読み取る std::string get_parameter(std::ifstream& ifs) { std::string param; ifs >> param; while (param == ":") ifs >> param; // ":"は読み飛ばす return param; } // infileから情報を読み取りCvrpクラスをセットアップする void read_vrp(Cvrp& cvrp, const std::string &infile) { std::ifstream ifs(infile.c_str()); if (!ifs) throw std::runtime_error("error: can't open file " + infile); std::string edge_weight_type, edge_weight_format, display_data_type; while (!ifs.eof()) { std::string tsp_keyword; ifs >> tsp_keyword; trim(tsp_keyword, " :"); if (tsp_keyword == Tsplib::NAME) { cvrp.name_ = get_parameter(ifs); } else if (tsp_keyword == Tsplib::DIMENSION) { cvrp.dimension_ = stoi(get_parameter(ifs)); } else if (tsp_keyword == Tsplib::CAPACITY) { cvrp.capacity_ = stoi(get_parameter(ifs)); } else if (tsp_keyword == Tsplib::DEMAND_SECTION) { cvrp.demands_.push_back(0); // 0要素目は0にしておく for (int i=1; i <= cvrp.dimension_; i++) { unsigned int node_id, demand; ifs >> node_id >> demand; if (node_id != i) throw std::runtime_error("error:" "DEMAND_SECTION format may be different"); cvrp.demands_.push_back(demand); } } else if (tsp_keyword == Tsplib::EDGE_WEIGHT_TYPE) { edge_weight_type = get_parameter(ifs); } else if (tsp_keyword == Tsplib::EDGE_WEIGHT_FORMAT) { edge_weight_format = get_parameter(ifs); } else if (tsp_keyword == Tsplib::DISPLAY_DATA_TYPE) { display_data_type = get_parameter(ifs); } else if (tsp_keyword == Tsplib::EDGE_WEIGHT_SECTION) { if (edge_weight_format == Tsplib::EdgeWeightFormat::LOWER_ROW) { int num=0; for (int i=0; i < cvrp.dimension_; i++) { for (int j=0; j < i; j++) { int weight; ifs >> weight; cvrp.distances_.push_back(weight); num++; } } // n点からなる完全グラフの枝数はn * (n-1) / 2 const int num_edges = cvrp.dimension_ * (cvrp.dimension_-1) / 2; if (num != num_edges) throw std::runtime_error("error:" "EDGE_WEIGHT_SECTION may be differnt"); } } else if (tsp_keyword == Tsplib::NODE_COORD_SECTION) { int n=1, m, x, y; while (n != cvrp.dimension_) { ifs >> n >> x >> y; std::pair<int,int> c(x,y); cvrp.coords_.push_back(c); n++; } } else if (tsp_keyword == Tsplib::DEPOT_SECTION) { cvrp.depot_ = stoi(get_parameter(ifs)); if (stoi(get_parameter(ifs)) != -1) throw std::runtime_error("error:" "can't handle multiple depots"); } } // distancesの設定 if (edge_weight_type != Tsplib::EdgeWeightType::EXPLICIT) { auto& distances = cvrp.distances_; auto& coords = cvrp.coords_; for (int i=0; i < cvrp.dimension_; i++) { for (int j=0; j < i; j++) { int dx = coords[j].first - coords[i].first; int dy = coords[j].second - coords[i].second; distances.push_back(floor(sqrt(dx*dx + dy*dy)+0.5)); } } } } } // namespace VrpSolver <commit_msg>Cvrpへの設定をif文ではなくswitch文に変更<commit_after>#include <sstream> #include <fstream> #include <stdexcept> #include <map> #include <cmath> #include "cvrp.h" #include "tsplib_format.h" namespace VrpSolver { unsigned int Cvrp::demand(unsigned int node_id) const { if ((1 > node_id) || (node_id > dimension_)) throw std::out_of_range("error: in Cvrp::demand"); return demands_[node_id]; } int Cvrp::distance(unsigned int from, unsigned int to) const { if ((1 > from) || (from > dimension_) || (1 > to) || (to > dimension_)) throw std::out_of_range("error: in Cvrp::distance"); const int index = (to > from) ? ((to-2)*(to-1)/2+(from-1)) : ((from-2)*(from-1)/2+(to-1)); return distances_[index]; } // 文字列strからtrim_char文字列に含まれている文字を削除 void trim(std::string& str, const std::string& trim_char) { size_t pos; while ((pos = str.find_first_of(trim_char)) != std::string::npos) str.erase(pos, 1); } // セミコロン以後の文字列(空白の直前まで)を読み取る std::string get_parameter(std::ifstream& ifs) { std::string param; ifs >> param; while (param == ":") ifs >> param; // ":"は読み飛ばす return param; } enum TsplibKeyword { NAME=100, TYPE, COMMENT, DIMENSION, CAPACITY, EDGE_WEIGHT_TYPE, EDGE_WEIGHT_FORMAT, EDGE_DATA_FORMAT, NODE_COORD_TYPE, DISPLAY_DATA_TYPE, NODE_COORD_SECTION, DEPOT_SECTION, DEMAND_SECTION, EDGE_DATA_SECTION, EDGE_WEIGHT_SECTION, END_OF_FILE }; std::map<std::string, TsplibKeyword> keyword_map = { { "NAME", NAME }, { "TYPE", TYPE }, { "COMMENT", COMMENT }, { "DIMENSION", DIMENSION }, { "CAPACITY", CAPACITY }, { "EDGE_WEIGHT_TYPE", EDGE_WEIGHT_TYPE }, { "EDGE_WEIGHT_FORMAT", EDGE_WEIGHT_FORMAT }, { "EDGE_DATA_FORMAT", EDGE_DATA_FORMAT }, { "NODE_COORD_TYPE", NODE_COORD_TYPE }, { "DISPLAY_DATA_TYPE", DISPLAY_DATA_TYPE }, { "NODE_COORD_SECTION", NODE_COORD_SECTION }, { "DEPOT_SECTION", DEPOT_SECTION }, { "DEMAND_SECTION", DEMAND_SECTION }, { "EDGE_DATA_SECTION", EDGE_DATA_SECTION }, { "EDGE_WEIGHT_SECTION", EDGE_WEIGHT_SECTION }, { "EOF", END_OF_FILE } }; // infileから情報を読み取りCvrpクラスをセットアップする void read_vrp(Cvrp& cvrp, const std::string &infile) { std::ifstream ifs(infile.c_str()); if (!ifs) throw std::runtime_error("error: can't open file " + infile); std::string edge_weight_type, edge_weight_format, display_data_type; while (ifs) { std::string tsp_keyword; ifs >> tsp_keyword; if (ifs.eof()) break; trim(tsp_keyword, " :"); switch (keyword_map[tsp_keyword]) { // The specification part case NAME : cvrp.name_ = get_parameter(ifs); break; case TYPE : { std::string not_use; getline(ifs, not_use); } break; case COMMENT : { std::string not_use; getline(ifs, not_use); } break; case DIMENSION : cvrp.dimension_ = stoi(get_parameter(ifs)); break; case CAPACITY : cvrp.capacity_ = stoi(get_parameter(ifs)); break; case EDGE_WEIGHT_TYPE : edge_weight_type = get_parameter(ifs); break; case EDGE_WEIGHT_FORMAT : edge_weight_format = get_parameter(ifs); break; case EDGE_DATA_FORMAT : { std::string not_use; getline(ifs, not_use); break; } case NODE_COORD_TYPE : { std::string not_use; getline(ifs, not_use); break; } case DISPLAY_DATA_TYPE : display_data_type = get_parameter(ifs); break; // The data part case NODE_COORD_SECTION : { int n=0, m, x, y; // m do not use for (int i=0; i != cvrp.dimension_; i++) { ifs >> m >> x >> y; std::pair<int,int> c(x,y); cvrp.coords_.push_back(c); } break; } case DEPOT_SECTION : { cvrp.depot_ = stoi(get_parameter(ifs)); if (stoi(get_parameter(ifs)) != -1) throw std::runtime_error("error:" "can't handle multiple depots"); break; } case DEMAND_SECTION : { cvrp.demands_.push_back(0); // 0要素目は0にしておく for (int i=1; i <= cvrp.dimension_; i++) { unsigned int node_id, demand; ifs >> node_id >> demand; if (node_id != i) throw std::runtime_error("error:" "DEMAND_SECTION format may be different"); cvrp.demands_.push_back(demand); } break; } case EDGE_DATA_SECTION : throw std::runtime_error("Sorry, can not handle 'EDGE_DATA_SECTION'"); break; case EDGE_WEIGHT_SECTION : { if (edge_weight_format != "LOWER_ROW") throw std::runtime_error("Sorry, can not handle except EDGE_WEIGHT_FORMAT == LOWER_ROW"); for (int i=0; i < cvrp.dimension_; i++) { for (int j=0; j < i; j++) { int distance; ifs >> distance; cvrp.distances_.push_back(distance); } } break; } case END_OF_FILE : // do nothing break; default : throw std::runtime_error("error: unknown keyword '" + tsp_keyword + "'"); break; } } // distancesの設定 if (edge_weight_type != Tsplib::EdgeWeightType::EXPLICIT) { auto& distances = cvrp.distances_; auto& coords = cvrp.coords_; for (int i=0; i < cvrp.dimension_; i++) { for (int j=0; j < i; j++) { int dx = coords[j].first - coords[i].first; int dy = coords[j].second - coords[i].second; distances.push_back(floor(sqrt(dx*dx + dy*dy)+0.5)); } } } } } // namespace VrpSolver <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdint.h> #include <vector> #include <utility> #include <mesos/authorizer/authorizer.hpp> #include <mesos/master/detector.hpp> #include <mesos/mesos.hpp> #include <mesos/module/anonymous.hpp> #include <mesos/slave/resource_estimator.hpp> #include <process/owned.hpp> #include <process/process.hpp> #include <stout/check.hpp> #include <stout/flags.hpp> #include <stout/hashset.hpp> #include <stout/nothing.hpp> #include <stout/os.hpp> #include <stout/stringify.hpp> #include <stout/try.hpp> #include "common/build.hpp" #include "common/http.hpp" #include "hook/manager.hpp" #ifdef __linux__ #include "linux/systemd.hpp" #endif // __linux__ #include "logging/logging.hpp" #include "messages/flags.hpp" #include "messages/messages.hpp" #include "module/manager.hpp" #include "slave/gc.hpp" #include "slave/slave.hpp" #include "slave/status_update_manager.hpp" #include "version/version.hpp" using namespace mesos::internal; using namespace mesos::internal::slave; using mesos::master::detector::MasterDetector; using mesos::modules::Anonymous; using mesos::modules::ModuleManager; using mesos::master::detector::MasterDetector; using mesos::slave::QoSController; using mesos::slave::ResourceEstimator; using mesos::Authorizer; using mesos::SlaveInfo; using process::Owned; using process::firewall::DisabledEndpointsFirewallRule; using process::firewall::FirewallRule; using std::cerr; using std::cout; using std::endl; using std::move; using std::string; using std::vector; class Flags : public virtual slave::Flags { public: Flags() { add(&Flags::ip, "ip", "IP address to listen on. This cannot be used in conjunction\n" "with `--ip_discovery_command`."); add(&Flags::port, "port", "Port to listen on.", SlaveInfo().port()); add(&Flags::advertise_ip, "advertise_ip", "IP address advertised to reach this Mesos slave.\n" "The slave does not bind to this IP address.\n" "However, this IP address may be used to access this slave."); add(&Flags::advertise_port, "advertise_port", "Port advertised to reach this Mesos slave (along with\n" "`advertise_ip`). The slave does not bind to this port.\n" "However, this port (along with `advertise_ip`) may be used to\n" "access this slave."); add(&Flags::master, "master", "May be one of:\n" " `host:port`\n" " `zk://host1:port1,host2:port2,.../path`\n" " `zk://username:password@host1:port1,host2:port2,.../path`\n" " `file:///path/to/file` (where file contains one of the above)"); add(&Flags::ip_discovery_command, "ip_discovery_command", "Optional IP discovery binary: if set, it is expected to emit\n" "the IP address which the slave will try to bind to.\n" "Cannot be used in conjunction with `--ip`."); } // The following flags are executable specific (e.g., since we only // have one instance of libprocess per execution, we only want to // advertise the IP and port option once, here). Option<string> ip; uint16_t port; Option<string> advertise_ip; Option<string> advertise_port; Option<string> master; // Optional IP discover script that will set the slave's IP. // If set, its output is expected to be a valid parseable IP string. Option<string> ip_discovery_command; }; int main(int argc, char** argv) { // The order of initialization is as follows: // * Windows socket stack. // * Validate flags. // * Log build information. // * Libprocess // * Logging // * Version process // * Firewall rules: should be initialized before initializing HTTP endpoints. // * Modules: Load module libraries and manifests before they // can be instantiated. // * Anonymous modules: Later components such as Allocators, and master // contender/detector might depend upon anonymous modules. // * Hooks. // * Systemd support (if it exists). // * Fetcher and Containerizer. // * Master detector. // * Authorizer. // * Garbage collector. // * Status update manager. // * Resource estimator. // * QoS controller. // * `Agent` process. // // TODO(avinash): Add more comments discussing the rationale behind for this // particular component ordering. GOOGLE_PROTOBUF_VERIFY_VERSION; ::Flags flags; Try<flags::Warnings> load = flags.load("MESOS_", argc, argv); if (flags.help) { cout << flags.usage() << endl; return EXIT_SUCCESS; } if (flags.version) { cout << "mesos" << " " << MESOS_VERSION << endl; return EXIT_SUCCESS; } // TODO(marco): this pattern too should be abstracted away // in FlagsBase; I have seen it at least 15 times. if (load.isError()) { cerr << flags.usage(load.error()) << endl; return EXIT_FAILURE; } if (flags.master.isNone() && flags.master_detector.isNone()) { cerr << flags.usage("Missing required option `--master` or " "`--master_detector`.") << endl; return EXIT_FAILURE; } if (flags.master.isSome() && flags.master_detector.isSome()) { cerr << flags.usage("Only one of --master or --master_detector options " "should be specified."); return EXIT_FAILURE; } // Initialize libprocess. if (flags.ip_discovery_command.isSome() && flags.ip.isSome()) { EXIT(EXIT_FAILURE) << flags.usage( "Only one of `--ip` or `--ip_discovery_command` should be specified"); } if (flags.ip_discovery_command.isSome()) { Try<string> ipAddress = os::shell(flags.ip_discovery_command.get()); if (ipAddress.isError()) { EXIT(EXIT_FAILURE) << ipAddress.error(); } os::setenv("LIBPROCESS_IP", strings::trim(ipAddress.get())); } else if (flags.ip.isSome()) { os::setenv("LIBPROCESS_IP", flags.ip.get()); } os::setenv("LIBPROCESS_PORT", stringify(flags.port)); if (flags.advertise_ip.isSome()) { os::setenv("LIBPROCESS_ADVERTISE_IP", flags.advertise_ip.get()); } if (flags.advertise_port.isSome()) { os::setenv("LIBPROCESS_ADVERTISE_PORT", flags.advertise_port.get()); } // Log build information. LOG(INFO) << "Build: " << build::DATE << " by " << build::USER; LOG(INFO) << "Version: " << MESOS_VERSION; if (build::GIT_TAG.isSome()) { LOG(INFO) << "Git tag: " << build::GIT_TAG.get(); } if (build::GIT_SHA.isSome()) { LOG(INFO) << "Git SHA: " << build::GIT_SHA.get(); } const string id = process::ID::generate("slave"); // Process ID. // If `process::initialize()` returns `false`, then it was called before this // invocation, meaning the authentication realm for libprocess-level HTTP // endpoints was set incorrectly. This should be the first invocation. if (!process::initialize( id, READWRITE_HTTP_AUTHENTICATION_REALM, READONLY_HTTP_AUTHENTICATION_REALM)) { EXIT(EXIT_FAILURE) << "The call to `process::initialize()` in the agent's " << "`main()` was not the function's first invocation"; } logging::initialize(argv[0], flags, true); // Catch signals. // Log any flag warnings (after logging is initialized). foreach (const flags::Warning& warning, load->warnings) { LOG(WARNING) << warning.message; } spawn(new VersionProcess(), true); if (flags.firewall_rules.isSome()) { vector<Owned<FirewallRule>> rules; const Firewall firewall = flags.firewall_rules.get(); if (firewall.has_disabled_endpoints()) { hashset<string> paths; foreach (const string& path, firewall.disabled_endpoints().paths()) { paths.insert(path); } rules.emplace_back(new DisabledEndpointsFirewallRule(paths)); } process::firewall::install(move(rules)); } // Initialize modules. if (flags.modules.isSome() && flags.modulesDir.isSome()) { EXIT(EXIT_FAILURE) << flags.usage("Only one of --modules or --modules_dir should be specified"); } if (flags.modulesDir.isSome()) { Try<Nothing> result = ModuleManager::load(flags.modulesDir.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error(); } } if (flags.modules.isSome()) { Try<Nothing> result = ModuleManager::load(flags.modules.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error(); } } // Create anonymous modules. foreach (const string& name, ModuleManager::find<Anonymous>()) { Try<Anonymous*> create = ModuleManager::create<Anonymous>(name); if (create.isError()) { EXIT(EXIT_FAILURE) << "Failed to create anonymous module named '" << name << "'"; } // We don't bother keeping around the pointer to this anonymous // module, when we exit that will effectively free its memory. // // TODO(benh): We might want to add explicit finalization (and // maybe explicit initialization too) in order to let the module // do any housekeeping necessary when the slave is cleanly // terminating. } // Initialize hooks. if (flags.hooks.isSome()) { Try<Nothing> result = HookManager::initialize(flags.hooks.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error installing hooks: " << result.error(); } } #ifdef __linux__ // Initialize systemd if it exists. if (flags.systemd_enable_support && systemd::exists()) { LOG(INFO) << "Inializing systemd state"; systemd::Flags systemdFlags; systemdFlags.enabled = flags.systemd_enable_support; systemdFlags.runtime_directory = flags.systemd_runtime_directory; systemdFlags.cgroups_hierarchy = flags.cgroups_hierarchy; Try<Nothing> initialize = systemd::initialize(systemdFlags); if (initialize.isError()) { EXIT(EXIT_FAILURE) << "Failed to initialize systemd: " + initialize.error(); } } #endif // __linux__ Fetcher fetcher; Try<Containerizer*> containerizer = Containerizer::create(flags, false, &fetcher); if (containerizer.isError()) { EXIT(EXIT_FAILURE) << "Failed to create a containerizer: " << containerizer.error(); } Try<MasterDetector*> detector_ = MasterDetector::create( flags.master, flags.master_detector); if (detector_.isError()) { EXIT(EXIT_FAILURE) << "Failed to create a master detector: " << detector_.error(); } MasterDetector* detector = detector_.get(); Option<Authorizer*> authorizer_ = None(); string authorizerName = flags.authorizer; Result<Authorizer*> authorizer((None())); if (authorizerName != slave::DEFAULT_AUTHORIZER) { LOG(INFO) << "Creating '" << authorizerName << "' authorizer"; // NOTE: The contents of --acls will be ignored. authorizer = Authorizer::create(authorizerName); } else { // `authorizerName` is `DEFAULT_AUTHORIZER` at this point. if (flags.acls.isSome()) { LOG(INFO) << "Creating default '" << authorizerName << "' authorizer"; authorizer = Authorizer::create(flags.acls.get()); } } if (authorizer.isError()) { EXIT(EXIT_FAILURE) << "Could not create '" << authorizerName << "' authorizer: " << authorizer.error(); } else if (authorizer.isSome()) { authorizer_ = authorizer.get(); // Set the authorization callbacks for libprocess HTTP endpoints. // Note that these callbacks capture `authorizer_.get()`, but the agent // creates a copy of the authorizer during construction. Thus, if in the // future it becomes possible to dynamically set the authorizer, this would // break. process::http::authorization::setCallbacks( createAuthorizationCallbacks(authorizer_.get())); } Files files(READONLY_HTTP_AUTHENTICATION_REALM, authorizer_); GarbageCollector gc; StatusUpdateManager statusUpdateManager(flags); Try<ResourceEstimator*> resourceEstimator = ResourceEstimator::create(flags.resource_estimator); if (resourceEstimator.isError()) { cerr << "Failed to create resource estimator: " << resourceEstimator.error() << endl; return EXIT_FAILURE; } Try<QoSController*> qosController = QoSController::create(flags.qos_controller); if (qosController.isError()) { cerr << "Failed to create QoS Controller: " << qosController.error() << endl; return EXIT_FAILURE; } Slave* slave = new Slave( id, flags, detector, containerizer.get(), &files, &gc, &statusUpdateManager, resourceEstimator.get(), qosController.get(), authorizer_); process::spawn(slave); process::wait(slave->self()); delete slave; delete resourceEstimator.get(); delete qosController.get(); delete detector; delete containerizer.get(); if (authorizer_.isSome()) { delete authorizer_.get(); } // NOTE: We need to finalize libprocess, on Windows especially, // as any binary that uses the networking stack on Windows must // also clean up the networking stack before exiting. process::finalize(true); return EXIT_SUCCESS; } <commit_msg>Fixed a crash on the agent when handling the SIGUSR1 signal.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdint.h> #include <vector> #include <utility> #include <mesos/authorizer/authorizer.hpp> #include <mesos/master/detector.hpp> #include <mesos/mesos.hpp> #include <mesos/module/anonymous.hpp> #include <mesos/slave/resource_estimator.hpp> #include <process/owned.hpp> #include <process/process.hpp> #include <stout/check.hpp> #include <stout/flags.hpp> #include <stout/hashset.hpp> #include <stout/nothing.hpp> #include <stout/os.hpp> #include <stout/stringify.hpp> #include <stout/try.hpp> #include "common/build.hpp" #include "common/http.hpp" #include "hook/manager.hpp" #ifdef __linux__ #include "linux/systemd.hpp" #endif // __linux__ #include "logging/logging.hpp" #include "messages/flags.hpp" #include "messages/messages.hpp" #include "module/manager.hpp" #include "slave/gc.hpp" #include "slave/slave.hpp" #include "slave/status_update_manager.hpp" #include "version/version.hpp" using namespace mesos::internal; using namespace mesos::internal::slave; using mesos::master::detector::MasterDetector; using mesos::modules::Anonymous; using mesos::modules::ModuleManager; using mesos::master::detector::MasterDetector; using mesos::slave::QoSController; using mesos::slave::ResourceEstimator; using mesos::Authorizer; using mesos::SlaveInfo; using process::Owned; using process::firewall::DisabledEndpointsFirewallRule; using process::firewall::FirewallRule; using std::cerr; using std::cout; using std::endl; using std::move; using std::string; using std::vector; class Flags : public virtual slave::Flags { public: Flags() { add(&Flags::ip, "ip", "IP address to listen on. This cannot be used in conjunction\n" "with `--ip_discovery_command`."); add(&Flags::port, "port", "Port to listen on.", SlaveInfo().port()); add(&Flags::advertise_ip, "advertise_ip", "IP address advertised to reach this Mesos slave.\n" "The slave does not bind to this IP address.\n" "However, this IP address may be used to access this slave."); add(&Flags::advertise_port, "advertise_port", "Port advertised to reach this Mesos slave (along with\n" "`advertise_ip`). The slave does not bind to this port.\n" "However, this port (along with `advertise_ip`) may be used to\n" "access this slave."); add(&Flags::master, "master", "May be one of:\n" " `host:port`\n" " `zk://host1:port1,host2:port2,.../path`\n" " `zk://username:password@host1:port1,host2:port2,.../path`\n" " `file:///path/to/file` (where file contains one of the above)"); add(&Flags::ip_discovery_command, "ip_discovery_command", "Optional IP discovery binary: if set, it is expected to emit\n" "the IP address which the slave will try to bind to.\n" "Cannot be used in conjunction with `--ip`."); } // The following flags are executable specific (e.g., since we only // have one instance of libprocess per execution, we only want to // advertise the IP and port option once, here). Option<string> ip; uint16_t port; Option<string> advertise_ip; Option<string> advertise_port; Option<string> master; // Optional IP discover script that will set the slave's IP. // If set, its output is expected to be a valid parseable IP string. Option<string> ip_discovery_command; }; int main(int argc, char** argv) { // The order of initialization is as follows: // * Windows socket stack. // * Validate flags. // * Log build information. // * Libprocess // * Logging // * Version process // * Firewall rules: should be initialized before initializing HTTP endpoints. // * Modules: Load module libraries and manifests before they // can be instantiated. // * Anonymous modules: Later components such as Allocators, and master // contender/detector might depend upon anonymous modules. // * Hooks. // * Systemd support (if it exists). // * Fetcher and Containerizer. // * Master detector. // * Authorizer. // * Garbage collector. // * Status update manager. // * Resource estimator. // * QoS controller. // * `Agent` process. // // TODO(avinash): Add more comments discussing the rationale behind for this // particular component ordering. GOOGLE_PROTOBUF_VERIFY_VERSION; ::Flags flags; Try<flags::Warnings> load = flags.load("MESOS_", argc, argv); if (flags.help) { cout << flags.usage() << endl; return EXIT_SUCCESS; } if (flags.version) { cout << "mesos" << " " << MESOS_VERSION << endl; return EXIT_SUCCESS; } // TODO(marco): this pattern too should be abstracted away // in FlagsBase; I have seen it at least 15 times. if (load.isError()) { cerr << flags.usage(load.error()) << endl; return EXIT_FAILURE; } if (flags.master.isNone() && flags.master_detector.isNone()) { cerr << flags.usage("Missing required option `--master` or " "`--master_detector`.") << endl; return EXIT_FAILURE; } if (flags.master.isSome() && flags.master_detector.isSome()) { cerr << flags.usage("Only one of --master or --master_detector options " "should be specified."); return EXIT_FAILURE; } // Initialize libprocess. if (flags.ip_discovery_command.isSome() && flags.ip.isSome()) { EXIT(EXIT_FAILURE) << flags.usage( "Only one of `--ip` or `--ip_discovery_command` should be specified"); } if (flags.ip_discovery_command.isSome()) { Try<string> ipAddress = os::shell(flags.ip_discovery_command.get()); if (ipAddress.isError()) { EXIT(EXIT_FAILURE) << ipAddress.error(); } os::setenv("LIBPROCESS_IP", strings::trim(ipAddress.get())); } else if (flags.ip.isSome()) { os::setenv("LIBPROCESS_IP", flags.ip.get()); } os::setenv("LIBPROCESS_PORT", stringify(flags.port)); if (flags.advertise_ip.isSome()) { os::setenv("LIBPROCESS_ADVERTISE_IP", flags.advertise_ip.get()); } if (flags.advertise_port.isSome()) { os::setenv("LIBPROCESS_ADVERTISE_PORT", flags.advertise_port.get()); } // Log build information. LOG(INFO) << "Build: " << build::DATE << " by " << build::USER; LOG(INFO) << "Version: " << MESOS_VERSION; if (build::GIT_TAG.isSome()) { LOG(INFO) << "Git tag: " << build::GIT_TAG.get(); } if (build::GIT_SHA.isSome()) { LOG(INFO) << "Git SHA: " << build::GIT_SHA.get(); } const string id = process::ID::generate("slave"); // Process ID. // If `process::initialize()` returns `false`, then it was called before this // invocation, meaning the authentication realm for libprocess-level HTTP // endpoints was set incorrectly. This should be the first invocation. if (!process::initialize( id, READWRITE_HTTP_AUTHENTICATION_REALM, READONLY_HTTP_AUTHENTICATION_REALM)) { EXIT(EXIT_FAILURE) << "The call to `process::initialize()` in the agent's " << "`main()` was not the function's first invocation"; } logging::initialize(argv[0], flags, true); // Catch signals. // Log any flag warnings (after logging is initialized). foreach (const flags::Warning& warning, load->warnings) { LOG(WARNING) << warning.message; } spawn(new VersionProcess(), true); if (flags.firewall_rules.isSome()) { vector<Owned<FirewallRule>> rules; const Firewall firewall = flags.firewall_rules.get(); if (firewall.has_disabled_endpoints()) { hashset<string> paths; foreach (const string& path, firewall.disabled_endpoints().paths()) { paths.insert(path); } rules.emplace_back(new DisabledEndpointsFirewallRule(paths)); } process::firewall::install(move(rules)); } // Initialize modules. if (flags.modules.isSome() && flags.modulesDir.isSome()) { EXIT(EXIT_FAILURE) << flags.usage("Only one of --modules or --modules_dir should be specified"); } if (flags.modulesDir.isSome()) { Try<Nothing> result = ModuleManager::load(flags.modulesDir.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error(); } } if (flags.modules.isSome()) { Try<Nothing> result = ModuleManager::load(flags.modules.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error(); } } // Create anonymous modules. foreach (const string& name, ModuleManager::find<Anonymous>()) { Try<Anonymous*> create = ModuleManager::create<Anonymous>(name); if (create.isError()) { EXIT(EXIT_FAILURE) << "Failed to create anonymous module named '" << name << "'"; } // We don't bother keeping around the pointer to this anonymous // module, when we exit that will effectively free its memory. // // TODO(benh): We might want to add explicit finalization (and // maybe explicit initialization too) in order to let the module // do any housekeeping necessary when the slave is cleanly // terminating. } // Initialize hooks. if (flags.hooks.isSome()) { Try<Nothing> result = HookManager::initialize(flags.hooks.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error installing hooks: " << result.error(); } } #ifdef __linux__ // Initialize systemd if it exists. if (flags.systemd_enable_support && systemd::exists()) { LOG(INFO) << "Inializing systemd state"; systemd::Flags systemdFlags; systemdFlags.enabled = flags.systemd_enable_support; systemdFlags.runtime_directory = flags.systemd_runtime_directory; systemdFlags.cgroups_hierarchy = flags.cgroups_hierarchy; Try<Nothing> initialize = systemd::initialize(systemdFlags); if (initialize.isError()) { EXIT(EXIT_FAILURE) << "Failed to initialize systemd: " + initialize.error(); } } #endif // __linux__ Fetcher* fetcher = new Fetcher(); Try<Containerizer*> containerizer = Containerizer::create(flags, false, fetcher); if (containerizer.isError()) { EXIT(EXIT_FAILURE) << "Failed to create a containerizer: " << containerizer.error(); } Try<MasterDetector*> detector_ = MasterDetector::create( flags.master, flags.master_detector); if (detector_.isError()) { EXIT(EXIT_FAILURE) << "Failed to create a master detector: " << detector_.error(); } MasterDetector* detector = detector_.get(); Option<Authorizer*> authorizer_ = None(); string authorizerName = flags.authorizer; Result<Authorizer*> authorizer((None())); if (authorizerName != slave::DEFAULT_AUTHORIZER) { LOG(INFO) << "Creating '" << authorizerName << "' authorizer"; // NOTE: The contents of --acls will be ignored. authorizer = Authorizer::create(authorizerName); } else { // `authorizerName` is `DEFAULT_AUTHORIZER` at this point. if (flags.acls.isSome()) { LOG(INFO) << "Creating default '" << authorizerName << "' authorizer"; authorizer = Authorizer::create(flags.acls.get()); } } if (authorizer.isError()) { EXIT(EXIT_FAILURE) << "Could not create '" << authorizerName << "' authorizer: " << authorizer.error(); } else if (authorizer.isSome()) { authorizer_ = authorizer.get(); // Set the authorization callbacks for libprocess HTTP endpoints. // Note that these callbacks capture `authorizer_.get()`, but the agent // creates a copy of the authorizer during construction. Thus, if in the // future it becomes possible to dynamically set the authorizer, this would // break. process::http::authorization::setCallbacks( createAuthorizationCallbacks(authorizer_.get())); } Files* files = new Files(READONLY_HTTP_AUTHENTICATION_REALM, authorizer_); GarbageCollector* gc = new GarbageCollector(); StatusUpdateManager* statusUpdateManager = new StatusUpdateManager(flags); Try<ResourceEstimator*> resourceEstimator = ResourceEstimator::create(flags.resource_estimator); if (resourceEstimator.isError()) { cerr << "Failed to create resource estimator: " << resourceEstimator.error() << endl; return EXIT_FAILURE; } Try<QoSController*> qosController = QoSController::create(flags.qos_controller); if (qosController.isError()) { cerr << "Failed to create QoS Controller: " << qosController.error() << endl; return EXIT_FAILURE; } Slave* slave = new Slave( id, flags, detector, containerizer.get(), files, gc, statusUpdateManager, resourceEstimator.get(), qosController.get(), authorizer_); process::spawn(slave); process::wait(slave->self()); delete slave; delete qosController.get(); delete resourceEstimator.get(); delete statusUpdateManager; delete gc; delete files; if (authorizer_.isSome()) { delete authorizer_.get(); } delete detector; delete containerizer.get(); delete fetcher; // NOTE: We need to finalize libprocess, on Windows especially, // as any binary that uses the networking stack on Windows must // also clean up the networking stack before exiting. process::finalize(true); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2017 Nathan Osman * * 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 <qmdnsengine/bitmap.h> #include "bitmap_p.h" using namespace QMdnsEngine; BitmapPrivate::BitmapPrivate() : length(0), data(nullptr) { } BitmapPrivate::~BitmapPrivate() { free(); } void BitmapPrivate::free() { if (data) { delete data; } } void BitmapPrivate::fromData(quint8 newLength, const quint8 *newData) { for (int i = 0; i < newLength; ++i) { data[i] = newData[i]; } length = newLength; } Bitmap::Bitmap() : d(new BitmapPrivate) { } Bitmap::Bitmap(const Bitmap &other) : d(new BitmapPrivate) { d->fromData(other.d->length, other.d->data); } Bitmap &Bitmap::operator=(const Bitmap &other) { d->free(); d->fromData(other.d->length, other.d->data); return *this; } bool Bitmap::operator==(const Bitmap &other) { if (d->length != other.d->length) { return false; } for (int i = 0; i < d->length; ++i) { if (d->data[i] != other.d->data[i]) { return false; } } return true; } Bitmap::~Bitmap() { delete d; } quint8 Bitmap::length() const { return d->length; } const quint8 *Bitmap::data() const { return d->data; } void Bitmap::setData(quint8 length, const quint8 *data) { d->free(); d->fromData(length, data); } <commit_msg>Add missing memory allocation.<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2017 Nathan Osman * * 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 <qmdnsengine/bitmap.h> #include "bitmap_p.h" using namespace QMdnsEngine; BitmapPrivate::BitmapPrivate() : length(0), data(nullptr) { } BitmapPrivate::~BitmapPrivate() { free(); } void BitmapPrivate::free() { if (data) { delete data; } } void BitmapPrivate::fromData(quint8 newLength, const quint8 *newData) { data = new quint8[newLength]; for (int i = 0; i < newLength; ++i) { data[i] = newData[i]; } length = newLength; } Bitmap::Bitmap() : d(new BitmapPrivate) { } Bitmap::Bitmap(const Bitmap &other) : d(new BitmapPrivate) { d->fromData(other.d->length, other.d->data); } Bitmap &Bitmap::operator=(const Bitmap &other) { d->free(); d->fromData(other.d->length, other.d->data); return *this; } bool Bitmap::operator==(const Bitmap &other) { if (d->length != other.d->length) { return false; } for (int i = 0; i < d->length; ++i) { if (d->data[i] != other.d->data[i]) { return false; } } return true; } Bitmap::~Bitmap() { delete d; } quint8 Bitmap::length() const { return d->length; } const quint8 *Bitmap::data() const { return d->data; } void Bitmap::setData(quint8 length, const quint8 *data) { d->free(); d->fromData(length, data); } <|endoftext|>
<commit_before>#include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <iterator> #include <utility> #include <set> #include <stack> #include "../gogui/gogui_core/include/gogui.hpp" using namespace gogui; using std::set; using std::swap; using std::pair; using std::sort; using std::lower_bound; /* polygon */ void load_dataset(vector<Line>& lines, vector<Point>& points, const char* filename) { FILE* file = fopen(filename, "rb"); if(file != NULL) { bool first = true; double x, y, prev_x, prev_y, first_x, first_y; while(fscanf(file, "%lf %lf", &x, &y) == 2) { if(!first) { Point curr(x, y); Point prev(prev_x, prev_y); lines.push_back(Line(prev, curr)); points.push_back(curr); } else { first = false; first_x = x; first_y = y; points.push_back(Point(first_x, first_y)); } prev_x = x; prev_y = y; } if(!first) { Point curr(x, y); Point fp(first_x, first_y); lines.push_back(Line(curr, fp)); } fclose(file); } } int n; // nr of points unsigned int min = 0; unsigned int max = 0; typedef struct { double x, y; bool in_first_branch = false; } point_t; std::vector<point_t> list; // min && max belong to both bool is_y_monotone(vector<Line>& lines) { n = lines.size(); for (int i = 1; i < n; i++) { if(lines[i].point1.y < lines[min].point1.y) min = i; if(lines[i].point1.y > lines[max].point1.y) max = i; } for (int i = 0; i < n; i++) { point_t point; point.x = lines[i].point1.x; point.y = lines[i].point1.y; list.push_back(point); } assert(n > 0); //printf("%lf %lf\n", lines[min].point1.y, lines[max].point1.y); unsigned int prev = min; bool correct = true; bool up = true; for(unsigned int i = min+1; i != min; i = (i+1) % n) { if((up && (lines[i].point1.y < lines[prev].point1.y)) || (!up && (lines[i].point1.y > lines[prev].point1.y))) correct = false; if(up) list[i].in_first_branch = true; if(i == max) up = false; //printf("%lf %lf\n", lines[prev].point1.y, lines[i].point1.y); prev = i; } return correct; } bool comparator(point_t a, point_t b) { return (a.y > b.y); } double angle (point_t p, point_t q, point_t r) { // angle in < pqr (q) double dotprod = (r.x - q.x)*(p.x - q.x) + (r.y - q.y)*(p.y - q.y); double len1squared = (p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y); double len2squared = (r.x - q.x) * (r.x - q.x) + (r.y - q.y) * (r.y - q.y); return acos(dotprod/sqrt(len1squared*len2squared)); } void setPoint(vector<Point>& points, point_t& p, GeoObject::Status status) { for(unsigned int i = 0; i < points.size(); i++) { if((points[i].x == p.x) && (points[i].y == p.y)) { points[i].setStatus(status); return; } } } bool neq(point_t a, point_t b) { return !((a.x == b.x) && (a.y == b.y)); } double ccw(point_t p1, point_t p2, point_t p3) { return (p1.x - p3.x)*(p2.y - p3.y) - (p1.y - p3.y)*(p2.x - p3.x); } void triangulate(vector<Line>& lines, vector<Point>& points) { point_t min_p = list[min]; point_t max_p = list[max]; sort(list.begin(), list.end(), comparator); /*for (int i = 0; i < n; i++) { printf("%lf %lf %d\n", list[i].x, list[i].y, list[i].in_first_branch); }*/ std::stack<point_t> stack; point_t a = list.back(); list.pop_back(); stack.push(a); point_t b = list.back(); stack.push(b); list.pop_back(); setPoint(points, a, GeoObject::Status::Active); setPoint(points, b, GeoObject::Status::Active); snapshot(); while(!list.empty()) { point_t p = list.back(); list.pop_back(); point_t q = stack.top(); if((p.in_first_branch != q.in_first_branch)) { while(!stack.empty()) { point_t r = stack.top(); stack.pop(); setPoint(points, r, GeoObject::Status::Processed); snapshot(); lines.push_back(Line(Point(p.x, p.y), Point(r.x, r.y))); snapshot(); } } else { point_t mark = stack.top(); setPoint(points, mark, GeoObject::Status::Processed); snapshot(); stack.pop(); point_t r = stack.top(); while ((!p.in_first_branch && (ccw(p,q,r) > 0)) || (p.in_first_branch && (ccw(p,q,r) < 0))) { lines.push_back(Line(Point(p.x, p.y), Point(r.x, r.y))); snapshot(); q = r; point_t mark = stack.top(); setPoint(points, mark, GeoObject::Status::Processed); snapshot(); stack.pop(); if(stack.empty()) break; r = stack.top(); } } stack.push(q); stack.push(p); setPoint(points, p, GeoObject::Status::Active); setPoint(points, q, GeoObject::Status::Active); snapshot(); } } int main(int argc, char* argv[]) { if(argc != 2) { printf("usage: %s [dataset] \n", argv[0]); exit(-1); } vector<Line> lines; vector<Point> points; load_dataset(lines, points, argv[1]); snapshot(); if(is_y_monotone(lines)) triangulate(lines, points); printJSON(); return 0; } <commit_msg>Removed unused variables<commit_after>#include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <iterator> #include <utility> #include <set> #include <stack> #include "../gogui/gogui_core/include/gogui.hpp" using namespace gogui; using std::set; using std::swap; using std::pair; using std::sort; using std::lower_bound; /* polygon */ void load_dataset(vector<Line>& lines, vector<Point>& points, const char* filename) { FILE* file = fopen(filename, "rb"); if(file != NULL) { bool first = true; double x, y, prev_x, prev_y, first_x, first_y; while(fscanf(file, "%lf %lf", &x, &y) == 2) { if(!first) { Point curr(x, y); Point prev(prev_x, prev_y); lines.push_back(Line(prev, curr)); points.push_back(curr); } else { first = false; first_x = x; first_y = y; points.push_back(Point(first_x, first_y)); } prev_x = x; prev_y = y; } if(!first) { Point curr(x, y); Point fp(first_x, first_y); lines.push_back(Line(curr, fp)); } fclose(file); } } int n; // nr of points unsigned int min = 0; unsigned int max = 0; typedef struct { double x, y; bool in_first_branch = false; } point_t; std::vector<point_t> list; // min && max belong to both bool is_y_monotone(vector<Line>& lines) { n = lines.size(); for (int i = 1; i < n; i++) { if(lines[i].point1.y < lines[min].point1.y) min = i; if(lines[i].point1.y > lines[max].point1.y) max = i; } for (int i = 0; i < n; i++) { point_t point; point.x = lines[i].point1.x; point.y = lines[i].point1.y; list.push_back(point); } assert(n > 0); //printf("%lf %lf\n", lines[min].point1.y, lines[max].point1.y); unsigned int prev = min; bool correct = true; bool up = true; for(unsigned int i = min+1; i != min; i = (i+1) % n) { if((up && (lines[i].point1.y < lines[prev].point1.y)) || (!up && (lines[i].point1.y > lines[prev].point1.y))) correct = false; if(up) list[i].in_first_branch = true; if(i == max) up = false; //printf("%lf %lf\n", lines[prev].point1.y, lines[i].point1.y); prev = i; } return correct; } bool comparator(point_t a, point_t b) { return (a.y > b.y); } double angle (point_t p, point_t q, point_t r) { // angle in < pqr (q) double dotprod = (r.x - q.x)*(p.x - q.x) + (r.y - q.y)*(p.y - q.y); double len1squared = (p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y); double len2squared = (r.x - q.x) * (r.x - q.x) + (r.y - q.y) * (r.y - q.y); return acos(dotprod/sqrt(len1squared*len2squared)); } void setPoint(vector<Point>& points, point_t& p, GeoObject::Status status) { for(unsigned int i = 0; i < points.size(); i++) { if((points[i].x == p.x) && (points[i].y == p.y)) { points[i].setStatus(status); return; } } } bool neq(point_t a, point_t b) { return !((a.x == b.x) && (a.y == b.y)); } double ccw(point_t p1, point_t p2, point_t p3) { return (p1.x - p3.x)*(p2.y - p3.y) - (p1.y - p3.y)*(p2.x - p3.x); } void triangulate(vector<Line>& lines, vector<Point>& points) { sort(list.begin(), list.end(), comparator); /*for (int i = 0; i < n; i++) { printf("%lf %lf %d\n", list[i].x, list[i].y, list[i].in_first_branch); }*/ std::stack<point_t> stack; point_t a = list.back(); list.pop_back(); stack.push(a); point_t b = list.back(); stack.push(b); list.pop_back(); setPoint(points, a, GeoObject::Status::Active); setPoint(points, b, GeoObject::Status::Active); snapshot(); while(!list.empty()) { point_t p = list.back(); list.pop_back(); point_t q = stack.top(); if((p.in_first_branch != q.in_first_branch)) { while(!stack.empty()) { point_t r = stack.top(); stack.pop(); setPoint(points, r, GeoObject::Status::Processed); snapshot(); lines.push_back(Line(Point(p.x, p.y), Point(r.x, r.y))); snapshot(); } } else { point_t mark = stack.top(); setPoint(points, mark, GeoObject::Status::Processed); snapshot(); stack.pop(); point_t r = stack.top(); while ((!p.in_first_branch && (ccw(p,q,r) > 0)) || (p.in_first_branch && (ccw(p,q,r) < 0))) { lines.push_back(Line(Point(p.x, p.y), Point(r.x, r.y))); snapshot(); q = r; point_t mark = stack.top(); setPoint(points, mark, GeoObject::Status::Processed); snapshot(); stack.pop(); if(stack.empty()) break; r = stack.top(); } } stack.push(q); stack.push(p); setPoint(points, p, GeoObject::Status::Active); setPoint(points, q, GeoObject::Status::Active); snapshot(); } } int main(int argc, char* argv[]) { if(argc != 2) { printf("usage: %s [dataset] \n", argv[0]); exit(-1); } vector<Line> lines; vector<Point> points; load_dataset(lines, points, argv[1]); snapshot(); if(is_y_monotone(lines)) triangulate(lines, points); printJSON(); return 0; } <|endoftext|>