text
stringlengths
54
60.6k
<commit_before>#ifndef __TEXTURE_HPP_INCLUDED #define __TEXTURE_HPP_INCLUDED #include "cpp/ylikuutio/common/globals.hpp" #include "shader.hpp" #include "render_templates.hpp" #include "cpp/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> // GLfloat, GLuint etc. #endif // Include standard headers #include <iostream> // std::cout, std::cin, std::cerr #include <queue> // std::queue #include <stdint.h> // uint32_t etc. #include <string> // std::string #include <vector> // std::vector namespace ontology { class Species; class Object; class VectorFont; class Material { public: // constructor. Material(MaterialStruct material_struct); // destructor. ~Material(); // this method sets pointer to this shader to nullptr, sets `parent_pointer` according to the input, and requests a new `childID` from the new shader. void bind_to_new_parent(ontology::Shader* new_shader_pointer); friend class Shader; friend class VectorFont; friend class Glyph; friend class Species; friend class Object; template<class T1> friend void render_children(std::vector<void*> &child_pointer_vector); template<class T1> friend void hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<T1> &child_pointer_vector, std::queue<uint32_t> &free_childID_queue); template<class T1, class T2> friend void hierarchy::bind_child_to_new_parent(T1 child_pointer, T2 new_parent_pointer, std::vector<T1> &old_child_pointer_vector, std::queue<uint32_t> &old_free_childID_queue); // this method renders all species using this texture. void render(); private: // this method sets `Species` pointer. void set_species_pointer(uint32_t childID, ontology::Species* child_pointer); // this method sets `VectorFont` pointer. void set_vector_font_pointer(uint32_t childID, ontology::VectorFont* child_pointer); // this method sets a world species pointer. void set_terrain_species_pointer(ontology::Species* terrain_species_pointer); ontology::Shader* parent_pointer; // pointer to the shader. void bind_to_parent(); ontology::Species* terrain_species_pointer; // pointer to world species (used in collision detection). GLuint texture; // Material, returned by `load_DDS_texture` or `load_BMP_texture`. GLuint openGL_textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`. std::vector<ontology::Species*> species_pointer_vector; std::vector<ontology::VectorFont*> vector_font_pointer_vector; std::queue<uint32_t> free_speciesID_queue; std::queue<uint32_t> free_vector_fontID_queue; std::string texture_file_format; // type of the model file, eg. `"bmp"`. std::string texture_filename; // filename of the model file. uint32_t childID; // texture ID, returned by `Shader::get_textureID`. const char* char_texture_file_format; const char* char_texture_filename; }; } #endif <commit_msg>`void Material::render()` is `private` again.<commit_after>#ifndef __TEXTURE_HPP_INCLUDED #define __TEXTURE_HPP_INCLUDED #include "cpp/ylikuutio/common/globals.hpp" #include "shader.hpp" #include "render_templates.hpp" #include "cpp/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> // GLfloat, GLuint etc. #endif // Include standard headers #include <iostream> // std::cout, std::cin, std::cerr #include <queue> // std::queue #include <stdint.h> // uint32_t etc. #include <string> // std::string #include <vector> // std::vector namespace ontology { class Species; class Object; class VectorFont; class Material { public: // constructor. Material(MaterialStruct material_struct); // destructor. ~Material(); // this method sets pointer to this shader to nullptr, sets `parent_pointer` according to the input, and requests a new `childID` from the new shader. void bind_to_new_parent(ontology::Shader* new_shader_pointer); friend class Shader; friend class VectorFont; friend class Glyph; friend class Species; friend class Object; template<class T1> friend void render_children(std::vector<T1> &child_pointer_vector); template<class T1> friend void hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<T1> &child_pointer_vector, std::queue<uint32_t> &free_childID_queue); template<class T1, class T2> friend void hierarchy::bind_child_to_new_parent(T1 child_pointer, T2 new_parent_pointer, std::vector<T1> &old_child_pointer_vector, std::queue<uint32_t> &old_free_childID_queue); private: // this method renders all species using this texture. void render(); // this method sets `Species` pointer. void set_species_pointer(uint32_t childID, ontology::Species* child_pointer); // this method sets `VectorFont` pointer. void set_vector_font_pointer(uint32_t childID, ontology::VectorFont* child_pointer); // this method sets a world species pointer. void set_terrain_species_pointer(ontology::Species* terrain_species_pointer); ontology::Shader* parent_pointer; // pointer to the shader. void bind_to_parent(); ontology::Species* terrain_species_pointer; // pointer to world species (used in collision detection). GLuint texture; // Material, returned by `load_DDS_texture` or `load_BMP_texture`. GLuint openGL_textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`. std::vector<ontology::Species*> species_pointer_vector; std::vector<ontology::VectorFont*> vector_font_pointer_vector; std::queue<uint32_t> free_speciesID_queue; std::queue<uint32_t> free_vector_fontID_queue; std::string texture_file_format; // type of the model file, eg. `"bmp"`. std::string texture_filename; // filename of the model file. uint32_t childID; // texture ID, returned by `Shader::get_textureID`. const char* char_texture_file_format; const char* char_texture_filename; }; } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sstream> #include <OGRE/OgreSceneNode.h> #include <OGRE/OgreSceneManager.h> #include <tf/transform_listener.h> #include "rviz/default_plugin/markers/arrow_marker.h" #include "rviz/default_plugin/markers/line_list_marker.h" #include "rviz/default_plugin/markers/line_strip_marker.h" #include "rviz/default_plugin/markers/mesh_resource_marker.h" #include "rviz/default_plugin/markers/points_marker.h" #include "rviz/default_plugin/markers/shape_marker.h" #include "rviz/default_plugin/markers/text_view_facing_marker.h" #include "rviz/default_plugin/markers/triangle_list_marker.h" #include "rviz/display_context.h" #include "rviz/frame_manager.h" #include "rviz/ogre_helpers/arrow.h" #include "rviz/ogre_helpers/billboard_line.h" #include "rviz/ogre_helpers/shape.h" #include "rviz/properties/int_property.h" #include "rviz/properties/property.h" #include "rviz/properties/ros_topic_property.h" #include "rviz/selection/selection_manager.h" #include "rviz/validate_floats.h" #include "rviz/default_plugin/marker_display.h" namespace rviz { //////////////////////////////////////////////////////////////////////////////////////////////////////////////// MarkerDisplay::MarkerDisplay() : Display() { marker_topic_property_ = new RosTopicProperty( "Marker Topic", "visualization_marker", QString::fromStdString( ros::message_traits::datatype<visualization_msgs::Marker>() ), "visualization_msgs::Marker topic to subscribe to. <topic>_array will also" " automatically be subscribed with type visualization_msgs::MarkerArray.", this, SLOT( updateTopic() )); queue_size_property_ = new IntProperty( "Queue Size", 100, "Advanced: set the size of the incoming Marker message queue. Increasing this is" " useful if your incoming TF data is delayed significantly from your Marker data, " "but it can greatly increase memory usage if the messages are big.", this, SLOT( updateQueueSize() )); queue_size_property_->setMin( 0 ); namespaces_category_ = new Property( "Namespaces", QVariant(), "", this ); } void MarkerDisplay::onInitialize() { tf_filter_ = new tf::MessageFilter<visualization_msgs::Marker>( *context_->getTFClient(), fixed_frame_.toStdString(), queue_size_property_->getInt(), update_nh_ ); scene_node_ = scene_manager_->getRootSceneNode()->createChildSceneNode(); tf_filter_->connectInput(sub_); tf_filter_->registerCallback(boost::bind(&MarkerDisplay::incomingMarker, this, _1)); tf_filter_->registerFailureCallback(boost::bind(&MarkerDisplay::failedMarker, this, _1, _2)); } MarkerDisplay::~MarkerDisplay() { unsubscribe(); clearMarkers(); delete tf_filter_; } void MarkerDisplay::clearMarkers() { markers_.clear(); markers_with_expiration_.clear(); frame_locked_markers_.clear(); tf_filter_->clear(); namespaces_category_->removeAllChildren(); namespaces_.clear(); } void MarkerDisplay::onEnable() { subscribe(); scene_node_->setVisible( true ); } void MarkerDisplay::onDisable() { unsubscribe(); tf_filter_->clear(); clearMarkers(); scene_node_->setVisible( false ); } void MarkerDisplay::updateQueueSize() { tf_filter_->setQueueSize( (uint32_t) queue_size_property_->getInt() ); } void MarkerDisplay::updateTopic() { unsubscribe(); subscribe(); } void MarkerDisplay::subscribe() { if( !isEnabled() ) { return; } std::string marker_topic = marker_topic_property_->getTopicStd(); if( !marker_topic.empty() ) { array_sub_.shutdown(); sub_.unsubscribe(); try { sub_.subscribe( update_nh_, marker_topic, 1000 ); array_sub_ = update_nh_.subscribe( marker_topic + "_array", 1000, &MarkerDisplay::incomingMarkerArray, this ); setStatus( StatusProperty::Ok, "Topic", "OK" ); } catch( ros::Exception& e ) { setStatus( StatusProperty::Error, "Topic", QString("Error subscribing: ") + e.what() ); } } } void MarkerDisplay::unsubscribe() { sub_.unsubscribe(); array_sub_.shutdown(); } void MarkerDisplay::deleteMarker(MarkerID id) { deleteMarkerStatus( id ); M_IDToMarker::iterator it = markers_.find( id ); if( it != markers_.end() ) { markers_with_expiration_.erase(it->second); frame_locked_markers_.erase(it->second); markers_.erase(it); } } void MarkerDisplay::deleteMarkersInNamespace( const std::string& ns ) { std::vector<MarkerID> to_delete; // TODO: this is inefficient, should store every in-use id per namespace and lookup by that M_IDToMarker::iterator marker_it = markers_.begin(); M_IDToMarker::iterator marker_end = markers_.end(); for (; marker_it != marker_end; ++marker_it) { if (marker_it->first.first == ns) { to_delete.push_back(marker_it->first); } } { std::vector<MarkerID>::iterator it = to_delete.begin(); std::vector<MarkerID>::iterator end = to_delete.end(); for (; it != end; ++it) { deleteMarker(*it); } } } void MarkerDisplay::setMarkerStatus(MarkerID id, StatusLevel level, const std::string& text) { std::stringstream ss; ss << id.first << "/" << id.second; std::string marker_name = ss.str(); setStatusStd(level, marker_name, text); } void MarkerDisplay::deleteMarkerStatus(MarkerID id) { std::stringstream ss; ss << id.first << "/" << id.second; std::string marker_name = ss.str(); deleteStatusStd(marker_name); } void MarkerDisplay::incomingMarkerArray(const visualization_msgs::MarkerArray::ConstPtr& array) { std::vector<visualization_msgs::Marker>::const_iterator it = array->markers.begin(); std::vector<visualization_msgs::Marker>::const_iterator end = array->markers.end(); for (; it != end; ++it) { const visualization_msgs::Marker& marker = *it; tf_filter_->add(visualization_msgs::Marker::Ptr(new visualization_msgs::Marker(marker))); } } void MarkerDisplay::incomingMarker( const visualization_msgs::Marker::ConstPtr& marker ) { boost::mutex::scoped_lock lock(queue_mutex_); message_queue_.push_back(marker); } void MarkerDisplay::failedMarker(const visualization_msgs::Marker::ConstPtr& marker, tf::FilterFailureReason reason) { std::string error = context_->getFrameManager()->discoverFailureReason(marker->header.frame_id, marker->header.stamp, marker->__connection_header ? (*marker->__connection_header)["callerid"] : "unknown", reason); setMarkerStatus(MarkerID(marker->ns, marker->id), StatusProperty::Error, error); } bool validateFloats(const visualization_msgs::Marker& msg) { bool valid = true; valid = valid && validateFloats(msg.pose); valid = valid && validateFloats(msg.scale); valid = valid && validateFloats(msg.color); valid = valid && validateFloats(msg.points); return valid; } void MarkerDisplay::processMessage( const visualization_msgs::Marker::ConstPtr& message ) { if (!validateFloats(*message)) { setMarkerStatus(MarkerID(message->ns, message->id), StatusProperty::Error, "Contains invalid floating point values (nans or infs)"); return; } switch ( message->action ) { case visualization_msgs::Marker::ADD: processAdd( message ); break; case visualization_msgs::Marker::DELETE: processDelete( message ); break; default: ROS_ERROR( "Unknown marker action: %d\n", message->action ); } } void MarkerDisplay::processAdd( const visualization_msgs::Marker::ConstPtr& message ) { QString namespace_name = QString::fromStdString( message->ns ); M_Namespace::iterator ns_it = namespaces_.find( namespace_name ); if( ns_it == namespaces_.end() ) { ns_it = namespaces_.insert( namespace_name, new MarkerNamespace( namespace_name, namespaces_category_, this )); } if( !ns_it.value()->isEnabled() ) { return; } deleteMarkerStatus( MarkerID( message->ns, message->id )); bool create = true; MarkerBasePtr marker; M_IDToMarker::iterator it = markers_.find( MarkerID(message->ns, message->id) ); if ( it != markers_.end() ) { marker = it->second; markers_with_expiration_.erase(marker); if ( message->type == marker->getMessage()->type ) { create = false; } else { markers_.erase( it ); } } if ( create ) { switch ( message->type ) { case visualization_msgs::Marker::CUBE: case visualization_msgs::Marker::CYLINDER: case visualization_msgs::Marker::SPHERE: { marker.reset(new ShapeMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::ARROW: { marker.reset(new ArrowMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::LINE_STRIP: { marker.reset(new LineStripMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::LINE_LIST: { marker.reset(new LineListMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::SPHERE_LIST: case visualization_msgs::Marker::CUBE_LIST: case visualization_msgs::Marker::POINTS: { marker.reset(new PointsMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::TEXT_VIEW_FACING: { marker.reset(new TextViewFacingMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::MESH_RESOURCE: { marker.reset(new MeshResourceMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::TRIANGLE_LIST: { marker.reset(new TriangleListMarker(this, context_, scene_node_)); } break; default: ROS_ERROR( "Unknown marker type: %d", message->type ); } markers_.insert(std::make_pair(MarkerID(message->ns, message->id), marker)); } if (marker) { marker->setMessage(message); if (message->lifetime.toSec() > 0.0001f) { markers_with_expiration_.insert(marker); } if (message->frame_locked) { frame_locked_markers_.insert(marker); } context_->queueRender(); } } void MarkerDisplay::processDelete( const visualization_msgs::Marker::ConstPtr& message ) { deleteMarker(MarkerID(message->ns, message->id)); context_->queueRender(); } void MarkerDisplay::update(float wall_dt, float ros_dt) { V_MarkerMessage local_queue; { boost::mutex::scoped_lock lock(queue_mutex_); local_queue.swap( message_queue_ ); } if ( !local_queue.empty() ) { V_MarkerMessage::iterator message_it = local_queue.begin(); V_MarkerMessage::iterator message_end = local_queue.end(); for ( ; message_it != message_end; ++message_it ) { visualization_msgs::Marker::ConstPtr& marker = *message_it; processMessage( marker ); } } { S_MarkerBase::iterator it = markers_with_expiration_.begin(); S_MarkerBase::iterator end = markers_with_expiration_.end(); for (; it != end;) { MarkerBasePtr marker = *it; if (marker->expired()) { S_MarkerBase::iterator copy = it; ++it; deleteMarker(marker->getID()); } else { ++it; } } } { S_MarkerBase::iterator it = frame_locked_markers_.begin(); S_MarkerBase::iterator end = frame_locked_markers_.end(); for (; it != end; ++it) { MarkerBasePtr marker = *it; marker->updateFrameLocked(); } } } void MarkerDisplay::fixedFrameChanged() { tf_filter_->setTargetFrame( fixed_frame_.toStdString() ); clearMarkers(); } void MarkerDisplay::reset() { Display::reset(); clearMarkers(); } ///////////////////////////////////////////////////////////////////////////////// // MarkerNamespace MarkerNamespace::MarkerNamespace( const QString& name, Property* parent_property, MarkerDisplay* owner ) : BoolProperty( name, true, "Enable/disable all markers in this namespace.", parent_property, SLOT( onEnableChanged() ), this ) , owner_( owner ) {} void MarkerNamespace::onEnableChanged() { if( !isEnabled() ) { owner_->deleteMarkersInNamespace( getName().toStdString() ); } } } // namespace rviz #include <pluginlib/class_list_macros.h> PLUGINLIB_DECLARE_CLASS( rviz, Marker, rviz::MarkerDisplay, rviz::Display ) <commit_msg>rviz trunk: fixed bug in marker namespace enable/disable handler.<commit_after>/* * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sstream> #include <OGRE/OgreSceneNode.h> #include <OGRE/OgreSceneManager.h> #include <tf/transform_listener.h> #include "rviz/default_plugin/markers/arrow_marker.h" #include "rviz/default_plugin/markers/line_list_marker.h" #include "rviz/default_plugin/markers/line_strip_marker.h" #include "rviz/default_plugin/markers/mesh_resource_marker.h" #include "rviz/default_plugin/markers/points_marker.h" #include "rviz/default_plugin/markers/shape_marker.h" #include "rviz/default_plugin/markers/text_view_facing_marker.h" #include "rviz/default_plugin/markers/triangle_list_marker.h" #include "rviz/display_context.h" #include "rviz/frame_manager.h" #include "rviz/ogre_helpers/arrow.h" #include "rviz/ogre_helpers/billboard_line.h" #include "rviz/ogre_helpers/shape.h" #include "rviz/properties/int_property.h" #include "rviz/properties/property.h" #include "rviz/properties/ros_topic_property.h" #include "rviz/selection/selection_manager.h" #include "rviz/validate_floats.h" #include "rviz/default_plugin/marker_display.h" namespace rviz { //////////////////////////////////////////////////////////////////////////////////////////////////////////////// MarkerDisplay::MarkerDisplay() : Display() { marker_topic_property_ = new RosTopicProperty( "Marker Topic", "visualization_marker", QString::fromStdString( ros::message_traits::datatype<visualization_msgs::Marker>() ), "visualization_msgs::Marker topic to subscribe to. <topic>_array will also" " automatically be subscribed with type visualization_msgs::MarkerArray.", this, SLOT( updateTopic() )); queue_size_property_ = new IntProperty( "Queue Size", 100, "Advanced: set the size of the incoming Marker message queue. Increasing this is" " useful if your incoming TF data is delayed significantly from your Marker data, " "but it can greatly increase memory usage if the messages are big.", this, SLOT( updateQueueSize() )); queue_size_property_->setMin( 0 ); namespaces_category_ = new Property( "Namespaces", QVariant(), "", this ); } void MarkerDisplay::onInitialize() { tf_filter_ = new tf::MessageFilter<visualization_msgs::Marker>( *context_->getTFClient(), fixed_frame_.toStdString(), queue_size_property_->getInt(), update_nh_ ); scene_node_ = scene_manager_->getRootSceneNode()->createChildSceneNode(); tf_filter_->connectInput(sub_); tf_filter_->registerCallback(boost::bind(&MarkerDisplay::incomingMarker, this, _1)); tf_filter_->registerFailureCallback(boost::bind(&MarkerDisplay::failedMarker, this, _1, _2)); } MarkerDisplay::~MarkerDisplay() { unsubscribe(); clearMarkers(); delete tf_filter_; } void MarkerDisplay::clearMarkers() { markers_.clear(); markers_with_expiration_.clear(); frame_locked_markers_.clear(); tf_filter_->clear(); namespaces_category_->removeAllChildren(); namespaces_.clear(); } void MarkerDisplay::onEnable() { subscribe(); scene_node_->setVisible( true ); } void MarkerDisplay::onDisable() { unsubscribe(); tf_filter_->clear(); clearMarkers(); scene_node_->setVisible( false ); } void MarkerDisplay::updateQueueSize() { tf_filter_->setQueueSize( (uint32_t) queue_size_property_->getInt() ); } void MarkerDisplay::updateTopic() { unsubscribe(); subscribe(); } void MarkerDisplay::subscribe() { if( !isEnabled() ) { return; } std::string marker_topic = marker_topic_property_->getTopicStd(); if( !marker_topic.empty() ) { array_sub_.shutdown(); sub_.unsubscribe(); try { sub_.subscribe( update_nh_, marker_topic, 1000 ); array_sub_ = update_nh_.subscribe( marker_topic + "_array", 1000, &MarkerDisplay::incomingMarkerArray, this ); setStatus( StatusProperty::Ok, "Topic", "OK" ); } catch( ros::Exception& e ) { setStatus( StatusProperty::Error, "Topic", QString("Error subscribing: ") + e.what() ); } } } void MarkerDisplay::unsubscribe() { sub_.unsubscribe(); array_sub_.shutdown(); } void MarkerDisplay::deleteMarker(MarkerID id) { deleteMarkerStatus( id ); M_IDToMarker::iterator it = markers_.find( id ); if( it != markers_.end() ) { markers_with_expiration_.erase(it->second); frame_locked_markers_.erase(it->second); markers_.erase(it); } } void MarkerDisplay::deleteMarkersInNamespace( const std::string& ns ) { std::vector<MarkerID> to_delete; // TODO: this is inefficient, should store every in-use id per namespace and lookup by that M_IDToMarker::iterator marker_it = markers_.begin(); M_IDToMarker::iterator marker_end = markers_.end(); for (; marker_it != marker_end; ++marker_it) { if (marker_it->first.first == ns) { to_delete.push_back(marker_it->first); } } { std::vector<MarkerID>::iterator it = to_delete.begin(); std::vector<MarkerID>::iterator end = to_delete.end(); for (; it != end; ++it) { deleteMarker(*it); } } } void MarkerDisplay::setMarkerStatus(MarkerID id, StatusLevel level, const std::string& text) { std::stringstream ss; ss << id.first << "/" << id.second; std::string marker_name = ss.str(); setStatusStd(level, marker_name, text); } void MarkerDisplay::deleteMarkerStatus(MarkerID id) { std::stringstream ss; ss << id.first << "/" << id.second; std::string marker_name = ss.str(); deleteStatusStd(marker_name); } void MarkerDisplay::incomingMarkerArray(const visualization_msgs::MarkerArray::ConstPtr& array) { std::vector<visualization_msgs::Marker>::const_iterator it = array->markers.begin(); std::vector<visualization_msgs::Marker>::const_iterator end = array->markers.end(); for (; it != end; ++it) { const visualization_msgs::Marker& marker = *it; tf_filter_->add(visualization_msgs::Marker::Ptr(new visualization_msgs::Marker(marker))); } } void MarkerDisplay::incomingMarker( const visualization_msgs::Marker::ConstPtr& marker ) { boost::mutex::scoped_lock lock(queue_mutex_); message_queue_.push_back(marker); } void MarkerDisplay::failedMarker(const visualization_msgs::Marker::ConstPtr& marker, tf::FilterFailureReason reason) { std::string error = context_->getFrameManager()->discoverFailureReason(marker->header.frame_id, marker->header.stamp, marker->__connection_header ? (*marker->__connection_header)["callerid"] : "unknown", reason); setMarkerStatus(MarkerID(marker->ns, marker->id), StatusProperty::Error, error); } bool validateFloats(const visualization_msgs::Marker& msg) { bool valid = true; valid = valid && validateFloats(msg.pose); valid = valid && validateFloats(msg.scale); valid = valid && validateFloats(msg.color); valid = valid && validateFloats(msg.points); return valid; } void MarkerDisplay::processMessage( const visualization_msgs::Marker::ConstPtr& message ) { if (!validateFloats(*message)) { setMarkerStatus(MarkerID(message->ns, message->id), StatusProperty::Error, "Contains invalid floating point values (nans or infs)"); return; } switch ( message->action ) { case visualization_msgs::Marker::ADD: processAdd( message ); break; case visualization_msgs::Marker::DELETE: processDelete( message ); break; default: ROS_ERROR( "Unknown marker action: %d\n", message->action ); } } void MarkerDisplay::processAdd( const visualization_msgs::Marker::ConstPtr& message ) { QString namespace_name = QString::fromStdString( message->ns ); M_Namespace::iterator ns_it = namespaces_.find( namespace_name ); if( ns_it == namespaces_.end() ) { ns_it = namespaces_.insert( namespace_name, new MarkerNamespace( namespace_name, namespaces_category_, this )); } if( !ns_it.value()->isEnabled() ) { return; } deleteMarkerStatus( MarkerID( message->ns, message->id )); bool create = true; MarkerBasePtr marker; M_IDToMarker::iterator it = markers_.find( MarkerID(message->ns, message->id) ); if ( it != markers_.end() ) { marker = it->second; markers_with_expiration_.erase(marker); if ( message->type == marker->getMessage()->type ) { create = false; } else { markers_.erase( it ); } } if ( create ) { switch ( message->type ) { case visualization_msgs::Marker::CUBE: case visualization_msgs::Marker::CYLINDER: case visualization_msgs::Marker::SPHERE: { marker.reset(new ShapeMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::ARROW: { marker.reset(new ArrowMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::LINE_STRIP: { marker.reset(new LineStripMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::LINE_LIST: { marker.reset(new LineListMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::SPHERE_LIST: case visualization_msgs::Marker::CUBE_LIST: case visualization_msgs::Marker::POINTS: { marker.reset(new PointsMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::TEXT_VIEW_FACING: { marker.reset(new TextViewFacingMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::MESH_RESOURCE: { marker.reset(new MeshResourceMarker(this, context_, scene_node_)); } break; case visualization_msgs::Marker::TRIANGLE_LIST: { marker.reset(new TriangleListMarker(this, context_, scene_node_)); } break; default: ROS_ERROR( "Unknown marker type: %d", message->type ); } markers_.insert(std::make_pair(MarkerID(message->ns, message->id), marker)); } if (marker) { marker->setMessage(message); if (message->lifetime.toSec() > 0.0001f) { markers_with_expiration_.insert(marker); } if (message->frame_locked) { frame_locked_markers_.insert(marker); } context_->queueRender(); } } void MarkerDisplay::processDelete( const visualization_msgs::Marker::ConstPtr& message ) { deleteMarker(MarkerID(message->ns, message->id)); context_->queueRender(); } void MarkerDisplay::update(float wall_dt, float ros_dt) { V_MarkerMessage local_queue; { boost::mutex::scoped_lock lock(queue_mutex_); local_queue.swap( message_queue_ ); } if ( !local_queue.empty() ) { V_MarkerMessage::iterator message_it = local_queue.begin(); V_MarkerMessage::iterator message_end = local_queue.end(); for ( ; message_it != message_end; ++message_it ) { visualization_msgs::Marker::ConstPtr& marker = *message_it; processMessage( marker ); } } { S_MarkerBase::iterator it = markers_with_expiration_.begin(); S_MarkerBase::iterator end = markers_with_expiration_.end(); for (; it != end;) { MarkerBasePtr marker = *it; if (marker->expired()) { S_MarkerBase::iterator copy = it; ++it; deleteMarker(marker->getID()); } else { ++it; } } } { S_MarkerBase::iterator it = frame_locked_markers_.begin(); S_MarkerBase::iterator end = frame_locked_markers_.end(); for (; it != end; ++it) { MarkerBasePtr marker = *it; marker->updateFrameLocked(); } } } void MarkerDisplay::fixedFrameChanged() { tf_filter_->setTargetFrame( fixed_frame_.toStdString() ); clearMarkers(); } void MarkerDisplay::reset() { Display::reset(); clearMarkers(); } ///////////////////////////////////////////////////////////////////////////////// // MarkerNamespace MarkerNamespace::MarkerNamespace( const QString& name, Property* parent_property, MarkerDisplay* owner ) : BoolProperty( name, true, "Enable/disable all markers in this namespace.", parent_property ) , owner_( owner ) { // Can't do this connect in chained constructor above because at // that point it doesn't really know that "this" is a // MarkerNamespace*, so the signal doesn't get connected. connect( this, SIGNAL( changed() ), this, SLOT( onEnableChanged() )); } void MarkerNamespace::onEnableChanged() { if( !isEnabled() ) { owner_->deleteMarkersInNamespace( getName().toStdString() ); } } } // namespace rviz #include <pluginlib/class_list_macros.h> PLUGINLIB_DECLARE_CLASS( rviz, Marker, rviz::MarkerDisplay, rviz::Display ) <|endoftext|>
<commit_before>#include "HEALTH.H" #include "DELTAPAK.H" #include "DRAW.H" #include "DRAWPHAS.H" #include "GAMEFLOW.H" #include "LARA.H" #include "NEWINV2.H" #include "OBJECTS.H" #include "SPECIFIC.H" #include "SPOTCAM.H" #include <stdio.h> int health_bar_timer = 0; char PoisonFlag = 0; struct DISPLAYPU pickups[8]; short PickupX = 0; short PickupY = 0; short PickupVel = 0; short CurrentPickup = 0; void AddDisplayPickup(short object_number)//3B6F4, ? (F) { struct DISPLAYPU* pu = &pickups[0]; long lp; if (gfCurrentLevel == LVL5_SUBMARINE && object_number == PUZZLE_ITEM1 || gfCurrentLevel == LVL5_OLD_MILL && object_number == PUZZLE_ITEM3) { object_number = CROWBAR_ITEM; } for(lp = 0; lp < 8; lp++, pu++) { if (pu->life < 0) { pu->life = 45; pu->object_number = object_number; break; } } DEL_picked_up_object(object_number); } void DrawPickups(int timed)// (F) { struct DISPLAYPU* pu = &pickups[CurrentPickup]; long lp; if (pu->life > 0) { if (PickupX > 0) { PickupX += (-PickupX >> 3); } else { pu->life--; } } else if (pu->life == 0) { if (PickupX < 128) { if (PickupVel < 16) PickupX += ++PickupVel; } else { pu->life = -1; PickupVel = 0; } } else { for (lp = 0; lp < 8; lp++) { if (pickups[(CurrentPickup + lp) % 8].life > 0) break; } if (lp == 8) { CurrentPickup = 0; return; } CurrentPickup = (CurrentPickup + lp) % 8; } S_DrawPickup(pu->object_number); } void InitialisePickUpDisplay()//3B580, 3B9DC (F) { int i; for (i = 7; i > -1; i--) { pickups[i].life = -1; } PickupY = 128; PickupX = 128; PickupVel = 0; CurrentPickup = 0; } void DrawAirBar(int flash_state) { S_Warn("[DrawAirBar] - Unimplemented!\n"); } void DrawHealthBar(int flash_state) { S_Warn("[DrawHealthBar] - Unimplemented!\n"); } void DrawGameInfo(int timed)//3AD68(<), 3B268(!) { #if PC_VERSION if (GLOBAL_playing_cutseq == 0 && !bDisableLaraControl && gfGameMode != 1) { int flash_state = FlashIt(); DrawHealthBar(flash_state); DrawAirBar(flash_state); DrawPickups(timed); /*if (DashTimer < 120) s_drawdas*/ } #else // line 2, offset 0x3ad68 int flash_state; // $s0 //{ // line 17, offset 0x3adac char sbuf[80]; // stack offset -192 //} // line 19, offset 0x3adac { // line 53, offset 0x3af50 char buf[80]; // stack offset -112 int seconds; // $s3 } // line 77, offset 0x3b0a0 if (GLOBAL_playing_cutseq != 0 || bDisableLaraControl != 0) { return; } sprintf(sbuf, "Room:%d X:%d Y:%d Z:%d", lara_item->room_number, (lara_item->pos.x_pos - room[lara_item->room_number].x) / SECTOR(1), (lara_item->pos.y_pos - room[lara_item->room_number].minfloor) / CLICK, (lara_item->pos.z_pos - room[lara_item->room_number].z) / SECTOR(1)); PrintString(256, 24, 0, sbuf, 0); //^Not verified for retail/internal split if (gfGameMode == 1) { //loc_3B0A0 return; } flash_state = FlashIt(); DrawHealthBar(flash_state); DrawAirBar(flash_state); DrawPickups(timed);//Arg does not seem right imo if (DashTimer < 120) { //TODO }//loc_3AF14 return; #endif } // line 79, offset 0x3b0a0 int FlashIt()//3AD2C, 3B22C { static int flash_state; static int flash_count; if (--flash_count != 0) { flash_count = 5; flash_state ^= 1; } return flash_state; } void AddDisplayPickup(short object_number)//3B6F4(<), 3BB50(<) (F) { struct DISPLAYPU* pu = &pickups[0]; long lp = 0; if (gfCurrentLevel == LVL5_SUBMARINE && object_number == PUZZLE_ITEM1) { object_number = CROWBAR_ITEM; } if (gfCurrentLevel == LVL5_OLD_MILL && object_number == PUZZLE_ITEM3) { object_number = CROWBAR_ITEM; } if (pu->life < 0) { pu->life = 45; pu->object_number = object_number; } else { //loc_3B764 lp++; //loc_3B768 do { if (lp > 7) { DEL_picked_up_object(object_number); return; } } while (++pu->life >= 0, lp++); pu->life = 45; pu->object_number = object_number; } //loc_3B790 DEL_picked_up_object(object_number); return; }<commit_msg>Revert "Add AddDisplayPickup()"<commit_after>#include "HEALTH.H" #include "DELTAPAK.H" #include "DRAW.H" #include "DRAWPHAS.H" #include "GAMEFLOW.H" #include "LARA.H" #include "SPOTCAM.H" #include <stdio.h> #include "SPECIFIC.H" #include "OBJECTS.H" #include "NEWINV2.H" int health_bar_timer = 0; char PoisonFlag = 0; struct DISPLAYPU pickups[8]; short PickupX = 0; short PickupY = 0; short PickupVel = 0; short CurrentPickup = 0; void AddDisplayPickup(short object_number)//3B6F4, ? (F) { struct DISPLAYPU* pu = &pickups[0]; long lp; if (gfCurrentLevel == LVL5_SUBMARINE && object_number == PUZZLE_ITEM1 || gfCurrentLevel == LVL5_OLD_MILL && object_number == PUZZLE_ITEM3) { object_number = CROWBAR_ITEM; } for(lp = 0; lp < 8; lp++, pu++) { if (pu->life < 0) { pu->life = 45; pu->object_number = object_number; break; } } DEL_picked_up_object(object_number); } void DrawPickups(int timed)// (F) { struct DISPLAYPU* pu = &pickups[CurrentPickup]; long lp; if (pu->life > 0) { if (PickupX > 0) { PickupX += (-PickupX >> 3); } else { pu->life--; } } else if (pu->life == 0) { if (PickupX < 128) { if (PickupVel < 16) PickupX += ++PickupVel; } else { pu->life = -1; PickupVel = 0; } } else { for (lp = 0; lp < 8; lp++) { if (pickups[(CurrentPickup + lp) % 8].life > 0) break; } if (lp == 8) { CurrentPickup = 0; return; } CurrentPickup = (CurrentPickup + lp) % 8; } S_DrawPickup(pu->object_number); } void InitialisePickUpDisplay()//3B580, 3B9DC (F) { int i; for (i = 7; i > -1; i--) { pickups[i].life = -1; } PickupY = 128; PickupX = 128; PickupVel = 0; CurrentPickup = 0; } void DrawAirBar(int flash_state) { S_Warn("[DrawAirBar] - Unimplemented!\n"); } void DrawHealthBar(int flash_state) { S_Warn("[DrawHealthBar] - Unimplemented!\n"); } void DrawGameInfo(int timed)//3AD68(<), 3B268(!) { #if PC_VERSION if (GLOBAL_playing_cutseq == 0 && !bDisableLaraControl && gfGameMode != 1) { int flash_state = FlashIt(); DrawHealthBar(flash_state); DrawAirBar(flash_state); DrawPickups(timed); /*if (DashTimer < 120) s_drawdas*/ } #else // line 2, offset 0x3ad68 int flash_state; // $s0 //{ // line 17, offset 0x3adac char sbuf[80]; // stack offset -192 //} // line 19, offset 0x3adac { // line 53, offset 0x3af50 char buf[80]; // stack offset -112 int seconds; // $s3 } // line 77, offset 0x3b0a0 if (GLOBAL_playing_cutseq != 0 || bDisableLaraControl != 0) { return; } sprintf(sbuf, "Room:%d X:%d Y:%d Z:%d", lara_item->room_number, (lara_item->pos.x_pos - room[lara_item->room_number].x) / SECTOR(1), (lara_item->pos.y_pos - room[lara_item->room_number].minfloor) / CLICK, (lara_item->pos.z_pos - room[lara_item->room_number].z) / SECTOR(1)); PrintString(256, 24, 0, sbuf, 0); //^Not verified for retail/internal split if (gfGameMode == 1) { //loc_3B0A0 return; } flash_state = FlashIt(); DrawHealthBar(flash_state); DrawAirBar(flash_state); DrawPickups(timed);//Arg does not seem right imo if (DashTimer < 120) { //TODO }//loc_3AF14 return; #endif } // line 79, offset 0x3b0a0 int FlashIt()//3AD2C, 3B22C { static int flash_state; static int flash_count; if (--flash_count != 0) { flash_count = 5; flash_state ^= 1; } return flash_state; } <|endoftext|>
<commit_before>// Copyright 2014 BVLC and contributors. #include <vector> #include "cuda_runtime.h" #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/vision_layers.hpp" #include "caffe/test/test_gradient_check_util.hpp" #include "caffe/test/test_caffe_main.hpp" namespace caffe { extern cudaDeviceProp CAFFE_TEST_CUDA_PROP; template <typename Dtype> class ArgMaxLayerTest : public ::testing::Test { protected: ArgMaxLayerTest() : blob_bottom_(new Blob<Dtype>(20, 10, 1, 1)), blob_top_(new Blob<Dtype>()) { Caffe::set_random_seed(1701); // fill the values FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); blob_bottom_vec_.push_back(blob_bottom_); blob_top_vec_.push_back(blob_top_); } virtual ~ArgMaxLayerTest() { delete blob_bottom_; delete blob_top_; } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; }; typedef ::testing::Types<float, double> Dtypes; TYPED_TEST_CASE(ArgMaxLayerTest, Dtypes); TYPED_TEST(ArgMaxLayerTest, TestSetup) { LayerParameter layer_param; ThresholdLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_)); EXPECT_EQ(this->blob_top_->num(), this->bottom_top_->num()); EXPECT_EQ(this->blob_top_->channels(), 1); } TYPED_TEST(ArgMaxLayerTest, TestSetupMaxVal) { LayerParameter layer_param; ArgMaxLayerParameter* argmax_param = layer_param.mutable_argmax_param(); argmax_param->set_out_max_val(true); ThresholdLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_)); EXPECT_EQ(this->blob_top_->num(), this->bottom_top_->num()); EXPECT_EQ(this->blob_top_->channels(), 2); } TYPED_TEST(ArgMaxLayerTest, TestCPU) { LayerParameter layer_param; Caffe::set_mode(Caffe::CPU); ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_)); layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_)); // Now, check values const TypeParam* bottom_data = this->blob_bottom_->cpu_data(); const TypeParam* top_data = this->blob_top_->cpu_data(); int max_ind; TypeParam max_val; int num = this->blob_bottom_->num(); int dim = this->blob_bottom_->count() / num; for (int i = 0; i < num; ++i) { EXPECT_GE(top_data[i], 0); EXPECT_LE(top_data[i], dim); max_ind = top_data[i]; max_val = bottom_data[i * dim + max_ind]; for (int j = 0; j < dim; ++j) { EXPECT_LE(bottom_data[i * dim + j], max_val); } } } TYPED_TEST(ArgMaxLayerTest, TestCPUMaxVal) { LayerParameter layer_param; Caffe::set_mode(Caffe::CPU); ArgMaxLayerParameter* argmax_param = layer_param.mutable_argmax_param(); argmax_param->set_out_max_val(true); ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_)); layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_)); // Now, check values const TypeParam* bottom_data = this->blob_bottom_->cpu_data(); const TypeParam* top_data = this->blob_top_->cpu_data(); int max_ind; TypeParam max_val; int num = this->blob_bottom_->num(); int dim = this->blob_bottom_->count() / num; for (int i = 0; i < num; ++i) { EXPECT_GE(top_data[i], 0); EXPECT_LE(top_data[i], dim); max_ind = top_data[i * 2]; max_val = top_data[i * 2 + 1]; EXPECT_EQ(bottom_data[i * dim + max_ind],max_val); for (int j = 0; j < dim; ++j) { EXPECT_LE(bottom_data[i * dim + j], max_val); } } } } // namespace caffe <commit_msg>Fixed name of blob_bottom_<commit_after>// Copyright 2014 BVLC and contributors. #include <vector> #include "cuda_runtime.h" #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/vision_layers.hpp" #include "caffe/test/test_gradient_check_util.hpp" #include "caffe/test/test_caffe_main.hpp" namespace caffe { extern cudaDeviceProp CAFFE_TEST_CUDA_PROP; template <typename Dtype> class ArgMaxLayerTest : public ::testing::Test { protected: ArgMaxLayerTest() : blob_bottom_(new Blob<Dtype>(20, 10, 1, 1)), blob_top_(new Blob<Dtype>()) { Caffe::set_random_seed(1701); // fill the values FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); blob_bottom_vec_.push_back(blob_bottom_); blob_top_vec_.push_back(blob_top_); } virtual ~ArgMaxLayerTest() { delete blob_bottom_; delete blob_top_; } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; }; typedef ::testing::Types<float, double> Dtypes; TYPED_TEST_CASE(ArgMaxLayerTest, Dtypes); TYPED_TEST(ArgMaxLayerTest, TestSetup) { LayerParameter layer_param; ThresholdLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_)); EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num()); EXPECT_EQ(this->blob_top_->channels(), 1); } TYPED_TEST(ArgMaxLayerTest, TestSetupMaxVal) { LayerParameter layer_param; ArgMaxLayerParameter* argmax_param = layer_param.mutable_argmax_param(); argmax_param->set_out_max_val(true); ThresholdLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_)); EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num()); EXPECT_EQ(this->blob_top_->channels(), 2); } TYPED_TEST(ArgMaxLayerTest, TestCPU) { LayerParameter layer_param; Caffe::set_mode(Caffe::CPU); ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_)); layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_)); // Now, check values const TypeParam* bottom_data = this->blob_bottom_->cpu_data(); const TypeParam* top_data = this->blob_top_->cpu_data(); int max_ind; TypeParam max_val; int num = this->blob_bottom_->num(); int dim = this->blob_bottom_->count() / num; for (int i = 0; i < num; ++i) { EXPECT_GE(top_data[i], 0); EXPECT_LE(top_data[i], dim); max_ind = top_data[i]; max_val = bottom_data[i * dim + max_ind]; for (int j = 0; j < dim; ++j) { EXPECT_LE(bottom_data[i * dim + j], max_val); } } } TYPED_TEST(ArgMaxLayerTest, TestCPUMaxVal) { LayerParameter layer_param; Caffe::set_mode(Caffe::CPU); ArgMaxLayerParameter* argmax_param = layer_param.mutable_argmax_param(); argmax_param->set_out_max_val(true); ArgMaxLayer<TypeParam> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_)); layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_)); // Now, check values const TypeParam* bottom_data = this->blob_bottom_->cpu_data(); const TypeParam* top_data = this->blob_top_->cpu_data(); int max_ind; TypeParam max_val; int num = this->blob_bottom_->num(); int dim = this->blob_bottom_->count() / num; for (int i = 0; i < num; ++i) { EXPECT_GE(top_data[i], 0); EXPECT_LE(top_data[i], dim); max_ind = top_data[i * 2]; max_val = top_data[i * 2 + 1]; EXPECT_EQ(bottom_data[i * dim + max_ind],max_val); for (int j = 0; j < dim; ++j) { EXPECT_LE(bottom_data[i * dim + j], max_val); } } } } // namespace caffe <|endoftext|>
<commit_before>#ifndef VVVSTLHELPER_H #define VVVSTLHELPER_H #include <algorithm> #include <string> #include <vector> template<typename C, class P, typename = typename std::enable_if_t<std::is_rvalue_reference<C&&>::value> > inline decltype(auto) filter(C&& v, P p ) { const auto n = std::copy_if( v.begin(), v.end(), v.begin(), p ); v.resize( std::distance(v.begin(), n) ); return std::move(v); } template<class C, class P> inline C filter( const C& v, P p) { C ret; std::copy_if( v.begin(), v.end(), std::back_inserter( ret ), p ); return ret; } template<class C, class P> inline bool any_of(const C& c, const P& p) { return std::any_of(c.begin(), c.end(), p); } template<class C, class V> inline bool contain(const C& c, const V& v) { return any_of(c, [&v](const auto& e){return e == v;}); } inline std::string joinStringsWith( const std::vector<std::string>& v, const std::string& delimiter) { std::string ret; const auto numStrings = v.size(); const auto lastIndex = numStrings-1; for(size_t i = 0; i < numStrings; ++i) { ret += v[i]; if( i!= lastIndex) ret += delimiter; } return ret; } inline void split(const std::string& input, char delimiter, std::vector<std::string>& ret) { using namespace std; size_t last_pos = 0; while(true) { const size_t current_pos = input.find(delimiter,last_pos); if(current_pos == string::npos) { const string substr = input.substr(last_pos, input.size() - last_pos ); ret.push_back(substr); break; } else { const string substr = input.substr(last_pos, current_pos-last_pos); ret.push_back(substr); last_pos = current_pos+1; }} } inline std::vector<std::string> split(const std::string& str, char delimiter=' ') { std::vector<std::string> ret; split(str, delimiter, ret); return ret; } #endif <commit_msg>reformat<commit_after>#ifndef VVVSTLHELPER_H #define VVVSTLHELPER_H #include <algorithm> #include <string> #include <vector> template<typename C, class P, typename = typename std::enable_if_t<std::is_rvalue_reference<C&&>::value> > inline decltype(auto) filter(C&& v, P p ) { const auto n = std::copy_if( v.begin(), v.end(), v.begin(), p ); v.resize( std::distance(v.begin(), n) ); return std::move(v); } template<class C, class P> inline C filter( const C& v, P p) { C ret; std::copy_if( v.begin(), v.end(), std::back_inserter( ret ), p ); return ret; } template<class C, class P> inline bool any_of(const C& c, const P& p) { return std::any_of(c.begin(), c.end(), p); } template<class C, class V> inline bool contain(const C& c, const V& v) { return any_of(c, [&v](const auto& e){return e == v;}); } inline std::string joinStringsWith(const std::vector<std::string>& v, const std::string& delimiter) { std::string ret; const auto numStrings = v.size(); const auto lastIndex = numStrings-1; for(size_t i = 0; i < numStrings; ++i) { ret += v[i]; if( i!= lastIndex) ret += delimiter; } return ret; } inline void split(const std::string& input, char delimiter, std::vector<std::string>& ret) { using namespace std; size_t last_pos = 0; while(true) { const size_t current_pos = input.find(delimiter,last_pos); if(current_pos == string::npos) { const string substr = input.substr(last_pos, input.size() - last_pos ); ret.push_back(substr); break; } else { const string substr = input.substr(last_pos, current_pos-last_pos); ret.push_back(substr); last_pos = current_pos+1; }} } inline std::vector<std::string> split(const std::string& str, char delimiter=' ') { std::vector<std::string> ret; split(str, delimiter, ret); return ret; } #endif <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2006-2008 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Nokia Corporation (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "globalconfig_p.h" #include "factory_p.h" #include "objectdescription.h" #include "phonondefs_p.h" #include "platformplugin.h" #include "backendinterface.h" #include "qsettingsgroup_p.h" #include "phononnamespace_p.h" #include "pulsesupport_p.h" #include <QtCore/QList> #include <QtCore/QVariant> QT_BEGIN_NAMESPACE namespace Phonon { GlobalConfig::GlobalConfig() : m_config(QLatin1String("kde.org"), QLatin1String("libphonon")) { } GlobalConfig::~GlobalConfig() { } enum WhatToFilter { FilterAdvancedDevices = 1, FilterHardwareDevices = 2, FilterUnavailableDevices = 4 }; static void filter(ObjectDescriptionType type, BackendInterface *backendIface, QList<int> *list, int whatToFilter) { QMutableListIterator<int> it(*list); while (it.hasNext()) { const QHash<QByteArray, QVariant> properties = backendIface->objectDescriptionProperties(type, it.next()); QVariant var; if (whatToFilter & FilterAdvancedDevices) { var = properties.value("isAdvanced"); if (var.isValid() && var.toBool()) { it.remove(); continue; } } if (whatToFilter & FilterHardwareDevices) { var = properties.value("isHardwareDevice"); if (var.isValid() && var.toBool()) { it.remove(); continue; } } if (whatToFilter & FilterUnavailableDevices) { var = properties.value("available"); if (var.isValid() && !var.toBool()) { it.remove(); continue; } } } } static QList<int> listSortedByConfig(const QSettingsGroup &backendConfig, Phonon::Category category, QList<int> &defaultList) { if (defaultList.size() <= 1) { // nothing to sort return defaultList; } else { // make entries unique QSet<int> seen; QMutableListIterator<int> it(defaultList); while (it.hasNext()) { if (seen.contains(it.next())) { it.remove(); } else { seen.insert(it.value()); } } } QString categoryKey = QLatin1String("Category_") + QString::number(static_cast<int>(category)); if (!backendConfig.hasKey(categoryKey)) { // no list in config for the given category categoryKey = QLatin1String("Category_") + QString::number(static_cast<int>(Phonon::NoCategory)); if (!backendConfig.hasKey(categoryKey)) { // no list in config for NoCategory return defaultList; } } //Now the list from m_config QList<int> deviceList = backendConfig.value(categoryKey, QList<int>()); //if there are devices in m_config that the backend doesn't report, remove them from the list QMutableListIterator<int> i(deviceList); while (i.hasNext()) { if (0 == defaultList.removeAll(i.next())) { i.remove(); } } //if the backend reports more devices that are not in m_config append them to the list deviceList += defaultList; return deviceList; } bool GlobalConfig::getHideAdvancedDevices() const { //The devices need to be stored independently for every backend const QSettingsGroup generalGroup(&m_config, QLatin1String("General")); return generalGroup.value(QLatin1String("HideAdvancedDevices"), true); } void GlobalConfig::hideAdvancedDevices(bool hide) { QSettingsGroup generalGroup(&m_config, QLatin1String("General")); generalGroup.value(QLatin1String("HideAdvancedDevices"), hide); } bool GlobalConfig::isHiddenAudioOutputDevice(int i) const { if (!getHideAdvancedDevices()) return false; AudioOutputDevice ad = AudioOutputDevice::fromIndex(i); const QVariant var = ad.property("isAdvanced"); return (var.isValid() && var.toBool()); } void GlobalConfig::setAudioOutputDeviceListFor(Phonon::Category category, QList<int> order) { QSettingsGroup backendConfig(&m_config, QLatin1String("AudioOutputDevice")); // + Factory::identifier()); const QList<int> noCategoryOrder = audioOutputDeviceListFor(Phonon::NoCategory, ShowUnavailableDevices|ShowAdvancedDevices); if (category != Phonon::NoCategory && order == noCategoryOrder) { backendConfig.removeEntry(QLatin1String("Category_") + QString::number(category)); } else { backendConfig.setValue(QLatin1String("Category_") + QString::number(category), order); } } QList<int> GlobalConfig::audioOutputDeviceListFor(Phonon::Category category, int override) const { //The devices need to be stored independently for every backend const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioOutputDevice")); // + Factory::identifier()); const bool hideAdvancedDevices = ((override & AdvancedDevicesFromSettings) ? getHideAdvancedDevices() : static_cast<bool>(override & HideAdvancedDevices)); QList<int> defaultList; BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend()); #ifndef QT_NO_PHONON_PLATFORMPLUGIN if (!backendIface || !PulseSupport::getInstance()->isActive()) { if (PlatformPlugin *platformPlugin = Factory::platformPlugin()) { // the platform plugin lists the audio devices for the platform // this list already is in default order (as defined by the platform plugin) defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioOutputDeviceType); if (hideAdvancedDevices) { QMutableListIterator<int> it(defaultList); while (it.hasNext()) { AudioOutputDevice objDesc = AudioOutputDevice::fromIndex(it.next()); const QVariant var = objDesc.property("isAdvanced"); if (var.isValid() && var.toBool()) { it.remove(); } } } } } #endif //QT_NO_PHONON_PLATFORMPLUGIN // lookup the available devices directly from the backend if (backendIface) { // this list already is in default order (as defined by the backend) QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioOutputDeviceType); if (hideAdvancedDevices || !defaultList.isEmpty() || (override & HideUnavailableDevices)) { filter(AudioOutputDeviceType, backendIface, &list, (hideAdvancedDevices ? FilterAdvancedDevices : 0) // the platform plugin already provided the hardware devices | (defaultList.isEmpty() ? 0 : FilterHardwareDevices) | ((override & HideUnavailableDevices) ? FilterUnavailableDevices : 0) ); } defaultList += list; } return listSortedByConfig(backendConfig, category, defaultList); } int GlobalConfig::audioOutputDeviceFor(Phonon::Category category, int override) const { QList<int> ret = audioOutputDeviceListFor(category, override); if (ret.isEmpty()) return -1; return ret.first(); } #ifndef QT_NO_PHONON_AUDIOCAPTURE bool GlobalConfig::isHiddenAudioCaptureDevice(int i) const { if (!getHideAdvancedDevices()) return false; AudioCaptureDevice ad = AudioCaptureDevice::fromIndex(i); const QVariant var = ad.property("isAdvanced"); return (var.isValid() && var.toBool()); } void GlobalConfig::setAudioCaptureDeviceListFor(Phonon::Category category, QList<int> order) { QSettingsGroup backendConfig(&m_config, QLatin1String("AudioCaptureDevice")); // + Factory::identifier()); const QList<int> noCategoryOrder = audioCaptureDeviceListFor(Phonon::NoCategory, ShowUnavailableDevices|ShowAdvancedDevices); if (category != Phonon::NoCategory && order == noCategoryOrder) { backendConfig.removeEntry(QLatin1String("Category_") + QString::number(category)); } else { backendConfig.setValue(QLatin1String("Category_") + QString::number(category), order); } } QList<int> GlobalConfig::audioCaptureDeviceListFor(Phonon::Category category, int override) const { //The devices need to be stored independently for every backend const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioCaptureDevice")); // + Factory::identifier()); const bool hideAdvancedDevices = ((override & AdvancedDevicesFromSettings) ? getHideAdvancedDevices() : static_cast<bool>(override & HideAdvancedDevices)); QList<int> defaultList; BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend()); #ifndef QT_NO_PHONON_PLATFORMPLUGIN if (!backendIface || !PulseSupport::getInstance()->isActive()) { if (PlatformPlugin *platformPlugin = Factory::platformPlugin()) { // the platform plugin lists the audio devices for the platform // this list already is in default order (as defined by the platform plugin) defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType); if (hideAdvancedDevices) { QMutableListIterator<int> it(defaultList); while (it.hasNext()) { AudioCaptureDevice objDesc = AudioCaptureDevice::fromIndex(it.next()); const QVariant var = objDesc.property("isAdvanced"); if (var.isValid() && var.toBool()) { it.remove(); } } } } } #endif //QT_NO_PHONON_PLATFORMPLUGIN // lookup the available devices directly from the backend if (backendIface) { // this list already is in default order (as defined by the backend) QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType); if (hideAdvancedDevices || !defaultList.isEmpty() || (override & HideUnavailableDevices)) { filter(AudioCaptureDeviceType, backendIface, &list, (hideAdvancedDevices ? FilterAdvancedDevices : 0) // the platform plugin already provided the hardware devices | (defaultList.isEmpty() ? 0 : FilterHardwareDevices) | ((override & HideUnavailableDevices) ? FilterUnavailableDevices : 0) ); } defaultList += list; } return listSortedByConfig(backendConfig, category, defaultList); } int GlobalConfig::audioCaptureDeviceFor(Phonon::Category category, int override) const { QList<int> ret = audioCaptureDeviceListFor(category, override); if (ret.isEmpty()) return -1; return ret.first(); } #endif //QT_NO_PHONON_AUDIOCAPTURE } // namespace Phonon QT_END_NAMESPACE <commit_msg>pulseaudio: If the results are coming from pulseaudio, there is no need to sort.<commit_after>/* This file is part of the KDE project Copyright (C) 2006-2008 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Nokia Corporation (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "globalconfig_p.h" #include "factory_p.h" #include "objectdescription.h" #include "phonondefs_p.h" #include "platformplugin.h" #include "backendinterface.h" #include "qsettingsgroup_p.h" #include "phononnamespace_p.h" #include "pulsesupport_p.h" #include <QtCore/QList> #include <QtCore/QVariant> QT_BEGIN_NAMESPACE namespace Phonon { GlobalConfig::GlobalConfig() : m_config(QLatin1String("kde.org"), QLatin1String("libphonon")) { } GlobalConfig::~GlobalConfig() { } enum WhatToFilter { FilterAdvancedDevices = 1, FilterHardwareDevices = 2, FilterUnavailableDevices = 4 }; static void filter(ObjectDescriptionType type, BackendInterface *backendIface, QList<int> *list, int whatToFilter) { QMutableListIterator<int> it(*list); while (it.hasNext()) { const QHash<QByteArray, QVariant> properties = backendIface->objectDescriptionProperties(type, it.next()); QVariant var; if (whatToFilter & FilterAdvancedDevices) { var = properties.value("isAdvanced"); if (var.isValid() && var.toBool()) { it.remove(); continue; } } if (whatToFilter & FilterHardwareDevices) { var = properties.value("isHardwareDevice"); if (var.isValid() && var.toBool()) { it.remove(); continue; } } if (whatToFilter & FilterUnavailableDevices) { var = properties.value("available"); if (var.isValid() && !var.toBool()) { it.remove(); continue; } } } } static QList<int> listSortedByConfig(const QSettingsGroup &backendConfig, Phonon::Category category, QList<int> &defaultList) { if (PulseSupport::getInstance()->isActive() || defaultList.size() <= 1) { // nothing to sort return defaultList; } else { // make entries unique QSet<int> seen; QMutableListIterator<int> it(defaultList); while (it.hasNext()) { if (seen.contains(it.next())) { it.remove(); } else { seen.insert(it.value()); } } } QString categoryKey = QLatin1String("Category_") + QString::number(static_cast<int>(category)); if (!backendConfig.hasKey(categoryKey)) { // no list in config for the given category categoryKey = QLatin1String("Category_") + QString::number(static_cast<int>(Phonon::NoCategory)); if (!backendConfig.hasKey(categoryKey)) { // no list in config for NoCategory return defaultList; } } //Now the list from m_config QList<int> deviceList = backendConfig.value(categoryKey, QList<int>()); //if there are devices in m_config that the backend doesn't report, remove them from the list QMutableListIterator<int> i(deviceList); while (i.hasNext()) { if (0 == defaultList.removeAll(i.next())) { i.remove(); } } //if the backend reports more devices that are not in m_config append them to the list deviceList += defaultList; return deviceList; } bool GlobalConfig::getHideAdvancedDevices() const { //The devices need to be stored independently for every backend const QSettingsGroup generalGroup(&m_config, QLatin1String("General")); return generalGroup.value(QLatin1String("HideAdvancedDevices"), true); } void GlobalConfig::hideAdvancedDevices(bool hide) { QSettingsGroup generalGroup(&m_config, QLatin1String("General")); generalGroup.value(QLatin1String("HideAdvancedDevices"), hide); } bool GlobalConfig::isHiddenAudioOutputDevice(int i) const { if (!getHideAdvancedDevices()) return false; AudioOutputDevice ad = AudioOutputDevice::fromIndex(i); const QVariant var = ad.property("isAdvanced"); return (var.isValid() && var.toBool()); } void GlobalConfig::setAudioOutputDeviceListFor(Phonon::Category category, QList<int> order) { QSettingsGroup backendConfig(&m_config, QLatin1String("AudioOutputDevice")); // + Factory::identifier()); const QList<int> noCategoryOrder = audioOutputDeviceListFor(Phonon::NoCategory, ShowUnavailableDevices|ShowAdvancedDevices); if (category != Phonon::NoCategory && order == noCategoryOrder) { backendConfig.removeEntry(QLatin1String("Category_") + QString::number(category)); } else { backendConfig.setValue(QLatin1String("Category_") + QString::number(category), order); } } QList<int> GlobalConfig::audioOutputDeviceListFor(Phonon::Category category, int override) const { //The devices need to be stored independently for every backend const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioOutputDevice")); // + Factory::identifier()); const bool hideAdvancedDevices = ((override & AdvancedDevicesFromSettings) ? getHideAdvancedDevices() : static_cast<bool>(override & HideAdvancedDevices)); QList<int> defaultList; BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend()); #ifndef QT_NO_PHONON_PLATFORMPLUGIN if (!backendIface || !PulseSupport::getInstance()->isActive()) { if (PlatformPlugin *platformPlugin = Factory::platformPlugin()) { // the platform plugin lists the audio devices for the platform // this list already is in default order (as defined by the platform plugin) defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioOutputDeviceType); if (hideAdvancedDevices) { QMutableListIterator<int> it(defaultList); while (it.hasNext()) { AudioOutputDevice objDesc = AudioOutputDevice::fromIndex(it.next()); const QVariant var = objDesc.property("isAdvanced"); if (var.isValid() && var.toBool()) { it.remove(); } } } } } #endif //QT_NO_PHONON_PLATFORMPLUGIN // lookup the available devices directly from the backend if (backendIface) { // this list already is in default order (as defined by the backend) QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioOutputDeviceType); if (hideAdvancedDevices || !defaultList.isEmpty() || (override & HideUnavailableDevices)) { filter(AudioOutputDeviceType, backendIface, &list, (hideAdvancedDevices ? FilterAdvancedDevices : 0) // the platform plugin already provided the hardware devices | (defaultList.isEmpty() ? 0 : FilterHardwareDevices) | ((override & HideUnavailableDevices) ? FilterUnavailableDevices : 0) ); } defaultList += list; } return listSortedByConfig(backendConfig, category, defaultList); } int GlobalConfig::audioOutputDeviceFor(Phonon::Category category, int override) const { QList<int> ret = audioOutputDeviceListFor(category, override); if (ret.isEmpty()) return -1; return ret.first(); } #ifndef QT_NO_PHONON_AUDIOCAPTURE bool GlobalConfig::isHiddenAudioCaptureDevice(int i) const { if (!getHideAdvancedDevices()) return false; AudioCaptureDevice ad = AudioCaptureDevice::fromIndex(i); const QVariant var = ad.property("isAdvanced"); return (var.isValid() && var.toBool()); } void GlobalConfig::setAudioCaptureDeviceListFor(Phonon::Category category, QList<int> order) { QSettingsGroup backendConfig(&m_config, QLatin1String("AudioCaptureDevice")); // + Factory::identifier()); const QList<int> noCategoryOrder = audioCaptureDeviceListFor(Phonon::NoCategory, ShowUnavailableDevices|ShowAdvancedDevices); if (category != Phonon::NoCategory && order == noCategoryOrder) { backendConfig.removeEntry(QLatin1String("Category_") + QString::number(category)); } else { backendConfig.setValue(QLatin1String("Category_") + QString::number(category), order); } } QList<int> GlobalConfig::audioCaptureDeviceListFor(Phonon::Category category, int override) const { //The devices need to be stored independently for every backend const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioCaptureDevice")); // + Factory::identifier()); const bool hideAdvancedDevices = ((override & AdvancedDevicesFromSettings) ? getHideAdvancedDevices() : static_cast<bool>(override & HideAdvancedDevices)); QList<int> defaultList; BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend()); #ifndef QT_NO_PHONON_PLATFORMPLUGIN if (!backendIface || !PulseSupport::getInstance()->isActive()) { if (PlatformPlugin *platformPlugin = Factory::platformPlugin()) { // the platform plugin lists the audio devices for the platform // this list already is in default order (as defined by the platform plugin) defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType); if (hideAdvancedDevices) { QMutableListIterator<int> it(defaultList); while (it.hasNext()) { AudioCaptureDevice objDesc = AudioCaptureDevice::fromIndex(it.next()); const QVariant var = objDesc.property("isAdvanced"); if (var.isValid() && var.toBool()) { it.remove(); } } } } } #endif //QT_NO_PHONON_PLATFORMPLUGIN // lookup the available devices directly from the backend if (backendIface) { // this list already is in default order (as defined by the backend) QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType); if (hideAdvancedDevices || !defaultList.isEmpty() || (override & HideUnavailableDevices)) { filter(AudioCaptureDeviceType, backendIface, &list, (hideAdvancedDevices ? FilterAdvancedDevices : 0) // the platform plugin already provided the hardware devices | (defaultList.isEmpty() ? 0 : FilterHardwareDevices) | ((override & HideUnavailableDevices) ? FilterUnavailableDevices : 0) ); } defaultList += list; } return listSortedByConfig(backendConfig, category, defaultList); } int GlobalConfig::audioCaptureDeviceFor(Phonon::Category category, int override) const { QList<int> ret = audioCaptureDeviceListFor(category, override); if (ret.isEmpty()) return -1; return ret.first(); } #endif //QT_NO_PHONON_AUDIOCAPTURE } // namespace Phonon QT_END_NAMESPACE <|endoftext|>
<commit_before>// flagStay.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" #include <string> #include <vector> #include <math.h> BZ_GET_PLUGIN_VERSION class FlagStayZoneHandler : public bz_CustomMapObjectHandler { public: virtual bool handle ( bzApiString object, bz_CustomMapObjectInfo *data ); }; FlagStayZoneHandler flagStayZoneHandler; class EventHandler : public bz_EventHandler { public: virtual void process ( bz_EventData *eventData ); }; EventHandler eventHandler; BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ ) { bz_debugMessage(4,"flagStay plugin loaded"); bz_registerCustomMapObject("FLAGSTAYZONE",&flagStayZoneHandler); bz_registerEvent(bz_ePlayerUpdateEvent,&eventHandler); return 0; } BZF_PLUGIN_CALL int bz_Unload ( void ) { bz_removeEvent(bz_ePlayerUpdateEvent,&eventHandler); bz_removeCustomMapObject("FLAGSTAYZONE"); bz_debugMessage(4,"flagStay plugin unloaded"); return 0; } class FlagStayZone { public: FlagStayZone() { box = false; xMax = xMin = yMax = yMin = zMax = zMin = rad = 0; } bool box; float xMax,xMin,yMax,yMin,zMax,zMin; float rad; bool pointIn ( float pos[3] ) { if ( box ) { if ( pos[0] > xMax || pos[0] < xMin ) return false; if ( pos[1] > yMax || pos[1] < yMin ) return false; if ( pos[2] > zMax || pos[2] < zMin ) return false; } else { float vec[3]; vec[0] = pos[0]-xMax; vec[1] = pos[1]-yMax; vec[2] = pos[2]-zMax; float dist = sqrt(vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2]); if ( dist > rad) return false; } return true; } bool checkFlag ( const char* flag ) { for ( unsigned int i = 0; i < flagList.size(); i++ ) { if ( flagList[i] == flag ) return true; } return false; } std::vector<std::string> flagList; }; std::vector <FlagStayZone> zoneList; bool FlagStayZoneHandler::handle ( bzApiString object, bz_CustomMapObjectInfo *data ) { if (object != "FLAGSTAYZONE" || !data) return false; FlagStayZone newZone; // parse all the chunks for ( unsigned int i = 0; i < data->data.size(); i++ ) { std::string line = data->data.get(i).c_str(); bzAPIStringList *nubs = bz_newStringList(); nubs->tokenize(line.c_str()," ",0,true); if ( nubs->size() > 0) { std::string key = bz_toupper(nubs->get(0).c_str()); if ( key == "BBOX" && nubs->size() > 6) { newZone.box = true; newZone.xMin = (float)atof(nubs->get(1).c_str()); newZone.xMax = (float)atof(nubs->get(2).c_str()); newZone.yMin = (float)atof(nubs->get(3).c_str()); newZone.yMax = (float)atof(nubs->get(4).c_str()); newZone.zMin = (float)atof(nubs->get(5).c_str()); newZone.zMax = (float)atof(nubs->get(6).c_str()); } else if ( key == "RAD" && nubs->size() > 5) { newZone.box = false; newZone.rad = (float)atof(nubs->get(4).c_str()); newZone.xMax =(float)atof(nubs->get(1).c_str()); newZone.yMax =(float)atof(nubs->get(2).c_str()); newZone.zMax =(float)atof(nubs->get(3).c_str()); } else if ( key == "FLAG" && nubs->size() > 1) { std::string flag = nubs->get(1).c_str(); newZone.flagList.push_back(flag); } } bz_deleteStringList(nubs); zoneList.push_back(newZone); } return true; } void EventHandler::process ( bz_EventData *eventData ) { float pos[3] = {0}; int playerID = -1; switch (eventData->eventType) { case bz_ePlayerUpdateEvent: pos[0] = ((bz_PlayerUpdateEventData*)eventData)->pos[0]; pos[1] = ((bz_PlayerUpdateEventData*)eventData)->pos[1]; pos[2] = ((bz_PlayerUpdateEventData*)eventData)->pos[2]; playerID = ((bz_PlayerUpdateEventData*)eventData)->playerID; break; case bz_eShotFiredEvent: pos[0] = ((bz_ShotFiredEventData*)eventData)->pos[0]; pos[1] = ((bz_ShotFiredEventData*)eventData)->pos[1]; pos[2] = ((bz_ShotFiredEventData*)eventData)->pos[2]; playerID = ((bz_ShotFiredEventData*)eventData)->playerID; break; } bz_PlayerRecord *player = bz_getPlayerByIndex(playerID); if (!player) return; // check and see if a zone cares about the current flag for ( unsigned int i = 0; i < zoneList.size(); i++ ) { if ( zoneList[i].checkFlag(player->currentFlag.c_str()) ) { if ( !zoneList[i].pointIn(pos) ) // they have taken the flag out of a zone, pop it. { bz_removePlayerFlag(playerID); i = (unsigned int)zoneList.size(); // finish out } } } bz_freePlayerRecord(player); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>cylinders not spheres :)<commit_after>// flagStay.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" #include <string> #include <vector> #include <math.h> BZ_GET_PLUGIN_VERSION class FlagStayZoneHandler : public bz_CustomMapObjectHandler { public: virtual bool handle ( bzApiString object, bz_CustomMapObjectInfo *data ); }; FlagStayZoneHandler flagStayZoneHandler; class EventHandler : public bz_EventHandler { public: virtual void process ( bz_EventData *eventData ); }; EventHandler eventHandler; BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ ) { bz_debugMessage(4,"flagStay plugin loaded"); bz_registerCustomMapObject("FLAGSTAYZONE",&flagStayZoneHandler); bz_registerEvent(bz_ePlayerUpdateEvent,&eventHandler); return 0; } BZF_PLUGIN_CALL int bz_Unload ( void ) { bz_removeEvent(bz_ePlayerUpdateEvent,&eventHandler); bz_removeCustomMapObject("FLAGSTAYZONE"); bz_debugMessage(4,"flagStay plugin unloaded"); return 0; } class FlagStayZone { public: FlagStayZone() { box = false; xMax = xMin = yMax = yMin = zMax = zMin = rad = 0; } bool box; float xMax,xMin,yMax,yMin,zMax,zMin; float rad; bool pointIn ( float pos[3] ) { if ( box ) { if ( pos[0] > xMax || pos[0] < xMin ) return false; if ( pos[1] > yMax || pos[1] < yMin ) return false; if ( pos[2] > zMax || pos[2] < zMin ) return false; } else { float vec[3]; vec[0] = pos[0]-xMax; vec[1] = pos[1]-yMax; vec[2] = pos[2]-zMax; float dist = sqrt(vec[0]*vec[0]+vec[1]*vec[1]); if ( dist > rad) return false; if ( pos[2] > zMax || pos[2] < zMin ) return false; } return true; } bool checkFlag ( const char* flag ) { for ( unsigned int i = 0; i < flagList.size(); i++ ) { if ( flagList[i] == flag ) return true; } return false; } std::vector<std::string> flagList; }; std::vector <FlagStayZone> zoneList; bool FlagStayZoneHandler::handle ( bzApiString object, bz_CustomMapObjectInfo *data ) { if (object != "FLAGSTAYZONE" || !data) return false; FlagStayZone newZone; // parse all the chunks for ( unsigned int i = 0; i < data->data.size(); i++ ) { std::string line = data->data.get(i).c_str(); bzAPIStringList *nubs = bz_newStringList(); nubs->tokenize(line.c_str()," ",0,true); if ( nubs->size() > 0) { std::string key = bz_toupper(nubs->get(0).c_str()); if ( key == "BBOX" && nubs->size() > 6) { newZone.box = true; newZone.xMin = (float)atof(nubs->get(1).c_str()); newZone.xMax = (float)atof(nubs->get(2).c_str()); newZone.yMin = (float)atof(nubs->get(3).c_str()); newZone.yMax = (float)atof(nubs->get(4).c_str()); newZone.zMin = (float)atof(nubs->get(5).c_str()); newZone.zMax = (float)atof(nubs->get(6).c_str()); } else if ( key == "CYLINDER" && nubs->size() > 5) { newZone.box = false; newZone.rad = (float)atof(nubs->get(5).c_str()); newZone.xMax =(float)atof(nubs->get(1).c_str()); newZone.yMax =(float)atof(nubs->get(2).c_str()); newZone.zMin =(float)atof(nubs->get(3).c_str()); newZone.zMax =(float)atof(nubs->get(4).c_str()); } else if ( key == "FLAG" && nubs->size() > 1) { std::string flag = nubs->get(1).c_str(); newZone.flagList.push_back(flag); } } bz_deleteStringList(nubs); zoneList.push_back(newZone); } return true; } void EventHandler::process ( bz_EventData *eventData ) { float pos[3] = {0}; int playerID = -1; switch (eventData->eventType) { case bz_ePlayerUpdateEvent: pos[0] = ((bz_PlayerUpdateEventData*)eventData)->pos[0]; pos[1] = ((bz_PlayerUpdateEventData*)eventData)->pos[1]; pos[2] = ((bz_PlayerUpdateEventData*)eventData)->pos[2]; playerID = ((bz_PlayerUpdateEventData*)eventData)->playerID; break; case bz_eShotFiredEvent: pos[0] = ((bz_ShotFiredEventData*)eventData)->pos[0]; pos[1] = ((bz_ShotFiredEventData*)eventData)->pos[1]; pos[2] = ((bz_ShotFiredEventData*)eventData)->pos[2]; playerID = ((bz_ShotFiredEventData*)eventData)->playerID; break; } bz_PlayerRecord *player = bz_getPlayerByIndex(playerID); if (!player) return; // check and see if a zone cares about the current flag for ( unsigned int i = 0; i < zoneList.size(); i++ ) { if ( zoneList[i].checkFlag(player->currentFlag.c_str()) ) { if ( !zoneList[i].pointIn(pos) ) // they have taken the flag out of a zone, pop it. { bz_removePlayerFlag(playerID); i = (unsigned int)zoneList.size(); // finish out } } } bz_freePlayerRecord(player); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>// flagStay.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" #include <string> #include <vector> #include <math.h> BZ_GET_PLUGIN_VERSION class FlagStayZoneHandler : public bz_CustomMapObjectHandler { public: virtual bool handle ( bzApiString object, bz_CustomMapObjectInfo *data ); }; FlagStayZoneHandler flagStayZoneHandler; class EventHandler : public bz_EventHandler { public: virtual void process ( bz_EventData *eventData ); }; EventHandler eventHandler; BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ ) { bz_debugMessage(4,"flagStay plugin loaded"); bz_registerCustomMapObject("FLAGSTAYZONE",&flagStayZoneHandler); bz_registerEvent(bz_ePlayerUpdateEvent,&eventHandler); return 0; } BZF_PLUGIN_CALL int bz_Unload ( void ) { bz_removeEvent(bz_ePlayerUpdateEvent,&eventHandler); bz_removeCustomMapObject("FLAGSTAYZONE"); bz_debugMessage(4,"flagStay plugin unloaded"); return 0; } class FlagStayZone { public: FlagStayZone() { box = false; xMax = xMin = yMax = yMin = zMax = zMin = rad = 0; } bool box; float xMax,xMin,yMax,yMin,zMax,zMin; float rad; std::string message; bool pointIn ( float pos[3] ) { if ( box ) { if ( pos[0] > xMax || pos[0] < xMin ) return false; if ( pos[1] > yMax || pos[1] < yMin ) return false; if ( pos[2] > zMax || pos[2] < zMin ) return false; } else { float vec[3]; vec[0] = pos[0]-xMax; vec[1] = pos[1]-yMax; vec[2] = pos[2]-zMax; float dist = sqrt(vec[0]*vec[0]+vec[1]*vec[1]); if ( dist > rad) return false; if ( pos[2] > zMax || pos[2] < zMin ) return false; } return true; } bool checkFlag ( const char* flag ) { for ( unsigned int i = 0; i < flagList.size(); i++ ) { if ( flagList[i] == flag ) return true; } return false; } std::vector<std::string> flagList; }; std::vector <FlagStayZone> zoneList; bool FlagStayZoneHandler::handle ( bzApiString object, bz_CustomMapObjectInfo *data ) { if (object != "FLAGSTAYZONE" || !data) return false; FlagStayZone newZone; // parse all the chunks for ( unsigned int i = 0; i < data->data.size(); i++ ) { std::string line = data->data.get(i).c_str(); bzAPIStringList *nubs = bz_newStringList(); nubs->tokenize(line.c_str()," ",0,true); if ( nubs->size() > 0) { std::string key = bz_toupper(nubs->get(0).c_str()); if ( key == "BBOX" && nubs->size() > 6) { newZone.box = true; newZone.xMin = (float)atof(nubs->get(1).c_str()); newZone.xMax = (float)atof(nubs->get(2).c_str()); newZone.yMin = (float)atof(nubs->get(3).c_str()); newZone.yMax = (float)atof(nubs->get(4).c_str()); newZone.zMin = (float)atof(nubs->get(5).c_str()); newZone.zMax = (float)atof(nubs->get(6).c_str()); } else if ( key == "CYLINDER" && nubs->size() > 5) { newZone.box = false; newZone.rad = (float)atof(nubs->get(5).c_str()); newZone.xMax =(float)atof(nubs->get(1).c_str()); newZone.yMax =(float)atof(nubs->get(2).c_str()); newZone.zMin =(float)atof(nubs->get(3).c_str()); newZone.zMax =(float)atof(nubs->get(4).c_str()); } else if ( key == "FLAG" && nubs->size() > 1) { std::string flag = nubs->get(1).c_str(); newZone.flagList.push_back(flag); } else if ( key == "MESSAGE" && nubs->size() > 1 ) { newZone.message = nubs->get(1).c_str(); } } bz_deleteStringList(nubs); } zoneList.push_back(newZone); return true; } void EventHandler::process ( bz_EventData *eventData ) { float pos[3] = {0}; int playerID = -1; switch (eventData->eventType) { case bz_ePlayerUpdateEvent: pos[0] = ((bz_PlayerUpdateEventData*)eventData)->pos[0]; pos[1] = ((bz_PlayerUpdateEventData*)eventData)->pos[1]; pos[2] = ((bz_PlayerUpdateEventData*)eventData)->pos[2]; playerID = ((bz_PlayerUpdateEventData*)eventData)->playerID; break; case bz_eShotFiredEvent: pos[0] = ((bz_ShotFiredEventData*)eventData)->pos[0]; pos[1] = ((bz_ShotFiredEventData*)eventData)->pos[1]; pos[2] = ((bz_ShotFiredEventData*)eventData)->pos[2]; playerID = ((bz_ShotFiredEventData*)eventData)->playerID; break; } bz_PlayerRecord *player = bz_getPlayerByIndex(playerID); if (!player) return; // check and see if a zone cares about the current flag for ( unsigned int i = 0; i < zoneList.size(); i++ ) { if ( zoneList[i].checkFlag(player->currentFlag.c_str()) ) { if ( !zoneList[i].pointIn(pos) ) // they have taken the flag out of a zone, pop it. { bz_removePlayerFlag(playerID); if (zoneList[i].message.size()) bz_sendTextMessage(BZ_SERVER,playerID,zoneList[i].message.c_str()); i = (unsigned int)zoneList.size(); // finish out } } } bz_freePlayerRecord(player); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>make the plugin work<commit_after>// flagStay.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" #include <string> #include <vector> #include <math.h> BZ_GET_PLUGIN_VERSION class FlagStayZoneHandler : public bz_CustomMapObjectHandler { public: virtual bool handle ( bzApiString object, bz_CustomMapObjectInfo *data ); }; FlagStayZoneHandler flagStayZoneHandler; class EventHandler : public bz_EventHandler { public: virtual void process ( bz_EventData *eventData ); }; EventHandler eventHandler; BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ ) { bz_debugMessage(4,"flagStay plugin loaded"); bz_registerCustomMapObject("FLAGSTAYZONE",&flagStayZoneHandler); bz_registerEvent(bz_ePlayerUpdateEvent,&eventHandler); return 0; } BZF_PLUGIN_CALL int bz_Unload ( void ) { bz_removeEvent(bz_ePlayerUpdateEvent,&eventHandler); bz_removeCustomMapObject("FLAGSTAYZONE"); bz_debugMessage(4,"flagStay plugin unloaded"); return 0; } class FlagStayZone { public: FlagStayZone() { box = false; xMax = xMin = yMax = yMin = zMax = zMin = rad = 0; } bool box; float xMax,xMin,yMax,yMin,zMax,zMin; float rad; std::string message; bool pointIn ( float pos[3] ) { if ( box ) { if ( pos[0] > xMax || pos[0] < xMin ) return false; if ( pos[1] > yMax || pos[1] < yMin ) return false; if ( pos[2] > zMax || pos[2] < zMin ) return false; } else { float vec[3]; vec[0] = pos[0]-xMax; vec[1] = pos[1]-yMax; vec[2] = pos[2]-zMax; float dist = sqrt(vec[0]*vec[0]+vec[1]*vec[1]); if ( dist > rad) return false; if ( pos[2] > zMax || pos[2] < zMin ) return false; } return true; } bool checkFlag ( const char* flag ) { for ( unsigned int i = 0; i < flagList.size(); i++ ) { if ( flagList[i] == flag ) return true; } return false; } std::vector<std::string> flagList; }; std::vector <FlagStayZone> zoneList; bool FlagStayZoneHandler::handle ( bzApiString object, bz_CustomMapObjectInfo *data ) { if (object != "FLAGSTAYZONE" || !data) return false; FlagStayZone newZone; // parse all the chunks for ( unsigned int i = 0; i < data->data.size(); i++ ) { std::string line = data->data.get(i).c_str(); bzAPIStringList *nubs = bz_newStringList(); nubs->tokenize(line.c_str()," ",0,true); if ( nubs->size() > 0) { std::string key = bz_toupper(nubs->get(0).c_str()); if ( key == "BBOX" && nubs->size() > 6) { newZone.box = true; newZone.xMin = (float)atof(nubs->get(1).c_str()); newZone.xMax = (float)atof(nubs->get(2).c_str()); newZone.yMin = (float)atof(nubs->get(3).c_str()); newZone.yMax = (float)atof(nubs->get(4).c_str()); newZone.zMin = (float)atof(nubs->get(5).c_str()); newZone.zMax = (float)atof(nubs->get(6).c_str()); } else if ( key == "CYLINDER" && nubs->size() > 5) { newZone.box = false; newZone.rad = (float)atof(nubs->get(5).c_str()); newZone.xMax =(float)atof(nubs->get(1).c_str()); newZone.yMax =(float)atof(nubs->get(2).c_str()); newZone.zMin =(float)atof(nubs->get(3).c_str()); newZone.zMax =(float)atof(nubs->get(4).c_str()); } else if ( key == "FLAG" && nubs->size() > 1) { std::string flag = nubs->get(1).c_str(); newZone.flagList.push_back(flag); } else if ( key == "MESSAGE" && nubs->size() > 1 ) { newZone.message = nubs->get(1).c_str(); } } bz_deleteStringList(nubs); } zoneList.push_back(newZone); return true; } void EventHandler::process ( bz_EventData *eventData ) { float pos[3] = {0}; int playerID = -1; switch (eventData->eventType) { case bz_ePlayerUpdateEvent: pos[0] = ((bz_PlayerUpdateEventData*)eventData)->pos[0]; pos[1] = ((bz_PlayerUpdateEventData*)eventData)->pos[1]; pos[2] = ((bz_PlayerUpdateEventData*)eventData)->pos[2]; playerID = ((bz_PlayerUpdateEventData*)eventData)->playerID; break; case bz_eShotFiredEvent: pos[0] = ((bz_ShotFiredEventData*)eventData)->pos[0]; pos[1] = ((bz_ShotFiredEventData*)eventData)->pos[1]; pos[2] = ((bz_ShotFiredEventData*)eventData)->pos[2]; playerID = ((bz_ShotFiredEventData*)eventData)->playerID; break; } const char* flagAbrev = bz_getPlayerFlag(playerID); if (!flagAbrev) return; // check and see if a zone cares about the current flag for ( unsigned int i = 0; i < zoneList.size(); i++ ) { if ( zoneList[i].checkFlag(flagAbrev) ) { if ( !zoneList[i].pointIn(pos) ) // they have taken the flag out of a zone, pop it. { bz_removePlayerFlag(playerID); if (zoneList[i].message.size()) bz_sendTextMessage(BZ_SERVER,playerID,zoneList[i].message.c_str()); i = (unsigned int)zoneList.size(); // finish out } } } } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>//===------ SimplifyInstructions.cpp - Remove redundant instructions ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a utility pass used for testing the InstructionSimplify analysis. // The analysis is applied to every instruction, and if it simplifies then the // instruction is replaced by the simplification. If you are looking for a pass // that performs serious instruction folding, use the instcombine pass instead. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "instsimplify" #include "llvm/Function.h" #include "llvm/Pass.h" #include "llvm/Type.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/Target/TargetData.h" #include "llvm/Transforms/Scalar.h" using namespace llvm; STATISTIC(NumSimplified, "Number of redundant instructions removed"); namespace { struct InstSimplifier : public FunctionPass { static char ID; // Pass identification, replacement for typeid InstSimplifier() : FunctionPass(ID) { initializeInstSimplifierPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); } /// runOnFunction - Remove instructions that simplify. bool runOnFunction(Function &F) { bool Changed = false; const TargetData *TD = getAnalysisIfAvailable<TargetData>(); const DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>(); for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) { Instruction *I = BI++; if (Value *V = SimplifyInstruction(I, TD, DT)) { I->replaceAllUsesWith(V); I->eraseFromParent(); Changed = true; ++NumSimplified; } } return Changed; } }; } char InstSimplifier::ID = 0; INITIALIZE_PASS(InstSimplifier, "instsimplify", "Remove redundant instructions", false, false) char &llvm::InstructionSimplifierID = InstSimplifier::ID; // Public interface to the simplify instructions pass. FunctionPass *llvm::createInstructionSimplifierPass() { return new InstSimplifier(); } <commit_msg>If an instruction simplifies, try again to simplify any uses of it. This is not very important since the pass is only used for testing, but it does make it more realistic. Suggested by Frits van Bommel.<commit_after>//===------ SimplifyInstructions.cpp - Remove redundant instructions ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a utility pass used for testing the InstructionSimplify analysis. // The analysis is applied to every instruction, and if it simplifies then the // instruction is replaced by the simplification. If you are looking for a pass // that performs serious instruction folding, use the instcombine pass instead. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "instsimplify" #include "llvm/Function.h" #include "llvm/Pass.h" #include "llvm/Type.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/Target/TargetData.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/Local.h" using namespace llvm; STATISTIC(NumSimplified, "Number of redundant instructions removed"); namespace { struct InstSimplifier : public FunctionPass { static char ID; // Pass identification, replacement for typeid InstSimplifier() : FunctionPass(ID) { initializeInstSimplifierPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); } /// runOnFunction - Remove instructions that simplify. bool runOnFunction(Function &F) { const TargetData *TD = getAnalysisIfAvailable<TargetData>(); const DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>(); bool Changed = false; // Add all interesting instructions to the worklist. std::set<Instruction*> Worklist; for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) { Instruction *I = BI++; // Zap any dead instructions. if (isInstructionTriviallyDead(I)) { I->eraseFromParent(); Changed = true; continue; } // Add all others to the worklist. Worklist.insert(I); } // Simplify everything in the worklist until the cows come home. while (!Worklist.empty()) { Instruction *I = *Worklist.begin(); Worklist.erase(Worklist.begin()); Value *V = SimplifyInstruction(I, TD, DT); if (!V) continue; // This instruction simplifies! Replace it with its simplification and // add all uses to the worklist, since they may now simplify. I->replaceAllUsesWith(V); for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE; ++UI) // In unreachable code an instruction can use itself, in which case // don't add it to the worklist since we are about to erase it. if (*UI != I) Worklist.insert(cast<Instruction>(*UI)); if (isInstructionTriviallyDead(I)) I->eraseFromParent(); ++NumSimplified; Changed = true; } return Changed; } }; } char InstSimplifier::ID = 0; INITIALIZE_PASS(InstSimplifier, "instsimplify", "Remove redundant instructions", false, false) char &llvm::InstructionSimplifierID = InstSimplifier::ID; // Public interface to the simplify instructions pass. FunctionPass *llvm::createInstructionSimplifierPass() { return new InstSimplifier(); } <|endoftext|>
<commit_before>#include "contentfactory.h" #include <iostream> ContentFactory::ContentFactory() { } ContentFactory::~ContentFactory() { } std::string ContentFactory::ReplaceImageTags(const std::string& input) { size_t currentIndex = 0; std::string result = input; currentIndex = result.find(kCFYImageTag, currentIndex); while (currentIndex < result.size()) { size_t closingIndex = result.find(kCFYCloseTag, currentIndex); if (closingIndex < result.size()) { size_t fileNameBeginIndex = result.find(" ", currentIndex); if (fileNameBeginIndex < closingIndex) { std::string imageTag = ""; fileNameBeginIndex++; size_t fileNameEndIndex = result.find(" ", fileNameBeginIndex); if (fileNameEndIndex > closingIndex) fileNameEndIndex = closingIndex; std::string fileName = result.substr(fileNameBeginIndex, fileNameEndIndex - fileNameBeginIndex); std::string alt; if (fileNameEndIndex < closingIndex) alt = input.substr(fileNameEndIndex + 1, closingIndex - fileNameEndIndex - 1); else alt = ""; imageTag.insert(imageTag.size(), "<p class=\"image\"><img src=\"images/"); imageTag.insert(imageTag.end(), fileName.begin(), fileName.end()); imageTag.insert(imageTag.size(), "\" alt=\""); imageTag.insert(imageTag.end(), alt.begin(), alt.end()); imageTag.insert(imageTag.size(), "\" /></p><p class=\"image_legend\">"); imageTag.insert(imageTag.end(), alt.begin(), alt.end()); imageTag.insert(imageTag.size(), "</p>"); result.erase(currentIndex, closingIndex - currentIndex + 1); result.insert(currentIndex, imageTag); } } currentIndex = result.find(kCFYImageTag, currentIndex + 1); } return result; } std::string ContentFactory::ReplaceLinkTags(const std::string &input, bool local) { size_t currentIndex = 0; std::string result = input; currentIndex = result.find(kCFYLinkTag, currentIndex); while (currentIndex < result.size()) { size_t closingIndex = result.find(kCFYCloseTag, currentIndex); if (closingIndex < result.size()) { size_t fileNameBeginIndex = result.find(" ", currentIndex); if (fileNameBeginIndex < closingIndex) { std::string linkTag = ""; fileNameBeginIndex++; size_t fileNameEndIndex = result.find(" ", fileNameBeginIndex); if (fileNameEndIndex > closingIndex) fileNameEndIndex = closingIndex; std::string fileName = result.substr(fileNameBeginIndex, fileNameEndIndex - fileNameBeginIndex); std::string title; if (fileNameEndIndex < closingIndex) title = result.substr(fileNameEndIndex + 1, closingIndex - fileNameEndIndex - 1); else title = ""; if (local && fileName.find("http") == std::string::npos) fileName += ".html"; linkTag.insert(linkTag.size(), "<a href=\""); linkTag.insert(linkTag.end(), fileName.begin(), fileName.end()); linkTag.insert(linkTag.size(), "\">"); linkTag.insert(linkTag.end(), title.begin(), title.end()); linkTag.insert(linkTag.size(), "</a>"); result.erase(currentIndex, closingIndex - currentIndex + 1); result.insert(currentIndex, linkTag); } } currentIndex = result.find(kCFYLinkTag, currentIndex + 1); } return result; } void ContentFactory::ReplaceInString(std::string &source, std::string search, const std::string replacement) { size_t pos = 0; while ((pos = source.find(search, pos)) != std::string::npos) { source.replace(pos, search.length(), replacement); pos += replacement.length(); } } void ContentFactory::SanitizeString(std::string &source) { // Ouch. This hurts. ReplaceInString(source, " ", "-"); ReplaceInString(source, "'", "-"); ReplaceInString(source, "\\", "-"); ReplaceInString(source, ":", "-"); ReplaceInString(source, "ç", "c"); ReplaceInString(source, "é", "e"); ReplaceInString(source, "ê", "e"); ReplaceInString(source, "à", "a"); ReplaceInString(source, "è", "e"); ReplaceInString(source, "--", "-"); ReplaceInString(source, "--", "-"); ReplaceInString(source, "--", "-"); } <commit_msg>core: fixed article names with points and underscores not exported properly<commit_after>#include "contentfactory.h" #include <iostream> ContentFactory::ContentFactory() { } ContentFactory::~ContentFactory() { } std::string ContentFactory::ReplaceImageTags(const std::string& input) { size_t currentIndex = 0; std::string result = input; currentIndex = result.find(kCFYImageTag, currentIndex); while (currentIndex < result.size()) { size_t closingIndex = result.find(kCFYCloseTag, currentIndex); if (closingIndex < result.size()) { size_t fileNameBeginIndex = result.find(" ", currentIndex); if (fileNameBeginIndex < closingIndex) { std::string imageTag = ""; fileNameBeginIndex++; size_t fileNameEndIndex = result.find(" ", fileNameBeginIndex); if (fileNameEndIndex > closingIndex) fileNameEndIndex = closingIndex; std::string fileName = result.substr(fileNameBeginIndex, fileNameEndIndex - fileNameBeginIndex); std::string alt; if (fileNameEndIndex < closingIndex) alt = input.substr(fileNameEndIndex + 1, closingIndex - fileNameEndIndex - 1); else alt = ""; imageTag.insert(imageTag.size(), "<p class=\"image\"><img src=\"images/"); imageTag.insert(imageTag.end(), fileName.begin(), fileName.end()); imageTag.insert(imageTag.size(), "\" alt=\""); imageTag.insert(imageTag.end(), alt.begin(), alt.end()); imageTag.insert(imageTag.size(), "\" /></p><p class=\"image_legend\">"); imageTag.insert(imageTag.end(), alt.begin(), alt.end()); imageTag.insert(imageTag.size(), "</p>"); result.erase(currentIndex, closingIndex - currentIndex + 1); result.insert(currentIndex, imageTag); } } currentIndex = result.find(kCFYImageTag, currentIndex + 1); } return result; } std::string ContentFactory::ReplaceLinkTags(const std::string &input, bool local) { size_t currentIndex = 0; std::string result = input; currentIndex = result.find(kCFYLinkTag, currentIndex); while (currentIndex < result.size()) { size_t closingIndex = result.find(kCFYCloseTag, currentIndex); if (closingIndex < result.size()) { size_t fileNameBeginIndex = result.find(" ", currentIndex); if (fileNameBeginIndex < closingIndex) { std::string linkTag = ""; fileNameBeginIndex++; size_t fileNameEndIndex = result.find(" ", fileNameBeginIndex); if (fileNameEndIndex > closingIndex) fileNameEndIndex = closingIndex; std::string fileName = result.substr(fileNameBeginIndex, fileNameEndIndex - fileNameBeginIndex); std::string title; if (fileNameEndIndex < closingIndex) title = result.substr(fileNameEndIndex + 1, closingIndex - fileNameEndIndex - 1); else title = ""; if (local && fileName.find("http") == std::string::npos) fileName += ".html"; linkTag.insert(linkTag.size(), "<a href=\""); linkTag.insert(linkTag.end(), fileName.begin(), fileName.end()); linkTag.insert(linkTag.size(), "\">"); linkTag.insert(linkTag.end(), title.begin(), title.end()); linkTag.insert(linkTag.size(), "</a>"); result.erase(currentIndex, closingIndex - currentIndex + 1); result.insert(currentIndex, linkTag); } } currentIndex = result.find(kCFYLinkTag, currentIndex + 1); } return result; } void ContentFactory::ReplaceInString(std::string &source, std::string search, const std::string replacement) { size_t pos = 0; while ((pos = source.find(search, pos)) != std::string::npos) { source.replace(pos, search.length(), replacement); pos += replacement.length(); } } void ContentFactory::SanitizeString(std::string &source) { // Ouch. This hurts. ReplaceInString(source, ".", "-"); ReplaceInString(source, "_", "-"); ReplaceInString(source, " ", "-"); ReplaceInString(source, "'", "-"); ReplaceInString(source, "\\", "-"); ReplaceInString(source, ":", "-"); ReplaceInString(source, "ç", "c"); ReplaceInString(source, "é", "e"); ReplaceInString(source, "ê", "e"); ReplaceInString(source, "à", "a"); ReplaceInString(source, "è", "e"); ReplaceInString(source, "--", "-"); ReplaceInString(source, "--", "-"); ReplaceInString(source, "--", "-"); } <|endoftext|>
<commit_before>#include "MoveDummy.h" #include "ObjectDummy.h" #include "BodyDummy.h" #include "ShapeCapsule.h" #include "Utils.h" #include "Engine.h" #include "Physics.h" #include "Game.h" #include "World.h" #define MOVE_DUMMY_IFPS (1.0f/100.0f) #define MOVE_DUMMY_CLAMP 89.9f #define MOVE_DUMMY_COLLISIONS 1<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "MoveDummy.h" #include "ObjectDummy.h" #include "BodyDummy.h" #include "ShapeCapsule.h" #include "Utils.h" #include "Engine.h" #include "Physics.h" #include "Game.h" #include "World.h" #define MOVE_DUMMY_IFPS (1.0f/100.0f) #define MOVE_DUMMY_CLAMP 89.9f #define MOVE_DUMMY_COLLISIONS 1 using namespace MathLib; CMoveDummy::CMoveDummy() //캯 { m_pObject = new CObjectDummy(); //һʵ m_pDummy = new CBodyDummy(); m_pShape = new CShapeCapsule(0.5f, 1.0f); SetCollisionMask(1); Clear(); }<|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_CORE_CHAINABLE_OBJECT_HPP #define STAN_MATH_REV_CORE_CHAINABLE_OBJECT_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core/chainable_alloc.hpp> #include <stan/math/rev/core/typedefs.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/typedefs.hpp> #include <vector> namespace stan { namespace math { /** * `chainable_object` hold another object is useful for connecting * the lifetime of a specific object to the chainable stack * * `chainable_object` objects should only be allocated with `new`. * `chainable_object` objects allocated on the stack will result * in a double free (`obj_` will get destructed once when the * chainable_object leaves scope and once when the chainable * stack memory is recovered). * * @tparam T type of object to hold */ template <typename T> class chainable_object : public chainable_alloc { private: plain_type_t<T> obj_; public: /** * Construct chainable object from another object * * @tparam S type of object to hold (must have the same plain type as `T`) */ template <typename S, require_same_t<plain_type_t<T>, plain_type_t<S>>* = nullptr> explicit chainable_object(S&& obj) : obj_(std::forward<S>(obj)) {} /** * Return a reference to the underlying object * * @return reference to underlying object */ inline T& get() noexcept { return obj_; } }; /** * Store the given object in a `chainable_object` so it is destructed * only when the chainable stack memory is recovered and return * a pointer to the underlying object * * @tparam T type of object to hold * @param obj object to hold * @return pointer to object held in `chainable_object` */ template <typename T> auto make_chainable_ptr(T&& obj) { auto ptr = new chainable_object<T>(std::forward<T>(obj)); return &ptr->get(); } } // namespace math } // namespace stan #endif <commit_msg>Added const version of get (Issue #2101)<commit_after>#ifndef STAN_MATH_REV_CORE_CHAINABLE_OBJECT_HPP #define STAN_MATH_REV_CORE_CHAINABLE_OBJECT_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core/chainable_alloc.hpp> #include <stan/math/rev/core/typedefs.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/typedefs.hpp> #include <vector> namespace stan { namespace math { /** * `chainable_object` hold another object is useful for connecting * the lifetime of a specific object to the chainable stack * * `chainable_object` objects should only be allocated with `new`. * `chainable_object` objects allocated on the stack will result * in a double free (`obj_` will get destructed once when the * chainable_object leaves scope and once when the chainable * stack memory is recovered). * * @tparam T type of object to hold */ template <typename T> class chainable_object : public chainable_alloc { private: plain_type_t<T> obj_; public: /** * Construct chainable object from another object * * @tparam S type of object to hold (must have the same plain type as `T`) */ template <typename S, require_same_t<plain_type_t<T>, plain_type_t<S>>* = nullptr> explicit chainable_object(S&& obj) : obj_(std::forward<S>(obj)) {} /** * Return a reference to the underlying object * * @return reference to underlying object */ inline auto& get() noexcept { return obj_; } inline const auto& get() const noexcept { return obj_; } }; /** * Store the given object in a `chainable_object` so it is destructed * only when the chainable stack memory is recovered and return * a pointer to the underlying object * * @tparam T type of object to hold * @param obj object to hold * @return pointer to object held in `chainable_object` */ template <typename T> auto make_chainable_ptr(T&& obj) { auto ptr = new chainable_object<T>(std::forward<T>(obj)); return &ptr->get(); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before> #ifndef DUNE_DETAILEL_DISCRETIZATIONS_MAPPER_MULTISCALE_HH #define DUNE_DETAILEL_DISCRETIZATIONS_MAPPER_MULTISCALE_HH // system #include <map> #include <sstream> #include <vector> // dune-common #include <dune/common/exceptions.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace Mapper { template <class IndexImp = size_t> class Multiscale { public: typedef IndexImp IndexType; typedef Multiscale<IndexType> ThisType; static const std::string id; Multiscale() : subdomainMap_(0) , numSubdomains_(0) , size_(0) , prepared_(false) , finalized_(false) { } void prepare() { assert(!finalized_); if (!prepared_) { subdomainMap_ = new std::map<unsigned int, IndexType>(); prepared_ = true; } return; } // void prepare() void add(const unsigned int subdomain, const IndexType size) { assert(prepared_); assert(!finalized_); assert(0 <= subdomain); assert(0 <= size); // create entry for this subdomain if needed (doing this explicitly instead of just using insert only to increment // size) if (subdomainMap_->find(subdomain) == subdomainMap_->end()) { subdomainMap_->insert(std::pair<unsigned int, IndexType>(subdomain, size)); ++numSubdomains_; } return; } // void add(const unsigned int subdomain, const IndexType size) void finalize() { assert(prepared_); if (!finalized_) { // test for consecutive numbering of subdomains and create vector of local sizes for (unsigned int subdomain = 0; subdomain < numSubdomains_; ++subdomain) { const typename std::map<unsigned int, IndexType>::const_iterator result = subdomainMap_->find(subdomain); if (result == subdomainMap_->end()) { std::stringstream msg; msg << "Error in " << id << ": numbering of subdomains has to be consecutive upon calling finalize!"; DUNE_THROW(Dune::InvalidStateException, msg.str()); } else { const IndexType& localSize = result->second; localSizes_.push_back(localSize); globalStartIndices_.push_back(size_); size_ += localSize; } } // // test for consecutive numbering of subdomains and create vector of local sizes // clean up delete subdomainMap_; finalized_ = true; } return; } // void finalize() unsigned int numSubdomains() const { assert(finalized_); return numSubdomains_; } IndexType size() const { assert(finalized_); return size_; } IndexType toGlobal(const unsigned int subdomain, const IndexType localIndex) const { assert(finalized_); assert(subdomain < numSubdomains()); assert(0 <= localIndex); assert(localIndex < localSizes_[subdomain]); return globalStartIndices_[subdomain] + localIndex; } // IndexType toGlobal(const unsigned int subdomain, const InedxType localIndex) const private: std::map<unsigned int, IndexType>* subdomainMap_; unsigned int numSubdomains_; unsigned int size_; std::vector<IndexType> localSizes_; std::vector<IndexType> globalStartIndices_; bool prepared_; bool finalized_; }; // class Multiscale template <class IndexType> const std::string Multiscale<IndexType>::id = "detailed.discretizations.mapper.multiscale"; } // namespace Mapper } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILEL_DISCRETIZATIONS_MAPPER_MULTISCALE_HH <commit_msg>[mapper.multiscale] replaced unsigned int by IndexType<commit_after> #ifndef DUNE_DETAILEL_DISCRETIZATIONS_MAPPER_MULTISCALE_HH #define DUNE_DETAILEL_DISCRETIZATIONS_MAPPER_MULTISCALE_HH // system #include <map> #include <sstream> #include <vector> // dune-common #include <dune/common/exceptions.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace Mapper { template <class IndexImp = size_t> class Multiscale { public: typedef IndexImp IndexType; typedef Multiscale<IndexType> ThisType; static const std::string id; Multiscale() : subdomainMap_(0) , numSubdomains_(0) , size_(0) , prepared_(false) , finalized_(false) { } void prepare() { assert(!finalized_); if (!prepared_) { subdomainMap_ = new std::map<unsigned int, IndexType>(); prepared_ = true; } return; } // void prepare() void add(const unsigned int subdomain, const IndexType size) { assert(prepared_); assert(!finalized_); assert(0 <= subdomain); assert(0 <= size); // create entry for this subdomain if needed (doing this explicitly instead of just using insert only to increment // size) if (subdomainMap_->find(subdomain) == subdomainMap_->end()) { subdomainMap_->insert(std::pair<unsigned int, IndexType>(subdomain, size)); ++numSubdomains_; } return; } // void add(const unsigned int subdomain, const IndexType size) void finalize() { assert(prepared_); if (!finalized_) { // test for consecutive numbering of subdomains and create vector of local sizes for (unsigned int subdomain = 0; subdomain < numSubdomains_; ++subdomain) { const typename std::map<unsigned int, IndexType>::const_iterator result = subdomainMap_->find(subdomain); if (result == subdomainMap_->end()) { std::stringstream msg; msg << "Error in " << id << ": numbering of subdomains has to be consecutive upon calling finalize!"; DUNE_THROW(Dune::InvalidStateException, msg.str()); } else { const IndexType& localSize = result->second; localSizes_.push_back(localSize); globalStartIndices_.push_back(size_); size_ += localSize; } } // // test for consecutive numbering of subdomains and create vector of local sizes // clean up delete subdomainMap_; finalized_ = true; } return; } // void finalize() IndexType numSubdomains() const { assert(finalized_); return numSubdomains_; } IndexType size() const { assert(finalized_); return size_; } IndexType toGlobal(const unsigned int subdomain, const IndexType localIndex) const { assert(finalized_); assert(subdomain < numSubdomains()); assert(0 <= localIndex); assert(localIndex < localSizes_[subdomain]); return globalStartIndices_[subdomain] + localIndex; } // IndexType toGlobal(const unsigned int subdomain, const InedxType localIndex) const private: std::map<unsigned int, IndexType>* subdomainMap_; unsigned int numSubdomains_; unsigned int size_; std::vector<IndexType> localSizes_; std::vector<IndexType> globalStartIndices_; bool prepared_; bool finalized_; }; // class Multiscale template <class IndexType> const std::string Multiscale<IndexType>::id = "detailed.discretizations.mapper.multiscale"; } // namespace Mapper } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILEL_DISCRETIZATIONS_MAPPER_MULTISCALE_HH <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: hiranges.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2004-01-06 18:59:56 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_HIRANGES_HXX #define SC_HIRANGES_HXX #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif //================================================================== struct ScHighlightEntry { ScRange aRef; Color aColor; ScHighlightEntry( const ScRange& rR, const Color& rC ) : aRef(rR), aColor(rC) {} }; class ScHighlightRanges { List aEntries; public: ScHighlightRanges(); ~ScHighlightRanges(); ULONG Count() const { return aEntries.Count(); } void Insert( ScHighlightEntry* pNew ) { aEntries.Insert(pNew, LIST_APPEND); } ScHighlightEntry* GetObject( ULONG nIndex ) const { return (ScHighlightEntry*)aEntries.GetObject(nIndex); } }; #endif <commit_msg>INTEGRATION: CWS rowlimit (1.1.1.1.346); FILE MERGED 2004/01/21 14:31:57 er 1.1.1.1.346.2: RESYNC: (1.1.1.1-1.2); FILE MERGED 2003/11/28 19:47:58 er 1.1.1.1.346.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>/************************************************************************* * * $RCSfile: hiranges.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:34:26 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_HIRANGES_HXX #define SC_HIRANGES_HXX #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif //================================================================== struct ScHighlightEntry { ScRange aRef; Color aColor; ScHighlightEntry( const ScRange& rR, const Color& rC ) : aRef(rR), aColor(rC) {} }; class ScHighlightRanges { List aEntries; public: ScHighlightRanges(); ~ScHighlightRanges(); ULONG Count() const { return aEntries.Count(); } void Insert( ScHighlightEntry* pNew ) { aEntries.Insert(pNew, LIST_APPEND); } ScHighlightEntry* GetObject( ULONG nIndex ) const { return (ScHighlightEntry*)aEntries.GetObject(nIndex); } }; #endif <|endoftext|>
<commit_before>#include "GUIHelper.h" #include <QDialog> #include <QApplication> #include <QFormLayout> #include <QLabel> #include <QDialogButtonBox> #include <QDebug> void GUIHelper::showMessage(QString title, QString message, QMap<QString, QString> add_info) { //create dialog QDialog* dialog = new QDialog(QApplication::activeWindow()); dialog->window()->setWindowTitle(title); QGridLayout* layout = new QGridLayout(); dialog->window()->setLayout(layout); //add content int row = 0; layout->addWidget(new QLabel("message:"),row ,0, Qt::AlignLeft|Qt::AlignTop); layout->addWidget(new QLabel(message),row ,1); foreach(QString key, add_info.keys()) { ++row; layout->addWidget(new QLabel(key + ":"),row ,0, Qt::AlignLeft|Qt::AlignTop); layout->addWidget(new QLabel(add_info[key]),row ,1); } //show dialog->exec(); } QSharedPointer<QDialog> GUIHelper::showWidgetAsDialog(QWidget* widget, QString title, bool buttons, bool modal) { QSharedPointer<QDialog> dialog = QSharedPointer<QDialog>(new QDialog(QApplication::activeWindow())); dialog->setWindowFlags(Qt::Window); dialog->setWindowTitle(title); dialog->setLayout(new QBoxLayout(QBoxLayout::TopToBottom)); dialog->layout()->setMargin(3); dialog->layout()->addWidget(widget); //add buttons if (buttons) { QDialogButtonBox* button_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); dialog->connect(button_box, SIGNAL(accepted()), dialog.data(), SLOT(accept())); dialog->connect(button_box, SIGNAL(rejected()), dialog.data(), SLOT(reject())); dialog->layout()->addWidget(button_box); } //show dialog if (modal) { dialog->exec(); } else { dialog->show(); } return dialog; } void GUIHelper::styleSplitter(QSplitter* splitter) { splitter->setHandleWidth(1); splitter->setStyleSheet("QSplitter::handle { background-color: #666666; margin: 1px; }"); } void GUIHelper::resizeTableCells(QTableWidget* widget, int max_col_width) { //resize columns width widget->resizeColumnsToContents(); //restrict width if (max_col_width>0) { for (int i=0; i<widget->columnCount(); ++i) { if (widget->columnWidth(i)>max_col_width) { widget->setColumnWidth(i, max_col_width); } } } //row height widget->resizeRowToContents(0); for (int i=1; i<widget->rowCount(); ++i) { widget->setRowHeight(i, widget->rowHeight(0)); } } QFrame* GUIHelper::horizontalLine() { QFrame* line = new QFrame(); line->setObjectName("line"); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); line->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); line->setMinimumHeight(3); return line; } <commit_msg>GUIHelper::resizeTableCells - Fixed bug in row height calculation.<commit_after>#include "GUIHelper.h" #include <QDialog> #include <QApplication> #include <QFormLayout> #include <QLabel> #include <QDialogButtonBox> #include <QDebug> void GUIHelper::showMessage(QString title, QString message, QMap<QString, QString> add_info) { //create dialog QDialog* dialog = new QDialog(QApplication::activeWindow()); dialog->window()->setWindowTitle(title); QGridLayout* layout = new QGridLayout(); dialog->window()->setLayout(layout); //add content int row = 0; layout->addWidget(new QLabel("message:"),row ,0, Qt::AlignLeft|Qt::AlignTop); layout->addWidget(new QLabel(message),row ,1); foreach(QString key, add_info.keys()) { ++row; layout->addWidget(new QLabel(key + ":"),row ,0, Qt::AlignLeft|Qt::AlignTop); layout->addWidget(new QLabel(add_info[key]),row ,1); } //show dialog->exec(); } QSharedPointer<QDialog> GUIHelper::showWidgetAsDialog(QWidget* widget, QString title, bool buttons, bool modal) { QSharedPointer<QDialog> dialog = QSharedPointer<QDialog>(new QDialog(QApplication::activeWindow())); dialog->setWindowFlags(Qt::Window); dialog->setWindowTitle(title); dialog->setLayout(new QBoxLayout(QBoxLayout::TopToBottom)); dialog->layout()->setMargin(3); dialog->layout()->addWidget(widget); //add buttons if (buttons) { QDialogButtonBox* button_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); dialog->connect(button_box, SIGNAL(accepted()), dialog.data(), SLOT(accept())); dialog->connect(button_box, SIGNAL(rejected()), dialog.data(), SLOT(reject())); dialog->layout()->addWidget(button_box); } //show dialog if (modal) { dialog->exec(); } else { dialog->show(); } return dialog; } void GUIHelper::styleSplitter(QSplitter* splitter) { splitter->setHandleWidth(1); splitter->setStyleSheet("QSplitter::handle { background-color: #666666; margin: 1px; }"); } void GUIHelper::resizeTableCells(QTableWidget* widget, int max_col_width) { //resize columns width widget->resizeColumnsToContents(); //restrict width if (max_col_width>0) { for (int i=0; i<widget->columnCount(); ++i) { if (widget->columnWidth(i)>max_col_width) { widget->setColumnWidth(i, max_col_width); } } } //determine row height int height = -1; for (int i=0; i<widget->rowCount(); ++i) { if (!widget->isRowHidden(i)) { widget->resizeRowToContents(i); height = widget->rowHeight(i); break; } } //set row height if (height!=-1) { for (int i=0; i<widget->rowCount(); ++i) { widget->setRowHeight(i, height); } } } QFrame* GUIHelper::horizontalLine() { QFrame* line = new QFrame(); line->setObjectName("line"); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); line->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); line->setMinimumHeight(3); return line; } <|endoftext|>
<commit_before>#ifndef PYOSMIUM_GENERIC_HANDLER_HPP #define PYOSMIUM_GENERIC_HANDLER_HPP #include <osmium/area/assembler.hpp> #include <osmium/area/multipolygon_collector.hpp> #include <osmium/handler.hpp> #include <osmium/handler/node_locations_for_ways.hpp> #include <osmium/index/map/all.hpp> #include <osmium/io/any_input.hpp> #include <osmium/io/file.hpp> #include <osmium/visitor.hpp> #include <boost/python.hpp> typedef osmium::index::map::Map<osmium::unsigned_object_id_type, osmium::Location> index_type; class BaseHandler : public osmium::handler::Handler { protected: enum pre_handler { no_handler, location_handler, area_handler }; public: // handler functions virtual void node(const osmium::Node&)= 0; virtual void way(const osmium::Way&) = 0; virtual void relation(const osmium::Relation&) = 0; virtual void changeset(const osmium::Changeset&) = 0; virtual void area(const osmium::Area&) = 0; private: void apply_with_location(osmium::io::Reader &r, const std::string &idx) { const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance(); std::unique_ptr<index_type> index = map_factory.create_map(idx); osmium::handler::NodeLocationsForWays<index_type> location_handler(*index); location_handler.ignore_errors(); osmium::apply(r, location_handler, *this); } void apply_with_area(osmium::io::Reader &r, osmium::area::MultipolygonCollector<osmium::area::Assembler> &collector, const std::string &idx) { const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance(); std::unique_ptr<index_type> index = map_factory.create_map(idx); osmium::handler::NodeLocationsForWays<index_type> location_handler(*index); location_handler.ignore_errors(); osmium::apply(r, location_handler, *this, collector.handler([this](const osmium::memory::Buffer& area_buffer) { osmium::apply(area_buffer, *this); }) ); } protected: void apply(const osmium::io::File &file, osmium::osm_entity_bits::type types, pre_handler pre = no_handler, const std::string &idx = "sparse_mem_array") { switch (pre) { case no_handler: { osmium::io::Reader reader(file, types); osmium::apply(reader, *this); reader.close(); break; } case location_handler: { osmium::io::Reader reader(file, types); apply_with_location(reader, idx); reader.close(); break; } case area_handler: { osmium::area::Assembler::config_type assembler_config; osmium::area::MultipolygonCollector<osmium::area::Assembler> collector(assembler_config); osmium::io::Reader reader1(file); collector.read_relations(reader1); reader1.close(); osmium::io::Reader reader2(file); apply_with_area(reader2, collector, idx); reader2.close(); break; } } } }; using namespace boost::python; struct SimpleHandlerWrap: BaseHandler, wrapper<BaseHandler> { void node(const osmium::Node& node) override { if (!m_has_node_cb) return; if (override f = this->get_override("node")) { f(boost::ref(node)); } } void way(const osmium::Way& way) { if (override f = this->get_override("way")) f(boost::ref(way)); } void relation(const osmium::Relation& rel) { if (override f = this->get_override("relation")) f(boost::ref(rel)); } void changeset(const osmium::Changeset& cs) { if (override f = this->get_override("changeset")) f(boost::ref(cs)); } void area(const osmium::Area& area) { if (override f = this->get_override("area")) f(boost::ref(area)); } void apply_file(const std::string &filename, bool locations = false, const std::string &idx = "sparse_mem_array") { apply_object(osmium::io::File(filename), locations, idx); } void apply_buffer(const boost::python::object &buf, const boost::python::str &format, bool locations = false, const std::string &idx = "sparse_mem_array") { Py_buffer pybuf; PyObject_GetBuffer(buf.ptr(), &pybuf, PyBUF_C_CONTIGUOUS); size_t len = (size_t) pybuf.len; const char *cbuf = reinterpret_cast<const char *>(pybuf.buf); const char *cfmt = boost::python::extract<const char *>(format); apply_object(osmium::io::File(cbuf, len, cfmt), locations, idx); } private: void apply_object(osmium::io::File file, bool locations, const std::string &idx) { osmium::osm_entity_bits::type entities = osmium::osm_entity_bits::nothing; BaseHandler::pre_handler handler = locations? BaseHandler::location_handler :BaseHandler::no_handler; m_has_node_cb = hasfunc("node"); if (hasfunc("area")) { entities = osmium::osm_entity_bits::object; handler = BaseHandler::area_handler; } else { if (locations || m_has_node_cb) entities |= osmium::osm_entity_bits::node; if (hasfunc("way")) entities |= osmium::osm_entity_bits::way; if (hasfunc("relation")) entities |= osmium::osm_entity_bits::relation; } if (hasfunc("changeset")) entities |= osmium::osm_entity_bits::changeset; apply(file, entities, handler, idx); } bool hasfunc(char const *name) { reference_existing_object::apply<SimpleHandlerWrap*>::type converter; PyObject* obj = converter( this ); if (PyObject_HasAttrString(obj, name)) { auto o = boost::python::object(handle<>(obj)); return o.attr(name) != boost::python::object(); } return false; } bool m_has_node_cb; }; #endif <commit_msg>precheck which handlers are implemented<commit_after>#ifndef PYOSMIUM_GENERIC_HANDLER_HPP #define PYOSMIUM_GENERIC_HANDLER_HPP #include <osmium/area/assembler.hpp> #include <osmium/area/multipolygon_collector.hpp> #include <osmium/handler.hpp> #include <osmium/handler/node_locations_for_ways.hpp> #include <osmium/index/map/all.hpp> #include <osmium/io/any_input.hpp> #include <osmium/io/file.hpp> #include <osmium/visitor.hpp> #include <boost/python.hpp> typedef osmium::index::map::Map<osmium::unsigned_object_id_type, osmium::Location> index_type; class BaseHandler : public osmium::handler::Handler { protected: enum pre_handler { no_handler, location_handler, area_handler }; public: // handler functions virtual void node(const osmium::Node&)= 0; virtual void way(const osmium::Way&) = 0; virtual void relation(const osmium::Relation&) = 0; virtual void changeset(const osmium::Changeset&) = 0; virtual void area(const osmium::Area&) = 0; private: void apply_with_location(osmium::io::Reader &r, const std::string &idx) { const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance(); std::unique_ptr<index_type> index = map_factory.create_map(idx); osmium::handler::NodeLocationsForWays<index_type> location_handler(*index); location_handler.ignore_errors(); osmium::apply(r, location_handler, *this); } void apply_with_area(osmium::io::Reader &r, osmium::area::MultipolygonCollector<osmium::area::Assembler> &collector, const std::string &idx) { const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance(); std::unique_ptr<index_type> index = map_factory.create_map(idx); osmium::handler::NodeLocationsForWays<index_type> location_handler(*index); location_handler.ignore_errors(); osmium::apply(r, location_handler, *this, collector.handler([this](const osmium::memory::Buffer& area_buffer) { osmium::apply(area_buffer, *this); }) ); } protected: void apply(const osmium::io::File &file, osmium::osm_entity_bits::type types, pre_handler pre = no_handler, const std::string &idx = "sparse_mem_array") { switch (pre) { case no_handler: { osmium::io::Reader reader(file, types); osmium::apply(reader, *this); reader.close(); break; } case location_handler: { osmium::io::Reader reader(file, types); apply_with_location(reader, idx); reader.close(); break; } case area_handler: { osmium::area::Assembler::config_type assembler_config; osmium::area::MultipolygonCollector<osmium::area::Assembler> collector(assembler_config); osmium::io::Reader reader1(file); collector.read_relations(reader1); reader1.close(); osmium::io::Reader reader2(file); apply_with_area(reader2, collector, idx); reader2.close(); break; } } } }; using namespace boost::python; struct SimpleHandlerWrap: BaseHandler, wrapper<BaseHandler> { void node(const osmium::Node& node) override { if (!(m_callbacks & osmium::osm_entity_bits::node)) return; if (override f = this->get_override("node")) { f(boost::ref(node)); } } void way(const osmium::Way& way) { if (!(m_callbacks & osmium::osm_entity_bits::way)) return; if (override f = this->get_override("way")) f(boost::ref(way)); } void relation(const osmium::Relation& rel) { if (!(m_callbacks & osmium::osm_entity_bits::relation)) return; if (override f = this->get_override("relation")) f(boost::ref(rel)); } void changeset(const osmium::Changeset& cs) { if (!(m_callbacks & osmium::osm_entity_bits::changeset)) return; if (override f = this->get_override("changeset")) f(boost::ref(cs)); } void area(const osmium::Area& area) { if (!(m_callbacks & osmium::osm_entity_bits::area)) return; if (override f = this->get_override("area")) f(boost::ref(area)); } void apply_file(const std::string &filename, bool locations = false, const std::string &idx = "sparse_mem_array") { apply_object(osmium::io::File(filename), locations, idx); } void apply_buffer(const boost::python::object &buf, const boost::python::str &format, bool locations = false, const std::string &idx = "sparse_mem_array") { Py_buffer pybuf; PyObject_GetBuffer(buf.ptr(), &pybuf, PyBUF_C_CONTIGUOUS); size_t len = (size_t) pybuf.len; const char *cbuf = reinterpret_cast<const char *>(pybuf.buf); const char *cfmt = boost::python::extract<const char *>(format); apply_object(osmium::io::File(cbuf, len, cfmt), locations, idx); } private: void apply_object(osmium::io::File file, bool locations, const std::string &idx) { osmium::osm_entity_bits::type entities = osmium::osm_entity_bits::nothing; BaseHandler::pre_handler handler = locations? BaseHandler::location_handler :BaseHandler::no_handler; m_callbacks = osmium::osm_entity_bits::nothing; if (hasfunc("node")) m_callbacks |= osmium::osm_entity_bits::node; if (hasfunc("way")) m_callbacks |= osmium::osm_entity_bits::way; if (hasfunc("relation")) m_callbacks |= osmium::osm_entity_bits::relation; if (hasfunc("area")) m_callbacks |= osmium::osm_entity_bits::area; if (hasfunc("changeset")) m_callbacks |= osmium::osm_entity_bits::changeset; if (m_callbacks & osmium::osm_entity_bits::area) { entities = osmium::osm_entity_bits::object; handler = BaseHandler::area_handler; } else { if (locations || m_callbacks & osmium::osm_entity_bits::node) entities |= osmium::osm_entity_bits::node; if (m_callbacks & osmium::osm_entity_bits::way) entities |= osmium::osm_entity_bits::way; if (m_callbacks & osmium::osm_entity_bits::relation) entities |= osmium::osm_entity_bits::relation; } if (m_callbacks & osmium::osm_entity_bits::changeset) entities |= osmium::osm_entity_bits::changeset; apply(file, entities, handler, idx); } bool hasfunc(char const *name) { reference_existing_object::apply<SimpleHandlerWrap*>::type converter; PyObject* obj = converter( this ); if (PyObject_HasAttrString(obj, name)) { auto o = boost::python::object(handle<>(obj)); return o.attr(name) != boost::python::object(); } return false; } osmium::osm_entity_bits::type m_callbacks; }; #endif <|endoftext|>
<commit_before>#include "ItemPU.hpp" #include "item.pb.h" #include <sqlpp11/sqlpp11.h> #include <sqlpp11/postgresql/insert.h> #include "sql_schema/items.h" #include "sql_schema/parameters.h" using namespace pb; namespace eedb{ namespace pu{ constexpr schema::items i; ItemPU::ItemPU(){ } void ItemPU::process(ClientRequest &msgReq) { DB db; process(db, msgReq); } void ItemPU::process(DB &db, ClientRequest &msgReq) { // Check if this is the message that handler wants Q_ASSERT( msgReq.data_case() == pb::ClientRequest::kItemReqFieldNumber ); Q_ASSERT( msgReq.has_itemreq() ); auto req = msgReq.itemreq(); if(user()->isOffline()) sendServerError(pb::Error_UserOffilne); else{ auto msgType = req.action_case(); switch ( msgType ) { case ItemRequest::kAdd: handle_add(db, *req.mutable_add() ); break; case ItemRequest::kGet: // handle_login(db, req.login() ); break; case ItemRequest::kModify: // handle_logout(db, req.logout() ); break; case ItemRequest::kRemove: // handle_get(db, req.get() ); break; case UserReq::ACTION_NOT_SET: sendServerError(pb::Error_NoActionChoosen); break; } } } void ItemPU::handle_add(DB &db, ItemRequest_Add &msg) { constexpr schema::items it; auth::AccesControl stat(user()->id()); bool allow = false; if(msg.has_is_private() && msg.is_private()) allow = stat.checkUserAction<schema::items>(db, "add_private_item"); else allow = stat.checkUserAction<schema::items>(db, "add_public_item"); if(allow){ run_saveItemInDb(db, msg); } else { sendServerError(pb::Error_AccesDeny); } } #include <QJsonObject> void ItemPU::run_saveItemInDb(DB &db, ItemRequest_Add &msg) { //check parameters QJsonObject params; if(msg.parameters_size() > 0){ static constexpr schema::parameters p; std::vector<quint64> parametersIds; for(const auto &parameter:msg.parameters()) parametersIds.push_back( parameter.id() ); // check is all parameters are avalible in database bool allAvalible = db( select(count(p.uid)) .from(p) .where(p.uid.in(sqlpp::value_list(parametersIds)))) .front().count == parametersIds.size(); if(!allAvalible){ add_response()->mutable_itemres()->set_code(pb::ItemResponse_Replay_ParameterDontExists); return; } for(const auto &parameter:msg.parameters()){ params.insert("id", parameter.id() ); } } auto res = add_response()->mutable_itemres(); auto prep = db.prepare(sqlpp::postgresql::insert_into(i).set( i.name = parameter(i.name), i.category_id = msg.category_id(), i.symbol = parameter(i.symbol), i.owner = user()->id(), i.description = parameter(i.description), i.params = parameter(i.params) ).returning(i.uid) ); prep.params.name = msg.name(); prep.params.symbol = msg.symbol(); if(msg.has_description() && !msg.description().empty()) prep.params.description = msg.description(); auto return_value = db(prep); if(msg.has_returning_id() && msg.returning_id()) res->set_id(return_value.front().uid); res->set_code(ItemResponse_Replay_OK); } } } <commit_msg>fix build<commit_after>#include "ItemPU.hpp" #include "item.pb.h" #include <sqlpp11/sqlpp11.h> #include <sqlpp11/postgresql/insert.h> #include "sql_schema/items.h" #include "sql_schema/parameters.h" using namespace pb; namespace eedb{ namespace pu{ constexpr schema::items i; ItemPU::ItemPU(){ } void ItemPU::process(ClientRequest &msgReq) { DB db; process(db, msgReq); } void ItemPU::process(DB &db, ClientRequest &msgReq) { // Check if this is the message that handler wants Q_ASSERT( msgReq.data_case() == pb::ClientRequest::kItemReqFieldNumber ); Q_ASSERT( msgReq.has_itemreq() ); auto req = msgReq.itemreq(); if(user()->isOffline()) sendServerError(pb::Error_UserOffilne); else{ auto msgType = req.action_case(); switch ( msgType ) { case ItemRequest::kAdd: handle_add(db, *req.mutable_add() ); break; case ItemRequest::kGet: // handle_login(db, req.login() ); break; case ItemRequest::kModify: // handle_logout(db, req.logout() ); break; case ItemRequest::kRemove: // handle_get(db, req.get() ); break; case UserReq::ACTION_NOT_SET: sendServerError(pb::Error_NoActionChoosen); break; } } } void ItemPU::handle_add(DB &db, ItemRequest_Add &msg) { constexpr schema::items it; auth::AccesControl stat(user()->id()); bool allow = false; if(msg.has_is_private() && msg.is_private()) allow = stat.checkUserAction<schema::items>(db, "add_private_item"); else allow = stat.checkUserAction<schema::items>(db, "add_public_item"); if(allow){ run_saveItemInDb(db, msg); } else { sendServerError(pb::Error_AccesDeny); } } #include <QJsonObject> void ItemPU::run_saveItemInDb(DB &db, ItemRequest_Add &msg) { //check parameters QJsonObject params; if(msg.parameters_size() > 0){ static constexpr schema::parameters p; std::vector<quint64> parametersIds; for(const auto &parameter:msg.parameters()) parametersIds.push_back( parameter.id() ); // check is all parameters are avalible in database bool allAvalible = db( select(count(p.uid)) .from(p) .where(p.uid.in(sqlpp::value_list(parametersIds)))) .front().count == parametersIds.size(); if(!allAvalible){ add_response()->mutable_itemres()->set_code(pb::ItemResponse_Replay_ParameterDontExists); return; } // for(const auto &parameter:msg.parameters()){ // params.insert("id", parameter.id() ); // } } auto res = add_response()->mutable_itemres(); auto prep = db.prepare(sqlpp::postgresql::insert_into(i).set( i.name = parameter(i.name), i.category_id = msg.category_id(), i.symbol = parameter(i.symbol), i.owner = user()->id(), i.description = parameter(i.description), i.params = parameter(i.params) ).returning(i.uid) ); prep.params.name = msg.name(); prep.params.symbol = msg.symbol(); if(msg.has_description() && !msg.description().empty()) prep.params.description = msg.description(); auto return_value = db(prep); if(msg.has_returning_id() && msg.returning_id()) res->set_id(return_value.front().uid); res->set_code(ItemResponse_Replay_OK); } } } <|endoftext|>
<commit_before>#include "HPACK.h" #include "hpack_table.h" #include "gtest/gtest.h" #include <string.h> #include "picojson/picojson.h" #include <fstream> #include <iostream> #include <iterator> TEST(encode_intTest, NormalTest) { uint8_t dst[10]; uint8_t expect[][5] = { {0x01, 0x00}, {0x0f, 0x01}, //{0x1f, 0xa1, 0x8d, 0xb7, 0x01}, }; uint64_t len = encode_int(dst, 1, 1); EXPECT_EQ(2, len); EXPECT_TRUE(0 == std::memcmp(dst, expect[0], len)); len = encode_int(dst, 16, 4); EXPECT_EQ(2, len); EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len)); /* len = encode_int(dst, 3000000, 5); EXPECT_EQ(5, len); EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len)); */ } TEST(decode_intTest, NormalTest) { uint32_t dst = 0; uint8_t data[][5] = { {0x01, 0x00}, {0x0f, 0x01}, }; EXPECT_EQ(1, decode_int(data[0], 1)); EXPECT_EQ(16, decode_int(data[1], 4)); } const static std::string TestCases[] = { "hpack-test-case/haskell-http2-naive/", "hpack-test-case/haskell-http2-naive-huffman/", "hpack-test-case/haskell-http2-static/", "hpack-test-case/haskell-http2-static-huffman/", "hpack-test-case/haskell-http2-linear/", "hpack-test-case/haskell-http2-linear-huffman/", }; const static std::string out_tmp_file = "filename.txt"; bool read_json_files(std::vector<std::string> &jsons, const std::string testcase) { std::string call_str = "ls " + testcase + " > " + out_tmp_file; int len = call_str.length(); char call[70]; memcpy(call, call_str.c_str(), len+1); system(call); std::ifstream fnames(out_tmp_file); if (fnames.fail()) { std::cerr << "fail to open" << out_tmp_file << std::endl; return false; } std::string field; while (std::getline(fnames, field)) { jsons.push_back(field); } return true; } bool read_json_as_pico(picojson::value& v, const std::string path) { std::ifstream ifs(path); if (ifs.fail()) { std::cerr << "fail to open" << std::endl; return false; } std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); std::string err = picojson::parse(v, str); if (! err.empty()) { std::cerr << err << std::endl; return false; } return true; } bool read_header_wire(std::vector<header>& ans_headers, std::string& wire, picojson::array::iterator it_seqno) { picojson::object obj_in = it_seqno->get<picojson::object>(); wire = obj_in["wire"].to_str(); picojson::array json_headers = obj_in["headers"].get<picojson::array>(); picojson::array::iterator it_headers; for (it_headers = json_headers.begin(); it_headers != json_headers.end(); it_headers++) { picojson::object content = it_headers->get<picojson::object>(); picojson::object::iterator it = content.begin(); ans_headers.push_back(header(it->first, it->second.to_str())); } return true; } bool wire2byte(uint8_t *wire_byte, const std::string wire) { int len = wire.length(); for (int i = 0; i < len; i += 2) { *(wire_byte+i/2) = (uint8_t)std::stoi(wire.substr(i, 2).c_str(), nullptr, 16); } return true; } void detect_testcase_type(bool &from_header, bool &from_static, bool &is_huffman,const std::string testcase) { from_header = std::string::npos != testcase.find("linear", 0); from_static = from_header || std::string::npos != testcase.find("static", 0); is_huffman = std::string::npos != testcase.find("huffman", 0); } TEST(encodeTest, NormalTest) { for (const std::string testcase : TestCases) { std::vector<std::string> jsons; bool err = read_json_files(jsons, testcase); if (!err) { } bool from_header, from_static, is_huffman; detect_testcase_type(from_header, from_static, is_huffman, testcase); std::cout << testcase << " " << from_header << from_static << is_huffman << std::endl; Table* table = new Table(); for (std::string json_file : jsons) { picojson::value v; err = read_json_as_pico(v, testcase + json_file); if (!err) { } picojson::object obj = v.get<picojson::object>(); picojson::array arr = obj["cases"].get<picojson::array>(); picojson::array::iterator it_seqno; for (it_seqno = arr.begin(); it_seqno != arr.end(); it_seqno++) { std::string wire; std::vector<header> ans_headers; err = read_header_wire(ans_headers, wire, it_seqno); if (!err) { } uint8_t dst[20000]; int64_t len = hpack_encode(dst, ans_headers,from_static, from_header, is_huffman, table, -1); uint8_t *wire_byte = new uint8_t[wire.length()/2]; err = wire2byte(wire_byte, wire); if (!err) { } EXPECT_EQ(wire.length()/2, len); EXPECT_TRUE(0 == std::memcmp(dst, wire_byte, len)); delete [] wire_byte; } } delete table; } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>use ASSERT to stop testing<commit_after>#include "HPACK.h" #include "hpack_table.h" #include "gtest/gtest.h" #include <string.h> #include "picojson/picojson.h" #include <fstream> #include <iostream> #include <iterator> TEST(encode_intTest, NormalTest) { uint8_t dst[10]; uint8_t expect[][5] = { {0x01, 0x00}, {0x0f, 0x01}, //{0x1f, 0xa1, 0x8d, 0xb7, 0x01}, }; uint64_t len = encode_int(dst, 1, 1); EXPECT_EQ(2, len); EXPECT_TRUE(0 == std::memcmp(dst, expect[0], len)); len = encode_int(dst, 16, 4); EXPECT_EQ(2, len); EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len)); /* len = encode_int(dst, 3000000, 5); EXPECT_EQ(5, len); EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len)); */ } TEST(decode_intTest, NormalTest) { uint32_t dst = 0; uint8_t data[][5] = { {0x01, 0x00}, {0x0f, 0x01}, }; EXPECT_EQ(1, decode_int(data[0], 1)); EXPECT_EQ(16, decode_int(data[1], 4)); } const static std::string TestCases[] = { "hpack-test-case/haskell-http2-naive/", "hpack-test-case/haskell-http2-naive-huffman/", "hpack-test-case/haskell-http2-static/", "hpack-test-case/haskell-http2-static-huffman/", "hpack-test-case/haskell-http2-linear/", "hpack-test-case/haskell-http2-linear-huffman/", }; const static std::string out_tmp_file = "filename.txt"; bool read_json_files(std::vector<std::string> &jsons, const std::string testcase) { std::string call_str = "ls " + testcase + " > " + out_tmp_file; int len = call_str.length(); char call[70]; memcpy(call, call_str.c_str(), len+1); system(call); std::ifstream fnames(out_tmp_file); if (fnames.fail()) { std::cerr << "fail to open" << out_tmp_file << std::endl; return false; } std::string field; while (std::getline(fnames, field)) { jsons.push_back(field); } return true; } bool read_json_as_pico(picojson::value& v, const std::string path) { std::ifstream ifs(path); if (ifs.fail()) { std::cerr << "fail to open" << std::endl; return false; } std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); std::string err = picojson::parse(v, str); if (! err.empty()) { std::cerr << err << std::endl; return false; } return true; } bool read_header_wire(std::vector<header>& ans_headers, std::string& wire, picojson::array::iterator it_seqno) { picojson::object obj_in = it_seqno->get<picojson::object>(); wire = obj_in["wire"].to_str(); picojson::array json_headers = obj_in["headers"].get<picojson::array>(); picojson::array::iterator it_headers; for (it_headers = json_headers.begin(); it_headers != json_headers.end(); it_headers++) { picojson::object content = it_headers->get<picojson::object>(); picojson::object::iterator it = content.begin(); ans_headers.push_back(header(it->first, it->second.to_str())); } return true; } bool wire2byte(uint8_t *wire_byte, const std::string wire) { int len = wire.length(); for (int i = 0; i < len; i += 2) { *(wire_byte+i/2) = (uint8_t)std::stoi(wire.substr(i, 2).c_str(), nullptr, 16); } return true; } void detect_testcase_type(bool &from_header, bool &from_static, bool &is_huffman,const std::string testcase) { from_header = std::string::npos != testcase.find("linear", 0); from_static = from_header || std::string::npos != testcase.find("static", 0); is_huffman = std::string::npos != testcase.find("huffman", 0); } TEST(encodeTest, NormalTest) { for (const std::string testcase : TestCases) { std::vector<std::string> jsons; bool err = read_json_files(jsons, testcase); if (!err) { } bool from_header, from_static, is_huffman; detect_testcase_type(from_header, from_static, is_huffman, testcase); std::cout << testcase << " " << from_header << from_static << is_huffman << std::endl; Table* table = new Table(); for (std::string json_file : jsons) { picojson::value v; err = read_json_as_pico(v, testcase + json_file); if (!err) { } picojson::object obj = v.get<picojson::object>(); picojson::array arr = obj["cases"].get<picojson::array>(); picojson::array::iterator it_seqno; for (it_seqno = arr.begin(); it_seqno != arr.end(); it_seqno++) { std::string wire; std::vector<header> ans_headers; err = read_header_wire(ans_headers, wire, it_seqno); if (!err) { } uint8_t dst[20000]; int64_t len = hpack_encode(dst, ans_headers,from_static, from_header, is_huffman, table, -1); uint8_t *wire_byte = new uint8_t[wire.length()/2]; err = wire2byte(wire_byte, wire); if (!err) { } EXPECT_EQ(wire.length()/2, len); EXPECT_TRUE(0 == std::memcmp(dst, wire_byte, len)); ASSERT_EQ(wire.length()/2, len); ASSERT_TRUE(0 == wire_assert); delete [] wire_byte; } } delete table; } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "catch.hpp" #include <boost/icl/interval.hpp> #include <boost/icl/interval_set.hpp> #include <boost/icl/separate_interval_set.hpp> #include <boost/icl/split_interval_set.hpp> #include <boost/icl/interval_map.hpp> #include <boost/optional.hpp> #include <iostream> TEST_CASE("interval tests", "[boost]") { typedef boost::icl::interval<int> Interval; SECTION("closed intervals") { auto ival = Interval::closed(1, 3); REQUIRE(ival.lower() == 1); REQUIRE(ival.upper() == 3); REQUIRE(contains(ival, 1) == true); REQUIRE(contains(ival, 3) == true); } SECTION("open intervals") { auto ival = Interval::open(1, 3); REQUIRE(ival.lower() == 1); REQUIRE(ival.upper() == 3); REQUIRE(contains(ival, 1) == false); REQUIRE(contains(ival, 3) == false); } SECTION("right open intervals") { auto ival = Interval::right_open(1, 3); REQUIRE(ival.lower() == 1); REQUIRE(ival.upper() == 3); REQUIRE(contains(ival, 1) == true); REQUIRE(contains(ival, 3) == false); } SECTION("left open intervals") { auto ival = Interval::left_open(1, 3); REQUIRE(ival.lower() == 1); REQUIRE(ival.upper() == 3); REQUIRE(contains(ival, 1) == false); REQUIRE(contains(ival, 3) == true); } } TEST_CASE("interval set tests", "[boost]") { typedef boost::icl::interval<int> Interval; SECTION("interval sets") { // intervals joined on overlap or touch. typedef boost::icl::interval_set<int> IntervalSet; auto iset = IntervalSet{}; iset += Interval::closed(1, 3); REQUIRE( (iset == IntervalSet(Interval::closed(1, 3))) ); iset += Interval::open(2, 5); REQUIRE( (iset == IntervalSet(Interval::right_open(1, 5))) ); iset += Interval::closed(5, 7); REQUIRE( (iset == IntervalSet(Interval::closed(1, 7))) ); iset += Interval::closed(10, 12); REQUIRE( contains(iset, Interval::closed(2, 6)) ); REQUIRE( contains(iset, Interval::closed(10, 12)) ); REQUIRE_FALSE( contains(iset, Interval::closed(8, 9)) ); REQUIRE_FALSE( contains(iset, Interval::closed(8, 11)) ); } SECTION("separate interval sets") { // intervals joined on overlap, not touch. typedef boost::icl::separate_interval_set<int> SeparateIntervalSet; auto se_iset = SeparateIntervalSet{}; se_iset += Interval::right_open(1, 3); se_iset += Interval::closed(3, 5); REQUIRE_FALSE( (se_iset == SeparateIntervalSet(Interval::closed(1, 5))) ); // as se_iset is {[1, 3), [3, 5]}. se_iset += Interval::closed(2, 4); REQUIRE( (se_iset == SeparateIntervalSet(Interval::closed(1, 5))) ); } SECTION("split interval sets") { // intervals split on overlap, borders preserved. typedef boost::icl::split_interval_set<int> SplitIntervalSet; auto sp_iset = SplitIntervalSet{}; sp_iset += Interval::right_open(1, 3); sp_iset += Interval::right_open(2, 5); auto res = SplitIntervalSet{}; res += Interval::right_open(1, 2); res += Interval::right_open(2, 3); res += Interval::right_open(3, 5); REQUIRE( (sp_iset == res) ); } } TEST_CASE("interval map tests", "[boost]") { // interval maps have the "identity absorber" property. This prevents storing // identities as values. For example, the following values cannot be stored: // - int values cannot store 0. // - std::string values cannot store "". // - set<T> values cannot store {}. typedef boost::icl::interval<int> Interval; typedef boost::icl::discrete_interval<int> DiscreteInterval; SECTION("interval maps") { typedef boost::icl::interval_map<int, int> IntervalMap; auto imap = IntervalMap{}; imap += std::make_pair(Interval::closed(6, 8), 1); imap += std::make_pair(Interval::closed(7, 9), 2); std::vector<int> key_lowers, key_uppers, vals; std::vector<DiscreteInterval> keys; for(auto it = imap.begin(); it != imap.end(); ++it) { key_lowers.push_back(it->first.lower()); key_uppers.push_back(it->first.upper()); vals.push_back(it->second); keys.push_back(it->first); } REQUIRE( (key_lowers == std::vector<int>({6, 7, 8})) ); REQUIRE( (key_uppers == std::vector<int>({7, 8, 9})) ); REQUIRE( (vals == std::vector<int>({1, 3, 2})) ); REQUIRE( (keys == std::vector<DiscreteInterval>( { DiscreteInterval::right_open(6, 7) , DiscreteInterval::closed(7, 8) , DiscreteInterval::left_open(8, 9)})) ); } } TEST_CASE("optional test", "[boost]") { SECTION("optional construction") { auto optInt = boost::optional<int>{}; REQUIRE_FALSE(optInt.is_initialized()); optInt = 1; REQUIRE(optInt.is_initialized()); REQUIRE(optInt.get() == 1); } SECTION("optional returning function") { auto positivePart = [](int num)->boost::optional<int> { return num > 0 ? num : boost::optional<int>{}; }; auto optVal = positivePart(5); REQUIRE(optVal.is_initialized()); REQUIRE(optVal.get() == 5); REQUIRE_FALSE(positivePart(-5).is_initialized()); } } <commit_msg>added tests for interval maps that can store 0 as a value.<commit_after>#include "catch.hpp" #include <boost/icl/interval.hpp> #include <boost/icl/interval_set.hpp> #include <boost/icl/map.hpp> // required only for boost::icl::partial_enricher. #include <boost/icl/separate_interval_set.hpp> #include <boost/icl/split_interval_set.hpp> #include <boost/icl/interval_map.hpp> #include <boost/optional.hpp> #include <iostream> TEST_CASE("interval tests", "[boost]") { typedef boost::icl::interval<int> Interval; SECTION("closed intervals") { auto ival = Interval::closed(1, 3); REQUIRE(ival.lower() == 1); REQUIRE(ival.upper() == 3); REQUIRE(contains(ival, 1) == true); REQUIRE(contains(ival, 3) == true); } SECTION("open intervals") { auto ival = Interval::open(1, 3); REQUIRE(ival.lower() == 1); REQUIRE(ival.upper() == 3); REQUIRE(contains(ival, 1) == false); REQUIRE(contains(ival, 3) == false); } SECTION("right open intervals") { auto ival = Interval::right_open(1, 3); REQUIRE(ival.lower() == 1); REQUIRE(ival.upper() == 3); REQUIRE(contains(ival, 1) == true); REQUIRE(contains(ival, 3) == false); } SECTION("left open intervals") { auto ival = Interval::left_open(1, 3); REQUIRE(ival.lower() == 1); REQUIRE(ival.upper() == 3); REQUIRE(contains(ival, 1) == false); REQUIRE(contains(ival, 3) == true); } } TEST_CASE("interval set tests", "[boost]") { typedef boost::icl::interval<int> Interval; SECTION("interval sets") { // intervals joined on overlap or touch. typedef boost::icl::interval_set<int> IntervalSet; auto iset = IntervalSet{}; iset += Interval::closed(1, 3); REQUIRE( (iset == IntervalSet(Interval::closed(1, 3))) ); iset += Interval::open(2, 5); REQUIRE( (iset == IntervalSet(Interval::right_open(1, 5))) ); iset += Interval::closed(5, 7); REQUIRE( (iset == IntervalSet(Interval::closed(1, 7))) ); iset += Interval::closed(10, 12); REQUIRE( contains(iset, Interval::closed(2, 6)) ); REQUIRE( contains(iset, Interval::closed(10, 12)) ); REQUIRE_FALSE( contains(iset, Interval::closed(8, 9)) ); REQUIRE_FALSE( contains(iset, Interval::closed(8, 11)) ); } SECTION("separate interval sets") { // intervals joined on overlap, not touch. typedef boost::icl::separate_interval_set<int> SeparateIntervalSet; auto se_iset = SeparateIntervalSet{}; se_iset += Interval::right_open(1, 3); se_iset += Interval::closed(3, 5); REQUIRE_FALSE( (se_iset == SeparateIntervalSet(Interval::closed(1, 5))) ); // as se_iset is {[1, 3), [3, 5]}. se_iset += Interval::closed(2, 4); REQUIRE( (se_iset == SeparateIntervalSet(Interval::closed(1, 5))) ); } SECTION("split interval sets") { // intervals split on overlap, borders preserved. typedef boost::icl::split_interval_set<int> SplitIntervalSet; auto sp_iset = SplitIntervalSet{}; sp_iset += Interval::right_open(1, 3); sp_iset += Interval::right_open(2, 5); auto res = SplitIntervalSet{}; res += Interval::right_open(1, 2); res += Interval::right_open(2, 3); res += Interval::right_open(3, 5); REQUIRE( (sp_iset == res) ); } } TEST_CASE("interval map tests", "[boost]") { // interval maps have the "identity absorber" property. This prevents storing // identities as values. For example, the following values cannot be stored: // - int values cannot store 0. // - std::string values cannot store "". // - set<T> values cannot store {}. typedef boost::icl::interval<int> Interval; typedef boost::icl::discrete_interval<int> DiscreteInterval; SECTION("interval maps") { typedef boost::icl::interval_map<int, int> IntervalMap; auto imap = IntervalMap{}; imap += std::make_pair(Interval::closed(6, 8), 1); imap += std::make_pair(Interval::closed(7, 9), 2); std::vector<int> key_lowers, key_uppers, vals; std::vector<DiscreteInterval> keys; for(auto it = imap.begin(); it != imap.end(); ++it) { key_lowers.push_back(it->first.lower()); key_uppers.push_back(it->first.upper()); vals.push_back(it->second); keys.push_back(it->first); } REQUIRE( (key_lowers == std::vector<int>({6, 7, 8})) ); REQUIRE( (key_uppers == std::vector<int>({7, 8, 9})) ); REQUIRE( (vals == std::vector<int>({1, 3, 2})) ); REQUIRE( (keys == std::vector<DiscreteInterval>( { DiscreteInterval::right_open(6, 7) , DiscreteInterval::closed(7, 8) , DiscreteInterval::left_open(8, 9) })) ); } SECTION("enriched interval maps") { typedef boost::icl::interval_map<int, int, boost::icl::partial_enricher> EIMap; // The third template above is a trait of the interval map. There are 4 possible traits: // - partial_absorber // - partial_enricher // - total absorber // - total enricher // "partial" means that the map is defined only for keys that have been inserted. // "total" means that the map is considered to have a "neutral" value for all keys not // stored in the map. // "absorber" means that the identity element with respect to "+" cannot be stored as a // value. For example, 0 for int types and "" for std::string types. // "enricher" allows storing the identity element. auto eimap = EIMap{}; eimap += std::make_pair(Interval::closed(1, 10), 0); eimap += std::make_pair(Interval::closed(3, 5), 1); eimap += std::make_pair(Interval::closed(8, 10), 3); std::vector<DiscreteInterval> keys; std::vector<int> vals; for(auto it = eimap.begin(); it != eimap.end(); ++it) { keys.push_back(it->first); vals.push_back(it->second); } REQUIRE( (keys == std::vector<DiscreteInterval>( { DiscreteInterval::right_open(1, 3) , DiscreteInterval::closed(3, 5) , DiscreteInterval::open(5, 8) , DiscreteInterval::closed(8, 10) })) ); REQUIRE( (vals == std::vector<int>({0, 1, 0, 3})) ); } } TEST_CASE("optional test", "[boost]") { SECTION("optional construction") { auto optInt = boost::optional<int>{}; REQUIRE_FALSE(optInt.is_initialized()); optInt = 1; REQUIRE(optInt.is_initialized()); REQUIRE(optInt.get() == 1); } SECTION("optional returning function") { auto positivePart = [](int num)->boost::optional<int> { return num > 0 ? num : boost::optional<int>{}; }; auto optVal = positivePart(5); REQUIRE(optVal.is_initialized()); REQUIRE(optVal.get() == 5); REQUIRE_FALSE(positivePart(-5).is_initialized()); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: inputwin.hxx,v $ * * $Revision: 1.16 $ * * last change: $Author: vg $ $Date: 2007-02-27 13:24:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_INPUTWIN_HXX #define SC_INPUTWIN_HXX #ifndef _TOOLBOX_HXX //autogen #include <vcl/toolbox.hxx> #endif #ifndef _SFX_CHILDWIN_HXX //autogen #include <sfx2/childwin.hxx> #endif #ifndef _SFXLSTNER_HXX //autogen #include <svtools/lstner.hxx> #endif #ifndef _COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _WINDOW_HXX //autogen #include <vcl/window.hxx> #endif #ifndef _TRANSFER_HXX #include <svtools/transfer.hxx> #endif class ScEditEngineDefaulter; class EditView; struct ESelection; class ScInputHandler; class ScAccessibleEditLineTextData; struct EENotify; class ScRangeList; //======================================================================== class ScTextWnd : public Window, public DragSourceHelper // edit window { public: ScTextWnd( Window* pParent ); virtual ~ScTextWnd(); void SetTextString( const String& rString ); const String& GetTextString() const; BOOL IsInputActive(); EditView* GetEditView(); // fuer FunktionsAutopiloten void MakeDialogEditView(); void StartEditEngine(); void StopEditEngine( BOOL bAll ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); void SetFormulaMode( BOOL bSet ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible(); void SetAccessibleTextData(ScAccessibleEditLineTextData* pTextData) {pAccTextData = pTextData;} DECL_LINK( NotifyHdl, EENotify* ); protected: virtual void Paint( const Rectangle& rRec ); virtual void Resize(); virtual void MouseMove( const MouseEvent& rMEvt ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void Command( const CommandEvent& rCEvt ); virtual void KeyInput(const KeyEvent& rKEvt); virtual void GetFocus(); virtual void LoseFocus(); virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel ); virtual String GetText() const; private: void ImplInitSettings(); void UpdateAutoCorrFlag(); private: String aString; Font aTextFont; ScEditEngineDefaulter* pEditEngine; // erst bei Bedarf angelegt EditView* pEditView; ScAccessibleEditLineTextData* pAccTextData; BOOL bIsRTL; BOOL bIsInsertMode; BOOL bFormulaMode; // #102710#; this flag should be true if a key input or a command is handled // it prevents the call of InputChanged in the ModifyHandler of the EditEngine BOOL bInputMode; }; //======================================================================== class ScPosWnd : public ComboBox, public SfxListener // Positionsanzeige { private: String aPosStr; Accelerator* pAccel; ULONG nTipVisible; BOOL bFormulaMode; BOOL bTopHadFocus; public: ScPosWnd( Window* pParent ); virtual ~ScPosWnd(); void SetPos( const String& rPosStr ); // angezeigter Text void SetFormulaMode( BOOL bSet ); protected: virtual void Select(); virtual void Modify(); virtual long Notify( NotifyEvent& rNEvt ); virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ); private: void FillRangeNames(); void FillFunctions(); void DoEnter(); void HideTip(); void ReleaseFocus_Impl(); }; //======================================================================== class ScInputWindow : public ToolBox // Parent-Toolbox { public: ScInputWindow( Window* pParent, SfxBindings* pBind ); virtual ~ScInputWindow(); virtual void Resize(); virtual void Select(); void SetFuncString( const String& rString, BOOL bDoEdit = TRUE ); void SetPosString( const String& rStr ); void SetTextString( const String& rString ); const String& GetTextString(); void SetOkCancelMode(); void SetSumAssignMode(); void EnableButtons( BOOL bEnable = TRUE ); void SetFormulaMode( BOOL bSet ); BOOL IsInputActive(); EditView* GetEditView(); EditView* ActivateEdit( const String& rText, const ESelection& rSel ); void TextGrabFocus(); void TextInvalidate(); void SwitchToTextWin(); void PosGrabFocus(); // Fuer FunktionsAutopiloten void MakeDialogEditView(); void StopEditEngine( BOOL bAll ); void SetInputHandler( ScInputHandler* pNew ); ScInputHandler* GetInputHandler(){ return pInputHdl;} void StateChanged( StateChangedType nType ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); protected: virtual void SetText( const String& rString ); virtual String GetText() const; sal_Bool UseSubTotal( ScRangeList* pRangeList ) const; private: ScPosWnd aWndPos; ScTextWnd aTextWindow; ScInputHandler* pInputHdl; SfxBindings* pBindings; String aTextOk; String aTextCancel; String aTextSum; String aTextEqual; BOOL bIsOkCancelMode; }; //================================================================== class ScInputWindowWrapper : public SfxChildWindow { public: ScInputWindowWrapper( Window* pParent, USHORT nId, SfxBindings* pBindings, SfxChildWinInfo* pInfo ); SFX_DECL_CHILDWINDOW(ScInputWindowWrapper); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.16.330); FILE MERGED 2008/04/01 15:30:55 thb 1.16.330.2: #i85898# Stripping all external header guards 2008/03/31 17:15:42 rt 1.16.330.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: inputwin.hxx,v $ * $Revision: 1.17 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SC_INPUTWIN_HXX #define SC_INPUTWIN_HXX #ifndef _TOOLBOX_HXX //autogen #include <vcl/toolbox.hxx> #endif #include <sfx2/childwin.hxx> #include <svtools/lstner.hxx> #ifndef _COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #include <vcl/window.hxx> #include <svtools/transfer.hxx> class ScEditEngineDefaulter; class EditView; struct ESelection; class ScInputHandler; class ScAccessibleEditLineTextData; struct EENotify; class ScRangeList; //======================================================================== class ScTextWnd : public Window, public DragSourceHelper // edit window { public: ScTextWnd( Window* pParent ); virtual ~ScTextWnd(); void SetTextString( const String& rString ); const String& GetTextString() const; BOOL IsInputActive(); EditView* GetEditView(); // fuer FunktionsAutopiloten void MakeDialogEditView(); void StartEditEngine(); void StopEditEngine( BOOL bAll ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); void SetFormulaMode( BOOL bSet ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible(); void SetAccessibleTextData(ScAccessibleEditLineTextData* pTextData) {pAccTextData = pTextData;} DECL_LINK( NotifyHdl, EENotify* ); protected: virtual void Paint( const Rectangle& rRec ); virtual void Resize(); virtual void MouseMove( const MouseEvent& rMEvt ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); virtual void MouseButtonUp( const MouseEvent& rMEvt ); virtual void Command( const CommandEvent& rCEvt ); virtual void KeyInput(const KeyEvent& rKEvt); virtual void GetFocus(); virtual void LoseFocus(); virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel ); virtual String GetText() const; private: void ImplInitSettings(); void UpdateAutoCorrFlag(); private: String aString; Font aTextFont; ScEditEngineDefaulter* pEditEngine; // erst bei Bedarf angelegt EditView* pEditView; ScAccessibleEditLineTextData* pAccTextData; BOOL bIsRTL; BOOL bIsInsertMode; BOOL bFormulaMode; // #102710#; this flag should be true if a key input or a command is handled // it prevents the call of InputChanged in the ModifyHandler of the EditEngine BOOL bInputMode; }; //======================================================================== class ScPosWnd : public ComboBox, public SfxListener // Positionsanzeige { private: String aPosStr; Accelerator* pAccel; ULONG nTipVisible; BOOL bFormulaMode; BOOL bTopHadFocus; public: ScPosWnd( Window* pParent ); virtual ~ScPosWnd(); void SetPos( const String& rPosStr ); // angezeigter Text void SetFormulaMode( BOOL bSet ); protected: virtual void Select(); virtual void Modify(); virtual long Notify( NotifyEvent& rNEvt ); virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ); private: void FillRangeNames(); void FillFunctions(); void DoEnter(); void HideTip(); void ReleaseFocus_Impl(); }; //======================================================================== class ScInputWindow : public ToolBox // Parent-Toolbox { public: ScInputWindow( Window* pParent, SfxBindings* pBind ); virtual ~ScInputWindow(); virtual void Resize(); virtual void Select(); void SetFuncString( const String& rString, BOOL bDoEdit = TRUE ); void SetPosString( const String& rStr ); void SetTextString( const String& rString ); const String& GetTextString(); void SetOkCancelMode(); void SetSumAssignMode(); void EnableButtons( BOOL bEnable = TRUE ); void SetFormulaMode( BOOL bSet ); BOOL IsInputActive(); EditView* GetEditView(); EditView* ActivateEdit( const String& rText, const ESelection& rSel ); void TextGrabFocus(); void TextInvalidate(); void SwitchToTextWin(); void PosGrabFocus(); // Fuer FunktionsAutopiloten void MakeDialogEditView(); void StopEditEngine( BOOL bAll ); void SetInputHandler( ScInputHandler* pNew ); ScInputHandler* GetInputHandler(){ return pInputHdl;} void StateChanged( StateChangedType nType ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); protected: virtual void SetText( const String& rString ); virtual String GetText() const; sal_Bool UseSubTotal( ScRangeList* pRangeList ) const; private: ScPosWnd aWndPos; ScTextWnd aTextWindow; ScInputHandler* pInputHdl; SfxBindings* pBindings; String aTextOk; String aTextCancel; String aTextSum; String aTextEqual; BOOL bIsOkCancelMode; }; //================================================================== class ScInputWindowWrapper : public SfxChildWindow { public: ScInputWindowWrapper( Window* pParent, USHORT nId, SfxBindings* pBindings, SfxChildWinInfo* pInfo ); SFX_DECL_CHILDWINDOW(ScInputWindowWrapper); }; #endif <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <list> using namespace std; double sinus(double x){ return sin(x); } double power(double base, double exp){ return pow(base, exp); } double wielomian(double a, double b, double c, double d, double x){ return a*x*x*x -b*x*x +c*x -d; } //list<double> rozwiazania; template<class F>void bisekcja(double start, double end, F funk, double epsilon){ if( (funk(start) >=0 && funk(end) < 0) || (funk(start)<0 && funk(end) >=0) ){ double center = (start+end)/2; double centerValue = funk(center); if(abs(centerValue) < epsilon){ //rozwiazania.push_back(center); cout << center << endl; } else { bisekcja(start, center, funk, epsilon); bisekcja(center, end, funk, epsilon); } } } int main() { cout << "Hello World!" << endl; //bisekcja(-1,1.1,sinus,0.02); auto exponent = [](double x) -> double {return power(2,x);}; auto wiel = [](double x) -> double {return wielomian(2,3,2,1,x);}; bisekcja(-1,1.1,sinus,0.001); /*for(list<double>::iterator it = rozwiazania.begin(); it != rozwiazania.end(); it++){ cout << *it << endl; }*/ return 0; } <commit_msg>bla bla<commit_after>#include <iostream> #include <cmath> #include <list> using namespace std; double sinus(double x){ return sin(x); } double power(double base, double exp){ return pow(base, exp); } double wielomian(double a, double b, double c, double d, double x){ return a*x*x*x -b*x*x +c*x -d; } //list<double> rozwiazania; template<class F>void bisekcja(double start, double end, F funk, double epsilon){ if( (funk(start) >=0 && funk(end) < 0) || (funk(start)<0 && funk(end) >=0) ){ double center = (start+end)/2; double centerValue = funk(center); if(abs(centerValue) < epsilon){ //rozwiazania.push_back(center); cout << center << endl; } else { bisekcja(start, center, funk, epsilon); bisekcja(center, end, funk, epsilon); } } } template<class F> double siecznych(F funk, double a, double b, double eps){ double x0; x0 = a - funk(a) * (a - b) / (funk(a) - funk(b)); if (fabs(funk(x0)) < eps){ cout << x0 << endl; cout << funk(x0) << endl; return x0; } else{ cout << x0 << endl; cout << funk(x0) << endl; return siecznych(funk, x0, a, eps); } } int main() { cout << "Hello World!" << endl; //bisekcja(-1,1.1,sinus,0.02); auto exponent = [](double x) -> double {return power(2,x);}; auto wiel = [](double x) -> double {return wielomian(2,3,2,1,x);}; bisekcja(-1,1.1,sinus,0.001); cout << endl << endl; double a = 2; siecznych([a](double x)->double {return power(a, x);}, 2, 6, 0.2); /*for(list<double>::iterator it = rozwiazania.begin(); it != rozwiazania.end(); it++){ cout << *it << endl; }*/ return 0; } <|endoftext|>
<commit_before>#include <stdarg.h> #include <string.h> #include "JavaObject.h" DEFINE_JAVA_CLASS_NAME(JavaObject, ""); JavaObject::JavaObject(jobject object) : object(object) { } JavaObject::~JavaObject() { if (object) getJNIEnv()->DeleteGlobalRef(object); } void JavaObject::setJObjectLocal(jobject object) { setJObject(object); getJNIEnv()->DeleteLocalRef(object); } void JavaObject::setJObject(jobject object) { // TODO: check class_name of jobject if (object) getJNIEnv()->DeleteGlobalRef(object); object = getJNIEnv()->NewGlobalRef(object); } jvalue JavaObject::invokeInstanceMethod(const char* name, const char* signature, ...) const { JNIEnv* env = getJNIEnv(); jvalue jval; jthrowable jexc = 0; va_list args; va_start(args, signature); ::invokeMethodV(env, &jval, &jexc, INSTANCE, getJObject(), getJavaClassName(), name, signature, args); va_end(args); if (jexc) throw JavaException(jexc); return jval; } void JavaObject::constructNewObject(const char* signature, ...) const { JNIEnv* env = getJNIEnv(); jthrowable jexc = 0; va_list args; va_start(args, signature); jobject new_obj = constructNewObjectOfClassV(env, &jexc, getJavaClassName(), signature, args); va_end(args); if (jexc) throw JavaException(jexc); if (object) env->DeleteGlobalRef(object); object = env->NewGlobalRef(new_obj); env->DeleteLocalRef(new_obj); } JavaException::JavaException(jobject jexc) : JavaObject(), exception_name(0), exception_message(0) { setJObjectLocal(jexc); } JavaException::~JavaException() throw() { free(exception_name); free(exception_message); getJNIEnv()->ExceptionClear(); } const char* JavaException::name() const { if (!exception_name) { JNIEnv *env = getJNIEnv(); jclass exccls(env->GetObjectClass(getJObject())); jclass clscls(env->FindClass("java/lang/Class")); jmethodID getName(env->GetMethodID(clscls, "getName", "()Ljava/lang/String;")); jstring name(static_cast<jstring>(env->CallObjectMethod(exccls, getName))); const char* utfName(env->GetStringUTFChars(name, 0)); exception_name = strdup(utfName); env->ReleaseStringUTFChars(name, utfName); } return exception_name; } const char* JavaException::what() const throw() { if (!exception_message) { JNIEnv *env = getJNIEnv(); jclass exccls(env->GetObjectClass(getJObject())); jmethodID getMessage(env->GetMethodID(exccls, "getMessage", "()Ljava/lang/String;")); jstring message(static_cast<jstring>(env->CallObjectMethod(getJObject(), getMessage))); const char* utfMessage(env->GetStringUTFChars(message, 0)); exception_message = strdup(utfMessage); env->ReleaseStringUTFChars(message, utfMessage); } return exception_message; } JByteArray::JByteArray(const char* data, int size) : env(::getJNIEnv()), buffer(0) { size = size != -1 ? size : strlen(data); jbyteArray a = env->NewByteArray(size); array = static_cast<jbyteArray>(env->NewGlobalRef(a)); env->DeleteLocalRef(a); env->SetByteArrayRegion(array, 0, size, (const jbyte*)data); } JByteArray::JByteArray() : env(::getJNIEnv()), array(0), buffer(0) { } JByteArray::~JByteArray() { if (array) env->DeleteGlobalRef(array); if (buffer) free(buffer); } JByteArray* JByteArray::fromJObject(jobject object) { // TODO: check object type JByteArray* a = new JByteArray(); a->array = static_cast<jbyteArray>(object); return a; } const char* JByteArray::c_str() const { int len = env->GetArrayLength(array); if (buffer) free(buffer); jbyte* elems = env->GetByteArrayElements(array, NULL); if (elems) buffer = strndup((char*)elems, len); else buffer = 0; env->ReleaseByteArrayElements(array, elems, JNI_ABORT); return buffer; } <commit_msg>Fix initialization of JavaObject<commit_after>#include <stdarg.h> #include <string.h> #include "JavaObject.h" DEFINE_JAVA_CLASS_NAME(JavaObject, ""); JavaObject::JavaObject(jobject object) : object(object) { } JavaObject::~JavaObject() { if (object) getJNIEnv()->DeleteGlobalRef(object); } void JavaObject::setJObjectLocal(jobject object_) { setJObject(object_); getJNIEnv()->DeleteLocalRef(object_); } void JavaObject::setJObject(jobject object_) { // TODO: check class_name of jobject if (object) getJNIEnv()->DeleteGlobalRef(object); object = getJNIEnv()->NewGlobalRef(object_); } jvalue JavaObject::invokeInstanceMethod(const char* name, const char* signature, ...) const { JNIEnv* env = getJNIEnv(); jvalue jval; jthrowable jexc = 0; va_list args; va_start(args, signature); ::invokeMethodV(env, &jval, &jexc, INSTANCE, getJObject(), getJavaClassName(), name, signature, args); va_end(args); if (jexc) throw JavaException(jexc); return jval; } void JavaObject::constructNewObject(const char* signature, ...) const { JNIEnv* env = getJNIEnv(); jthrowable jexc = 0; va_list args; va_start(args, signature); jobject new_obj = constructNewObjectOfClassV(env, &jexc, getJavaClassName(), signature, args); va_end(args); if (jexc) throw JavaException(jexc); if (object) env->DeleteGlobalRef(object); object = env->NewGlobalRef(new_obj); env->DeleteLocalRef(new_obj); } JavaException::JavaException(jobject jexc) : JavaObject(), exception_name(0), exception_message(0) { setJObjectLocal(jexc); } JavaException::~JavaException() throw() { free(exception_name); free(exception_message); getJNIEnv()->ExceptionClear(); } const char* JavaException::name() const { if (!exception_name) { JNIEnv *env = getJNIEnv(); jclass exccls(env->GetObjectClass(getJObject())); jclass clscls(env->FindClass("java/lang/Class")); jmethodID getName(env->GetMethodID(clscls, "getName", "()Ljava/lang/String;")); jstring name(static_cast<jstring>(env->CallObjectMethod(exccls, getName))); const char* utfName(env->GetStringUTFChars(name, 0)); exception_name = strdup(utfName); env->ReleaseStringUTFChars(name, utfName); } return exception_name; } const char* JavaException::what() const throw() { if (!exception_message) { JNIEnv *env = getJNIEnv(); jclass exccls(env->GetObjectClass(getJObject())); jmethodID getMessage(env->GetMethodID(exccls, "getMessage", "()Ljava/lang/String;")); jstring message(static_cast<jstring>(env->CallObjectMethod(getJObject(), getMessage))); const char* utfMessage(env->GetStringUTFChars(message, 0)); exception_message = strdup(utfMessage); env->ReleaseStringUTFChars(message, utfMessage); } return exception_message; } JByteArray::JByteArray(const char* data, int size) : env(::getJNIEnv()), buffer(0) { size = size != -1 ? size : strlen(data); jbyteArray a = env->NewByteArray(size); array = static_cast<jbyteArray>(env->NewGlobalRef(a)); env->DeleteLocalRef(a); env->SetByteArrayRegion(array, 0, size, (const jbyte*)data); } JByteArray::JByteArray() : env(::getJNIEnv()), array(0), buffer(0) { } JByteArray::~JByteArray() { if (array) env->DeleteGlobalRef(array); if (buffer) free(buffer); } JByteArray* JByteArray::fromJObject(jobject object) { // TODO: check object type JByteArray* a = new JByteArray(); a->array = static_cast<jbyteArray>(object); return a; } const char* JByteArray::c_str() const { int len = env->GetArrayLength(array); if (buffer) free(buffer); jbyte* elems = env->GetByteArrayElements(array, NULL); if (elems) buffer = strndup((char*)elems, len); else buffer = 0; env->ReleaseByteArrayElements(array, elems, JNI_ABORT); return buffer; } <|endoftext|>
<commit_before>/** \file add_synonyms.cc * \brief Generic version for augmenting title data with synonyms found in the authority data * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen 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/>. */ /* We offer a list of tags and subfields where the primary data resides along with a list of tags and subfields where the synonym data is found and a list of unused fields in the title data where the synonyms can be stored */ #include <iostream> #include <vector> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MarcUtil.h" #include "MarcXmlWriter.h" #include "MediaTypeUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" static unsigned modified_count(0); static unsigned record_count(0); void Usage() { std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n"; std::exit(EXIT_FAILURE); } std::string getTag(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(0, 3); } std::string getSubfields(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(3); } void ExtractSynonyms(File * const norm_data_marc_input, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &synonym_tags_and_subfield_codes, std::map<std::string, std::string> *synonym_map) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator synonym; while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(norm_data_marc_input)){ unsigned int i(0); for (primary = primary_tags_and_subfield_codes.begin(), synonym = synonym_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++synonym, ++i) { // Fill maps with synonyms std::vector<std::string> primary_values; std::vector<std::string> synonym_values; if (record.extractSubfields(getTag(*primary), getSubfields(*primary), &primary_values) and record.extractSubfields(getTag(*synonym), getSubfields(*synonym), &synonym_values)) { synonym_map[i].emplace(StringUtil::Join(primary_values, ','), StringUtil::Join(synonym_values, ',')); } } } } void ProcessRecord(MarcUtil::Record * const record, std::map<std::string, std::string> *synonym_map, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator output; unsigned int i(0); for (primary = primary_tags_and_subfield_codes.begin(), output = output_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++output, ++i) { // Insert synonyms std::vector<std::string> primary_values; if (record->extractSubfields(getTag(*primary), getSubfields(*primary), &primary_values)) { std::string synonyms = synonym_map[i][StringUtil::Join(primary_values, ',')]; if (synonyms.empty()) continue; // Abort if field is already populated std::string tag = getTag(*output); if (record->getFieldIndex(tag) != -1) Error("Field with tag " + tag + " is not empty for PPN " + record->getFields()[0] + '\n'); std::string subfield_spec = getSubfields(*output); if (subfield_spec.size() != 1) Error("We currently only support a single subfield and thus specifying " + subfield_spec + " as output subfield is not valid\n"); Subfields subfields(' ', ' '); // <- indicators must be set explicitly although empty subfields.addSubfield(subfield_spec.at(0), synonyms); if (not(record->insertField(tag, subfields.toString()))) Warning("Could not insert field " + tag + " for PPN " + record->getFields()[0] + '\n'); ++modified_count; } } } void InsertSynonyms(File * const marc_input, File * marc_output, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes, std::map<std::string, std::string> *synonym_map) { MarcXmlWriter xml_writer(marc_output); while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_input)) { ProcessRecord(&record, synonym_map, primary_tags_and_subfield_codes, output_tags_and_subfield_codes); record.write(&xml_writer); ++record_count; } std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n"; } int main(int argc, char **argv) { progname = argv[0]; if (argc != 4) Usage(); const std::string marc_input_filename(argv[1]); std::unique_ptr<File> marc_input(FileUtil::OpenInputFileOrDie(marc_input_filename)); const std::string norm_data_marc_input_filename(argv[2]); std::unique_ptr<File> norm_data_marc_input(FileUtil::OpenInputFileOrDie(norm_data_marc_input_filename)); const std::string marc_output_filename(argv[3]); if (unlikely(marc_input_filename == marc_output_filename)) Error("Title data input file name equals output file name!"); if (unlikely(norm_data_marc_input_filename == marc_output_filename)) Error("Authority data input file name equals output file name!"); std::string output_mode("w"); if (marc_input->isCompressingOrUncompressing()) output_mode += 'c'; File marc_output(marc_output_filename, output_mode); if (not marc_output) Error("can't open \"" + marc_output_filename + "\" for writing!"); try { // Determine possible mappings const std::string AUTHORITY_DATA_PRIMARY_SPEC = "110abcd:111abcd:130abcd:150abcd:151abcd"; const std::string AUTHORITY_DATA_SYNONYM_SPEC = "410abcd:411abcd:430abcd:450abcd:451abcd"; const std::string TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS = "180a:181a:182a:183a:184a"; // Determine fields to handle std::set<std::string> primary_tags_and_subfield_codes; std::set<std::string> synonym_tags_and_subfield_codes; std::set<std::string> output_tags_and_subfield_codes; if (unlikely(StringUtil::Split(AUTHORITY_DATA_PRIMARY_SPEC, ":", &primary_tags_and_subfield_codes) < 1)) Error("Need at least one primary field"); if (unlikely(StringUtil::Split(AUTHORITY_DATA_SYNONYM_SPEC, ":", &synonym_tags_and_subfield_codes) < 1)) Error("Need at least one synonym field"); if (unlikely(StringUtil::Split(TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS, ":", &output_tags_and_subfield_codes) < 1)) Error("Need at least one output field"); unsigned num_of_entries(primary_tags_and_subfield_codes.size()); if (synonym_tags_and_subfield_codes.size() != num_of_entries or output_tags_and_subfield_codes.size() != num_of_entries) Error("Number of fields in all field specifications must be identical"); // Set up the array of synonym lists std::map<std::string, std::string> *synonym_map = new std::map<std::string, std::string>[num_of_entries]; ExtractSynonyms(norm_data_marc_input.get(), primary_tags_and_subfield_codes, synonym_tags_and_subfield_codes, synonym_map); // Iterate over the title data InsertSynonyms(marc_input.get(), &marc_output, primary_tags_and_subfield_codes, output_tags_and_subfield_codes, synonym_map); delete[] synonym_map; } catch (std::exception &x){ Error("caught exception: " + std::string(x.what())); } } <commit_msg>Now using separate field specs for input data<commit_after>/** \file add_synonyms.cc * \brief Generic version for augmenting title data with synonyms found in the authority data * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen 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/>. */ /* We offer a list of tags and subfields where the primary data resides along with a list of tags and subfields where the synonym data is found and a list of unused fields in the title data where the synonyms can be stored */ #include <iostream> #include <vector> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MarcUtil.h" #include "MarcXmlWriter.h" #include "MediaTypeUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" static unsigned modified_count(0); static unsigned record_count(0); void Usage() { std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n"; std::exit(EXIT_FAILURE); } std::string getTag(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(0, 3); } std::string getSubfields(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(3); } void ExtractSynonyms(File * const norm_data_marc_input, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &synonym_tags_and_subfield_codes, std::map<std::string, std::string> *synonym_map) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator synonym; while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(norm_data_marc_input)){ unsigned int i(0); for (primary = primary_tags_and_subfield_codes.begin(), synonym = synonym_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++synonym, ++i) { // Fill maps with synonyms std::vector<std::string> primary_values; std::vector<std::string> synonym_values; if (record.extractSubfields(getTag(*primary), getSubfields(*primary), &primary_values) and record.extractSubfields(getTag(*synonym), getSubfields(*synonym), &synonym_values)) { synonym_map[i].emplace(StringUtil::Join(primary_values, ','), StringUtil::Join(synonym_values, ',')); } } } } void ProcessRecord(MarcUtil::Record * const record, std::map<std::string, std::string> *synonym_map, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator output; unsigned int i(0); for (primary = primary_tags_and_subfield_codes.begin(), output = output_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++output, ++i) { // Insert synonyms std::vector<std::string> primary_values; if (record->extractSubfields(getTag(*primary), getSubfields(*primary), &primary_values)) { std::string synonyms = synonym_map[i][StringUtil::Join(primary_values, ',')]; if (synonyms.empty()) continue; // Abort if field is already populated std::string tag = getTag(*output); if (record->getFieldIndex(tag) != -1) Error("Field with tag " + tag + " is not empty for PPN " + record->getFields()[0] + '\n'); std::string subfield_spec = getSubfields(*output); if (subfield_spec.size() != 1) Error("We currently only support a single subfield and thus specifying " + subfield_spec + " as output subfield is not valid\n"); Subfields subfields(' ', ' '); // <- indicators must be set explicitly although empty subfields.addSubfield(subfield_spec.at(0), synonyms); if (not(record->insertField(tag, subfields.toString()))) Warning("Could not insert field " + tag + " for PPN " + record->getFields()[0] + '\n'); ++modified_count; } } } void InsertSynonyms(File * const marc_input, File * marc_output, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes, std::map<std::string, std::string> *synonym_map) { MarcXmlWriter xml_writer(marc_output); while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_input)) { ProcessRecord(&record, synonym_map, primary_tags_and_subfield_codes, output_tags_and_subfield_codes); record.write(&xml_writer); ++record_count; } std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n"; } int main(int argc, char **argv) { progname = argv[0]; if (argc != 4) Usage(); const std::string marc_input_filename(argv[1]); std::unique_ptr<File> marc_input(FileUtil::OpenInputFileOrDie(marc_input_filename)); const std::string norm_data_marc_input_filename(argv[2]); std::unique_ptr<File> norm_data_marc_input(FileUtil::OpenInputFileOrDie(norm_data_marc_input_filename)); const std::string marc_output_filename(argv[3]); if (unlikely(marc_input_filename == marc_output_filename)) Error("Title data input file name equals output file name!"); if (unlikely(norm_data_marc_input_filename == marc_output_filename)) Error("Authority data input file name equals output file name!"); std::string output_mode("w"); if (marc_input->isCompressingOrUncompressing()) output_mode += 'c'; File marc_output(marc_output_filename, output_mode); if (not marc_output) Error("can't open \"" + marc_output_filename + "\" for writing!"); try { // Determine possible mappings const std::string AUTHORITY_DATA_PRIMARY_SPEC = "110abcd:111abcd:130abcd:150abcd:151abcd"; const std::string AUTHORITY_DATA_SYNONYM_SPEC = "410abcd:411abcd:430abcd:450abcd:451abcd"; const std::string TITLE_DATA_PRIMARY_SPEC = "610abcd:611abcd:430abcd:650abcd:651abcd"; const std::string TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS = "180a:181a:182a:183a:184a"; // Determine fields to handle std::set<std::string> primary_tags_and_subfield_codes; std::set<std::string> synonym_tags_and_subfield_codes; std::set<std::string> input_tags_and_subfield_codes; std::set<std::string> output_tags_and_subfield_codes; if (unlikely(StringUtil::Split(AUTHORITY_DATA_PRIMARY_SPEC, ":", &primary_tags_and_subfield_codes) < 1)) Error("Need at least one primary field"); if (unlikely(StringUtil::Split(AUTHORITY_DATA_SYNONYM_SPEC, ":", &synonym_tags_and_subfield_codes) < 1)) Error("Need at least one synonym field"); if (unlikely(StringUtil::Split(TITLE_DATA_PRIMARY_SPEC, ":", &input_tags_and_subfield_codes) < 1)) Error("Need at least one input field"); if (unlikely(StringUtil::Split(TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS, ":", &output_tags_and_subfield_codes) < 1)) Error("Need at least one output field"); unsigned num_of_entries(primary_tags_and_subfield_codes.size()); if (synonym_tags_and_subfield_codes.size() != num_of_entries or input_tags_and_subfield_codes.size() != num_of_entries or output_tags_and_subfield_codes.size() != num_of_entries) Error("Number of fields in all field specifications must be identical"); // Set up the array of synonym lists std::map<std::string, std::string> *synonym_map = new std::map<std::string, std::string>[num_of_entries]; ExtractSynonyms(norm_data_marc_input.get(), primary_tags_and_subfield_codes, synonym_tags_and_subfield_codes, synonym_map); // Iterate over the title data InsertSynonyms(marc_input.get(), &marc_output, input_tags_and_subfield_codes, output_tags_and_subfield_codes, synonym_map); delete[] synonym_map; } catch (std::exception &x){ Error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software 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. * *=========================================================================*/ #ifndef __itkOtsuThresholdCalculator_hxx #define __itkOtsuThresholdCalculator_hxx #include "itkOtsuThresholdCalculator.h" #include "itkProgressReporter.h" #include "vnl/vnl_math.h" namespace itk { template< class THistogram, class TOutput > void OtsuThresholdCalculator< THistogram, TOutput > ::GenerateData(void) { const HistogramType * histogram = this->GetInput(); // histogram->Print(std::cout); if ( histogram->GetTotalFrequency() == 0 ) { itkExceptionMacro(<< "Histogram is empty"); } ProgressReporter progress(this, 0, histogram->GetSize(0)*2 ); if( histogram->GetSize(0) == 1 ) { this->GetOutput()->Set( static_cast<OutputType>(histogram->GetMeasurement(0,0)) ); } unsigned int size = histogram->GetSize(0); // normalize the frequencies std::vector< double > relativeFrequency; relativeFrequency.resize(size); double totalMean = 0.0; for ( unsigned int j = 0; j < size; j++ ) { relativeFrequency[j] = histogram->GetFrequency(j,0); relativeFrequency[j] /= histogram->GetTotalFrequency(); totalMean += ( j + 1 ) * relativeFrequency[j]; progress.CompletedPixel(); } // compute Otsu's threshold by maximizing the between-class // variance double freqLeft = relativeFrequency[0]; double meanLeft = 1.0; double meanRight = ( totalMean - freqLeft ) / ( 1.0 - freqLeft ); double maxVarBetween = freqLeft * ( 1.0 - freqLeft ) * vnl_math_sqr(meanLeft - meanRight); int maxBinNumber = 0; double freqLeftOld = freqLeft; double meanLeftOld = meanLeft; for ( unsigned int j = 1; j < size; j++ ) { freqLeft += relativeFrequency[j]; meanLeft = ( meanLeftOld * freqLeftOld + ( j + 1 ) * relativeFrequency[j] ) / freqLeft; if ( freqLeft == 1.0 ) { meanRight = 0.0; } else { meanRight = ( totalMean - meanLeft * freqLeft ) / ( 1.0 - freqLeft ); } double varBetween = freqLeft * ( 1.0 - freqLeft ) * vnl_math_sqr(meanLeft - meanRight); // for portability - different compilers seem to produce results // that differ by one bin, presumable because of the precision of // calculating varBetween const double tolerance = 0.00001; if ( (varBetween - tolerance) > maxVarBetween ) { maxVarBetween = varBetween; maxBinNumber = j; } // cache old values freqLeftOld = freqLeft; meanLeftOld = meanLeft; progress.CompletedPixel(); } // should be this for backward compatibility // this->GetOutput()->Set( static_cast<OutputType>( // histogram->GetBinMin( 0, maxBinNumber + 1 ) ) ); this->GetOutput()->Set( static_cast<OutputType>( histogram->GetMeasurement( maxBinNumber + 1, 0 ) ) ); } } // end namespace itk #endif <commit_msg>BUG: Correct for divide by zero when first bin has zero frequency<commit_after>/*========================================================================= * * Copyright Insight Software 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. * *=========================================================================*/ #ifndef __itkOtsuThresholdCalculator_hxx #define __itkOtsuThresholdCalculator_hxx #include "itkOtsuThresholdCalculator.h" #include "itkProgressReporter.h" #include "vnl/vnl_math.h" namespace itk { template< class THistogram, class TOutput > void OtsuThresholdCalculator< THistogram, TOutput > ::GenerateData(void) { const HistogramType * histogram = this->GetInput(); if ( histogram->GetTotalFrequency() == 0 ) { itkExceptionMacro(<< "Histogram is empty"); } ProgressReporter progress(this, 0, histogram->GetSize(0)*2 ); if( histogram->GetSize(0) == 1 ) { this->GetOutput()->Set( static_cast<OutputType>(histogram->GetMeasurement(0,0)) ); } SizeValueType size = histogram->GetSize(0); // normalize the frequencies std::vector< double > relativeFrequency; relativeFrequency.resize(size); double totalMean = 0.0; for ( SizeValueType j = 0; j < size; j++ ) { relativeFrequency[j] = histogram->GetFrequency(j,0); relativeFrequency[j] /= histogram->GetTotalFrequency(); totalMean += ( j + 1 ) * relativeFrequency[j]; progress.CompletedPixel(); } // compute Otsu's threshold by maximizing the between-class // variance double freqLeft = relativeFrequency[0]; double meanLeft = 1.0; double meanRight = 0.0; if ( freqLeft < 1.0 ) { meanRight = ( totalMean - meanLeft * freqLeft ) / ( 1.0 - freqLeft ); } double maxVarBetween = freqLeft * ( 1.0 - freqLeft ) * vnl_math_sqr(meanLeft - meanRight); SizeValueType maxBinNumber = 0; double freqLeftOld = freqLeft; double meanLeftOld = meanLeft; for ( SizeValueType j = 1; j < size; j++ ) { freqLeft += relativeFrequency[j]; if ( freqLeft > 0.0 ) { meanLeft = ( meanLeftOld * freqLeftOld + ( j + 1 ) * relativeFrequency[j] ) / freqLeft; } if ( freqLeft >= 1.0 ) { meanRight = 0.0; } else { meanRight = ( totalMean - meanLeft * freqLeft ) / ( 1.0 - freqLeft ); } double varBetween = freqLeft * ( 1.0 - freqLeft ) * vnl_math_sqr(meanLeft - meanRight); // for portability - different compilers seem to produce results // that differ by one bin, presumable because of the precision of // calculating varBetween const double tolerance = 0.00001; if ( (varBetween - tolerance) > maxVarBetween ) { maxVarBetween = varBetween; maxBinNumber = j; } // cache old values freqLeftOld = freqLeft; meanLeftOld = meanLeft; progress.CompletedPixel(); } // should be this for backward compatibility // this->GetOutput()->Set( static_cast<OutputType>( // histogram->GetBinMin( 0, maxBinNumber + 1 ) ) ); this->GetOutput()->Set( static_cast<OutputType>( histogram->GetMeasurement( maxBinNumber + 1, 0 ) ) ); } } // end namespace itk #endif <|endoftext|>
<commit_before>/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com> 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 "nomlib/graphics/Image.hpp" namespace nom { Image::Image ( void ) : image_ ( nullptr, priv::FreeSurface ) { NOM_LOG_TRACE ( NOM ); if ( IMG_Init ( IMG_INIT_PNG ) != IMG_INIT_PNG ) { NOM_LOG_ERR ( NOM, IMG_GetError() ); } atexit ( IMG_Quit ); } Image::~Image ( void ) { NOM_LOG_TRACE ( NOM ); } Image::Image ( uint32 flags ) : image_ ( nullptr, priv::FreeSurface ) { NOM_LOG_TRACE ( NOM ); if ( IMG_Init ( flags ) != flags ) { NOM_LOG_ERR ( NOM, IMG_GetError() ); } atexit ( IMG_Quit ); } Image::Image ( const Image& other ) : image_ { other.image(), priv::FreeSurface } { NOM_LOG_TRACE ( NOM ); } Image& Image::operator = ( const Image& other ) { this->image_ = other.image_; return *this; } SDL_Surface* Image::image ( void ) const { return this->image_.get(); } bool Image::valid ( void ) const { if ( this->image() != nullptr ) { return true; } else { return false; } } int32 Image::width ( void ) const { SDL_Surface* buffer = this->image(); return buffer->w; } int32 Image::height ( void ) const { SDL_Surface* buffer = this->image(); return buffer->h; } void* Image::pixels ( void ) const { SDL_Surface* buffer = this->image(); return buffer->pixels; } uint16 Image::pitch ( void ) const { SDL_Surface* buffer = this->image(); return buffer->pitch; } uint8 Image::bits_per_pixel ( void ) const { SDL_Surface* buffer = this->image(); return buffer->format->BitsPerPixel; } const SDL_PixelFormat* Image::pixel_format ( void ) const { SDL_Surface* buffer = this->image(); return buffer->format; } bool Image::load ( const std::string& filename ) { this->image_.reset ( IMG_Load ( filename.c_str() ), priv::FreeSurface ); if ( this->valid() == false ) { NOM_LOG_ERR ( NOM, IMG_GetError() ); return false; } return true; } bool Image::load_bmp ( const std::string& filename ) { this->image_.reset ( SDL_LoadBMP ( filename.c_str() ), priv::FreeSurface ); if ( this->valid() == false ) { NOM_LOG_ERR ( NOM, SDL_GetError() ); return false; } return true; } bool Image::save ( const std::string& filename, SDL_Surface* video_buffer ) { if ( SDL_SaveBMP ( video_buffer, filename.c_str() ) != 0 ) { NOM_LOG_ERR ( NOM, SDL_GetError() ); return false; } return true; } const Point2i Image::size ( void ) const { SDL_Surface* buffer = this->image(); Point2i image_pos ( buffer->w, buffer->h ); priv::FreeSurface ( buffer ); return image_pos; } bool Image::set_colorkey ( const Color& key, uint32 flags ) { SDL_Surface* buffer = this->image(); uint32 transparent_color = key.RGB ( buffer->format ); if ( this->valid() == false ) { NOM_LOG_ERR ( NOM, "Could not set color key: invalid image buffer." ); priv::FreeSurface ( buffer ); return false; } if ( SDL_SetColorKey ( buffer, SDL_TRUE ^ flags, transparent_color ) != 0 ) { NOM_LOG_ERR ( NOM, SDL_GetError() ); priv::FreeSurface ( buffer ); return false; } priv::FreeSurface ( buffer ); return true; } uint32 Image::pixel ( int32 x, int32 y ) { switch ( this->bits_per_pixel() ) { default: return -1; break; // Unknown case 8: { uint8* pixels = static_cast<uint8*> ( this->pixels() ); return pixels[ ( y * this->pitch() ) + x ]; } break; case 16: { uint16* pixels = static_cast<uint16*> ( this->pixels() ); return pixels[ ( y * this->pitch() / 2 ) + x ]; } break; case 24: { uint8* pixels = static_cast<uint8*> ( this->pixels() ); return pixels[ ( y * this->pitch() ) + x ]; } break; case 32: { uint32* pixels = static_cast<uint32*> ( this->pixels() ); return pixels[ ( y * this->pitch()/4 ) + x ]; } break; } // end switch } } // namespace nom <commit_msg>Add surface conversion for image surfaces<commit_after>/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com> 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 "nomlib/graphics/Image.hpp" namespace nom { Image::Image ( void ) : image_ ( nullptr, priv::FreeSurface ) { NOM_LOG_TRACE ( NOM ); if ( IMG_Init ( IMG_INIT_PNG ) != IMG_INIT_PNG ) { NOM_LOG_ERR ( NOM, IMG_GetError() ); } atexit ( IMG_Quit ); } Image::~Image ( void ) { NOM_LOG_TRACE ( NOM ); } Image::Image ( uint32 flags ) : image_ ( nullptr, priv::FreeSurface ) { NOM_LOG_TRACE ( NOM ); if ( IMG_Init ( flags ) != flags ) { NOM_LOG_ERR ( NOM, IMG_GetError() ); } atexit ( IMG_Quit ); } Image::Image ( const Image& other ) : image_ { other.image(), priv::FreeSurface } { NOM_LOG_TRACE ( NOM ); } Image& Image::operator = ( const Image& other ) { this->image_ = other.image_; return *this; } SDL_Surface* Image::image ( void ) const { return this->image_.get(); } bool Image::valid ( void ) const { if ( this->image() != nullptr ) { return true; } else { return false; } } int32 Image::width ( void ) const { SDL_Surface* buffer = this->image(); return buffer->w; } int32 Image::height ( void ) const { SDL_Surface* buffer = this->image(); return buffer->h; } void* Image::pixels ( void ) const { SDL_Surface* buffer = this->image(); return buffer->pixels; } uint16 Image::pitch ( void ) const { SDL_Surface* buffer = this->image(); return buffer->pitch; } uint8 Image::bits_per_pixel ( void ) const { SDL_Surface* buffer = this->image(); return buffer->format->BitsPerPixel; } const SDL_PixelFormat* Image::pixel_format ( void ) const { SDL_Surface* buffer = this->image(); return buffer->format; } bool Image::load ( const std::string& filename ) { SDL_Surface *buffer = IMG_Load ( filename.c_str() ); if ( buffer == nullptr ) { NOM_LOG_ERR ( NOM, IMG_GetError() ); return false; } this->image_.reset ( SDL_ConvertSurfaceFormat ( buffer, SDL_PIXELFORMAT_RGBA8888, 0 ), priv::FreeSurface ); priv::FreeSurface ( buffer ); return true; } bool Image::load_bmp ( const std::string& filename ) { SDL_Surface *buffer = IMG_Load ( filename.c_str() ); if ( buffer == nullptr ) { NOM_LOG_ERR ( NOM, IMG_GetError() ); return false; } this->image_.reset ( SDL_ConvertSurfaceFormat ( buffer, SDL_PIXELFORMAT_RGBA8888, 0 ), priv::FreeSurface ); priv::FreeSurface ( buffer ); return true; } bool Image::save ( const std::string& filename, SDL_Surface* video_buffer ) { if ( SDL_SaveBMP ( video_buffer, filename.c_str() ) != 0 ) { NOM_LOG_ERR ( NOM, SDL_GetError() ); return false; } return true; } const Point2i Image::size ( void ) const { SDL_Surface* buffer = this->image(); Point2i image_pos ( buffer->w, buffer->h ); priv::FreeSurface ( buffer ); return image_pos; } bool Image::set_colorkey ( const Color& key, uint32 flags ) { SDL_Surface* buffer = this->image(); uint32 transparent_color = key.RGB ( buffer->format ); if ( this->valid() == false ) { NOM_LOG_ERR ( NOM, "Could not set color key: invalid image buffer." ); priv::FreeSurface ( buffer ); return false; } if ( SDL_SetColorKey ( buffer, SDL_TRUE ^ flags, transparent_color ) != 0 ) { NOM_LOG_ERR ( NOM, SDL_GetError() ); priv::FreeSurface ( buffer ); return false; } priv::FreeSurface ( buffer ); return true; } uint32 Image::pixel ( int32 x, int32 y ) { switch ( this->bits_per_pixel() ) { default: return -1; break; // Unknown case 8: { uint8* pixels = static_cast<uint8*> ( this->pixels() ); return pixels[ ( y * this->pitch() ) + x ]; } break; case 16: { uint16* pixels = static_cast<uint16*> ( this->pixels() ); return pixels[ ( y * this->pitch() / 2 ) + x ]; } break; case 24: { uint8* pixels = static_cast<uint8*> ( this->pixels() ); return pixels[ ( y * this->pitch() ) + x ]; } break; case 32: { uint32* pixels = static_cast<uint32*> ( this->pixels() ); return pixels[ ( y * this->pitch()/4 ) + x ]; } break; } // end switch } } // namespace nom <|endoftext|>
<commit_before>/* <x0/HttpServer.cpp> * * This file is part of the x0 web server project and is released under AGPL-3. * http://www.xzero.io/ * * (c) 2009-2014 Christian Parpart <trapni@gmail.com> */ #include <x0/http/HttpServer.h> #include <x0/http/HttpRequest.h> #include <x0/http/HttpWorker.h> #include <x0/ServerSocket.h> #include <x0/SocketSpec.h> #include <x0/Logger.h> #include <x0/DebugLogger.h> #include <x0/Library.h> #include <x0/AnsiColor.h> #include <x0/strutils.h> #include <x0/sysconfig.h> #include <sd-daemon.h> #include <iostream> #include <fstream> #include <cstdarg> #include <cstdlib> #if defined(HAVE_SYS_UTSNAME_H) # include <sys/utsname.h> #endif #if defined(HAVE_ZLIB_H) # include <zlib.h> #endif #if defined(HAVE_BZLIB_H) # include <bzlib.h> #endif #include <sys/resource.h> #include <sys/time.h> #include <pwd.h> #include <grp.h> #include <getopt.h> #include <stdio.h> #if 0 // !defined(XZERO_NDEBUG) # define TRACE(msg...) DEBUG("HttpServer: " msg) #else # define TRACE(msg...) do {} while (0) #endif namespace x0 { /** initializes the HTTP server object. * \param io_service an Asio io_service to use or nullptr to create our own one. * \see HttpServer::run() */ HttpServer::HttpServer(struct ::ev_loop *loop, unsigned generation) : requestHandler(), onConnectionOpen(), onPreProcess(), onResolveDocumentRoot(), onResolveEntity(), onPostProcess(), onRequestDone(), onConnectionClose(), onConnectionStateChanged(), onWorkerSpawn(), onWorkerUnspawn(), generation_(generation), listeners_(), loop_(loop ? loop : ev_default_loop(0)), startupTime_(ev_now(loop_)), logger_(), logLevel_(Severity::warn), colored_log_(false), workerIdPool_(0), workers_(), lastWorker_(0), maxConnections(512), maxKeepAlive(TimeSpan::fromSeconds(60)), maxKeepAliveRequests(100), maxReadIdle(TimeSpan::fromSeconds(60)), maxWriteIdle(TimeSpan::fromSeconds(360)), tcpCork(false), tcpNoDelay(false), lingering(TimeSpan::Zero), tag("x0/" VERSION), advertise(true), maxRequestUriSize(4 * 1024), maxRequestHeaderSize(1 * 1024), maxRequestHeaderCount(100), maxRequestBodySize(4 * 1024 * 1024), requestHeaderBufferSize(8 * 1024), requestBodyBufferSize(8 * 1024) { DebugLogger::get().onLogWrite = [&](const char* msg, size_t n) { LogMessage lm(Severity::debug1, "%s", msg); logger_->write(lm); }; HttpRequest::initialize(); logger_.reset(new FileLogger(STDERR_FILENO, [this]() { return static_cast<time_t>(ev_now(loop_)); })); // setting a reasonable default max-connection limit. // However, this cannot be computed as we do not know what the user // actually configures, such as fastcgi requires +1 fd, local file +1 fd, // http client connection of course +1 fd, listener sockets, etc. struct rlimit rlim; if (::getrlimit(RLIMIT_NOFILE, &rlim) == 0) maxConnections = std::max(int(rlim.rlim_cur / 3) - 5, 1); // Spawn main-thread worker spawnWorker(); } HttpServer::~HttpServer() { TRACE("destroying"); stop(); for (auto i: listeners_) delete i; while (!workers_.empty()) destroyWorker(workers_[workers_.size() - 1]); #ifndef __APPLE__ // explicit cleanup DebugLogger::get().reset(); #endif } void HttpServer::onNewConnection(std::unique_ptr<Socket>&& cs, ServerSocket* ss) { if (cs) { selectWorker()->enqueue(std::make_pair(std::move(cs), ss)); } else { log(Severity::error, "Accepting incoming connection failed. %s", strerror(errno)); } } // {{{ worker mgnt HttpWorker *HttpServer::spawnWorker() { bool isMainWorker = workers_.empty(); HttpWorker *worker = new HttpWorker(*this, isMainWorker ? loop_ : nullptr, workerIdPool_++, !isMainWorker); workers_.push_back(worker); return worker; } /** * Selects (by round-robin) the next worker. * * \return a worker * \note This method is not thread-safe, and thus, should not be invoked within a request handler. */ HttpWorker* HttpServer::nextWorker() { // select by RR (round-robin) // this is thread-safe since only one thread is to select a new worker // (the main thread) if (++lastWorker_ == workers_.size()) lastWorker_ = 0; return workers_[lastWorker_]; } HttpWorker *HttpServer::selectWorker() { #if 1 // defined(X0_WORKER_RR) return nextWorker(); #else // select by lowest connection load HttpWorker *best = workers_[0]; int value = best->connectionLoad(); for (size_t i = 1, e = workers_.size(); i != e; ++i) { HttpWorker *w = workers_[i]; int l = w->connectionLoad(); if (l < value) { value = l; best = w; } } return best; #endif } void HttpServer::destroyWorker(HttpWorker *worker) { auto i = std::find(workers_.begin(), workers_.end(), worker); assert(i != workers_.end()); worker->stop(); if (worker != workers_.front()) worker->join(); workers_.erase(i); delete worker; } // }}} /** calls run on the internally referenced io_service. * \note use this if you do not have your own main loop. * \note automatically starts the server if it wasn't started via \p start() yet. * \see start(), stop() */ int HttpServer::run() { workers_.front()->run(); return 0; } /** unregisters all listeners from the underlying io_service and calls stop on it. * \see start(), run() */ void HttpServer::stop() { for (auto listener: listeners_) listener->stop(); for (auto worker: workers_) worker->stop(); } void HttpServer::kill() { stop(); for (auto worker: workers_) worker->kill(); } void HttpServer::log(LogMessage&& msg) { if (logger_) { #if !defined(XZERO_NDEBUG) #ifndef __APPLE__ if (msg.isDebug() && msg.hasTags() && DebugLogger::get().isConfigured()) { int level = 3 - msg.severity(); // compute proper debug level Buffer text; text << msg; BufferRef tag = msg.tagAt(msg.tagCount() - 1); size_t i = tag.find('/'); if (i != tag.npos) tag = tag.ref(0, i); DebugLogger::get().logUntagged(tag.str(), level, "%s", text.c_str()); return; } #endif #endif logger_->write(msg); } } /** * sets up a TCP/IP ServerSocket on given bind_address and port. * * If there is already a ServerSocket on this bind_address:port pair * then no error will be raised. */ ServerSocket* HttpServer::setupListener(const std::string& bind_address, int port, int backlog) { return setupListener(SocketSpec::fromInet(IPAddress(bind_address), port, backlog)); } ServerSocket *HttpServer::setupUnixListener(const std::string& path, int backlog) { return setupListener(SocketSpec::fromLocal(path, backlog)); } ServerSocket* HttpServer::setupListener(const SocketSpec& _spec) { // validate backlog against system's hard limit SocketSpec spec(_spec); int somaxconn = readFile("/proc/sys/net/core/somaxconn").toInt(); if (spec.backlog() > 0) { if (somaxconn && spec.backlog() > somaxconn) { log(Severity::error, "Listener %s configured with a backlog higher than the system permits (%ld > %ld). " "See /proc/sys/net/core/somaxconn for your system limits.", spec.str().c_str(), spec.backlog(), somaxconn); return nullptr; } } // create a new listener ServerSocket* lp = new ServerSocket(loop_); lp->set<HttpServer, &HttpServer::onNewConnection>(this); listeners_.push_back(lp); if (spec.backlog() <= 0) lp->setBacklog(somaxconn); if (spec.multiAcceptCount() > 0) lp->setMultiAcceptCount(spec.multiAcceptCount()); if (lp->open(spec, O_NONBLOCK | O_CLOEXEC)) { log(Severity::info, "Listening on %s", spec.str().c_str()); return lp; } else { log(Severity::error, "Could not create listener %s: %s", spec.str().c_str(), lp->errorText().c_str()); return nullptr; } } void HttpServer::destroyListener(ServerSocket* listener) { for (auto i = listeners_.begin(), e = listeners_.end(); i != e; ++i) { if (*i == listener) { listeners_.erase(i); delete listener; break; } } } void HttpServer::setLogLevel(Severity s) { logLevel_ = s; logger()->setLevel(s); log(s > Severity::info ? s : Severity::info, "Logging level set to: %s", s.c_str()); } } // namespace x0 <commit_msg>[http] HttpServer: listener check on SOMAXCONN backlog only performed when compiled unter Linux<commit_after>/* <x0/HttpServer.cpp> * * This file is part of the x0 web server project and is released under AGPL-3. * http://www.xzero.io/ * * (c) 2009-2014 Christian Parpart <trapni@gmail.com> */ #include <x0/http/HttpServer.h> #include <x0/http/HttpRequest.h> #include <x0/http/HttpWorker.h> #include <x0/ServerSocket.h> #include <x0/SocketSpec.h> #include <x0/Logger.h> #include <x0/DebugLogger.h> #include <x0/Library.h> #include <x0/AnsiColor.h> #include <x0/strutils.h> #include <x0/sysconfig.h> #include <sd-daemon.h> #include <iostream> #include <fstream> #include <cstdarg> #include <cstdlib> #if defined(HAVE_SYS_UTSNAME_H) # include <sys/utsname.h> #endif #if defined(HAVE_ZLIB_H) # include <zlib.h> #endif #if defined(HAVE_BZLIB_H) # include <bzlib.h> #endif #include <sys/resource.h> #include <sys/time.h> #include <pwd.h> #include <grp.h> #include <getopt.h> #include <stdio.h> #if 0 // !defined(XZERO_NDEBUG) # define TRACE(msg...) DEBUG("HttpServer: " msg) #else # define TRACE(msg...) do {} while (0) #endif namespace x0 { /** initializes the HTTP server object. * \param io_service an Asio io_service to use or nullptr to create our own one. * \see HttpServer::run() */ HttpServer::HttpServer(struct ::ev_loop *loop, unsigned generation) : requestHandler(), onConnectionOpen(), onPreProcess(), onResolveDocumentRoot(), onResolveEntity(), onPostProcess(), onRequestDone(), onConnectionClose(), onConnectionStateChanged(), onWorkerSpawn(), onWorkerUnspawn(), generation_(generation), listeners_(), loop_(loop ? loop : ev_default_loop(0)), startupTime_(ev_now(loop_)), logger_(), logLevel_(Severity::warn), colored_log_(false), workerIdPool_(0), workers_(), lastWorker_(0), maxConnections(512), maxKeepAlive(TimeSpan::fromSeconds(60)), maxKeepAliveRequests(100), maxReadIdle(TimeSpan::fromSeconds(60)), maxWriteIdle(TimeSpan::fromSeconds(360)), tcpCork(false), tcpNoDelay(false), lingering(TimeSpan::Zero), tag("x0/" VERSION), advertise(true), maxRequestUriSize(4 * 1024), maxRequestHeaderSize(1 * 1024), maxRequestHeaderCount(100), maxRequestBodySize(4 * 1024 * 1024), requestHeaderBufferSize(8 * 1024), requestBodyBufferSize(8 * 1024) { DebugLogger::get().onLogWrite = [&](const char* msg, size_t n) { LogMessage lm(Severity::debug1, "%s", msg); logger_->write(lm); }; HttpRequest::initialize(); logger_.reset(new FileLogger(STDERR_FILENO, [this]() { return static_cast<time_t>(ev_now(loop_)); })); // setting a reasonable default max-connection limit. // However, this cannot be computed as we do not know what the user // actually configures, such as fastcgi requires +1 fd, local file +1 fd, // http client connection of course +1 fd, listener sockets, etc. struct rlimit rlim; if (::getrlimit(RLIMIT_NOFILE, &rlim) == 0) maxConnections = std::max(int(rlim.rlim_cur / 3) - 5, 1); // Spawn main-thread worker spawnWorker(); } HttpServer::~HttpServer() { TRACE("destroying"); stop(); for (auto i: listeners_) delete i; while (!workers_.empty()) destroyWorker(workers_[workers_.size() - 1]); #ifndef __APPLE__ // explicit cleanup DebugLogger::get().reset(); #endif } void HttpServer::onNewConnection(std::unique_ptr<Socket>&& cs, ServerSocket* ss) { if (cs) { selectWorker()->enqueue(std::make_pair(std::move(cs), ss)); } else { log(Severity::error, "Accepting incoming connection failed. %s", strerror(errno)); } } // {{{ worker mgnt HttpWorker *HttpServer::spawnWorker() { bool isMainWorker = workers_.empty(); HttpWorker *worker = new HttpWorker(*this, isMainWorker ? loop_ : nullptr, workerIdPool_++, !isMainWorker); workers_.push_back(worker); return worker; } /** * Selects (by round-robin) the next worker. * * \return a worker * \note This method is not thread-safe, and thus, should not be invoked within a request handler. */ HttpWorker* HttpServer::nextWorker() { // select by RR (round-robin) // this is thread-safe since only one thread is to select a new worker // (the main thread) if (++lastWorker_ == workers_.size()) lastWorker_ = 0; return workers_[lastWorker_]; } HttpWorker *HttpServer::selectWorker() { #if 1 // defined(X0_WORKER_RR) return nextWorker(); #else // select by lowest connection load HttpWorker *best = workers_[0]; int value = best->connectionLoad(); for (size_t i = 1, e = workers_.size(); i != e; ++i) { HttpWorker *w = workers_[i]; int l = w->connectionLoad(); if (l < value) { value = l; best = w; } } return best; #endif } void HttpServer::destroyWorker(HttpWorker *worker) { auto i = std::find(workers_.begin(), workers_.end(), worker); assert(i != workers_.end()); worker->stop(); if (worker != workers_.front()) worker->join(); workers_.erase(i); delete worker; } // }}} /** calls run on the internally referenced io_service. * \note use this if you do not have your own main loop. * \note automatically starts the server if it wasn't started via \p start() yet. * \see start(), stop() */ int HttpServer::run() { workers_.front()->run(); return 0; } /** unregisters all listeners from the underlying io_service and calls stop on it. * \see start(), run() */ void HttpServer::stop() { for (auto listener: listeners_) listener->stop(); for (auto worker: workers_) worker->stop(); } void HttpServer::kill() { stop(); for (auto worker: workers_) worker->kill(); } void HttpServer::log(LogMessage&& msg) { if (logger_) { #if !defined(XZERO_NDEBUG) #ifndef __APPLE__ if (msg.isDebug() && msg.hasTags() && DebugLogger::get().isConfigured()) { int level = 3 - msg.severity(); // compute proper debug level Buffer text; text << msg; BufferRef tag = msg.tagAt(msg.tagCount() - 1); size_t i = tag.find('/'); if (i != tag.npos) tag = tag.ref(0, i); DebugLogger::get().logUntagged(tag.str(), level, "%s", text.c_str()); return; } #endif #endif logger_->write(msg); } } /** * sets up a TCP/IP ServerSocket on given bind_address and port. * * If there is already a ServerSocket on this bind_address:port pair * then no error will be raised. */ ServerSocket* HttpServer::setupListener(const std::string& bind_address, int port, int backlog) { return setupListener(SocketSpec::fromInet(IPAddress(bind_address), port, backlog)); } ServerSocket *HttpServer::setupUnixListener(const std::string& path, int backlog) { return setupListener(SocketSpec::fromLocal(path, backlog)); } ServerSocket* HttpServer::setupListener(const SocketSpec& _spec) { // validate backlog against system's hard limit SocketSpec spec(_spec); int somaxconn = SOMAXCONN; #if defined(__linux__) somaxconn = readFile("/proc/sys/net/core/somaxconn").toInt(); if (spec.backlog() > 0) { if (somaxconn && spec.backlog() > somaxconn) { log(Severity::error, "Listener %s configured with a backlog higher than the system permits (%ld > %ld). " "See /proc/sys/net/core/somaxconn for your system limits.", spec.str().c_str(), spec.backlog(), somaxconn); return nullptr; } } #endif // create a new listener ServerSocket* lp = new ServerSocket(loop_); lp->set<HttpServer, &HttpServer::onNewConnection>(this); listeners_.push_back(lp); if (spec.backlog() <= 0) lp->setBacklog(somaxconn); if (spec.multiAcceptCount() > 0) lp->setMultiAcceptCount(spec.multiAcceptCount()); if (lp->open(spec, O_NONBLOCK | O_CLOEXEC)) { log(Severity::info, "Listening on %s", spec.str().c_str()); return lp; } else { log(Severity::error, "Could not create listener %s: %s", spec.str().c_str(), lp->errorText().c_str()); return nullptr; } } void HttpServer::destroyListener(ServerSocket* listener) { for (auto i = listeners_.begin(), e = listeners_.end(); i != e; ++i) { if (*i == listener) { listeners_.erase(i); delete listener; break; } } } void HttpServer::setLogLevel(Severity s) { logLevel_ = s; logger()->setLevel(s); log(s > Severity::info ? s : Severity::info, "Logging level set to: %s", s.c_str()); } } // namespace x0 <|endoftext|>
<commit_before>// Copyright 2020 The Pigweed Authors // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // https://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. // This file implements a basic fuzz test for the TokenDatabase class // A database is created from fuzz data, and a random entry count (also // derived from the fuzz data) is set. We then run iterations and 'find' // operations on this database. #include <cstring> #include <span> #include "pw_fuzzer/asan_interface.h" #include "pw_fuzzer/fuzzed_data_provider.h" #include "pw_preprocessor/util.h" #include "pw_tokenizer/token_database.h" namespace pw::tokenizer { namespace { enum FuzzTestType : uint8_t { kValidHeader, kRandomHeader, kMaxValue = kRandomHeader, }; constexpr size_t kTokenHeaderSize = 16; // The default max length in bytes of fuzzed data provided. Note that // this needs to change if the fuzzer executable is run with a // '-max_len' argument. constexpr size_t kFuzzDataSizeMax = 4096; // Location of the 'EntryCount' field in the token header. constexpr size_t kEntryCountOffset = 8; constexpr size_t kEntryCountSize = 4; void SetTokenEntryCountInBuffer(uint8_t* buffer, uint32_t count) { memcpy(buffer + kEntryCountOffset, &count, kEntryCountSize); } void IterateOverDatabase(TokenDatabase* const database) { for (TokenDatabase::Entry entry : *database) { // Since we don't "use" the contents of the entry, we exercise // the entry by extracting its contents into volatile variables // to prevent it from being optimized out during compilation. volatile const char* entry_string = entry.string; volatile uint32_t entry_token = entry.token; PW_UNUSED(entry_string); PW_UNUSED(entry_token); } } } // namespace extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { constexpr size_t kBufferSizeMax = kFuzzDataSizeMax + kTokenHeaderSize; constexpr char kDefaultHeader[] = "TOKENS\0\0\0\0\0\0\0\0\0"; static uint8_t buffer[kBufferSizeMax]; if (size > kFuzzDataSizeMax) { return 0; } FuzzedDataProvider provider(data, size); // Initialize the token header with either a valid or invalid header // based on a random enum consumed from the fuzz data. switch (provider.ConsumeEnum<FuzzTestType>()) { case kValidHeader: memcpy(buffer, kDefaultHeader, kTokenHeaderSize); break; case kRandomHeader: { std::vector<uint8_t> random_header = provider.ConsumeBytes<uint8_t>(kTokenHeaderSize); random_header.resize(kTokenHeaderSize); memcpy(buffer, &random_header[0], kTokenHeaderSize); break; } } // Consume a 'test token' integer to look up later in the database. uint32_t random_token = provider.ConsumeIntegral<uint32_t>(); // Consume a 'token count' integer to set as our database entry count. uint32_t random_token_count = provider.ConsumeIntegralInRange<uint32_t>(0, kFuzzDataSizeMax); // Consume the remaining data. Note that the data corresponding to the // string entries in the database are not explicitly null-terminated. // TODO(karthikmb): Once OSS-Fuzz updates to Clang11.0, switch to // provider.ConsumeData() to avoid extra memory and the memcpy call. auto consumed_bytes = provider.ConsumeBytes<uint8_t>(provider.remaining_bytes()); memcpy(buffer + kTokenHeaderSize, &consumed_bytes[0], consumed_bytes.size()); SetTokenEntryCountInBuffer(buffer, random_token_count); // Poison the unused buffer space for this run of the fuzzer to // prevent the token database creator from reading too far in. size_t data_size = kTokenHeaderSize + consumed_bytes.size(); size_t poisoned_length = kBufferSizeMax - data_size; void* poisoned = &buffer[data_size]; ASAN_POISON_MEMORY_REGION(poisoned, poisoned_length); // We create a database from a std::span of the buffer since the string // entries might not be null terminated, and the creation of a database // from a raw buffer has an explicit null terminated string requirement // specified in the API. std::span<uint8_t> data_span(buffer, data_size); auto token_database = TokenDatabase::Create<std::span<uint8_t>>(data_span); volatile auto match = token_database.Find(random_token); PW_UNUSED(match); IterateOverDatabase(&token_database); // Un-poison for the next iteration. ASAN_UNPOISON_MEMORY_REGION(poisoned, poisoned_length); return 0; } } // namespace pw::tokenizer <commit_msg>pw_tokenizer: Add attributes on unused variables<commit_after>// Copyright 2020 The Pigweed Authors // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // https://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. // This file implements a basic fuzz test for the TokenDatabase class // A database is created from fuzz data, and a random entry count (also // derived from the fuzz data) is set. We then run iterations and 'find' // operations on this database. #include <cstring> #include <span> #include "pw_fuzzer/asan_interface.h" #include "pw_fuzzer/fuzzed_data_provider.h" #include "pw_preprocessor/util.h" #include "pw_tokenizer/token_database.h" namespace pw::tokenizer { namespace { enum FuzzTestType : uint8_t { kValidHeader, kRandomHeader, kMaxValue = kRandomHeader, }; constexpr size_t kTokenHeaderSize = 16; // The default max length in bytes of fuzzed data provided. Note that // this needs to change if the fuzzer executable is run with a // '-max_len' argument. constexpr size_t kFuzzDataSizeMax = 4096; // Location of the 'EntryCount' field in the token header. constexpr size_t kEntryCountOffset = 8; constexpr size_t kEntryCountSize = 4; void SetTokenEntryCountInBuffer(uint8_t* buffer, uint32_t count) { memcpy(buffer + kEntryCountOffset, &count, kEntryCountSize); } void IterateOverDatabase(TokenDatabase* const database) { for (TokenDatabase::Entry entry : *database) { // Since we don't "use" the contents of the entry, we exercise // the entry by extracting its contents into volatile variables // to prevent it from being optimized out during compilation. [[maybe_unused]] volatile const char* entry_string = entry.string; [[maybe_unused]] volatile uint32_t entry_token = entry.token; } } } // namespace extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { constexpr size_t kBufferSizeMax = kFuzzDataSizeMax + kTokenHeaderSize; constexpr char kDefaultHeader[] = "TOKENS\0\0\0\0\0\0\0\0\0"; static uint8_t buffer[kBufferSizeMax]; if (size > kFuzzDataSizeMax) { return 0; } FuzzedDataProvider provider(data, size); // Initialize the token header with either a valid or invalid header // based on a random enum consumed from the fuzz data. switch (provider.ConsumeEnum<FuzzTestType>()) { case kValidHeader: memcpy(buffer, kDefaultHeader, kTokenHeaderSize); break; case kRandomHeader: { std::vector<uint8_t> random_header = provider.ConsumeBytes<uint8_t>(kTokenHeaderSize); random_header.resize(kTokenHeaderSize); memcpy(buffer, &random_header[0], kTokenHeaderSize); break; } } // Consume a 'test token' integer to look up later in the database. uint32_t random_token = provider.ConsumeIntegral<uint32_t>(); // Consume a 'token count' integer to set as our database entry count. uint32_t random_token_count = provider.ConsumeIntegralInRange<uint32_t>(0, kFuzzDataSizeMax); // Consume the remaining data. Note that the data corresponding to the // string entries in the database are not explicitly null-terminated. // TODO(karthikmb): Once OSS-Fuzz updates to Clang11.0, switch to // provider.ConsumeData() to avoid extra memory and the memcpy call. auto consumed_bytes = provider.ConsumeBytes<uint8_t>(provider.remaining_bytes()); memcpy(buffer + kTokenHeaderSize, &consumed_bytes[0], consumed_bytes.size()); SetTokenEntryCountInBuffer(buffer, random_token_count); // Poison the unused buffer space for this run of the fuzzer to // prevent the token database creator from reading too far in. size_t data_size = kTokenHeaderSize + consumed_bytes.size(); size_t poisoned_length = kBufferSizeMax - data_size; void* poisoned = &buffer[data_size]; ASAN_POISON_MEMORY_REGION(poisoned, poisoned_length); // We create a database from a std::span of the buffer since the string // entries might not be null terminated, and the creation of a database // from a raw buffer has an explicit null terminated string requirement // specified in the API. std::span<uint8_t> data_span(buffer, data_size); auto token_database = TokenDatabase::Create<std::span<uint8_t>>(data_span); [[maybe_unused]] volatile auto match = token_database.Find(random_token); IterateOverDatabase(&token_database); // Un-poison for the next iteration. ASAN_UNPOISON_MEMORY_REGION(poisoned, poisoned_length); return 0; } } // namespace pw::tokenizer <|endoftext|>
<commit_before>/* * A auto-growing buffer you can write to. * * author: Max Kellermann <mk@cm4all.com> */ #include "growing_buffer.hxx" #include "pool.hxx" #include "util/ConstBuffer.hxx" #include "util/WritableBuffer.hxx" #include <assert.h> #include <string.h> struct buffer { struct buffer *next; size_t length; char data[sizeof(size_t)]; }; struct GrowingBuffer { struct pool *pool; #ifndef NDEBUG size_t initial_size; #endif size_t size; struct buffer *current, *tail, first; }; GrowingBuffer *gcc_malloc growing_buffer_new(struct pool *pool, size_t initial_size) { GrowingBuffer *gb = (GrowingBuffer *) p_malloc(pool, sizeof(*gb) - sizeof(gb->first.data) + initial_size); gb->pool = pool; #ifndef NDEBUG gb->initial_size = initial_size; #endif gb->size = initial_size; gb->current = &gb->first; gb->tail = &gb->first; gb->first.next = nullptr; gb->first.length = 0; return gb; } static void growing_buffer_append_buffer(GrowingBuffer *gb, struct buffer *buffer) { assert(gb != nullptr); assert(buffer != nullptr); assert(buffer->next == nullptr); gb->tail->next = buffer; gb->tail = buffer; } void * growing_buffer_write(GrowingBuffer *gb, size_t length) { struct buffer *buffer = gb->tail; void *ret; assert(gb->size > 0); if (buffer->length + length > gb->size) { if (gb->size < length) gb->size = length; /* XXX round up? */ buffer = (struct buffer *) p_malloc(gb->pool, sizeof(*buffer) - sizeof(buffer->data) + gb->size); buffer->next = nullptr; buffer->length = 0; growing_buffer_append_buffer(gb, buffer); } assert(buffer->length + length <= gb->size); ret = buffer->data + buffer->length; buffer->length += length; return ret; } void growing_buffer_write_buffer(GrowingBuffer *gb, const void *p, size_t length) { memcpy(growing_buffer_write(gb, length), p, length); } void growing_buffer_write_string(GrowingBuffer *gb, const char *p) { growing_buffer_write_buffer(gb, p, strlen(p)); } void growing_buffer_cat(GrowingBuffer *dest, GrowingBuffer *src) { dest->tail->next = &src->first; dest->tail = src->tail; dest->size = src->size; } size_t growing_buffer_size(const GrowingBuffer *gb) { size_t size = 0; for (const struct buffer *buffer = &gb->first; buffer != nullptr; buffer = buffer->next) size += buffer->length; return size; } GrowingBufferReader::GrowingBufferReader(const GrowingBuffer &gb) #ifndef NDEBUG :growing_buffer(&gb) #endif { assert(gb.first.length > 0 || gb.first.next == nullptr || (gb.first.next != nullptr && gb.size > gb.initial_size && gb.first.next->length > gb.initial_size)); buffer = &gb.first; if (buffer->length == 0 && buffer->next != nullptr) buffer = buffer->next; position = 0; } void GrowingBufferReader::Update() { assert(buffer != nullptr); assert(position <= buffer->length); if (position == buffer->length && buffer->next != nullptr) { /* the reader was at the end of all buffers, but then a new buffer was appended */ buffer = buffer->next; position = 0; } } bool GrowingBufferReader::IsEOF() const { assert(buffer != nullptr); assert(position <= buffer->length); return position == buffer->length; } size_t GrowingBufferReader::Available() const { assert(buffer != nullptr); assert(position <= buffer->length); size_t available = buffer->length - position; for (const struct buffer *b = buffer->next; b != nullptr; b = b->next) { assert(b->length > 0); available += b->length; } return available; } ConstBuffer<void> GrowingBufferReader::Read() const { assert(buffer != nullptr); const struct buffer *b = buffer; if (b->length == 0 && b->next != nullptr) { /* skip the empty first buffer that was too small */ assert(b == &growing_buffer->first); assert(position == 0); b = b->next; } if (position >= b->length) { assert(position == b->length); assert(buffer->next == nullptr); return nullptr; } return { b->data + position, b->length - position }; } void GrowingBufferReader::Consume(size_t length) { assert(buffer != nullptr); if (length == 0) return; if (buffer->length == 0 && buffer->next != nullptr) { /* skip the empty first buffer that was too small */ assert(buffer == &growing_buffer->first); assert(position == 0); buffer = buffer->next; } position += length; assert(position <= buffer->length); if (position >= buffer->length) { if (buffer->next == nullptr) return; buffer = buffer->next; position = 0; } } void GrowingBufferReader::Skip(size_t length) { assert(buffer != nullptr); while (length > 0) { size_t remaining = buffer->length - position; if (length < remaining || (length == remaining && buffer->next == nullptr)) { position += length; return; } length -= remaining; assert(buffer->next != nullptr); buffer = buffer->next; position = 0; } } static void * growing_buffer_copy(void *dest0, const GrowingBuffer *gb) { unsigned char *dest = (unsigned char *)dest0; for (const struct buffer *buffer = &gb->first; buffer != nullptr; buffer = buffer->next) { memcpy(dest, buffer->data, buffer->length); dest += buffer->length; } return dest; } WritableBuffer<void> growing_buffer_dup(const GrowingBuffer *gb, struct pool *pool) { size_t length; length = growing_buffer_size(gb); if (length == 0) return nullptr; void *dest = p_malloc(pool, length); growing_buffer_copy(dest, gb); return { dest, length }; } <commit_msg>growing_buffer: fix assertion failure when skipping to end<commit_after>/* * A auto-growing buffer you can write to. * * author: Max Kellermann <mk@cm4all.com> */ #include "growing_buffer.hxx" #include "pool.hxx" #include "util/ConstBuffer.hxx" #include "util/WritableBuffer.hxx" #include <assert.h> #include <string.h> struct buffer { struct buffer *next; size_t length; char data[sizeof(size_t)]; }; struct GrowingBuffer { struct pool *pool; #ifndef NDEBUG size_t initial_size; #endif size_t size; struct buffer *current, *tail, first; }; GrowingBuffer *gcc_malloc growing_buffer_new(struct pool *pool, size_t initial_size) { GrowingBuffer *gb = (GrowingBuffer *) p_malloc(pool, sizeof(*gb) - sizeof(gb->first.data) + initial_size); gb->pool = pool; #ifndef NDEBUG gb->initial_size = initial_size; #endif gb->size = initial_size; gb->current = &gb->first; gb->tail = &gb->first; gb->first.next = nullptr; gb->first.length = 0; return gb; } static void growing_buffer_append_buffer(GrowingBuffer *gb, struct buffer *buffer) { assert(gb != nullptr); assert(buffer != nullptr); assert(buffer->next == nullptr); gb->tail->next = buffer; gb->tail = buffer; } void * growing_buffer_write(GrowingBuffer *gb, size_t length) { struct buffer *buffer = gb->tail; void *ret; assert(gb->size > 0); if (buffer->length + length > gb->size) { if (gb->size < length) gb->size = length; /* XXX round up? */ buffer = (struct buffer *) p_malloc(gb->pool, sizeof(*buffer) - sizeof(buffer->data) + gb->size); buffer->next = nullptr; buffer->length = 0; growing_buffer_append_buffer(gb, buffer); } assert(buffer->length + length <= gb->size); ret = buffer->data + buffer->length; buffer->length += length; return ret; } void growing_buffer_write_buffer(GrowingBuffer *gb, const void *p, size_t length) { memcpy(growing_buffer_write(gb, length), p, length); } void growing_buffer_write_string(GrowingBuffer *gb, const char *p) { growing_buffer_write_buffer(gb, p, strlen(p)); } void growing_buffer_cat(GrowingBuffer *dest, GrowingBuffer *src) { dest->tail->next = &src->first; dest->tail = src->tail; dest->size = src->size; } size_t growing_buffer_size(const GrowingBuffer *gb) { size_t size = 0; for (const struct buffer *buffer = &gb->first; buffer != nullptr; buffer = buffer->next) size += buffer->length; return size; } GrowingBufferReader::GrowingBufferReader(const GrowingBuffer &gb) #ifndef NDEBUG :growing_buffer(&gb) #endif { assert(gb.first.length > 0 || gb.first.next == nullptr || (gb.first.next != nullptr && gb.size > gb.initial_size && gb.first.next->length > gb.initial_size)); buffer = &gb.first; if (buffer->length == 0 && buffer->next != nullptr) buffer = buffer->next; position = 0; } void GrowingBufferReader::Update() { assert(buffer != nullptr); assert(position <= buffer->length); if (position == buffer->length && buffer->next != nullptr) { /* the reader was at the end of all buffers, but then a new buffer was appended */ buffer = buffer->next; position = 0; } } bool GrowingBufferReader::IsEOF() const { assert(buffer != nullptr); assert(position <= buffer->length); return position == buffer->length; } size_t GrowingBufferReader::Available() const { assert(buffer != nullptr); assert(position <= buffer->length); size_t available = buffer->length - position; for (const struct buffer *b = buffer->next; b != nullptr; b = b->next) { assert(b->length > 0); available += b->length; } return available; } ConstBuffer<void> GrowingBufferReader::Read() const { assert(buffer != nullptr); const struct buffer *b = buffer; if (b->length == 0 && b->next != nullptr) { /* skip the empty first buffer that was too small */ assert(b == &growing_buffer->first); assert(position == 0); b = b->next; } if (position >= b->length) { assert(position == b->length); assert(buffer->next == nullptr); return nullptr; } return { b->data + position, b->length - position }; } void GrowingBufferReader::Consume(size_t length) { assert(buffer != nullptr); if (length == 0) return; if (buffer->length == 0 && buffer->next != nullptr) { /* skip the empty first buffer that was too small */ assert(buffer == &growing_buffer->first); assert(position == 0); buffer = buffer->next; } position += length; assert(position <= buffer->length); if (position >= buffer->length) { if (buffer->next == nullptr) return; buffer = buffer->next; position = 0; } } void GrowingBufferReader::Skip(size_t length) { assert(buffer != nullptr); while (length > 0) { size_t remaining = buffer->length - position; if (length < remaining || (length == remaining && buffer->next == nullptr)) { position += length; return; } length -= remaining; if (buffer->next == nullptr) { assert(position + remaining == length); position = length; return; } assert(buffer->next != nullptr); buffer = buffer->next; position = 0; } } static void * growing_buffer_copy(void *dest0, const GrowingBuffer *gb) { unsigned char *dest = (unsigned char *)dest0; for (const struct buffer *buffer = &gb->first; buffer != nullptr; buffer = buffer->next) { memcpy(dest, buffer->data, buffer->length); dest += buffer->length; } return dest; } WritableBuffer<void> growing_buffer_dup(const GrowingBuffer *gb, struct pool *pool) { size_t length; length = growing_buffer_size(gb); if (length == 0) return nullptr; void *dest = p_malloc(pool, length); growing_buffer_copy(dest, gb); return { dest, length }; } <|endoftext|>
<commit_before>/* Cycript - Optimizing JavaScript Compiler/Runtime * Copyright (C) 2009-2012 Jay Freeman (saurik) */ /* GNU Lesser General Public License, Version 3 {{{ */ /* * Cycript 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. * * Cycript 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 Cycript. If not, see <http://www.gnu.org/licenses/>. **/ /* }}} */ #include "Highlight.hpp" #include "Cycript.tab.hh" #include "Parser.hpp" static void Skip(const char *data, size_t size, std::ostream &output, size_t &offset, cy::position &current, cy::position target) { while (current.line != target.line || current.column != target.column) { _assert(offset != size); char next(data[offset++]); output.put(next); _assert(current.line < target.line || current.line == target.line && current.column < target.column); if (next == '\n') current.lines(); else current.columns(); } } struct CYColor { bool bold_; unsigned code_; CYColor() { } CYColor(bool bold, unsigned code) : bold_(bold), code_(code) { } }; void CYLexerHighlight(const char *data, size_t size, std::ostream &output, bool ignore) { CYStream stream(data, data + size); CYDriver driver(stream); driver.commented_ = true; size_t offset(0); cy::position current; CYLocalPool pool; YYSTYPE value; cy::location location; while (cylex(&value, &location, driver.scanner_) != 0) { CYColor color; switch (value.highlight_) { case hi::Comment: color = CYColor(true, 30); break; case hi::Constant: color = CYColor(false, 31); break; case hi::Control: color = CYColor(false, 33); break; case hi::Escape: color = CYColor(true, 31); break; case hi::Identifier: color = CYColor(false, 0); break; case hi::Meta: color = CYColor(false, 32); break; case hi::Nothing: color = CYColor(false, 0); break; case hi::Operator: color = CYColor(false, 36); break; case hi::Structure: color = CYColor(true, 34); break; case hi::Type: color = CYColor(true, 34); break; } Skip(data, size, output, offset, current, location.begin); if (color.code_ != 0) { if (ignore) output << CYIgnoreStart; output << "\e[" << (color.bold_ ? '1' : '0') << ";" << color.code_ << "m"; if (ignore) output << CYIgnoreEnd; } Skip(data, size, output, offset, current, location.end); if (color.code_ != 0) { if (ignore) output << CYIgnoreStart; output << "\e[0m"; if (ignore) output << CYIgnoreEnd; } } output.write(data + offset, size - offset); } <commit_msg>Protect against fall-through of color selection.<commit_after>/* Cycript - Optimizing JavaScript Compiler/Runtime * Copyright (C) 2009-2012 Jay Freeman (saurik) */ /* GNU Lesser General Public License, Version 3 {{{ */ /* * Cycript 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. * * Cycript 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 Cycript. If not, see <http://www.gnu.org/licenses/>. **/ /* }}} */ #include "Highlight.hpp" #include "Cycript.tab.hh" #include "Parser.hpp" static void Skip(const char *data, size_t size, std::ostream &output, size_t &offset, cy::position &current, cy::position target) { while (current.line != target.line || current.column != target.column) { _assert(offset != size); char next(data[offset++]); output.put(next); _assert(current.line < target.line || current.line == target.line && current.column < target.column); if (next == '\n') current.lines(); else current.columns(); } } struct CYColor { bool bold_; unsigned code_; CYColor() { } CYColor(bool bold, unsigned code) : bold_(bold), code_(code) { } }; void CYLexerHighlight(const char *data, size_t size, std::ostream &output, bool ignore) { CYStream stream(data, data + size); CYDriver driver(stream); driver.commented_ = true; size_t offset(0); cy::position current; CYLocalPool pool; YYSTYPE value; cy::location location; while (cylex(&value, &location, driver.scanner_) != 0) { CYColor color; switch (value.highlight_) { case hi::Comment: color = CYColor(true, 30); break; case hi::Constant: color = CYColor(false, 31); break; case hi::Control: color = CYColor(false, 33); break; case hi::Escape: color = CYColor(true, 31); break; case hi::Identifier: color = CYColor(false, 0); break; case hi::Meta: color = CYColor(false, 32); break; case hi::Nothing: color = CYColor(false, 0); break; case hi::Operator: color = CYColor(false, 36); break; case hi::Structure: color = CYColor(true, 34); break; case hi::Type: color = CYColor(true, 34); break; // XXX: maybe I should use nodefault here? default: color = CYColor(true, 0); break; } Skip(data, size, output, offset, current, location.begin); if (color.code_ != 0) { if (ignore) output << CYIgnoreStart; output << "\e[" << (color.bold_ ? '1' : '0') << ";" << color.code_ << "m"; if (ignore) output << CYIgnoreEnd; } Skip(data, size, output, offset, current, location.end); if (color.code_ != 0) { if (ignore) output << CYIgnoreStart; output << "\e[0m"; if (ignore) output << CYIgnoreEnd; } } output.write(data + offset, size - offset); } <|endoftext|>
<commit_before>#include <vector> #include <iostream> #include <iterator> #include <algorithm> #include <Spark/SparseLinearSolvers.hpp> #include <Spark/ConjugateGradient.hpp> #include <Spark/converters.hpp> #include <Spark/io.hpp> #include <boost/numeric/ublas/io.hpp> #include <dfesnippets/blas/Blas.hpp> #include <dfesnippets/sparse/utils.hpp> #include <Eigen/Sparse> using Td = Eigen::Triplet<double>; using Md = Eigen::SparseMatrix<double>; Md one(int m) { std::vector<Td> nnzs; for (int i = 0; i < m; i++) nnzs.push_back(Td(i, i, 1)); Md a(m, m); a.setFromTriplets(nnzs.begin(), nnzs.end()); return a; } // functor to generate a matrix struct IdentityGenerator { Md operator()(int m) { return one(m); } }; struct RandomGenerator { Md operator()(int m) { return one(m) * 2; } }; struct EigenMatrixGenerator { Md matrix; EigenMatrixGenerator(Md _matrix) : matrix(_matrix) {} Md operator()(int m) { return matrix; } }; template<typename MatrixGenerator> int test(int m, MatrixGenerator mg) { Md a = mg(m); Eigen::VectorXd x(m); for (int i = 0; i < m; i++) x[i] = i; Eigen::VectorXd b = a * x; spark::sparse_linear_solvers::EigenSolver es; std::vector<double> sol(m); std::vector<double> newb(b.data(), b.data() + b.size()); es.solve(a, &sol[0], &newb[0]); spark::cg::DfeCg cg{}; auto ublas = spark::converters::eigenToUblas(a); std::vector<double> res = cg.solve(*ublas, newb); bool check = std::equal(sol.begin(), sol.end(), res.begin(), [](double a, double b) { return dfesnippets::utils::almost_equal(a, b, 1E-10, 1E-15); }); if (!check) { std::cout << "Results didn't match" << std::endl; std::cout << "Solution (EIGEN): " << std::endl; std::copy(sol.begin(), sol.end(), std::ostream_iterator<double>{std::cout, " "}); std::cout << std::endl; std::cout << "Solution (DFE): " << std::endl; std::copy(res.begin(), res.end(), std::ostream_iterator<double>{std::cout, " "}); std::cout << std::endl; return 1; } return 0; } int main() { //test(16, IdentityGenerator{}); //test(100, RandomGenerator{}); spark::io::MmReader<double> m; auto matrix = m.mmread("../test-matrices/bfwb62.mtx"); auto eigenMatrix = spark::converters::tripletToEigen(matrix); int status = 0; status |= test(eigenMatrix->rows(), EigenMatrixGenerator(*eigenMatrix)); //for_each(matrix.begin(), matrix.end(), //[] (std::tuple<int, int, double> tpl) { //std::cout << std::get<0>(tpl) << " " << std::get<1>(tpl) << " " << std::get<2>(tpl) << std::endl; //}); // std::cout << *eigenMatrix << std::endl; return status; } <commit_msg>Use a functor to generate Rhs<commit_after>#include <vector> #include <iostream> #include <iterator> #include <algorithm> #include <Spark/SparseLinearSolvers.hpp> #include <Spark/ConjugateGradient.hpp> #include <Spark/converters.hpp> #include <Spark/io.hpp> #include <boost/numeric/ublas/io.hpp> #include <dfesnippets/blas/Blas.hpp> #include <dfesnippets/sparse/utils.hpp> #include <Eigen/Sparse> using Td = Eigen::Triplet<double>; using Vd = Eigen::VectorXd; using Md = Eigen::SparseMatrix<double>; Md one(int m) { std::vector<Td> nnzs; for (int i = 0; i < m; i++) nnzs.push_back(Td(i, i, 1)); Md a(m, m); a.setFromTriplets(nnzs.begin(), nnzs.end()); return a; } // functor to generate a matrix struct IdentityGenerator { Md operator()(int m) { return one(m); } }; struct RandomGenerator { Md operator()(int m) { return one(m) * 2; } }; struct EigenMatrixGenerator { Md matrix; EigenMatrixGenerator(Md _matrix) : matrix(_matrix) {} Md operator()(int m) { return matrix; } }; struct SimpleRhsGenerator { Vd operator()(Md mat, int m) { Eigen::VectorXd x(m); for (int i = 0; i < m; i++) x[i] = i; return mat * x; } }; template<typename MatrixGenerator, typename RhsGenerator> int test(int m, MatrixGenerator mg, RhsGenerator rhsg) { Md a = mg(m); Eigen::VectorXd b = rhsg(a, m); spark::sparse_linear_solvers::EigenSolver es; std::vector<double> sol(m); std::vector<double> newb(b.data(), b.data() + b.size()); es.solve(a, &sol[0], &newb[0]); spark::cg::DfeCg cg{}; auto ublas = spark::converters::eigenToUblas(a); std::vector<double> res = cg.solve(*ublas, newb); bool check = std::equal(sol.begin(), sol.end(), res.begin(), [](double a, double b) { return dfesnippets::utils::almost_equal(a, b, 1E-10, 1E-15); }); if (!check) { std::cout << "Results didn't match" << std::endl; std::cout << "Solution (EIGEN): " << std::endl; std::copy(sol.begin(), sol.end(), std::ostream_iterator<double>{std::cout, " "}); std::cout << std::endl; std::cout << "Solution (DFE): " << std::endl; std::copy(res.begin(), res.end(), std::ostream_iterator<double>{std::cout, " "}); std::cout << std::endl; return 1; } return 0; } int main() { //test(16, IdentityGenerator{}); //test(100, RandomGenerator{}); spark::io::MmReader<double> m; auto matrix = m.mmread("../test-matrices/bfwb62.mtx"); auto eigenMatrix = spark::converters::tripletToEigen(matrix); int status = 0; status |= test(eigenMatrix->rows(), EigenMatrixGenerator{*eigenMatrix}, SimpleRhsGenerator{}); //for_each(matrix.begin(), matrix.end(), //[] (std::tuple<int, int, double> tpl) { //std::cout << std::get<0>(tpl) << " " << std::get<1>(tpl) << " " << std::get<2>(tpl) << std::endl; //}); // std::cout << *eigenMatrix << std::endl; return status; } <|endoftext|>
<commit_before>/** \file add_synonyms.cc * \brief Generic version for augmenting title data with synonyms found in the authority data * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen 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/>. */ /* We offer a list of tags and subfields where the primary data resides along with a list of tags and subfields where the synonym data is found and a list of unused fields in the title data where the synonyms can be stored */ #include <iostream> #include <map> #include <vector> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MarcUtil.h" #include "MarcXmlWriter.h" #include "MediaTypeUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" static unsigned modified_count(0); static unsigned record_count(0); void Usage() { std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n"; std::exit(EXIT_FAILURE); } std::string GetTag(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(0, 3); } std::string GetSubfields(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(3); } void ExtractSynonyms(File * const norm_data_marc_input, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &synonym_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> * const synonym_maps) { while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(norm_data_marc_input)) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator synonym; unsigned int i(0); for (primary = primary_tags_and_subfield_codes.begin(), synonym = synonym_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++synonym, ++i) { // Fill maps with synonyms std::vector<std::string> primary_values; std::vector<std::string> synonym_values; if (record.extractSubfields(GetTag(*primary), GetSubfields(*primary), &primary_values) and record.extractSubfields(GetTag(*synonym), GetSubfields(*synonym), &synonym_values)) (*synonym_maps)[i].emplace(StringUtil::Join(primary_values, ','), StringUtil::Join(synonym_values, ',')); } } } void ProcessRecord(MarcUtil::Record * const record, std::vector<std::map<std::string, std::string>> &synonym_maps, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator output; unsigned int i(0); if (primary_tags_and_subfield_codes.size() == output_tags_and_subfield_codes.size()) { for (primary = primary_tags_and_subfield_codes.begin(), output = output_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++output, ++i) { std::vector<std::string> primary_values; std::string synonyms; if (record->extractSubfields(GetTag(*primary), GetSubfields(*primary), &primary_values)) { // First case: Look up synonyms only in one category if (i < synonym_maps.size()) synonyms = synonym_maps[i][StringUtil::Join(primary_values, ',')]; // Second case: Look up synonyms in all categories else { for (auto sm : synonym_maps) synonyms += sm[StringUtil::Join(primary_values, ',')]; } if (synonyms.empty()) continue; // Insert synonyms // Abort if field is already populated std::string tag(GetTag(*output)); if (record->getFieldIndex(tag) != -1) Error("Field with tag " + tag + " is not empty for PPN " + record->getControlNumber() + '\n'); std::string subfield_spec = GetSubfields(*output); if (subfield_spec.size() != 1) Error("We currently only support a single subfield and thus specifying " + subfield_spec + " as output subfield is not valid\n"); Subfields subfields(' ', ' '); // <- indicators must be set explicitly although empty subfields.addSubfield(subfield_spec.at(0), synonyms); if (not(record->insertField(tag, subfields.toString()))) Warning("Could not insert field " + tag + " for PPN " + record->getControlNumber() + '\n'); ++modified_count; } } } } void InsertSynonyms(File * const marc_input, File * marc_output, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> &synonym_maps) { MarcXmlWriter xml_writer(marc_output); while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_input)) { ProcessRecord(&record, synonym_maps, primary_tags_and_subfield_codes, output_tags_and_subfield_codes); record.write(&xml_writer); ++record_count; } std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n"; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 4) Usage(); const std::string marc_input_filename(argv[1]); std::unique_ptr<File> marc_input(FileUtil::OpenInputFileOrDie(marc_input_filename)); const std::string norm_data_marc_input_filename(argv[2]); std::unique_ptr<File> norm_data_marc_input(FileUtil::OpenInputFileOrDie(norm_data_marc_input_filename)); const std::string marc_output_filename(argv[3]); if (unlikely(marc_input_filename == marc_output_filename)) Error("Title data input file name equals output file name!"); if (unlikely(norm_data_marc_input_filename == marc_output_filename)) Error("Authority data input file name equals output file name!"); File marc_output(marc_output_filename, "w"); if (not marc_output) Error("can't open \"" + marc_output_filename + "\" for writing!"); try { // Determine possible mappings const std::string AUTHORITY_DATA_PRIMARY_SPEC("110abcd:111abcd:130abcd:150abcd:151abcd"); const std::string AUTHORITY_DATA_SYNONYM_SPEC("410abcd:411abcd:430abcd:450abcd:451abcd"); const std::string TITLE_DATA_PRIMARY_SPEC("610abcd:611abcd:630abcd:650abcd:651abcd:689abcd"); const std::string TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS("180a:181a:182a:183a:184a:185a"); // Determine fields to handle std::set<std::string> primary_tags_and_subfield_codes; std::set<std::string> synonym_tags_and_subfield_codes; std::set<std::string> input_tags_and_subfield_codes; std::set<std::string> output_tags_and_subfield_codes; if (unlikely(StringUtil::Split(AUTHORITY_DATA_PRIMARY_SPEC, ":", &primary_tags_and_subfield_codes) < 1)) Error("Need at least one primary field"); if (unlikely(StringUtil::Split(AUTHORITY_DATA_SYNONYM_SPEC, ":", &synonym_tags_and_subfield_codes) < 1)) Error("Need at least one synonym field"); if (unlikely(StringUtil::Split(TITLE_DATA_PRIMARY_SPEC, ":", &input_tags_and_subfield_codes) < 1)) Error("Need at least one input field"); if (unlikely(StringUtil::Split(TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS, ":", &output_tags_and_subfield_codes) < 1)) Error("Need at least one output field"); unsigned num_of_authority_entries(primary_tags_and_subfield_codes.size()); if (synonym_tags_and_subfield_codes.size() != num_of_authority_entries) Error("Number of authority primary specs must match number of synonym specs"); if (input_tags_and_subfield_codes.size() != output_tags_and_subfield_codes.size()) Error("Number of fields title entry specs must match number of output specs"); std::vector<std::map<std::string, std::string>> synonym_maps(num_of_authority_entries, std::map<std::string, std::string>()); // Extract the synonyms from authority data ExtractSynonyms(norm_data_marc_input.get(), primary_tags_and_subfield_codes, synonym_tags_and_subfield_codes, &synonym_maps); // Iterate over the title data InsertSynonyms(marc_input.get(), &marc_output, input_tags_and_subfield_codes, output_tags_and_subfield_codes, synonym_maps); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <commit_msg>Required adjustments<commit_after>/** \file add_synonyms.cc * \brief Generic version for augmenting title data with synonyms found in the authority data * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen 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/>. */ /* We offer a list of tags and subfields where the primary data resides along with a list of tags and subfields where the synonym data is found and a list of unused fields in the title data where the synonyms can be stored */ #include <iostream> #include <map> #include <vector> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MarcUtil.h" #include "MarcXmlWriter.h" #include "MediaTypeUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" static unsigned modified_count(0); static unsigned record_count(0); void Usage() { std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n"; std::exit(EXIT_FAILURE); } std::string GetTag(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(0, 3); } std::string GetSubfields(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(3); } void ExtractSynonyms(File * const norm_data_marc_input, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &synonym_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> * const synonym_maps) { while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(norm_data_marc_input)) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator synonym; unsigned int i(0); for (primary = primary_tags_and_subfield_codes.begin(), synonym = synonym_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++synonym, ++i) { // Fill maps with synonyms std::vector<std::string> primary_values; std::vector<std::string> synonym_values; if (record.extractSubfields(GetTag(*primary), GetSubfields(*primary), &primary_values) and record.extractSubfields(GetTag(*synonym), GetSubfields(*synonym), &synonym_values)) (*synonym_maps)[i].emplace(StringUtil::Join(primary_values, ','), StringUtil::Join(synonym_values, ',')); } } } void ProcessRecord(MarcUtil::Record * const record, const std::vector<std::map<std::string, std::string>> &synonym_maps, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator output; unsigned int i(0); if (primary_tags_and_subfield_codes.size() == output_tags_and_subfield_codes.size()) { for (primary = primary_tags_and_subfield_codes.begin(), output = output_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++output, ++i) { std::vector<std::string> primary_values; std::string synonyms; if (record->extractSubfields(GetTag(*primary), GetSubfields(*primary), &primary_values)) { // First case: Look up synonyms only in one category if (i < synonym_maps.size()) { const auto synonym_map(synonym_maps[i]); synonyms = synonym_map.find(StringUtil::Join(primary_values, ','))->second; } // Second case: Look up synonyms in all categories else { for (auto sm : synonym_maps) synonyms += sm[StringUtil::Join(primary_values, ',')]; } if (synonyms.empty()) continue; // Insert synonyms // Abort if field is already populated std::string tag(GetTag(*output)); if (record->getFieldIndex(tag) != -1) Error("Field with tag " + tag + " is not empty for PPN " + record->getControlNumber() + '\n'); std::string subfield_spec = GetSubfields(*output); if (subfield_spec.size() != 1) Error("We currently only support a single subfield and thus specifying " + subfield_spec + " as output subfield is not valid\n"); Subfields subfields(' ', ' '); // <- indicators must be set explicitly although empty subfields.addSubfield(subfield_spec.at(0), synonyms); if (not(record->insertField(tag, subfields.toString()))) Warning("Could not insert field " + tag + " for PPN " + record->getControlNumber() + '\n'); ++modified_count; } } } } void InsertSynonyms(File * const marc_input, File * marc_output, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> &synonym_maps) { MarcXmlWriter xml_writer(marc_output); while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_input)) { ProcessRecord(&record, synonym_maps, primary_tags_and_subfield_codes, output_tags_and_subfield_codes); record.write(&xml_writer); ++record_count; } std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n"; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 4) Usage(); const std::string marc_input_filename(argv[1]); std::unique_ptr<File> marc_input(FileUtil::OpenInputFileOrDie(marc_input_filename)); const std::string norm_data_marc_input_filename(argv[2]); std::unique_ptr<File> norm_data_marc_input(FileUtil::OpenInputFileOrDie(norm_data_marc_input_filename)); const std::string marc_output_filename(argv[3]); if (unlikely(marc_input_filename == marc_output_filename)) Error("Title data input file name equals output file name!"); if (unlikely(norm_data_marc_input_filename == marc_output_filename)) Error("Authority data input file name equals output file name!"); File marc_output(marc_output_filename, "w"); if (not marc_output) Error("can't open \"" + marc_output_filename + "\" for writing!"); try { // Determine possible mappings const std::string AUTHORITY_DATA_PRIMARY_SPEC("110abcd:111abcd:130abcd:150abcd:151abcd"); const std::string AUTHORITY_DATA_SYNONYM_SPEC("410abcd:411abcd:430abcd:450abcd:451abcd"); const std::string TITLE_DATA_PRIMARY_SPEC("610abcd:611abcd:630abcd:650abcd:651abcd:689abcd"); const std::string TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS("180a:181a:182a:183a:184a:185a"); // Determine fields to handle std::set<std::string> primary_tags_and_subfield_codes; std::set<std::string> synonym_tags_and_subfield_codes; std::set<std::string> input_tags_and_subfield_codes; std::set<std::string> output_tags_and_subfield_codes; if (unlikely(StringUtil::Split(AUTHORITY_DATA_PRIMARY_SPEC, ":", &primary_tags_and_subfield_codes) < 1)) Error("Need at least one primary field"); if (unlikely(StringUtil::Split(AUTHORITY_DATA_SYNONYM_SPEC, ":", &synonym_tags_and_subfield_codes) < 1)) Error("Need at least one synonym field"); if (unlikely(StringUtil::Split(TITLE_DATA_PRIMARY_SPEC, ":", &input_tags_and_subfield_codes) < 1)) Error("Need at least one input field"); if (unlikely(StringUtil::Split(TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS, ":", &output_tags_and_subfield_codes) < 1)) Error("Need at least one output field"); unsigned num_of_authority_entries(primary_tags_and_subfield_codes.size()); if (synonym_tags_and_subfield_codes.size() != num_of_authority_entries) Error("Number of authority primary specs must match number of synonym specs"); if (input_tags_and_subfield_codes.size() != output_tags_and_subfield_codes.size()) Error("Number of fields title entry specs must match number of output specs"); std::vector<std::map<std::string, std::string>> synonym_maps(num_of_authority_entries, std::map<std::string, std::string>()); // Extract the synonyms from authority data ExtractSynonyms(norm_data_marc_input.get(), primary_tags_and_subfield_codes, synonym_tags_and_subfield_codes, &synonym_maps); // Iterate over the title data InsertSynonyms(marc_input.get(), &marc_output, input_tags_and_subfield_codes, output_tags_and_subfield_codes, synonym_maps); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>#include "board.hpp" #include "exception.hpp" #include "gtest/gtest.h" class BoardTest : public ::testing::Test { protected: BoardTest() : board_(1, 2) { } Quoridor::Board board_; }; TEST_F(BoardTest, ctor) { EXPECT_EQ(1, board_.row_num()); EXPECT_EQ(2, board_.col_num()); // test invalid Board construction EXPECT_THROW(Quoridor::Board(-1, 1), Quoridor::Exception); EXPECT_THROW(Quoridor::Board(8, 0), Quoridor::Exception); } TEST_F(BoardTest, set_size) { // test invalid Board sizes EXPECT_THROW(board_.set_size(0, 0), Quoridor::Exception); EXPECT_THROW(board_.set_size(0, 1), Quoridor::Exception); EXPECT_THROW(board_.set_size(1, 0), Quoridor::Exception); EXPECT_THROW(board_.set_size(-1, -1), Quoridor::Exception); EXPECT_THROW(board_.set_size(-1, 1), Quoridor::Exception); EXPECT_THROW(board_.set_size(1, -1), Quoridor::Exception); board_.set_size(10, 11); EXPECT_EQ(10, board_.row_num()); EXPECT_EQ(11, board_.col_num()); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Add tests for Board add_wall method.<commit_after>#include "board.hpp" #include "exception.hpp" #include "gtest/gtest.h" class BoardTest : public ::testing::Test { protected: BoardTest() : board_(8, 9) { } Quoridor::Board board_; }; TEST_F(BoardTest, ctor) { EXPECT_EQ(8, board_.row_num()); EXPECT_EQ(9, board_.col_num()); // test invalid Board construction EXPECT_THROW(Quoridor::Board(-1, 1), Quoridor::Exception); EXPECT_THROW(Quoridor::Board(8, 0), Quoridor::Exception); } TEST_F(BoardTest, set_size) { // test invalid Board sizes EXPECT_THROW(board_.set_size(0, 0), Quoridor::Exception); EXPECT_THROW(board_.set_size(0, 1), Quoridor::Exception); EXPECT_THROW(board_.set_size(1, 0), Quoridor::Exception); EXPECT_THROW(board_.set_size(-1, -1), Quoridor::Exception); EXPECT_THROW(board_.set_size(-1, 1), Quoridor::Exception); EXPECT_THROW(board_.set_size(1, -1), Quoridor::Exception); board_.set_size(10, 11); EXPECT_EQ(10, board_.row_num()); EXPECT_EQ(11, board_.col_num()); } TEST_F(BoardTest, add_wall) { // add valid walls EXPECT_EQ(0, board_.add_wall(Quoridor::Wall(0, 0, 0, 2))); EXPECT_EQ(0, board_.add_wall(Quoridor::Wall(0, 0, 2, 2))); // add walls beyond the board EXPECT_EQ(-1, board_.add_wall(Quoridor::Wall(0, 10, 0, 2))); // add intersecting walls EXPECT_EQ(-2, board_.add_wall(Quoridor::Wall(0, 0, 0, 1))); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <benchmark/benchmark.h> #include <fmt/format.h> #include <array> #include <bitset> #include <iostream> #include <map> #include <sstream> #include <string> #include <vector> using namespace std; using count_t = long long; // See discussion at // https://stackoverflow.com/questions/40122141/preventing-compiler-optimizations-while-benchmarking // about correct use of benchmark::DoNotOptimize and benchmark::ClobberMemory static void BM_empty(benchmark::State& state) { { for (auto _ : state) ; } } BENCHMARK(BM_empty); static void BM_add(benchmark::State& state) { count_t a = 0; for (auto _ : state) { a += 1; } benchmark::DoNotOptimize(a); } BENCHMARK(BM_add); count_t non_inline_func(count_t x) { return x; } static void BM_func_call(benchmark::State& state) { count_t a = 0; count_t i{0}; for (auto _ : state) { a += non_inline_func(i++); } benchmark::DoNotOptimize(a); } BENCHMARK(BM_func_call); inline count_t inline_func(count_t x) { return x; } static void BM_inline_func_call(benchmark::State& state) { count_t a{0}; count_t i{0}; for (auto _ : state) { a += inline_func(i++); } benchmark::DoNotOptimize(a); } BENCHMARK(BM_inline_func_call); static void BM_deref_ptr(benchmark::State& state) { count_t a = 0; count_t* b = &a; count_t c; for (auto _ : state) { c = *b; benchmark::DoNotOptimize(c); } } BENCHMARK(BM_deref_ptr); static void BM_write_64k(benchmark::State& state) { const int memSize = 1024 * 64; unsigned char mem[memSize]; for (auto _ : state) { for (int j = 0; j < memSize; ++j) { mem[j] = j; benchmark::DoNotOptimize(mem[memSize - 1]); benchmark::ClobberMemory(); } } } BENCHMARK(BM_write_64k); static void BM_read_64k(benchmark::State& state) { const int memSize = 1024 * 64; unsigned char mem[memSize]; for (int j = 0; j < memSize; ++j) { mem[j] = j; benchmark::DoNotOptimize(mem[j]); } benchmark::ClobberMemory(); int result = 1; for (auto _ : state) { for (int j = 0; j < memSize; ++j) { result &= mem[j]; benchmark::DoNotOptimize(mem[j]); } } } BENCHMARK(BM_read_64k); static void BM_read_64k_vec(benchmark::State& state) { const int memSize = 1024 * 64; vector<unsigned char> mem(memSize); for (int j = 0; j < memSize; ++j) { mem[j] = j; benchmark::DoNotOptimize(mem[j]); } benchmark::ClobberMemory(); int result = 1; for (auto _ : state) { for (int j = 0; j < memSize; ++j) { result &= mem[j]; benchmark::DoNotOptimize(mem[j]); } } } BENCHMARK(BM_read_64k_vec); static void BM_read_64k_vec_at(benchmark::State& state) { const int memSize = 1024 * 64; vector<unsigned char> mem(memSize); for (int j = 0; j < memSize; ++j) { mem[j] = j; benchmark::DoNotOptimize(mem[j]); } benchmark::ClobberMemory(); int result = 1; for (auto _ : state) { for (int j = 0; j < memSize; ++j) { result &= mem.at(j); benchmark::DoNotOptimize(mem.at(j)); } } } BENCHMARK(BM_read_64k_vec_at); static void BM_read_64k_array_at(benchmark::State& state) { const int memSize = 1024 * 64; array<unsigned char, memSize> mem; for (int j = 0; j < memSize; ++j) { mem[j] = j; benchmark::DoNotOptimize(mem[j]); } benchmark::ClobberMemory(); int result = 1; for (auto _ : state) { for (int j = 0; j < memSize; ++j) { result &= mem.at(j); } } } BENCHMARK(BM_read_64k_array_at); static void BM_try_catch(benchmark::State& state) { int result = 0; for (auto _ : state) { try { throw exception(); } catch (exception& e) { ++result; } } benchmark::DoNotOptimize(result); } BENCHMARK(BM_try_catch); int a_func(int a) { return 2 * a; } static void BM_func_ptr(benchmark::State& state) { int result = 0; auto f_ptr = a_func; for (auto _ : state) { result += f_ptr(1); } benchmark::DoNotOptimize(result); } BENCHMARK(BM_func_ptr); class C { public: int a_method(int a) { return 2 * a; } virtual int a_virtual_method(int a) { return 2 * a; } }; class C2 : public C { public: virtual int a_virtual_method(int a) { return 3 * a; } }; static void BM_nonvirt_method(benchmark::State& state) { int result = 0; C c; for (auto _ : state) { result += c.a_method(1); } benchmark::DoNotOptimize(result); } BENCHMARK(BM_nonvirt_method); static void BM_virt_method(benchmark::State& state) { int result = 0; C2 c2; for (auto _ : state) { result += c2.a_virtual_method(1); } benchmark::DoNotOptimize(result); } BENCHMARK(BM_virt_method); vector<string> many_strings() { return vector<string>(10000, "abcdefghijklmnopqrstuvwxyz"); } vector<string> many_strings_static() { static vector<string> result(10000, "abcdefghijklmnopqrstuvwxyz"); return result; } static void BM_string_concat_plus(benchmark::State& state) { for (auto _ : state) { string result; for (const string& s : many_strings()) { result += s; } benchmark::DoNotOptimize(result); } } BENCHMARK(BM_string_concat_plus); static void BM_string_concat_ostringstream(benchmark::State& state) { for (auto _ : state) { ostringstream result; for (const string& s : many_strings()) { result << s; } benchmark::DoNotOptimize(result); } } BENCHMARK(BM_string_concat_ostringstream); static void BM_lambda(benchmark::State& state) { long result{0}; long a{0}; long i{0}; auto lambda = [](long x, long y) -> long { return x + y; }; for (auto _ : state) { result += lambda(a, i); ++a; ++i; } benchmark::DoNotOptimize(result); } BENCHMARK(BM_lambda); static void BM_xor(benchmark::State& state) { unsigned char c = 1; int i{0}; for (auto _ : state) { c ^= i++; } benchmark::DoNotOptimize(c); } BENCHMARK(BM_xor); void BM_xor_bitset(benchmark::State& state) { bitset<8> c = 1; int i{0}; for (auto _ : state) { c ^= i++; } benchmark::DoNotOptimize(c.to_ulong()); } BENCHMARK(BM_xor_bitset); static void BM_string_formatting_fmt_positional(benchmark::State& state) { count_t i{0}; std::string s; for (auto _ : state) { s = fmt::format( "{} {} {} {} {} {} {} {} {} {}", i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9); benchmark::DoNotOptimize(s); } } BENCHMARK(BM_string_formatting_fmt_positional); static void BM_string_formatting_fmt_named_args(benchmark::State& state) { using namespace fmt::literals; int i{0}; std::string s; for (auto _ : state) { s = fmt::format( "{zero} {one} {two} {three} {four} {five} {six} {seven} {eight} {nine}", "zero"_a = i, "one"_a = i + 1, "two"_a = i + 2, "three"_a = i + 3, "four"_a = i + 4, "five"_a = i + 5, "six"_a = i + 6, "seven"_a = i + 7, "eight"_a = i + 8, "nine"_a = i + 9); benchmark::DoNotOptimize(s); } } BENCHMARK(BM_string_formatting_fmt_named_args); static void BM_string_formatting_ostringstream(benchmark::State& state) { using namespace fmt::literals; int i{0}; std::string s; for (auto _ : state) { std::ostringstream strm; strm << (i + 1) << " " << (i + 2) << " " << (i + 3) << " " << (i + 4) << " " << (i + 5) << " " << (i + 6) << " " << (i + 7) << " " << (i + 8) << " " << (i + 9); s = strm.str(); benchmark::DoNotOptimize(s); } } BENCHMARK(BM_string_formatting_ostringstream); static void BM_string_formatting_sprintf(benchmark::State& state) { using namespace fmt::literals; int i{0}; char s[1024]; for (auto _ : state) { int status = sprintf( s, "%d %d %d %d %d %d %d %d %d %d ", (i + 0), (i + 1), (i + 2), (i + 3), (i + 4), (i + 5), (i + 6), (i + 7), (i + 8), (i + 9)); benchmark::DoNotOptimize(status); benchmark::DoNotOptimize(s); } } BENCHMARK(BM_string_formatting_sprintf); BENCHMARK_MAIN();<commit_msg>Added benchmarks for inserting into and retrieving from (unordered) maps<commit_after>#include <benchmark/benchmark.h> #include <fmt/format.h> #include <array> #include <bitset> #include <iostream> #include <map> #include <sstream> #include <string> #include <unordered_map> #include <vector> using namespace std; using count_t = long long; // See discussion at // https://stackoverflow.com/questions/40122141/preventing-compiler-optimizations-while-benchmarking // about correct use of benchmark::DoNotOptimize and benchmark::ClobberMemory static void BM_empty(benchmark::State& state) { { for (auto _ : state) ; } } BENCHMARK(BM_empty); static void BM_add(benchmark::State& state) { count_t a = 0; for (auto _ : state) { a += 1; } benchmark::DoNotOptimize(a); } BENCHMARK(BM_add); count_t non_inline_func(count_t x) { return x; } static void BM_func_call(benchmark::State& state) { count_t a = 0; count_t i{0}; for (auto _ : state) { a += non_inline_func(i++); } benchmark::DoNotOptimize(a); } BENCHMARK(BM_func_call); inline count_t inline_func(count_t x) { return x; } static void BM_inline_func_call(benchmark::State& state) { count_t a{0}; count_t i{0}; for (auto _ : state) { a += inline_func(i++); } benchmark::DoNotOptimize(a); } BENCHMARK(BM_inline_func_call); static void BM_deref_ptr(benchmark::State& state) { count_t a = 0; count_t* b = &a; count_t c; for (auto _ : state) { c = *b; benchmark::DoNotOptimize(c); } } BENCHMARK(BM_deref_ptr); static void BM_write_64k(benchmark::State& state) { const int memSize = 1024 * 64; unsigned char mem[memSize]; for (auto _ : state) { for (int j = 0; j < memSize; ++j) { mem[j] = j; benchmark::DoNotOptimize(mem[memSize - 1]); benchmark::ClobberMemory(); } } } BENCHMARK(BM_write_64k); static void BM_read_64k(benchmark::State& state) { const int memSize = 1024 * 64; unsigned char mem[memSize]; for (int j = 0; j < memSize; ++j) { mem[j] = j; benchmark::DoNotOptimize(mem[j]); } benchmark::ClobberMemory(); int result = 1; for (auto _ : state) { for (int j = 0; j < memSize; ++j) { result &= mem[j]; benchmark::DoNotOptimize(mem[j]); } } } BENCHMARK(BM_read_64k); static void BM_read_64k_vec(benchmark::State& state) { const int memSize = 1024 * 64; vector<unsigned char> mem(memSize); for (int j = 0; j < memSize; ++j) { mem[j] = j; benchmark::DoNotOptimize(mem[j]); } benchmark::ClobberMemory(); int result = 1; for (auto _ : state) { for (int j = 0; j < memSize; ++j) { result &= mem[j]; benchmark::DoNotOptimize(mem[j]); } } } BENCHMARK(BM_read_64k_vec); static void BM_read_64k_vec_at(benchmark::State& state) { const int memSize = 1024 * 64; vector<unsigned char> mem(memSize); for (int j = 0; j < memSize; ++j) { mem[j] = j; benchmark::DoNotOptimize(mem[j]); } benchmark::ClobberMemory(); int result = 1; for (auto _ : state) { for (int j = 0; j < memSize; ++j) { result &= mem.at(j); benchmark::DoNotOptimize(mem.at(j)); } } } BENCHMARK(BM_read_64k_vec_at); static void BM_read_64k_array_at(benchmark::State& state) { const int memSize = 1024 * 64; array<unsigned char, memSize> mem; for (int j = 0; j < memSize; ++j) { mem[j] = j; benchmark::DoNotOptimize(mem[j]); } benchmark::ClobberMemory(); int result = 1; for (auto _ : state) { for (int j = 0; j < memSize; ++j) { result &= mem.at(j); } } } BENCHMARK(BM_read_64k_array_at); static void BM_try_catch(benchmark::State& state) { int result = 0; for (auto _ : state) { try { throw exception(); } catch (exception& e) { ++result; } } benchmark::DoNotOptimize(result); } BENCHMARK(BM_try_catch); int a_func(int a) { return 2 * a; } static void BM_func_ptr(benchmark::State& state) { int result = 0; auto f_ptr = a_func; for (auto _ : state) { result += f_ptr(1); } benchmark::DoNotOptimize(result); } BENCHMARK(BM_func_ptr); class C { public: int a_method(int a) { return 2 * a; } virtual int a_virtual_method(int a) { return 2 * a; } }; class C2 : public C { public: virtual int a_virtual_method(int a) { return 3 * a; } }; static void BM_nonvirt_method(benchmark::State& state) { int result = 0; C c; for (auto _ : state) { result += c.a_method(1); } benchmark::DoNotOptimize(result); } BENCHMARK(BM_nonvirt_method); static void BM_virt_method(benchmark::State& state) { int result = 0; C2 c2; for (auto _ : state) { result += c2.a_virtual_method(1); } benchmark::DoNotOptimize(result); } BENCHMARK(BM_virt_method); vector<string> many_strings() { return vector<string>(10000, "abcdefghijklmnopqrstuvwxyz"); } vector<string> many_strings_static() { static vector<string> result(10000, "abcdefghijklmnopqrstuvwxyz"); return result; } static void BM_string_concat_plus(benchmark::State& state) { for (auto _ : state) { string result; for (const string& s : many_strings()) { result += s; } benchmark::DoNotOptimize(result); } } BENCHMARK(BM_string_concat_plus); static void BM_string_concat_ostringstream(benchmark::State& state) { for (auto _ : state) { ostringstream result; for (const string& s : many_strings()) { result << s; } benchmark::DoNotOptimize(result); } } BENCHMARK(BM_string_concat_ostringstream); static void BM_lambda(benchmark::State& state) { long result{0}; long a{0}; long i{0}; auto lambda = [](long x, long y) -> long { return x + y; }; for (auto _ : state) { result += lambda(a, i); ++a; ++i; } benchmark::DoNotOptimize(result); } BENCHMARK(BM_lambda); static void BM_xor(benchmark::State& state) { unsigned char c = 1; int i{0}; for (auto _ : state) { c ^= i++; } benchmark::DoNotOptimize(c); } BENCHMARK(BM_xor); void BM_xor_bitset(benchmark::State& state) { bitset<8> c = 1; int i{0}; for (auto _ : state) { c ^= i++; } benchmark::DoNotOptimize(c.to_ulong()); } BENCHMARK(BM_xor_bitset); static void BM_string_formatting_fmt_positional(benchmark::State& state) { count_t i{0}; std::string s; for (auto _ : state) { s = fmt::format( "{} {} {} {} {} {} {} {} {} {}", i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9); benchmark::DoNotOptimize(s); } } BENCHMARK(BM_string_formatting_fmt_positional); static void BM_string_formatting_fmt_named_args(benchmark::State& state) { using namespace fmt::literals; int i{0}; std::string s; for (auto _ : state) { s = fmt::format( "{zero} {one} {two} {three} {four} {five} {six} {seven} {eight} {nine}", "zero"_a = i, "one"_a = i + 1, "two"_a = i + 2, "three"_a = i + 3, "four"_a = i + 4, "five"_a = i + 5, "six"_a = i + 6, "seven"_a = i + 7, "eight"_a = i + 8, "nine"_a = i + 9); benchmark::DoNotOptimize(s); } } BENCHMARK(BM_string_formatting_fmt_named_args); static void BM_string_formatting_ostringstream(benchmark::State& state) { using namespace fmt::literals; int i{0}; std::string s; for (auto _ : state) { std::ostringstream strm; strm << (i + 1) << " " << (i + 2) << " " << (i + 3) << " " << (i + 4) << " " << (i + 5) << " " << (i + 6) << " " << (i + 7) << " " << (i + 8) << " " << (i + 9); s = strm.str(); benchmark::DoNotOptimize(s); } } BENCHMARK(BM_string_formatting_ostringstream); static void BM_string_formatting_sprintf(benchmark::State& state) { using namespace fmt::literals; int i{0}; char s[1024]; for (auto _ : state) { int status = sprintf( s, "%d %d %d %d %d %d %d %d %d %d ", (i + 0), (i + 1), (i + 2), (i + 3), (i + 4), (i + 5), (i + 6), (i + 7), (i + 8), (i + 9)); benchmark::DoNotOptimize(status); benchmark::DoNotOptimize(s); } } BENCHMARK(BM_string_formatting_sprintf); std::vector<string> largeStringVec() { std::vector<std::string> result; for (int i{0}; i < 100000; ++i) { result.push_back(fmt::format("value_{}", i)); } return result; } static void BM_map_insertion(benchmark::State& state) { for (auto _ : state) { std::map<std::string, int> m; int value{0}; for (const auto& s : largeStringVec()) { m.insert({s, value++}); } benchmark::DoNotOptimize(m.size()); benchmark::ClobberMemory(); } } BENCHMARK(BM_map_insertion); static void BM_unordered_map_insertion(benchmark::State& state) { for (auto _ : state) { std::unordered_map<std::string, int> m; int value{0}; for (const auto& s : largeStringVec()) { m.insert({s, value++}); } benchmark::DoNotOptimize(m.size()); benchmark::ClobberMemory(); } } BENCHMARK(BM_unordered_map_insertion); static void BM_map_retrieval(benchmark::State& state) { std::map<std::string, int> m; int value{0}; for (const auto& s : largeStringVec()) { m.insert({s, value++}); } for (auto _ : state) { for (const auto& s : largeStringVec()) { benchmark::DoNotOptimize(m[s]); } } } BENCHMARK(BM_map_retrieval); static void BM_unordered_map_retrieval(benchmark::State& state) { std::unordered_map<std::string, int> m; int value{0}; for (const auto& s : largeStringVec()) { m.insert({s, value++}); } for (auto _ : state) { for (const auto& s : largeStringVec()) { benchmark::DoNotOptimize(m[s]); } } } BENCHMARK(BM_unordered_map_retrieval); BENCHMARK_MAIN(); <|endoftext|>
<commit_before> /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: prodmap.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef PRODUCT_MAPPER_HXX #define PRODUCT_MAPPER_HXX #ifndef _SSTRING_HXX #include <bootstrp/sstring.hxx> #endif class GenericInformation; class GenericInformationList; DECLARE_LIST( BaseProductList, ByteString * ) // // class ProductMapper // #define PRODUCT_MAPPER_OK 0x0000 #define PRODUCT_MAPPER_NO_PRODUCT 0x0001 #define PRODUCT_MAPPER_NO_VERSION_INFORMATION 0x0002 class ProductMapper { private: GenericInformationList *pVersionList; GenericInformationList *pProductList; SByteStringList aBaseList; SByteStringList aPrintedList; USHORT PrintDependentTargets( const ByteString &rProduct, USHORT nLevel = 0 ); USHORT PrintAndDeleteBaseList(); SByteStringList *GetMinorList( const ByteString &rVersion, const ByteString &rEnvironment ); BaseProductList *GetBases( GenericInformation *pProductInfo, USHORT nLevel = 0, BaseProductList *pBases = NULL ); USHORT PrintSingleMinorList( GenericInformation *pProductInfo, BaseProductList *pBases, const ByteString rEnvironment ); public: ProductMapper(); ProductMapper( GenericInformationList *pVerList ); ~ProductMapper(); void CreateProductList( GenericInformationList *pVerList ); USHORT GetProductInformation( const ByteString &rProduct, GenericInformation *& pProductInfo ); USHORT PrintDependencies( const ByteString &rProduct ); USHORT PrintProductList(); USHORT PrintMinorList( const ByteString rProduct, const ByteString rEnvironment ); static String GetVersionRoot( GenericInformationList *pList, const ByteString &rVersion ); GenericInformationList *GetProductList() { return pProductList; } }; #endif // PRODUCT_MAPPER_HXX <commit_msg>#i103452#: replace PRODUCT by !DBG_UTIL; replace assert by OSL_ASSERT where possible<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: prodmap.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifdef PRODUCT_MAPPER_HXX #define PRODUCT_MAPPER_HXX #ifndef _SSTRING_HXX #include <bootstrp/sstring.hxx> #endif class GenericInformation; class GenericInformationList; DECLARE_LIST( BaseProductList, ByteString * ) // // class ProductMapper // #define PRODUCT_MAPPER_OK 0x0000 #define PRODUCT_MAPPER_NO_PRODUCT 0x0001 #define PRODUCT_MAPPER_NO_VERSION_INFORMATION 0x0002 class ProductMapper { private: GenericInformationList *pVersionList; GenericInformationList *pProductList; SByteStringList aBaseList; SByteStringList aPrintedList; USHORT PrintDependentTargets( const ByteString &rProduct, USHORT nLevel = 0 ); USHORT PrintAndDeleteBaseList(); SByteStringList *GetMinorList( const ByteString &rVersion, const ByteString &rEnvironment ); BaseProductList *GetBases( GenericInformation *pProductInfo, USHORT nLevel = 0, BaseProductList *pBases = NULL ); USHORT PrintSingleMinorList( GenericInformation *pProductInfo, BaseProductList *pBases, const ByteString rEnvironment ); public: ProductMapper(); ProductMapper( GenericInformationList *pVerList ); ~ProductMapper(); void CreateProductList( GenericInformationList *pVerList ); USHORT GetProductInformation( const ByteString &rProduct, GenericInformation *& pProductInfo ); USHORT PrintDependencies( const ByteString &rProduct ); USHORT PrintProductList(); USHORT PrintMinorList( const ByteString rProduct, const ByteString rEnvironment ); static String GetVersionRoot( GenericInformationList *pList, const ByteString &rVersion ); GenericInformationList *GetProductList() { return pProductList; } }; #endif // PRODUCT_MAPPER_HXX <|endoftext|>
<commit_before>/* Luwra * Minimal-overhead Lua wrapper for C++ * * Copyright (C) 2015, Ole Krüger <ole@vprsm.de> */ #ifndef LUWRA_USERTYPES_H_ #define LUWRA_USERTYPES_H_ #include "common.hpp" #include "types.hpp" #include "stack.hpp" #include "auxiliary.hpp" #include <map> #include <string> LUWRA_NS_BEGIN namespace internal { template <typename T> using StripUserType = typename std::remove_cv<T>::type; /** * User type registry identifiers */ template <typename T> struct UserTypeReg { /** * Dummy field which is used because it has a seperate address for each instance of T */ static const int id; /** * Registry name for a metatable which is associated with a user type */ static const std::string name; }; template <typename T> const int UserTypeReg<T>::id = INT_MAX; #ifndef LUWRA_REGISTRY_PREFIX #define LUWRA_REGISTRY_PREFIX "Luwra#" #endif template <typename T> const std::string UserTypeReg<T>::name = LUWRA_REGISTRY_PREFIX + std::to_string(uintptr_t(&id)); /** * Register a new metatable for a user type T. */ template <typename U> static inline void new_user_type_metatable(State* state) { using T = StripUserType<U>; luaL_newmetatable(state, UserTypeReg<T>::name.c_str()); } /** * Check if the value at the given index if a user type T. */ template <typename U> static inline StripUserType<U>* check_user_type(State* state, int index) { using T = StripUserType<U>; return static_cast<T*>( luaL_checkudata(state, index, UserTypeReg<T>::name.c_str()) ); } /** * Apply U's metatable for the value at the top of the stack. */ template <typename U> static inline void apply_user_type_meta_table(State* state) { setMetatable(state, UserTypeReg<StripUserType<U>>::name.c_str()); } /** * Lua C function to construct a user type T with parameters A */ template <typename U, typename... A> static inline int construct_user_type(State* state) { return static_cast<int>( direct<size_t (A...)>( state, &Value<StripUserType<U>&>::template push<A...>, state ) ); } /** * Lua C function to destruct a user type T */ template <typename U> static inline int destruct_user_type(State* state) { using T = StripUserType<U>; read<T&>(state, 1).~T(); return 0; } /** * Create a string representation for user type T. */ template <typename U> static int stringify_user_type(State* state) { using T = StripUserType<U>; return static_cast<int>( push( state, internal::UserTypeReg<T>::name + "@" + std::to_string(uintptr_t(Value<T*>::read(state, 1))) ) ); } } /** * User type */ template <typename U> struct Value<U&> { using T = internal::StripUserType<U>; /** * Reference a user type value on the stack. * \param state Lua state * \param n Stack index * \returns Reference to the user type value */ static inline U& read(State* state, int n) { // T is unqualified, therefore conversion from T& to U& is allowed return *internal::check_user_type<T>(state, n); } /** * Construct a user type value on the stack. * \note Instances created using this specialization are allocated and constructed as full user * data types in Lua. The default garbage-collecting hook will destruct the user type, * once it has been marked. * \param state Lua state * \param args Constructor arguments * \returns Number of values that have been pushed onto the stack */ template <typename... A> static inline size_t push(State* state, A&&... args) { void* mem = lua_newuserdata(state, sizeof(T)); if (!mem) { luaL_error(state, "Failed to allocate user type"); return -1; } // Construct new (mem) T {std::forward<A>(args)...}; // Apply metatable for unqualified type T internal::apply_user_type_meta_table<T>(state); return 1; } }; /** * Construct a user type value on the stack. * \note Instances created using this specialization are allocated and constructed as full user * data types in Lua. The default garbage-collecting hook will destruct the user type, * once it has been marked. * \param state Lua state * \param args Constructor arguments * \returns Reference to the constructed value */ template <typename U, typename... A> static inline internal::StripUserType<U>& construct(State* state, A&&... args) { using T = internal::StripUserType<U>; void* mem = lua_newuserdata(state, sizeof(T)); if (!mem) { luaL_error(state, "Failed to allocate user type"); // 'luaL_error' will not return } // Construct T* value = new (mem) T {std::forward<A>(args)...}; // Apply metatable for unqualified type T internal::apply_user_type_meta_table<T>(state); return *value; } /** * User type */ template <typename U> struct Value<U*> { using T = internal::StripUserType<U>; /** * Reference a user type value on the stack. * \param state Lua state * \param n Stack index * \returns Pointer to the user type value. */ static inline U* read(State* state, int n) { // T is unqualified, therefore conversion from T* to U* is allowed return internal::check_user_type<T>(state, n); } /** * Copy a value onto the stack. This function behaves exactly as if you would call * `Value<U&>::push(state, *ptr)`. * \param state Lua state * \param ptr Pointer to the user type value * \returns Number of values that have been pushed */ static inline size_t push(State* state, const T* ptr) { return Value<T&>::push(state, *ptr); } }; /** * Register the metatable for user type `T`. This function allows you to register methods * which are shared across all instances of this type. * * By default a garbage-collector hook and string representation function are added as meta methods. * Both can be overwritten. * * \tparam U User type struct or class * * \param state Lua state * \param methods Map of methods * \param meta_methods Map of meta methods */ template <typename U> static inline void registerUserType( State* state, const FieldVector& methods = FieldVector(), const FieldVector& meta_methods = FieldVector() ) { using T = internal::StripUserType<U>; // Setup an appropriate metatable name internal::new_user_type_metatable<T>(state); // Insert methods setFields(state, -1, { {"__index", methods}, {"__gc", &internal::destruct_user_type<T>}, {"__tostring", &internal::stringify_user_type<T>} }); // Insert meta methods setFields(state, -1, meta_methods); // Pop metatable off the stack lua_pop(state, -1); } namespace internal { template <typename T> struct UserTypeSignature { static_assert( sizeof(T) == -1, "Parameter to UserTypeSignature is not a valid signature" ); }; template <typename T, typename... A> struct UserTypeSignature<T (A...)> { using UserType = StripUserType<T>; static inline void registerConstructor(State* state, const std::string& name) { setGlobal(state, name, &construct_user_type<UserType, A...>); } }; } /** * Same as the other `registerUserType` but registers the constructor as well. The template parameter * is a signature `U(A...)` where `U` is the user type and `A...` its constructor parameters. */ template <typename T> static inline void registerUserType( State* state, const std::string& ctor_name, const FieldVector& methods = FieldVector(), const FieldVector& meta_methods = FieldVector() ) { using U = typename internal::UserTypeSignature<T>::UserType; registerUserType<U>(state, methods, meta_methods); internal::UserTypeSignature<T>::registerConstructor(state, ctor_name); } LUWRA_NS_END /** * Generate a `lua_CFunction` wrapper for a constructor. * \param type Type to instantiate * \param ... Constructor parameter types * \return Wrapped function as `lua_CFunction` */ #define LUWRA_WRAP_CONSTRUCTOR(type, ...) \ (&luwra::internal::construct_user_type<luwra::internal::StripUserType<type>, __VA_ARGS__>) /** * Define the registry name for a user type. * \param type User type * \param regname Registry name */ #define LUWRA_DEF_REGISTRY_NAME(type, regname) \ LUWRA_NS_BEGIN \ namespace internal { \ template <> struct UserTypeReg<type> { static const std::string name; }; \ const std::string UserTypeReg<type>::name = (regname); \ } \ LUWRA_NS_END #define LUWRA_FIELD(type, name) \ {#name, LUWRA_WRAP_FIELD(__LUWRA_NS_RESOLVE(type, name))} #define LUWRA_METHOD(type, name) \ {#name, LUWRA_WRAP_METHOD(__LUWRA_NS_RESOLVE(type, name))} #define LUWRA_FUNCTION(type, name) \ {#name, LUWRA_WRAP_FUNCTION(__LUWRA_NS_RESOLVE(type, name))} #endif <commit_msg>Use 'construct' in 'Value<T&>::push' to avoid duplicate code<commit_after>/* Luwra * Minimal-overhead Lua wrapper for C++ * * Copyright (C) 2015, Ole Krüger <ole@vprsm.de> */ #ifndef LUWRA_USERTYPES_H_ #define LUWRA_USERTYPES_H_ #include "common.hpp" #include "types.hpp" #include "stack.hpp" #include "auxiliary.hpp" #include <map> #include <string> LUWRA_NS_BEGIN namespace internal { template <typename T> using StripUserType = typename std::remove_cv<T>::type; /** * User type registry identifiers */ template <typename T> struct UserTypeReg { /** * Dummy field which is used because it has a seperate address for each instance of T */ static const int id; /** * Registry name for a metatable which is associated with a user type */ static const std::string name; }; template <typename T> const int UserTypeReg<T>::id = INT_MAX; #ifndef LUWRA_REGISTRY_PREFIX #define LUWRA_REGISTRY_PREFIX "Luwra#" #endif template <typename T> const std::string UserTypeReg<T>::name = LUWRA_REGISTRY_PREFIX + std::to_string(uintptr_t(&id)); /** * Register a new metatable for a user type T. */ template <typename U> static inline void new_user_type_metatable(State* state) { using T = StripUserType<U>; luaL_newmetatable(state, UserTypeReg<T>::name.c_str()); } /** * Check if the value at the given index if a user type T. */ template <typename U> static inline StripUserType<U>* check_user_type(State* state, int index) { using T = StripUserType<U>; return static_cast<T*>( luaL_checkudata(state, index, UserTypeReg<T>::name.c_str()) ); } /** * Apply U's metatable for the value at the top of the stack. */ template <typename U> static inline void apply_user_type_meta_table(State* state) { setMetatable(state, UserTypeReg<StripUserType<U>>::name.c_str()); } /** * Lua C function to construct a user type T with parameters A */ template <typename U, typename... A> static inline int construct_user_type(State* state) { return static_cast<int>( direct<size_t (A...)>( state, &Value<StripUserType<U>&>::template push<A...>, state ) ); } /** * Lua C function to destruct a user type T */ template <typename U> static inline int destruct_user_type(State* state) { using T = StripUserType<U>; read<T&>(state, 1).~T(); return 0; } /** * Create a string representation for user type T. */ template <typename U> static int stringify_user_type(State* state) { using T = StripUserType<U>; return static_cast<int>( push( state, internal::UserTypeReg<T>::name + "@" + std::to_string(uintptr_t(Value<T*>::read(state, 1))) ) ); } } /** * Construct a user type value on the stack. * \note Instances created using this specialization are allocated and constructed as full user * data types in Lua. The default garbage-collecting hook will destruct the user type, * once it has been marked. * \param state Lua state * \param args Constructor arguments * \returns Reference to the constructed value */ template <typename U, typename... A> static inline internal::StripUserType<U>& construct(State* state, A&&... args) { using T = internal::StripUserType<U>; void* mem = lua_newuserdata(state, sizeof(T)); if (!mem) { luaL_error(state, "Failed to allocate user type"); // 'luaL_error' will not return } // Construct T* value = new (mem) T {std::forward<A>(args)...}; // Apply metatable for unqualified type T internal::apply_user_type_meta_table<T>(state); return *value; } /** * User type */ template <typename U> struct Value<U&> { using T = internal::StripUserType<U>; /** * Reference a user type value on the stack. * \param state Lua state * \param n Stack index * \returns Reference to the user type value */ static inline U& read(State* state, int n) { // T is unqualified, therefore conversion from T& to U& is allowed return *internal::check_user_type<T>(state, n); } /** * Construct a user type value on the stack. * \note Instances created using this specialization are allocated and constructed as full user * data types in Lua. The default garbage-collecting hook will destruct the user type, * once it has been marked. * \param state Lua state * \param args Constructor arguments * \returns Number of values that have been pushed onto the stack */ template <typename... A> static inline size_t push(State* state, A&&... args) { construct<T>(state, std::forward<A>(args)...); return 1; } }; /** * User type */ template <typename U> struct Value<U*> { using T = internal::StripUserType<U>; /** * Reference a user type value on the stack. * \param state Lua state * \param n Stack index * \returns Pointer to the user type value. */ static inline U* read(State* state, int n) { // T is unqualified, therefore conversion from T* to U* is allowed return internal::check_user_type<T>(state, n); } /** * Copy a value onto the stack. This function behaves exactly as if you would call * `Value<U&>::push(state, *ptr)`. * \param state Lua state * \param ptr Pointer to the user type value * \returns Number of values that have been pushed */ static inline size_t push(State* state, const T* ptr) { return Value<T&>::push(state, *ptr); } }; /** * Register the metatable for user type `T`. This function allows you to register methods * which are shared across all instances of this type. * * By default a garbage-collector hook and string representation function are added as meta methods. * Both can be overwritten. * * \tparam U User type struct or class * * \param state Lua state * \param methods Map of methods * \param meta_methods Map of meta methods */ template <typename U> static inline void registerUserType( State* state, const FieldVector& methods = FieldVector(), const FieldVector& meta_methods = FieldVector() ) { using T = internal::StripUserType<U>; // Setup an appropriate metatable name internal::new_user_type_metatable<T>(state); // Insert methods setFields(state, -1, { {"__index", methods}, {"__gc", &internal::destruct_user_type<T>}, {"__tostring", &internal::stringify_user_type<T>} }); // Insert meta methods setFields(state, -1, meta_methods); // Pop metatable off the stack lua_pop(state, -1); } namespace internal { template <typename T> struct UserTypeSignature { static_assert( sizeof(T) == -1, "Parameter to UserTypeSignature is not a valid signature" ); }; template <typename T, typename... A> struct UserTypeSignature<T (A...)> { using UserType = StripUserType<T>; static inline void registerConstructor(State* state, const std::string& name) { setGlobal(state, name, &construct_user_type<UserType, A...>); } }; } /** * Same as the other `registerUserType` but registers the constructor as well. The template parameter * is a signature `U(A...)` where `U` is the user type and `A...` its constructor parameters. */ template <typename T> static inline void registerUserType( State* state, const std::string& ctor_name, const FieldVector& methods = FieldVector(), const FieldVector& meta_methods = FieldVector() ) { using U = typename internal::UserTypeSignature<T>::UserType; registerUserType<U>(state, methods, meta_methods); internal::UserTypeSignature<T>::registerConstructor(state, ctor_name); } LUWRA_NS_END /** * Generate a `lua_CFunction` wrapper for a constructor. * \param type Type to instantiate * \param ... Constructor parameter types * \return Wrapped function as `lua_CFunction` */ #define LUWRA_WRAP_CONSTRUCTOR(type, ...) \ (&luwra::internal::construct_user_type<luwra::internal::StripUserType<type>, __VA_ARGS__>) /** * Define the registry name for a user type. * \param type User type * \param regname Registry name */ #define LUWRA_DEF_REGISTRY_NAME(type, regname) \ LUWRA_NS_BEGIN \ namespace internal { \ template <> struct UserTypeReg<type> { static const std::string name; }; \ const std::string UserTypeReg<type>::name = (regname); \ } \ LUWRA_NS_END #define LUWRA_FIELD(type, name) \ {#name, LUWRA_WRAP_FIELD(__LUWRA_NS_RESOLVE(type, name))} #define LUWRA_METHOD(type, name) \ {#name, LUWRA_WRAP_METHOD(__LUWRA_NS_RESOLVE(type, name))} #define LUWRA_FUNCTION(type, name) \ {#name, LUWRA_WRAP_FUNCTION(__LUWRA_NS_RESOLVE(type, name))} #endif <|endoftext|>
<commit_before>#include <Eigen/Dense> #include <Eigen/Sparse> #include <iostream> #include <cassert> #include <fstream> #include <string> #include <algorithm> #include <random> #include <chrono> #include <memory> #include <cmath> #include <unsupported/Eigen/SparseExtra> #include <Eigen/Sparse> #if defined(_OPENMP) #include <omp.h> #endif #include <signal.h> #include "utils.h" #include "model.h" #include "mvnormal.h" using namespace std; using namespace Eigen; void Factors::setRelationDataTest(int* rows, int* cols, double* values, int N, int nrows, int ncols) { assert(nrows == Yrows() && ncols == Ycols() && "Size of train must be equal to size of test"); Ytest.resize(nrows, ncols); sparseFromIJV(Ytest, rows, cols, values, N); } void Factors::setRelationDataTest(SparseDoubleMatrix &Y) { setRelationDataTest(Y.rows, Y.cols, Y.vals, Y.nnz, Y.nrow, Y.ncol); } void Factors::setRelationDataTest(SparseMatrixD Y) { Ytest = Y; } //--- output model to files void Factors::savePredictions(std::string save_prefix, int iter, int burnin) { VectorXd yhat_sd_raw = getStds(iter, burnin); MatrixXd testdata_raw = to_coo(Ytest); std::string fname_pred = save_prefix + "-predictions.csv"; std::ofstream predfile; predfile.open(fname_pred); predfile << "row,col,y,y_pred,y_pred_std\n"; for (int i = 0; i < predictions.size(); i++) { predfile << to_string( (int)testdata_raw(i,0) ); predfile << "," << to_string( (int)testdata_raw(i,1) ); predfile << "," << to_string( testdata_raw(i,2) ); predfile << "," << to_string( predictions(i) ); predfile << "," << to_string( yhat_sd_raw(i) ); predfile << "\n"; } predfile.close(); printf("Saved predictions into '%s'.\n", fname_pred.c_str()); } void Factors::saveGlobalParams(std::string save_prefix) { VectorXd means(1); means << mean_rating; writeToCSVfile(save_prefix + "-meanvalue.csv", means); } void Factors::saveModel(std::string save_prefix, int iter, int burnin) { int i = 0; for(auto &U : factors) { writeToCSVfile(save_prefix + "U" + std::to_string(++i) + "-latents.csv", U); } savePredictions(save_prefix, iter, burnin); } ///--- update RMSE and AUC void Factors::update_predictions(int iter, int burnin) { if (Ytest.nonZeros() == 0) return; assert(last_iter <= iter); if (last_iter < 0) { const int N = Ytest.nonZeros(); predictions = VectorXd::Zero(N); predictions_var = VectorXd::Zero(N); stds = VectorXd::Zero(N); } if (last_iter == iter) return; assert(last_iter + 1 == iter); double se = 0.0, se_avg = 0.0; const double inorm = 1.0 / (iter - burnin - 1); #pragma omp parallel for schedule(dynamic,8) reduction(+:se, se_avg) for (int k = 0; k < Ytest.outerSize(); ++k) { int idx = Ytest.outerIndexPtr()[k]; for (Eigen::SparseMatrix<double>::InnerIterator it(Ytest,k); it; ++it) { const double pred = col(0,it.col()).dot(col(1,it.row())) + mean_rating; se += square(it.value() - pred); // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm double pred_avg; if (iter <= burnin) { pred_avg = pred; } else { double delta = pred - predictions[idx]; pred_avg = (predictions[idx] + delta / (iter - burnin + 1)); predictions_var[idx] += delta * (pred - pred_avg); } se_avg += square(it.value() - pred_avg); predictions[idx] = pred_avg; stds[idx] = sqrt(predictions_var[idx] * inorm); idx++; } } const unsigned N = Ytest.nonZeros(); rmse = sqrt( se / N ); rmse_avg = sqrt( se_avg / N ); last_iter = iter; } std::pair<double,double> Factors::getRMSE(int iter, int burnin) { update_predictions(iter, burnin); return std::make_pair(rmse, rmse_avg); } const Eigen::VectorXd &Factors::getPredictions(int iter, int burnin) { update_predictions(iter, burnin); return predictions; } const Eigen::VectorXd &Factors::getPredictionsVar(int iter, int burnin) { update_predictions(iter, burnin); return predictions_var; } const Eigen::VectorXd &Factors::getStds(int iter, int burnin) { update_predictions(iter, burnin); return stds; } double Factors::auc() { if (Ytest.nonZeros() == 0) return NAN; double *test_vector = Ytest.valuePtr(); Eigen::VectorXd stack_x(predictions.size()); Eigen::VectorXd stack_y(predictions.size()); double auc = 0.0; std::vector<unsigned int> permutation( predictions.size() ); for(unsigned int i = 0; i < predictions.size(); i++) { permutation[i] = i; } std::sort(permutation.begin(), permutation.end(), [this](unsigned int a, unsigned int b) { return predictions[a] < predictions[b];}); int NP = Ytest.sum(); int NN = Ytest.nonZeros() - NP; //Build stack_x and stack_y stack_x[0] = test_vector[permutation[0]]; stack_y[0] = 1-stack_x[0]; for(int i=1; i < predictions.size(); i++) { stack_x[i] = stack_x[i-1] + test_vector[permutation[i]]; stack_y[i] = stack_y[i-1] + 1 - test_vector[permutation[i]]; } for(int i=0; i < predictions.size() - 1; i++) { auc += (stack_x(i+1) - stack_x(i)) * stack_y(i+1) / (NP*NN); //TODO:Make it Eigen } return auc; } std::ostream &Factors::printInitStatus(std::ostream &os, std::string indent) { os << indent << "Type: " << name << "\n"; os << indent << "Num-latents: " << num_latent << "\n"; os << indent << "Train data: [" << Yrows() << " x " << Ycols() << "]\n"; os << indent << "Test data: [" << Ytest.rows() << " x " << Ytest.cols() << "]\n"; return os; } template<typename YType> void MF<YType>::init_base() { assert(Yrows() > 0 && Ycols() > 0); mean_rating = Y.sum() / Y.nonZeros(); U(0) = nrandn(num_latent, Y.cols()); U(1) = nrandn(num_latent, Y.rows()); Yc.push_back(Y); Yc.push_back(Y.transpose()); } template<> void MF<SparseMatrixD>::init() { init_base(); Yc.at(0).coeffs() -= mean_rating; Yc.at(1).coeffs() -= mean_rating; } template<> void MF<Eigen::MatrixXd>::init() { init_base(); Yc.at(0).array() -= this->mean_rating; Yc.at(1).array() -= this->mean_rating; } template<typename YType> void MF<YType>::setRelationData(YType Y) { this->Y = Y; } template struct MF<SparseMatrix<double>>; template struct MF<MatrixXd>; template<> double MF<Eigen::MatrixXd>::var_total() const { auto &Y = Yc.at(0); double se = Y.array().square().sum(); double var_total = se / Y.nonZeros(); if (var_total <= 0.0 || std::isnan(var_total)) { // if var cannot be computed using 1.0 var_total = 1.0; } return var_total; } template<> double MF<SparseMatrixD>::var_total() const { double se = 0.0; auto &Y = Yc.at(0); #pragma omp parallel for schedule(dynamic, 4) reduction(+:se) for (int k = 0; k < Y.outerSize(); ++k) { for (SparseMatrix<double>::InnerIterator it(Y,k); it; ++it) { se += square(it.value()); } } double var_total = se / Y.nonZeros(); if (var_total <= 0.0 || std::isnan(var_total)) { // if var cannot be computed using 1.0 var_total = 1.0; } return var_total; } // for the adaptive gaussian noise template<> double MF<Eigen::MatrixXd>::sumsq() const { double sumsq = 0.0; #pragma omp parallel for schedule(dynamic, 4) reduction(+:sumsq) for (int j = 0; j < this->Y.cols(); j++) { auto Vj = this->U(1).col(j); for (int i = 0; i < this->Y.rows(); i++) { double Yhat = Vj.dot( this->U(0).col(j) ) + this->mean_rating; sumsq += square(Yhat - this->Y(i,j)); } } return sumsq; } template<> double MF<SparseMatrixD>::sumsq() const { double sumsq = 0.0; #pragma omp parallel for schedule(dynamic, 4) reduction(+:sumsq) for (int j = 0; j < Y.outerSize(); j++) { auto Vj = col(1, j); for (SparseMatrix<double>::InnerIterator it(Y, j); it; ++it) { double Yhat = Vj.dot( col(0, it.row()) ) + mean_rating; sumsq += square(Yhat - it.value()); } } return sumsq; } template<> void MF<SparseMatrixD>::setRelationData(int* rows, int* cols, double* values, int N, int nrows, int ncols) { Y.resize(nrows, ncols); sparseFromIJV(Y, rows, cols, values, N); } template<> void MF<SparseMatrixD>::setRelationData(SparseDoubleMatrix &Y) { setRelationData(Y.rows, Y.cols, Y.vals, Y.nnz, Y.nrow, Y.ncol); } // //-- SparseMF specific stuff // Factors::PnM SparseMF::get_pnm(int f, int n) { MatrixXd MM = MatrixXd::Zero(num_latent, num_latent); VectorXd rr = VectorXd::Zero(num_latent); for (SparseMatrix<double>::InnerIterator it(Yc.at(f), n); it; ++it) { auto col = V(f).col(it.row()); rr.noalias() += col * it.value(); MM.triangularView<Eigen::Lower>() += col * col.transpose(); } return std::make_pair(rr, MM); } Factors::PnM SparseMF::get_probit_pnm(int f, int n) { MatrixXd MM = MatrixXd::Zero(num_latent, num_latent); VectorXd rr = VectorXd::Zero(num_latent); auto u = U(f).col(n); for (SparseMatrix<double>::InnerIterator it(Yc.at(f), n); it; ++it) { auto col = V(f).col(it.row()); MM.triangularView<Eigen::Lower>() += col * col.transpose(); auto z = (2 * it.value() - 1) * fabs(col.dot(u) + bmrandn_single()); rr.noalias() += col * z; } return std::make_pair(rr, MM); } // //-- DenseMF specific stuff // template<class YType> Factors::PnM DenseMF<YType>::get_pnm(int f, int d) { auto &Y = this->Yc.at(f); VectorXd rr = (this->V(f) * Y.col(d)); return std::make_pair(rr, VV.at(f)); } template<class YType> void DenseMF<YType>::update_pnm(int f) { auto &Vf = this->V(f); auto &VVf = VV.at(f); VVf = MatrixXd::Zero(this->num_latent, this->num_latent); SHOW(VVf); #pragma omp parallel for schedule(dynamic, 2) reduction(MatrixPlus:XX) for(int n = 0; n < Vf.cols(); n++) { auto v = Vf.col(n); VVf += v * v.transpose(); SHOW(VVf); } } <commit_msg>DenseDense and SparseDense<commit_after>#include <Eigen/Dense> #include <Eigen/Sparse> #include <iostream> #include <cassert> #include <fstream> #include <string> #include <algorithm> #include <random> #include <chrono> #include <memory> #include <cmath> #include <unsupported/Eigen/SparseExtra> #include <Eigen/Sparse> #if defined(_OPENMP) #include <omp.h> #endif #include <signal.h> #include "utils.h" #include "model.h" #include "mvnormal.h" using namespace std; using namespace Eigen; void Factors::setRelationDataTest(int* rows, int* cols, double* values, int N, int nrows, int ncols) { assert(nrows == Yrows() && ncols == Ycols() && "Size of train must be equal to size of test"); Ytest.resize(nrows, ncols); sparseFromIJV(Ytest, rows, cols, values, N); } void Factors::setRelationDataTest(SparseDoubleMatrix &Y) { setRelationDataTest(Y.rows, Y.cols, Y.vals, Y.nnz, Y.nrow, Y.ncol); } void Factors::setRelationDataTest(SparseMatrixD Y) { Ytest = Y; } //--- output model to files void Factors::savePredictions(std::string save_prefix, int iter, int burnin) { VectorXd yhat_sd_raw = getStds(iter, burnin); MatrixXd testdata_raw = to_coo(Ytest); std::string fname_pred = save_prefix + "-predictions.csv"; std::ofstream predfile; predfile.open(fname_pred); predfile << "row,col,y,y_pred,y_pred_std\n"; for (int i = 0; i < predictions.size(); i++) { predfile << to_string( (int)testdata_raw(i,0) ); predfile << "," << to_string( (int)testdata_raw(i,1) ); predfile << "," << to_string( testdata_raw(i,2) ); predfile << "," << to_string( predictions(i) ); predfile << "," << to_string( yhat_sd_raw(i) ); predfile << "\n"; } predfile.close(); printf("Saved predictions into '%s'.\n", fname_pred.c_str()); } void Factors::saveGlobalParams(std::string save_prefix) { VectorXd means(1); means << mean_rating; writeToCSVfile(save_prefix + "-meanvalue.csv", means); } void Factors::saveModel(std::string save_prefix, int iter, int burnin) { int i = 0; for(auto &U : factors) { writeToCSVfile(save_prefix + "U" + std::to_string(++i) + "-latents.csv", U); } savePredictions(save_prefix, iter, burnin); } ///--- update RMSE and AUC void Factors::update_predictions(int iter, int burnin) { if (Ytest.nonZeros() == 0) return; assert(last_iter <= iter); if (last_iter < 0) { const int N = Ytest.nonZeros(); predictions = VectorXd::Zero(N); predictions_var = VectorXd::Zero(N); stds = VectorXd::Zero(N); } if (last_iter == iter) return; assert(last_iter + 1 == iter); double se = 0.0, se_avg = 0.0; const double inorm = 1.0 / (iter - burnin - 1); #pragma omp parallel for schedule(dynamic,8) reduction(+:se, se_avg) for (int k = 0; k < Ytest.outerSize(); ++k) { int idx = Ytest.outerIndexPtr()[k]; for (Eigen::SparseMatrix<double>::InnerIterator it(Ytest,k); it; ++it) { const double pred = col(0,it.col()).dot(col(1,it.row())) + mean_rating; se += square(it.value() - pred); // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm double pred_avg; if (iter <= burnin) { pred_avg = pred; } else { double delta = pred - predictions[idx]; pred_avg = (predictions[idx] + delta / (iter - burnin + 1)); predictions_var[idx] += delta * (pred - pred_avg); } se_avg += square(it.value() - pred_avg); predictions[idx] = pred_avg; stds[idx] = sqrt(predictions_var[idx] * inorm); idx++; } } const unsigned N = Ytest.nonZeros(); rmse = sqrt( se / N ); rmse_avg = sqrt( se_avg / N ); last_iter = iter; } std::pair<double,double> Factors::getRMSE(int iter, int burnin) { update_predictions(iter, burnin); return std::make_pair(rmse, rmse_avg); } const Eigen::VectorXd &Factors::getPredictions(int iter, int burnin) { update_predictions(iter, burnin); return predictions; } const Eigen::VectorXd &Factors::getPredictionsVar(int iter, int burnin) { update_predictions(iter, burnin); return predictions_var; } const Eigen::VectorXd &Factors::getStds(int iter, int burnin) { update_predictions(iter, burnin); return stds; } double Factors::auc() { if (Ytest.nonZeros() == 0) return NAN; double *test_vector = Ytest.valuePtr(); Eigen::VectorXd stack_x(predictions.size()); Eigen::VectorXd stack_y(predictions.size()); double auc = 0.0; std::vector<unsigned int> permutation( predictions.size() ); for(unsigned int i = 0; i < predictions.size(); i++) { permutation[i] = i; } std::sort(permutation.begin(), permutation.end(), [this](unsigned int a, unsigned int b) { return predictions[a] < predictions[b];}); int NP = Ytest.sum(); int NN = Ytest.nonZeros() - NP; //Build stack_x and stack_y stack_x[0] = test_vector[permutation[0]]; stack_y[0] = 1-stack_x[0]; for(int i=1; i < predictions.size(); i++) { stack_x[i] = stack_x[i-1] + test_vector[permutation[i]]; stack_y[i] = stack_y[i-1] + 1 - test_vector[permutation[i]]; } for(int i=0; i < predictions.size() - 1; i++) { auc += (stack_x(i+1) - stack_x(i)) * stack_y(i+1) / (NP*NN); //TODO:Make it Eigen } return auc; } std::ostream &Factors::printInitStatus(std::ostream &os, std::string indent) { os << indent << "Type: " << name << "\n"; os << indent << "Num-latents: " << num_latent << "\n"; os << indent << "Train data: [" << Yrows() << " x " << Ycols() << "]\n"; os << indent << "Test data: [" << Ytest.rows() << " x " << Ytest.cols() << "]\n"; return os; } template<typename YType> void MF<YType>::init_base() { assert(Yrows() > 0 && Ycols() > 0); mean_rating = Y.sum() / Y.nonZeros(); U(0) = nrandn(num_latent, Y.cols()); U(1) = nrandn(num_latent, Y.rows()); Yc.push_back(Y); Yc.push_back(Y.transpose()); } template<> void MF<SparseMatrixD>::init() { init_base(); Yc.at(0).coeffs() -= mean_rating; Yc.at(1).coeffs() -= mean_rating; } template<> void MF<Eigen::MatrixXd>::init() { init_base(); Yc.at(0).array() -= this->mean_rating; Yc.at(1).array() -= this->mean_rating; } template<typename YType> void MF<YType>::setRelationData(YType Y) { this->Y = Y; } template struct MF<SparseMatrix<double>>; template struct MF<MatrixXd>; template<> double MF<Eigen::MatrixXd>::var_total() const { auto &Y = Yc.at(0); double se = Y.array().square().sum(); double var_total = se / Y.nonZeros(); if (var_total <= 0.0 || std::isnan(var_total)) { // if var cannot be computed using 1.0 var_total = 1.0; } return var_total; } template<> double MF<SparseMatrixD>::var_total() const { double se = 0.0; auto &Y = Yc.at(0); #pragma omp parallel for schedule(dynamic, 4) reduction(+:se) for (int k = 0; k < Y.outerSize(); ++k) { for (SparseMatrix<double>::InnerIterator it(Y,k); it; ++it) { se += square(it.value()); } } double var_total = se / Y.nonZeros(); if (var_total <= 0.0 || std::isnan(var_total)) { // if var cannot be computed using 1.0 var_total = 1.0; } return var_total; } // for the adaptive gaussian noise template<> double MF<Eigen::MatrixXd>::sumsq() const { double sumsq = 0.0; #pragma omp parallel for schedule(dynamic, 4) reduction(+:sumsq) for (int j = 0; j < this->Y.cols(); j++) { auto Vj = this->U(1).col(j); for (int i = 0; i < this->Y.rows(); i++) { double Yhat = Vj.dot( this->U(0).col(j) ) + this->mean_rating; sumsq += square(Yhat - this->Y(i,j)); } } return sumsq; } template<> double MF<SparseMatrixD>::sumsq() const { double sumsq = 0.0; #pragma omp parallel for schedule(dynamic, 4) reduction(+:sumsq) for (int j = 0; j < Y.outerSize(); j++) { auto Vj = col(1, j); for (SparseMatrix<double>::InnerIterator it(Y, j); it; ++it) { double Yhat = Vj.dot( col(0, it.row()) ) + mean_rating; sumsq += square(Yhat - it.value()); } } return sumsq; } template<> void MF<SparseMatrixD>::setRelationData(int* rows, int* cols, double* values, int N, int nrows, int ncols) { Y.resize(nrows, ncols); sparseFromIJV(Y, rows, cols, values, N); } template<> void MF<SparseMatrixD>::setRelationData(SparseDoubleMatrix &Y) { setRelationData(Y.rows, Y.cols, Y.vals, Y.nnz, Y.nrow, Y.ncol); } // //-- SparseMF specific stuff // Factors::PnM SparseMF::get_pnm(int f, int n) { MatrixXd MM = MatrixXd::Zero(num_latent, num_latent); VectorXd rr = VectorXd::Zero(num_latent); for (SparseMatrix<double>::InnerIterator it(Yc.at(f), n); it; ++it) { auto col = V(f).col(it.row()); rr.noalias() += col * it.value(); MM.triangularView<Eigen::Lower>() += col * col.transpose(); } return std::make_pair(rr, MM); } Factors::PnM SparseMF::get_probit_pnm(int f, int n) { MatrixXd MM = MatrixXd::Zero(num_latent, num_latent); VectorXd rr = VectorXd::Zero(num_latent); auto u = U(f).col(n); for (SparseMatrix<double>::InnerIterator it(Yc.at(f), n); it; ++it) { auto col = V(f).col(it.row()); MM.triangularView<Eigen::Lower>() += col * col.transpose(); auto z = (2 * it.value() - 1) * fabs(col.dot(u) + bmrandn_single()); rr.noalias() += col * z; } return std::make_pair(rr, MM); } // //-- DenseMF specific stuff // template<class YType> Factors::PnM DenseMF<YType>::get_pnm(int f, int d) { auto &Y = this->Yc.at(f); VectorXd rr = (this->V(f) * Y.col(d)); return std::make_pair(rr, VV.at(f)); } template<class YType> void DenseMF<YType>::update_pnm(int f) { auto &Vf = this->V(f); auto &VVf = VV.at(f); VVf = MatrixXd::Zero(this->num_latent, this->num_latent); SHOW(VVf); #pragma omp parallel for schedule(dynamic, 2) reduction(MatrixPlus:XX) for(int n = 0; n < Vf.cols(); n++) { auto v = Vf.col(n); VVf += v * v.transpose(); SHOW(VVf); } } template struct DenseMF<Eigen::MatrixXd>; template struct DenseMF<SparseMatrixD>; <|endoftext|>
<commit_before>// // Copyright 2015 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. // // EGLSanityCheckTest.cpp: // Tests used to check environment in which other tests are run. #include <gtest/gtest.h> #include "gpu_info_util/SystemInfo.h" #include "test_utils/ANGLETest.h" #include "test_utils/angle_test_instantiate.h" using namespace angle; class EGLSanityCheckTest : public EGLTest {}; // Checks the tests are running against ANGLE TEST_F(EGLSanityCheckTest, IsRunningOnANGLE) { const char *extensionString = static_cast<const char *>(eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS)); ASSERT_NE(strstr(extensionString, "EGL_ANGLE_platform_angle"), nullptr); } // Checks that getting function pointer works TEST_F(EGLSanityCheckTest, HasGetPlatformDisplayEXT) { ASSERT_NE(eglGetPlatformDisplayEXT, nullptr); } // Checks that calling GetProcAddress for a non-existant function fails. TEST_F(EGLSanityCheckTest, GetProcAddressNegativeTest) { auto check = eglGetProcAddress("WigglyWombats"); EXPECT_EQ(nullptr, check); } // Tests that our whitelist function generally maps to our support function. // We can add specific exceptions here if needed. TEST_F(EGLSanityCheckTest, WhitelistMatchesSupport) { // Cannot make any useful checks if SystemInfo is not supported. SystemInfo systemInfo; ANGLE_SKIP_TEST_IF(!GetSystemInfo(&systemInfo)); auto check = [&systemInfo](const PlatformParameters &params) { EXPECT_EQ(IsConfigWhitelisted(systemInfo, params), IsConfigSupported(params)) << params; }; check(ES1_OPENGL()); check(ES2_OPENGL()); check(ES3_OPENGL()); check(ES31_OPENGL()); check(ES1_OPENGLES()); check(ES2_OPENGLES()); check(ES3_OPENGLES()); check(ES31_OPENGLES()); check(ES1_D3D9()); check(ES2_D3D9()); check(ES1_D3D11()); check(ES2_D3D11()); check(ES3_D3D11()); check(ES31_D3D11()); // Has an issue on the Android Shield TV. // check(ES1_VULKAN()); check(ES2_VULKAN()); check(ES3_VULKAN()); check(ES1_VULKAN_NULL()); check(ES2_VULKAN_NULL()); check(ES3_VULKAN_NULL()); check(ES1_NULL()); check(ES2_NULL()); check(ES3_NULL()); check(ES31_NULL()); }<commit_msg>Skip WhitelistMatchesSupport test on Android.<commit_after>// // Copyright 2015 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. // // EGLSanityCheckTest.cpp: // Tests used to check environment in which other tests are run. #include <gtest/gtest.h> #include "gpu_info_util/SystemInfo.h" #include "test_utils/ANGLETest.h" #include "test_utils/angle_test_instantiate.h" using namespace angle; class EGLSanityCheckTest : public EGLTest {}; // Checks the tests are running against ANGLE TEST_F(EGLSanityCheckTest, IsRunningOnANGLE) { const char *extensionString = static_cast<const char *>(eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS)); ASSERT_NE(strstr(extensionString, "EGL_ANGLE_platform_angle"), nullptr); } // Checks that getting function pointer works TEST_F(EGLSanityCheckTest, HasGetPlatformDisplayEXT) { ASSERT_NE(eglGetPlatformDisplayEXT, nullptr); } // Checks that calling GetProcAddress for a non-existant function fails. TEST_F(EGLSanityCheckTest, GetProcAddressNegativeTest) { auto check = eglGetProcAddress("WigglyWombats"); EXPECT_EQ(nullptr, check); } // Tests that our whitelist function generally maps to our support function. // We can add specific exceptions here if needed. TEST_F(EGLSanityCheckTest, WhitelistMatchesSupport) { // Has issues with Vulkan support detection on Android. ANGLE_SKIP_TEST_IF(IsAndroid()); // Cannot make any useful checks if SystemInfo is not supported. SystemInfo systemInfo; ANGLE_SKIP_TEST_IF(!GetSystemInfo(&systemInfo)); auto check = [&systemInfo](const PlatformParameters &params) { EXPECT_EQ(IsConfigWhitelisted(systemInfo, params), IsConfigSupported(params)) << params; }; check(ES1_OPENGL()); check(ES2_OPENGL()); check(ES3_OPENGL()); check(ES31_OPENGL()); check(ES1_OPENGLES()); check(ES2_OPENGLES()); check(ES3_OPENGLES()); check(ES31_OPENGLES()); check(ES1_D3D9()); check(ES2_D3D9()); check(ES1_D3D11()); check(ES2_D3D11()); check(ES3_D3D11()); check(ES31_D3D11()); check(ES1_VULKAN()); check(ES2_VULKAN()); check(ES3_VULKAN()); check(ES1_VULKAN_NULL()); check(ES2_VULKAN_NULL()); check(ES3_VULKAN_NULL()); check(ES1_NULL()); check(ES2_NULL()); check(ES3_NULL()); check(ES31_NULL()); }<|endoftext|>
<commit_before>#include "insertion.hpp" #include <iostream> using namespace std; void sort(vector<int> &array) { for (int i = 1; i < array.size(); i++) { int tmp = array[i]; int j = i - 1; while (j >= 0 && array[j] > tmp) { array[j + 1] = array[j]; j--; } array[j + 1] = tmp; } } const char *self() { return "Insertion sort"; } <commit_msg>fix warning<commit_after>#include "insertion.hpp" #include <iostream> using namespace std; void sort(vector<int> &array) { for (size_t i = 1; i < array.size(); i++) { int tmp = array[i]; int j = i - 1; while (j >= 0 && array[j] > tmp) { array[j + 1] = array[j]; j--; } array[j + 1] = tmp; } } const char *self() { return "Insertion sort"; } <|endoftext|>
<commit_before>#include <gtkmm.h> #include <string> #include <fstream> #include <iostream> #include "libjsapi.h" #include "application.h" #include "window.h" #include "builder.h" std::string LoadScript(int argc, char** argv) { std::string script; for (int i = 1; i < argc; i++) { std::fstream file; file.open(argv[i], std::ios::in); while (!!file) { char buffer[4096]; file.read(buffer, sizeof(buffer)); script.append(buffer, file.gcount()); } script += ";\n"; } return std::move(script); } int main(int argc, char** argv) { try { std::string script = LoadScript(argc, argv); rs::jsapi::Runtime rt(1024 * 1024 * 1024, true, true); auto app = new Application(rt, "com.ripcordsoftware.examples.gtk", 1, argv); rs::jsapi::Global::DefineProperty(rt, "app", *app); auto builder = new Builder(rt); rs::jsapi::Global::DefineProperty(rt, "builder", *builder); rs::jsapi::Global::DefineFunction(rt, "trace", [](const std::vector<rs::jsapi::Value>& args, rs::jsapi::Value& result){ for (auto arg : args) { std::cout << arg.ToString(); } if (args.size() > 0) { std::cout << std::endl; } return true; }); rt.Evaluate(script.c_str()); //rs::jsapi::Script scr(rt, script.c_str()); //scr.Compile(); //scr.Execute(); } catch (const rs::jsapi::ScriptException& ex) { std::cerr << "ERROR: line " << ex.lineno << std::endl << ex.what() << std::endl << ex.linebuf << std::endl; } return 0; }<commit_msg>Minor change to benefit from RVO<commit_after>#include <gtkmm.h> #include <string> #include <fstream> #include <iostream> #include "libjsapi.h" #include "application.h" #include "window.h" #include "builder.h" std::string LoadScript(int argc, char** argv) { std::string script; for (int i = 1; i < argc; i++) { std::fstream file; file.open(argv[i], std::ios::in); while (!!file) { char buffer[4096]; file.read(buffer, sizeof(buffer)); script.append(buffer, file.gcount()); } script += ";\n"; } return script; } int main(int argc, char** argv) { try { std::string script = LoadScript(argc, argv); rs::jsapi::Runtime rt(1024 * 1024 * 1024, true, true); auto app = new Application(rt, "com.ripcordsoftware.examples.gtk", 1, argv); rs::jsapi::Global::DefineProperty(rt, "app", *app); auto builder = new Builder(rt); rs::jsapi::Global::DefineProperty(rt, "builder", *builder); rs::jsapi::Global::DefineFunction(rt, "trace", [](const std::vector<rs::jsapi::Value>& args, rs::jsapi::Value& result){ for (auto arg : args) { std::cout << arg.ToString(); } if (args.size() > 0) { std::cout << std::endl; } return true; }); rt.Evaluate(script.c_str()); //rs::jsapi::Script scr(rt, script.c_str()); //scr.Compile(); //scr.Execute(); } catch (const rs::jsapi::ScriptException& ex) { std::cerr << "ERROR: line " << ex.lineno << std::endl << ex.what() << std::endl << ex.linebuf << std::endl; } return 0; }<|endoftext|>
<commit_before>#include "medActionsToolBox.h" #include <QtGui> #include <medDataManager.h> #include <medAbstractDbController.h> #include <medToolBoxBody.h> class medActionsToolBoxPrivate { public: QWidget* buttonsWidget; QWidget* noButtonsSelectedWidget; QPushButton* removeBt; QPushButton* viewBt; QPushButton* exportBt; QPushButton* bookmarkBt; QPushButton* importBt; QPushButton* loadBt; QPushButton* indexBt; QPushButton* saveBt; QList<QAbstractButton*> buttonsList; QMultiMap<QString, QString> itemToActions; }; medActionsToolBox::medActionsToolBox( QWidget *parent /*= 0*/ ) : medToolBox(parent), d(new medActionsToolBoxPrivate) { /** * This toolbox will show possible action buttons depending on the * items that is currently selected in the file system or db browser. * * Which actions are appropriate to which item is specified in the itemToActions map. * * It consists of two widgets: one containing the buttons and another one * with an explanatory label telling the user that an item must be selected. * Both widgets' visibilities are set depending on the selection. */ d->buttonsWidget = new QWidget(this); d->noButtonsSelectedWidget = new QWidget(this); initializeItemToActionsMap(); /* Begin create buttons */ d->removeBt = new QPushButton(d->buttonsWidget); d->removeBt->setAccessibleName("Remove"); d->removeBt->setText("Remove"); d->removeBt->setToolTip(tr("Remove selected item from the database.")); d->removeBt->setIcon(QIcon(":/icons/cross.svg")); d->viewBt = new QPushButton(d->buttonsWidget); d->viewBt->setAccessibleName("View"); d->viewBt->setText("View"); d->viewBt->setToolTip(tr("Load and visualize the currently selected item.")); d->viewBt->setIcon(QIcon(":/icons/eye.png")); d->exportBt = new QPushButton(d->buttonsWidget); d->exportBt->setAccessibleName("Export"); d->exportBt->setText("Export"); d->exportBt->setToolTip(tr("Export the series.")); d->exportBt->setIcon(QIcon(":/icons/export.png")); d->importBt = new QPushButton(d->buttonsWidget); d->importBt->setAccessibleName("Import"); d->importBt->setText("Import"); d->importBt->setToolTip(tr("Import (copy) item(s) into medInria's database.")); d->importBt->setIcon(QIcon(":/icons/import.png")); d->loadBt = new QPushButton(d->buttonsWidget); d->loadBt->setAccessibleName("Load"); d->loadBt->setText("Load"); d->loadBt->setToolTip(tr("Temporary load the item(s) so as they can be used inside medInria,\nbut do not include them in the database.")); d->loadBt->setIcon(QIcon(":/icons/document-open.png")); d->indexBt = new QPushButton(d->buttonsWidget); d->indexBt->setAccessibleName("Index"); d->indexBt->setText("Index"); d->indexBt->setToolTip(tr("Include the item(s) into medInria's database but do not import (copy) them.")); d->indexBt->setIcon(QIcon(":/icons/finger.png")); d->bookmarkBt = new QPushButton(d->buttonsWidget); d->bookmarkBt->setAccessibleName("Bookmark"); d->bookmarkBt->setText("Bookmark"); d->bookmarkBt->setToolTip(tr("Bookmark selected folder/resource.")); d->bookmarkBt->setIcon(QIcon(":/icons/star.svg")); d->saveBt = new QPushButton(d->buttonsWidget); d->saveBt->setAccessibleName("Save"); d->saveBt->setText("Save"); d->saveBt->setToolTip(tr("Save selected item into the database.")); d->saveBt->setIcon(QIcon(":/icons/save.png")); /* End create buttons */ // the order of the buttons in this list determines the order used to place them in the grid layout d->buttonsList << d->viewBt << d->loadBt << d->importBt << d->indexBt; d->buttonsList << d->removeBt << d->exportBt << d->saveBt << d->bookmarkBt; int COLUMNS = 4; // we will use 2 rows of 4 buttons each int i = 0; QGridLayout *gridLayout = new QGridLayout(d->buttonsWidget); gridLayout->setHorizontalSpacing(4); foreach(QAbstractButton* bt, d->buttonsList) { bt->setMinimumWidth(bt->minimumWidth()+12); bt->setAutoFillBackground(true); bt->setObjectName("actionToolBoxButton"); // set for style sheet medInria.qss gridLayout->addWidget(bt, (int)i/COLUMNS, (int)i%COLUMNS/*, Qt::AlignCenter*/); i++; } this->addWidget(d->buttonsWidget); d->buttonsWidget->setVisible(false); QLabel* noButtonsSelectedLabel = new QLabel( tr("Select any item to see possible actions."), d->noButtonsSelectedWidget); noButtonsSelectedLabel->setObjectName("actionToolBoxLabel"); // we use a layout to center the label QHBoxLayout* noButtonsSelectedLayout = new QHBoxLayout(d->noButtonsSelectedWidget); noButtonsSelectedLayout->addWidget(noButtonsSelectedLabel, 0, Qt::AlignCenter); this->addWidget(d->noButtonsSelectedWidget); connect(d->removeBt, SIGNAL(clicked()), this, SIGNAL(removeClicked())); connect(d->viewBt, SIGNAL(clicked()), this, SIGNAL(viewClicked())); connect(d->exportBt, SIGNAL(clicked()), this, SIGNAL(exportClicked())); connect(d->bookmarkBt, SIGNAL(clicked()), this, SIGNAL(bookmarkClicked())); connect(d->importBt, SIGNAL(clicked()), this, SIGNAL(importClicked())); connect(d->loadBt, SIGNAL(clicked()), this, SIGNAL(loadClicked())); connect(d->indexBt, SIGNAL(clicked()), this, SIGNAL(indexClicked())); connect(d->saveBt, SIGNAL(clicked()), this, SIGNAL(saveClicked())); // we keep the size of the toolbox fixed so as it doesn't not resize // constantly due to the exchange of the widgets this->body()->setFixedHeight(38 + 38 + 35); this->setTitle(tr("Actions")); } medActionsToolBox::~medActionsToolBox() { // delete d->itemToActions; // d->itemToActions = NULL; delete d; d = NULL; } void medActionsToolBox::patientSelected(const medDataIndex& index) { if( !(medDataManager::instance()->controllerForDataSource(index.dataSourceId())->isPersistent()) ) updateButtons("Unsaved Patient"); else updateButtons("Patient"); } void medActionsToolBox::seriesSelected(const medDataIndex& index) { if( !(medDataManager::instance()->controllerForDataSource(index.dataSourceId())->isPersistent()) ) updateButtons("Unsaved Series"); else updateButtons("Series"); } void medActionsToolBox::noPatientOrSeriesSelected() { updateButtons("None"); } void medActionsToolBox::selectedPathsChanged(const QStringList& paths) { bool containsFolders = false; bool containsFiles = false; foreach(QString path, paths) { QFileInfo fi(path); if (fi.isDir()) containsFolders = true; else containsFiles = true; } if (containsFolders && containsFiles) updateButtons("Files & Folders"); else if (containsFolders) updateButtons("Folders"); else if (containsFiles) updateButtons("Files"); else updateButtons("None"); } void medActionsToolBox::updateButtons(QString selectedItem) { QList<QString> actions = d->itemToActions.values(selectedItem); foreach(QAbstractButton* bt, d->buttonsList) { bt->setVisible(true); bool showButton = actions.contains( bt->accessibleName() ); bt->setEnabled(showButton); // Not accessible buttons are disabled if(!showButton) bt->setStyleSheet( "background: rgb(64, 64, 64);" "min-height: 30px;" "color: rgb(105, 105, 105)"); } // insert an explanatory label if no button is being displayed if(actions.size() == 0) { d->noButtonsSelectedWidget->setVisible(true); d->buttonsWidget->setVisible(false); } else { d->noButtonsSelectedWidget->setVisible(false); d->buttonsWidget->setVisible(true); } } void medActionsToolBox::initializeItemToActionsMap() { d->itemToActions = QMultiMap<QString, QString>(); d->itemToActions.insert("Patient", "Remove"); d->itemToActions.insert("Unsaved Patient", "Remove"); d->itemToActions.insert("Unsaved Patient", "Save"); d->itemToActions.insert("Series", "View"); d->itemToActions.insert("Series", "Export"); d->itemToActions.insert("Series", "Remove"); d->itemToActions.insert("Unsaved Series", "Remove"); d->itemToActions.insert("Unsaved Series", "Save"); d->itemToActions.insert("Unsaved Series", "View"); d->itemToActions.insert("Unsaved Series", "Export"); d->itemToActions.insert("Folders", "Bookmark"); d->itemToActions.insert("Folders", "Import"); d->itemToActions.insert("Folders", "Index"); d->itemToActions.insert("Folders", "Load"); d->itemToActions.insert("Folders", "View"); d->itemToActions.insert("Files", "Import"); d->itemToActions.insert("Files", "Index"); d->itemToActions.insert("Files", "Load"); d->itemToActions.insert("Files", "View"); d->itemToActions.insert("Files & Folders", "Import"); d->itemToActions.insert("Files & Folders", "Index"); d->itemToActions.insert("Files & Folders", "Load"); d->itemToActions.insert("Files & Folders", "View"); } <commit_msg>Add tr function in setText and apply no particular style to disabled action buttons<commit_after>#include "medActionsToolBox.h" #include <QtGui> #include <medDataManager.h> #include <medAbstractDbController.h> #include <medToolBoxBody.h> class medActionsToolBoxPrivate { public: QWidget* buttonsWidget; QWidget* noButtonsSelectedWidget; QPushButton* removeBt; QPushButton* viewBt; QPushButton* exportBt; QPushButton* bookmarkBt; QPushButton* importBt; QPushButton* loadBt; QPushButton* indexBt; QPushButton* saveBt; QList<QAbstractButton*> buttonsList; QMultiMap<QString, QString> itemToActions; }; medActionsToolBox::medActionsToolBox( QWidget *parent /*= 0*/ ) : medToolBox(parent), d(new medActionsToolBoxPrivate) { /** * This toolbox will show possible action buttons depending on the * items that is currently selected in the file system or db browser. * * Which actions are appropriate to which item is specified in the itemToActions map. * * It consists of two widgets: one containing the buttons and another one * with an explanatory label telling the user that an item must be selected. * Both widgets' visibilities are set depending on the selection. */ d->buttonsWidget = new QWidget(this); d->noButtonsSelectedWidget = new QWidget(this); initializeItemToActionsMap(); /* Begin create buttons */ d->removeBt = new QPushButton(d->buttonsWidget); d->removeBt->setAccessibleName("Remove"); d->removeBt->setText(tr("Remove")); d->removeBt->setToolTip(tr("Remove selected item from the database.")); d->removeBt->setIcon(QIcon(":/icons/cross.svg")); d->viewBt = new QPushButton(d->buttonsWidget); d->viewBt->setAccessibleName("View"); d->viewBt->setText(tr("View")); d->viewBt->setToolTip(tr("Load and visualize the currently selected item.")); d->viewBt->setIcon(QIcon(":/icons/eye.png")); d->exportBt = new QPushButton(d->buttonsWidget); d->exportBt->setAccessibleName("Export"); d->exportBt->setText(tr("Export")); d->exportBt->setToolTip(tr("Export the series.")); d->exportBt->setIcon(QIcon(":/icons/export.png")); d->importBt = new QPushButton(d->buttonsWidget); d->importBt->setAccessibleName("Import"); d->importBt->setText(tr("Import")); d->importBt->setToolTip(tr("Import (copy) item(s) into medInria's database.")); d->importBt->setIcon(QIcon(":/icons/import.png")); d->loadBt = new QPushButton(d->buttonsWidget); d->loadBt->setAccessibleName("Load"); d->loadBt->setText(tr("Load")); d->loadBt->setToolTip(tr("Temporary load the item(s) so as they can be used inside medInria,\nbut do not include them in the database.")); d->loadBt->setIcon(QIcon(":/icons/document-open.png")); d->indexBt = new QPushButton(d->buttonsWidget); d->indexBt->setAccessibleName("Index"); d->indexBt->setText(tr("Index")); d->indexBt->setToolTip(tr("Include the item(s) into medInria's database but do not import (copy) them.")); d->indexBt->setIcon(QIcon(":/icons/finger.png")); d->bookmarkBt = new QPushButton(d->buttonsWidget); d->bookmarkBt->setAccessibleName("Bookmark"); d->bookmarkBt->setText(tr("Bookmark")); d->bookmarkBt->setToolTip(tr("Bookmark selected folder/resource.")); d->bookmarkBt->setIcon(QIcon(":/icons/star.svg")); d->saveBt = new QPushButton(d->buttonsWidget); d->saveBt->setAccessibleName("Save"); d->saveBt->setText(tr("Save")); d->saveBt->setToolTip(tr("Save selected item into the database.")); d->saveBt->setIcon(QIcon(":/icons/save.png")); /* End create buttons */ // the order of the buttons in this list determines the order used to place them in the grid layout d->buttonsList << d->viewBt << d->loadBt << d->importBt << d->indexBt; d->buttonsList << d->removeBt << d->exportBt << d->saveBt << d->bookmarkBt; int COLUMNS = 4; // we will use 2 rows of 4 buttons each int i = 0; QGridLayout *gridLayout = new QGridLayout(d->buttonsWidget); gridLayout->setHorizontalSpacing(4); foreach(QAbstractButton* bt, d->buttonsList) { bt->setAutoFillBackground(true); bt->setObjectName("actionToolBoxButton"); // set for style sheet medInria.qss gridLayout->addWidget(bt, (int)i/COLUMNS, (int)i%COLUMNS); i++; } this->addWidget(d->buttonsWidget); d->buttonsWidget->setVisible(false); QLabel* noButtonsSelectedLabel = new QLabel( tr("Select any item to see possible actions."), d->noButtonsSelectedWidget); noButtonsSelectedLabel->setObjectName("actionToolBoxLabel"); // we use a layout to center the label QHBoxLayout* noButtonsSelectedLayout = new QHBoxLayout(d->noButtonsSelectedWidget); noButtonsSelectedLayout->addWidget(noButtonsSelectedLabel, 0, Qt::AlignCenter); this->addWidget(d->noButtonsSelectedWidget); connect(d->removeBt, SIGNAL(clicked()), this, SIGNAL(removeClicked())); connect(d->viewBt, SIGNAL(clicked()), this, SIGNAL(viewClicked())); connect(d->exportBt, SIGNAL(clicked()), this, SIGNAL(exportClicked())); connect(d->bookmarkBt, SIGNAL(clicked()), this, SIGNAL(bookmarkClicked())); connect(d->importBt, SIGNAL(clicked()), this, SIGNAL(importClicked())); connect(d->loadBt, SIGNAL(clicked()), this, SIGNAL(loadClicked())); connect(d->indexBt, SIGNAL(clicked()), this, SIGNAL(indexClicked())); connect(d->saveBt, SIGNAL(clicked()), this, SIGNAL(saveClicked())); // we keep the size of the toolbox fixed so as it doesn't not resize // constantly due to the exchange of the widgets this->body()->setFixedHeight(38 + 38 + 35); this->setTitle(tr("Actions")); } medActionsToolBox::~medActionsToolBox() { // delete d->itemToActions; // d->itemToActions = NULL; delete d; d = NULL; } void medActionsToolBox::patientSelected(const medDataIndex& index) { if( !(medDataManager::instance()->controllerForDataSource(index.dataSourceId())->isPersistent()) ) updateButtons("Unsaved Patient"); else updateButtons("Patient"); } void medActionsToolBox::seriesSelected(const medDataIndex& index) { if( !(medDataManager::instance()->controllerForDataSource(index.dataSourceId())->isPersistent()) ) updateButtons("Unsaved Series"); else updateButtons("Series"); } void medActionsToolBox::noPatientOrSeriesSelected() { updateButtons("None"); } void medActionsToolBox::selectedPathsChanged(const QStringList& paths) { bool containsFolders = false; bool containsFiles = false; foreach(QString path, paths) { QFileInfo fi(path); if (fi.isDir()) containsFolders = true; else containsFiles = true; } if (containsFolders && containsFiles) updateButtons("Files & Folders"); else if (containsFolders) updateButtons("Folders"); else if (containsFiles) updateButtons("Files"); else updateButtons("None"); } void medActionsToolBox::updateButtons(QString selectedItem) { QList<QString> actions = d->itemToActions.values(selectedItem); foreach(QAbstractButton* bt, d->buttonsList) { bt->setVisible(true); bool showButton = actions.contains( bt->accessibleName() ); bt->setEnabled(showButton); // Not accessible buttons are disabled } // insert an explanatory label if no button is being displayed if(actions.size() == 0) { d->noButtonsSelectedWidget->setVisible(true); d->buttonsWidget->setVisible(false); } else { d->noButtonsSelectedWidget->setVisible(false); d->buttonsWidget->setVisible(true); } } void medActionsToolBox::initializeItemToActionsMap() { d->itemToActions = QMultiMap<QString, QString>(); d->itemToActions.insert("Patient", "Remove"); d->itemToActions.insert("Unsaved Patient", "Remove"); d->itemToActions.insert("Unsaved Patient", "Save"); d->itemToActions.insert("Series", "View"); d->itemToActions.insert("Series", "Export"); d->itemToActions.insert("Series", "Remove"); d->itemToActions.insert("Unsaved Series", "Remove"); d->itemToActions.insert("Unsaved Series", "Save"); d->itemToActions.insert("Unsaved Series", "View"); d->itemToActions.insert("Unsaved Series", "Export"); d->itemToActions.insert("Folders", "Bookmark"); d->itemToActions.insert("Folders", "Import"); d->itemToActions.insert("Folders", "Index"); d->itemToActions.insert("Folders", "Load"); d->itemToActions.insert("Folders", "View"); d->itemToActions.insert("Files", "Import"); d->itemToActions.insert("Files", "Index"); d->itemToActions.insert("Files", "Load"); d->itemToActions.insert("Files", "View"); d->itemToActions.insert("Files & Folders", "Import"); d->itemToActions.insert("Files & Folders", "Index"); d->itemToActions.insert("Files & Folders", "Load"); d->itemToActions.insert("Files & Folders", "View"); } <|endoftext|>
<commit_before>#include "audiooutputfilter.h" AudioOutputFilter::AudioOutputFilter(QString id, StatisticsInterface* stats, QAudioFormat format): Filter(id, "Audio Output", stats, RAWAUDIO, NONE), output_() { maxBufferSize_ = 3; // to avoid extra latency output_.init(format); } void AudioOutputFilter::process() { std::unique_ptr<Data> input = getInput(); while(input) { output_.input(std::move(input)); } } <commit_msg>fix(Processing): Take all input if available in output filter<commit_after>#include "audiooutputfilter.h" AudioOutputFilter::AudioOutputFilter(QString id, StatisticsInterface* stats, QAudioFormat format): Filter(id, "Audio Output", stats, RAWAUDIO, NONE), output_() { maxBufferSize_ = 3; // to avoid extra latency output_.init(format); } void AudioOutputFilter::process() { std::unique_ptr<Data> input = getInput(); while(input) { output_.input(std::move(input)); // get next input input = getInput(); } } <|endoftext|>
<commit_before>#include "DrawTexture.h" #include "DTEX_Texture.h" #include "DTEX_Math.h" #include "RenderAPI.h" #include "ResCache.h" #include "Target.h" namespace dtex { SINGLETON_DEFINITION(DrawTexture); DrawTexture::DrawTexture() : m_curr(NULL) { } void DrawTexture::Draw(int src_tex_id, int src_w, int src_h, const Rect& src_r, Texture* dst, const Rect& dst_r, bool rotate) { Bind(dst); float vertices[8]; float w_inv = m_curr->GetWidthInv(), h_inv = m_curr->GetHeightInv(); float dst_xmin = dst_r.xmin * w_inv * 2 - 1, dst_xmax = dst_r.xmax * w_inv * 2 - 1, dst_ymin = dst_r.ymin * h_inv * 2 - 1, dst_ymax = dst_r.ymax * h_inv * 2 - 1; vertices[0] = dst_xmin; vertices[1] = dst_ymin; vertices[2] = dst_xmax; vertices[3] = dst_ymin; vertices[4] = dst_xmax; vertices[5] = dst_ymax; vertices[6] = dst_xmin; vertices[7] = dst_ymax; if (rotate) { float x, y; x = vertices[6]; y = vertices[7]; vertices[6] = vertices[4]; vertices[7] = vertices[5]; vertices[4] = vertices[2]; vertices[5] = vertices[3]; vertices[2] = vertices[0]; vertices[3] = vertices[1]; vertices[0] = x; vertices[1] = y; } float texcoords[8]; float src_w_inv = 1.0f / src_w, src_h_inv = 1.0f / src_h; float src_xmin = src_r.xmin * src_w_inv, src_xmax = src_r.xmax * src_w_inv, src_ymin = src_r.ymin * src_h_inv, src_ymax = src_r.ymax * src_h_inv; texcoords[0] = src_xmin; texcoords[1] = src_ymin; texcoords[2] = src_xmax; texcoords[3] = src_ymin; texcoords[4] = src_xmax; texcoords[5] = src_ymax; texcoords[6] = src_xmin; texcoords[7] = src_ymax; RenderAPI::SetProgram(); RenderAPI::Draw(vertices, texcoords, src_tex_id); } void DrawTexture::ClearTex(Texture* tex) { Bind(tex); RenderAPI::ClearColor(0, 0, 0, 0); } void DrawTexture::ClearTex(Texture* tex, float xmin, float ymin, float xmax, float ymax) { Bind(tex); int w = m_curr->GetWidth(), h = m_curr->GetHeight(); RenderAPI::ScissorPush( w * xmin, h * ymin, w * (xmax - xmin), h * (ymax - ymin)); RenderAPI::ClearColor(0, 0, 0, 0); RenderAPI::ScissorPop(); } void DrawTexture::Flush() { if (m_curr) { DrawAfter(m_ctx); m_curr = NULL; } } void DrawTexture::Clear() { m_curr = NULL; if (m_ctx.target) { ResCache::Instance()->ReturnTarget(m_ctx.target); m_ctx.target = NULL; } } void DrawTexture::DrawBefore(Context& ctx) { RenderAPI::DrawBegin(); RenderAPI::GetViewport(ctx.vx, ctx.vy, ctx.vw, ctx.vh); RenderAPI::SetViewport(0, 0, m_curr->GetWidth(), m_curr->GetHeight()); Target* target = ResCache::Instance()->FetchTarget(); target->Bind(); target->BindTexture(m_curr->GetID()); ctx.target = target; } void DrawTexture::DrawAfter(Context& ctx) { ctx.target->UnbindTexture(); ctx.target->Unbind(); ResCache::Instance()->ReturnTarget(ctx.target); ctx.target = NULL; RenderAPI::SetViewport(ctx.vx, ctx.vy, ctx.vw, ctx.vh); RenderAPI::DrawEnd(); } void DrawTexture::Bind(Texture* tex) { if (!tex || m_curr == tex) { return; } if (m_curr) { DrawAfter(m_ctx); } m_curr = tex; DrawBefore(m_ctx); } }<commit_msg>[FIXED] texture clear<commit_after>#include "DrawTexture.h" #include "DTEX_Texture.h" #include "DTEX_Math.h" #include "RenderAPI.h" #include "ResCache.h" #include "Target.h" namespace dtex { SINGLETON_DEFINITION(DrawTexture); DrawTexture::DrawTexture() : m_curr(NULL) { } void DrawTexture::Draw(int src_tex_id, int src_w, int src_h, const Rect& src_r, Texture* dst, const Rect& dst_r, bool rotate) { Bind(dst); float vertices[8]; float w_inv = m_curr->GetWidthInv(), h_inv = m_curr->GetHeightInv(); float dst_xmin = dst_r.xmin * w_inv * 2 - 1, dst_xmax = dst_r.xmax * w_inv * 2 - 1, dst_ymin = dst_r.ymin * h_inv * 2 - 1, dst_ymax = dst_r.ymax * h_inv * 2 - 1; vertices[0] = dst_xmin; vertices[1] = dst_ymin; vertices[2] = dst_xmax; vertices[3] = dst_ymin; vertices[4] = dst_xmax; vertices[5] = dst_ymax; vertices[6] = dst_xmin; vertices[7] = dst_ymax; if (rotate) { float x, y; x = vertices[6]; y = vertices[7]; vertices[6] = vertices[4]; vertices[7] = vertices[5]; vertices[4] = vertices[2]; vertices[5] = vertices[3]; vertices[2] = vertices[0]; vertices[3] = vertices[1]; vertices[0] = x; vertices[1] = y; } float texcoords[8]; float src_w_inv = 1.0f / src_w, src_h_inv = 1.0f / src_h; float src_xmin = src_r.xmin * src_w_inv, src_xmax = src_r.xmax * src_w_inv, src_ymin = src_r.ymin * src_h_inv, src_ymax = src_r.ymax * src_h_inv; texcoords[0] = src_xmin; texcoords[1] = src_ymin; texcoords[2] = src_xmax; texcoords[3] = src_ymin; texcoords[4] = src_xmax; texcoords[5] = src_ymax; texcoords[6] = src_xmin; texcoords[7] = src_ymax; RenderAPI::SetProgram(); RenderAPI::Draw(vertices, texcoords, src_tex_id); } void DrawTexture::ClearTex(Texture* tex) { Bind(tex); RenderAPI::ClearColor(0, 0, 0, 0); } void DrawTexture::ClearTex(Texture* tex, float xmin, float ymin, float xmax, float ymax) { Bind(tex); int w = m_curr->GetWidth(), h = m_curr->GetHeight(); RenderAPI::ScissorPush( w * xmin, h * ymin, w * (xmax - xmin), h * (ymax - ymin)); RenderAPI::ClearColor(0, 0, 0, 0); RenderAPI::ScissorPop(); } void DrawTexture::Flush() { if (m_curr) { DrawAfter(m_ctx); m_curr = NULL; } } void DrawTexture::Clear() { Flush(); m_curr = NULL; if (m_ctx.target) { ResCache::Instance()->ReturnTarget(m_ctx.target); m_ctx.target = NULL; } } void DrawTexture::DrawBefore(Context& ctx) { RenderAPI::DrawBegin(); RenderAPI::GetViewport(ctx.vx, ctx.vy, ctx.vw, ctx.vh); RenderAPI::SetViewport(0, 0, m_curr->GetWidth(), m_curr->GetHeight()); Target* target = ResCache::Instance()->FetchTarget(); target->Bind(); target->BindTexture(m_curr->GetID()); ctx.target = target; } void DrawTexture::DrawAfter(Context& ctx) { ctx.target->UnbindTexture(); ctx.target->Unbind(); ResCache::Instance()->ReturnTarget(ctx.target); ctx.target = NULL; RenderAPI::SetViewport(ctx.vx, ctx.vy, ctx.vw, ctx.vh); RenderAPI::DrawEnd(); } void DrawTexture::Bind(Texture* tex) { if (!tex || m_curr == tex) { return; } if (m_curr) { DrawAfter(m_ctx); } m_curr = tex; DrawBefore(m_ctx); } }<|endoftext|>
<commit_before>/* * Copyright © 2012, 2013, 2014 Intel Corporation * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND 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 "brw_vec4.h" #include "brw_cfg.h" using namespace brw; /** @file brw_vec4_cse.cpp * * Support for local common subexpression elimination. * * See Muchnick's Advanced Compiler Design and Implementation, section * 13.1 (p378). */ namespace { struct aeb_entry : public exec_node { /** The instruction that generates the expression value. */ vec4_instruction *generator; /** The temporary where the value is stored. */ src_reg tmp; }; } static bool is_expression(const vec4_instruction *const inst) { switch (inst->opcode) { case BRW_OPCODE_SEL: case BRW_OPCODE_NOT: case BRW_OPCODE_AND: case BRW_OPCODE_OR: case BRW_OPCODE_XOR: case BRW_OPCODE_SHR: case BRW_OPCODE_SHL: case BRW_OPCODE_ASR: case BRW_OPCODE_CMP: case BRW_OPCODE_CMPN: case BRW_OPCODE_ADD: case BRW_OPCODE_MUL: case BRW_OPCODE_FRC: case BRW_OPCODE_RNDU: case BRW_OPCODE_RNDD: case BRW_OPCODE_RNDE: case BRW_OPCODE_RNDZ: case BRW_OPCODE_LINE: case BRW_OPCODE_PLN: case BRW_OPCODE_MAD: case BRW_OPCODE_LRP: return true; case SHADER_OPCODE_RCP: case SHADER_OPCODE_RSQ: case SHADER_OPCODE_SQRT: case SHADER_OPCODE_EXP2: case SHADER_OPCODE_LOG2: case SHADER_OPCODE_POW: case SHADER_OPCODE_INT_QUOTIENT: case SHADER_OPCODE_INT_REMAINDER: case SHADER_OPCODE_SIN: case SHADER_OPCODE_COS: return inst->mlen == 0; default: return false; } } static bool is_expression_commutative(enum opcode op) { switch (op) { case BRW_OPCODE_AND: case BRW_OPCODE_OR: case BRW_OPCODE_XOR: case BRW_OPCODE_ADD: case BRW_OPCODE_MUL: return true; default: return false; } } static bool operands_match(enum opcode op, src_reg *xs, src_reg *ys) { if (!is_expression_commutative(op)) { return xs[0].equals(ys[0]) && xs[1].equals(ys[1]) && xs[2].equals(ys[2]); } else { return (xs[0].equals(ys[0]) && xs[1].equals(ys[1])) || (xs[1].equals(ys[0]) && xs[0].equals(ys[1])); } } static bool instructions_match(vec4_instruction *a, vec4_instruction *b) { return a->opcode == b->opcode && a->saturate == b->saturate && a->conditional_mod == b->conditional_mod && a->dst.type == b->dst.type && a->dst.writemask == b->dst.writemask && operands_match(a->opcode, a->src, b->src); } bool vec4_visitor::opt_cse_local(bblock_t *block) { bool progress = false; exec_list aeb; void *cse_ctx = ralloc_context(NULL); int ip = block->start_ip; foreach_inst_in_block (vec4_instruction, inst, block) { /* Skip some cases. */ if (is_expression(inst) && !inst->predicate && inst->mlen == 0 && (inst->dst.file != HW_REG || inst->dst.is_null())) { bool found = false; foreach_in_list_use_after(aeb_entry, entry, &aeb) { /* Match current instruction's expression against those in AEB. */ if (instructions_match(inst, entry->generator)) { found = true; progress = true; break; } } if (!found) { /* Our first sighting of this expression. Create an entry. */ aeb_entry *entry = ralloc(cse_ctx, aeb_entry); entry->tmp = src_reg(); /* file will be BAD_FILE */ entry->generator = inst; aeb.push_tail(entry); } else { /* This is at least our second sighting of this expression. * If we don't have a temporary already, make one. */ bool no_existing_temp = entry->tmp.file == BAD_FILE; if (no_existing_temp && !entry->generator->dst.is_null()) { entry->tmp = src_reg(this, glsl_type::float_type); entry->tmp.type = inst->dst.type; entry->tmp.swizzle = BRW_SWIZZLE_XYZW; vec4_instruction *copy = MOV(entry->generator->dst, entry->tmp); entry->generator->insert_after(block, copy); entry->generator->dst = dst_reg(entry->tmp); } /* dest <- temp */ if (!inst->dst.is_null()) { assert(inst->dst.type == entry->tmp.type); vec4_instruction *copy = MOV(inst->dst, entry->tmp); copy->force_writemask_all = inst->force_writemask_all; inst->insert_before(block, copy); } /* Set our iterator so that next time through the loop inst->next * will get the instruction in the basic block after the one we've * removed. */ vec4_instruction *prev = (vec4_instruction *)inst->prev; inst->remove(block); /* Appending an instruction may have changed our bblock end. */ if (inst == block->end) { block->end = prev; } inst = prev; } } foreach_in_list_safe(aeb_entry, entry, &aeb) { /* Kill all AEB entries that write a different value to or read from * the flag register if we just wrote it. */ if (inst->writes_flag()) { if (entry->generator->reads_flag() || (entry->generator->writes_flag() && !instructions_match(inst, entry->generator))) { entry->remove(); ralloc_free(entry); continue; } } for (int i = 0; i < 3; i++) { src_reg *src = &entry->generator->src[i]; /* Kill all AEB entries that use the destination we just * overwrote. */ if (inst->dst.file == entry->generator->src[i].file && inst->dst.reg == entry->generator->src[i].reg) { entry->remove(); ralloc_free(entry); break; } /* Kill any AEB entries using registers that don't get reused any * more -- a sure sign they'll fail operands_match(). */ int last_reg_use = MAX2(MAX2(virtual_grf_end[src->reg * 4 + 0], virtual_grf_end[src->reg * 4 + 1]), MAX2(virtual_grf_end[src->reg * 4 + 2], virtual_grf_end[src->reg * 4 + 3])); if (src->file == GRF && last_reg_use < ip) { entry->remove(); ralloc_free(entry); break; } } } ip++; } ralloc_free(cse_ctx); return progress; } bool vec4_visitor::opt_cse() { bool progress = false; calculate_live_intervals(); foreach_block (block, cfg) { progress = opt_cse_local(block) || progress; } if (progress) invalidate_live_intervals(false); return progress; } <commit_msg>i965/vec4: Only examine virtual_grf_end for GRF sources<commit_after>/* * Copyright © 2012, 2013, 2014 Intel Corporation * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND 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 "brw_vec4.h" #include "brw_cfg.h" using namespace brw; /** @file brw_vec4_cse.cpp * * Support for local common subexpression elimination. * * See Muchnick's Advanced Compiler Design and Implementation, section * 13.1 (p378). */ namespace { struct aeb_entry : public exec_node { /** The instruction that generates the expression value. */ vec4_instruction *generator; /** The temporary where the value is stored. */ src_reg tmp; }; } static bool is_expression(const vec4_instruction *const inst) { switch (inst->opcode) { case BRW_OPCODE_SEL: case BRW_OPCODE_NOT: case BRW_OPCODE_AND: case BRW_OPCODE_OR: case BRW_OPCODE_XOR: case BRW_OPCODE_SHR: case BRW_OPCODE_SHL: case BRW_OPCODE_ASR: case BRW_OPCODE_CMP: case BRW_OPCODE_CMPN: case BRW_OPCODE_ADD: case BRW_OPCODE_MUL: case BRW_OPCODE_FRC: case BRW_OPCODE_RNDU: case BRW_OPCODE_RNDD: case BRW_OPCODE_RNDE: case BRW_OPCODE_RNDZ: case BRW_OPCODE_LINE: case BRW_OPCODE_PLN: case BRW_OPCODE_MAD: case BRW_OPCODE_LRP: return true; case SHADER_OPCODE_RCP: case SHADER_OPCODE_RSQ: case SHADER_OPCODE_SQRT: case SHADER_OPCODE_EXP2: case SHADER_OPCODE_LOG2: case SHADER_OPCODE_POW: case SHADER_OPCODE_INT_QUOTIENT: case SHADER_OPCODE_INT_REMAINDER: case SHADER_OPCODE_SIN: case SHADER_OPCODE_COS: return inst->mlen == 0; default: return false; } } static bool is_expression_commutative(enum opcode op) { switch (op) { case BRW_OPCODE_AND: case BRW_OPCODE_OR: case BRW_OPCODE_XOR: case BRW_OPCODE_ADD: case BRW_OPCODE_MUL: return true; default: return false; } } static bool operands_match(enum opcode op, src_reg *xs, src_reg *ys) { if (!is_expression_commutative(op)) { return xs[0].equals(ys[0]) && xs[1].equals(ys[1]) && xs[2].equals(ys[2]); } else { return (xs[0].equals(ys[0]) && xs[1].equals(ys[1])) || (xs[1].equals(ys[0]) && xs[0].equals(ys[1])); } } static bool instructions_match(vec4_instruction *a, vec4_instruction *b) { return a->opcode == b->opcode && a->saturate == b->saturate && a->conditional_mod == b->conditional_mod && a->dst.type == b->dst.type && a->dst.writemask == b->dst.writemask && operands_match(a->opcode, a->src, b->src); } bool vec4_visitor::opt_cse_local(bblock_t *block) { bool progress = false; exec_list aeb; void *cse_ctx = ralloc_context(NULL); int ip = block->start_ip; foreach_inst_in_block (vec4_instruction, inst, block) { /* Skip some cases. */ if (is_expression(inst) && !inst->predicate && inst->mlen == 0 && (inst->dst.file != HW_REG || inst->dst.is_null())) { bool found = false; foreach_in_list_use_after(aeb_entry, entry, &aeb) { /* Match current instruction's expression against those in AEB. */ if (instructions_match(inst, entry->generator)) { found = true; progress = true; break; } } if (!found) { /* Our first sighting of this expression. Create an entry. */ aeb_entry *entry = ralloc(cse_ctx, aeb_entry); entry->tmp = src_reg(); /* file will be BAD_FILE */ entry->generator = inst; aeb.push_tail(entry); } else { /* This is at least our second sighting of this expression. * If we don't have a temporary already, make one. */ bool no_existing_temp = entry->tmp.file == BAD_FILE; if (no_existing_temp && !entry->generator->dst.is_null()) { entry->tmp = src_reg(this, glsl_type::float_type); entry->tmp.type = inst->dst.type; entry->tmp.swizzle = BRW_SWIZZLE_XYZW; vec4_instruction *copy = MOV(entry->generator->dst, entry->tmp); entry->generator->insert_after(block, copy); entry->generator->dst = dst_reg(entry->tmp); } /* dest <- temp */ if (!inst->dst.is_null()) { assert(inst->dst.type == entry->tmp.type); vec4_instruction *copy = MOV(inst->dst, entry->tmp); copy->force_writemask_all = inst->force_writemask_all; inst->insert_before(block, copy); } /* Set our iterator so that next time through the loop inst->next * will get the instruction in the basic block after the one we've * removed. */ vec4_instruction *prev = (vec4_instruction *)inst->prev; inst->remove(block); /* Appending an instruction may have changed our bblock end. */ if (inst == block->end) { block->end = prev; } inst = prev; } } foreach_in_list_safe(aeb_entry, entry, &aeb) { /* Kill all AEB entries that write a different value to or read from * the flag register if we just wrote it. */ if (inst->writes_flag()) { if (entry->generator->reads_flag() || (entry->generator->writes_flag() && !instructions_match(inst, entry->generator))) { entry->remove(); ralloc_free(entry); continue; } } for (int i = 0; i < 3; i++) { src_reg *src = &entry->generator->src[i]; /* Kill all AEB entries that use the destination we just * overwrote. */ if (inst->dst.file == entry->generator->src[i].file && inst->dst.reg == entry->generator->src[i].reg) { entry->remove(); ralloc_free(entry); break; } /* Kill any AEB entries using registers that don't get reused any * more -- a sure sign they'll fail operands_match(). */ if (src->file == GRF) { assert((src->reg * 4 + 3) < (virtual_grf_count * 4)); int last_reg_use = MAX2(MAX2(virtual_grf_end[src->reg * 4 + 0], virtual_grf_end[src->reg * 4 + 1]), MAX2(virtual_grf_end[src->reg * 4 + 2], virtual_grf_end[src->reg * 4 + 3])); if (last_reg_use < ip) { entry->remove(); ralloc_free(entry); break; } } } } ip++; } ralloc_free(cse_ctx); return progress; } bool vec4_visitor::opt_cse() { bool progress = false; calculate_live_intervals(); foreach_block (block, cfg) { progress = opt_cse_local(block) || progress; } if (progress) invalidate_live_intervals(false); return progress; } <|endoftext|>
<commit_before>/* * Main Menu-bar */ #include <stdint.h> #include <stdio.h> #include <vector> #include <SDL2/SDL.h> #include "imgui.h" extern "C" { #include "util.h" #include "snepulator.h" #include "config.h" #include "database/sms_db.h" #include "gamepad.h" #include "video/tms9928a.h" #include "video/sms_vdp.h" #include "cpu/z80.h" #include "sg-1000.h" #include "sms.h" #include "colecovision.h" extern TMS9928A_Mode sms_vdp_mode_get (void); /* TODO: Access through a function instead of accessing the array */ extern Gamepad_Instance gamepad_list [128]; extern uint32_t gamepad_list_count; extern Snepulator_Gamepad gamepad_1; extern Snepulator_Gamepad gamepad_2; } #include "gui/input.h" #include "gui/menubar.h" #include "gui/open.h" extern Snepulator_State state; extern File_Open_State open_state; extern bool config_capture_events; /* TODO: Move into state */ void snepulator_audio_device_open (const char *device); /* * C-friendly wrapper for ImGui::Text */ #include <stdarg.h> static void menubar_diagnostics_print (const char *format, ...) { va_list args; va_start (args, format); if (strcmp ("---", format) == 0) { ImGui::Separator (); } else { ImGui::TextV (format, args); } va_end (args); } /* * Render the menubar. */ void snepulator_render_menubar (void) { bool open_modal = false; bool input_modal = false; if (ImGui::BeginMainMenuBar ()) { if (ImGui::BeginMenu ("File")) { if (ImGui::MenuItem ("Open ROM...", NULL)) { snepulator_pause_set (true); open_state.title = "Open ROM..."; snepulator_set_open_regex (".*\\.(bin|col|gg|sg|sms)$"); open_state.callback = snepulator_rom_set; open_modal = true; } if (ImGui::BeginMenu ("Open BIOS")) { if (ImGui::MenuItem ("Master System...", NULL)) { snepulator_pause_set (true); open_state.title = "Open Master System BIOS..."; snepulator_set_open_regex (".*\\.(bin|sms)$"); open_state.callback = snepulator_bios_set; open_modal = true; } if (ImGui::MenuItem ("ColecoVision...", NULL)) { snepulator_pause_set (true); open_state.title = "Open ColecoVision BIOS..."; snepulator_set_open_regex (".*\\.(col)$"); open_state.callback = snepulator_bios_set; open_modal = true; } if (ImGui::BeginMenu ("Clear")) { if (ImGui::MenuItem ("Master System", NULL)) { config_entry_remove ("sms", "bios"); config_write (); if (state.sms_bios_filename != NULL) { free (state.sms_bios_filename); state.sms_bios_filename = NULL; } } if (ImGui::MenuItem ("ColecoVision", NULL)) { config_entry_remove ("colecovision", "bios"); config_write (); if (state.colecovision_bios_filename != NULL) { free (state.colecovision_bios_filename); state.colecovision_bios_filename = NULL; } } ImGui::EndMenu (); } ImGui::EndMenu (); } if (ImGui::MenuItem ("Close ROM", NULL)) { snepulator_reset (); snepulator_draw_logo (); } if (ImGui::MenuItem ("Pause", NULL, state.run == RUN_STATE_PAUSED)) { snepulator_pause_set (state.run != RUN_STATE_PAUSED); } ImGui::Separator (); if (ImGui::MenuItem ("Quit", NULL)) { state.run = RUN_STATE_EXIT; } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Console")) { if (ImGui::MenuItem ("Hard Reset")) { snepulator_system_init (); } ImGui::Separator (); if (ImGui::MenuItem ("World", NULL, state.region == REGION_WORLD)) { snepulator_region_set (REGION_WORLD); } if (ImGui::MenuItem ("Japan", NULL, state.region == REGION_JAPAN)) { snepulator_region_set (REGION_JAPAN); } ImGui::Separator (); if (ImGui::MenuItem ("Auto", NULL, state.format_auto)) { snepulator_video_format_set (VIDEO_FORMAT_AUTO); } if (ImGui::MenuItem ("NTSC", NULL, state.format == VIDEO_FORMAT_NTSC)) { snepulator_video_format_set (VIDEO_FORMAT_NTSC); } if (ImGui::MenuItem ("PAL", NULL, state.format == VIDEO_FORMAT_PAL)) { snepulator_video_format_set (VIDEO_FORMAT_PAL); } ImGui::Separator (); if (ImGui::MenuItem ("Overclock", NULL, !!state.overclock)) { snepulator_overclock_set (!state.overclock); } if (ImGui::MenuItem ("Remove Sprite Limit", NULL, state.remove_sprite_limit)) { snepulator_remove_sprite_limit_set (!state.remove_sprite_limit); } if (ImGui::MenuItem ("Disable Blanking", NULL, state.disable_blanking)) { snepulator_disable_blanking_set (!state.disable_blanking); } ImGui::Separator (); if (ImGui::BeginMenu ("Diagnostics")) { if (state.diagnostics_show == NULL) { ImGui::Text ("No diagnostics available."); } else { state.diagnostics_print = menubar_diagnostics_print; state.diagnostics_show (); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Statistics")) { ImGui::Text ("Video"); ImGui::Text ("Host: %.2f fps", state.host_framerate); ImGui::Text ("VDP: %.2f fps", state.vdp_framerate); ImGui::Separator (); ImGui::Text ("Audio"); ImGui::Text ("Ring buffer: %.2f%% full", state.audio_ring_utilisation * 100.0); ImGui::EndMenu (); } if (ImGui::MenuItem ("Time Five Minutes", NULL)) { uint32_t start_time; uint32_t end_time; snepulator_pause_set (true); start_time = snepulator_get_ticks (); state.run_callback (state.console_context, 5 * 60000); /* Simulate five minutes */ end_time = snepulator_get_ticks (); snepulator_pause_set (false); fprintf (stdout, "[DEBUG] Took %d ms to emulate five minutes. (%fx speed-up)\n", end_time - start_time, (5.0 * 60000.0) / (end_time - start_time)); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("State")) { if (ImGui::MenuItem ("Quick Save", NULL)) { if ((state.run == RUN_STATE_RUNNING || state.run == RUN_STATE_PAUSED) && state.state_save) { char *path = quicksave_path (state.get_rom_hash (state.console_context)); state.state_save (state.console_context, path); free (path); } } if (ImGui::MenuItem ("Quick Load", NULL)) { if ((state.run == RUN_STATE_RUNNING || state.run == RUN_STATE_PAUSED) && state.state_load) { char *path = quicksave_path (state.get_rom_hash (state.console_context)); state.state_load (state.console_context, path); free (path); snepulator_pause_set (false); } } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Input")) { if (ImGui::BeginMenu ("Player 1")) { if (ImGui::BeginMenu ("Type")) { if (ImGui::MenuItem ("Auto", NULL, gamepad_1.type_auto)) { gamepad_1.type_auto = true; } if (ImGui::MenuItem ("SMS Gamepad", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS)) { gamepad_1.type = GAMEPAD_TYPE_SMS; gamepad_1.type_auto = false; } if (ImGui::MenuItem ("SMS Light Phaser", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PHASER)) { gamepad_1.type = GAMEPAD_TYPE_SMS_PHASER; gamepad_1.type_auto = false; } if (ImGui::MenuItem ("SMS Paddle", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PADDLE)) { gamepad_1.type = GAMEPAD_TYPE_SMS_PADDLE; gamepad_1.type_auto = false; } ImGui::EndMenu (); } ImGui::Separator (); for (uint32_t i = 0; i < gamepad_list_count; i++) { if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_1.instance_id)) { gamepad_change_device (1, i); } } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Player 2")) { for (uint32_t i = 0; i < gamepad_list_count; i++) { if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_2.instance_id)) { gamepad_change_device (2, i); } } ImGui::EndMenu (); } if (ImGui::MenuItem ("Configure...", NULL)) { input_start (); input_modal = true; } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Audio")) { if (ImGui::BeginMenu ("Device")) { static char current_device[80] = { '\0' }; int count = SDL_GetNumAudioDevices (0); for (int i = 0; i < count; i++) { const char *audio_device_name = SDL_GetAudioDeviceName (i, 0); if (audio_device_name == NULL) audio_device_name = "Unknown Audio Device"; if (ImGui::MenuItem (audio_device_name, NULL, !strncmp (audio_device_name, current_device, 80))) { strncpy (current_device, audio_device_name, 79); snepulator_audio_device_open (audio_device_name); } } ImGui::EndMenu (); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Video")) { if (ImGui::BeginMenu ("Filter")) { if (ImGui::MenuItem ("Nearest Neighbour", NULL, state.video_filter == VIDEO_FILTER_NEAREST)) { snepulator_video_filter_set (VIDEO_FILTER_NEAREST); } if (ImGui::MenuItem ("Linear Interpolation", NULL, state.video_filter == VIDEO_FILTER_LINEAR)) { snepulator_video_filter_set (VIDEO_FILTER_LINEAR); } if (ImGui::MenuItem ("Scanlines", NULL, state.video_filter == VIDEO_FILTER_SCANLINES)) { snepulator_video_filter_set (VIDEO_FILTER_SCANLINES); } if (ImGui::MenuItem ("Dot Matrix", NULL, state.video_filter == VIDEO_FILTER_DOT_MATRIX)) { snepulator_video_filter_set (VIDEO_FILTER_DOT_MATRIX); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("3D Mode")) { if (ImGui::MenuItem ("Red-Cyan", NULL, state.video_3d_mode == VIDEO_3D_RED_CYAN)) { snepulator_video_3d_mode_set (VIDEO_3D_RED_CYAN); } if (ImGui::MenuItem ("Red-Green", NULL, state.video_3d_mode == VIDEO_3D_RED_GREEN)) { snepulator_video_3d_mode_set (VIDEO_3D_RED_GREEN); } if (ImGui::MenuItem ("Magenta-Green", NULL, state.video_3d_mode == VIDEO_3D_MAGENTA_GREEN)) { snepulator_video_3d_mode_set (VIDEO_3D_MAGENTA_GREEN); } if (ImGui::MenuItem ("Left image only", NULL, state.video_3d_mode == VIDEO_3D_LEFT_ONLY)) { snepulator_video_3d_mode_set (VIDEO_3D_LEFT_ONLY); } if (ImGui::MenuItem ("Right image only", NULL, state.video_3d_mode == VIDEO_3D_RIGHT_ONLY)) { snepulator_video_3d_mode_set (VIDEO_3D_RIGHT_ONLY); } ImGui::Separator (); if (ImGui::BeginMenu ("Colour")) { if (ImGui::MenuItem ("Saturation 0%", NULL, state.video_3d_saturation == 0.0)) { snepulator_video_3d_saturation_set (0.0); } if (ImGui::MenuItem ("Saturation 25%", NULL, state.video_3d_saturation == 0.25)) { snepulator_video_3d_saturation_set (0.25); } if (ImGui::MenuItem ("Saturation 50%", NULL, state.video_3d_saturation == 0.50)) { snepulator_video_3d_saturation_set (0.50); } if (ImGui::MenuItem ("Saturation 75%", NULL, state.video_3d_saturation == 0.75)) { snepulator_video_3d_saturation_set (0.75); } if (ImGui::MenuItem ("Saturation 100%", NULL, state.video_3d_saturation == 1.0)) { snepulator_video_3d_saturation_set (1.0); } ImGui::EndMenu (); } ImGui::EndMenu (); } if (ImGui::MenuItem ("Take Screenshot")) { snepulator_take_screenshot (); } ImGui::EndMenu (); } ImGui::EndMainMenuBar (); } /* Open any popups requested */ if (open_modal) { ImGui::OpenPopup (open_state.title); } if (input_modal) { config_capture_events = true; ImGui::OpenPopup ("Configure device..."); } } <commit_msg>gui: Don't auto-hide gui while menu is open<commit_after>/* * Main Menu-bar */ #include <stdint.h> #include <stdio.h> #include <vector> #include <SDL2/SDL.h> #include "imgui.h" extern "C" { #include "util.h" #include "snepulator.h" #include "config.h" #include "database/sms_db.h" #include "gamepad.h" #include "video/tms9928a.h" #include "video/sms_vdp.h" #include "cpu/z80.h" #include "sg-1000.h" #include "sms.h" #include "colecovision.h" extern TMS9928A_Mode sms_vdp_mode_get (void); /* TODO: Access through a function instead of accessing the array */ extern Gamepad_Instance gamepad_list [128]; extern uint32_t gamepad_list_count; extern Snepulator_Gamepad gamepad_1; extern Snepulator_Gamepad gamepad_2; } #include "gui/input.h" #include "gui/menubar.h" #include "gui/open.h" extern Snepulator_State state; extern File_Open_State open_state; extern bool config_capture_events; /* TODO: Move into state */ void snepulator_audio_device_open (const char *device); /* * C-friendly wrapper for ImGui::Text */ #include <stdarg.h> static void menubar_diagnostics_print (const char *format, ...) { va_list args; va_start (args, format); if (strcmp ("---", format) == 0) { ImGui::Separator (); } else { ImGui::TextV (format, args); } va_end (args); } /* * Render the menubar. * * Updates mouse_time so that the menu won't disappear while open. */ void snepulator_render_menubar (void) { bool open_modal = false; bool input_modal = false; if (ImGui::BeginMainMenuBar ()) { if (ImGui::BeginMenu ("File")) { state.mouse_time = snepulator_get_ticks (); if (ImGui::MenuItem ("Open ROM...", NULL)) { snepulator_pause_set (true); open_state.title = "Open ROM..."; snepulator_set_open_regex (".*\\.(bin|col|gg|sg|sms)$"); open_state.callback = snepulator_rom_set; open_modal = true; } if (ImGui::BeginMenu ("Open BIOS")) { if (ImGui::MenuItem ("Master System...", NULL)) { snepulator_pause_set (true); open_state.title = "Open Master System BIOS..."; snepulator_set_open_regex (".*\\.(bin|sms)$"); open_state.callback = snepulator_bios_set; open_modal = true; } if (ImGui::MenuItem ("ColecoVision...", NULL)) { snepulator_pause_set (true); open_state.title = "Open ColecoVision BIOS..."; snepulator_set_open_regex (".*\\.(col)$"); open_state.callback = snepulator_bios_set; open_modal = true; } if (ImGui::BeginMenu ("Clear")) { if (ImGui::MenuItem ("Master System", NULL)) { config_entry_remove ("sms", "bios"); config_write (); if (state.sms_bios_filename != NULL) { free (state.sms_bios_filename); state.sms_bios_filename = NULL; } } if (ImGui::MenuItem ("ColecoVision", NULL)) { config_entry_remove ("colecovision", "bios"); config_write (); if (state.colecovision_bios_filename != NULL) { free (state.colecovision_bios_filename); state.colecovision_bios_filename = NULL; } } ImGui::EndMenu (); } ImGui::EndMenu (); } if (ImGui::MenuItem ("Close ROM", NULL)) { snepulator_reset (); snepulator_draw_logo (); } if (ImGui::MenuItem ("Pause", NULL, state.run == RUN_STATE_PAUSED)) { snepulator_pause_set (state.run != RUN_STATE_PAUSED); } ImGui::Separator (); if (ImGui::MenuItem ("Quit", NULL)) { state.run = RUN_STATE_EXIT; } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Console")) { state.mouse_time = snepulator_get_ticks (); if (ImGui::MenuItem ("Hard Reset")) { snepulator_system_init (); } ImGui::Separator (); if (ImGui::MenuItem ("World", NULL, state.region == REGION_WORLD)) { snepulator_region_set (REGION_WORLD); } if (ImGui::MenuItem ("Japan", NULL, state.region == REGION_JAPAN)) { snepulator_region_set (REGION_JAPAN); } ImGui::Separator (); if (ImGui::MenuItem ("Auto", NULL, state.format_auto)) { snepulator_video_format_set (VIDEO_FORMAT_AUTO); } if (ImGui::MenuItem ("NTSC", NULL, state.format == VIDEO_FORMAT_NTSC)) { snepulator_video_format_set (VIDEO_FORMAT_NTSC); } if (ImGui::MenuItem ("PAL", NULL, state.format == VIDEO_FORMAT_PAL)) { snepulator_video_format_set (VIDEO_FORMAT_PAL); } ImGui::Separator (); if (ImGui::MenuItem ("Overclock", NULL, !!state.overclock)) { snepulator_overclock_set (!state.overclock); } if (ImGui::MenuItem ("Remove Sprite Limit", NULL, state.remove_sprite_limit)) { snepulator_remove_sprite_limit_set (!state.remove_sprite_limit); } if (ImGui::MenuItem ("Disable Blanking", NULL, state.disable_blanking)) { snepulator_disable_blanking_set (!state.disable_blanking); } ImGui::Separator (); if (ImGui::BeginMenu ("Diagnostics")) { if (state.diagnostics_show == NULL) { ImGui::Text ("No diagnostics available."); } else { state.diagnostics_print = menubar_diagnostics_print; state.diagnostics_show (); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Statistics")) { ImGui::Text ("Video"); ImGui::Text ("Host: %.2f fps", state.host_framerate); ImGui::Text ("VDP: %.2f fps", state.vdp_framerate); ImGui::Separator (); ImGui::Text ("Audio"); ImGui::Text ("Ring buffer: %.2f%% full", state.audio_ring_utilisation * 100.0); ImGui::EndMenu (); } if (ImGui::MenuItem ("Time Five Minutes", NULL)) { uint32_t start_time; uint32_t end_time; snepulator_pause_set (true); start_time = snepulator_get_ticks (); state.run_callback (state.console_context, 5 * 60000); /* Simulate five minutes */ end_time = snepulator_get_ticks (); snepulator_pause_set (false); fprintf (stdout, "[DEBUG] Took %d ms to emulate five minutes. (%fx speed-up)\n", end_time - start_time, (5.0 * 60000.0) / (end_time - start_time)); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("State")) { state.mouse_time = snepulator_get_ticks (); if (ImGui::MenuItem ("Quick Save", NULL)) { if ((state.run == RUN_STATE_RUNNING || state.run == RUN_STATE_PAUSED) && state.state_save) { char *path = quicksave_path (state.get_rom_hash (state.console_context)); state.state_save (state.console_context, path); free (path); } } if (ImGui::MenuItem ("Quick Load", NULL)) { if ((state.run == RUN_STATE_RUNNING || state.run == RUN_STATE_PAUSED) && state.state_load) { char *path = quicksave_path (state.get_rom_hash (state.console_context)); state.state_load (state.console_context, path); free (path); snepulator_pause_set (false); } } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Input")) { state.mouse_time = snepulator_get_ticks (); if (ImGui::BeginMenu ("Player 1")) { if (ImGui::BeginMenu ("Type")) { if (ImGui::MenuItem ("Auto", NULL, gamepad_1.type_auto)) { gamepad_1.type_auto = true; } if (ImGui::MenuItem ("SMS Gamepad", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS)) { gamepad_1.type = GAMEPAD_TYPE_SMS; gamepad_1.type_auto = false; } if (ImGui::MenuItem ("SMS Light Phaser", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PHASER)) { gamepad_1.type = GAMEPAD_TYPE_SMS_PHASER; gamepad_1.type_auto = false; } if (ImGui::MenuItem ("SMS Paddle", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PADDLE)) { gamepad_1.type = GAMEPAD_TYPE_SMS_PADDLE; gamepad_1.type_auto = false; } ImGui::EndMenu (); } ImGui::Separator (); for (uint32_t i = 0; i < gamepad_list_count; i++) { if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_1.instance_id)) { gamepad_change_device (1, i); } } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Player 2")) { for (uint32_t i = 0; i < gamepad_list_count; i++) { if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_2.instance_id)) { gamepad_change_device (2, i); } } ImGui::EndMenu (); } if (ImGui::MenuItem ("Configure...", NULL)) { input_start (); input_modal = true; } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Audio")) { state.mouse_time = snepulator_get_ticks (); if (ImGui::BeginMenu ("Device")) { static char current_device[80] = { '\0' }; int count = SDL_GetNumAudioDevices (0); for (int i = 0; i < count; i++) { const char *audio_device_name = SDL_GetAudioDeviceName (i, 0); if (audio_device_name == NULL) audio_device_name = "Unknown Audio Device"; if (ImGui::MenuItem (audio_device_name, NULL, !strncmp (audio_device_name, current_device, 80))) { strncpy (current_device, audio_device_name, 79); snepulator_audio_device_open (audio_device_name); } } ImGui::EndMenu (); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Video")) { state.mouse_time = snepulator_get_ticks (); if (ImGui::BeginMenu ("Filter")) { if (ImGui::MenuItem ("Nearest Neighbour", NULL, state.video_filter == VIDEO_FILTER_NEAREST)) { snepulator_video_filter_set (VIDEO_FILTER_NEAREST); } if (ImGui::MenuItem ("Linear Interpolation", NULL, state.video_filter == VIDEO_FILTER_LINEAR)) { snepulator_video_filter_set (VIDEO_FILTER_LINEAR); } if (ImGui::MenuItem ("Scanlines", NULL, state.video_filter == VIDEO_FILTER_SCANLINES)) { snepulator_video_filter_set (VIDEO_FILTER_SCANLINES); } if (ImGui::MenuItem ("Dot Matrix", NULL, state.video_filter == VIDEO_FILTER_DOT_MATRIX)) { snepulator_video_filter_set (VIDEO_FILTER_DOT_MATRIX); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("3D Mode")) { if (ImGui::MenuItem ("Red-Cyan", NULL, state.video_3d_mode == VIDEO_3D_RED_CYAN)) { snepulator_video_3d_mode_set (VIDEO_3D_RED_CYAN); } if (ImGui::MenuItem ("Red-Green", NULL, state.video_3d_mode == VIDEO_3D_RED_GREEN)) { snepulator_video_3d_mode_set (VIDEO_3D_RED_GREEN); } if (ImGui::MenuItem ("Magenta-Green", NULL, state.video_3d_mode == VIDEO_3D_MAGENTA_GREEN)) { snepulator_video_3d_mode_set (VIDEO_3D_MAGENTA_GREEN); } if (ImGui::MenuItem ("Left image only", NULL, state.video_3d_mode == VIDEO_3D_LEFT_ONLY)) { snepulator_video_3d_mode_set (VIDEO_3D_LEFT_ONLY); } if (ImGui::MenuItem ("Right image only", NULL, state.video_3d_mode == VIDEO_3D_RIGHT_ONLY)) { snepulator_video_3d_mode_set (VIDEO_3D_RIGHT_ONLY); } ImGui::Separator (); if (ImGui::BeginMenu ("Colour")) { if (ImGui::MenuItem ("Saturation 0%", NULL, state.video_3d_saturation == 0.0)) { snepulator_video_3d_saturation_set (0.0); } if (ImGui::MenuItem ("Saturation 25%", NULL, state.video_3d_saturation == 0.25)) { snepulator_video_3d_saturation_set (0.25); } if (ImGui::MenuItem ("Saturation 50%", NULL, state.video_3d_saturation == 0.50)) { snepulator_video_3d_saturation_set (0.50); } if (ImGui::MenuItem ("Saturation 75%", NULL, state.video_3d_saturation == 0.75)) { snepulator_video_3d_saturation_set (0.75); } if (ImGui::MenuItem ("Saturation 100%", NULL, state.video_3d_saturation == 1.0)) { snepulator_video_3d_saturation_set (1.0); } ImGui::EndMenu (); } ImGui::EndMenu (); } if (ImGui::MenuItem ("Take Screenshot")) { snepulator_take_screenshot (); } ImGui::EndMenu (); } ImGui::EndMainMenuBar (); } /* Open any popups requested */ if (open_modal) { ImGui::OpenPopup (open_state.title); } if (input_modal) { config_capture_events = true; ImGui::OpenPopup ("Configure device..."); } } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <vector> #include "test.h" #include "trace.h" #include "double.h" #include "mpq.h" #include "mpfp.h" #include "interval_def.h" using namespace lean; typedef interval<double> qi; typedef interval<double> di; typedef interval<mpfp> fi; typedef std::vector<qi> qiv; static qiv mk_some_intervals(int low, int hi) { qiv r; for (unsigned lo = 0; lo < 2; lo++) for (unsigned uo = 0; uo < 2; uo++) for (int l = low; l <= hi; l++) for (int u = l; u <= hi; u++) { if ((lo || uo) && l == u) continue; r.push_back(qi(lo, l, u, uo)); } return r; } template<typename T> bool closed_endpoints(interval<T> const & i) { return !i.is_lower_open() && !i.is_upper_open(); } static void tst1() { qi t(1, 3); std::cout << t + qi(2, 4, false, true) << "\n"; std::cout << t << " --> " << inv(t) << "\n"; lean_assert(neg(t) == qi(-3, -1)); lean_assert(neg(neg(t)) == t); lean_assert(qi(1, 2) + qi(2, 3) == qi(3, 5)); lean_assert(qi(1, 5) + qi(-2, -3) == qi(-1, 2)); for (auto i1 : mk_some_intervals(-2, 2)) for (auto i2 : mk_some_intervals(-2, 2)) { auto r = i1 + i2; auto s = i1; s += i2; lean_assert(r == s); lean_assert(r.lower() == i1.lower() + i2.lower()); lean_assert(r.upper() == i1.upper() + i2.upper()); lean_assert(r.is_lower_open() == i1.is_lower_open() || i2.is_lower_open()); lean_assert(r.is_upper_open() == i1.is_upper_open() || i2.is_upper_open()); r -= i2; lean_assert(r.contains(i1)); r = i1 - i2; s = i1; s -= i2; lean_assert(r == s); lean_assert(r.lower() == i1.lower() - i2.upper()); lean_assert(r.upper() == i1.upper() - i2.lower()); lean_assert(r.is_lower_open() == i1.is_lower_open() || i2.is_upper_open()); lean_assert(r.is_upper_open() == i1.is_upper_open() || i2.is_lower_open()); r -= r; lean_assert(r.contains_zero()); r = i1 * i2; s = i1; s *= i2; lean_assert(r == s); lean_assert(r.lower() == std::min(i1.lower()*i2.lower(), std::min(i1.lower()*i2.upper(), std::min(i1.upper()*i2.lower(), i1.upper()*i2.upper())))); lean_assert(r.upper() == std::max(i1.lower()*i2.lower(), std::max(i1.lower()*i2.upper(), std::max(i1.upper()*i2.lower(), i1.upper()*i2.upper())))); } lean_assert(qi(1, 3).before(qi(4, 6))); lean_assert(!qi(1, 3).before(qi(3, 6))); lean_assert(qi(1, 3, true, true).before(qi(3, 6))); } static void tst2() { lean_assert(power(qi(2, 3), 2) == qi(4, 9)); lean_assert(power(qi(-2, 3), 2) == qi(0, 9)); lean_assert(power(qi(true, -2, 3, true), 2) == qi(false, 0, 9, true)); lean_assert(power(qi(true, -4, 3, true), 2) == qi(false, 0, 16, true)); lean_assert(power(qi(-3, -2), 2) == qi(4, 9)); std::cout << power(qi(false, -3, -2, true), 2) << " --> " << qi(true, 4, 9, false) << "\n"; lean_assert(power(qi(false, -3, -2, true), 2) == qi(true, 4, 9, false)); lean_assert(power(qi(-3,-1), 3) == qi(-27, -1)); lean_assert(power(qi(-3, 4), 3) == qi(-27, 64)); lean_assert(power(qi(),3) == qi()); lean_assert(power(qi(),2) == qi(false, 0)); // (-oo, oo)^2 == [0, oo) } static void double_interval_trans() { di i1(1.0, 2.0); std::cout << "power(" << i1 << ", 3) = " << power(i1, 3) << std::endl; std::cout << "exp(" << i1 << ") = " << exp(i1) << std::endl; std::cout << "log(" << i1 << ") = " << log(i1) << std::endl; } static void mpfr_interval_trans() { fi i1(1.0, 2.0); std::cout << "power(" << i1 << ", 3) = " << power(i1, 3) << std::endl; std::cout << "exp(" << i1 << ") = " << exp(i1) << std::endl; std::cout << "log(" << i1 << ") = " << log(i1) << std::endl; } int main() { continue_on_violation(true); enable_trace("numerics"); tst1(); tst2(); double_interval_trans(); mpfr_interval_trans(); return has_violations() ? 1 : 0; } <commit_msg>Add more tests to interval<commit_after>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <vector> #include "test.h" #include "trace.h" #include "double.h" #include "mpq.h" #include "mpfp.h" #include "interval_def.h" using namespace lean; typedef interval<double> qi; typedef interval<double> di; typedef interval<mpfp> fi; typedef std::vector<qi> qiv; static qiv mk_some_intervals(int low, int hi) { qiv r; for (unsigned lo = 0; lo < 2; lo++) for (unsigned uo = 0; uo < 2; uo++) for (int l = low; l <= hi; l++) for (int u = l; u <= hi; u++) { if ((lo || uo) && l == u) continue; r.push_back(qi(lo, l, u, uo)); } return r; } template<typename T> bool closed_endpoints(interval<T> const & i) { return !i.is_lower_open() && !i.is_upper_open(); } static void tst1() { qi t(1, 3); std::cout << t + qi(2, 4, false, true) << "\n"; std::cout << t << " --> " << inv(t) << "\n"; lean_assert(neg(t) == qi(-3, -1)); lean_assert(neg(neg(t)) == t); lean_assert(qi(1, 2) + qi(2, 3) == qi(3, 5)); lean_assert(qi(1, 5) + qi(-2, -3) == qi(-1, 2)); for (auto i1 : mk_some_intervals(-2, 2)) for (auto i2 : mk_some_intervals(-2, 2)) { auto r = i1 + i2; auto s = i1; s += i2; lean_assert(r == s); lean_assert(r.lower() == i1.lower() + i2.lower()); lean_assert(r.upper() == i1.upper() + i2.upper()); lean_assert(r.is_lower_open() == i1.is_lower_open() || i2.is_lower_open()); lean_assert(r.is_upper_open() == i1.is_upper_open() || i2.is_upper_open()); r -= i2; lean_assert(r.contains(i1)); r = i1 - i2; s = i1; s -= i2; lean_assert(r == s); lean_assert(r.lower() == i1.lower() - i2.upper()); lean_assert(r.upper() == i1.upper() - i2.lower()); lean_assert(r.is_lower_open() == i1.is_lower_open() || i2.is_upper_open()); lean_assert(r.is_upper_open() == i1.is_upper_open() || i2.is_lower_open()); r -= r; lean_assert(r.contains_zero()); r = i1 * i2; s = i1; s *= i2; lean_assert(r == s); lean_assert(r.lower() == std::min(i1.lower()*i2.lower(), std::min(i1.lower()*i2.upper(), std::min(i1.upper()*i2.lower(), i1.upper()*i2.upper())))); lean_assert(r.upper() == std::max(i1.lower()*i2.lower(), std::max(i1.lower()*i2.upper(), std::max(i1.upper()*i2.lower(), i1.upper()*i2.upper())))); } lean_assert(qi(1, 3).before(qi(4, 6))); lean_assert(!qi(1, 3).before(qi(3, 6))); lean_assert(qi(1, 3, true, true).before(qi(3, 6))); } static void tst2() { lean_assert(power(qi(2, 3), 2) == qi(4, 9)); lean_assert(power(qi(-2, 3), 2) == qi(0, 9)); lean_assert(power(qi(true, -2, 3, true), 2) == qi(false, 0, 9, true)); lean_assert(power(qi(true, -4, 3, true), 2) == qi(false, 0, 16, true)); lean_assert(power(qi(-3, -2), 2) == qi(4, 9)); std::cout << power(qi(false, -3, -2, true), 2) << " --> " << qi(true, 4, 9, false) << "\n"; lean_assert(power(qi(false, -3, -2, true), 2) == qi(true, 4, 9, false)); lean_assert(power(qi(-3,-1), 3) == qi(-27, -1)); lean_assert(power(qi(-3, 4), 3) == qi(-27, 64)); lean_assert(power(qi(),3) == qi()); lean_assert(power(qi(),2) == qi(false, 0)); // (-oo, oo)^2 == [0, oo) } static void double_interval_trans() { di i1(1.0, 2.0); std::cout << "power(" << i1 << ", 3) = " << power(i1, 3) << std::endl; std::cout << "exp(" << i1 << ") = " << exp(i1) << std::endl; std::cout << "log(" << i1 << ") = " << log(i1) << std::endl; } template<typename T1, typename T2, typename T3> void print_result(T1 a, std::string const & op, T2 b, T3 r) { std::cout << a << " " << op << " " << b << " = " << r << std::endl; } static void mpfr_interval_trans() { fi i1(1.0, 2.0); fi i2(3.0, 4.0); fi i3(-10.0, -5.0); fi i4(-3.0, +4.0); fi i5(5.0, 8.0); mpfp c1(0.6); mpfp c2(3.0); mpfp c3(0.0); mpfp c4(-4.5); mpfp c5(-0.3); print_result(i1, "+", c1, i1 + c1); print_result(i2, "+", c2, i2 + c2); print_result(i3, "+", c3, i3 + c3); print_result(i4, "+", c4, i4 + c4); print_result(i5, "+", c5, i5 + c5); print_result(i5, "+", c1, i5 + c1); print_result(i4, "+", c2, i4 + c2); print_result(i2, "+", c4, i2 + c4); print_result(i1, "+", c5, i1 + c5); print_result(c1, "+", i1, c1 + i1); print_result(c2, "+", i2, c2 + i2); print_result(c3, "+", i3, c3 + i3); print_result(c4, "+", i4, c4 + i4); print_result(c5, "+", i5, c5 + i5); print_result(c5, "+", i1, c5 + i1); print_result(c4, "+", i2, c4 + i2); print_result(c2, "+", i4, c2 + i4); print_result(c1, "+", i5, c1 + i5); print_result(i1, "-", c1, i1 - c1); print_result(i2, "-", c2, i2 - c2); print_result(i3, "-", c3, i3 - c3); print_result(i4, "-", c4, i4 - c4); print_result(i5, "-", c5, i5 - c5); print_result(i5, "-", c1, i5 - c1); print_result(i4, "-", c2, i4 - c2); print_result(i2, "-", c4, i2 - c4); print_result(i1, "-", c5, i1 - c5); print_result(i1, "*", c1, i1 * c1); print_result(i2, "*", c2, i2 * c2); print_result(i3, "*", c3, i3 * c3); print_result(i4, "*", c4, i4 * c4); print_result(i5, "*", c5, i5 * c5); print_result(i5, "*", c1, i5 * c1); print_result(i4, "*", c2, i4 * c2); print_result(i2, "*", c4, i2 * c4); print_result(i1, "*", c5, i1 * c5); print_result(i1, "+", c1, i1 + c1); print_result(i2, "+", c2, i2 + c2); print_result(i3, "+", c3, i3 + c3); print_result(i4, "+", c4, i4 + c4); print_result(i5, "+", c5, i5 + c5); print_result(i5, "+", c1, i5 + c1); print_result(i4, "+", c2, i4 + c2); print_result(i2, "+", c4, i2 + c4); print_result(i1, "+", c5, i1 + c5); std::cout << "power(" << i1 << ", 3) = " << power(i1, 3) << std::endl; std::cout << "exp(" << i1 << ") = " << exp(i1) << std::endl; std::cout << "log(" << i1 << ") = " << log(i1) << std::endl; } int main() { continue_on_violation(true); enable_trace("numerics"); tst1(); tst2(); double_interval_trans(); mpfr_interval_trans(); return has_violations() ? 1 : 0; } <|endoftext|>
<commit_before><commit_msg>grt: avoid pass local nets to fastroute core<commit_after><|endoftext|>
<commit_before><commit_msg>grt: addd check if net have global route<commit_after><|endoftext|>
<commit_before>/** @file TextView unit tests. @section license License 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 <iomanip> #include <iostream> #include <sstream> #include <string> #include "tscpp/util/TextView.h" #include "catch.hpp" using ts::TextView; using namespace std::literals; TEST_CASE("TextView Constructor", "[libts][TextView]") { static std::string base = "Evil Dave Rulez!"; TextView tv(base); TextView b{base.data(), base.size()}; TextView c{std::string_view(base)}; } TEST_CASE("TextView Operations", "[libts][TextView]") { TextView tv{"Evil Dave Rulez"}; TextView tv_lower{"evil dave rulez"}; TextView nothing; size_t off; REQUIRE(tv.find('l') == 3); off = tv.find_if([](char c) { return c == 'D'; }); REQUIRE(off == tv.find('D')); REQUIRE(tv); REQUIRE(!tv == false); if (nothing) { REQUIRE(nullptr == "bad operator bool on TextView"); } REQUIRE(!nothing == true); REQUIRE(nothing.empty() == true); REQUIRE(memcmp(tv, tv) == 0); REQUIRE(memcmp(tv, tv_lower) != 0); REQUIRE(strcmp(tv, tv) == 0); REQUIRE(strcmp(tv, tv_lower) != 0); REQUIRE(strcasecmp(tv, tv) == 0); REQUIRE(strcasecmp(tv, tv_lower) == 0); REQUIRE(strcasecmp(nothing, tv) != 0); } TEST_CASE("TextView Trimming", "[libts][TextView]") { TextView tv(" Evil Dave Rulz ..."); TextView tv2{"More Text1234567890"}; REQUIRE("Evil Dave Rulz ..." == TextView(tv).ltrim_if(&isspace)); REQUIRE(tv2 == TextView{tv2}.ltrim_if(&isspace)); REQUIRE("More Text" == TextView{tv2}.rtrim_if(&isdigit)); REQUIRE(" Evil Dave Rulz " == TextView(tv).rtrim('.')); REQUIRE("Evil Dave Rulz" == TextView(tv).trim(" .")); } TEST_CASE("TextView Find", "[libts][TextView]") { TextView addr{"172.29.145.87:5050"}; REQUIRE(addr.find(':') == 13); REQUIRE(addr.rfind(':') == 13); REQUIRE(addr.find('.') == 3); REQUIRE(addr.rfind('.') == 10); } TEST_CASE("TextView Affixes", "[libts][TextView]") { TextView s; // scratch. TextView tv1("0123456789;01234567890"); TextView prefix{tv1.prefix(10)}; REQUIRE("0123456789" == prefix); REQUIRE("67890" == tv1.suffix(5)); TextView tv2 = tv1.prefix(';'); REQUIRE(tv2 == "0123456789"); TextView right{tv1}; TextView left{right.split_prefix_at(';')}; REQUIRE(right.size() == 11); REQUIRE(left.size() == 10); TextView tv3 = "abcdefg:gfedcba"; left = tv3; right = left.split_suffix_at(";:,"); TextView pre{tv3}, post{pre.split_suffix_at(7)}; REQUIRE(post.size() == 7); REQUIRE(right.size() == 7); REQUIRE(left.size() == 7); REQUIRE(left == "abcdefg"); REQUIRE(right == "gfedcba"); TextView addr1{"[fe80::fc54:ff:fe60:d886]"}; TextView addr2{"[fe80::fc54:ff:fe60:d886]:956"}; TextView addr3{"192.168.1.1:5050"}; TextView t = addr1; ++t; REQUIRE("fe80::fc54:ff:fe60:d886]" == t); TextView a = t.take_prefix_at(']'); REQUIRE("fe80::fc54:ff:fe60:d886" == a); REQUIRE(t.empty()); t = addr2; ++t; a = t.take_prefix_at(']'); REQUIRE("fe80::fc54:ff:fe60:d886" == a); REQUIRE(':' == *t); ++t; REQUIRE("956" == t); t = addr3; TextView sf{t.suffix(':')}; REQUIRE("5050" == sf); REQUIRE(t == addr3); t = addr3; s = t.split_suffix_at(11); REQUIRE("5050" == s); REQUIRE("192.168.1.1" == t); t = addr3; s = t.split_suffix_at(':'); REQUIRE("5050" == s); REQUIRE("192.168.1.1" == t); t = addr3; s = t.split_suffix_at('Q'); REQUIRE(s.empty()); REQUIRE(t == addr3); t = addr3; s = t.take_suffix_at(':'); REQUIRE("5050" == s); REQUIRE("192.168.1.1" == t); t = addr3; s = t.take_suffix_at('Q'); REQUIRE(s == addr3); REQUIRE(t.empty()); auto is_sep{[](char c) { return isspace(c) || ',' == c || ';' == c; }}; TextView token; t = ";; , ;;one;two,th:ree four,, ; ,,f-ive="sv; // Do an unrolled loop. REQUIRE(!t.ltrim_if(is_sep).empty()); REQUIRE(t.take_prefix_if(is_sep) == "one"); REQUIRE(!t.ltrim_if(is_sep).empty()); REQUIRE(t.take_prefix_if(is_sep) == "two"); REQUIRE(!t.ltrim_if(is_sep).empty()); REQUIRE(t.take_prefix_if(is_sep) == "th:ree"); REQUIRE(!t.ltrim_if(is_sep).empty()); REQUIRE(t.take_prefix_if(is_sep) == "four"); REQUIRE(!t.ltrim_if(is_sep).empty()); REQUIRE(t.take_prefix_if(is_sep) == "f-ive="); REQUIRE(t.empty()); // Simulate pulling off FQDN pieces in reverse order from a string_view. // Simulates operations in HostLookup.cc, where the use of string_view // necessitates this workaround of failures in the string_view API. With a // TextView, it would just be repeated @c take_suffix_at('.') std::string_view fqdn{"bob.ne1.corp.ngeo.com"}; TextView elt{TextView{fqdn}.suffix('.')}; REQUIRE(elt == "com"); // Unroll loop for testing. fqdn.remove_suffix(std::min(fqdn.size(), elt.size() + 1)); elt = TextView{fqdn}.suffix('.'); REQUIRE(elt == "ngeo"); fqdn.remove_suffix(std::min(fqdn.size(), elt.size() + 1)); elt = TextView{fqdn}.suffix('.'); REQUIRE(elt == "corp"); fqdn.remove_suffix(std::min(fqdn.size(), elt.size() + 1)); elt = TextView{fqdn}.suffix('.'); REQUIRE(elt == "ne1"); fqdn.remove_suffix(std::min(fqdn.size(), elt.size() + 1)); elt = TextView{fqdn}.suffix('.'); REQUIRE(elt == "bob"); fqdn.remove_suffix(std::min(fqdn.size(), elt.size() + 1)); elt = TextView{fqdn}.suffix('.'); REQUIRE(elt.empty()); // Check some edge cases. fqdn = "."sv; token = TextView{fqdn}.take_suffix_at('.'); REQUIRE(token.size() == 0); REQUIRE(token.empty()); s = "."sv; REQUIRE(s.size() == 1); REQUIRE(s.rtrim('.').empty()); token = s.take_suffix_at('.'); REQUIRE(token.size() == 0); REQUIRE(token.empty()); s = "."sv; REQUIRE(s.size() == 1); REQUIRE(s.ltrim('.').empty()); token = s.take_prefix_at('.'); REQUIRE(token.size() == 0); REQUIRE(token.empty()); auto is_not_alnum = [](char c) { return !isalnum(c); }; s = "file.cc"; REQUIRE(s.suffix('.') == "cc"); REQUIRE(s.suffix_if(is_not_alnum) == "cc"); REQUIRE(s.prefix('.') == "file"); REQUIRE(s.prefix_if(is_not_alnum) == "file"); s.remove_suffix_at('.'); REQUIRE(s == "file"); s = "file.cc.org.123"; REQUIRE(s.suffix('.') == "123"); REQUIRE(s.prefix('.') == "file"); s.remove_suffix_if(is_not_alnum); REQUIRE(s == "file.cc.org"); s.remove_suffix_at('.'); REQUIRE(s == "file.cc"); s.remove_prefix_at('.'); REQUIRE(s == "cc"); s = "file.cc.org.123"; s.remove_prefix_if(is_not_alnum); REQUIRE(s == "cc.org.123"); s.remove_suffix_at('!'); REQUIRE(s.empty()); s = "file.cc.org"; s.remove_prefix('!'); REQUIRE(s.empty()); // From MIMEHdr::get_host_port_values auto f_host = [](TextView b, TextView &host, TextView &port) -> void { if ('[' == *b) { auto idx = b.find(']'); if (idx <= b.size() && b[idx + 1] == ':') { host = b.take_prefix_at(idx + 1); port = b; } else { host = b; } } else { auto x = b.split_prefix_at(':'); if (x) { host = x; port = b; } else { host = b; } } }; TextView host, port; s = "host"; f_host(s, host, port); REQUIRE(host == "host"); REQUIRE(port.empty()); s = "host:"; f_host(s, host, port); REQUIRE(host == "host"); REQUIRE(port.empty()); s = "[host]"; f_host(s, host, port); REQUIRE(host == "[host]"); REQUIRE(port.empty()); s = "host:port"; f_host(s, host, port); REQUIRE(host == "host"); REQUIRE(port == "port"); s = "[host]:port"; f_host(s, host, port); REQUIRE(host == "[host]"); REQUIRE(port == "port"); s = "[host]:"; f_host(s, host, port); REQUIRE(host == "[host]"); REQUIRE(port.empty()); }; TEST_CASE("TextView Formatting", "[libts][TextView]") { TextView a("01234567"); { std::ostringstream buff; buff << '|' << a << '|'; REQUIRE(buff.str() == "|01234567|"); } { std::ostringstream buff; buff << '|' << std::setw(5) << a << '|'; REQUIRE(buff.str() == "|01234567|"); } { std::ostringstream buff; buff << '|' << std::setw(12) << a << '|'; REQUIRE(buff.str() == "| 01234567|"); } { std::ostringstream buff; buff << '|' << std::setw(12) << std::right << a << '|'; REQUIRE(buff.str() == "| 01234567|"); } { std::ostringstream buff; buff << '|' << std::setw(12) << std::left << a << '|'; REQUIRE(buff.str() == "|01234567 |"); } { std::ostringstream buff; buff << '|' << std::setw(12) << std::right << std::setfill('_') << a << '|'; REQUIRE(buff.str() == "|____01234567|"); } { std::ostringstream buff; buff << '|' << std::setw(12) << std::left << std::setfill('_') << a << '|'; REQUIRE(buff.str() == "|01234567____|"); } } TEST_CASE("TextView Conversions", "[libts][TextView]") { TextView n = " 956783"; TextView n2 = n; TextView n3 = "031"; TextView n4 = "13f8q"; TextView n5 = "0x13f8"; TextView n6 = "0X13f8"; TextView x; n2.ltrim_if(&isspace); REQUIRE(956783 == svtoi(n)); REQUIRE(956783 == svtoi(n2)); REQUIRE(0x13f8 == svtoi(n4, &x, 16)); REQUIRE(x == "13f8"); REQUIRE(0x13f8 == svtoi(n5)); REQUIRE(0x13f8 == svtoi(n6)); REQUIRE(25 == svtoi(n3)); REQUIRE(31 == svtoi(n3, nullptr, 10)); } <commit_msg>TextView: Add additional constructor tests. (#7189)<commit_after>/** @file TextView unit tests. @section license License 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 <iomanip> #include <iostream> #include <sstream> #include <string> #include "tscpp/util/TextView.h" #include "catch.hpp" using ts::TextView; using namespace std::literals; TEST_CASE("TextView Constructor", "[libts][TextView]") { static const char *delain = "Best Band"; static std::string base = "Evil Dave Rulez!"; TextView tv(base); TextView alpha{delain, TextView::npos}; TextView bravo{delain, 9}; TextView b{base.data(), base.size()}; TextView c{std::string_view(base)}; tv.assign(base); REQUIRE(0 == strcmp(tv, base)); REQUIRE(0 == strcmp(b, c)); REQUIRE(0 == strcmp(tv, b)); REQUIRE(strlen(delain) == alpha.size()); REQUIRE(0 == strcmp(alpha, bravo)); static const char *null = nullptr; TextView null1{nullptr}; TextView null2{null, 0}; TextView null3{null, TextView::npos}; REQUIRE(null1.empty() == true); REQUIRE(null2.empty() == true); REQUIRE(null3.empty() == true); } TEST_CASE("TextView Operations", "[libts][TextView]") { TextView tv{"Evil Dave Rulez"}; TextView tv_lower{"evil dave rulez"}; TextView nothing; size_t off; REQUIRE(tv.find('l') == 3); off = tv.find_if([](char c) { return c == 'D'; }); REQUIRE(off == tv.find('D')); REQUIRE(tv); REQUIRE(!tv == false); if (nothing) { REQUIRE(nullptr == "bad operator bool on TextView"); } REQUIRE(!nothing == true); REQUIRE(nothing.empty() == true); REQUIRE(memcmp(tv, tv) == 0); REQUIRE(memcmp(tv, tv_lower) != 0); REQUIRE(strcmp(tv, tv) == 0); REQUIRE(strcmp(tv, tv_lower) != 0); REQUIRE(strcasecmp(tv, tv) == 0); REQUIRE(strcasecmp(tv, tv_lower) == 0); REQUIRE(strcasecmp(nothing, tv) != 0); } TEST_CASE("TextView Trimming", "[libts][TextView]") { TextView tv(" Evil Dave Rulz ..."); TextView tv2{"More Text1234567890"}; REQUIRE("Evil Dave Rulz ..." == TextView(tv).ltrim_if(&isspace)); REQUIRE(tv2 == TextView{tv2}.ltrim_if(&isspace)); REQUIRE("More Text" == TextView{tv2}.rtrim_if(&isdigit)); REQUIRE(" Evil Dave Rulz " == TextView(tv).rtrim('.')); REQUIRE("Evil Dave Rulz" == TextView(tv).trim(" .")); } TEST_CASE("TextView Find", "[libts][TextView]") { TextView addr{"172.29.145.87:5050"}; REQUIRE(addr.find(':') == 13); REQUIRE(addr.rfind(':') == 13); REQUIRE(addr.find('.') == 3); REQUIRE(addr.rfind('.') == 10); } TEST_CASE("TextView Affixes", "[libts][TextView]") { TextView s; // scratch. TextView tv1("0123456789;01234567890"); TextView prefix{tv1.prefix(10)}; REQUIRE("0123456789" == prefix); REQUIRE("67890" == tv1.suffix(5)); TextView tv2 = tv1.prefix(';'); REQUIRE(tv2 == "0123456789"); TextView right{tv1}; TextView left{right.split_prefix_at(';')}; REQUIRE(right.size() == 11); REQUIRE(left.size() == 10); TextView tv3 = "abcdefg:gfedcba"; left = tv3; right = left.split_suffix_at(";:,"); TextView pre{tv3}, post{pre.split_suffix_at(7)}; REQUIRE(post.size() == 7); REQUIRE(right.size() == 7); REQUIRE(left.size() == 7); REQUIRE(left == "abcdefg"); REQUIRE(right == "gfedcba"); TextView addr1{"[fe80::fc54:ff:fe60:d886]"}; TextView addr2{"[fe80::fc54:ff:fe60:d886]:956"}; TextView addr3{"192.168.1.1:5050"}; TextView t = addr1; ++t; REQUIRE("fe80::fc54:ff:fe60:d886]" == t); TextView a = t.take_prefix_at(']'); REQUIRE("fe80::fc54:ff:fe60:d886" == a); REQUIRE(t.empty()); t = addr2; ++t; a = t.take_prefix_at(']'); REQUIRE("fe80::fc54:ff:fe60:d886" == a); REQUIRE(':' == *t); ++t; REQUIRE("956" == t); t = addr3; TextView sf{t.suffix(':')}; REQUIRE("5050" == sf); REQUIRE(t == addr3); t = addr3; s = t.split_suffix_at(11); REQUIRE("5050" == s); REQUIRE("192.168.1.1" == t); t = addr3; s = t.split_suffix_at(':'); REQUIRE("5050" == s); REQUIRE("192.168.1.1" == t); t = addr3; s = t.split_suffix_at('Q'); REQUIRE(s.empty()); REQUIRE(t == addr3); t = addr3; s = t.take_suffix_at(':'); REQUIRE("5050" == s); REQUIRE("192.168.1.1" == t); t = addr3; s = t.take_suffix_at('Q'); REQUIRE(s == addr3); REQUIRE(t.empty()); auto is_sep{[](char c) { return isspace(c) || ',' == c || ';' == c; }}; TextView token; t = ";; , ;;one;two,th:ree four,, ; ,,f-ive="sv; // Do an unrolled loop. REQUIRE(!t.ltrim_if(is_sep).empty()); REQUIRE(t.take_prefix_if(is_sep) == "one"); REQUIRE(!t.ltrim_if(is_sep).empty()); REQUIRE(t.take_prefix_if(is_sep) == "two"); REQUIRE(!t.ltrim_if(is_sep).empty()); REQUIRE(t.take_prefix_if(is_sep) == "th:ree"); REQUIRE(!t.ltrim_if(is_sep).empty()); REQUIRE(t.take_prefix_if(is_sep) == "four"); REQUIRE(!t.ltrim_if(is_sep).empty()); REQUIRE(t.take_prefix_if(is_sep) == "f-ive="); REQUIRE(t.empty()); // Simulate pulling off FQDN pieces in reverse order from a string_view. // Simulates operations in HostLookup.cc, where the use of string_view // necessitates this workaround of failures in the string_view API. With a // TextView, it would just be repeated @c take_suffix_at('.') std::string_view fqdn{"bob.ne1.corp.ngeo.com"}; TextView elt{TextView{fqdn}.suffix('.')}; REQUIRE(elt == "com"); // Unroll loop for testing. fqdn.remove_suffix(std::min(fqdn.size(), elt.size() + 1)); elt = TextView{fqdn}.suffix('.'); REQUIRE(elt == "ngeo"); fqdn.remove_suffix(std::min(fqdn.size(), elt.size() + 1)); elt = TextView{fqdn}.suffix('.'); REQUIRE(elt == "corp"); fqdn.remove_suffix(std::min(fqdn.size(), elt.size() + 1)); elt = TextView{fqdn}.suffix('.'); REQUIRE(elt == "ne1"); fqdn.remove_suffix(std::min(fqdn.size(), elt.size() + 1)); elt = TextView{fqdn}.suffix('.'); REQUIRE(elt == "bob"); fqdn.remove_suffix(std::min(fqdn.size(), elt.size() + 1)); elt = TextView{fqdn}.suffix('.'); REQUIRE(elt.empty()); // Check some edge cases. fqdn = "."sv; token = TextView{fqdn}.take_suffix_at('.'); REQUIRE(token.size() == 0); REQUIRE(token.empty()); s = "."sv; REQUIRE(s.size() == 1); REQUIRE(s.rtrim('.').empty()); token = s.take_suffix_at('.'); REQUIRE(token.size() == 0); REQUIRE(token.empty()); s = "."sv; REQUIRE(s.size() == 1); REQUIRE(s.ltrim('.').empty()); token = s.take_prefix_at('.'); REQUIRE(token.size() == 0); REQUIRE(token.empty()); auto is_not_alnum = [](char c) { return !isalnum(c); }; s = "file.cc"; REQUIRE(s.suffix('.') == "cc"); REQUIRE(s.suffix_if(is_not_alnum) == "cc"); REQUIRE(s.prefix('.') == "file"); REQUIRE(s.prefix_if(is_not_alnum) == "file"); s.remove_suffix_at('.'); REQUIRE(s == "file"); s = "file.cc.org.123"; REQUIRE(s.suffix('.') == "123"); REQUIRE(s.prefix('.') == "file"); s.remove_suffix_if(is_not_alnum); REQUIRE(s == "file.cc.org"); s.remove_suffix_at('.'); REQUIRE(s == "file.cc"); s.remove_prefix_at('.'); REQUIRE(s == "cc"); s = "file.cc.org.123"; s.remove_prefix_if(is_not_alnum); REQUIRE(s == "cc.org.123"); s.remove_suffix_at('!'); REQUIRE(s.empty()); s = "file.cc.org"; s.remove_prefix('!'); REQUIRE(s.empty()); // From MIMEHdr::get_host_port_values auto f_host = [](TextView b, TextView &host, TextView &port) -> void { if ('[' == *b) { auto idx = b.find(']'); if (idx <= b.size() && b[idx + 1] == ':') { host = b.take_prefix_at(idx + 1); port = b; } else { host = b; } } else { auto x = b.split_prefix_at(':'); if (x) { host = x; port = b; } else { host = b; } } }; TextView host, port; s = "host"; f_host(s, host, port); REQUIRE(host == "host"); REQUIRE(port.empty()); s = "host:"; f_host(s, host, port); REQUIRE(host == "host"); REQUIRE(port.empty()); s = "[host]"; f_host(s, host, port); REQUIRE(host == "[host]"); REQUIRE(port.empty()); s = "host:port"; f_host(s, host, port); REQUIRE(host == "host"); REQUIRE(port == "port"); s = "[host]:port"; f_host(s, host, port); REQUIRE(host == "[host]"); REQUIRE(port == "port"); s = "[host]:"; f_host(s, host, port); REQUIRE(host == "[host]"); REQUIRE(port.empty()); }; TEST_CASE("TextView Formatting", "[libts][TextView]") { TextView a("01234567"); { std::ostringstream buff; buff << '|' << a << '|'; REQUIRE(buff.str() == "|01234567|"); } { std::ostringstream buff; buff << '|' << std::setw(5) << a << '|'; REQUIRE(buff.str() == "|01234567|"); } { std::ostringstream buff; buff << '|' << std::setw(12) << a << '|'; REQUIRE(buff.str() == "| 01234567|"); } { std::ostringstream buff; buff << '|' << std::setw(12) << std::right << a << '|'; REQUIRE(buff.str() == "| 01234567|"); } { std::ostringstream buff; buff << '|' << std::setw(12) << std::left << a << '|'; REQUIRE(buff.str() == "|01234567 |"); } { std::ostringstream buff; buff << '|' << std::setw(12) << std::right << std::setfill('_') << a << '|'; REQUIRE(buff.str() == "|____01234567|"); } { std::ostringstream buff; buff << '|' << std::setw(12) << std::left << std::setfill('_') << a << '|'; REQUIRE(buff.str() == "|01234567____|"); } } TEST_CASE("TextView Conversions", "[libts][TextView]") { TextView n = " 956783"; TextView n2 = n; TextView n3 = "031"; TextView n4 = "13f8q"; TextView n5 = "0x13f8"; TextView n6 = "0X13f8"; TextView x; n2.ltrim_if(&isspace); REQUIRE(956783 == svtoi(n)); REQUIRE(956783 == svtoi(n2)); REQUIRE(0x13f8 == svtoi(n4, &x, 16)); REQUIRE(x == "13f8"); REQUIRE(0x13f8 == svtoi(n5)); REQUIRE(0x13f8 == svtoi(n6)); REQUIRE(25 == svtoi(n3)); REQUIRE(31 == svtoi(n3, nullptr, 10)); } <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <vector> #include <sndfile.hh> #define kiss_fft_scalar float #include "kiss_fft.h" int main(int argc, char *argv[]) { const int I = 2; const int D = 1; const int N = 256; const int M = I*N/D; const int L = N/8; kiss_fft_cfg fwd = kiss_fft_alloc(N, 0, NULL, NULL); kiss_fft_cfg inv = kiss_fft_alloc(M, 1, NULL, NULL); if (argc != 2) return -1; const std::string infilename = argv[argc-1]; const std::string outfilename = "orig.wav"; const std::string resfilename = "res.wav"; SndfileHandle infile(infilename); SndfileHandle outfile(outfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate()); SndfileHandle resfile(resfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate() * I/D); std::vector<kiss_fft_scalar> buffer(N); std::vector<kiss_fft_cpx> fwd_fft_in_buffer(N); std::vector<kiss_fft_cpx> fwd_fft_out_buffer(N); std::vector<kiss_fft_cpx> bwd_fft_in_buffer(M); std::vector<kiss_fft_cpx> bwd_fft_out_buffer(M); /* prepend 2L zeros */ for (int i=0; i < 2*L; ++i) { buffer[i] = 0; } while (sf_count_t readcount = infile.read(buffer.data() + 2*L, N - 2*L)) { /* Store original samples */ outfile.write(buffer.data() + 2*L, std::min(static_cast<int>(readcount), N - 2*L)); /* Create FFT input buffer: 1 block of N samples with 2*L overlap */ for(int i=0; i < std::min(static_cast<int>(readcount) + 2*L, N); ++i) { fwd_fft_in_buffer[i].r = buffer[i]; fwd_fft_in_buffer[i].i = 0.0; std::cout << i << ": (" << fwd_fft_in_buffer[i].r << "," << fwd_fft_in_buffer[i].i << ")\n"; } std::cout << "\n"; /* Forward N points FFT */ kiss_fft(fwd, fwd_fft_in_buffer.data(), fwd_fft_out_buffer.data()); for(int i=0; i < N; ++i) { std::cout << " FFT: " << i << " (" << fwd_fft_out_buffer[i].r << "," << fwd_fft_out_buffer[i].i << ")\n"; } /* Create IFFT input buffer */ for(int i=0; i < N/2; ++i) { bwd_fft_in_buffer[i].r = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i].r; bwd_fft_in_buffer[i].i = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i].i; } for(int i=N/2; i <= M - N/2; ++i) { bwd_fft_in_buffer[i].r = static_cast<kiss_fft_scalar>(I/D) * 0.0; bwd_fft_in_buffer[i].i = static_cast<kiss_fft_scalar>(I/D) * 0.0; } for(int i=M - N/2 + 1; i < M; ++i) { bwd_fft_in_buffer[i].r = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i + M/2].r; bwd_fft_in_buffer[i].i = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i + M/2].i; } /* Backward M points IFFT */ kiss_fft(inv, bwd_fft_in_buffer.data(), bwd_fft_out_buffer.data()); for(int i=0; i < M; ++i) { std::cout << "IFFT: " << i << " (" << bwd_fft_out_buffer[i].r << "," << bwd_fft_out_buffer[i].i << ")\n"; } /* Discard first and last I/D*L points and store the rest of the real vector */ std::vector<double> res(M - 2*I/D*L); int j = I/D*L; for(int i=0; i < M - 2*I/D*L; ++i) { res[i] = bwd_fft_out_buffer[j++].r; } resfile.write(res.data(), res.size()); /* Shift vector to the left 2*L times */ std::rotate(buffer.begin(), buffer.begin() + N - 2*L, buffer.end()); }; kiss_fft_free(fwd); kiss_fft_free(inv); return 0; } <commit_msg>Use RAII and fix loop indices.<commit_after>#include <iostream> #include <vector> #include <memory> #include <algorithm> #include <sndfile.hh> #define kiss_fft_scalar float #include "kiss_fft.h" int main(int argc, char *argv[]) { const int I = 2; const int D = 1; const int N = 256; const int M = I/D*N; if (argc != 2) { std::cerr << "Usage upsampling_algorithm_short_sequence <filename>\n"; return -1; } const std::string infilename = argv[argc-1]; const std::string resfilename = "res.wav"; SndfileHandle infile(infilename); SndfileHandle resfile(resfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate() * I/D); // Input data std::vector<kiss_fft_scalar> buffer(N); if (infile.read(buffer.data(), N) != N) { std::cerr << "Error reading " << N << " samples from " << infilename << ".\n"; } // Kiss FFT configurations auto fwd_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> { kiss_fft_alloc(N, 0, NULL, NULL), kiss_fft_free }; auto inv_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> { kiss_fft_alloc(M, 1, NULL, NULL), kiss_fft_free }; if (fwd_cfg == nullptr || inv_cfg == nullptr) { std::cerr << "Error allocating Kiss FFT configurations\n"; } // FFT input/output buffers std::vector<kiss_fft_cpx> fwd_fft_in_buffer(N); std::vector<kiss_fft_cpx> fwd_fft_out_buffer(N); // IFFT input/output buffers std::vector<kiss_fft_cpx> bwd_fft_in_buffer(M); std::vector<kiss_fft_cpx> bwd_fft_out_buffer(M); // Create FFT input buffer for (int i=0; i < N; ++i) { fwd_fft_in_buffer[i].r = buffer[i]; fwd_fft_in_buffer[i].i = 0.0; std::cout << i << ": (" << fwd_fft_in_buffer[i].r << "," << fwd_fft_in_buffer[i].i << ")\n"; } std::cout << "\n"; // Forward N points FFT kiss_fft(fwd_cfg.get(), fwd_fft_in_buffer.data(), fwd_fft_out_buffer.data()); for (int i=0; i < N; ++i) { std::cout << " FFT: " << i << " (" << fwd_fft_out_buffer[i].r << "," << fwd_fft_out_buffer[i].i << ")\n"; } // Create IFFT input buffer for (int i=0; i < N/2; ++i) { bwd_fft_in_buffer[i].r = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i].r; bwd_fft_in_buffer[i].i = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i].i; } for (int i=N/2; i < M - N/2; ++i) { bwd_fft_in_buffer[i].r = static_cast<kiss_fft_scalar>(I/D) * 0.0; bwd_fft_in_buffer[i].i = static_cast<kiss_fft_scalar>(I/D) * 0.0; } for (int i=M - N/2; i < M; ++i) { bwd_fft_in_buffer[i].r = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i - N].r; bwd_fft_in_buffer[i].i = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i - N].i; } for (int i=0; i < M; ++i) { std::cout << i << ": (" << bwd_fft_in_buffer[i].r << "," << bwd_fft_in_buffer[i].i << ")\n"; } // Backward M points IFFT kiss_fft(inv_cfg.get(), bwd_fft_in_buffer.data(), bwd_fft_out_buffer.data()); for(int i=0; i < M; ++i) { std::cout << "IFFT: " << i << " (" << bwd_fft_out_buffer[i].r << "," << bwd_fft_out_buffer[i].i << ")\n"; } return 0; } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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. #ifndef SERVER_ROUTE_HPP #define SERVER_ROUTE_HPP #include <regex> #include <string> #include <delegate> #include "request.hpp" #include "response.hpp" #include "../route/path_to_regex.hpp" namespace server { using End_point = delegate<void(Request_ptr, Response_ptr)>; using Route_expr = std::regex; struct Route { Route(const std::string& ex, End_point e) : path{ex} , end_point{e} { expr = route::Path_to_regex::path_to_regex(path, keys); } std::string path; Route_expr expr; End_point end_point; route::Keys keys; }; //< struct Route } //< namespace server #endif //< SERVER_ROUTE_HPP <commit_msg>route: Add attribute to bring most viewed route to front of queue<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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. #ifndef SERVER_ROUTE_HPP #define SERVER_ROUTE_HPP #include <regex> #include <string> #include <delegate> #include "request.hpp" #include "response.hpp" #include "../route/path_to_regex.hpp" namespace server { using End_point = delegate<void(Request_ptr, Response_ptr)>; using Route_expr = std::regex; struct Route { Route(const std::string& ex, End_point e) : path{ex} , end_point{e} { expr = route::Path_to_regex::path_to_regex(path, keys); } std::string path; Route_expr expr; End_point end_point; route::Keys keys; unsigned hits; }; //< struct Route inline bool operator < (const Route& lhs, const Route& rhs) noexcept { return lhs.hits < rhs.hits; } } //< namespace server #endif //< SERVER_ROUTE_HPP <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/ui/ui_test.h" #include "base/command_line.h" #include "base/file_util.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/automation_proxy.h" #include "net/base/net_util.h" typedef UITest ChromeMainTest; #if !defined(OS_MACOSX) #if defined(USE_AURA) // http://crbug.com/104650 #define MAYBE_SecondLaunch FAILS_SecondLaunch #define MAYBE_ReuseBrowserInstanceWhenOpeningFile \ FAILS_ReuseBrowserInstanceWhenOpeningFile #define MAYBE_SecondLaunchWithIncognitoUrl FAILS_SecondLaunchWithIncognitoUrl #define MAYBE_SecondLaunchFromIncognitoWithNormalUrl \ FAILS_SecondLaunchFromIncognitoWithNormalUrl #else #define MAYBE_SecondLaunch SecondLaunch #define MAYBE_ReuseBrowserInstanceWhenOpeningFile \ ReuseBrowserInstanceWhenOpeningFile #define MAYBE_SecondLaunchWithIncognitoUrl SecondLaunchWithIncognitoUrl #define MAYBE_SecondLaunchFromIncognitoWithNormalUrl \ SecondLaunchFromIncognitoWithNormalUrl #endif // These tests don't apply to the Mac version; see // LaunchAnotherBrowserBlockUntilClosed for details. // Make sure that the second invocation creates a new window. TEST_F(ChromeMainTest, MAYBE_SecondLaunch) { include_testing_id_ = false; ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed( CommandLine(CommandLine::NO_PROGRAM))); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2)); } TEST_F(ChromeMainTest, MAYBE_ReuseBrowserInstanceWhenOpeningFile) { include_testing_id_ = false; FilePath test_file = test_data_directory_.AppendASCII("empty.html"); CommandLine command_line(CommandLine::NO_PROGRAM); command_line.AppendArgPath(test_file); ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed(command_line)); ASSERT_TRUE(automation()->IsURLDisplayed(net::FilePathToFileURL(test_file))); } TEST_F(ChromeMainTest, MAYBE_SecondLaunchWithIncognitoUrl) { include_testing_id_ = false; int num_normal_windows; // We should start with one normal window. ASSERT_TRUE(automation()->GetNormalBrowserWindowCount(&num_normal_windows)); ASSERT_EQ(1, num_normal_windows); // Run with --incognito switch and an URL specified. FilePath test_file = test_data_directory_.AppendASCII("empty.html"); CommandLine command_line(CommandLine::NO_PROGRAM); command_line.AppendSwitch(switches::kIncognito); command_line.AppendArgPath(test_file); ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed(command_line)); // There should be one normal and one incognito window now. ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2)); ASSERT_TRUE(automation()->GetNormalBrowserWindowCount(&num_normal_windows)); ASSERT_EQ(1, num_normal_windows); } TEST_F(ChromeMainTest, MAYBE_SecondLaunchFromIncognitoWithNormalUrl) { include_testing_id_ = false; int num_normal_windows; // We should start with one normal window. ASSERT_TRUE(automation()->GetNormalBrowserWindowCount(&num_normal_windows)); ASSERT_EQ(1, num_normal_windows); scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); // Create an incognito window. ASSERT_TRUE(browser_proxy->RunCommand(IDC_NEW_INCOGNITO_WINDOW)); int window_count; ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); ASSERT_EQ(2, window_count); ASSERT_TRUE(automation()->GetNormalBrowserWindowCount(&num_normal_windows)); ASSERT_EQ(1, num_normal_windows); // Close the first window. ASSERT_TRUE(browser_proxy->RunCommand(IDC_CLOSE_WINDOW)); browser_proxy = NULL; // There should only be the incognito window open now. ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); ASSERT_EQ(1, window_count); ASSERT_TRUE(automation()->GetNormalBrowserWindowCount(&num_normal_windows)); ASSERT_EQ(0, num_normal_windows); // Run with just an URL specified, no --incognito switch. FilePath test_file = test_data_directory_.AppendASCII("empty.html"); CommandLine command_line(CommandLine::NO_PROGRAM); command_line.AppendArgPath(test_file); ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed(command_line)); // There should be one normal and one incognito window now. ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2)); ASSERT_TRUE(automation()->GetNormalBrowserWindowCount(&num_normal_windows)); ASSERT_EQ(1, num_normal_windows); } #endif // !OS_MACOSX <commit_msg>Remove FAILS for Aura ChromeMainTest builds<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/ui/ui_test.h" #include "base/command_line.h" #include "base/file_util.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/automation_proxy.h" #include "net/base/net_util.h" typedef UITest ChromeMainTest; #if !defined(OS_MACOSX) // These tests don't apply to the Mac version; see // LaunchAnotherBrowserBlockUntilClosed for details. // Make sure that the second invocation creates a new window. TEST_F(ChromeMainTest, SecondLaunch) { include_testing_id_ = false; ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed( CommandLine(CommandLine::NO_PROGRAM))); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2)); } TEST_F(ChromeMainTest, ReuseBrowserInstanceWhenOpeningFile) { include_testing_id_ = false; FilePath test_file = test_data_directory_.AppendASCII("empty.html"); CommandLine command_line(CommandLine::NO_PROGRAM); command_line.AppendArgPath(test_file); ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed(command_line)); ASSERT_TRUE(automation()->IsURLDisplayed(net::FilePathToFileURL(test_file))); } TEST_F(ChromeMainTest, SecondLaunchWithIncognitoUrl) { include_testing_id_ = false; int num_normal_windows; // We should start with one normal window. ASSERT_TRUE(automation()->GetNormalBrowserWindowCount(&num_normal_windows)); ASSERT_EQ(1, num_normal_windows); // Run with --incognito switch and an URL specified. FilePath test_file = test_data_directory_.AppendASCII("empty.html"); CommandLine command_line(CommandLine::NO_PROGRAM); command_line.AppendSwitch(switches::kIncognito); command_line.AppendArgPath(test_file); ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed(command_line)); // There should be one normal and one incognito window now. ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2)); ASSERT_TRUE(automation()->GetNormalBrowserWindowCount(&num_normal_windows)); ASSERT_EQ(1, num_normal_windows); } TEST_F(ChromeMainTest, SecondLaunchFromIncognitoWithNormalUrl) { include_testing_id_ = false; int num_normal_windows; // We should start with one normal window. ASSERT_TRUE(automation()->GetNormalBrowserWindowCount(&num_normal_windows)); ASSERT_EQ(1, num_normal_windows); scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser_proxy.get()); // Create an incognito window. ASSERT_TRUE(browser_proxy->RunCommand(IDC_NEW_INCOGNITO_WINDOW)); int window_count; ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); ASSERT_EQ(2, window_count); ASSERT_TRUE(automation()->GetNormalBrowserWindowCount(&num_normal_windows)); ASSERT_EQ(1, num_normal_windows); // Close the first window. ASSERT_TRUE(browser_proxy->RunCommand(IDC_CLOSE_WINDOW)); browser_proxy = NULL; // There should only be the incognito window open now. ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); ASSERT_EQ(1, window_count); ASSERT_TRUE(automation()->GetNormalBrowserWindowCount(&num_normal_windows)); ASSERT_EQ(0, num_normal_windows); // Run with just an URL specified, no --incognito switch. FilePath test_file = test_data_directory_.AppendASCII("empty.html"); CommandLine command_line(CommandLine::NO_PROGRAM); command_line.AppendArgPath(test_file); ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed(command_line)); // There should be one normal and one incognito window now. ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2)); ASSERT_TRUE(automation()->GetNormalBrowserWindowCount(&num_normal_windows)); ASSERT_EQ(1, num_normal_windows); } #endif // !OS_MACOSX <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/net/preconnect.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "chrome/browser/profiles/profile.h" #include "content/browser/browser_thread.h" #include "net/base/net_log.h" #include "net/base/ssl_config_service.h" #include "net/http/http_network_session.h" #include "net/http/http_request_info.h" #include "net/http/http_stream_factory.h" #include "net/http/http_transaction_factory.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" namespace chrome_browser_net { void PreconnectOnUIThread( const GURL& url, UrlInfo::ResolutionMotivation motivation, int count) { // Prewarm connection to Search URL. BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableFunction(PreconnectOnIOThread, url, motivation, count)); return; } void PreconnectOnIOThread( const GURL& url, UrlInfo::ResolutionMotivation motivation, int count) { net::URLRequestContextGetter* getter = Profile::GetDefaultRequestContext(); if (!getter) return; if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { LOG(DFATAL) << "This must be run only on the IO thread."; return; } // We are now commited to doing the async preconnection call. UMA_HISTOGRAM_ENUMERATION("Net.PreconnectMotivation", motivation, UrlInfo::MAX_MOTIVATED); net::URLRequestContext* context = getter->GetURLRequestContext(); net::HttpTransactionFactory* factory = context->http_transaction_factory(); net::HttpNetworkSession* session = factory->GetSession(); net::HttpRequestInfo request_info; request_info.url = url; request_info.method = "GET"; // It almost doesn't matter whether we use net::LOWEST or net::HIGHEST // priority here, as we won't make a request, and will surrender the created // socket to the pool as soon as we can. However, we would like to mark the // speculative socket as such, and IF we use a net::LOWEST priority, and if // a navigation asked for a socket (after us) then it would get our socket, // and we'd get its later-arriving socket, which might make us record that // the speculation didn't help :-/. By using net::HIGHEST, we ensure that // a socket is given to us if "we asked first" and this allows us to mark it // as speculative, and better detect stats (if it gets used). // TODO(jar): histogram to see how often we accidentally use a previously- // unused socket, when a previously used socket was available. request_info.priority = net::HIGHEST; // Translate the motivation from UrlRequest motivations to HttpRequest // motivations. switch (motivation) { case UrlInfo::OMNIBOX_MOTIVATED: request_info.motivation = net::HttpRequestInfo::OMNIBOX_MOTIVATED; break; case UrlInfo::LEARNED_REFERAL_MOTIVATED: request_info.motivation = net::HttpRequestInfo::PRECONNECT_MOTIVATED; break; case UrlInfo::SELF_REFERAL_MOTIVATED: case UrlInfo::EARLY_LOAD_MOTIVATED: request_info.motivation = net::HttpRequestInfo::EARLY_LOAD_MOTIVATED; break; default: // Other motivations should never happen here. NOTREACHED(); break; } // Setup the SSL Configuration. net::SSLConfig ssl_config; session->ssl_config_service()->GetSSLConfig(&ssl_config); if (session->http_stream_factory()->next_protos()) ssl_config.next_protos = *session->http_stream_factory()->next_protos(); // All preconnects should perform EV certificate verification. ssl_config.verify_ev_cert = true; net::HttpStreamFactory* http_stream_factory = session->http_stream_factory(); http_stream_factory->PreconnectStreams( count, request_info, ssl_config, net::BoundNetLog()); } } // namespace chrome_browser_net <commit_msg>Ensure User-agent is present in preconnection request<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/net/preconnect.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "chrome/browser/profiles/profile.h" #include "content/browser/browser_thread.h" #include "net/base/net_log.h" #include "net/base/ssl_config_service.h" #include "net/http/http_network_session.h" #include "net/http/http_request_info.h" #include "net/http/http_stream_factory.h" #include "net/http/http_transaction_factory.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" namespace chrome_browser_net { void PreconnectOnUIThread( const GURL& url, UrlInfo::ResolutionMotivation motivation, int count) { // Prewarm connection to Search URL. BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableFunction(PreconnectOnIOThread, url, motivation, count)); return; } void PreconnectOnIOThread( const GURL& url, UrlInfo::ResolutionMotivation motivation, int count) { net::URLRequestContextGetter* getter = Profile::GetDefaultRequestContext(); if (!getter) return; if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { LOG(DFATAL) << "This must be run only on the IO thread."; return; } // We are now commited to doing the async preconnection call. UMA_HISTOGRAM_ENUMERATION("Net.PreconnectMotivation", motivation, UrlInfo::MAX_MOTIVATED); net::URLRequestContext* context = getter->GetURLRequestContext(); net::HttpTransactionFactory* factory = context->http_transaction_factory(); net::HttpNetworkSession* session = factory->GetSession(); net::HttpRequestInfo request_info; request_info.url = url; request_info.method = "GET"; request_info.extra_headers.SetHeader(net::HttpRequestHeaders::kUserAgent, context->GetUserAgent(url)); // It almost doesn't matter whether we use net::LOWEST or net::HIGHEST // priority here, as we won't make a request, and will surrender the created // socket to the pool as soon as we can. However, we would like to mark the // speculative socket as such, and IF we use a net::LOWEST priority, and if // a navigation asked for a socket (after us) then it would get our socket, // and we'd get its later-arriving socket, which might make us record that // the speculation didn't help :-/. By using net::HIGHEST, we ensure that // a socket is given to us if "we asked first" and this allows us to mark it // as speculative, and better detect stats (if it gets used). // TODO(jar): histogram to see how often we accidentally use a previously- // unused socket, when a previously used socket was available. request_info.priority = net::HIGHEST; // Translate the motivation from UrlRequest motivations to HttpRequest // motivations. switch (motivation) { case UrlInfo::OMNIBOX_MOTIVATED: request_info.motivation = net::HttpRequestInfo::OMNIBOX_MOTIVATED; break; case UrlInfo::LEARNED_REFERAL_MOTIVATED: request_info.motivation = net::HttpRequestInfo::PRECONNECT_MOTIVATED; break; case UrlInfo::SELF_REFERAL_MOTIVATED: case UrlInfo::EARLY_LOAD_MOTIVATED: request_info.motivation = net::HttpRequestInfo::EARLY_LOAD_MOTIVATED; break; default: // Other motivations should never happen here. NOTREACHED(); break; } // Setup the SSL Configuration. net::SSLConfig ssl_config; session->ssl_config_service()->GetSSLConfig(&ssl_config); if (session->http_stream_factory()->next_protos()) ssl_config.next_protos = *session->http_stream_factory()->next_protos(); // All preconnects should perform EV certificate verification. ssl_config.verify_ev_cert = true; net::HttpStreamFactory* http_stream_factory = session->http_stream_factory(); http_stream_factory->PreconnectStreams( count, request_info, ssl_config, net::BoundNetLog()); } } // namespace chrome_browser_net <|endoftext|>
<commit_before>#include "NdefRecord.h" #undef LOG_TAG #define LOG_TAG "nfcd" #include <utils/Log.h> NdefRecord::NdefRecord(uint8_t tnf, std::vector<uint8_t>& type, std::vector<uint8_t>& id, std::vector<uint8_t>& payload) { mTnf = tnf; for(uint32_t i = 0; i < type.size(); i++) mType.push_back(type[i]); for(uint32_t i = 0; i < id.size(); i++) mId.push_back(id[i]); for(uint32_t i = 0; i < payload.size(); i++) mPayload.push_back(payload[i]); } NdefRecord::NdefRecord(uint8_t tnf, uint32_t typeLength, uint8_t* type, uint32_t idLength, uint8_t* id, uint32_t payloadLength, uint8_t* payload) { mTnf = tnf; for (uint32_t i = 0; i < typeLength; i++) mType.push_back((uint8_t)type[i]); for (uint32_t i = 0; i < idLength; i++) mId.push_back((uint8_t)id[i]); for (uint32_t i = 0; i < payloadLength; i++) mPayload.push_back((uint8_t)payload[i]); } NdefRecord::~NdefRecord() { } bool NdefRecord::parse(std::vector<uint8_t>& buf, bool ignoreMbMe, std::vector<NdefRecord>& records) { return NdefRecord::parse(buf, ignoreMbMe, records, 0); } bool NdefRecord::parse(std::vector<uint8_t>& buf, bool ignoreMbMe, std::vector<NdefRecord>& records, int offset) { std::vector<uint8_t> type; std::vector<uint8_t> id; std::vector<uint8_t> payload; bool inChunk = false; std::vector<std::vector<uint8_t> > chunks; uint8_t chunkTnf = -1; bool me = false; uint32_t index = offset; while(!me) { uint8_t flag = buf[index++]; bool mb = (flag & NdefRecord::FLAG_MB) != 0; me = (flag & NdefRecord::FLAG_ME) != 0; bool cf = (flag & NdefRecord::FLAG_CF) != 0; bool sr = (flag & NdefRecord::FLAG_SR) != 0; bool il = (flag & NdefRecord::FLAG_IL) != 0; uint8_t tnf = flag & 0x07; if (!mb && records.size() == 0 && !inChunk && !ignoreMbMe) { ALOGE("expected MB flag"); return false; } else if (mb && records.size() != 0 && !ignoreMbMe) { ALOGE("unexpected MB flag"); return false; } else if (inChunk && il) { ALOGE("unexpected IL flag in non-leading chunk"); return false; } else if (cf && me) { ALOGE("unexpected ME flag in non-trailing chunk"); return false ; } else if (inChunk && tnf != NdefRecord::TNF_UNCHANGED) { ALOGE("expected TNF_UNCHANGED in non-leading chunk"); return false ; } else if (!inChunk && tnf == NdefRecord::TNF_UNCHANGED) { ALOGE("unexpected TNF_UNCHANGED in first chunk or unchunked record"); return false; } uint32_t typeLength = buf[index++] & 0xFF; uint32_t payloadLength; if (sr) { payloadLength = buf[index++] & 0xFF; } else { payloadLength = ((uint32_t)buf[index] << 24) | ((uint32_t)buf[index + 1] << 16) | ((uint32_t)buf[index + 2] << 8) | ((uint32_t)buf[index + 3]); index += 4; } uint32_t idLength = il ? (buf[index++] & 0xFF) : 0; if (inChunk && typeLength != 0) { ALOGE("expected zero-length type in non-leading chunk"); return false; } if (!inChunk) { for (uint32_t idx = 0; idx < typeLength; idx++) { type.push_back(buf[index++]); } for (uint32_t idx = 0; idx < idLength; idx++) { id.push_back(buf[index++]); } } if (!ensureSanePayloadSize(payloadLength)) { return false; } for (uint32_t idx = 0; idx < payloadLength; idx++) { payload.push_back(buf[index++]); } if (cf && !inChunk) { // first chunk chunks.clear(); chunkTnf = tnf; } if (cf || inChunk) { // any chunk chunks.push_back(payload); } if (!cf && inChunk) { // last chunk, flatten the payload payloadLength = 0; for (uint32_t idx = 0; idx < chunks.size(); idx++) { payloadLength += chunks[idx].size(); } if (!ensureSanePayloadSize(payloadLength)) { return false; } for(uint32_t i = 0; i < chunks.size(); i++) { for(uint32_t j = 0; j < chunks[i].size(); j++) { payload.push_back(chunks[i][j]); } } tnf = chunkTnf; } if (cf) { // more chunks to come inChunk = true; continue; } else { inChunk = false; } bool isValid = validateTnf(tnf, type, id, payload); if (isValid == false) { return false; } NdefRecord record(tnf, type, id, payload); records.push_back(record); if (ignoreMbMe) { // for parsing a single NdefRecord break; } } return true; } bool NdefRecord::ensureSanePayloadSize(long size) { if (size > NdefRecord::MAX_PAYLOAD_SIZE) { ALOGE("payload above max limit: %d > ", NdefRecord::MAX_PAYLOAD_SIZE); return false; } return true; } bool NdefRecord::validateTnf(uint8_t tnf, std::vector<uint8_t>& type, std::vector<uint8_t>& id, std::vector<uint8_t>& payload) { bool isValid = true; switch (tnf) { case TNF_EMPTY: if (type.size() != 0 || id.size() != 0 || payload.size() != 0) { ALOGE("unexpected data in TNF_EMPTY record"); isValid = false; } break; case TNF_WELL_KNOWN: case TNF_MIME_MEDIA: case TNF_ABSOLUTE_URI: case TNF_EXTERNAL_TYPE: break; case TNF_UNKNOWN: case TNF_RESERVED: if (type.size() != 0) { ALOGE("unexpected type field in TNF_UNKNOWN or TNF_RESERVEd record"); isValid = false; } break; case TNF_UNCHANGED: ALOGE("unexpected TNF_UNCHANGED in first chunk or logical record"); isValid = false; break; default: ALOGE("unexpected tnf value"); isValid = false; break; } return isValid; } void NdefRecord::writeToByteBuffer(std::vector<uint8_t>& buf, bool mb, bool me) { bool sr = mPayload.size() < 256; bool il = mId.size() > 0; uint8_t flags = (uint8_t)((mb ? NdefRecord::FLAG_MB : 0) | (me ? NdefRecord::FLAG_ME : 0) | (sr ? NdefRecord::FLAG_SR : 0) | (il ? NdefRecord::FLAG_IL : 0) | mTnf); buf.push_back(flags); buf.push_back((uint8_t)mType.size()); if (sr) { buf.push_back((uint8_t)mPayload.size()); } else { // TODO : check this buf.push_back((mPayload.size() >> 24) & 0xff); buf.push_back((mPayload.size() >> 16) & 0xff); buf.push_back((mPayload.size() >> 8) & 0xff); buf.push_back(mPayload.size() & 0xff); } if (il) { buf.push_back((uint8_t)mId.size()); } for (uint32_t i = 0; i < mType.size(); i++) buf.push_back(mType[i]); for (uint32_t i = 0; i < mId.size(); i++) buf.push_back(mId[i]); for (uint32_t i = 0; i < mPayload.size(); i++) buf.push_back(mPayload[i]); } <commit_msg>Fix read second NDEF record error<commit_after>#include "NdefRecord.h" #undef LOG_TAG #define LOG_TAG "nfcd" #include <utils/Log.h> NdefRecord::NdefRecord(uint8_t tnf, std::vector<uint8_t>& type, std::vector<uint8_t>& id, std::vector<uint8_t>& payload) { mTnf = tnf; for(uint32_t i = 0; i < type.size(); i++) mType.push_back(type[i]); for(uint32_t i = 0; i < id.size(); i++) mId.push_back(id[i]); for(uint32_t i = 0; i < payload.size(); i++) mPayload.push_back(payload[i]); } NdefRecord::NdefRecord(uint8_t tnf, uint32_t typeLength, uint8_t* type, uint32_t idLength, uint8_t* id, uint32_t payloadLength, uint8_t* payload) { mTnf = tnf; for (uint32_t i = 0; i < typeLength; i++) mType.push_back((uint8_t)type[i]); for (uint32_t i = 0; i < idLength; i++) mId.push_back((uint8_t)id[i]); for (uint32_t i = 0; i < payloadLength; i++) mPayload.push_back((uint8_t)payload[i]); } NdefRecord::~NdefRecord() { } bool NdefRecord::parse(std::vector<uint8_t>& buf, bool ignoreMbMe, std::vector<NdefRecord>& records) { return NdefRecord::parse(buf, ignoreMbMe, records, 0); } bool NdefRecord::parse(std::vector<uint8_t>& buf, bool ignoreMbMe, std::vector<NdefRecord>& records, int offset) { bool inChunk = false; uint8_t chunkTnf = -1; bool me = false; uint32_t index = offset; while(!me) { std::vector<uint8_t> type; std::vector<uint8_t> id; std::vector<uint8_t> payload; std::vector<std::vector<uint8_t> > chunks; uint8_t flag = buf[index++]; bool mb = (flag & NdefRecord::FLAG_MB) != 0; me = (flag & NdefRecord::FLAG_ME) != 0; bool cf = (flag & NdefRecord::FLAG_CF) != 0; bool sr = (flag & NdefRecord::FLAG_SR) != 0; bool il = (flag & NdefRecord::FLAG_IL) != 0; uint8_t tnf = flag & 0x07; if (!mb && records.size() == 0 && !inChunk && !ignoreMbMe) { ALOGE("expected MB flag"); return false; } else if (mb && records.size() != 0 && !ignoreMbMe) { ALOGE("unexpected MB flag"); return false; } else if (inChunk && il) { ALOGE("unexpected IL flag in non-leading chunk"); return false; } else if (cf && me) { ALOGE("unexpected ME flag in non-trailing chunk"); return false ; } else if (inChunk && tnf != NdefRecord::TNF_UNCHANGED) { ALOGE("expected TNF_UNCHANGED in non-leading chunk"); return false ; } else if (!inChunk && tnf == NdefRecord::TNF_UNCHANGED) { ALOGE("unexpected TNF_UNCHANGED in first chunk or unchunked record"); return false; } uint32_t typeLength = buf[index++] & 0xFF; uint32_t payloadLength; if (sr) { payloadLength = buf[index++] & 0xFF; } else { payloadLength = ((uint32_t)buf[index] << 24) | ((uint32_t)buf[index + 1] << 16) | ((uint32_t)buf[index + 2] << 8) | ((uint32_t)buf[index + 3]); index += 4; } uint32_t idLength = il ? (buf[index++] & 0xFF) : 0; if (inChunk && typeLength != 0) { ALOGE("expected zero-length type in non-leading chunk"); return false; } if (!inChunk) { for (uint32_t idx = 0; idx < typeLength; idx++) { type.push_back(buf[index++]); } for (uint32_t idx = 0; idx < idLength; idx++) { id.push_back(buf[index++]); } } if (!ensureSanePayloadSize(payloadLength)) { return false; } for (uint32_t idx = 0; idx < payloadLength; idx++) { payload.push_back(buf[index++]); } if (cf && !inChunk) { // first chunk chunks.clear(); chunkTnf = tnf; } if (cf || inChunk) { // any chunk chunks.push_back(payload); } if (!cf && inChunk) { // last chunk, flatten the payload payloadLength = 0; for (uint32_t idx = 0; idx < chunks.size(); idx++) { payloadLength += chunks[idx].size(); } if (!ensureSanePayloadSize(payloadLength)) { return false; } for(uint32_t i = 0; i < chunks.size(); i++) { for(uint32_t j = 0; j < chunks[i].size(); j++) { payload.push_back(chunks[i][j]); } } tnf = chunkTnf; } if (cf) { // more chunks to come inChunk = true; continue; } else { inChunk = false; } bool isValid = validateTnf(tnf, type, id, payload); if (isValid == false) { return false; } NdefRecord record(tnf, type, id, payload); records.push_back(record); if (ignoreMbMe) { // for parsing a single NdefRecord break; } } return true; } bool NdefRecord::ensureSanePayloadSize(long size) { if (size > NdefRecord::MAX_PAYLOAD_SIZE) { ALOGE("payload above max limit: %d > ", NdefRecord::MAX_PAYLOAD_SIZE); return false; } return true; } bool NdefRecord::validateTnf(uint8_t tnf, std::vector<uint8_t>& type, std::vector<uint8_t>& id, std::vector<uint8_t>& payload) { bool isValid = true; switch (tnf) { case TNF_EMPTY: if (type.size() != 0 || id.size() != 0 || payload.size() != 0) { ALOGE("unexpected data in TNF_EMPTY record"); isValid = false; } break; case TNF_WELL_KNOWN: case TNF_MIME_MEDIA: case TNF_ABSOLUTE_URI: case TNF_EXTERNAL_TYPE: break; case TNF_UNKNOWN: case TNF_RESERVED: if (type.size() != 0) { ALOGE("unexpected type field in TNF_UNKNOWN or TNF_RESERVEd record"); isValid = false; } break; case TNF_UNCHANGED: ALOGE("unexpected TNF_UNCHANGED in first chunk or logical record"); isValid = false; break; default: ALOGE("unexpected tnf value"); isValid = false; break; } return isValid; } void NdefRecord::writeToByteBuffer(std::vector<uint8_t>& buf, bool mb, bool me) { bool sr = mPayload.size() < 256; bool il = mId.size() > 0; uint8_t flags = (uint8_t)((mb ? NdefRecord::FLAG_MB : 0) | (me ? NdefRecord::FLAG_ME : 0) | (sr ? NdefRecord::FLAG_SR : 0) | (il ? NdefRecord::FLAG_IL : 0) | mTnf); buf.push_back(flags); buf.push_back((uint8_t)mType.size()); if (sr) { buf.push_back((uint8_t)mPayload.size()); } else { // TODO : check this buf.push_back((mPayload.size() >> 24) & 0xff); buf.push_back((mPayload.size() >> 16) & 0xff); buf.push_back((mPayload.size() >> 8) & 0xff); buf.push_back(mPayload.size() & 0xff); } if (il) { buf.push_back((uint8_t)mId.size()); } for (uint32_t i = 0; i < mType.size(); i++) buf.push_back(mType[i]); for (uint32_t i = 0; i < mId.size(); i++) buf.push_back(mId[i]); for (uint32_t i = 0; i < mPayload.size(); i++) buf.push_back(mPayload[i]); } <|endoftext|>
<commit_before>/* Copyright Eli Dupree and Isaac Dupree, 2011, 2012 This file is part of Lasercake. Lasercake 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. Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LASERCAKE_MISC_STRUCTURES_HPP__ #define LASERCAKE_MISC_STRUCTURES_HPP__ #include <utility> #include <functional> #include <vector> #include <unordered_map> #include <boost/utility.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/optional.hpp> // These are too small to all get their own files. template<typename value_type, typename reference = value_type&, typename pointer = value_type*> class value_as_ptr { public: reference operator*() { return v_; } pointer operator->() { return boost::addressof(v_); } value_as_ptr(reference v) : v_(v) {} private: value_type v_; }; // Like boost::optional, but there is always a constructed T in a faux_optional, // it just might be invalid/inaccessible. Using boost::optional in polygon-collision- // detection was a slight performance hit compared to std::pair<bool, rational> but // faux_optional is no performance hit while still making its code clearer. template<class T> class faux_optional { private: struct unspecified_bool_{int member; private:unspecified_bool_();}; typedef int unspecified_bool_::* unspecified_bool_type; public: typedef T value_type; faux_optional() : exists_(false) {} faux_optional(boost::none_t) : exists_(false) {} faux_optional(value_type const& value) : exists_(true), value_(value) {} faux_optional& operator=(boost::none_t) { exists_ = false; return *this; } faux_optional& operator=(value_type const& value) { exists_ = true; value_ = value; return *this; } operator unspecified_bool_type()const { return exists_ ? &unspecified_bool_::member : nullptr; } operator boost::optional<value_type>()const { if(exists_) return value_; else return boost::none; } value_type& operator*() { caller_correct_if(exists_, "deref of empty optional"); return value_; } value_type const& operator*()const { caller_correct_if(exists_, "deref of empty optional"); return value_; } value_type* operator->() { return boost::addressof(**this); } value_type const* operator->()const { return boost::addressof(**this); } private: bool exists_; value_type value_; }; template<typename T> class literally_random_access_set { public: typedef size_t size_type; private: typedef std::unordered_map<T, size_type> contents_type_; typedef typename contents_type_::value_type contents_value_type_; typedef typename contents_type_::iterator contents_iterator_; typedef typename contents_type_::const_iterator contents_const_iterator_; // In contents_type_, the user is only permitted to change the keys // (i.e. literally_random_access_set members), // and keys can't be changed because they're being used as keys, so only // provide a const iterator. struct select1st_ { typedef T const& result_type; T const& operator()(contents_value_type_ const& v)const {return v.first;} }; public: typedef boost::transform_iterator<select1st_, contents_const_iterator_> iterator; typedef iterator const_iterator; bool insert(T const& t) { std::pair<contents_iterator_, bool> iter_and_did_anything_change = members_to_indices_.insert(contents_value_type_(t, size())); if (iter_and_did_anything_change.second) { try { pointers_vector_.push_back(&*iter_and_did_anything_change.first); } catch(...) { members_to_indices_.erase(iter_and_did_anything_change.first); } } return iter_and_did_anything_change.second; } bool erase(T const& t) { contents_iterator_ i = members_to_indices_.find(t); if (i != members_to_indices_.end()) { const size_type idx = i->second; members_to_indices_.erase(i); assert(idx < pointers_vector_.size()); contents_value_type_*const moved_ptr = pointers_vector_.back(); moved_ptr->second = idx; pointers_vector_[idx] = moved_ptr; pointers_vector_.pop_back(); return true; } return false; } template<typename RNG> T const& get_random(RNG& rng)const { caller_error_if(members_to_indices_.empty(), "Trying to get a random element of an empty literally_random_access_set"); const boost::random::uniform_int_distribution<size_type> random_item_idx(0, pointers_vector_.size()-1); const size_type idx = random_item_idx(rng); assert(idx < pointers_vector_.size()); return pointers_vector_[idx]->first; } bool empty()const { return members_to_indices_.empty(); } size_type size()const { return members_to_indices_.size(); } const_iterator begin()const { return const_iterator(members_to_indices_.begin(), select1st_()); } const_iterator end()const { return const_iterator(members_to_indices_.end(), select1st_()); } private: std::vector<contents_value_type_*> pointers_vector_; contents_type_ members_to_indices_; }; #endif <commit_msg>fix bug in case erased item was last item in vector<commit_after>/* Copyright Eli Dupree and Isaac Dupree, 2011, 2012 This file is part of Lasercake. Lasercake 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. Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LASERCAKE_MISC_STRUCTURES_HPP__ #define LASERCAKE_MISC_STRUCTURES_HPP__ #include <utility> #include <functional> #include <vector> #include <unordered_map> #include <boost/utility.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/optional.hpp> // These are too small to all get their own files. template<typename value_type, typename reference = value_type&, typename pointer = value_type*> class value_as_ptr { public: reference operator*() { return v_; } pointer operator->() { return boost::addressof(v_); } value_as_ptr(reference v) : v_(v) {} private: value_type v_; }; // Like boost::optional, but there is always a constructed T in a faux_optional, // it just might be invalid/inaccessible. Using boost::optional in polygon-collision- // detection was a slight performance hit compared to std::pair<bool, rational> but // faux_optional is no performance hit while still making its code clearer. template<class T> class faux_optional { private: struct unspecified_bool_{int member; private:unspecified_bool_();}; typedef int unspecified_bool_::* unspecified_bool_type; public: typedef T value_type; faux_optional() : exists_(false) {} faux_optional(boost::none_t) : exists_(false) {} faux_optional(value_type const& value) : exists_(true), value_(value) {} faux_optional& operator=(boost::none_t) { exists_ = false; return *this; } faux_optional& operator=(value_type const& value) { exists_ = true; value_ = value; return *this; } operator unspecified_bool_type()const { return exists_ ? &unspecified_bool_::member : nullptr; } operator boost::optional<value_type>()const { if(exists_) return value_; else return boost::none; } value_type& operator*() { caller_correct_if(exists_, "deref of empty optional"); return value_; } value_type const& operator*()const { caller_correct_if(exists_, "deref of empty optional"); return value_; } value_type* operator->() { return boost::addressof(**this); } value_type const* operator->()const { return boost::addressof(**this); } private: bool exists_; value_type value_; }; template<typename T> class literally_random_access_set { public: typedef size_t size_type; private: typedef std::unordered_map<T, size_type> contents_type_; typedef typename contents_type_::value_type contents_value_type_; typedef typename contents_type_::iterator contents_iterator_; typedef typename contents_type_::const_iterator contents_const_iterator_; // In contents_type_, the user is only permitted to change the keys // (i.e. literally_random_access_set members), // and keys can't be changed because they're being used as keys, so only // provide a const iterator. struct select1st_ { typedef T const& result_type; T const& operator()(contents_value_type_ const& v)const {return v.first;} }; public: typedef boost::transform_iterator<select1st_, contents_const_iterator_> iterator; typedef iterator const_iterator; bool insert(T const& t) { std::pair<contents_iterator_, bool> iter_and_did_anything_change = members_to_indices_.insert(contents_value_type_(t, size())); if (iter_and_did_anything_change.second) { try { pointers_vector_.push_back(&*iter_and_did_anything_change.first); } catch(...) { members_to_indices_.erase(iter_and_did_anything_change.first); } } return iter_and_did_anything_change.second; } bool erase(T const& t) { contents_iterator_ i = members_to_indices_.find(t); if (i != members_to_indices_.end()) { const size_type idx = i->second; assert(idx < pointers_vector_.size()); contents_value_type_*const moved_ptr = pointers_vector_.back(); moved_ptr->second = idx; pointers_vector_[idx] = moved_ptr; pointers_vector_.pop_back(); members_to_indices_.erase(i); return true; } return false; } template<typename RNG> T const& get_random(RNG& rng)const { caller_error_if(members_to_indices_.empty(), "Trying to get a random element of an empty literally_random_access_set"); const boost::random::uniform_int_distribution<size_type> random_item_idx(0, pointers_vector_.size()-1); const size_type idx = random_item_idx(rng); assert(idx < pointers_vector_.size()); return pointers_vector_[idx]->first; } bool empty()const { return members_to_indices_.empty(); } size_type size()const { return members_to_indices_.size(); } const_iterator begin()const { return const_iterator(members_to_indices_.begin(), select1st_()); } const_iterator end()const { return const_iterator(members_to_indices_.end(), select1st_()); } private: std::vector<contents_value_type_*> pointers_vector_; contents_type_ members_to_indices_; }; #endif <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, 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 the Rice University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/base/spaces/SO3StateSpace.h" #include <algorithm> #include <limits> #include <cmath> #include "ompl/tools/config/MagicConstants.h" #include <boost/math/constants/constants.hpp> // Define for boost version < 1.47 #ifndef BOOST_ASSERT_MSG #define BOOST_ASSERT_MSG(expr, msg) assert(expr) #endif static const double MAX_QUATERNION_NORM_ERROR = 1e-9; /// @cond IGNORE namespace ompl { namespace base { static inline void computeAxisAngle(SO3StateSpace::StateType &q, double ax, double ay, double az, double angle) { double norm = sqrt(ax * ax + ay * ay + az * az); if (norm < MAX_QUATERNION_NORM_ERROR) q.setIdentity(); else { double s = sin(angle / 2.0); q.x = s * ax / norm; q.y = s * ay / norm; q.z = s * az / norm; q.w = cos(angle / 2.0); } } /* Standard quaternion multiplication: q = q0 * q1 */ static inline void quaternionProduct(SO3StateSpace::StateType &q, const SO3StateSpace::StateType& q0, const SO3StateSpace::StateType& q1) { q.x = q0.w*q1.x + q0.x*q1.w + q0.y*q1.z - q0.z*q1.y; q.y = q0.w*q1.y + q0.y*q1.w + q0.z*q1.x - q0.x*q1.z; q.z = q0.w*q1.z + q0.z*q1.w + q0.x*q1.y - q0.y*q1.x; q.w = q0.w*q1.w - q0.x*q1.x - q0.y*q1.y - q0.z*q1.z; } } } /// @endcond void ompl::base::SO3StateSpace::StateType::setAxisAngle(double ax, double ay, double az, double angle) { computeAxisAngle(*this, ax, ay, az, angle); } void ompl::base::SO3StateSpace::StateType::setIdentity(void) { x = y = z = 0.0; w = 1.0; } void ompl::base::SO3StateSampler::sampleUniform(State *state) { rng_.quaternion(&state->as<SO3StateSpace::StateType>()->x); } void ompl::base::SO3StateSampler::sampleUniformNear(State *state, const State *near, const double distance) { if (distance >= .25 * boost::math::constants::pi<double>()) { sampleUniform(state); return; } double d = rng_.uniform01(); SO3StateSpace::StateType q, *qs = static_cast<SO3StateSpace::StateType*>(state); const SO3StateSpace::StateType *qnear = static_cast<const SO3StateSpace::StateType*>(near); computeAxisAngle(q, rng_.gaussian01(), rng_.gaussian01(), rng_.gaussian01(), 2.*pow(d,1./3.)*distance); quaternionProduct(*qs, *qnear, q); } void ompl::base::SO3StateSampler::sampleGaussian(State *state, const State * mean, const double stdDev) { // CDF of N(0, 1.17) at -pi/4 is approx. .25, so there's .25 probability // weight in each tail. Since the maximum distance in SO(3) is pi/2, we're // essentially as likely to sample a state within distance [0, pi/4] as // within distance [pi/4, pi/2]. With most weight in the tails (that wrap // around in case of quaternions) we might as well sample uniformly. if (stdDev > 1.17) { sampleUniform(state); return; } double x = rng_.gaussian(0, stdDev), y = rng_.gaussian(0, stdDev), z = rng_.gaussian(0, stdDev), theta = std::sqrt(x*x + y*y + z*z); if (theta < std::numeric_limits<double>::epsilon()) space_->copyState(state, mean); else { SO3StateSpace::StateType q, *qs = static_cast<SO3StateSpace::StateType*>(state); const SO3StateSpace::StateType *qmu = static_cast<const SO3StateSpace::StateType*>(mean); double s = sin(theta / 2) / theta; q.w = cos(theta / 2); q.x = s * x; q.y = s * y; q.z = s * z; quaternionProduct(*qs, *qmu, q); } } unsigned int ompl::base::SO3StateSpace::getDimension(void) const { return 3; } double ompl::base::SO3StateSpace::getMaximumExtent(void) const { return .5 * boost::math::constants::pi<double>(); } double ompl::base::SO3StateSpace::norm(const StateType *state) const { double nrmSqr = state->x * state->x + state->y * state->y + state->z * state->z + state->w * state->w; return (fabs(nrmSqr - 1.0) > std::numeric_limits<double>::epsilon()) ? sqrt(nrmSqr) : 1.0; } void ompl::base::SO3StateSpace::enforceBounds(State *state) const { StateType *qstate = static_cast<StateType*>(state); double nrm = norm(qstate); if (fabs(nrm) < MAX_QUATERNION_NORM_ERROR) qstate->setIdentity(); else if (fabs(nrm - 1.0) > MAX_QUATERNION_NORM_ERROR) { qstate->x /= nrm; qstate->y /= nrm; qstate->z /= nrm; qstate->w /= nrm; } } bool ompl::base::SO3StateSpace::satisfiesBounds(const State *state) const { return fabs(norm(static_cast<const StateType*>(state)) - 1.0) < MAX_QUATERNION_NORM_ERROR; } void ompl::base::SO3StateSpace::copyState(State *destination, const State *source) const { const StateType *qsource = static_cast<const StateType*>(source); StateType *qdestination = static_cast<StateType*>(destination); qdestination->x = qsource->x; qdestination->y = qsource->y; qdestination->z = qsource->z; qdestination->w = qsource->w; } unsigned int ompl::base::SO3StateSpace::getSerializationLength(void) const { return sizeof(double) * 4; } void ompl::base::SO3StateSpace::serialize(void *serialization, const State *state) const { memcpy(serialization, &state->as<StateType>()->x, sizeof(double) * 4); } void ompl::base::SO3StateSpace::deserialize(State *state, const void *serialization) const { memcpy(&state->as<StateType>()->x, serialization, sizeof(double) * 4); } /// @cond IGNORE /* Based on code from : Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ */ namespace ompl { namespace base { static inline double arcLength(const State *state1, const State *state2) { const SO3StateSpace::StateType *qs1 = static_cast<const SO3StateSpace::StateType*>(state1); const SO3StateSpace::StateType *qs2 = static_cast<const SO3StateSpace::StateType*>(state2); double dq = fabs(qs1->x * qs2->x + qs1->y * qs2->y + qs1->z * qs2->z + qs1->w * qs2->w); if (dq > 1.0 - MAX_QUATERNION_NORM_ERROR) return 0.0; else return acos(dq); } } } /// @endcond double ompl::base::SO3StateSpace::distance(const State *state1, const State *state2) const { BOOST_ASSERT_MSG(satisfiesBounds(state1) && satisfiesBounds(state2), "The states passed to SO3StateSpace::distance are not within bounds. Call " "SO3StateSpace::enforceBounds() in, e.g., ompl::control::ODESolver::PostPropagationEvent, " "ompl::control::StatePropagator, or ompl::base::StateValidityChecker"); return arcLength(state1, state2); } bool ompl::base::SO3StateSpace::equalStates(const State *state1, const State *state2) const { return arcLength(state1, state2) < std::numeric_limits<double>::epsilon(); } /* Based on code from : Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ */ void ompl::base::SO3StateSpace::interpolate(const State *from, const State *to, const double t, State *state) const { assert(fabs(norm(static_cast<const StateType*>(from)) - 1.0) < MAX_QUATERNION_NORM_ERROR); assert(fabs(norm(static_cast<const StateType*>(to)) - 1.0) < MAX_QUATERNION_NORM_ERROR); double theta = arcLength(from, to); if (theta > std::numeric_limits<double>::epsilon()) { double d = 1.0 / sin(theta); double s0 = sin((1.0 - t) * theta); double s1 = sin(t * theta); const StateType *qs1 = static_cast<const StateType*>(from); const StateType *qs2 = static_cast<const StateType*>(to); StateType *qr = static_cast<StateType*>(state); double dq = qs1->x * qs2->x + qs1->y * qs2->y + qs1->z * qs2->z + qs1->w * qs2->w; if (dq < 0) // Take care of long angle case see http://en.wikipedia.org/wiki/Slerp s1 = -s1; qr->x = (qs1->x * s0 + qs2->x * s1) * d; qr->y = (qs1->y * s0 + qs2->y * s1) * d; qr->z = (qs1->z * s0 + qs2->z * s1) * d; qr->w = (qs1->w * s0 + qs2->w * s1) * d; } else { if (state != from) copyState(state, from); } } ompl::base::StateSamplerPtr ompl::base::SO3StateSpace::allocDefaultStateSampler(void) const { return StateSamplerPtr(new SO3StateSampler(this)); } ompl::base::State* ompl::base::SO3StateSpace::allocState(void) const { return new StateType(); } void ompl::base::SO3StateSpace::freeState(State *state) const { delete static_cast<StateType*>(state); } void ompl::base::SO3StateSpace::registerProjections(void) { class SO3DefaultProjection : public ProjectionEvaluator { public: SO3DefaultProjection(const StateSpace *space) : ProjectionEvaluator(space) { } virtual unsigned int getDimension(void) const { return 3; } virtual void defaultCellSizes(void) { cellSizes_.resize(3); cellSizes_[0] = boost::math::constants::pi<double>() / magic::PROJECTION_DIMENSION_SPLITS; cellSizes_[1] = boost::math::constants::pi<double>() / magic::PROJECTION_DIMENSION_SPLITS; cellSizes_[2] = boost::math::constants::pi<double>() / magic::PROJECTION_DIMENSION_SPLITS; bounds_.resize(3); bounds_.setLow(-1.0); bounds_.setHigh(1.0); } virtual void project(const State *state, EuclideanProjection &projection) const { projection(0) = state->as<SO3StateSpace::StateType>()->x; projection(1) = state->as<SO3StateSpace::StateType>()->y; projection(2) = state->as<SO3StateSpace::StateType>()->z; } }; registerDefaultProjection(ProjectionEvaluatorPtr(dynamic_cast<ProjectionEvaluator*>(new SO3DefaultProjection(this)))); } double* ompl::base::SO3StateSpace::getValueAddressAtIndex(State *state, const unsigned int index) const { return index < 4 ? &(state->as<StateType>()->x) + index : NULL; } void ompl::base::SO3StateSpace::printState(const State *state, std::ostream &out) const { out << "SO3State ["; if (state) { const StateType *qstate = static_cast<const StateType*>(state); out << qstate->x << " " << qstate->y << " " << qstate->z << " " << qstate->w; } else out << "NULL"; out << ']' << std::endl; } void ompl::base::SO3StateSpace::printSettings(std::ostream &out) const { out << "SO(3) state space '" << getName() << "' (represented using quaternions)" << std::endl; } <commit_msg>Correcting SO3StateSpace's sampleGaussian() routine by adding a scaling parameter to the input standard deviation as shown in Yu Qiu's thesis on distributions over SO(3).<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, 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 the Rice University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/base/spaces/SO3StateSpace.h" #include <algorithm> #include <limits> #include <cmath> #include "ompl/tools/config/MagicConstants.h" #include <boost/math/constants/constants.hpp> // Define for boost version < 1.47 #ifndef BOOST_ASSERT_MSG #define BOOST_ASSERT_MSG(expr, msg) assert(expr) #endif static const double MAX_QUATERNION_NORM_ERROR = 1e-9; /// @cond IGNORE namespace ompl { namespace base { static inline void computeAxisAngle(SO3StateSpace::StateType &q, double ax, double ay, double az, double angle) { double norm = sqrt(ax * ax + ay * ay + az * az); if (norm < MAX_QUATERNION_NORM_ERROR) q.setIdentity(); else { double s = sin(angle / 2.0); q.x = s * ax / norm; q.y = s * ay / norm; q.z = s * az / norm; q.w = cos(angle / 2.0); } } /* Standard quaternion multiplication: q = q0 * q1 */ static inline void quaternionProduct(SO3StateSpace::StateType &q, const SO3StateSpace::StateType& q0, const SO3StateSpace::StateType& q1) { q.x = q0.w*q1.x + q0.x*q1.w + q0.y*q1.z - q0.z*q1.y; q.y = q0.w*q1.y + q0.y*q1.w + q0.z*q1.x - q0.x*q1.z; q.z = q0.w*q1.z + q0.z*q1.w + q0.x*q1.y - q0.y*q1.x; q.w = q0.w*q1.w - q0.x*q1.x - q0.y*q1.y - q0.z*q1.z; } } } /// @endcond void ompl::base::SO3StateSpace::StateType::setAxisAngle(double ax, double ay, double az, double angle) { computeAxisAngle(*this, ax, ay, az, angle); } void ompl::base::SO3StateSpace::StateType::setIdentity(void) { x = y = z = 0.0; w = 1.0; } void ompl::base::SO3StateSampler::sampleUniform(State *state) { rng_.quaternion(&state->as<SO3StateSpace::StateType>()->x); } void ompl::base::SO3StateSampler::sampleUniformNear(State *state, const State *near, const double distance) { if (distance >= .25 * boost::math::constants::pi<double>()) { sampleUniform(state); return; } double d = rng_.uniform01(); SO3StateSpace::StateType q, *qs = static_cast<SO3StateSpace::StateType*>(state); const SO3StateSpace::StateType *qnear = static_cast<const SO3StateSpace::StateType*>(near); computeAxisAngle(q, rng_.gaussian01(), rng_.gaussian01(), rng_.gaussian01(), 2.*pow(d,1./3.)*distance); quaternionProduct(*qs, *qnear, q); } void ompl::base::SO3StateSampler::sampleGaussian(State *state, const State * mean, const double stdDev) { // CDF of N(0, 1.17) at -pi/4 is approx. .25, so there's .25 probability // weight in each tail. Since the maximum distance in SO(3) is pi/2, we're // essentially as likely to sample a state within distance [0, pi/4] as // within distance [pi/4, pi/2]. With most weight in the tails (that wrap // around in case of quaternions) we might as well sample uniformly. if (stdDev > 1.17) { sampleUniform(state); return; } // We scale the input stdDev by 1/sqrt(3), as given in Section // 2.2, Proposition 1 in Yu Qiu's thesis: // // http://lib.dr.iastate.edu/cgi/viewcontent.cgi?article=4014&context=etd double rotDev = stdDev / boost::math::constants::root_three<double>(); double x = rng_.gaussian(0, rotDev), y = rng_.gaussian(0, rotDev), z = rng_.gaussian(0, rotDev), theta = std::sqrt(x*x + y*y + z*z); if (theta < std::numeric_limits<double>::epsilon()) space_->copyState(state, mean); else { SO3StateSpace::StateType q, *qs = static_cast<SO3StateSpace::StateType*>(state); const SO3StateSpace::StateType *qmu = static_cast<const SO3StateSpace::StateType*>(mean); double s = sin(theta / 2) / theta; q.w = cos(theta / 2); q.x = s * x; q.y = s * y; q.z = s * z; quaternionProduct(*qs, *qmu, q); } } unsigned int ompl::base::SO3StateSpace::getDimension(void) const { return 3; } double ompl::base::SO3StateSpace::getMaximumExtent(void) const { return .5 * boost::math::constants::pi<double>(); } double ompl::base::SO3StateSpace::norm(const StateType *state) const { double nrmSqr = state->x * state->x + state->y * state->y + state->z * state->z + state->w * state->w; return (fabs(nrmSqr - 1.0) > std::numeric_limits<double>::epsilon()) ? sqrt(nrmSqr) : 1.0; } void ompl::base::SO3StateSpace::enforceBounds(State *state) const { StateType *qstate = static_cast<StateType*>(state); double nrm = norm(qstate); if (fabs(nrm) < MAX_QUATERNION_NORM_ERROR) qstate->setIdentity(); else if (fabs(nrm - 1.0) > MAX_QUATERNION_NORM_ERROR) { qstate->x /= nrm; qstate->y /= nrm; qstate->z /= nrm; qstate->w /= nrm; } } bool ompl::base::SO3StateSpace::satisfiesBounds(const State *state) const { return fabs(norm(static_cast<const StateType*>(state)) - 1.0) < MAX_QUATERNION_NORM_ERROR; } void ompl::base::SO3StateSpace::copyState(State *destination, const State *source) const { const StateType *qsource = static_cast<const StateType*>(source); StateType *qdestination = static_cast<StateType*>(destination); qdestination->x = qsource->x; qdestination->y = qsource->y; qdestination->z = qsource->z; qdestination->w = qsource->w; } unsigned int ompl::base::SO3StateSpace::getSerializationLength(void) const { return sizeof(double) * 4; } void ompl::base::SO3StateSpace::serialize(void *serialization, const State *state) const { memcpy(serialization, &state->as<StateType>()->x, sizeof(double) * 4); } void ompl::base::SO3StateSpace::deserialize(State *state, const void *serialization) const { memcpy(&state->as<StateType>()->x, serialization, sizeof(double) * 4); } /// @cond IGNORE /* Based on code from : Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ */ namespace ompl { namespace base { static inline double arcLength(const State *state1, const State *state2) { const SO3StateSpace::StateType *qs1 = static_cast<const SO3StateSpace::StateType*>(state1); const SO3StateSpace::StateType *qs2 = static_cast<const SO3StateSpace::StateType*>(state2); double dq = fabs(qs1->x * qs2->x + qs1->y * qs2->y + qs1->z * qs2->z + qs1->w * qs2->w); if (dq > 1.0 - MAX_QUATERNION_NORM_ERROR) return 0.0; else return acos(dq); } } } /// @endcond double ompl::base::SO3StateSpace::distance(const State *state1, const State *state2) const { BOOST_ASSERT_MSG(satisfiesBounds(state1) && satisfiesBounds(state2), "The states passed to SO3StateSpace::distance are not within bounds. Call " "SO3StateSpace::enforceBounds() in, e.g., ompl::control::ODESolver::PostPropagationEvent, " "ompl::control::StatePropagator, or ompl::base::StateValidityChecker"); return arcLength(state1, state2); } bool ompl::base::SO3StateSpace::equalStates(const State *state1, const State *state2) const { return arcLength(state1, state2) < std::numeric_limits<double>::epsilon(); } /* Based on code from : Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ */ void ompl::base::SO3StateSpace::interpolate(const State *from, const State *to, const double t, State *state) const { assert(fabs(norm(static_cast<const StateType*>(from)) - 1.0) < MAX_QUATERNION_NORM_ERROR); assert(fabs(norm(static_cast<const StateType*>(to)) - 1.0) < MAX_QUATERNION_NORM_ERROR); double theta = arcLength(from, to); if (theta > std::numeric_limits<double>::epsilon()) { double d = 1.0 / sin(theta); double s0 = sin((1.0 - t) * theta); double s1 = sin(t * theta); const StateType *qs1 = static_cast<const StateType*>(from); const StateType *qs2 = static_cast<const StateType*>(to); StateType *qr = static_cast<StateType*>(state); double dq = qs1->x * qs2->x + qs1->y * qs2->y + qs1->z * qs2->z + qs1->w * qs2->w; if (dq < 0) // Take care of long angle case see http://en.wikipedia.org/wiki/Slerp s1 = -s1; qr->x = (qs1->x * s0 + qs2->x * s1) * d; qr->y = (qs1->y * s0 + qs2->y * s1) * d; qr->z = (qs1->z * s0 + qs2->z * s1) * d; qr->w = (qs1->w * s0 + qs2->w * s1) * d; } else { if (state != from) copyState(state, from); } } ompl::base::StateSamplerPtr ompl::base::SO3StateSpace::allocDefaultStateSampler(void) const { return StateSamplerPtr(new SO3StateSampler(this)); } ompl::base::State* ompl::base::SO3StateSpace::allocState(void) const { return new StateType(); } void ompl::base::SO3StateSpace::freeState(State *state) const { delete static_cast<StateType*>(state); } void ompl::base::SO3StateSpace::registerProjections(void) { class SO3DefaultProjection : public ProjectionEvaluator { public: SO3DefaultProjection(const StateSpace *space) : ProjectionEvaluator(space) { } virtual unsigned int getDimension(void) const { return 3; } virtual void defaultCellSizes(void) { cellSizes_.resize(3); cellSizes_[0] = boost::math::constants::pi<double>() / magic::PROJECTION_DIMENSION_SPLITS; cellSizes_[1] = boost::math::constants::pi<double>() / magic::PROJECTION_DIMENSION_SPLITS; cellSizes_[2] = boost::math::constants::pi<double>() / magic::PROJECTION_DIMENSION_SPLITS; bounds_.resize(3); bounds_.setLow(-1.0); bounds_.setHigh(1.0); } virtual void project(const State *state, EuclideanProjection &projection) const { projection(0) = state->as<SO3StateSpace::StateType>()->x; projection(1) = state->as<SO3StateSpace::StateType>()->y; projection(2) = state->as<SO3StateSpace::StateType>()->z; } }; registerDefaultProjection(ProjectionEvaluatorPtr(dynamic_cast<ProjectionEvaluator*>(new SO3DefaultProjection(this)))); } double* ompl::base::SO3StateSpace::getValueAddressAtIndex(State *state, const unsigned int index) const { return index < 4 ? &(state->as<StateType>()->x) + index : NULL; } void ompl::base::SO3StateSpace::printState(const State *state, std::ostream &out) const { out << "SO3State ["; if (state) { const StateType *qstate = static_cast<const StateType*>(state); out << qstate->x << " " << qstate->y << " " << qstate->z << " " << qstate->w; } else out << "NULL"; out << ']' << std::endl; } void ompl::base::SO3StateSpace::printSettings(std::ostream &out) const { out << "SO(3) state space '" << getName() << "' (represented using quaternions)" << std::endl; } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2014 Andy Teijelo <ateijelo@gmail.com> 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. */ //#define QT_NO_DEBUG_OUTPUT #include <QtDebug> #include <QFile> #include <QAction> #include <QJsonDocument> #include <QJsonArray> #include <QApplication> #include <QMessageBox> #include <QProcess> #include <QFileInfo> #include <QDir> #include <QTimer> #include <QScreen> #include "quickmenu.h" void QuickMenu::show() { icon.show(); } QuickMenu::QuickMenu(QString jsonPath, QObject *parent) : QObject(parent), jsonPath(jsonPath), creationCheckInterval(100) { // We've just started buildMenu(); if (!QFile::exists(jsonPath)) { fileExisted = false; waitForCreation(); } else { fileExisted = true; startWatching(); } icon.setContextMenu(&rootMenu); connect(&watcher,SIGNAL(fileChanged(QString)),this,SLOT(fileChanged())); connect(&icon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,SLOT(showMenuAtMouse())); } QJsonDocument QuickMenu::readJsonFile() { QJsonDocument rootDoc; QFile f(jsonPath); if (!f.open(QIODevice::ReadOnly)) { rootMenu.addAction(QIcon::fromTheme("dialog-warning"), QString("Error opening %1: %2") .arg(jsonPath) .arg(f.errorString())); return rootDoc; } QByteArray data; QJsonParseError parseError; data = f.readAll(); rootDoc = QJsonDocument::fromJson(data,&parseError); if (rootDoc.isNull()) { std::pair<int,int> p = position(data, parseError); rootMenu.addAction(QIcon::fromTheme("dialog-warning"),QString("Parse Error: %1: %2:%3: %4") .arg(jsonPath) .arg(p.first) .arg(p.second) .arg(parseError.errorString())); } return rootDoc; } void QuickMenu::buildMenu() { qDebug() << "building menu"; rootMenu.clear(); foreach (QMenu *m, subMenus) { m->deleteLater(); } subMenus.clear(); auto rootDoc = readJsonFile(); qDebug() << "rootDoc is null?" << rootDoc.isNull(); if (!(rootDoc.isNull())) { auto rootObj = rootDoc.object(); addMenu(&rootMenu, rootObj); if (rootMenu.icon().isNull()) { icon.setIcon(QIcon(":/default.png")); } else { icon.setIcon(rootMenu.icon()); } } else { icon.setIcon(QIcon(":/default-warning.png")); } rootMenu.addAction("Quit",qApp,SLOT(quit())); } void QuickMenu::actionTriggered() { QAction* a = (QAction *)sender(); QJsonObject entry = a->data().toJsonObject(); QString pwd = entry.value("pwd").toString(); QStringList args; args << "-c"; args << entry.value("action").toString(); QProcess::startDetached("sh",args,pwd); } void QuickMenu::showError(const QString &title, const QString &msg) { icon.showMessage(title, msg); } void QuickMenu::startWatching() { watcher.addPath(jsonPath); } void QuickMenu::waitForCreation() { if (!QFile::exists(jsonPath)) { qDebug() << "path" << jsonPath << "doesn't exist"; QTimer::singleShot(creationCheckInterval, this, SLOT(waitForCreation())); creationCheckInterval = qMin(creationCheckInterval * 2, 1000); if (fileExisted) { buildMenu(); // The file disappeared, reflect it in the menu fileExisted = false; } } else { buildMenu(); fileExisted = true; startWatching(); } } void QuickMenu::fileChanged() { qDebug() << "fileChanged"; if (!watcher.files().contains(jsonPath)) { qDebug() << "watch list didn't contain" << jsonPath; creationCheckInterval = 100; // We'll give the file 100ms to reappear before changing the // icon to a warning, in case it was just overwritten, or moved. // After that, the menu will reflect the error, and QuickMenu // will start checking regularly for the file to reappear. QTimer::singleShot(creationCheckInterval, this, SLOT(waitForCreation())); } else { buildMenu(); } } void QuickMenu::newConnection() { showMenuAtIcon(); } void QuickMenu::showMenuAtIcon() { qDebug() << icon.geometry().topLeft(); //icon.contextMenu()->popup(icon.geometry().topLeft()); int top = icon.geometry().top(); if (top > (qApp->primaryScreen()->size().height() / 2)) { top -= rootMenu.sizeHint().height(); } int left = icon.geometry().left(); qDebug() << qApp->primaryScreen()->size(); icon.contextMenu()->popup(QPoint(left,top)); } void QuickMenu::showMenuAtMouse() { qDebug() << QCursor::pos(); icon.contextMenu()->popup(QCursor::pos()); } void QuickMenu::addMenu(QMenu *menu, const QJsonObject &obj) { if (!obj.contains("menu")) return; menu->setIcon(loadIcon(obj)); if (obj.contains("shortcut")) { menu->menuAction()->setShortcut(QKeySequence(obj.value("shortcut").toString())); } QJsonArray entries = obj.value("menu").toArray(); foreach (QJsonValue e, entries) { if (!e.isObject()) continue; auto entry = e.toObject(); auto label = entry.value("label").toString(); if (entry.contains("menu")) { QMenu *subMenu = menu->addMenu(label); subMenus.insert(subMenu); addMenu(subMenu, entry); } else if (entry.contains("action")) { QAction *action = menu->addAction(loadIcon(entry),label,this,SLOT(actionTriggered())); action->setData(QVariant(entry)); } } } QIcon QuickMenu::loadIcon(const QJsonObject &obj) { QFileInfo fi(jsonPath); auto iconPath = fi.dir().absoluteFilePath(obj.value("icon").toString()); if (QFile::exists(iconPath)) return QIcon(iconPath); return QIcon(); } std::pair<int, int> QuickMenu::position(const QByteArray &data, const QJsonParseError &parseError) { int line = 1; int column = 1; for (int i=0; i<parseError.offset; i++) { if (data.at(i) == '\n') { line += 1; column = 0; } column++; } return {line,column}; } void QuickMenu::listenOn(const QString &name) { server = new QLocalServer(this); int attempts = 2; while (true) { attempts--; server->listen(name); if (server->isListening()) { break; } else { QLocalServer::removeServer(name); } if (attempts <= 0) { qDebug() << QString("Failed to create local server '%1'").arg(name); break; } } connect(server,SIGNAL(newConnection()),this,SLOT(newConnection())); } <commit_msg>Pop up in the same position, regardless of where the icon was clicked.<commit_after>/* The MIT License (MIT) Copyright (c) 2014 Andy Teijelo <ateijelo@gmail.com> 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. */ //#define QT_NO_DEBUG_OUTPUT #include <QtDebug> #include <QFile> #include <QAction> #include <QJsonDocument> #include <QJsonArray> #include <QApplication> #include <QMessageBox> #include <QProcess> #include <QFileInfo> #include <QDir> #include <QTimer> #include <QScreen> #include "quickmenu.h" void QuickMenu::show() { icon.show(); } QuickMenu::QuickMenu(QString jsonPath, QObject *parent) : QObject(parent), jsonPath(jsonPath), creationCheckInterval(100) { // We've just started buildMenu(); if (!QFile::exists(jsonPath)) { fileExisted = false; waitForCreation(); } else { fileExisted = true; startWatching(); } icon.setContextMenu(&rootMenu); connect(&watcher,SIGNAL(fileChanged(QString)),this,SLOT(fileChanged())); connect(&icon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,SLOT(showMenuAtIcon())); } QJsonDocument QuickMenu::readJsonFile() { QJsonDocument rootDoc; QFile f(jsonPath); if (!f.open(QIODevice::ReadOnly)) { rootMenu.addAction(QIcon::fromTheme("dialog-warning"), QString("Error opening %1: %2") .arg(jsonPath) .arg(f.errorString())); return rootDoc; } QByteArray data; QJsonParseError parseError; data = f.readAll(); rootDoc = QJsonDocument::fromJson(data,&parseError); if (rootDoc.isNull()) { std::pair<int,int> p = position(data, parseError); rootMenu.addAction(QIcon::fromTheme("dialog-warning"),QString("Parse Error: %1: %2:%3: %4") .arg(jsonPath) .arg(p.first) .arg(p.second) .arg(parseError.errorString())); } return rootDoc; } void QuickMenu::buildMenu() { qDebug() << "building menu"; rootMenu.clear(); foreach (QMenu *m, subMenus) { m->deleteLater(); } subMenus.clear(); auto rootDoc = readJsonFile(); qDebug() << "rootDoc is null?" << rootDoc.isNull(); if (!(rootDoc.isNull())) { auto rootObj = rootDoc.object(); addMenu(&rootMenu, rootObj); if (rootMenu.icon().isNull()) { icon.setIcon(QIcon(":/default.png")); } else { icon.setIcon(rootMenu.icon()); } } else { icon.setIcon(QIcon(":/default-warning.png")); } rootMenu.addAction("Quit",qApp,SLOT(quit())); } void QuickMenu::actionTriggered() { QAction* a = (QAction *)sender(); QJsonObject entry = a->data().toJsonObject(); QString pwd = entry.value("pwd").toString(); QStringList args; args << "-c"; args << entry.value("action").toString(); QProcess::startDetached("sh",args,pwd); } void QuickMenu::showError(const QString &title, const QString &msg) { icon.showMessage(title, msg); } void QuickMenu::startWatching() { watcher.addPath(jsonPath); } void QuickMenu::waitForCreation() { if (!QFile::exists(jsonPath)) { qDebug() << "path" << jsonPath << "doesn't exist"; QTimer::singleShot(creationCheckInterval, this, SLOT(waitForCreation())); creationCheckInterval = qMin(creationCheckInterval * 2, 1000); if (fileExisted) { buildMenu(); // The file disappeared, reflect it in the menu fileExisted = false; } } else { buildMenu(); fileExisted = true; startWatching(); } } void QuickMenu::fileChanged() { qDebug() << "fileChanged"; if (!watcher.files().contains(jsonPath)) { qDebug() << "watch list didn't contain" << jsonPath; creationCheckInterval = 100; // We'll give the file 100ms to reappear before changing the // icon to a warning, in case it was just overwritten, or moved. // After that, the menu will reflect the error, and QuickMenu // will start checking regularly for the file to reappear. QTimer::singleShot(creationCheckInterval, this, SLOT(waitForCreation())); } else { buildMenu(); } } void QuickMenu::newConnection() { showMenuAtIcon(); } void QuickMenu::showMenuAtIcon() { qDebug() << icon.geometry().topLeft(); //icon.contextMenu()->popup(icon.geometry().topLeft()); int top = icon.geometry().top(); if (top > (qApp->primaryScreen()->size().height() / 2)) { top -= rootMenu.sizeHint().height(); } int left = icon.geometry().left(); qDebug() << qApp->primaryScreen()->size(); icon.contextMenu()->popup(QPoint(left,top)); } void QuickMenu::showMenuAtMouse() { qDebug() << QCursor::pos(); icon.contextMenu()->popup(QCursor::pos()); } void QuickMenu::addMenu(QMenu *menu, const QJsonObject &obj) { if (!obj.contains("menu")) return; menu->setIcon(loadIcon(obj)); if (obj.contains("shortcut")) { menu->menuAction()->setShortcut(QKeySequence(obj.value("shortcut").toString())); } QJsonArray entries = obj.value("menu").toArray(); foreach (QJsonValue e, entries) { if (!e.isObject()) continue; auto entry = e.toObject(); auto label = entry.value("label").toString(); if (entry.contains("menu")) { QMenu *subMenu = menu->addMenu(label); subMenus.insert(subMenu); addMenu(subMenu, entry); } else if (entry.contains("action")) { QAction *action = menu->addAction(loadIcon(entry),label,this,SLOT(actionTriggered())); action->setData(QVariant(entry)); } } } QIcon QuickMenu::loadIcon(const QJsonObject &obj) { QFileInfo fi(jsonPath); auto iconPath = fi.dir().absoluteFilePath(obj.value("icon").toString()); if (QFile::exists(iconPath)) return QIcon(iconPath); return QIcon(); } std::pair<int, int> QuickMenu::position(const QByteArray &data, const QJsonParseError &parseError) { int line = 1; int column = 1; for (int i=0; i<parseError.offset; i++) { if (data.at(i) == '\n') { line += 1; column = 0; } column++; } return {line,column}; } void QuickMenu::listenOn(const QString &name) { server = new QLocalServer(this); int attempts = 2; while (true) { attempts--; server->listen(name); if (server->isListening()) { break; } else { QLocalServer::removeServer(name); } if (attempts <= 0) { qDebug() << QString("Failed to create local server '%1'").arg(name); break; } } connect(server,SIGNAL(newConnection()),this,SLOT(newConnection())); } <|endoftext|>
<commit_before>//C++ includes #include <sys/stat.h> #include <sys/types.h> #include <iostream> #include <cstdlib> #include <sstream> // External library include ( LibMesh, PETSc...) #include "FemusConfig.hpp" // FEMuS #include "paral.hpp" #include "FemusInit.hpp" #include "Files.hpp" #include "MultiLevelMeshTwo.hpp" #include "GenCase.hpp" #include "FETypeEnum.hpp" #include "GaussPoints.hpp" #include "MultiLevelProblem.hpp" #include "ElemType.hpp" #include "TimeLoop.hpp" #include "Typedefs.hpp" #include "Quantity.hpp" #include "QTYnumEnum.hpp" #include "Box.hpp" //for the DOMAIN #include "XDMFWriter.hpp" // application #include "TempQuantities.hpp" #include "OptLoop.hpp" #ifdef HAVE_LIBMESH #include "libmesh/libmesh.h" #endif void GenMatRhsT(MultiLevelProblem &ml_prob, unsigned Level, const unsigned &gridn, const bool &assemble_matrix); void GenMatRhsNS(MultiLevelProblem &ml_prob, unsigned Level, const unsigned &gridn, const bool &assemble_matrix); // ======================================= // TEMPERATURE + NS optimal control problem // ======================================= int main(int argc, char** argv) { #ifdef HAVE_LIBMESH libMesh::LibMeshInit init(argc,argv); #else FemusInit init(argc,argv); #endif // ======= Files ======================== Files files; files.ConfigureRestart(); files.CheckIODirectories(); files.CopyInputFiles(); files.RedirectCout(); // ======= Physics Input Parser ======================== FemusInputParser<double> physics_map("Physics",files.GetOutputPath()); const double rhof = physics_map.get("rho0"); const double Uref = physics_map.get("Uref"); const double Lref = physics_map.get("Lref"); const double muf = physics_map.get("mu0"); const double _pref = rhof*Uref*Uref; physics_map.set("pref",_pref); const double _Re = (rhof*Uref*Lref)/muf; physics_map.set("Re",_Re); const double _Fr = (Uref*Uref)/(9.81*Lref); physics_map.set("Fr",_Fr); const double _Pr = muf/rhof; physics_map.set("Pr",_Pr); // ======= Mesh ===== const unsigned NoLevels = 3; const unsigned dim = 2; const GeomElType geomel_type = QUAD; GenCase mesh(NoLevels,dim,geomel_type,"inclQ2D2x2.gam"); mesh.SetLref(1.); // ======= MyDomainShape (optional, implemented as child of Domain) ==================== FemusInputParser<double> box_map("Box",files.GetOutputPath()); Box mybox(mesh.get_dim(),box_map); mybox.InitAndNondimensionalize(mesh.get_Lref()); mesh.SetDomain(&mybox); mesh.GenerateCase(files.GetOutputPath()); mesh.SetLref(Lref); mybox.InitAndNondimensionalize(mesh.get_Lref()); XDMFWriter::ReadMeshAndNondimensionalizeBiquadraticHDF5(files.GetOutputPath(),mesh); XDMFWriter::PrintMeshXDMF(files.GetOutputPath(),mesh,BIQUADR_FE); XDMFWriter::PrintMeshLinear(files.GetOutputPath(),mesh); //gencase is dimensionalized, meshtwo is nondimensionalized //since the meshtwo is nondimensionalized, all the BC and IC are gonna be implemented on a nondimensionalized mesh //now, a mesh may or may not have an associated domain //moreover, a mesh may or may not be read from file //the generation is dimensional, the nondimensionalization occurs later //Both the Mesh and the optional domain must be nondimensionalized //first, we have to say if the mesh has a shape or not //that depends on the application, it must be put at the main level //then, after you know the shape, you may or may not generate the mesh with that shape //the two things are totally independent, and related to the application, not to the library // ======== Loop =================================== FemusInputParser<double> loop_map("TimeLoop",files.GetOutputPath()); OptLoop opt_loop(files, loop_map); // ===== QuantityMap : this is like the MultilevelSolution ========================================= QuantityMap qty_map; qty_map.SetMeshTwo(&mesh); qty_map.SetInputParser(&physics_map); Temperature temperature("Qty_Temperature",qty_map,1,QQ); qty_map.AddQuantity(&temperature); TempLift templift("Qty_TempLift",qty_map,1,QQ,opt_loop); qty_map.AddQuantity(&templift); TempAdj tempadj("Qty_TempAdj",qty_map,1,QQ); qty_map.AddQuantity(&tempadj); TempDes tempdes("Qty_TempDes",qty_map,1,QQ); qty_map.AddQuantity(&tempdes); //this is not going to be an Unknown! Pressure pressure("Qty_Pressure",qty_map,1,LL); qty_map.AddQuantity(&pressure); Velocity velocity("Qty_Velocity",qty_map,mesh.get_dim(),QQ); qty_map.AddQuantity(&velocity); // ===== end QuantityMap ========================================= // ====== Start new main ================================= MultiLevelMesh ml_msh; ml_msh.GenerateCoarseBoxMesh(8,8,0,0,1,0,2,0,0,QUAD9,"fifth"); // ml_msh.GenerateCoarseBoxMesh(numelemx,numelemy,numelemz,xa,xb,ya,yb,za,zb,elemtype,"fifth"); ml_msh.RefineMesh(NoLevels,NoLevels,NULL); ml_msh.PrintInfo(); ml_msh.SetWriter(XDMF); ml_msh.GetWriter()->write(files.GetOutputPath(),"biquadratic"); ml_msh.SetDomain(&mybox); MultiLevelSolution ml_sol(&ml_msh); ml_sol.AddSolution("FAKE",LAGRANGE,SECOND,0); MultiLevelProblem ml_prob(&ml_sol); ml_prob.SetMeshTwo(&mesh); ml_prob.SetQruleAndElemType("fifth"); ml_prob.SetInputParser(&physics_map); ml_prob.SetQtyMap(&qty_map); //=============================================== //================== Add EQUATIONS AND ====================== //========= associate an EQUATION to QUANTITIES ======== //======================================================== // not all the Quantities need to be unknowns of an equation SystemTwo & eqnNS = ml_prob.add_system<SystemTwo>("Eqn_NS"); eqnNS.AddSolutionToSystemPDE("FAKE"); eqnNS.AddUnknownToSystemPDE(&velocity); eqnNS.AddUnknownToSystemPDE(&pressure); eqnNS.SetAssembleFunction(GenMatRhsNS); SystemTwo & eqnT = ml_prob.add_system<SystemTwo>("Eqn_T"); eqnT.AddSolutionToSystemPDE("FAKE"); eqnT.AddUnknownToSystemPDE(&temperature); eqnT.AddUnknownToSystemPDE(&templift); eqnT.AddUnknownToSystemPDE(&tempadj);//the order in which you add defines the order in the matrix as well, so it is in tune with the assemble function eqnT.SetAssembleFunction(GenMatRhsT); //================================ //========= End add EQUATIONS and ======== //========= associate an EQUATION to QUANTITIES ======== //================================ //Ok now that the mesh file is there i want to COMPUTE the MG OPERATORS... but I want to compute them ONCE and FOR ALL, //not for every equation... but the functions belong to the single equation... I need to make them EXTERNAL // then I'll have A from the equation, PRL and REST from a MG object. //So somehow i'll have to put these objects at a higher level... but so far let us see if we can COMPUTE and PRINT from HERE and not from the gencase //once you have the list of the equations, you loop over them to initialize everything for (MultiLevelProblem::const_system_iterator eqn = ml_prob.begin(); eqn != ml_prob.end(); eqn++) { SystemTwo* sys = static_cast<SystemTwo*>(eqn->second); //===================== sys -> init_two(); //the dof map is built here based on all the solutions associated with that system sys -> _LinSolver[0]->set_solver_type(GMRES); //if I keep PREONLY it doesn't run //===================== sys -> init_unknown_vars(); //===================== sys -> _dofmap.ComputeMeshToDof(); //===================== sys -> initVectors(); //===================== sys -> Initialize(); ///===================== sys -> _bcond.GenerateBdc(); //===================== GenCase::ReadMGOps(files.GetOutputPath(),sys); } opt_loop.TransientSetup(ml_prob); // reset the initial state (if restart) and print the Case opt_loop.optimization_loop(ml_prob); // at this point, the run has been completed files.PrintRunForRestart(DEFAULT_LAST_RUN); files.log_petsc(); // ============ clean ================================ ml_prob.clear(); mesh.clear(); return 0; }<commit_msg>Adding Solutions to the MLProblem does not hurt<commit_after>//C++ includes #include <sys/stat.h> #include <sys/types.h> #include <iostream> #include <cstdlib> #include <sstream> // External library include ( LibMesh, PETSc...) #include "FemusConfig.hpp" // FEMuS #include "paral.hpp" #include "FemusInit.hpp" #include "Files.hpp" #include "MultiLevelMeshTwo.hpp" #include "GenCase.hpp" #include "FETypeEnum.hpp" #include "GaussPoints.hpp" #include "MultiLevelProblem.hpp" #include "ElemType.hpp" #include "TimeLoop.hpp" #include "Typedefs.hpp" #include "Quantity.hpp" #include "QTYnumEnum.hpp" #include "Box.hpp" //for the DOMAIN #include "XDMFWriter.hpp" // application #include "TempQuantities.hpp" #include "OptLoop.hpp" #ifdef HAVE_LIBMESH #include "libmesh/libmesh.h" #endif void GenMatRhsT(MultiLevelProblem &ml_prob, unsigned Level, const unsigned &gridn, const bool &assemble_matrix); void GenMatRhsNS(MultiLevelProblem &ml_prob, unsigned Level, const unsigned &gridn, const bool &assemble_matrix); // ======================================= // TEMPERATURE + NS optimal control problem // ======================================= int main(int argc, char** argv) { #ifdef HAVE_LIBMESH libMesh::LibMeshInit init(argc,argv); #else FemusInit init(argc,argv); #endif // ======= Files ======================== Files files; files.ConfigureRestart(); files.CheckIODirectories(); files.CopyInputFiles(); files.RedirectCout(); // ======= Physics Input Parser ======================== FemusInputParser<double> physics_map("Physics",files.GetOutputPath()); const double rhof = physics_map.get("rho0"); const double Uref = physics_map.get("Uref"); const double Lref = physics_map.get("Lref"); const double muf = physics_map.get("mu0"); const double _pref = rhof*Uref*Uref; physics_map.set("pref",_pref); const double _Re = (rhof*Uref*Lref)/muf; physics_map.set("Re",_Re); const double _Fr = (Uref*Uref)/(9.81*Lref); physics_map.set("Fr",_Fr); const double _Pr = muf/rhof; physics_map.set("Pr",_Pr); // ======= Mesh ===== const unsigned NoLevels = 3; const unsigned dim = 2; const GeomElType geomel_type = QUAD; GenCase mesh(NoLevels,dim,geomel_type,"inclQ2D2x2.gam"); mesh.SetLref(1.); // ======= MyDomainShape (optional, implemented as child of Domain) ==================== FemusInputParser<double> box_map("Box",files.GetOutputPath()); Box mybox(mesh.get_dim(),box_map); mybox.InitAndNondimensionalize(mesh.get_Lref()); mesh.SetDomain(&mybox); mesh.GenerateCase(files.GetOutputPath()); mesh.SetLref(Lref); mybox.InitAndNondimensionalize(mesh.get_Lref()); XDMFWriter::ReadMeshAndNondimensionalizeBiquadraticHDF5(files.GetOutputPath(),mesh); XDMFWriter::PrintMeshXDMF(files.GetOutputPath(),mesh,BIQUADR_FE); XDMFWriter::PrintMeshLinear(files.GetOutputPath(),mesh); //gencase is dimensionalized, meshtwo is nondimensionalized //since the meshtwo is nondimensionalized, all the BC and IC are gonna be implemented on a nondimensionalized mesh //now, a mesh may or may not have an associated domain //moreover, a mesh may or may not be read from file //the generation is dimensional, the nondimensionalization occurs later //Both the Mesh and the optional domain must be nondimensionalized //first, we have to say if the mesh has a shape or not //that depends on the application, it must be put at the main level //then, after you know the shape, you may or may not generate the mesh with that shape //the two things are totally independent, and related to the application, not to the library // ======== Loop =================================== FemusInputParser<double> loop_map("TimeLoop",files.GetOutputPath()); OptLoop opt_loop(files, loop_map); // ===== QuantityMap : this is like the MultilevelSolution ========================================= QuantityMap qty_map; qty_map.SetMeshTwo(&mesh); qty_map.SetInputParser(&physics_map); Temperature temperature("Qty_Temperature",qty_map,1,QQ); qty_map.AddQuantity(&temperature); TempLift templift("Qty_TempLift",qty_map,1,QQ,opt_loop); qty_map.AddQuantity(&templift); TempAdj tempadj("Qty_TempAdj",qty_map,1,QQ); qty_map.AddQuantity(&tempadj); TempDes tempdes("Qty_TempDes",qty_map,1,QQ); qty_map.AddQuantity(&tempdes); //this is not going to be an Unknown! Pressure pressure("Qty_Pressure",qty_map,1,LL); qty_map.AddQuantity(&pressure); Velocity velocity("Qty_Velocity",qty_map,mesh.get_dim(),QQ); qty_map.AddQuantity(&velocity); // ===== end QuantityMap ========================================= // ====== Start new main ================================= MultiLevelMesh ml_msh; ml_msh.GenerateCoarseBoxMesh(8,8,0,0,1,0,2,0,0,QUAD9,"fifth"); // ml_msh.GenerateCoarseBoxMesh(numelemx,numelemy,numelemz,xa,xb,ya,yb,za,zb,elemtype,"fifth"); ml_msh.RefineMesh(NoLevels,NoLevels,NULL); ml_msh.PrintInfo(); ml_msh.SetWriter(XDMF); ml_msh.GetWriter()->write(files.GetOutputPath(),"biquadratic"); ml_msh.SetDomain(&mybox); MultiLevelSolution ml_sol(&ml_msh); ml_sol.AddSolution("Qty_Temperature",LAGRANGE,SECOND,0); ml_sol.AddSolution("Qty_TempLift",LAGRANGE,SECOND,0); ml_sol.AddSolution("Qty_TempAdj",LAGRANGE,SECOND,0); ml_sol.AddSolution("Qty_Velocity",LAGRANGE,SECOND,0); ml_sol.AddSolution("Qty_Pressure",LAGRANGE,FIRST,0); ml_sol.AddSolution("Qty_TempDes",LAGRANGE,SECOND,0);//this is not going to be an Unknown! MultiLevelProblem ml_prob(&ml_sol); ml_prob.SetMeshTwo(&mesh); ml_prob.SetQruleAndElemType("fifth"); ml_prob.SetInputParser(&physics_map); ml_prob.SetQtyMap(&qty_map); //=============================================== //================== Add EQUATIONS AND ====================== //========= associate an EQUATION to QUANTITIES ======== //======================================================== // not all the Quantities need to be unknowns of an equation SystemTwo & eqnNS = ml_prob.add_system<SystemTwo>("Eqn_NS"); eqnNS.AddSolutionToSystemPDE("FAKE"); eqnNS.AddUnknownToSystemPDE(&velocity); eqnNS.AddUnknownToSystemPDE(&pressure); eqnNS.SetAssembleFunction(GenMatRhsNS); SystemTwo & eqnT = ml_prob.add_system<SystemTwo>("Eqn_T"); eqnT.AddSolutionToSystemPDE("FAKE"); eqnT.AddUnknownToSystemPDE(&temperature); eqnT.AddUnknownToSystemPDE(&templift); eqnT.AddUnknownToSystemPDE(&tempadj);//the order in which you add defines the order in the matrix as well, so it is in tune with the assemble function eqnT.SetAssembleFunction(GenMatRhsT); //================================ //========= End add EQUATIONS and ======== //========= associate an EQUATION to QUANTITIES ======== //================================ //Ok now that the mesh file is there i want to COMPUTE the MG OPERATORS... but I want to compute them ONCE and FOR ALL, //not for every equation... but the functions belong to the single equation... I need to make them EXTERNAL // then I'll have A from the equation, PRL and REST from a MG object. //So somehow i'll have to put these objects at a higher level... but so far let us see if we can COMPUTE and PRINT from HERE and not from the gencase //once you have the list of the equations, you loop over them to initialize everything for (MultiLevelProblem::const_system_iterator eqn = ml_prob.begin(); eqn != ml_prob.end(); eqn++) { SystemTwo* sys = static_cast<SystemTwo*>(eqn->second); //===================== sys -> init_two(); //the dof map is built here based on all the solutions associated with that system sys -> _LinSolver[0]->set_solver_type(GMRES); //if I keep PREONLY it doesn't run //===================== sys -> init_unknown_vars(); //===================== sys -> _dofmap.ComputeMeshToDof(); //===================== sys -> initVectors(); //===================== sys -> Initialize(); ///===================== sys -> _bcond.GenerateBdc(); //===================== GenCase::ReadMGOps(files.GetOutputPath(),sys); } opt_loop.TransientSetup(ml_prob); // reset the initial state (if restart) and print the Case opt_loop.optimization_loop(ml_prob); // at this point, the run has been completed files.PrintRunForRestart(DEFAULT_LAST_RUN); files.log_petsc(); // ============ clean ================================ ml_prob.clear(); mesh.clear(); return 0; }<|endoftext|>
<commit_before>// Licensed under a 3-clause BSD style license - see LICENSE.rst // Fast range median distance computations for dataset `y`: // // mu(l, r) = median(y[l:r+1]) // dist(l, r) = sum(abs(x - mu(l, r)) for x in y[l:r+1]) // // and an implementation of the find-best-partition dynamic program. // // We don't implement a rolling median computation, on the assumption that // accesses are concentrated on small windows in the data. #include <vector> #include <queue> #include <limits> #include <map> #include <algorithm> #include <Python.h> #define EXTERN_C_BEGIN extern "C" { #define EXTERN_C_END } // // Median computation. // template <class const_iterator> void compute_median(const_iterator start, const_iterator end, double *mu, double *dist) { size_t n = end - start; std::vector<double> tmp; std::vector<double>::iterator nth; tmp.insert(tmp.end(), start, end); if (start >= end) { *mu = 0; } else { nth = tmp.begin() + n/2; std::nth_element(tmp.begin(), nth, tmp.end()); if (n % 2 == 0) { *mu = (*nth + *std::max_element(tmp.begin(), nth)) / 2; } else { *mu = *nth; } } *dist = 0; for (const_iterator it = start; it < end; ++it) { *dist += fabs(*it - *mu); } } // // Cache for cache[left,right] == (mu, dist) // class Cache { private: struct Item { size_t left, right; double mu, dist; }; std::vector<Item> items_; size_t idx(size_t left, size_t right) const { // Enumeration of pairs size_t n = right - left; n = (n + left) * (n + left + 1) / 2 + n; return n % items_.size(); } public: Cache(size_t size) : items_(size) { std::vector<Item>::iterator it; for (it = items_.begin(); it < items_.end(); ++it) { it->left = -1; } } bool get(size_t left, size_t right, double *mu, double *dist) const { size_t i = idx(left, right); if (items_[i].left == left && items_[i].right == right) { *mu = items_[i].mu; *dist = items_[i].dist; return true; } return false; } void set(size_t left, size_t right, double mu, double dist) { size_t i = idx(left, right); items_[i].left = left; items_[i].right = right; items_[i].mu = mu; items_[i].dist = dist; } }; // // RangeMedian object. // typedef struct { PyObject_HEAD std::vector<double> *y; Cache *cache; } RangeMedianObject; PyObject *RangeMedian_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { RangeMedianObject *self; self = (RangeMedianObject*)type->tp_alloc(type, 0); self->y = NULL; self->cache = NULL; return (PyObject*)self; } int RangeMedian_init(RangeMedianObject *self, PyObject *args, PyObject *kwds) { static const char *kwlist[] = {"y", NULL}; PyObject *y_obj; Py_ssize_t size, k; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!", (char**)kwlist, &PyList_Type, &y_obj)) { return -1; } size = PyList_GET_SIZE(y_obj); try { self->y = new std::vector<double>(size); // Multiplier based on hardcoded constant sizes in step_detect.py, about // this many accesses expected --- but prefer primes due to a modulo // calculation in the cache. self->cache = new Cache(37*size + 401); } catch (const std::bad_alloc&) { PyErr_SetString(PyExc_MemoryError, "Allocating memory failed"); return -1; } for (k = 0; k < size; ++k) { PyObject *x; x = PyNumber_Float(PyList_GET_ITEM(y_obj, k)); if (x == NULL || !PyFloat_Check(x)) { Py_XDECREF(x); return -1; } (*self->y)[k] = PyFloat_AS_DOUBLE(x); Py_DECREF(x); } return 0; } static void RangeMedian_dealloc(RangeMedianObject *self) { delete self->y; delete self->cache; Py_TYPE(self)->tp_free((PyObject*)self); } static int RangeMedian_mu_dist(RangeMedianObject *self, Py_ssize_t left, Py_ssize_t right, double *mu, double *dist) { Py_ssize_t size = (Py_ssize_t)self->y->size(); if (left < 0 || right < 0 || left >= size || right >= size) { PyErr_SetString(PyExc_ValueError, "argument out of range"); return -1; } if (!self->cache->get(left, right, mu, dist)) { compute_median(self->y->begin() + left, self->y->begin() + right + 1, mu, dist); self->cache->set(left, right, *mu, *dist); } return 0; } static PyObject *RangeMedian_mu(RangeMedianObject *self, PyObject *args) { Py_ssize_t left, right; double mu = 0, dist; if (!PyArg_ParseTuple(args, "nn", &left, &right)) { return NULL; } if (RangeMedian_mu_dist(self, left, right, &mu, &dist) == -1) { return NULL; } return PyFloat_FromDouble(mu); } static PyObject *RangeMedian_dist(RangeMedianObject *self, PyObject *args) { Py_ssize_t left, right; double mu, dist = 0; if (!PyArg_ParseTuple(args, "nn", &left, &right)) { return NULL; } if (RangeMedian_mu_dist(self, left, right, &mu, &dist) == -1) { return NULL; } return PyFloat_FromDouble(dist); } static PyObject *RangeMedian_precompute(RangeMedianObject *self, PyObject *args) { Py_ssize_t max_size, min_pos, max_pos; if (!PyArg_ParseTuple(args, "nnn", &max_size, &min_pos, &max_pos)) { return NULL; } // noop Py_RETURN_NONE; } static PyObject *RangeMedian_find_best_partition(RangeMedianObject *self, PyObject *args) { Py_ssize_t min_size, max_size, min_pos, max_pos; double gamma; Py_ssize_t size; if (!PyArg_ParseTuple(args, "dnnnn", &gamma, &min_size, &max_size, &min_pos, &max_pos)) { return NULL; } size = self->y->size(); if (!(0 < min_size && min_size <= max_size && 0 <= min_pos && min_pos <= max_pos && max_pos <= size)) { PyErr_SetString(PyExc_ValueError, "invalid input indices"); return NULL; } double inf = std::numeric_limits<double>::infinity(); std::vector<double> B(max_pos - min_pos + 1); std::vector<Py_ssize_t> p(max_pos - min_pos); B[0] = -gamma; for (Py_ssize_t right = min_pos; right < max_pos; ++right) { B[right + 1 - min_pos] = inf; Py_ssize_t aa = std::max(right + 1 - max_size, min_pos); Py_ssize_t bb = std::max(right + 1 - min_size + 1, min_pos); for (Py_ssize_t left = aa; left < bb; ++left) { double mu, dist; if (RangeMedian_mu_dist(self, left, right, &mu, &dist) == -1) { return NULL; } double b = B[left - min_pos] + gamma + dist; if (b <= B[right + 1 - min_pos]) { B[right + 1 - min_pos] = b; p[right - min_pos] = left - 1; } } } PyObject *p_list; p_list = PyList_New(p.size()); if (p_list == NULL) { return NULL; } for (Py_ssize_t k = 0; k < (Py_ssize_t)p.size(); ++k) { #if PY_MAJOR_VERSION >= 3 PyObject *num = PyLong_FromSsize_t(p[k]); #else PyObject *num = PyInt_FromSsize_t(p[k]); #endif if (num == NULL) { Py_DECREF(p_list); return NULL; } PyList_SET_ITEM(p_list, k, num); } return p_list; } // // RangeMedian type. // static PyMethodDef RangeMedian_methods[] = { {"mu", (PyCFunction)RangeMedian_mu, METH_VARARGS, NULL}, {"dist", (PyCFunction)RangeMedian_dist, METH_VARARGS, NULL}, {"precompute", (PyCFunction)RangeMedian_precompute, METH_VARARGS, NULL}, {"find_best_partition", (PyCFunction)RangeMedian_find_best_partition, METH_VARARGS, NULL}, {NULL, NULL} }; static PyTypeObject RangeMedianType = { #if PY_MAJOR_VERSION >= 3 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, #endif "RangeMedian", sizeof(RangeMedianObject), 0, (destructor)RangeMedian_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare / tp_reserved 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags NULL, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext RangeMedian_methods, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset (initproc)RangeMedian_init, // tp_init 0, // tp_alloc RangeMedian_new, // tp_new 0, // tp_free 0, // tp_is_gc 0, // tp_bases 0, // tp_mro 0, // tp_cache 0, // tp_subclasses 0, // tp_weaklist 0, // tp_del 0, // tp_version_tag }; static PyTypeObject *RangeMedian_init_type(PyObject *m) { #if PY_MAJOR_VERSION < 3 RangeMedianType.ob_type = &PyType_Type; #endif if (PyType_Ready(&RangeMedianType) < 0) { return NULL; } if (PyModule_AddObject(m, "RangeMedian", (PyObject *)&RangeMedianType) == -1) { return NULL; } return &RangeMedianType; } // // Module initialization. // EXTERN_C_BEGIN #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_rangemedian", NULL, 0, NULL, NULL, NULL, NULL, NULL }; PyObject *PyInit__rangemedian(void) { PyObject *m; m = PyModule_Create(&moduledef); if (m == NULL) { return NULL; } if (RangeMedian_init_type(m) == NULL) { return NULL; } return m; } #else PyMODINIT_FUNC init_rangemedian(void) { PyObject *m; m = Py_InitModule("_rangemedian", NULL); if (m == NULL) { return; } RangeMedian_init_type(m); } #endif EXTERN_C_END <commit_msg>_rangemedian: implement weights<commit_after>// Licensed under a 3-clause BSD style license - see LICENSE.rst // Fast range median distance computations for dataset `y`: // // mu(l, r) = median(y[l:r+1]) // dist(l, r) = sum(abs(x - mu(l, r)) for x in y[l:r+1]) // // and an implementation of the find-best-partition dynamic program. // // We don't implement a rolling median computation, on the assumption that // accesses are concentrated on small windows in the data. #include <vector> #include <queue> #include <limits> #include <map> #include <algorithm> #include <utility> #include <Python.h> #define EXTERN_C_BEGIN extern "C" { #define EXTERN_C_END } // // Median computation. // template <class const_iterator> void compute_weighted_median(const_iterator start, const_iterator end, double *mu, double *dist) { std::vector<std::pair<double,double> > tmp; std::vector<std::pair<double,double> >::iterator it; double midpoint, wsum; if (start == end) { *mu = 0; *dist = 0; return; } tmp.insert(tmp.end(), start, end); std::sort(tmp.begin(), tmp.end()); midpoint = 0; for (it = tmp.begin(); it != tmp.end(); ++it) { midpoint += it->second; } midpoint /= 2; wsum = 0; for (it = tmp.begin(); it != tmp.end(); ++it) { wsum += it->second; if (wsum >= midpoint) { break; } } if (it != tmp.end()) { *mu = it->first; if (wsum == midpoint) { ++it; if (it != tmp.end()) { *mu = (it->first + *mu) / 2; } } } else { // Error condition, maybe some floating point summation issue --it; *mu = it->first; } *dist = 0; for (const_iterator it = start; it < end; ++it) { *dist += it->second * fabs(it->first - *mu); } } // // Cache for cache[left,right] == (mu, dist) // class Cache { private: struct Item { size_t left, right; double mu, dist; }; std::vector<Item> items_; size_t idx(size_t left, size_t right) const { // Enumeration of pairs size_t n = right - left; n = (n + left) * (n + left + 1) / 2 + n; return n % items_.size(); } public: Cache(size_t size) : items_(size) { std::vector<Item>::iterator it; for (it = items_.begin(); it < items_.end(); ++it) { it->left = -1; } } bool get(size_t left, size_t right, double *mu, double *dist) const { size_t i = idx(left, right); if (items_[i].left == left && items_[i].right == right) { *mu = items_[i].mu; *dist = items_[i].dist; return true; } return false; } void set(size_t left, size_t right, double mu, double dist) { size_t i = idx(left, right); items_[i].left = left; items_[i].right = right; items_[i].mu = mu; items_[i].dist = dist; } }; // // RangeMedian object. // typedef struct { PyObject_HEAD std::vector<std::pair<double,double> > *y; Cache *cache; } RangeMedianObject; PyObject *RangeMedian_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { RangeMedianObject *self; self = (RangeMedianObject*)type->tp_alloc(type, 0); self->y = NULL; self->cache = NULL; return (PyObject*)self; } int RangeMedian_init(RangeMedianObject *self, PyObject *args, PyObject *kwds) { static const char *kwlist[] = {"y", "w", NULL}; PyObject *y_obj, *w_obj; Py_ssize_t size, wsize, k; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!", (char**)kwlist, &PyList_Type, &y_obj, &PyList_Type, &w_obj)) { return -1; } size = PyList_GET_SIZE(y_obj); wsize = PyList_GET_SIZE(w_obj); if (wsize != size) { PyErr_SetString(PyExc_ValueError, "y and w must have same length"); return -1; } try { self->y = new std::vector<std::pair<double,double> >(size); // Multiplier based on hardcoded constant sizes in step_detect.py, about // this many accesses expected --- but prefer primes due to a modulo // calculation in the cache. self->cache = new Cache(37*size + 401); } catch (const std::bad_alloc&) { PyErr_SetString(PyExc_MemoryError, "Allocating memory failed"); return -1; } for (k = 0; k < size; ++k) { PyObject *x, *wx; x = PyNumber_Float(PyList_GET_ITEM(y_obj, k)); if (x == NULL || !PyFloat_Check(x)) { Py_XDECREF(x); return -1; } wx = PyNumber_Float(PyList_GET_ITEM(w_obj, k)); if (wx == NULL || !PyFloat_Check(wx)) { Py_XDECREF(x); Py_XDECREF(wx); return -1; } (*self->y)[k] = std::make_pair(PyFloat_AS_DOUBLE(x), PyFloat_AS_DOUBLE(wx)); Py_DECREF(x); Py_DECREF(wx); } return 0; } static void RangeMedian_dealloc(RangeMedianObject *self) { delete self->y; delete self->cache; Py_TYPE(self)->tp_free((PyObject*)self); } static int RangeMedian_mu_dist(RangeMedianObject *self, Py_ssize_t left, Py_ssize_t right, double *mu, double *dist) { Py_ssize_t size = (Py_ssize_t)self->y->size(); if (left < 0 || right < 0 || left >= size || right >= size) { PyErr_SetString(PyExc_ValueError, "argument out of range"); return -1; } if (!self->cache->get(left, right, mu, dist)) { compute_weighted_median(self->y->begin() + left, self->y->begin() + right + 1, mu, dist); self->cache->set(left, right, *mu, *dist); } return 0; } static PyObject *RangeMedian_mu(RangeMedianObject *self, PyObject *args) { Py_ssize_t left, right; double mu = 0, dist; if (!PyArg_ParseTuple(args, "nn", &left, &right)) { return NULL; } if (RangeMedian_mu_dist(self, left, right, &mu, &dist) == -1) { return NULL; } return PyFloat_FromDouble(mu); } static PyObject *RangeMedian_dist(RangeMedianObject *self, PyObject *args) { Py_ssize_t left, right; double mu, dist = 0; if (!PyArg_ParseTuple(args, "nn", &left, &right)) { return NULL; } if (RangeMedian_mu_dist(self, left, right, &mu, &dist) == -1) { return NULL; } return PyFloat_FromDouble(dist); } static PyObject *RangeMedian_find_best_partition(RangeMedianObject *self, PyObject *args) { Py_ssize_t min_size, max_size, min_pos, max_pos; double gamma; Py_ssize_t size; if (!PyArg_ParseTuple(args, "dnnnn", &gamma, &min_size, &max_size, &min_pos, &max_pos)) { return NULL; } size = self->y->size(); if (!(0 < min_size && min_size <= max_size && 0 <= min_pos && min_pos <= max_pos && max_pos <= size)) { PyErr_SetString(PyExc_ValueError, "invalid input indices"); return NULL; } double inf = std::numeric_limits<double>::infinity(); std::vector<double> B(max_pos - min_pos + 1); std::vector<Py_ssize_t> p(max_pos - min_pos); B[0] = -gamma; for (Py_ssize_t right = min_pos; right < max_pos; ++right) { B[right + 1 - min_pos] = inf; Py_ssize_t aa = std::max(right + 1 - max_size, min_pos); Py_ssize_t bb = std::max(right + 1 - min_size + 1, min_pos); for (Py_ssize_t left = aa; left < bb; ++left) { double mu, dist; if (RangeMedian_mu_dist(self, left, right, &mu, &dist) == -1) { return NULL; } double b = B[left - min_pos] + gamma + dist; if (b <= B[right + 1 - min_pos]) { B[right + 1 - min_pos] = b; p[right - min_pos] = left - 1; } } } PyObject *p_list; p_list = PyList_New(p.size()); if (p_list == NULL) { return NULL; } for (Py_ssize_t k = 0; k < (Py_ssize_t)p.size(); ++k) { #if PY_MAJOR_VERSION >= 3 PyObject *num = PyLong_FromSsize_t(p[k]); #else PyObject *num = PyInt_FromSsize_t(p[k]); #endif if (num == NULL) { Py_DECREF(p_list); return NULL; } PyList_SET_ITEM(p_list, k, num); } return p_list; } // // RangeMedian type. // static PyMethodDef RangeMedian_methods[] = { {"mu", (PyCFunction)RangeMedian_mu, METH_VARARGS, NULL}, {"dist", (PyCFunction)RangeMedian_dist, METH_VARARGS, NULL}, {"find_best_partition", (PyCFunction)RangeMedian_find_best_partition, METH_VARARGS, NULL}, {NULL, NULL} }; static PyTypeObject RangeMedianType = { #if PY_MAJOR_VERSION >= 3 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, #endif "RangeMedian", sizeof(RangeMedianObject), 0, (destructor)RangeMedian_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare / tp_reserved 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags NULL, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext RangeMedian_methods, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset (initproc)RangeMedian_init, // tp_init 0, // tp_alloc RangeMedian_new, // tp_new 0, // tp_free 0, // tp_is_gc 0, // tp_bases 0, // tp_mro 0, // tp_cache 0, // tp_subclasses 0, // tp_weaklist 0, // tp_del 0, // tp_version_tag }; static PyTypeObject *RangeMedian_init_type(PyObject *m) { #if PY_MAJOR_VERSION < 3 RangeMedianType.ob_type = &PyType_Type; #endif if (PyType_Ready(&RangeMedianType) < 0) { return NULL; } if (PyModule_AddObject(m, "RangeMedian", (PyObject *)&RangeMedianType) == -1) { return NULL; } return &RangeMedianType; } // // Module initialization. // EXTERN_C_BEGIN #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_rangemedian", NULL, 0, NULL, NULL, NULL, NULL, NULL }; PyObject *PyInit__rangemedian(void) { PyObject *m; m = PyModule_Create(&moduledef); if (m == NULL) { return NULL; } if (RangeMedian_init_type(m) == NULL) { return NULL; } return m; } #else PyMODINIT_FUNC init_rangemedian(void) { PyObject *m; m = Py_InitModule("_rangemedian", NULL); if (m == NULL) { return; } RangeMedian_init_type(m); } #endif EXTERN_C_END <|endoftext|>
<commit_before>#include "TestBlockLandApplication.h" #include <OIS.h> #include <iostream> const BlockInfo BLOCKINFO[] = { { BlockType::Air, "Air", Ogre::ColourValue(1.0, 1.0, 1.0) }, { BlockType::Grass, "Grass", Ogre::ColourValue(0.0, 0.5, 0.0) }, { BlockType::Soil, "Soil", Ogre::ColourValue(0.5, 0.3, 0.0) }, { BlockType::Rock, "Rock", Ogre::ColourValue(0.5, 0.5, 0.5) } }; TestBlockLandApplication::TestBlockLandApplication() : _worldXSize(-1), _worldZSize(-1), _chunkID(1), _blocks(nullptr) { } TestBlockLandApplication::~TestBlockLandApplication() { delete[] _blocks; } void TestBlockLandApplication::initWorldBlocksCaves() { // Change these to increase/decrease the cave size scale const float delta = 0.01f; const float valueLimit = 0.80f; float nx, ny, nz; for (int y = 0, ny = 0.0f; y < _worldHeight; ++y, ny += delta) { for (int z = 0, nz = 0.0f; z < _worldZSize; ++z, nz += delta) { for (int x = 0, nx = 0.0f; x < _worldXSize; ++x, nx += delta) { // const float value = NoiseSource.GetValue(nx, ny, nz); // if (value > valueLimit) // getBlock(x, y, z).type = BlockType::Air; } } } } void TestBlockLandApplication::initWorldBlocksLight() { const LightValue deltaLight = 16; for (int z = 0; z < _worldZSize; ++z) { for (int x = 0; x < _worldXSize; ++x) { LightValue light = 255; for (int y = _worldHeight - 1; y >= 0; --y) { getBlockLight(x, y, z) = light; if (getBlock(x, y, z).type != BlockType::Air) { if (light >= deltaLight) light -= deltaLight; else light = 0; } } } } } void TestBlockLandApplication::createChunk(const int startX, const int startY, const int startZ) { Ogre::ManualObject* meshChunk = new Ogre::ManualObject("MeshMatChunk" + Ogre::StringConverter::toString(_chunkID)); meshChunk->begin("BaseWhiteNoLighting"); /* Only create visible faces of chunk */ const BlockType defaultBlock = BlockType::Grass; const int sx = 0; const int sy = 0; const int sz = 0; int vertexIndex = 0; for (int z = startZ; z < CHUNK_SIZE + startZ; ++z) { for (int y = startY; y < CHUNK_SIZE + startY; ++y) { for (int x = startX; x < CHUNK_SIZE + startX; ++x) { const BlockType type = getBlock(x, y, z).type; if (type == BlockType::Air) continue; const float blockLightX = getBlockLight(x, y, z) / 255.0f; const float blockLightZ = blockLightX * 0.9f; const float blockLightY = blockLightX * 0.8f; BlockType blockType = defaultBlock; if (x > sx) blockType = getBlock(x - 1, y, z).type; const Ogre::ColourValue& color = BLOCKINFO[static_cast<int>(type)].color; if (blockType == BlockType::Air) { const Ogre::Vector3 normal(-1, 0, 0); mesh(meshChunk, normal, color * blockLightX, vertexIndex, x, y, z + 1, x, y + 1, z + 1, x, y + 1, z, x, y, z); } blockType = defaultBlock; if (x < sx + _worldXSize - 1) blockType = getBlock(x + 1, y, z).type; if (blockType == BlockType::Air) { const Ogre::Vector3 normal(1, 0, 0); mesh(meshChunk, normal, color * blockLightX, vertexIndex, x + 1, y, z, x + 1, y + 1, z, x + 1, y + 1, z + 1, x + 1, y, z + 1); } blockType = defaultBlock; if (y > sy) blockType = getBlock(x, y - 1, z).type; if (blockType == BlockType::Air) { const Ogre::Vector3 normal(0, -1, 0); mesh(meshChunk, normal, color * blockLightY, vertexIndex, x, y, z, x + 1, y, z, x + 1, y, z + 1, x, y, z + 1); } blockType = defaultBlock; if (y < sy + _worldHeight - 1) blockType = getBlock(x, y + 1, z).type; if (blockType == BlockType::Air) { const Ogre::Vector3 normal(0, 1, 0); mesh(meshChunk, normal, color * blockLightY, vertexIndex, x, y + 1, z + 1, x + 1, y + 1, z + 1, x + 1, y + 1, z, x, y + 1, z); } blockType = defaultBlock; if (z > sz) blockType = getBlock(x, y, z - 1).type; if (blockType == BlockType::Air) { const Ogre::Vector3 normal(0, 0, -1); mesh(meshChunk, normal, color * blockLightZ, vertexIndex, x, y + 1, z, x + 1, y + 1, z, x + 1, y, z, x, y, z); } blockType = defaultBlock; if (z < sz + _worldZSize - 1) blockType = getBlock(x, y, z + 1).type; if (blockType == BlockType::Air) { const Ogre::Vector3 normal(0, 0, 1); mesh(meshChunk, normal, color * blockLightZ, vertexIndex, x, y, z + 1, x + 1, y, z + 1, x + 1, y + 1, z + 1, x, y + 1, z + 1); } } } } meshChunk->end(); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(meshChunk); ++_chunkID; } Ogre::MaterialPtr TestBlockLandApplication::createSolidTexture(const Ogre::String& pName, const Ogre::ColourValue& color) { Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create(pName, "General"); Ogre::Technique* tech = mat->getTechnique(0); tech->setLightingEnabled(true); Ogre::Pass* pass = tech->getPass(0); Ogre::TextureUnitState* tex = pass->createTextureUnitState(); tex->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, color); return mat; } void TestBlockLandApplication::createWorldChunks() { for (int z = 0; z < _worldZSize; z += CHUNK_SIZE) { for (int y = 0; y < _worldHeight; y += CHUNK_SIZE) { for (int x = 0; x < _worldXSize; x += CHUNK_SIZE) { createChunk(x, y, z); } } } } void TestBlockLandApplication::createScene() { mSceneMgr->setSkyDome(true, "Examples/CloudySky", 2, 8, 100); mSceneMgr->setFog(Ogre::FOG_LINEAR, Ogre::ColourValue(0.8, 0.8, 1), 0.05, 0.0, 200); mCamera->setFarClipDistance(256); mCamera->setNearClipDistance(0.01); mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5)); Ogre::Light* l = mSceneMgr->createLight("MainLight"); l->setPosition(20, 80, 50); initWorldBlocksTerrain(); Ogre::LogManager::getSingletonPtr()->logMessage("*** initWorldBlocksCaves ***"); //initWorldBlocksCaves(); Ogre::LogManager::getSingletonPtr()->logMessage("*** initWorldBlocksLight ***"); initWorldBlocksLight(); Ogre::LogManager::getSingletonPtr()->logMessage("*** createWorldChunks ***"); createWorldChunks(); Ogre::LogManager::getSingletonPtr()->logMessage("*** done ***"); } TArray2D<TVec4D<float>> TestBlockLandApplication::createHeightMapImage() { CMWC4096 rnd; rnd.setSeedTime(); /** * Generating plains */ CImplicitFractal fractalPlains(anl::EFractalTypes::FBM, anl::GRADIENT, anl::QUINTIC); fractalPlains.setNumOctaves(2); fractalPlains.setFrequency(1); fractalPlains.setSeed(rnd.get()); CImplicitAutoCorrect autoCorrectPlains(0.0, 1.0); autoCorrectPlains.setSource(&fractalPlains); CImplicitScaleOffset scaleOffsetPlains(0.1, 0.0); scaleOffsetPlains.setSource(&autoCorrectPlains); /** * Generating highlands */ CImplicitFractal fractalHighlands(anl::RIDGEDMULTI, anl::GRADIENT, anl::QUINTIC); fractalHighlands.setNumOctaves(4); fractalHighlands.setFrequency(1); fractalHighlands.setSeed(rnd.get()); CImplicitAutoCorrect autoCorrectHighlands(0.0, 1.2); autoCorrectHighlands.setSource(&fractalHighlands); CImplicitScaleOffset scaleOffsetHighlands(0.75, 0.0); scaleOffsetHighlands.setSource(&autoCorrectHighlands); /** * Generating mountains */ CImplicitFractal fractalMountains(anl::BILLOW, anl::GRADIENT, anl::QUINTIC); fractalMountains.setNumOctaves(8); fractalMountains.setFrequency(0.1); fractalMountains.setSeed(rnd.get()); CImplicitAutoCorrect autoCorrectMountains(0.0, 2.0); autoCorrectMountains.setSource(&fractalMountains); CImplicitScaleOffset scaleOffsetMountains(2.0, 0.0); scaleOffsetMountains.setSource(&autoCorrectMountains); /*CImplicitSelect selection; selection.setLowSource(&scaleOffsetHighlands); selection.setHighSource(&scaleOffsetMountains); selection.setThreshold(0.1); selection.setFalloff(0.15);*/ CRGBACompositeChannels composite(anl::RGB); composite.setRedSource(&scaleOffsetPlains); composite.setGreenSource(&scaleOffsetPlains); composite.setBlueSource(&scaleOffsetPlains); composite.setAlphaSource(1.0); TArray2D<TVec4D<float>> img(256, 256); SMappingRanges ranges; mapRGBA2D(anl::SEAMLESS_NONE, img ,composite ,ranges, 0); //Just for debugging purpose saveRGBAArray((char*)"heightmap.tga", &img); return img; } void TestBlockLandApplication::initWorldBlocksTerrain() { Ogre::LogManager::getSingletonPtr()->logMessage("*** initWorldBlocksTerrain: create textures ***"); const int length = lengthof(BLOCKINFO); for (int i = 1; i < length; ++i) { const BlockInfo& info = BLOCKINFO[i]; createSolidTexture(info.name, info.color); } TArray2D<TVec4D<float>> map = createHeightMapImage(); _worldXSize = map.width(); _worldZSize = map.height(); std::ostringstream ss; ss << "*** initWorldBlocksTerrain: size " << _worldXSize << ":" << _worldZSize << "***"; _blocks = new Block[_worldZSize * _worldXSize * _worldHeight]; memset(_blocks, 0, sizeof(Block) * _worldZSize * _worldXSize * _worldHeight); Ogre::LogManager::getSingletonPtr()->logMessage(ss.str().c_str()); for (int z = 0; z < _worldZSize; ++z) { for (int x = 0; x < _worldXSize; ++x) { //TODO: scale into world height TVec4D<float> color = map.get(x, z); const int height = static_cast<int>(((color.get_x() + color.get_y() + color.get_z()) / 3.0f) * 255.0f); for (int y = 0; y < height; ++y) { assert(height < _worldHeight); getBlock(x, y, z).type = getLayerType(height); } } } } #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 #define WIN32_LEAN_AND_MEAN #include "windows.h" #endif #ifdef __cplusplus extern "C" { #endif #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT) #else int main(int argc, char *argv[]) #endif { // Create application object TestBlockLandApplication app; try { app.go(); } catch (Ogre::Exception& e) { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 MessageBox(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL); #else std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl; #endif } return 0; } #ifdef __cplusplus } #endif <commit_msg>* merged the 'plains'-noise and the 'highlands'-noise<commit_after>#include "TestBlockLandApplication.h" #include <OIS.h> #include <iostream> const BlockInfo BLOCKINFO[] = { { BlockType::Air, "Air", Ogre::ColourValue(1.0, 1.0, 1.0) }, { BlockType::Grass, "Grass", Ogre::ColourValue(0.0, 0.5, 0.0) }, { BlockType::Soil, "Soil", Ogre::ColourValue(0.5, 0.3, 0.0) }, { BlockType::Rock, "Rock", Ogre::ColourValue(0.5, 0.5, 0.5) } }; TestBlockLandApplication::TestBlockLandApplication() : _worldXSize(-1), _worldZSize(-1), _chunkID(1), _blocks(nullptr) { } TestBlockLandApplication::~TestBlockLandApplication() { delete[] _blocks; } void TestBlockLandApplication::initWorldBlocksCaves() { // Change these to increase/decrease the cave size scale const float delta = 0.01f; const float valueLimit = 0.80f; float nx, ny, nz; for (int y = 0, ny = 0.0f; y < _worldHeight; ++y, ny += delta) { for (int z = 0, nz = 0.0f; z < _worldZSize; ++z, nz += delta) { for (int x = 0, nx = 0.0f; x < _worldXSize; ++x, nx += delta) { // const float value = NoiseSource.GetValue(nx, ny, nz); // if (value > valueLimit) // getBlock(x, y, z).type = BlockType::Air; } } } } void TestBlockLandApplication::initWorldBlocksLight() { const LightValue deltaLight = 16; for (int z = 0; z < _worldZSize; ++z) { for (int x = 0; x < _worldXSize; ++x) { LightValue light = 255; for (int y = _worldHeight - 1; y >= 0; --y) { getBlockLight(x, y, z) = light; if (getBlock(x, y, z).type != BlockType::Air) { if (light >= deltaLight) light -= deltaLight; else light = 0; } } } } } void TestBlockLandApplication::createChunk(const int startX, const int startY, const int startZ) { Ogre::ManualObject* meshChunk = new Ogre::ManualObject("MeshMatChunk" + Ogre::StringConverter::toString(_chunkID)); meshChunk->begin("BaseWhiteNoLighting"); /* Only create visible faces of chunk */ const BlockType defaultBlock = BlockType::Grass; const int sx = 0; const int sy = 0; const int sz = 0; int vertexIndex = 0; for (int z = startZ; z < CHUNK_SIZE + startZ; ++z) { for (int y = startY; y < CHUNK_SIZE + startY; ++y) { for (int x = startX; x < CHUNK_SIZE + startX; ++x) { const BlockType type = getBlock(x, y, z).type; if (type == BlockType::Air) continue; const float blockLightX = getBlockLight(x, y, z) / 255.0f; const float blockLightZ = blockLightX * 0.9f; const float blockLightY = blockLightX * 0.8f; BlockType blockType = defaultBlock; if (x > sx) blockType = getBlock(x - 1, y, z).type; const Ogre::ColourValue& color = BLOCKINFO[static_cast<int>(type)].color; if (blockType == BlockType::Air) { const Ogre::Vector3 normal(-1, 0, 0); mesh(meshChunk, normal, color * blockLightX, vertexIndex, x, y, z + 1, x, y + 1, z + 1, x, y + 1, z, x, y, z); } blockType = defaultBlock; if (x < sx + _worldXSize - 1) blockType = getBlock(x + 1, y, z).type; if (blockType == BlockType::Air) { const Ogre::Vector3 normal(1, 0, 0); mesh(meshChunk, normal, color * blockLightX, vertexIndex, x + 1, y, z, x + 1, y + 1, z, x + 1, y + 1, z + 1, x + 1, y, z + 1); } blockType = defaultBlock; if (y > sy) blockType = getBlock(x, y - 1, z).type; if (blockType == BlockType::Air) { const Ogre::Vector3 normal(0, -1, 0); mesh(meshChunk, normal, color * blockLightY, vertexIndex, x, y, z, x + 1, y, z, x + 1, y, z + 1, x, y, z + 1); } blockType = defaultBlock; if (y < sy + _worldHeight - 1) blockType = getBlock(x, y + 1, z).type; if (blockType == BlockType::Air) { const Ogre::Vector3 normal(0, 1, 0); mesh(meshChunk, normal, color * blockLightY, vertexIndex, x, y + 1, z + 1, x + 1, y + 1, z + 1, x + 1, y + 1, z, x, y + 1, z); } blockType = defaultBlock; if (z > sz) blockType = getBlock(x, y, z - 1).type; if (blockType == BlockType::Air) { const Ogre::Vector3 normal(0, 0, -1); mesh(meshChunk, normal, color * blockLightZ, vertexIndex, x, y + 1, z, x + 1, y + 1, z, x + 1, y, z, x, y, z); } blockType = defaultBlock; if (z < sz + _worldZSize - 1) blockType = getBlock(x, y, z + 1).type; if (blockType == BlockType::Air) { const Ogre::Vector3 normal(0, 0, 1); mesh(meshChunk, normal, color * blockLightZ, vertexIndex, x, y, z + 1, x + 1, y, z + 1, x + 1, y + 1, z + 1, x, y + 1, z + 1); } } } } meshChunk->end(); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(meshChunk); ++_chunkID; } Ogre::MaterialPtr TestBlockLandApplication::createSolidTexture(const Ogre::String& pName, const Ogre::ColourValue& color) { Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create(pName, "General"); Ogre::Technique* tech = mat->getTechnique(0); tech->setLightingEnabled(true); Ogre::Pass* pass = tech->getPass(0); Ogre::TextureUnitState* tex = pass->createTextureUnitState(); tex->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, color); return mat; } void TestBlockLandApplication::createWorldChunks() { for (int z = 0; z < _worldZSize; z += CHUNK_SIZE) { for (int y = 0; y < _worldHeight; y += CHUNK_SIZE) { for (int x = 0; x < _worldXSize; x += CHUNK_SIZE) { createChunk(x, y, z); } } } } void TestBlockLandApplication::createScene() { mSceneMgr->setSkyDome(true, "Examples/CloudySky", 2, 8, 100); mSceneMgr->setFog(Ogre::FOG_LINEAR, Ogre::ColourValue(0.8, 0.8, 1), 0.05, 0.0, 200); mCamera->setFarClipDistance(256); mCamera->setNearClipDistance(0.01); mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5)); Ogre::Light* l = mSceneMgr->createLight("MainLight"); l->setPosition(20, 80, 50); initWorldBlocksTerrain(); Ogre::LogManager::getSingletonPtr()->logMessage("*** initWorldBlocksCaves ***"); //initWorldBlocksCaves(); Ogre::LogManager::getSingletonPtr()->logMessage("*** initWorldBlocksLight ***"); initWorldBlocksLight(); Ogre::LogManager::getSingletonPtr()->logMessage("*** createWorldChunks ***"); createWorldChunks(); Ogre::LogManager::getSingletonPtr()->logMessage("*** done ***"); } TArray2D<TVec4D<float>> TestBlockLandApplication::createHeightMapImage() { CMWC4096 rnd; rnd.setSeedTime(); CImplicitGradient groundGradient; groundGradient.setGradient(0.0, 0.0, 1.0, 1.0, 0.0, 0.0); /** * Generating plains */ CImplicitFractal fractalPlains(anl::EFractalTypes::FBM, anl::GRADIENT, anl::QUINTIC); fractalPlains.setNumOctaves(2); fractalPlains.setFrequency(1.0); fractalPlains.setSeed(rnd.get()); CImplicitAutoCorrect autoCorrectPlains(0.0, 1.0); autoCorrectPlains.setSource(&fractalPlains); CImplicitScaleOffset scaleOffsetPlains(0.125, 0.0); scaleOffsetPlains.setSource(&autoCorrectPlains); /** * Generating highlands */ CImplicitFractal fractalHighlands(anl::RIDGEDMULTI, anl::GRADIENT, anl::QUINTIC); fractalHighlands.setNumOctaves(4); fractalHighlands.setFrequency(0.3); fractalHighlands.setSeed(rnd.get()); CImplicitAutoCorrect autoCorrectHighlands(-0.5, 0.75); autoCorrectHighlands.setSource(&fractalHighlands); CImplicitScaleOffset scaleOffsetHighlands(0.75, 0.5); scaleOffsetHighlands.setSource(&autoCorrectHighlands); /** * Generating mountains */ CImplicitFractal fractalMountains(anl::BILLOW, anl::GRADIENT, anl::QUINTIC); fractalMountains.setNumOctaves(8); fractalMountains.setFrequency(0.01); fractalMountains.setSeed(rnd.get()); CImplicitAutoCorrect autoCorrectMountains(1.2, 2.0); autoCorrectMountains.setSource(&fractalMountains); CImplicitScaleOffset scaleOffsetMountains(2.0, 0.0); scaleOffsetMountains.setSource(&autoCorrectMountains); /** * Merge terrains */ CImplicitFractal terrainTypeFractal(anl::FBM, anl::GRADIENT, anl::QUINTIC); terrainTypeFractal.setNumOctaves(3); terrainTypeFractal.setFrequency(0.125); terrainTypeFractal.setSeed(rnd.get()); CImplicitAutoCorrect terrainAutoCorrect(-1.0, 1.0); terrainAutoCorrect.setSource(&terrainTypeFractal); CImplicitScaleDomain terrainTypeYScale; terrainTypeYScale.setSource(&terrainAutoCorrect); terrainTypeYScale.setScale(1.0, 0.0); CImplicitCache terrainTypeCache; terrainTypeCache.setSource(&terrainTypeYScale); CImplicitSelect selection; selection.setLowSource(&scaleOffsetPlains); selection.setHighSource(&scaleOffsetHighlands); selection.setControlSource(&terrainTypeYScale); selection.setThreshold(0.1); selection.setFalloff(0.3); /** * Create heigthmap */ CRGBACompositeChannels composite(anl::RGB); composite.setRedSource(&selection); composite.setGreenSource(&selection); composite.setBlueSource(&selection); composite.setAlphaSource(1.0); TArray2D<TVec4D<float>> img(256, 256); SMappingRanges ranges; mapRGBA2D(anl::SEAMLESS_NONE, img ,composite ,ranges, 0); //Just for debugging purpose saveRGBAArray((char*)"heightmap.tga", &img); return img; } void TestBlockLandApplication::initWorldBlocksTerrain() { Ogre::LogManager::getSingletonPtr()->logMessage("*** initWorldBlocksTerrain: create textures ***"); const int length = lengthof(BLOCKINFO); for (int i = 1; i < length; ++i) { const BlockInfo& info = BLOCKINFO[i]; createSolidTexture(info.name, info.color); } TArray2D<TVec4D<float>> map = createHeightMapImage(); _worldXSize = map.width(); _worldZSize = map.height(); std::ostringstream ss; ss << "*** initWorldBlocksTerrain: size " << _worldXSize << ":" << _worldZSize << "***"; _blocks = new Block[_worldZSize * _worldXSize * _worldHeight]; memset(_blocks, 0, sizeof(Block) * _worldZSize * _worldXSize * _worldHeight); Ogre::LogManager::getSingletonPtr()->logMessage(ss.str().c_str()); for (int z = 0; z < _worldZSize; ++z) { for (int x = 0; x < _worldXSize; ++x) { //TODO: scale into world height TVec4D<float> color = map.get(x, z); const int height = static_cast<int>(((color.get_x() + color.get_y() + color.get_z()) / 3.0f) * 255.0f); for (int y = 0; y < height; ++y) { assert(height < _worldHeight); getBlock(x, y, z).type = getLayerType(height); } } } } #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 #define WIN32_LEAN_AND_MEAN #include "windows.h" #endif #ifdef __cplusplus extern "C" { #endif #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT) #else int main(int argc, char *argv[]) #endif { // Create application object TestBlockLandApplication app; try { app.go(); } catch (Ogre::Exception& e) { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 MessageBox(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL); #else std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl; #endif } return 0; } #ifdef __cplusplus } #endif <|endoftext|>
<commit_before>#ifndef RPT_XMLSUBDOCUMENT_HXX #define RPT_XMLSUBDOCUMENT_HXX /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlSubDocument.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2007-07-09 11:56:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef RPT_XMLREPORTELEMENTBASE_HXX #include "xmlReportElementBase.hxx" #endif #ifndef _COM_SUN_STAR_REPORT_XREPORTDEFINITION_HPP_ #include <com/sun/star/report/XReportDefinition.hpp> #endif #include <vector> namespace rptxml { class ORptFilter; class OXMLSubDocument : public OXMLReportElementBase { ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition > m_xComponent; ::std::vector< ::rtl::OUString> m_aMasterFields; ::std::vector< ::rtl::OUString> m_aDetailFields; OXMLSubDocument(const OXMLSubDocument&); void operator =(const OXMLSubDocument&); public: OXMLSubDocument( ORptFilter& rImport ,sal_uInt16 nPrfx ,const ::rtl::OUString& rLName ,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition >& _xComponent ,OXMLTable* _pContainer); virtual ~OXMLSubDocument(); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); virtual void EndElement(); void addFieldPair(const ::std::pair< ::rtl::OUString,::rtl::OUString >& _aPair); }; // ----------------------------------------------------------------------------- } // namespace rptxml // ----------------------------------------------------------------------------- #endif // RPT_XMLSubDocument_HXX <commit_msg>INTEGRATION: CWS rptchart01_DEV300 (1.2.70); FILE MERGED 2008/02/13 07:12:30 oj 1.2.70.2: #i85225# impl sub-document 2008/01/25 13:56:45 oj 1.2.70.1: #i85225# removed<commit_after>#ifndef RPT_XMLSUBDOCUMENT_HXX #define RPT_XMLSUBDOCUMENT_HXX /************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlSubDocument.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2008-03-05 18:06:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef RPT_XMLREPORTELEMENTBASE_HXX #include "xmlReportElementBase.hxx" #endif #include <com/sun/star/report/XReportComponent.hpp> #include <vector> namespace rptxml { class ORptFilter; class OXMLSubDocument : public OXMLReportElementBase, public IMasterDetailFieds { ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> m_xComponent; ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> m_xFake; ::std::vector< ::rtl::OUString> m_aMasterFields; ::std::vector< ::rtl::OUString> m_aDetailFields; sal_Int32 m_nCurrentCount; bool m_bContainsShape; OXMLSubDocument(const OXMLSubDocument&); void operator =(const OXMLSubDocument&); virtual SvXMLImportContext* _CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); public: OXMLSubDocument( ORptFilter& rImport ,sal_uInt16 nPrfx ,const ::rtl::OUString& rLName ,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent >& _xComponent ,OXMLTable* _pContainer); virtual ~OXMLSubDocument(); virtual void EndElement(); virtual void addMasterDetailPair(const ::std::pair< ::rtl::OUString,::rtl::OUString >& _aPair); }; // ----------------------------------------------------------------------------- } // namespace rptxml // ----------------------------------------------------------------------------- #endif // RPT_XMLSubDocument_HXX <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file provides the embedder's side of random webkit glue functions. #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #include <wininet.h> #endif #include "base/clipboard.h" #include "base/scoped_clipboard_writer.h" #include "base/string_util.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/render_messages.h" #include "chrome/common/resource_bundle.h" #include "chrome/plugin/npobject_util.h" #include "chrome/renderer/net/render_dns_master.h" #include "chrome/renderer/render_process.h" #include "chrome/renderer/render_thread.h" #include "chrome/renderer/render_view.h" #include "chrome/renderer/visitedlink_slave.h" #include "googleurl/src/url_util.h" #include "net/base/mime_util.h" #include "net/base/net_errors.h" #include "webkit/glue/scoped_clipboard_writer_glue.h" #include "webkit/glue/webframe.h" #include "webkit/glue/webkit_glue.h" #include <vector> #include "SkBitmap.h" #if defined(OS_WIN) #include <strsafe.h> // note: per msdn docs, this must *follow* other includes #endif template <typename T, size_t stack_capacity> class ResizableStackArray { public: ResizableStackArray() : cur_buffer_(stack_buffer_), cur_capacity_(stack_capacity) { } ~ResizableStackArray() { FreeHeap(); } T* get() const { return cur_buffer_; } T& operator[](size_t i) { return cur_buffer_[i]; } size_t capacity() const { return cur_capacity_; } void Resize(size_t new_size) { if (new_size < cur_capacity_) return; // already big enough FreeHeap(); cur_capacity_ = new_size; cur_buffer_ = new T[new_size]; } private: // Resets the heap buffer, if any void FreeHeap() { if (cur_buffer_ != stack_buffer_) { delete[] cur_buffer_; cur_buffer_ = stack_buffer_; cur_capacity_ = stack_capacity; } } T stack_buffer_[stack_capacity]; T* cur_buffer_; size_t cur_capacity_; }; #if defined(OS_WIN) // This definition of WriteBitmap uses shared memory to communicate across // processes. void ScopedClipboardWriterGlue::WriteBitmap(const SkBitmap& bitmap) { // do not try to write a bitmap more than once if (shared_buf_) return; size_t buf_size = bitmap.getSize(); gfx::Size size(bitmap.width(), bitmap.height()); // Allocate a shared memory buffer to hold the bitmap bits shared_buf_ = RenderProcess::AllocSharedMemory(buf_size); if (!shared_buf_ || !shared_buf_->Map(buf_size)) { NOTREACHED(); return; } // Copy the bits into shared memory SkAutoLockPixels bitmap_lock(bitmap); memcpy(shared_buf_->memory(), bitmap.getPixels(), buf_size); shared_buf_->Unmap(); Clipboard::ObjectMapParam param1, param2; base::SharedMemoryHandle smh = shared_buf_->handle(); const char* shared_handle = reinterpret_cast<const char*>(&smh); for (size_t i = 0; i < sizeof base::SharedMemoryHandle; i++) param1.push_back(shared_handle[i]); const char* size_data = reinterpret_cast<const char*>(&size); for (size_t i = 0; i < sizeof gfx::Size; i++) param2.push_back(size_data[i]); Clipboard::ObjectMapParams params; params.push_back(param1); params.push_back(param2); objects_[Clipboard::CBF_SMBITMAP] = params; } #endif // Define a destructor that makes IPCs to flush the contents to the // system clipboard. ScopedClipboardWriterGlue::~ScopedClipboardWriterGlue() { if (objects_.empty()) return; #if defined(OS_WIN) if (shared_buf_) { g_render_thread->Send( new ViewHostMsg_ClipboardWriteObjectsSync(objects_)); RenderProcess::FreeSharedMemory(shared_buf_); return; } #endif g_render_thread->Send( new ViewHostMsg_ClipboardWriteObjectsAsync(objects_)); } namespace webkit_glue { // Global variable set during RenderProcess::GlobalInit if video was enabled // and our media libraries were successfully loaded. static bool g_media_player_available = false; void SetMediaPlayerAvailable(bool value) { g_media_player_available = value; } bool IsMediaPlayerAvailable() { return g_media_player_available; } void PrefetchDns(const std::string& hostname) { if (!hostname.empty()) DnsPrefetchCString(hostname.c_str(), hostname.length()); } void PrecacheUrl(const wchar_t* url, int url_length) { // TBD: jar: Need implementation that loads the targetted URL into our cache. // For now, at least prefetch DNS lookup GURL parsed_url(WideToUTF8(std::wstring(url, url_length))); PrefetchDns(parsed_url.host()); } void AppendToLog(const char* file, int line, const char* msg) { logging::LogMessage(file, line).stream() << msg; } bool GetMimeTypeFromExtension(const std::wstring &ext, std::string *mime_type) { if (IsPluginProcess()) return net::GetMimeTypeFromExtension(ext, mime_type); // The sandbox restricts our access to the registry, so we need to proxy // these calls over to the browser process. DCHECK(mime_type->empty()); g_render_thread->Send( new ViewHostMsg_GetMimeTypeFromExtension(ext, mime_type)); return !mime_type->empty(); } bool GetMimeTypeFromFile(const std::wstring &file_path, std::string *mime_type) { if (IsPluginProcess()) return net::GetMimeTypeFromFile(file_path, mime_type); // The sandbox restricts our access to the registry, so we need to proxy // these calls over to the browser process. DCHECK(mime_type->empty()); g_render_thread->Send( new ViewHostMsg_GetMimeTypeFromFile(file_path, mime_type)); return !mime_type->empty(); } bool GetPreferredExtensionForMimeType(const std::string& mime_type, std::wstring* ext) { if (IsPluginProcess()) return net::GetPreferredExtensionForMimeType(mime_type, ext); // The sandbox restricts our access to the registry, so we need to proxy // these calls over to the browser process. DCHECK(ext->empty()); g_render_thread->Send( new ViewHostMsg_GetPreferredExtensionForMimeType(mime_type, ext)); return !ext->empty(); } std::string GetDataResource(int resource_id) { return ResourceBundle::GetSharedInstance().GetDataResource(resource_id); } SkBitmap* GetBitmapResource(int resource_id) { return ResourceBundle::GetSharedInstance().GetBitmapNamed(resource_id); } #if defined(OS_WIN) HCURSOR LoadCursor(int cursor_id) { return ResourceBundle::GetSharedInstance().LoadCursor(cursor_id); } #endif // Clipboard glue Clipboard* ClipboardGetClipboard(){ return NULL; } #if defined(OS_LINUX) // TODO(port): This should replace the method below (the unsigned int is a // windows type). We may need to convert the type of format so it can be sent // over IPC. bool ClipboardIsFormatAvailable(Clipboard::FormatType format) { NOTIMPLEMENTED(); return false; } #endif bool ClipboardIsFormatAvailable(unsigned int format) { bool result; g_render_thread->Send( new ViewHostMsg_ClipboardIsFormatAvailable(format, &result)); return result; } void ClipboardReadText(std::wstring* result) { g_render_thread->Send(new ViewHostMsg_ClipboardReadText(result)); } void ClipboardReadAsciiText(std::string* result) { g_render_thread->Send(new ViewHostMsg_ClipboardReadAsciiText(result)); } void ClipboardReadHTML(std::wstring* markup, GURL* url) { g_render_thread->Send(new ViewHostMsg_ClipboardReadHTML(markup, url)); } GURL GetInspectorURL() { return GURL("chrome-ui://inspector/inspector.html"); } std::string GetUIResourceProtocol() { return "chrome"; } bool GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins) { return g_render_thread->Send( new ViewHostMsg_GetPlugins(refresh, plugins)); } #if defined(OS_WIN) bool EnsureFontLoaded(HFONT font) { LOGFONT logfont; GetObject(font, sizeof(LOGFONT), &logfont); return g_render_thread->Send(new ViewHostMsg_LoadFont(logfont)); } #endif webkit_glue::ScreenInfo GetScreenInfo(gfx::NativeViewId window) { webkit_glue::ScreenInfo results; g_render_thread->Send( new ViewHostMsg_GetScreenInfo(window, &results)); return results; } uint64 VisitedLinkHash(const char* canonical_url, size_t length) { return g_render_thread->visited_link_slave()->ComputeURLFingerprint( canonical_url, length); } bool IsLinkVisited(uint64 link_hash) { #if defined(OS_WIN) return g_render_thread->visited_link_slave()->IsVisited(link_hash); #elif defined(OS_POSIX) // TODO(port): Currently we don't have a HistoryService. This stops the // VisitiedLinkMaster from sucessfully calling Init(). In that case, no // message is ever sent to the renderer with the VisitiedLink shared memory // region and we end up crashing with SIGFPE as we try to hash by taking a // fingerprint mod 0. NOTIMPLEMENTED(); return false; #endif } int ResolveProxyFromRenderThread(const GURL& url, std::string* proxy_result) { // Send a synchronous IPC from renderer process to the browser process to // resolve the proxy. (includes --single-process case). int net_error; bool ipc_ok = g_render_thread->Send( new ViewHostMsg_ResolveProxy(url, &net_error, proxy_result)); return ipc_ok ? net_error : net::ERR_UNEXPECTED; } #ifndef USING_SIMPLE_RESOURCE_LOADER_BRIDGE // Each RenderView has a ResourceDispatcher. In unit tests, this function may // not work properly since there may be a ResourceDispatcher w/o a RenderView. // The WebView's delegate may be null, which typically happens as a WebView is // being closed (but it is also possible that it could be null at other times // since WebView has a SetDelegate method). static ResourceDispatcher* GetResourceDispatcher(WebFrame* frame) { WebViewDelegate* d = frame->GetView()->GetDelegate(); return d ? static_cast<RenderView*>(d)->resource_dispatcher() : NULL; } // static factory function ResourceLoaderBridge* ResourceLoaderBridge::Create( WebFrame* webframe, const std::string& method, const GURL& url, const GURL& policy_url, const GURL& referrer, const std::string& headers, int load_flags, int origin_pid, ResourceType::Type resource_type, bool mixed_content) { // TODO(darin): we need to eliminate the webframe parameter because webkit // does not always supply it (see ResourceHandle::loadResourceSynchronously). // Instead we should add context to ResourceRequest, which will be easy to do // once we merge to the latest WebKit (r23806 at least). if (!webframe) { NOTREACHED() << "no webframe"; return NULL; } ResourceDispatcher* dispatcher = GetResourceDispatcher(webframe); if (!dispatcher) { DLOG(WARNING) << "no resource dispatcher"; return NULL; } return dispatcher->CreateBridge(method, url, policy_url, referrer, headers, load_flags, origin_pid, resource_type, mixed_content, 0); } void SetCookie(const GURL& url, const GURL& policy_url, const std::string& cookie) { g_render_thread->Send(new ViewHostMsg_SetCookie(url, policy_url, cookie)); } std::string GetCookies(const GURL& url, const GURL& policy_url) { std::string cookies; g_render_thread->Send(new ViewHostMsg_GetCookies(url, policy_url, &cookies)); return cookies; } void NotifyCacheStats() { // Update the browser about our cache // NOTE: Since this can be called from the plugin process, we might not have // a RenderThread. Do nothing in that case. if (g_render_thread) g_render_thread->InformHostOfCacheStatsLater(); } #endif // !USING_SIMPLE_RESOURCE_LOADER_BRIDGE } // namespace webkit_glue <commit_msg>Remove VisitedLink NOTIMPLEMENTED() now that history is fixed.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file provides the embedder's side of random webkit glue functions. #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #include <wininet.h> #endif #include "base/clipboard.h" #include "base/scoped_clipboard_writer.h" #include "base/string_util.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/render_messages.h" #include "chrome/common/resource_bundle.h" #include "chrome/plugin/npobject_util.h" #include "chrome/renderer/net/render_dns_master.h" #include "chrome/renderer/render_process.h" #include "chrome/renderer/render_thread.h" #include "chrome/renderer/render_view.h" #include "chrome/renderer/visitedlink_slave.h" #include "googleurl/src/url_util.h" #include "net/base/mime_util.h" #include "net/base/net_errors.h" #include "webkit/glue/scoped_clipboard_writer_glue.h" #include "webkit/glue/webframe.h" #include "webkit/glue/webkit_glue.h" #include <vector> #include "SkBitmap.h" #if defined(OS_WIN) #include <strsafe.h> // note: per msdn docs, this must *follow* other includes #endif template <typename T, size_t stack_capacity> class ResizableStackArray { public: ResizableStackArray() : cur_buffer_(stack_buffer_), cur_capacity_(stack_capacity) { } ~ResizableStackArray() { FreeHeap(); } T* get() const { return cur_buffer_; } T& operator[](size_t i) { return cur_buffer_[i]; } size_t capacity() const { return cur_capacity_; } void Resize(size_t new_size) { if (new_size < cur_capacity_) return; // already big enough FreeHeap(); cur_capacity_ = new_size; cur_buffer_ = new T[new_size]; } private: // Resets the heap buffer, if any void FreeHeap() { if (cur_buffer_ != stack_buffer_) { delete[] cur_buffer_; cur_buffer_ = stack_buffer_; cur_capacity_ = stack_capacity; } } T stack_buffer_[stack_capacity]; T* cur_buffer_; size_t cur_capacity_; }; #if defined(OS_WIN) // This definition of WriteBitmap uses shared memory to communicate across // processes. void ScopedClipboardWriterGlue::WriteBitmap(const SkBitmap& bitmap) { // do not try to write a bitmap more than once if (shared_buf_) return; size_t buf_size = bitmap.getSize(); gfx::Size size(bitmap.width(), bitmap.height()); // Allocate a shared memory buffer to hold the bitmap bits shared_buf_ = RenderProcess::AllocSharedMemory(buf_size); if (!shared_buf_ || !shared_buf_->Map(buf_size)) { NOTREACHED(); return; } // Copy the bits into shared memory SkAutoLockPixels bitmap_lock(bitmap); memcpy(shared_buf_->memory(), bitmap.getPixels(), buf_size); shared_buf_->Unmap(); Clipboard::ObjectMapParam param1, param2; base::SharedMemoryHandle smh = shared_buf_->handle(); const char* shared_handle = reinterpret_cast<const char*>(&smh); for (size_t i = 0; i < sizeof base::SharedMemoryHandle; i++) param1.push_back(shared_handle[i]); const char* size_data = reinterpret_cast<const char*>(&size); for (size_t i = 0; i < sizeof gfx::Size; i++) param2.push_back(size_data[i]); Clipboard::ObjectMapParams params; params.push_back(param1); params.push_back(param2); objects_[Clipboard::CBF_SMBITMAP] = params; } #endif // Define a destructor that makes IPCs to flush the contents to the // system clipboard. ScopedClipboardWriterGlue::~ScopedClipboardWriterGlue() { if (objects_.empty()) return; #if defined(OS_WIN) if (shared_buf_) { g_render_thread->Send( new ViewHostMsg_ClipboardWriteObjectsSync(objects_)); RenderProcess::FreeSharedMemory(shared_buf_); return; } #endif g_render_thread->Send( new ViewHostMsg_ClipboardWriteObjectsAsync(objects_)); } namespace webkit_glue { // Global variable set during RenderProcess::GlobalInit if video was enabled // and our media libraries were successfully loaded. static bool g_media_player_available = false; void SetMediaPlayerAvailable(bool value) { g_media_player_available = value; } bool IsMediaPlayerAvailable() { return g_media_player_available; } void PrefetchDns(const std::string& hostname) { if (!hostname.empty()) DnsPrefetchCString(hostname.c_str(), hostname.length()); } void PrecacheUrl(const wchar_t* url, int url_length) { // TBD: jar: Need implementation that loads the targetted URL into our cache. // For now, at least prefetch DNS lookup GURL parsed_url(WideToUTF8(std::wstring(url, url_length))); PrefetchDns(parsed_url.host()); } void AppendToLog(const char* file, int line, const char* msg) { logging::LogMessage(file, line).stream() << msg; } bool GetMimeTypeFromExtension(const std::wstring &ext, std::string *mime_type) { if (IsPluginProcess()) return net::GetMimeTypeFromExtension(ext, mime_type); // The sandbox restricts our access to the registry, so we need to proxy // these calls over to the browser process. DCHECK(mime_type->empty()); g_render_thread->Send( new ViewHostMsg_GetMimeTypeFromExtension(ext, mime_type)); return !mime_type->empty(); } bool GetMimeTypeFromFile(const std::wstring &file_path, std::string *mime_type) { if (IsPluginProcess()) return net::GetMimeTypeFromFile(file_path, mime_type); // The sandbox restricts our access to the registry, so we need to proxy // these calls over to the browser process. DCHECK(mime_type->empty()); g_render_thread->Send( new ViewHostMsg_GetMimeTypeFromFile(file_path, mime_type)); return !mime_type->empty(); } bool GetPreferredExtensionForMimeType(const std::string& mime_type, std::wstring* ext) { if (IsPluginProcess()) return net::GetPreferredExtensionForMimeType(mime_type, ext); // The sandbox restricts our access to the registry, so we need to proxy // these calls over to the browser process. DCHECK(ext->empty()); g_render_thread->Send( new ViewHostMsg_GetPreferredExtensionForMimeType(mime_type, ext)); return !ext->empty(); } std::string GetDataResource(int resource_id) { return ResourceBundle::GetSharedInstance().GetDataResource(resource_id); } SkBitmap* GetBitmapResource(int resource_id) { return ResourceBundle::GetSharedInstance().GetBitmapNamed(resource_id); } #if defined(OS_WIN) HCURSOR LoadCursor(int cursor_id) { return ResourceBundle::GetSharedInstance().LoadCursor(cursor_id); } #endif // Clipboard glue Clipboard* ClipboardGetClipboard(){ return NULL; } #if defined(OS_LINUX) // TODO(port): This should replace the method below (the unsigned int is a // windows type). We may need to convert the type of format so it can be sent // over IPC. bool ClipboardIsFormatAvailable(Clipboard::FormatType format) { NOTIMPLEMENTED(); return false; } #endif bool ClipboardIsFormatAvailable(unsigned int format) { bool result; g_render_thread->Send( new ViewHostMsg_ClipboardIsFormatAvailable(format, &result)); return result; } void ClipboardReadText(std::wstring* result) { g_render_thread->Send(new ViewHostMsg_ClipboardReadText(result)); } void ClipboardReadAsciiText(std::string* result) { g_render_thread->Send(new ViewHostMsg_ClipboardReadAsciiText(result)); } void ClipboardReadHTML(std::wstring* markup, GURL* url) { g_render_thread->Send(new ViewHostMsg_ClipboardReadHTML(markup, url)); } GURL GetInspectorURL() { return GURL("chrome-ui://inspector/inspector.html"); } std::string GetUIResourceProtocol() { return "chrome"; } bool GetPlugins(bool refresh, std::vector<WebPluginInfo>* plugins) { return g_render_thread->Send( new ViewHostMsg_GetPlugins(refresh, plugins)); } #if defined(OS_WIN) bool EnsureFontLoaded(HFONT font) { LOGFONT logfont; GetObject(font, sizeof(LOGFONT), &logfont); return g_render_thread->Send(new ViewHostMsg_LoadFont(logfont)); } #endif webkit_glue::ScreenInfo GetScreenInfo(gfx::NativeViewId window) { webkit_glue::ScreenInfo results; g_render_thread->Send( new ViewHostMsg_GetScreenInfo(window, &results)); return results; } uint64 VisitedLinkHash(const char* canonical_url, size_t length) { return g_render_thread->visited_link_slave()->ComputeURLFingerprint( canonical_url, length); } bool IsLinkVisited(uint64 link_hash) { return g_render_thread->visited_link_slave()->IsVisited(link_hash); } int ResolveProxyFromRenderThread(const GURL& url, std::string* proxy_result) { // Send a synchronous IPC from renderer process to the browser process to // resolve the proxy. (includes --single-process case). int net_error; bool ipc_ok = g_render_thread->Send( new ViewHostMsg_ResolveProxy(url, &net_error, proxy_result)); return ipc_ok ? net_error : net::ERR_UNEXPECTED; } #ifndef USING_SIMPLE_RESOURCE_LOADER_BRIDGE // Each RenderView has a ResourceDispatcher. In unit tests, this function may // not work properly since there may be a ResourceDispatcher w/o a RenderView. // The WebView's delegate may be null, which typically happens as a WebView is // being closed (but it is also possible that it could be null at other times // since WebView has a SetDelegate method). static ResourceDispatcher* GetResourceDispatcher(WebFrame* frame) { WebViewDelegate* d = frame->GetView()->GetDelegate(); return d ? static_cast<RenderView*>(d)->resource_dispatcher() : NULL; } // static factory function ResourceLoaderBridge* ResourceLoaderBridge::Create( WebFrame* webframe, const std::string& method, const GURL& url, const GURL& policy_url, const GURL& referrer, const std::string& headers, int load_flags, int origin_pid, ResourceType::Type resource_type, bool mixed_content) { // TODO(darin): we need to eliminate the webframe parameter because webkit // does not always supply it (see ResourceHandle::loadResourceSynchronously). // Instead we should add context to ResourceRequest, which will be easy to do // once we merge to the latest WebKit (r23806 at least). if (!webframe) { NOTREACHED() << "no webframe"; return NULL; } ResourceDispatcher* dispatcher = GetResourceDispatcher(webframe); if (!dispatcher) { DLOG(WARNING) << "no resource dispatcher"; return NULL; } return dispatcher->CreateBridge(method, url, policy_url, referrer, headers, load_flags, origin_pid, resource_type, mixed_content, 0); } void SetCookie(const GURL& url, const GURL& policy_url, const std::string& cookie) { g_render_thread->Send(new ViewHostMsg_SetCookie(url, policy_url, cookie)); } std::string GetCookies(const GURL& url, const GURL& policy_url) { std::string cookies; g_render_thread->Send(new ViewHostMsg_GetCookies(url, policy_url, &cookies)); return cookies; } void NotifyCacheStats() { // Update the browser about our cache // NOTE: Since this can be called from the plugin process, we might not have // a RenderThread. Do nothing in that case. if (g_render_thread) g_render_thread->InformHostOfCacheStatsLater(); } #endif // !USING_SIMPLE_RESOURCE_LOADER_BRIDGE } // namespace webkit_glue <|endoftext|>
<commit_before>/* Button Boxes * * The Button Box widgets are used to arrange buttons with padding. */ #include "gtkmm.h" #include "gtk/gtk.h" class Example_ButtonBox : public Gtk::Window { public: Example_ButtonBox(); ~Example_ButtonBox() override; protected: Gtk::Frame* create_button_box(bool horizontal, const Glib::ustring& title, int spacing, Gtk::ButtonBoxStyle layout); //Member widgets: Gtk::Frame m_Frame_Horizontal, m_Frame_Vertical; Gtk::Box m_VBox_Main, m_VBox; Gtk::Box m_HBox; }; //Called by DemoWindow; Gtk::Window* do_buttonbox() { return new Example_ButtonBox(); } Example_ButtonBox::Example_ButtonBox() : m_Frame_Horizontal("Horizontal Button Boxes"), m_Frame_Vertical("Vertical Button Boxes"), m_VBox_Main(Gtk::ORIENTATION_VERTICAL), m_VBox(Gtk::ORIENTATION_VERTICAL), m_HBox(Gtk::ORIENTATION_HORIZONTAL) { set_title("Button Boxes"); set_border_width(10); add(m_VBox_Main); m_VBox_Main.pack_start(m_Frame_Horizontal, Gtk::PACK_EXPAND_WIDGET, 10); m_VBox.set_border_width(10); m_Frame_Horizontal.add(m_VBox); m_VBox.pack_start( *(create_button_box(true, "Spread", 40, Gtk::BUTTONBOX_SPREAD)) ); m_VBox.pack_start( *(create_button_box(true, "Edge", 40, Gtk::BUTTONBOX_EDGE)) ); m_VBox.pack_start( *(create_button_box(true, "Start", 40, Gtk::BUTTONBOX_START)) ); m_VBox.pack_start( *(create_button_box(true, "End", 40, Gtk::BUTTONBOX_END)) ); m_VBox_Main.pack_start(m_Frame_Vertical, Gtk::PACK_EXPAND_WIDGET, 10); m_VBox.set_border_width(10); m_Frame_Vertical.add(m_HBox); m_HBox.pack_start( *(create_button_box(false, "Spread", 30, Gtk::BUTTONBOX_SPREAD)) ); m_HBox.pack_start( *(create_button_box(false, "Edge", 30, Gtk::BUTTONBOX_EDGE)) ); m_HBox.pack_start( *(create_button_box(false, "Start", 30, Gtk::BUTTONBOX_START)) ); m_HBox.pack_start( *(create_button_box(false, "End", 30, Gtk::BUTTONBOX_END)) ); show_all(); } Example_ButtonBox::~Example_ButtonBox() { } Gtk::Frame* Example_ButtonBox::create_button_box(bool horizontal, const Glib::ustring& title, gint spacing, Gtk::ButtonBoxStyle layout) { Gtk::Frame* pFrame = Gtk::manage(new Gtk::Frame(title)); Gtk::ButtonBox* pButtonBox = nullptr; if (horizontal) pButtonBox = Gtk::manage(new Gtk::ButtonBox(Gtk::ORIENTATION_HORIZONTAL)); else pButtonBox = Gtk::manage(new Gtk::ButtonBox(Gtk::ORIENTATION_VERTICAL)); pButtonBox->set_border_width(5); pFrame->add(*pButtonBox); pButtonBox->set_layout(layout); pButtonBox->set_spacing(spacing); Gtk::Button* pButton = Gtk::manage(new Gtk::Button("_OK")); pButtonBox->add(*pButton); pButton = Gtk::manage(new Gtk::Button("_Cancel")); pButtonBox->add(*pButton); pButton = Gtk::manage(new Gtk::Button()); Gtk::Image* pImage = Gtk::manage(new Gtk::Image()); pImage->set_from_icon_name("help-browser", Gtk::ICON_SIZE_BUTTON); pButton->add(*pImage); pButtonBox->add(*pButton); return pFrame; } <commit_msg>ButtonBox demo: Enable mnemonics in the buttons<commit_after>/* Button Boxes * * The Button Box widgets are used to arrange buttons with padding. */ #include "gtkmm.h" #include "gtk/gtk.h" class Example_ButtonBox : public Gtk::Window { public: Example_ButtonBox(); ~Example_ButtonBox() override; protected: Gtk::Frame* create_button_box(bool horizontal, const Glib::ustring& title, int spacing, Gtk::ButtonBoxStyle layout); //Member widgets: Gtk::Frame m_Frame_Horizontal, m_Frame_Vertical; Gtk::Box m_VBox_Main, m_VBox; Gtk::Box m_HBox; }; //Called by DemoWindow; Gtk::Window* do_buttonbox() { return new Example_ButtonBox(); } Example_ButtonBox::Example_ButtonBox() : m_Frame_Horizontal("Horizontal Button Boxes"), m_Frame_Vertical("Vertical Button Boxes"), m_VBox_Main(Gtk::ORIENTATION_VERTICAL), m_VBox(Gtk::ORIENTATION_VERTICAL), m_HBox(Gtk::ORIENTATION_HORIZONTAL) { set_title("Button Boxes"); set_border_width(10); add(m_VBox_Main); m_VBox_Main.pack_start(m_Frame_Horizontal, Gtk::PACK_EXPAND_WIDGET, 10); m_VBox.set_border_width(10); m_Frame_Horizontal.add(m_VBox); m_VBox.pack_start( *(create_button_box(true, "Spread", 40, Gtk::BUTTONBOX_SPREAD)) ); m_VBox.pack_start( *(create_button_box(true, "Edge", 40, Gtk::BUTTONBOX_EDGE)) ); m_VBox.pack_start( *(create_button_box(true, "Start", 40, Gtk::BUTTONBOX_START)) ); m_VBox.pack_start( *(create_button_box(true, "End", 40, Gtk::BUTTONBOX_END)) ); m_VBox_Main.pack_start(m_Frame_Vertical, Gtk::PACK_EXPAND_WIDGET, 10); m_VBox.set_border_width(10); m_Frame_Vertical.add(m_HBox); m_HBox.pack_start( *(create_button_box(false, "Spread", 30, Gtk::BUTTONBOX_SPREAD)) ); m_HBox.pack_start( *(create_button_box(false, "Edge", 30, Gtk::BUTTONBOX_EDGE)) ); m_HBox.pack_start( *(create_button_box(false, "Start", 30, Gtk::BUTTONBOX_START)) ); m_HBox.pack_start( *(create_button_box(false, "End", 30, Gtk::BUTTONBOX_END)) ); show_all(); } Example_ButtonBox::~Example_ButtonBox() { } Gtk::Frame* Example_ButtonBox::create_button_box(bool horizontal, const Glib::ustring& title, gint spacing, Gtk::ButtonBoxStyle layout) { Gtk::Frame* pFrame = Gtk::manage(new Gtk::Frame(title)); Gtk::ButtonBox* pButtonBox = nullptr; if (horizontal) pButtonBox = Gtk::manage(new Gtk::ButtonBox(Gtk::ORIENTATION_HORIZONTAL)); else pButtonBox = Gtk::manage(new Gtk::ButtonBox(Gtk::ORIENTATION_VERTICAL)); pButtonBox->set_border_width(5); pFrame->add(*pButtonBox); pButtonBox->set_layout(layout); pButtonBox->set_spacing(spacing); Gtk::Button* pButton = Gtk::manage(new Gtk::Button("_OK", true)); pButtonBox->add(*pButton); pButton = Gtk::manage(new Gtk::Button("_Cancel", true)); pButtonBox->add(*pButton); pButton = Gtk::manage(new Gtk::Button()); Gtk::Image* pImage = Gtk::manage(new Gtk::Image()); pImage->set_from_icon_name("help-browser", Gtk::ICON_SIZE_BUTTON); pButton->add(*pImage); pButtonBox->add(*pButton); return pFrame; } <|endoftext|>
<commit_before>// // Logarithm.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Logarithm.h" #include <vector> #include<math.h> using namespace std; Logarithm::Logarithm(int base, int operand){ this->type = "logarithm"; this->base = base; this->operand = operand; this->eOperand = new Integer(operand); this->eBase = new Integer(base); } Logarithm::Logarithm(Expression* eBase, Expression* eOperand){ this->type = "logarithm"; this->eBase = eBase; this->eOperand = eOperand; } int Logarithm::getBase(){ return base; } int Logarithm::getOperand(){ return operand; } Expression* Logarithm::getEBase(){ return eBase; } Expression* Logarithm::getEOperand(){ return eOperand; } void Logarithm::setBase(Expression* x){ this->eBase = x; } void Logarithm::setOperand(Expression* x){ this->eOperand = x; } Logarithm::~Logarithm(){ delete this; } Expression* Logarithm::simplify(){ vector<int> primefactors = primeFactorization(operand);//Create a vector of all the prime factors of the operand int size1 = primefactors.size();//gets the size of this vector vector<Expression *> seperatedLogs(size1);//creates another vector of type expression to save all of the separated Logs has the same size of the number of prime factors for(int i = 0 ; i < size1; i++){ seperatedLogs.at(i) = new Logarithm(this->eBase, primefactors.at(i));//assigns values to each seperatedlog with the same base and operands of the prime factorization } for(int j; j <size1; j++){ if (seperatedLogs.at(j)->type == "logarithm") { if (base == operand){ Integer* inte= new Integer(1); seperatedLogs.at(j) = inte; } else if(base == (1/operand)){ Integer* inten= new Integer(1); seperatedLogs.at(j) = inten; } } } Expression * answer; if(size1 >= 2){ answer = seperatedLogs.at(0)->add(seperatedLogs.at(1)); } else{ answer = seperatedLogs.at(0); } for(int k = 1; k<size1; k++){ answer = answer->add(seperatedLogs.at(k)); } } vector<int> Logarithm::primeFactorization(int n) { int k = 0; vector<int> factors; while (n%2 == 0) { factors.push_back(2); k++; n = n/2; } for (int i = 3; i <= sqrt(n); i = i + 2) { while (n%1 == 0) { factors.push_back(2); k++; n = n/i; } } if (n > 2) { factors.push_back(n); } return factors; } Expression* Logarithm::add(Expression* a){ Expression* c = this; if(c->base && a->base && c->operand && a->operand) { if (c->getBase() == a->getBase() && c->getOperand() == a->getOperand()){ Expression* answer = new Expression(2->multiply(c)); return answer; } } /* else if(c->eBase && a->eBase && c->operand && a->operand) { if (c->getEBase() == a->getEBase() && c->getOperand() == a->getOperand()){ Expression* answer = new Expression(2->multiply(c)); return answer; } } else if(c->base && a->base && c->eOperand && a->eOperand) { if (c->getBase() == a->getBase() && c->getEOperand() == a->getEOperand()){ Expression* answer = new Expression(2->multiply(c)); return answer; } } */ else if(c->eBase && a->eBase && c->eOperand && a->eOperand) { if (c->getEBase() == a->getEBase() && c->getEOperand() == a->getEOperand()){ Expression* answer = new Expression(2->multiply(c)); return answer; } } else return c; } Expression* Logarithm::subtract(Expression* a){ Expression* c = this; if(c->base && a->base && c->operand && a->operand) { if (c->getBase() == a->getBase() && c->getOperand() == a->getOperand()){ Expression* answer = new Integer(0); return answer; } } /* else if(c->eBase && a->eBase && c->operand && a->operand) { if (c->getEBase() == a->getEBase() && c->getOperand() == a->getOperand()){ Expression* answer = new Integer(0); return answer; } } else if(c->base && a->base && c->eOperand && a->eOperand) { if (c->getBase() == a->getBase() && c->getEOperand() == a->getEOperand()){ Expression* answer = new Integer(0); return answer; } */ } else if(c->eBase && a->eBase && c->eOperand && a->eOperand) { if (c->getEBase() == a->getEBase() && c->getEOperand() == a->getEOperand()){ Expression* answer = new Integer(0); return answer; } } else return c; } Expression* Logarithm::multiply(Expression* a){ Expression* c = this; if((c->base && a->base) && (c->getBase() == a->getBase())) { if ((c->operand == a->operand) && (c->getOperand() == a->getOperand())) { Expression* answer = new Exponential(this, new Rational(2,1)); } else if ((c->eOperand == a->eOperand) && (c->getEOperand() == a->getEOperand())){ Expression* answer = new Exponential(this, new Rational(2,1)); } return this; } if((c->eBase && a->eBase) && (c->getEBase() == a->getEBase())){ if ((c->operand == a->operand) && (c->getOperand() == a->getOperand())) { Expression* answer = new Exponential(this, new Rational(2,1)); } else if ((c->eOperand == a->eOperand) && (c->getEOperand() == a->getEOperand())){ Expression* answer = new Exponential(this, new Rational(2,1)); } } else return c; } Expression* Logarithm::divide(Expression* a){ Expression* c = this; if(c->base && a->base) { if (c->getBase() == a->getBase()) { Expression* answer = new Logarithm(a->getOperand(),c->getOperand()); return answer; } else { return this; } if(c->eBase && a->eBase){ if (c->getEBase() == a->getEBase()){ Expression* answer = new Logarithm(a->getEOperand(), c->getEOperand()); return answer; } else{ return this; } } else return c; } ostream& Logarithm::print(std::ostream& output) const{ output << "Log_" << this->eBase << ":" << this->eOperand; return output; } string Logarithm::toString(){ stringstream ss; ss << "Log_" << this->eBase << "(" << this->eOperand; return ss.str(); }; // might need later had in simplify metthod not sure /*int i = 1; int x = operand; int y = base; if(x % y == 0 &&) { while (x>y) { x /=y ; i++;} Expression* simplified = new Integer(i); return simplified; } */ <commit_msg>Logarithm<commit_after>// // Logarithm.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Logarithm.h" #include <vector> #include<math.h> using namespace std; Logarithm::Logarithm(int base, int operand){ this->type = "logarithm"; this->base = base; this->operand = operand; this->eOperand = new Integer(operand); this->eBase = new Integer(base); } Logarithm::Logarithm(Expression* eBase, Expression* eOperand){ this->type = "logarithm"; this->eBase = eBase; this->eOperand = eOperand; } int Logarithm::getBase(){ return base; } int Logarithm::getOperand(){ return operand; } Expression* Logarithm::getEBase(){ return eBase; } Expression* Logarithm::getEOperand(){ return eOperand; } void Logarithm::setBase(Expression* x){ this->eBase = x; } void Logarithm::setOperand(Expression* x){ this->eOperand = x; } Logarithm::~Logarithm(){ delete this; } Expression* Logarithm::simplify(){ vector<int> primefactors = primeFactorization(operand);//Create a vector of all the prime factors of the operand int size1 = primefactors.size();//gets the size of this vector vector<Expression *> seperatedLogs(size1);//creates another vector of type expression to save all of the separated Logs has the same size of the number of prime factors for(int i = 0 ; i < size1; i++){ seperatedLogs.at(i) = new Logarithm(this->eBase, primefactors.at(i));//assigns values to each seperatedlog with the same base and operands of the prime factorization } for(int j; j <size1; j++) if (seperatedLogs.at(j)->type == "logarithm") {//checks to see if the value at seperated log is a log type if(eBase->type == eOperand->type){ //makes sure the ebase and eoperand are of the same type if (eBase == eOperand){// checks to see if the ebase and the eOperand are the same Integer* inte= new Integer(1);//returns one if they are the same seperatedLogs.at(j) = inte;//assigns 1 to the value of seperated log at j } } } Expression * answer;//creates a new variable called answer if(size1 >= 2){// if the size is two or higher answer = seperatedLogs.at(0)->add(seperatedLogs.at(1));// add the first two together } else{//if the size is just 1 answer = seperatedLogs.at(0);//the answer is the first one } for(int k = 1; k<size1; k++){ answer = answer->add(seperatedLogs.at(k));//keeps adding elements of seperated log to answer } } vector<int> Logarithm::primeFactorization(int n) { int k = 0; vector<int> factors; while (n%2 == 0) { factors.push_back(2); k++; n = n/2; } for (int i = 3; i <= sqrt(n); i = i + 2) { while (n%1 == 0) { factors.push_back(2); k++; n = n/i; } } if (n > 2) { factors.push_back(n); } return factors; } Expression* Logarithm::add(Expression* a){ return this; } Expression* Logarithm::subtract(Expression* a){ Logarithm* c = this; Logarithm* b = (Logarithm *) a; if(c->eBase->type == b->eBase->type && c->eOperand->type == b->eOperand->type) { if (c->getEBase() == b->getEBase() && c->getEOperand() == b->getEOperand()){ Expression* answer = new Integer(0); return answer; } } return c; } Expression* Logarithm::multiply(Expression* a){ Logarithm* c = this; Logarithm* b = (Logarithm *) a; if(c->eBase->type == b->eBase->type && c->eOperand->type == b->eOperand->type) { if (c->getEBase() == b->getEBase() && c->getEOperand() == b->getEOperand()){ Exponential* answer = new Exponential(this, new Rational(2,1)); return answer; } } return c; } Expression* Logarithm::divide(Expression* a){//this set up is "this" divided by a so if this = log11 and a = log3 it would be log11/log3 Logarithm* c = this; Logarithm* b = (Logarithm *) a; if(c->eBase->type == b->eBase->type && c->getEBase() == b->getEBase()) { Expression* numeratorOperand = c->getEOperand(); Expression* denominatorOperand = b->getEOperand(); Logarithm* answer = new Logarithm(denominatorOperand, numeratorOperand); return answer; } return c; } ostream& Logarithm::print(std::ostream& output) const{ output << "Log_" << this->eBase << ":" << this->eOperand; return output; } string Logarithm::toString(){ stringstream ss; ss << "Log_" << this->eBase << "(" << this->eOperand; return ss.str(); }; // might need later had in simplify metthod not sure /*int i = 1; int x = operand; int y = base; if(x % y == 0 &&) { while (x>y) { x /=y ; i++;} Expression* simplified = new Integer(i); return simplified; } */ <|endoftext|>
<commit_before>/* * $Id$ * * Copyright(C) 1998-2003 Satoshi Nakamura * All rights reserved. * */ #include <qmaccount.h> #include <qmapplication.h> #include <qmmessage.h> #include <qsconv.h> #include <qsstl.h> #include <qswindow.h> #include "attachmenthelper.h" #include "../model/tempfilecleaner.h" #include "../ui/dialogs.h" #include "../ui/resourceinc.h" using namespace qm; using namespace qs; /**************************************************************************** * * DetachCallbackImpl * */ namespace { struct DetachCallbackImpl : public AttachmentParser::DetachCallback { virtual QSTATUS confirmOverwrite( const WCHAR* pwszPath, WSTRING* pwstrPath); }; } QSTATUS DetachCallbackImpl::confirmOverwrite( const WCHAR* pwszPath, WSTRING* pwstrPath) { assert(pwszPath); assert(pwstrPath); DECLARE_QSTATUS(); *pwstrPath = 0; string_ptr<WSTRING> wstr; status = loadString(Application::getApplication().getResourceHandle(), IDS_CONFIRMOVERWRITE, &wstr); CHECK_QSTATUS(); string_ptr<WSTRING> wstrMessage(concat(wstr.get(), pwszPath)); if (!wstrMessage.get()) return QSTATUS_OUTOFMEMORY; string_ptr<WSTRING> wstrPath; int nMsg = 0; status = messageBox(wstrMessage.get(), MB_YESNOCANCEL, &nMsg); CHECK_QSTATUS(); switch (nMsg) { case IDCANCEL: break; case IDYES: wstrPath.reset(allocWString(pwszPath)); if (!wstrPath.get()) return QSTATUS_OUTOFMEMORY; break; case IDNO: // TODO // Open file dialog and pick new file name up. break; default: break; } *pwstrPath = wstrPath.release(); return QSTATUS_SUCCESS; } /**************************************************************************** * * AttachmentHelper * */ qm::AttachmentHelper::AttachmentHelper(Profile* pProfile, TempFileCleaner* pTempFileCleaner, HWND hwnd) : pProfile_(pProfile), pTempFileCleaner_(pTempFileCleaner), hwnd_(hwnd) { assert(pProfile); assert(hwnd); } qm::AttachmentHelper::~AttachmentHelper() { } QSTATUS qm::AttachmentHelper::detach( const MessagePtrList& listMessagePtr, const NameList* pListName) { DECLARE_QSTATUS(); DetachDialog::List list; struct Deleter { Deleter(DetachDialog::List& l) : l_(l) {} ~Deleter() { std::for_each(l_.begin(), l_.end(), unary_compose_f_gx( string_free<WSTRING>(), mem_data_ref(&DetachDialog::Item::wstrName_))); } DetachDialog::List& l_; } deleter(list); MessagePtrList::const_iterator itM = listMessagePtr.begin(); while (itM != listMessagePtr.end()) { MessagePtrLock mpl(*itM); if (mpl) { Message msg(&status); CHECK_QSTATUS(); status = mpl->getMessage(Account::GETMESSAGEFLAG_TEXT, 0, &msg); CHECK_QSTATUS(); AttachmentParser parser(msg); AttachmentParser::AttachmentList l; AttachmentParser::AttachmentListFree free(l); status = parser.getAttachments(&l); CHECK_QSTATUS(); AttachmentParser::AttachmentList::iterator itA = l.begin(); while (itA != l.end()) { string_ptr<WSTRING> wstrName(allocWString((*itA).first)); if (!wstrName.get()) return QSTATUS_OUTOFMEMORY; bool bSelected = true; if (pListName) { NameList::const_iterator itN = std::find_if( pListName->begin(), pListName->end(), std::bind2nd(string_equal<WCHAR>(), wstrName.get())); bSelected = itN != pListName->end(); } DetachDialog::Item item = { mpl, wstrName.get(), bSelected }; status = STLWrapper<DetachDialog::List>(list).push_back(item); CHECK_QSTATUS(); wstrName.release(); ++itA; } } ++itM; } if (!list.empty()) { DetachDialog dialog(pProfile_, list, &status); CHECK_QSTATUS(); int nRet = 0; status = dialog.doModal(hwnd_, 0, &nRet); CHECK_QSTATUS(); if (nRet == IDOK) { const WCHAR* pwszFolder = dialog.getFolder(); MessageHolder* pmh = 0; Message msg(&status); AttachmentParser::AttachmentList l; AttachmentParser::AttachmentListFree free(l); DetachCallbackImpl callback; unsigned int n = 0; DetachDialog::List::iterator it = list.begin(); while (it != list.end()) { if ((*it).pmh_ != pmh) { pmh = (*it).pmh_; n = 0; status = msg.clear(); CHECK_QSTATUS(); free.free(); } else { ++n; } if ((*it).wstrName_) { if (msg.getFlag() == Message::FLAG_EMPTY) { status = (*it).pmh_->getMessage( Account::GETMESSAGEFLAG_ALL, 0, &msg); CHECK_QSTATUS(); } if (l.empty()) { status = AttachmentParser(msg).getAttachments(&l); CHECK_QSTATUS(); } assert(n < l.size()); const AttachmentParser::AttachmentList::value_type& v = l[n]; string_ptr<WSTRING> wstrPath; status = AttachmentParser(*v.second).detach( pwszFolder, (*it).wstrName_, &callback, &wstrPath); CHECK_QSTATUS(); } ++it; } } } return QSTATUS_SUCCESS; } QSTATUS qm::AttachmentHelper::open(const Part* pPart, const WCHAR* pwszName, bool bOpenWithEditor) { assert(pPart); assert(pwszName); assert(pTempFileCleaner_); DECLARE_QSTATUS(); AttachmentParser parser(*pPart); DetachCallbackImpl callback; const WCHAR* pwszTempDir = Application::getApplication().getTemporaryFolder(); string_ptr<WSTRING> wstrPath; status = parser.detach(pwszTempDir, pwszName, &callback, &wstrPath); CHECK_QSTATUS(); status = pTempFileCleaner_->add(wstrPath.get()); CHECK_QSTATUS(); if (!bOpenWithEditor) { const WCHAR* p = wcsrchr(wstrPath.get(), L'.'); if (p) { ++p; string_ptr<WSTRING> wstrExtensions; status = pProfile_->getString(L"Global", L"WarnExtensions", L"exe com pif bat scr htm html hta vbs js", &wstrExtensions); CHECK_QSTATUS(); if (wcsstr(wstrExtensions.get(), p)) { int nMsg = 0; status = messageBox( Application::getApplication().getResourceHandle(), IDS_CONFIRMEXECUTEATTACHMENT, MB_YESNO | MB_DEFBUTTON2 | MB_ICONWARNING, &nMsg); CHECK_QSTATUS(); if (nMsg != IDYES) return QSTATUS_SUCCESS; } } } W2T(wstrPath.get(), ptszPath); string_ptr<TSTRING> tstrEditor; if (bOpenWithEditor) { string_ptr<WSTRING> wstrEditor; status = pProfile_->getString(L"Global", L"Editor", L"", &wstrEditor); CHECK_QSTATUS(); tstrEditor.reset(wcs2tcs(wstrEditor.get())); if (!tstrEditor.get()) return QSTATUS_OUTOFMEMORY; } SHELLEXECUTEINFO sei = { sizeof(sei), 0, hwnd_, 0, 0, 0, 0, SW_SHOW }; if (bOpenWithEditor) { sei.lpFile = tstrEditor.get(); sei.lpParameters = ptszPath; } else { sei.lpFile = ptszPath; } if (!::ShellExecuteEx(&sei)) { status = messageBox(Application::getApplication().getResourceHandle(), IDS_ERROR_EXECUTEATTACHMENT); CHECK_QSTATUS(); } return QSTATUS_SUCCESS; } <commit_msg>Fix it causes cruch when I select No in an overwrite confirmation dialog while detaching attachments. Fix to use correct window handle to show message boxes while detaching attachments.<commit_after>/* * $Id$ * * Copyright(C) 1998-2003 Satoshi Nakamura * All rights reserved. * */ #include <qmaccount.h> #include <qmapplication.h> #include <qmmessage.h> #include <qsconv.h> #include <qsstl.h> #include <qswindow.h> #include "attachmenthelper.h" #include "../model/tempfilecleaner.h" #include "../ui/dialogs.h" #include "../ui/resourceinc.h" using namespace qm; using namespace qs; /**************************************************************************** * * DetachCallbackImpl * */ namespace { class DetachCallbackImpl : public AttachmentParser::DetachCallback { public: DetachCallbackImpl(HWND hwnd); ~DetachCallbackImpl(); public: virtual QSTATUS confirmOverwrite( const WCHAR* pwszPath, WSTRING* pwstrPath); private: DetachCallbackImpl(const DetachCallbackImpl&); DetachCallbackImpl& operator=(const DetachCallbackImpl&); private: HWND hwnd_; }; } DetachCallbackImpl::DetachCallbackImpl(HWND hwnd) : hwnd_(hwnd) { } DetachCallbackImpl::~DetachCallbackImpl() { } QSTATUS DetachCallbackImpl::confirmOverwrite( const WCHAR* pwszPath, WSTRING* pwstrPath) { assert(pwszPath); assert(pwstrPath); DECLARE_QSTATUS(); *pwstrPath = 0; string_ptr<WSTRING> wstr; status = loadString(Application::getApplication().getResourceHandle(), IDS_CONFIRMOVERWRITE, &wstr); CHECK_QSTATUS(); string_ptr<WSTRING> wstrMessage(concat(wstr.get(), pwszPath)); if (!wstrMessage.get()) return QSTATUS_OUTOFMEMORY; string_ptr<WSTRING> wstrPath; int nMsg = 0; status = messageBox(wstrMessage.get(), MB_YESNOCANCEL, hwnd_, 0, 0, &nMsg); CHECK_QSTATUS(); switch (nMsg) { case IDCANCEL: break; case IDYES: wstrPath.reset(allocWString(pwszPath)); if (!wstrPath.get()) return QSTATUS_OUTOFMEMORY; break; case IDNO: // TODO // Open file dialog and pick new file name up. break; default: break; } *pwstrPath = wstrPath.release(); return QSTATUS_SUCCESS; } /**************************************************************************** * * AttachmentHelper * */ qm::AttachmentHelper::AttachmentHelper(Profile* pProfile, TempFileCleaner* pTempFileCleaner, HWND hwnd) : pProfile_(pProfile), pTempFileCleaner_(pTempFileCleaner), hwnd_(hwnd) { assert(pProfile); assert(hwnd); } qm::AttachmentHelper::~AttachmentHelper() { } QSTATUS qm::AttachmentHelper::detach( const MessagePtrList& listMessagePtr, const NameList* pListName) { DECLARE_QSTATUS(); DetachDialog::List list; struct Deleter { Deleter(DetachDialog::List& l) : l_(l) {} ~Deleter() { std::for_each(l_.begin(), l_.end(), unary_compose_f_gx( string_free<WSTRING>(), mem_data_ref(&DetachDialog::Item::wstrName_))); } DetachDialog::List& l_; } deleter(list); MessagePtrList::const_iterator itM = listMessagePtr.begin(); while (itM != listMessagePtr.end()) { MessagePtrLock mpl(*itM); if (mpl) { Message msg(&status); CHECK_QSTATUS(); status = mpl->getMessage(Account::GETMESSAGEFLAG_TEXT, 0, &msg); CHECK_QSTATUS(); AttachmentParser parser(msg); AttachmentParser::AttachmentList l; AttachmentParser::AttachmentListFree free(l); status = parser.getAttachments(&l); CHECK_QSTATUS(); AttachmentParser::AttachmentList::iterator itA = l.begin(); while (itA != l.end()) { string_ptr<WSTRING> wstrName(allocWString((*itA).first)); if (!wstrName.get()) return QSTATUS_OUTOFMEMORY; bool bSelected = true; if (pListName) { NameList::const_iterator itN = std::find_if( pListName->begin(), pListName->end(), std::bind2nd(string_equal<WCHAR>(), wstrName.get())); bSelected = itN != pListName->end(); } DetachDialog::Item item = { mpl, wstrName.get(), bSelected }; status = STLWrapper<DetachDialog::List>(list).push_back(item); CHECK_QSTATUS(); wstrName.release(); ++itA; } } ++itM; } if (!list.empty()) { DetachDialog dialog(pProfile_, list, &status); CHECK_QSTATUS(); int nRet = 0; status = dialog.doModal(hwnd_, 0, &nRet); CHECK_QSTATUS(); if (nRet == IDOK) { const WCHAR* pwszFolder = dialog.getFolder(); MessageHolder* pmh = 0; Message msg(&status); AttachmentParser::AttachmentList l; AttachmentParser::AttachmentListFree free(l); DetachCallbackImpl callback(hwnd_); unsigned int n = 0; DetachDialog::List::iterator it = list.begin(); while (it != list.end()) { if ((*it).pmh_ != pmh) { pmh = (*it).pmh_; n = 0; status = msg.clear(); CHECK_QSTATUS(); free.free(); } else { ++n; } if ((*it).wstrName_) { if (msg.getFlag() == Message::FLAG_EMPTY) { status = (*it).pmh_->getMessage( Account::GETMESSAGEFLAG_ALL, 0, &msg); CHECK_QSTATUS(); } if (l.empty()) { status = AttachmentParser(msg).getAttachments(&l); CHECK_QSTATUS(); } assert(n < l.size()); const AttachmentParser::AttachmentList::value_type& v = l[n]; string_ptr<WSTRING> wstrPath; status = AttachmentParser(*v.second).detach( pwszFolder, (*it).wstrName_, &callback, &wstrPath); CHECK_QSTATUS(); } ++it; } } } return QSTATUS_SUCCESS; } QSTATUS qm::AttachmentHelper::open(const Part* pPart, const WCHAR* pwszName, bool bOpenWithEditor) { assert(pPart); assert(pwszName); assert(pTempFileCleaner_); DECLARE_QSTATUS(); AttachmentParser parser(*pPart); DetachCallbackImpl callback(hwnd_); const WCHAR* pwszTempDir = Application::getApplication().getTemporaryFolder(); string_ptr<WSTRING> wstrPath; status = parser.detach(pwszTempDir, pwszName, &callback, &wstrPath); CHECK_QSTATUS(); if (!wstrPath.get()) return QSTATUS_SUCCESS; status = pTempFileCleaner_->add(wstrPath.get()); CHECK_QSTATUS(); if (!bOpenWithEditor) { const WCHAR* p = wcsrchr(wstrPath.get(), L'.'); if (p) { ++p; string_ptr<WSTRING> wstrExtensions; status = pProfile_->getString(L"Global", L"WarnExtensions", L"exe com pif bat scr htm html hta vbs js", &wstrExtensions); CHECK_QSTATUS(); if (wcsstr(wstrExtensions.get(), p)) { int nMsg = 0; status = messageBox( Application::getApplication().getResourceHandle(), IDS_CONFIRMEXECUTEATTACHMENT, MB_YESNO | MB_DEFBUTTON2 | MB_ICONWARNING, hwnd_, 0, 0, &nMsg); CHECK_QSTATUS(); if (nMsg != IDYES) return QSTATUS_SUCCESS; } } } W2T(wstrPath.get(), ptszPath); string_ptr<TSTRING> tstrEditor; if (bOpenWithEditor) { string_ptr<WSTRING> wstrEditor; status = pProfile_->getString(L"Global", L"Editor", L"", &wstrEditor); CHECK_QSTATUS(); tstrEditor.reset(wcs2tcs(wstrEditor.get())); if (!tstrEditor.get()) return QSTATUS_OUTOFMEMORY; } SHELLEXECUTEINFO sei = { sizeof(sei), 0, hwnd_, 0, 0, 0, 0, SW_SHOW }; if (bOpenWithEditor) { sei.lpFile = tstrEditor.get(); sei.lpParameters = ptszPath; } else { sei.lpFile = ptszPath; } if (!::ShellExecuteEx(&sei)) { status = messageBox(Application::getApplication().getResourceHandle(), IDS_ERROR_EXECUTEATTACHMENT, hwnd_); CHECK_QSTATUS(); } return QSTATUS_SUCCESS; } <|endoftext|>
<commit_before>#include "logicalModel.h" #include "graphicalModel.h" #include <QtCore/QUuid> using namespace qReal; using namespace models; using namespace models::details; using namespace modelsImplementation; LogicalModel::LogicalModel(qrRepo::LogicalRepoApi *repoApi, EditorManagerInterface const &editorManagerInterface) : AbstractModel(editorManagerInterface), mGraphicalModelView(this), mApi(*repoApi) { mRootItem = new LogicalModelItem(Id::rootId(), NULL); init(); mLogicalAssistApi = new LogicalModelAssistApi(*this, editorManagerInterface); } LogicalModel::~LogicalModel() { delete mLogicalAssistApi; cleanupTree(mRootItem); } void LogicalModel::init() { mModelItems.insert(Id::rootId(), mRootItem); mApi.setName(Id::rootId(), Id::rootId().toString()); // Turn off view notification while loading. blockSignals(true); loadSubtreeFromClient(static_cast<LogicalModelItem *>(mRootItem)); blockSignals(false); } void LogicalModel::loadSubtreeFromClient(LogicalModelItem * const parent) { foreach (Id childId, mApi.children(parent->id())) { if (mApi.isLogicalElement(childId)) { LogicalModelItem *child = loadElement(parent, childId); loadSubtreeFromClient(child); } } } LogicalModelItem *LogicalModel::loadElement(LogicalModelItem *parentItem, Id const &id) { int const newRow = parentItem->children().size(); beginInsertRows(index(parentItem), newRow, newRow); LogicalModelItem *item = new LogicalModelItem(id, parentItem); addInsufficientProperties(id); parentItem->addChild(item); mModelItems.insert(id, item); endInsertRows(); return item; } void LogicalModel::addInsufficientProperties(Id const &id, QString const &name) { if (!mEditorManagerInterface.hasElement(id.type())) { return; } QMap<QString, QVariant> const standardProperties; standardProperties.insert("name", name); standardProperties.insert("from", Id::rootId().toVariant()); standardProperties.insert("to", Id::rootId().toVariant()); standardProperties.insert("links", IdListHelper::toVariant(IdList())); standardProperties.insert("outgoingExplosion", Id().toVariant()); standardProperties.insert("incomingExplosions", IdListHelper::toVariant(IdList())); foreach (QString const &property, standardProperties.keys()) { if (!mApi.hasProperty(id, property)) { mApi.setProperty(id, property, standardProperties[property]); } } QStringList const properties = mEditorManagerInterface.propertyNames(id.type()); foreach (QString const &property, properties) { // for those properties that doesn't have default values, plugin will return empty string mApi.setProperty(id, property, mEditorManagerInterface.defaultPropertyValue(id, property)); } } void LogicalModel::connectToGraphicalModel(GraphicalModel * const graphicalModel) { mGraphicalModelView.setModel(graphicalModel); } AbstractModelItem *LogicalModel::createModelItem(Id const &id, AbstractModelItem *parentItem) const { return new LogicalModelItem(id, static_cast<LogicalModelItem *>(parentItem)); } void LogicalModel::updateElements(Id const &logicalId, QString const &name) { if ((logicalId == Id()) || (mApi.name(logicalId) == name)) { return; } mApi.setName(logicalId, name); emit dataChanged(indexById(logicalId), indexById(logicalId)); } QMimeData* LogicalModel::mimeData(QModelIndexList const &indexes) const { QByteArray data; bool isFromLogicalModel = true; QDataStream stream(&data, QIODevice::WriteOnly); foreach (QModelIndex index, indexes) { if (index.isValid()) { AbstractModelItem *item = static_cast<AbstractModelItem*>(index.internalPointer()); stream << item->id().toString(); stream << pathToItem(item); stream << mApi.property(item->id(), "name").toString(); stream << QPointF(); stream << isFromLogicalModel; } else { stream << Id::rootId().toString(); stream << QString(); stream << QString(); stream << QPointF(); stream << isFromLogicalModel; } } QMimeData *mimeData = new QMimeData(); mimeData->setData(DEFAULT_MIME_TYPE, data); return mimeData; } QString LogicalModel::pathToItem(AbstractModelItem const *item) const { if (item != mRootItem) { QString path; do { item = item->parent(); path = item->id().toString() + ID_PATH_DIVIDER + path; } while (item != mRootItem); return path; } else return Id::rootId().toString(); } void LogicalModel::addElementToModel(const Id &parent, const Id &id, const Id &logicalId , QString const &name, const QPointF &position) { if (mModelItems.contains(id)) return; Q_ASSERT_X(mModelItems.contains(parent), "addElementToModel", "Adding element to non-existing parent"); AbstractModelItem *parentItem = mModelItems[parent]; AbstractModelItem *newItem = NULL; if (logicalId != Id::rootId() && mModelItems.contains(logicalId)) { if (parent == logicalId) { return; } else { changeParent(index(mModelItems[logicalId]), index(parentItem), QPointF()); } } else { newItem = createModelItem(id, parentItem); initializeElement(id, parentItem, newItem, name, position); } } void LogicalModel::initializeElement(Id const &id, modelsImplementation::AbstractModelItem *parentItem , modelsImplementation::AbstractModelItem *item, QString const &name, QPointF const &position) { Q_UNUSED(position) int newRow = parentItem->children().size(); beginInsertRows(index(parentItem), newRow, newRow); parentItem->addChild(item); mApi.addChild(parentItem->id(), id); addInsufficientProperties(id); mModelItems.insert(id, item); endInsertRows(); } QVariant LogicalModel::data(const QModelIndex &index, int role) const { if (index.isValid()) { AbstractModelItem *item = static_cast<AbstractModelItem*>(index.internalPointer()); Q_ASSERT(item); switch (role) { case Qt::DisplayRole: case Qt::EditRole: return mApi.name(item->id()); case Qt::DecorationRole: return QVariant(); // return mEditorManager.icon(item->id()); case roles::idRole: return item->id().toVariant(); case roles::fromRole: return mApi.from(item->id()).toVariant(); case roles::toRole: return mApi.to(item->id()).toVariant(); } if (role >= roles::customPropertiesBeginRole) { QString selectedProperty = findPropertyName(item->id(), role); return mApi.property(item->id(), selectedProperty); } Q_ASSERT(role < Qt::UserRole); return QVariant(); } else { return QVariant(); } } bool LogicalModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid()) { AbstractModelItem *item = static_cast<AbstractModelItem *>(index.internalPointer()); switch (role) { case Qt::DisplayRole: case Qt::EditRole: mApi.setName(item->id(), value.toString()); break; case roles::fromRole: mApi.setFrom(item->id(), value.value<Id>()); break; case roles::toRole: mApi.setTo(item->id(), value.value<Id>()); break; default: if (role >= roles::customPropertiesBeginRole) { QString selectedProperty = findPropertyName(item->id(), role); mApi.setProperty(item->id(), selectedProperty, value); break; } Q_ASSERT(role < Qt::UserRole); return false; } emit dataChanged(index, index); return true; } return false; } void LogicalModel::changeParent(QModelIndex const &element, QModelIndex const &parent, QPointF const &position) { Q_UNUSED(position) if (!parent.isValid() || element.parent() == parent) return; int destinationRow = parentAbstractItem(parent)->children().size(); if (beginMoveRows(element.parent(), element.row(), element.row(), parent, destinationRow)) { AbstractModelItem *elementItem = static_cast<AbstractModelItem*>(element.internalPointer()); elementItem->parent()->removeChild(elementItem); AbstractModelItem *parentItem = parentAbstractItem(parent); mApi.setParent(elementItem->id(), parentItem->id()); elementItem->setParent(parentItem); parentItem->addChild(elementItem); endMoveRows(); } } void LogicalModel::changeParent(const Id &parentId, const Id &childId) { QModelIndex parentIndex = mLogicalAssistApi->indexById(parentId); QModelIndex childIndex = mLogicalAssistApi->indexById(childId); changeParent(childIndex, parentIndex, QPointF()); } void LogicalModel::stackBefore(const QModelIndex &element, const QModelIndex &sibling) { if (element == sibling) { return; } beginMoveRows(element.parent(), element.row(), element.row(), element.parent(), sibling.row()); AbstractModelItem *parent = static_cast<AbstractModelItem *>(element.parent().internalPointer()) , *item = static_cast<AbstractModelItem *>(element.internalPointer()) , *siblingItem = static_cast<AbstractModelItem *>(sibling.internalPointer()); parent->stackBefore(item, siblingItem); mApi.stackBefore(parent->id(), item->id(), siblingItem->id()); endMoveRows(); } qrRepo::LogicalRepoApi const &LogicalModel::api() const { return mApi; } qrRepo::LogicalRepoApi &LogicalModel::mutableApi() const { return mApi; } LogicalModelAssistApi &LogicalModel::logicalModelAssistApi() const { return *mLogicalAssistApi; } bool LogicalModel::removeRows(int row, int count, QModelIndex const &parent) { AbstractModelItem *parentItem = parentAbstractItem(parent); if (parentItem->children().size() < row + count) return false; else { for (int i = row; i < row + count; ++i) { AbstractModelItem *child = parentItem->children().at(i); removeModelItems(child); int childRow = child->row(); beginRemoveRows(parent, childRow, childRow); child->parent()->removeChild(child); mModelItems.remove(child->id()); if (mModelItems.count(child->id()) == 0) mApi.removeChild(parentItem->id(), child->id()); mApi.removeElement(child->id()); delete child; endRemoveRows(); } return true; } } void LogicalModel::removeModelItemFromApi(details::modelsImplementation::AbstractModelItem *const root, details::modelsImplementation::AbstractModelItem *child) { if (mModelItems.count(child->id())==0) { mApi.removeChild(root->id(),child->id()); } mApi.removeElement(child->id()); } qReal::details::ModelsAssistInterface* LogicalModel::modelAssistInterface() const { return mLogicalAssistApi; } <commit_msg>Some extended fixes<commit_after>#include "logicalModel.h" #include "graphicalModel.h" #include <QtCore/QUuid> using namespace qReal; using namespace models; using namespace models::details; using namespace modelsImplementation; LogicalModel::LogicalModel(qrRepo::LogicalRepoApi *repoApi, EditorManagerInterface const &editorManagerInterface) : AbstractModel(editorManagerInterface), mGraphicalModelView(this), mApi(*repoApi) { mRootItem = new LogicalModelItem(Id::rootId(), NULL); init(); mLogicalAssistApi = new LogicalModelAssistApi(*this, editorManagerInterface); } LogicalModel::~LogicalModel() { delete mLogicalAssistApi; cleanupTree(mRootItem); } void LogicalModel::init() { mModelItems.insert(Id::rootId(), mRootItem); mApi.setName(Id::rootId(), Id::rootId().toString()); // Turn off view notification while loading. blockSignals(true); loadSubtreeFromClient(static_cast<LogicalModelItem *>(mRootItem)); blockSignals(false); } void LogicalModel::loadSubtreeFromClient(LogicalModelItem * const parent) { foreach (Id childId, mApi.children(parent->id())) { if (mApi.isLogicalElement(childId)) { LogicalModelItem *child = loadElement(parent, childId); loadSubtreeFromClient(child); } } } LogicalModelItem *LogicalModel::loadElement(LogicalModelItem *parentItem, Id const &id) { int const newRow = parentItem->children().size(); beginInsertRows(index(parentItem), newRow, newRow); LogicalModelItem *item = new LogicalModelItem(id, parentItem); addInsufficientProperties(id); parentItem->addChild(item); mModelItems.insert(id, item); endInsertRows(); return item; } void LogicalModel::addInsufficientProperties(Id const &id, QString const &name) { if (!mEditorManagerInterface.hasElement(id.type())) { return; } QMap<QString, QVariant> standardProperties; standardProperties.insert("name", name); standardProperties.insert("from", Id::rootId().toVariant()); standardProperties.insert("to", Id::rootId().toVariant()); standardProperties.insert("links", IdListHelper::toVariant(IdList())); standardProperties.insert("outgoingExplosion", Id().toVariant()); standardProperties.insert("incomingExplosions", IdListHelper::toVariant(IdList())); foreach (QString const &property, standardProperties.keys()) { if (!mApi.hasProperty(id, property)) { mApi.setProperty(id, property, standardProperties[property]); } } QStringList const properties = mEditorManagerInterface.propertyNames(id.type()); foreach (QString const &property, properties) { // for those properties that doesn't have default values, plugin will return empty string mApi.setProperty(id, property, mEditorManagerInterface.defaultPropertyValue(id, property)); } } void LogicalModel::connectToGraphicalModel(GraphicalModel * const graphicalModel) { mGraphicalModelView.setModel(graphicalModel); } AbstractModelItem *LogicalModel::createModelItem(Id const &id, AbstractModelItem *parentItem) const { return new LogicalModelItem(id, static_cast<LogicalModelItem *>(parentItem)); } void LogicalModel::updateElements(Id const &logicalId, QString const &name) { if ((logicalId == Id()) || (mApi.name(logicalId) == name)) { return; } mApi.setName(logicalId, name); emit dataChanged(indexById(logicalId), indexById(logicalId)); } QMimeData* LogicalModel::mimeData(QModelIndexList const &indexes) const { QByteArray data; bool isFromLogicalModel = true; QDataStream stream(&data, QIODevice::WriteOnly); foreach (QModelIndex index, indexes) { if (index.isValid()) { AbstractModelItem *item = static_cast<AbstractModelItem*>(index.internalPointer()); stream << item->id().toString(); stream << pathToItem(item); stream << mApi.property(item->id(), "name").toString(); stream << QPointF(); stream << isFromLogicalModel; } else { stream << Id::rootId().toString(); stream << QString(); stream << QString(); stream << QPointF(); stream << isFromLogicalModel; } } QMimeData *mimeData = new QMimeData(); mimeData->setData(DEFAULT_MIME_TYPE, data); return mimeData; } QString LogicalModel::pathToItem(AbstractModelItem const *item) const { if (item != mRootItem) { QString path; do { item = item->parent(); path = item->id().toString() + ID_PATH_DIVIDER + path; } while (item != mRootItem); return path; } else return Id::rootId().toString(); } void LogicalModel::addElementToModel(const Id &parent, const Id &id, const Id &logicalId , QString const &name, const QPointF &position) { if (mModelItems.contains(id)) return; Q_ASSERT_X(mModelItems.contains(parent), "addElementToModel", "Adding element to non-existing parent"); AbstractModelItem *parentItem = mModelItems[parent]; AbstractModelItem *newItem = NULL; if (logicalId != Id::rootId() && mModelItems.contains(logicalId)) { if (parent == logicalId) { return; } else { changeParent(index(mModelItems[logicalId]), index(parentItem), QPointF()); } } else { newItem = createModelItem(id, parentItem); initializeElement(id, parentItem, newItem, name, position); } } void LogicalModel::initializeElement(Id const &id, modelsImplementation::AbstractModelItem *parentItem , modelsImplementation::AbstractModelItem *item, QString const &name, QPointF const &position) { Q_UNUSED(position) int newRow = parentItem->children().size(); beginInsertRows(index(parentItem), newRow, newRow); parentItem->addChild(item); mApi.addChild(parentItem->id(), id); addInsufficientProperties(id, name); mModelItems.insert(id, item); endInsertRows(); } QVariant LogicalModel::data(const QModelIndex &index, int role) const { if (index.isValid()) { AbstractModelItem *item = static_cast<AbstractModelItem*>(index.internalPointer()); Q_ASSERT(item); switch (role) { case Qt::DisplayRole: case Qt::EditRole: return mApi.name(item->id()); case Qt::DecorationRole: return QVariant(); // return mEditorManager.icon(item->id()); case roles::idRole: return item->id().toVariant(); case roles::fromRole: return mApi.from(item->id()).toVariant(); case roles::toRole: return mApi.to(item->id()).toVariant(); } if (role >= roles::customPropertiesBeginRole) { QString selectedProperty = findPropertyName(item->id(), role); return mApi.property(item->id(), selectedProperty); } Q_ASSERT(role < Qt::UserRole); return QVariant(); } else { return QVariant(); } } bool LogicalModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid()) { AbstractModelItem *item = static_cast<AbstractModelItem *>(index.internalPointer()); switch (role) { case Qt::DisplayRole: case Qt::EditRole: mApi.setName(item->id(), value.toString()); break; case roles::fromRole: mApi.setFrom(item->id(), value.value<Id>()); break; case roles::toRole: mApi.setTo(item->id(), value.value<Id>()); break; default: if (role >= roles::customPropertiesBeginRole) { QString selectedProperty = findPropertyName(item->id(), role); mApi.setProperty(item->id(), selectedProperty, value); break; } Q_ASSERT(role < Qt::UserRole); return false; } emit dataChanged(index, index); return true; } return false; } void LogicalModel::changeParent(QModelIndex const &element, QModelIndex const &parent, QPointF const &position) { Q_UNUSED(position) if (!parent.isValid() || element.parent() == parent) return; int destinationRow = parentAbstractItem(parent)->children().size(); if (beginMoveRows(element.parent(), element.row(), element.row(), parent, destinationRow)) { AbstractModelItem *elementItem = static_cast<AbstractModelItem*>(element.internalPointer()); elementItem->parent()->removeChild(elementItem); AbstractModelItem *parentItem = parentAbstractItem(parent); mApi.setParent(elementItem->id(), parentItem->id()); elementItem->setParent(parentItem); parentItem->addChild(elementItem); endMoveRows(); } } void LogicalModel::changeParent(const Id &parentId, const Id &childId) { QModelIndex parentIndex = mLogicalAssistApi->indexById(parentId); QModelIndex childIndex = mLogicalAssistApi->indexById(childId); changeParent(childIndex, parentIndex, QPointF()); } void LogicalModel::stackBefore(const QModelIndex &element, const QModelIndex &sibling) { if (element == sibling) { return; } beginMoveRows(element.parent(), element.row(), element.row(), element.parent(), sibling.row()); AbstractModelItem *parent = static_cast<AbstractModelItem *>(element.parent().internalPointer()) , *item = static_cast<AbstractModelItem *>(element.internalPointer()) , *siblingItem = static_cast<AbstractModelItem *>(sibling.internalPointer()); parent->stackBefore(item, siblingItem); mApi.stackBefore(parent->id(), item->id(), siblingItem->id()); endMoveRows(); } qrRepo::LogicalRepoApi const &LogicalModel::api() const { return mApi; } qrRepo::LogicalRepoApi &LogicalModel::mutableApi() const { return mApi; } LogicalModelAssistApi &LogicalModel::logicalModelAssistApi() const { return *mLogicalAssistApi; } bool LogicalModel::removeRows(int row, int count, QModelIndex const &parent) { AbstractModelItem *parentItem = parentAbstractItem(parent); if (parentItem->children().size() < row + count) return false; else { for (int i = row; i < row + count; ++i) { AbstractModelItem *child = parentItem->children().at(i); removeModelItems(child); int childRow = child->row(); beginRemoveRows(parent, childRow, childRow); child->parent()->removeChild(child); mModelItems.remove(child->id()); if (mModelItems.count(child->id()) == 0) mApi.removeChild(parentItem->id(), child->id()); mApi.removeElement(child->id()); delete child; endRemoveRows(); } return true; } } void LogicalModel::removeModelItemFromApi(details::modelsImplementation::AbstractModelItem *const root, details::modelsImplementation::AbstractModelItem *child) { if (mModelItems.count(child->id())==0) { mApi.removeChild(root->id(),child->id()); } mApi.removeElement(child->id()); } qReal::details::ModelsAssistInterface* LogicalModel::modelAssistInterface() const { return mLogicalAssistApi; } <|endoftext|>
<commit_before>/********************************************************************** // @@@ START COPYRIGHT @@@ // // (C) Copyright 2006-2014 Hewlett-Packard Development Company, L.P. // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- ***************************************************************************** * * File: ex_sscp_main.cpp * Description: This is the main program for SSCP. SQL stats control process The process * does the following: * - Creates the shared segment * . Handle messages from SSMP * * Created: 04/17/2006 * Language: C++ * ***************************************************************************** */ #include "Platform.h" #ifdef _DEBUG #include <fstream> #include <iostream> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #endif #include <errno.h> #include "ExCextdecs.h" #include "ex_ex.h" #include "Ipc.h" #include "Globals.h" #include "SqlStats.h" #include "memorymonitor.h" #include "sscpipc.h" #include "rts_msg.h" #include "ex_stdh.h" #include "ExStats.h" #include "PortProcessCalls.h" #include <sys/ipc.h> #include <sys/shm.h> #include "seabed/ms.h" #include "seabed/fs.h" extern void my_mpi_fclose(); #include "SCMVersHelp.h" DEFINE_DOVERS(mxsscp) void runServer(Int32 argc, char **argv); Int32 main(Int32 argc, char **argv) { dovers(argc, argv); msg_debug_hook("mxsscp", "mxsscp.hook"); try { file_init_attach(&argc, &argv, TRUE, (char *)""); } catch (SB_Fatal_Excep &e) { SQLMXLoggingArea::logExecRtInfo(__FILE__, __LINE__, e.what(), 0); exit(1); } try { file_mon_process_startup(true); } catch (SB_Fatal_Excep &e) { SQLMXLoggingArea::logExecRtInfo(__FILE__, __LINE__, e.what(), 0); exit(1); } atexit(my_mpi_fclose); // Synchronize C and C++ output streams ios::sync_with_stdio(); #ifdef _DEBUG // Redirect stdout and stderr to files named in environment // variables const char *stdOutFile = getenv("SQ_SSCP_STDOUT"); const char *stdErrFile = getenv("SQ_SSCP_STDERR"); Int32 fdOut = -1; Int32 fdErr = -1; if (stdOutFile && stdOutFile[0]) { fdOut = open(stdOutFile, O_WRONLY | O_APPEND | O_CREAT | O_SYNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fdOut >= 0) { fprintf(stderr, "[Redirecting MXSSCP stdout to %s]\n", stdOutFile); fflush(stderr); dup2(fdOut, fileno(stdout)); } else { fprintf(stderr, "*** WARNING: could not open %s for redirection: %s.\n", stdOutFile, strerror(errno)); } } if (stdErrFile && stdErrFile[0]) { fdErr = open(stdErrFile, O_WRONLY | O_APPEND | O_CREAT | O_SYNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fdErr >= 0) { fprintf(stderr, "[Redirecting MXUDR stderr to %s]\n", stdErrFile); fflush(stderr); dup2(fdErr, fileno(stderr)); } else { fprintf(stderr, "*** WARNING: could not open %s for redirection: %s.\n", stdErrFile, strerror(errno)); } } runServer(argc, argv); if (fdOut >= 0) { close(fdOut); } if (fdErr >= 0) { close(fdErr); } #else runServer(argc, argv); #endif return 0; } void runServer(Int32 argc, char **argv) { Int32 shmid; jmp_buf sscpJmpBuf; StatsGlobals *statsGlobals = NULL; void *statsGlobalsAddr; NABoolean createStatsGlobals = FALSE; CliGlobals *cliGlobals = CliGlobals::createCliGlobals(FALSE); char tmbuf[64]; time_t now; struct tm *nowtm; long maxSegSize = STATS_MAX_SEG_SIZE; char *envSegSize = getenv("MX_RTS_STATS_SEG_SIZE"); if (envSegSize) { maxSegSize = (long) str_atoi(envSegSize, str_len(envSegSize)); if (maxSegSize < 32) maxSegSize = 32; else if (maxSegSize > 256) maxSegSize = 256; maxSegSize *= 1024 * 1024; } long enableHugePages = 0; int shmFlag = RMS_SHMFLAGS; char *envShmHugePages = getenv("SQ_RMS_ENABLE_HUGEPAGES"); if (envShmHugePages != NULL) { enableHugePages = (long) str_atoi(envShmHugePages, str_len(envShmHugePages)); if (enableHugePages > 0) shmFlag = shmFlag | SHM_HUGETLB; } now = time(NULL); nowtm = localtime(&now); strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S ", nowtm); if ((shmid = shmget((key_t)getStatsSegmentId(), 0, // size doesn't matter unless we are creating. shmFlag)) == -1) { if (errno == ENOENT) { if ((shmid = shmget((key_t)getStatsSegmentId(), maxSegSize, shmFlag | IPC_CREAT)) == -1) { cout << tmbuf << " Shmget failed, key=" << getStatsSegmentId() <<", Error code : " << errno << "(" << strerror(errno) << ")\n"; exit(errno); } else { if (enableHugePages > 0) cout << tmbuf << " RMS Shared segment id=" << shmid << ", key=" << (key_t)getStatsSegmentId() << ", created with huge pages support\n"; else cout << tmbuf << " RMS Shared segment created id=" << shmid << ", key=" << (key_t)getStatsSegmentId() << "\n"; } createStatsGlobals = TRUE; } else { cout << tmbuf << " Shmget failed key=" << (key_t)getStatsSegmentId()<< ", Error code : " << errno << "(" << strerror(errno) << ")\n"; exit(errno); } } else { cout << tmbuf << " RMS Shared segment exists, attaching to it, shmid="<< shmid << ", key=" << (key_t)getStatsSegmentId() << "\n"; } if ((statsGlobalsAddr = shmat(shmid, getRmsSharedMemoryAddr(), 0)) == (void *)-1) { cout << tmbuf << "Shmat failed, shmid=" <<shmid << ", key=" << (key_t) getStatsSegmentId() << ", Error code : " << errno << "(" << strerror(errno) << ")\n"; exit(errno); } char *statsGlobalsStartAddr = (char *)statsGlobalsAddr; if (createStatsGlobals) { short envType = StatsGlobals::RTS_GLOBAL_ENV; statsGlobals = new (statsGlobalsStartAddr) StatsGlobals((void *)statsGlobalsAddr, envType, maxSegSize); cliGlobals->setSharedMemId(shmid); // We really should not squirrel the statsGlobals pointer away like // this until the StatsGloblas is initialized, but // statsGlobals->init() needs it ...... cliGlobals->setStatsGlobals(statsGlobals); statsGlobals->init(); } else { statsGlobals = (StatsGlobals *)statsGlobalsAddr; cliGlobals->setSharedMemId(shmid); cliGlobals->setStatsGlobals(statsGlobals); } #ifdef SQ_NEW_PHANDLE XPROCESSHANDLE_GETMINE_(&statsGlobals->sscpProcHandle_); #else XPROCESSHANDLE_GETMINE_(statsGlobals->sscpProcHandle_); #endif NAHeap *sscpHeap = cliGlobals->getExecutorMemory(); cliGlobals->setJmpBufPtr(&sscpJmpBuf); if (setjmp(sscpJmpBuf)) NAExit(1); // Abend IpcEnvironment *sscpIpcEnv = new (sscpHeap) IpcEnvironment(sscpHeap, cliGlobals->getEventConsumed(), FALSE, IPC_SQLSSCP_SERVER, FALSE, TRUE); SscpGlobals *sscpGlobals = NULL; sscpGlobals = new (sscpHeap) SscpGlobals(sscpHeap, statsGlobals); // Currently open $RECEIVE with 256 SscpGuaReceiveControlConnection *cc = new(sscpHeap) SscpGuaReceiveControlConnection(sscpIpcEnv, sscpGlobals, 256); sscpIpcEnv->setControlConnection(cc); while (TRUE) { while (cc->getConnection() == NULL) cc->wait(IpcInfiniteTimeout); #ifdef _DEBUG_RTS cerr << "No. of Requesters-1 " << cc->getNumRequestors() << " \n"; #endif while (cc->getNumRequestors() > 0) { sscpIpcEnv->getAllConnections()->waitOnAll(IpcInfiniteTimeout); } // Inner while } } // runServer <commit_msg>Allow RMS shared segment without huge pages<commit_after>/********************************************************************** // @@@ START COPYRIGHT @@@ // // (C) Copyright 2006-2014 Hewlett-Packard Development Company, L.P. // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- ***************************************************************************** * * File: ex_sscp_main.cpp * Description: This is the main program for SSCP. SQL stats control process The process * does the following: * - Creates the shared segment * . Handle messages from SSMP * * Created: 04/17/2006 * Language: C++ * ***************************************************************************** */ #include "Platform.h" #ifdef _DEBUG #include <fstream> #include <iostream> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #endif #include <errno.h> #include "ExCextdecs.h" #include "ex_ex.h" #include "Ipc.h" #include "Globals.h" #include "SqlStats.h" #include "memorymonitor.h" #include "sscpipc.h" #include "rts_msg.h" #include "ex_stdh.h" #include "ExStats.h" #include "PortProcessCalls.h" #include <sys/ipc.h> #include <sys/shm.h> #include "seabed/ms.h" #include "seabed/fs.h" extern void my_mpi_fclose(); #include "SCMVersHelp.h" DEFINE_DOVERS(mxsscp) void runServer(Int32 argc, char **argv); Int32 main(Int32 argc, char **argv) { dovers(argc, argv); msg_debug_hook("mxsscp", "mxsscp.hook"); try { file_init_attach(&argc, &argv, TRUE, (char *)""); } catch (SB_Fatal_Excep &e) { SQLMXLoggingArea::logExecRtInfo(__FILE__, __LINE__, e.what(), 0); exit(1); } try { file_mon_process_startup(true); } catch (SB_Fatal_Excep &e) { SQLMXLoggingArea::logExecRtInfo(__FILE__, __LINE__, e.what(), 0); exit(1); } atexit(my_mpi_fclose); // Synchronize C and C++ output streams ios::sync_with_stdio(); #ifdef _DEBUG // Redirect stdout and stderr to files named in environment // variables const char *stdOutFile = getenv("SQ_SSCP_STDOUT"); const char *stdErrFile = getenv("SQ_SSCP_STDERR"); Int32 fdOut = -1; Int32 fdErr = -1; if (stdOutFile && stdOutFile[0]) { fdOut = open(stdOutFile, O_WRONLY | O_APPEND | O_CREAT | O_SYNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fdOut >= 0) { fprintf(stderr, "[Redirecting MXSSCP stdout to %s]\n", stdOutFile); fflush(stderr); dup2(fdOut, fileno(stdout)); } else { fprintf(stderr, "*** WARNING: could not open %s for redirection: %s.\n", stdOutFile, strerror(errno)); } } if (stdErrFile && stdErrFile[0]) { fdErr = open(stdErrFile, O_WRONLY | O_APPEND | O_CREAT | O_SYNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fdErr >= 0) { fprintf(stderr, "[Redirecting MXUDR stderr to %s]\n", stdErrFile); fflush(stderr); dup2(fdErr, fileno(stderr)); } else { fprintf(stderr, "*** WARNING: could not open %s for redirection: %s.\n", stdErrFile, strerror(errno)); } } runServer(argc, argv); if (fdOut >= 0) { close(fdOut); } if (fdErr >= 0) { close(fdErr); } #else runServer(argc, argv); #endif return 0; } void runServer(Int32 argc, char **argv) { Int32 shmid; jmp_buf sscpJmpBuf; StatsGlobals *statsGlobals = NULL; void *statsGlobalsAddr; NABoolean createStatsGlobals = FALSE; CliGlobals *cliGlobals = CliGlobals::createCliGlobals(FALSE); char tmbuf[64]; time_t now; struct tm *nowtm; long maxSegSize = STATS_MAX_SEG_SIZE; char *envSegSize = getenv("MX_RTS_STATS_SEG_SIZE"); if (envSegSize) { maxSegSize = (long) str_atoi(envSegSize, str_len(envSegSize)); if (maxSegSize < 32) maxSegSize = 32; else if (maxSegSize > 256) maxSegSize = 256; maxSegSize *= 1024 * 1024; } long enableHugePages = 0; int shmFlag = RMS_SHMFLAGS; char *envShmHugePages = getenv("SQ_RMS_ENABLE_HUGEPAGES"); if (envShmHugePages != NULL) { enableHugePages = (long) str_atoi(envShmHugePages, str_len(envShmHugePages)); if (enableHugePages > 0) shmFlag = shmFlag | SHM_HUGETLB; } now = time(NULL); nowtm = localtime(&now); strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S ", nowtm); if ((shmid = shmget((key_t)getStatsSegmentId(), 0, // size doesn't matter unless we are creating. shmFlag)) == -1) { if (errno == ENOENT) { // Normal case, segment does not exist yet. Try to create. bool didCreate = true; if ((shmid = shmget((key_t)getStatsSegmentId(), maxSegSize, shmFlag | IPC_CREAT)) == -1) { if (enableHugePages > 0) { enableHugePages = 0; // try again withouf hugepages shmFlag = shmFlag & ~SHM_HUGETLB; if ((shmid = shmget((key_t)getStatsSegmentId(), maxSegSize, shmFlag | IPC_CREAT)) == -1) didCreate = false; } else didCreate = false; } if (didCreate) { cout << tmbuf << " RMS Shared segment id = " << shmid << ", key = " << (key_t)getStatsSegmentId() ; if (enableHugePages > 0) cout << ", created with huge pages support." << endl; else cout << ", created without huge pages support." << endl; createStatsGlobals = TRUE; } else { cout << tmbuf << " Shmget failed, key = " << getStatsSegmentId() <<", Error code: " << errno << " (" << strerror(errno) << ")" << endl; exit(errno); } } // if ENOENT (i.e., attempting creation.) } else { cout << tmbuf << " RMS Shared segment exists, attaching to it, shmid="<< shmid << ", key=" << (key_t)getStatsSegmentId() << "\n"; } if ((statsGlobalsAddr = shmat(shmid, getRmsSharedMemoryAddr(), 0)) == (void *)-1) { cout << tmbuf << "Shmat failed, shmid=" <<shmid << ", key=" << (key_t) getStatsSegmentId() << ", Error code : " << errno << "(" << strerror(errno) << ")\n"; exit(errno); } char *statsGlobalsStartAddr = (char *)statsGlobalsAddr; if (createStatsGlobals) { short envType = StatsGlobals::RTS_GLOBAL_ENV; statsGlobals = new (statsGlobalsStartAddr) StatsGlobals((void *)statsGlobalsAddr, envType, maxSegSize); cliGlobals->setSharedMemId(shmid); // We really should not squirrel the statsGlobals pointer away like // this until the StatsGloblas is initialized, but // statsGlobals->init() needs it ...... cliGlobals->setStatsGlobals(statsGlobals); statsGlobals->init(); } else { statsGlobals = (StatsGlobals *)statsGlobalsAddr; cliGlobals->setSharedMemId(shmid); cliGlobals->setStatsGlobals(statsGlobals); } #ifdef SQ_NEW_PHANDLE XPROCESSHANDLE_GETMINE_(&statsGlobals->sscpProcHandle_); #else XPROCESSHANDLE_GETMINE_(statsGlobals->sscpProcHandle_); #endif NAHeap *sscpHeap = cliGlobals->getExecutorMemory(); cliGlobals->setJmpBufPtr(&sscpJmpBuf); if (setjmp(sscpJmpBuf)) NAExit(1); // Abend IpcEnvironment *sscpIpcEnv = new (sscpHeap) IpcEnvironment(sscpHeap, cliGlobals->getEventConsumed(), FALSE, IPC_SQLSSCP_SERVER, FALSE, TRUE); SscpGlobals *sscpGlobals = NULL; sscpGlobals = new (sscpHeap) SscpGlobals(sscpHeap, statsGlobals); // Currently open $RECEIVE with 256 SscpGuaReceiveControlConnection *cc = new(sscpHeap) SscpGuaReceiveControlConnection(sscpIpcEnv, sscpGlobals, 256); sscpIpcEnv->setControlConnection(cc); while (TRUE) { while (cc->getConnection() == NULL) cc->wait(IpcInfiniteTimeout); #ifdef _DEBUG_RTS cerr << "No. of Requesters-1 " << cc->getNumRequestors() << " \n"; #endif while (cc->getNumRequestors() > 0) { sscpIpcEnv->getAllConnections()->waitOnAll(IpcInfiniteTimeout); } // Inner while } } // runServer <|endoftext|>
<commit_before><commit_msg>combine_block書き始めた<commit_after><|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // child_property_generator.cpp // // Identification: src/include/optimizer/child_property_generator.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/child_property_generator.h" #include "optimizer/column_manager.h" #include "optimizer/properties.h" #include "expression/expression_util.h" #include "expression/star_expression.h" using std::move; using std::vector; using std::make_pair; using std::vector; using std::shared_ptr; using std::pair; using std::make_shared; namespace peloton { namespace optimizer { vector<pair<PropertySet, vector<PropertySet>>> ChildPropertyGenerator::GetProperties(shared_ptr<GroupExpression> gexpr, PropertySet requirements) { requirements_ = requirements; output_.clear(); gexpr->Op().Accept(this); if (output_.empty()) { output_.push_back(make_pair(requirements_, vector<PropertySet>())); } return move(output_); } void ChildPropertyGenerator::Visit(const PhysicalLimit *) { // Let child fulfil all the required properties vector<PropertySet> child_input_properties{requirements_}; output_.push_back(make_pair(requirements_, move(child_input_properties))); } void ChildPropertyGenerator::Visit(const PhysicalScan *) { PropertySet provided_property; // Scan will provide PropertyPredicate auto predicate_prop = requirements_.GetPropertyOfType(PropertyType::PREDICATE); if (predicate_prop != nullptr) provided_property.AddProperty(predicate_prop); // AbstractExpression -> offset when insert ExprMap columns; vector<shared_ptr<expression::AbstractExpression>> column_exprs; auto columns_prop = requirements_.GetPropertyOfType(PropertyType::COLUMNS) ->As<PropertyColumns>(); if (columns_prop->HasStarExpression()) { column_exprs.emplace_back(new expression::StarExpression()); } else { // Add all the columns in PropertyColumn // Note: columns from PropertyColumn has to be inserted before PropertySort // to ensure we don't change the origin column order in PropertyColumn for (size_t i = 0; i < columns_prop->GetSize(); i++) { auto expr = columns_prop->GetColumn(i); expression::ExpressionUtil::GetTupleValueExprs(columns, expr.get()); } // Add all the columns from PropertySort to column_set auto sort_prop = requirements_.GetPropertyOfType(PropertyType::SORT)->As<PropertySort>(); if (sort_prop != nullptr) { for (size_t i = 0; i < sort_prop->GetSortColumnSize(); i++) { auto expr = sort_prop->GetSortColumn(i); expression::ExpressionUtil::GetTupleValueExprs(columns, expr.get()); } } // Generate the provided PropertyColumn column_exprs.resize(columns.size()); for (auto iter : columns) column_exprs[iter.second] = iter.first; } provided_property.AddProperty( shared_ptr<Property>(new PropertyColumns(move(column_exprs)))); output_.push_back(make_pair(move(provided_property), vector<PropertySet>())); }; /** * Note: * Fulfill the entire projection property in the aggregation. Should * enumerate different combination of the aggregation functions and other * projection. */ void ChildPropertyGenerator::Visit(const PhysicalHashGroupBy *op) { PropertySet child_input_property_set; PropertySet provided_property; for (auto prop : requirements_.Properties()) { switch (prop->Type()) { // Generate output columns for the child // Aggregation will break sort property case PropertyType::DISTINCT: case PropertyType::PROJECT: case PropertyType::SORT: break; case PropertyType::COLUMNS: { provided_property.AddProperty(prop); // Check group by columns and union it with the // PropertyColumn to generate child property auto col_prop = prop->As<PropertyColumns>(); size_t col_len = col_prop->GetSize(); ExprSet child_col; for (size_t col_idx = 0; col_idx < col_len; col_idx++) { auto expr = col_prop->GetColumn(col_idx); expression::ExpressionUtil::GetTupleValueExprs(child_col, expr.get()); } // Add group by columns for (auto group_by_col : op->columns) child_col.emplace(group_by_col->Copy()); // Add child PropertyColumn child_input_property_set.AddProperty(make_shared<PropertyColumns>( vector<shared_ptr<expression::AbstractExpression>>( child_col.begin(), child_col.end()))); break; } case PropertyType::PREDICATE: // PropertyPredicate will be fulfilled by the child operator child_input_property_set.AddProperty(prop); provided_property.AddProperty(prop); break; } } vector<PropertySet> child_input_properties{child_input_property_set}; output_.push_back(make_pair(provided_property, move(child_input_properties))); } void ChildPropertyGenerator::Visit(const PhysicalSortGroupBy *op) { PropertySet child_input_property_set; PropertySet provided_property; std::vector<bool> sort_ascending; auto group_by_col_len = op->columns.size(); for (auto prop : requirements_.Properties()) { switch (prop->Type()) { // Generate output columns for the child // Aggregation will break sort property case PropertyType::DISTINCT: case PropertyType::PROJECT: break; case PropertyType::SORT: { bool sort_fulfilled = true; auto sort_prop = prop->As<PropertySort>(); auto sort_col_len = sort_prop->GetSortColumnSize(); if (sort_col_len > group_by_col_len) break; for (size_t col_idx; col_idx < sort_col_len; col_idx++) { if (!sort_prop->GetSortColumn(col_idx) ->Equals(op->columns[col_idx].get())) { sort_fulfilled = false; break; } } if (sort_fulfilled) { provided_property.AddProperty(prop); for (size_t i = 0; i < sort_col_len; i++) sort_ascending.push_back(sort_prop->GetSortAscending(i)); } break; } case PropertyType::COLUMNS: { provided_property.AddProperty(prop); // Check group by columns and union it with the // PropertyColumn to generate child property auto col_prop = prop->As<PropertyColumns>(); size_t col_len = col_prop->GetSize(); ExprSet child_col; for (size_t col_idx = 0; col_idx < col_len; col_idx++) { auto expr = col_prop->GetColumn(col_idx); expression::ExpressionUtil::GetTupleValueExprs(child_col, expr.get()); } // Add group by columns for (auto group_by_col : op->columns) child_col.emplace(group_by_col->Copy()); // Add child PropertyColumn child_input_property_set.AddProperty(make_shared<PropertyColumns>( vector<shared_ptr<expression::AbstractExpression>>( child_col.begin(), child_col.end()))); break; } case PropertyType::PREDICATE: // PropertyPredicate will be fulfilled by the child operator child_input_property_set.AddProperty(prop); provided_property.AddProperty(prop); break; } } // Start from the idx of the next elements in sort_ascending // because it can be filled when the sort property is fulfilled for (size_t i = sort_ascending.size(); i < group_by_col_len; i++) sort_ascending.push_back(true); child_input_property_set.AddProperty( make_shared<PropertySort>(op->columns, sort_ascending)); vector<PropertySet> child_input_properties{child_input_property_set}; output_.push_back(make_pair(provided_property, move(child_input_properties))); } void ChildPropertyGenerator::Visit(const PhysicalDistinct *) {} void ChildPropertyGenerator::Visit(const PhysicalAggregate *) { PropertySet child_input_property_set; PropertySet provided_property; for (auto prop : requirements_.Properties()) { switch (prop->Type()) { // Generate output columns for the child // Aggregation will break sort property case PropertyType::DISTINCT: case PropertyType::PROJECT: case PropertyType::SORT: break; case PropertyType::COLUMNS: { provided_property.AddProperty(prop); // Check group by columns and union it with the // PropertyColumn to generate child property auto col_prop = prop->As<PropertyColumns>(); size_t col_len = col_prop->GetSize(); ExprSet child_col; for (size_t col_idx = 0; col_idx < col_len; col_idx++) { auto expr = col_prop->GetColumn(col_idx); expression::ExpressionUtil::GetTupleValueExprs(child_col, expr.get()); } // Add child PropertyColumn child_input_property_set.AddProperty(make_shared<PropertyColumns>( std::vector<std::shared_ptr<expression::AbstractExpression>>( child_col.begin(), child_col.end()))); break; } case PropertyType::PREDICATE: // PropertyPredicate will be fulfilled by the child operator child_input_property_set.AddProperty(prop); provided_property.AddProperty(prop); break; } } vector<PropertySet> child_input_properties{child_input_property_set}; output_.push_back(make_pair(provided_property, move(child_input_properties))); } void ChildPropertyGenerator::Visit(const PhysicalProject *) { PropertySet child_input_property_set; PropertySet provided_property; // Child scan will provide PropertyPredicate auto predicate_prop = requirements_.GetPropertyOfType(PropertyType::PREDICATE); if (predicate_prop != nullptr) { child_input_property_set.AddProperty(predicate_prop); provided_property.AddProperty(predicate_prop); } // AbstractExpression -> offset when insert ExprMap columns; vector<shared_ptr<expression::AbstractExpression>> column_exprs; auto columns_prop_shared_p = requirements_.GetPropertyOfType(PropertyType::COLUMNS); provided_property.AddProperty(columns_prop_shared_p); auto columns_prop = columns_prop_shared_p->As<PropertyColumns>(); // Projection will provide property column if (columns_prop->HasStarExpression()) { column_exprs.emplace_back(new expression::StarExpression()); } else { // Add all the columns in PropertyColumn // Note: columns from PropertyColumn has to be inserted before PropertySort // to ensure we don't change the origin column order in PropertyColumn for (size_t i = 0; i < columns_prop->GetSize(); i++) { auto expr = columns_prop->GetColumn(i); expression::ExpressionUtil::GetTupleValueExprs(columns, expr.get()); } // Add all the columns from PropertySort to column_set auto sort_prop = requirements_.GetPropertyOfType(PropertyType::SORT)->As<PropertySort>(); if (sort_prop != nullptr) { for (size_t i = 0; i < sort_prop->GetSortColumnSize(); i++) { auto expr = sort_prop->GetSortColumn(i); expression::ExpressionUtil::GetTupleValueExprs(columns, expr.get()); } } // Generate the provided PropertyColumn column_exprs.resize(columns.size()); for (auto iter : columns) column_exprs[iter.second] = iter.first; } // child must have all the columns need by projection and sort child_input_property_set.AddProperty( shared_ptr<Property>(new PropertyColumns(move(column_exprs)))); vector<PropertySet> child_input_properties{child_input_property_set}; output_.push_back( make_pair(move(provided_property), move(child_input_properties))); }; void ChildPropertyGenerator::Visit(const PhysicalOrderBy *) {} void ChildPropertyGenerator::Visit(const PhysicalFilter *){}; void ChildPropertyGenerator::Visit(const PhysicalInnerNLJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalLeftNLJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalRightNLJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalOuterNLJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalInnerHashJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalLeftHashJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalRightHashJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalOuterHashJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalInsert *){}; void ChildPropertyGenerator::Visit(const PhysicalUpdate *){ // Let child fulfil all the required properties vector<PropertySet> child_input_properties{requirements_}; output_.push_back(make_pair(requirements_, move(child_input_properties))); } void ChildPropertyGenerator::Visit(const PhysicalDelete *) { // Let child fulfil all the required properties vector<PropertySet> child_input_properties{requirements_}; output_.push_back(make_pair(requirements_, move(child_input_properties))); }; } /* namespace optimizer */ } /* namespace peloton */ <commit_msg>fix error occurred in release mode<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // child_property_generator.cpp // // Identification: src/include/optimizer/child_property_generator.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/child_property_generator.h" #include "optimizer/column_manager.h" #include "optimizer/properties.h" #include "expression/expression_util.h" #include "expression/star_expression.h" using std::move; using std::vector; using std::make_pair; using std::vector; using std::shared_ptr; using std::pair; using std::make_shared; namespace peloton { namespace optimizer { vector<pair<PropertySet, vector<PropertySet>>> ChildPropertyGenerator::GetProperties(shared_ptr<GroupExpression> gexpr, PropertySet requirements) { requirements_ = requirements; output_.clear(); gexpr->Op().Accept(this); if (output_.empty()) { output_.push_back(make_pair(requirements_, vector<PropertySet>())); } return move(output_); } void ChildPropertyGenerator::Visit(const PhysicalLimit *) { // Let child fulfil all the required properties vector<PropertySet> child_input_properties{requirements_}; output_.push_back(make_pair(requirements_, move(child_input_properties))); } void ChildPropertyGenerator::Visit(const PhysicalScan *) { PropertySet provided_property; // Scan will provide PropertyPredicate auto predicate_prop = requirements_.GetPropertyOfType(PropertyType::PREDICATE); if (predicate_prop != nullptr) provided_property.AddProperty(predicate_prop); // AbstractExpression -> offset when insert ExprMap columns; vector<shared_ptr<expression::AbstractExpression>> column_exprs; auto columns_prop = requirements_.GetPropertyOfType(PropertyType::COLUMNS) ->As<PropertyColumns>(); if (columns_prop->HasStarExpression()) { column_exprs.emplace_back(new expression::StarExpression()); } else { // Add all the columns in PropertyColumn // Note: columns from PropertyColumn has to be inserted before PropertySort // to ensure we don't change the origin column order in PropertyColumn for (size_t i = 0; i < columns_prop->GetSize(); i++) { auto expr = columns_prop->GetColumn(i); expression::ExpressionUtil::GetTupleValueExprs(columns, expr.get()); } // Add all the columns from PropertySort to column_set auto sort_prop = requirements_.GetPropertyOfType(PropertyType::SORT)->As<PropertySort>(); if (sort_prop != nullptr) { for (size_t i = 0; i < sort_prop->GetSortColumnSize(); i++) { auto expr = sort_prop->GetSortColumn(i); expression::ExpressionUtil::GetTupleValueExprs(columns, expr.get()); } } // Generate the provided PropertyColumn column_exprs.resize(columns.size()); for (auto iter : columns) column_exprs[iter.second] = iter.first; } provided_property.AddProperty( shared_ptr<Property>(new PropertyColumns(move(column_exprs)))); output_.push_back(make_pair(move(provided_property), vector<PropertySet>())); }; /** * Note: * Fulfill the entire projection property in the aggregation. Should * enumerate different combination of the aggregation functions and other * projection. */ void ChildPropertyGenerator::Visit(const PhysicalHashGroupBy *op) { PropertySet child_input_property_set; PropertySet provided_property; for (auto prop : requirements_.Properties()) { switch (prop->Type()) { // Generate output columns for the child // Aggregation will break sort property case PropertyType::DISTINCT: case PropertyType::PROJECT: case PropertyType::SORT: break; case PropertyType::COLUMNS: { provided_property.AddProperty(prop); // Check group by columns and union it with the // PropertyColumn to generate child property auto col_prop = prop->As<PropertyColumns>(); size_t col_len = col_prop->GetSize(); ExprSet child_col; for (size_t col_idx = 0; col_idx < col_len; col_idx++) { auto expr = col_prop->GetColumn(col_idx); expression::ExpressionUtil::GetTupleValueExprs(child_col, expr.get()); } // Add group by columns for (auto group_by_col : op->columns) child_col.emplace(group_by_col->Copy()); // Add child PropertyColumn child_input_property_set.AddProperty(make_shared<PropertyColumns>( vector<shared_ptr<expression::AbstractExpression>>( child_col.begin(), child_col.end()))); break; } case PropertyType::PREDICATE: // PropertyPredicate will be fulfilled by the child operator child_input_property_set.AddProperty(prop); provided_property.AddProperty(prop); break; } } vector<PropertySet> child_input_properties{child_input_property_set}; output_.push_back(make_pair(provided_property, move(child_input_properties))); } void ChildPropertyGenerator::Visit(const PhysicalSortGroupBy *op) { PropertySet child_input_property_set; PropertySet provided_property; std::vector<bool> sort_ascending; auto group_by_col_len = op->columns.size(); for (auto prop : requirements_.Properties()) { switch (prop->Type()) { // Generate output columns for the child // Aggregation will break sort property case PropertyType::DISTINCT: case PropertyType::PROJECT: break; case PropertyType::SORT: { bool sort_fulfilled = true; auto sort_prop = prop->As<PropertySort>(); auto sort_col_len = sort_prop->GetSortColumnSize(); if (sort_col_len > group_by_col_len) break; for (size_t col_idx = 0; col_idx < sort_col_len; col_idx++) { if (!sort_prop->GetSortColumn(col_idx) ->Equals(op->columns[col_idx].get())) { sort_fulfilled = false; break; } } if (sort_fulfilled) { provided_property.AddProperty(prop); for (size_t i = 0; i < sort_col_len; i++) sort_ascending.push_back(sort_prop->GetSortAscending(i)); } break; } case PropertyType::COLUMNS: { provided_property.AddProperty(prop); // Check group by columns and union it with the // PropertyColumn to generate child property auto col_prop = prop->As<PropertyColumns>(); size_t col_len = col_prop->GetSize(); ExprSet child_col; for (size_t col_idx = 0; col_idx < col_len; col_idx++) { auto expr = col_prop->GetColumn(col_idx); expression::ExpressionUtil::GetTupleValueExprs(child_col, expr.get()); } // Add group by columns for (auto group_by_col : op->columns) child_col.emplace(group_by_col->Copy()); // Add child PropertyColumn child_input_property_set.AddProperty(make_shared<PropertyColumns>( vector<shared_ptr<expression::AbstractExpression>>( child_col.begin(), child_col.end()))); break; } case PropertyType::PREDICATE: // PropertyPredicate will be fulfilled by the child operator child_input_property_set.AddProperty(prop); provided_property.AddProperty(prop); break; } } // Start from the idx of the next elements in sort_ascending // because it can be filled when the sort property is fulfilled for (size_t i = sort_ascending.size(); i < group_by_col_len; i++) sort_ascending.push_back(true); child_input_property_set.AddProperty( make_shared<PropertySort>(op->columns, sort_ascending)); vector<PropertySet> child_input_properties{child_input_property_set}; output_.push_back(make_pair(provided_property, move(child_input_properties))); } void ChildPropertyGenerator::Visit(const PhysicalDistinct *) {} void ChildPropertyGenerator::Visit(const PhysicalAggregate *) { PropertySet child_input_property_set; PropertySet provided_property; for (auto prop : requirements_.Properties()) { switch (prop->Type()) { // Generate output columns for the child // Aggregation will break sort property case PropertyType::DISTINCT: case PropertyType::PROJECT: case PropertyType::SORT: break; case PropertyType::COLUMNS: { provided_property.AddProperty(prop); // Check group by columns and union it with the // PropertyColumn to generate child property auto col_prop = prop->As<PropertyColumns>(); size_t col_len = col_prop->GetSize(); ExprSet child_col; for (size_t col_idx = 0; col_idx < col_len; col_idx++) { auto expr = col_prop->GetColumn(col_idx); expression::ExpressionUtil::GetTupleValueExprs(child_col, expr.get()); } // Add child PropertyColumn child_input_property_set.AddProperty(make_shared<PropertyColumns>( std::vector<std::shared_ptr<expression::AbstractExpression>>( child_col.begin(), child_col.end()))); break; } case PropertyType::PREDICATE: // PropertyPredicate will be fulfilled by the child operator child_input_property_set.AddProperty(prop); provided_property.AddProperty(prop); break; } } vector<PropertySet> child_input_properties{child_input_property_set}; output_.push_back(make_pair(provided_property, move(child_input_properties))); } void ChildPropertyGenerator::Visit(const PhysicalProject *) { PropertySet child_input_property_set; PropertySet provided_property; // Child scan will provide PropertyPredicate auto predicate_prop = requirements_.GetPropertyOfType(PropertyType::PREDICATE); if (predicate_prop != nullptr) { child_input_property_set.AddProperty(predicate_prop); provided_property.AddProperty(predicate_prop); } // AbstractExpression -> offset when insert ExprMap columns; vector<shared_ptr<expression::AbstractExpression>> column_exprs; auto columns_prop_shared_p = requirements_.GetPropertyOfType(PropertyType::COLUMNS); provided_property.AddProperty(columns_prop_shared_p); auto columns_prop = columns_prop_shared_p->As<PropertyColumns>(); // Projection will provide property column if (columns_prop->HasStarExpression()) { column_exprs.emplace_back(new expression::StarExpression()); } else { // Add all the columns in PropertyColumn // Note: columns from PropertyColumn has to be inserted before PropertySort // to ensure we don't change the origin column order in PropertyColumn for (size_t i = 0; i < columns_prop->GetSize(); i++) { auto expr = columns_prop->GetColumn(i); expression::ExpressionUtil::GetTupleValueExprs(columns, expr.get()); } // Add all the columns from PropertySort to column_set auto sort_prop = requirements_.GetPropertyOfType(PropertyType::SORT)->As<PropertySort>(); if (sort_prop != nullptr) { for (size_t i = 0; i < sort_prop->GetSortColumnSize(); i++) { auto expr = sort_prop->GetSortColumn(i); expression::ExpressionUtil::GetTupleValueExprs(columns, expr.get()); } } // Generate the provided PropertyColumn column_exprs.resize(columns.size()); for (auto iter : columns) column_exprs[iter.second] = iter.first; } // child must have all the columns need by projection and sort child_input_property_set.AddProperty( shared_ptr<Property>(new PropertyColumns(move(column_exprs)))); vector<PropertySet> child_input_properties{child_input_property_set}; output_.push_back( make_pair(move(provided_property), move(child_input_properties))); }; void ChildPropertyGenerator::Visit(const PhysicalOrderBy *) {} void ChildPropertyGenerator::Visit(const PhysicalFilter *){}; void ChildPropertyGenerator::Visit(const PhysicalInnerNLJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalLeftNLJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalRightNLJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalOuterNLJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalInnerHashJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalLeftHashJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalRightHashJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalOuterHashJoin *){}; void ChildPropertyGenerator::Visit(const PhysicalInsert *){}; void ChildPropertyGenerator::Visit(const PhysicalUpdate *){ // Let child fulfil all the required properties vector<PropertySet> child_input_properties{requirements_}; output_.push_back(make_pair(requirements_, move(child_input_properties))); } void ChildPropertyGenerator::Visit(const PhysicalDelete *) { // Let child fulfil all the required properties vector<PropertySet> child_input_properties{requirements_}; output_.push_back(make_pair(requirements_, move(child_input_properties))); }; } /* namespace optimizer */ } /* namespace peloton */ <|endoftext|>
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * * Condor Software Copyright Notice * Copyright (C) 1990-2006, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * This source code is covered by the Condor Public License, which can * be found in the accompanying LICENSE.TXT file, or online at * www.condorproject.org. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS, * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY * RIGHT. * ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ /* Here is the version string - update before a public release */ /* --- IMPORTANT! THE FORMAT OF THE VERSION STRING IS VERY STRICT BECAUSE IT IS PARSED AT RUNTIME. DO NOT ALTER THE FORMAT OR ENTER ANYTHING EXTRA BEFORE THE DATE. IF YOU WISH TO ADD EXTRA INFORMATION, DO SO _AFTER_ THE DATE AND BEFORE THE TRAILING '$' CHARACTER. EXAMPLES: $CondorVersion: 6.1.11 " __DATE__ " WinNTPreview $ [OK] $CondorVersion: 6.1.11 WinNTPreview " __DATE__ " $ [WRONG!!!] Any questions? See Todd or Derek. Note: if you mess it up, DaemonCore will EXCEPT at startup time. */ static char* CondorVersionString = "$CondorVersion: 6.9.3 " __DATE__ " PRE-RELEASE-UWCS $"; /* This is some wisdom from Cygnus's web page. If you just try to use the "stringify" operator on a preprocessor directive, you'd get "PLATFORM", not "Intel Linux" (or whatever the value of PLATFORM is). That's because the stringify operator is a special case, and the preprocessor isn't allowed to expand things that are passed to it. However, by defining two layers of macros, you get the right behavior, since the first pass converts: xstr(PLATFORM) -> str(Intel Linux) and the next pass gives: str(Intel Linux) -> "Intel Linux" This is exactly what we want, so we use it. -Derek Wright and Jeff Ballard, 12/2/99 Also, because the NT build system is totally different, we have to define the correct platform string right in here. :( -Derek 12/3/99 */ #if defined(WIN32) #define PLATFORM INTEL-WINNT50 #endif #define xstr(s) str(s) #define str(s) #s /* Here is the platform string. You don't need to edit this */ static char* CondorPlatformString = "$CondorPlatform: " xstr(PLATFORM) " $"; extern "C" { const char* CondorVersion( void ) { return CondorVersionString; } const char* CondorPlatform( void ) { return CondorPlatformString; } } /* extern "C" */ <commit_msg>On to 6.9.4!<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * * Condor Software Copyright Notice * Copyright (C) 1990-2006, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * This source code is covered by the Condor Public License, which can * be found in the accompanying LICENSE.TXT file, or online at * www.condorproject.org. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS, * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY * RIGHT. * ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ /* Here is the version string - update before a public release */ /* --- IMPORTANT! THE FORMAT OF THE VERSION STRING IS VERY STRICT BECAUSE IT IS PARSED AT RUNTIME. DO NOT ALTER THE FORMAT OR ENTER ANYTHING EXTRA BEFORE THE DATE. IF YOU WISH TO ADD EXTRA INFORMATION, DO SO _AFTER_ THE DATE AND BEFORE THE TRAILING '$' CHARACTER. EXAMPLES: $CondorVersion: 6.1.11 " __DATE__ " WinNTPreview $ [OK] $CondorVersion: 6.1.11 WinNTPreview " __DATE__ " $ [WRONG!!!] Any questions? See Todd or Derek. Note: if you mess it up, DaemonCore will EXCEPT at startup time. */ static char* CondorVersionString = "$CondorVersion: 6.9.4 " __DATE__ " PRE-RELEASE-UWCS $"; /* This is some wisdom from Cygnus's web page. If you just try to use the "stringify" operator on a preprocessor directive, you'd get "PLATFORM", not "Intel Linux" (or whatever the value of PLATFORM is). That's because the stringify operator is a special case, and the preprocessor isn't allowed to expand things that are passed to it. However, by defining two layers of macros, you get the right behavior, since the first pass converts: xstr(PLATFORM) -> str(Intel Linux) and the next pass gives: str(Intel Linux) -> "Intel Linux" This is exactly what we want, so we use it. -Derek Wright and Jeff Ballard, 12/2/99 Also, because the NT build system is totally different, we have to define the correct platform string right in here. :( -Derek 12/3/99 */ #if defined(WIN32) #define PLATFORM INTEL-WINNT50 #endif #define xstr(s) str(s) #define str(s) #s /* Here is the platform string. You don't need to edit this */ static char* CondorPlatformString = "$CondorPlatform: " xstr(PLATFORM) " $"; extern "C" { const char* CondorVersion( void ) { return CondorVersionString; } const char* CondorPlatform( void ) { return CondorPlatformString; } } /* extern "C" */ <|endoftext|>
<commit_before>#include <ros/ros.h> #include <geometry_msgs/Twist.h> int main(int argc, char *argv[]){ ros::init(argc, argv, "quadrotor_obstacle_avoidance"); ros::NodeHandle node; ros::Publisher cmd_pub = node.advertise<geometry_msgs::Twist>("cmd_vel", 10); ros::Duration(1).sleep(); geometry_msgs::Twist cmd; cmd.linear.z = 1; cmd_pub.publish(cmd); ros::Duration(3).sleep(); cmd.linear.z = 0.0; cmd_pub.publish(cmd); ros::Duration(3).sleep(); return 0; } <commit_msg>Provisional Implemented<commit_after>#include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <math> static const float tol = 0.000000000000001f; void normalize(double &vec[2]){ float m = sqrt(vec[0]*vec[0] + vec[1]*vec[1]); if(tol <= m) m = 1; vec[0] /= m; vec[1] /= m; if(fabs(vec[0]) < tol) vec[0] = 0.0f; if(fabs(vec[1]) < tol) vec[1] = 0.0f; } int main(int argc, char *argv[]){ ros::NodeHandle node; ros::Publisher cmd_pub = node.advertise<geometry_msgs::Twist>("cmd_vel", 10); ros::Duration(1).sleep(); geometry_msgs::Twist cmd; //cmd.linear.z = 1; double Fs[2]; double r[2], u[2]; double obs[2]; double U = 0; //double U, A, B, n, m, d; const double A = 0; const double B = 13000; const double n = 1; const double m = 2.5; const double force = 0.025; Fs[0] = Fs[1] = 0; obs[0] = 0.5; obs[1] = 0; r[0] -= obs[0]; r[1] -= obs[1]; u = r; normalize(u); //d = r.Magnitude()/Units[i].fLength; const double length = 4.0; d = sqrt(r[0]*r[0] + r[1]*r[1]) / length; U = -A/pow(d, n) + B/pow(d, m); u[0] *= U; u[1] *= U; //Fs += VRotate2D(-Units[i].fOrientation, U * u); cmd_pub.publish(cmd); return 0; } <|endoftext|>
<commit_before>#ifndef __mix_cpp #define __mix_cpp /* 頥 ᫮, १ ப, -2 砥 訡 Start, End - 砫 ப */ int GetInt(TCHAR *Start, TCHAR *End) { int Ret=-2; if(End >= Start) { TCHAR Tmp[11]; int Size=(int)(End-Start); if(Size) { if(Size < 11) { _tmemcpy(Tmp,Start,Size); Tmp[Size]=0; Ret=FarAtoi(Tmp); } } else Ret=0; } return Ret; } const TCHAR *GetMsg(int MsgId) { return(Info.GetMsg(Info.ModuleNumber,MsgId)); } /*頥 TRUE, ᫨ 䠩 name */ BOOL FileExists(const TCHAR *Name) { return GetFileAttributes(Name)!=0xFFFFFFFF; } void InitDialogItems(const struct InitDialogItem *Init,struct FarDialogItem *Item, int ItemsNumber) { int I; struct FarDialogItem *PItem=Item; const struct InitDialogItem *PInit=Init; for (I=0;I<ItemsNumber;I++,PItem++,PInit++) { PItem->Type=PInit->Type; PItem->X1=PInit->X1; PItem->Y1=PInit->Y1; PItem->X2=PInit->X2; PItem->Y2=PInit->Y2; PItem->Focus=PInit->Focus; PItem->History=(const TCHAR *)PInit->Selected; PItem->Flags=PInit->Flags; PItem->DefaultButton=PInit->DefaultButton; if ((unsigned int)(DWORD_PTR)PInit->Data<2000) #ifndef UNICODE lstrcpy(PItem->Data,GetMsg((unsigned int)(DWORD_PTR)PInit->Data)); #else PItem->PtrData = GetMsg((unsigned int)(DWORD_PTR)PInit->Data); #endif else #ifndef UNICODE lstrcpy(PItem->Data,PInit->Data); #else PItem->PtrData = PInit->Data; #endif } } TCHAR *GetCommaWord(TCHAR *Src,TCHAR *Word,TCHAR Separator) { int WordPos,SkipBrackets; if (*Src==0) return(NULL); SkipBrackets=FALSE; for (WordPos=0;*Src!=0;Src++,WordPos++) { if (*Src==_T('[') && _tcschr(Src+1,_T(']'))!=NULL) SkipBrackets=TRUE; if (*Src==_T(']')) SkipBrackets=FALSE; if (*Src==Separator && !SkipBrackets) { Word[WordPos]=0; Src++; while (IsSpace(*Src)) Src++; return(Src); } else Word[WordPos]=*Src; } Word[WordPos]=0; return(Src); } #endif <commit_msg>tiny fix<commit_after>#ifndef __mix_cpp #define __mix_cpp /* 頥 ᫮, १ ப, -2 砥 訡 Start, End - 砫 ப */ int GetInt(TCHAR *Start, TCHAR *End) { int Ret=-2; if(End >= Start) { TCHAR Tmp[11]; int Size=(int)(End-Start); if(Size) { if(Size < 11) { _tmemcpy(Tmp,Start,Size); Tmp[Size]=0; Ret=FarAtoi(Tmp); } } else Ret=0; } return Ret; } const TCHAR *GetMsg(int MsgId) { return(Info.GetMsg(Info.ModuleNumber,MsgId)); } /*頥 TRUE, ᫨ 䠩 name */ BOOL FileExists(const TCHAR *Name) { return GetFileAttributes(Name)!=0xFFFFFFFF; } void InitDialogItems(const struct InitDialogItem *Init,struct FarDialogItem *Item, int ItemsNumber) { int I; struct FarDialogItem *PItem=Item; const struct InitDialogItem *PInit=Init; for (I=0;I<ItemsNumber;I++,PItem++,PInit++) { PItem->Type=PInit->Type; PItem->X1=PInit->X1; PItem->Y1=PInit->Y1; PItem->X2=PInit->X2; PItem->Y2=PInit->Y2; PItem->Focus=PInit->Focus; PItem->History=(const TCHAR *)PInit->Selected; PItem->Flags=PInit->Flags; PItem->DefaultButton=PInit->DefaultButton; #ifdef UNICODE PItem->MaxLen=0; #endif if ((unsigned int)(DWORD_PTR)PInit->Data<2000) #ifndef UNICODE lstrcpy(PItem->Data,GetMsg((unsigned int)(DWORD_PTR)PInit->Data)); #else PItem->PtrData = GetMsg((unsigned int)(DWORD_PTR)PInit->Data); #endif else #ifndef UNICODE lstrcpy(PItem->Data,PInit->Data); #else PItem->PtrData = PInit->Data; #endif } } TCHAR *GetCommaWord(TCHAR *Src,TCHAR *Word,TCHAR Separator) { int WordPos,SkipBrackets; if (*Src==0) return(NULL); SkipBrackets=FALSE; for (WordPos=0;*Src!=0;Src++,WordPos++) { if (*Src==_T('[') && _tcschr(Src+1,_T(']'))!=NULL) SkipBrackets=TRUE; if (*Src==_T(']')) SkipBrackets=FALSE; if (*Src==Separator && !SkipBrackets) { Word[WordPos]=0; Src++; while (IsSpace(*Src)) Src++; return(Src); } else Word[WordPos]=*Src; } Word[WordPos]=0; return(Src); } #endif <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file MixClient.cpp * @author Arkadiy Paronyan arkadiy@ethdev.com * @date 2015 * Ethereum IDE client. */ #include "MixClient.h" #include <vector> #include <utility> #include <libdevcore/Exceptions.h> #include <libethcore/Params.h> #include <libethcore/BasicAuthority.h> #include <libethereum/CanonBlockChain.h> #include <libethereum/Transaction.h> #include <libethereum/Executive.h> #include <libethereum/ExtVM.h> #include <libethereum/BlockChain.h> #include <libevm/VM.h> #include "Exceptions.h" using namespace std; using namespace dev; using namespace dev::eth; namespace dev { namespace mix { u256 const c_mixGenesisDifficulty = 131072; //TODO: make it lower for Mix somehow namespace { } MixBlockChain::MixBlockChain(std::string const& _path, h256 _stateRoot): FullBlockChain<NoProof>(createGenesisBlock(_stateRoot), std::unordered_map<Address, Account>(), _path, WithExisting::Kill) { } bytes MixBlockChain::createGenesisBlock(h256 _stateRoot) { RLPStream block(3); block.appendList(13) << h256() << EmptyListSHA3 << h160() << _stateRoot << EmptyTrie << EmptyTrie << LogBloom() << c_mixGenesisDifficulty << 0 << c_genesisGasLimit << 0 << (unsigned)0 << std::string(); block.appendRaw(RLPEmptyList); block.appendRaw(RLPEmptyList); return block.out(); } MixClient::MixClient(std::string const& _dbPath): m_dbPath(_dbPath) { resetState(std::unordered_map<Address, Account>()); } MixClient::~MixClient() { } void MixClient::resetState(std::unordered_map<Address, Account> const& _accounts, Secret const& _miner) { WriteGuard l(x_state); Guard fl(x_filtersWatches); m_filters.clear(); for (auto& i: m_specialFilters) i.second.clear(); m_watches.clear(); m_stateDB = OverlayDB(); SecureTrieDB<Address, MemoryDB> accountState(&m_stateDB); accountState.init(); dev::eth::commit(_accounts, accountState); h256 stateRoot = accountState.root(); m_bc.reset(); m_bc.reset(new MixBlockChain(m_dbPath, stateRoot)); State s(m_stateDB, BaseState::PreExisting, KeyPair(_miner).address()); s.sync(bc()); m_state = s; m_startState = m_state; WriteGuard lx(x_executions); m_executions.clear(); } Transaction MixClient::replaceGas(Transaction const& _t, u256 const& _gas, Secret const& _secret) { Transaction ret; if (_secret) { if (_t.isCreation()) ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce(), _secret); else ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce(), _secret); } else { if (_t.isCreation()) ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce()); else ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce()); ret.forceSender(_t.safeSender()); } return ret; } void MixClient::executeTransaction(Transaction const& _t, State& _state, bool _call, bool _gasAuto, Secret const& _secret) { Transaction t = _gasAuto ? replaceGas(_t, m_state.gasLimitRemaining()) : _t; // do debugging run first LastHashes lastHashes(256); lastHashes[0] = bc().numberHash(bc().number()); for (unsigned i = 1; i < 256; ++i) lastHashes[i] = lastHashes[i - 1] ? bc().details(lastHashes[i - 1]).parent : h256(); State execState = _state; execState.addBalance(t.sender(), t.gas() * t.gasPrice()); //give it enough balance for gas estimation eth::ExecutionResult er; Executive execution(execState, lastHashes, 0); execution.setResultRecipient(er); execution.initialize(t); execution.execute(); std::vector<MachineState> machineStates; std::vector<unsigned> levels; std::vector<MachineCode> codes; std::map<bytes const*, unsigned> codeIndexes; std::vector<bytes> data; std::map<bytesConstRef const*, unsigned> dataIndexes; bytes const* lastCode = nullptr; bytesConstRef const* lastData = nullptr; unsigned codeIndex = 0; unsigned dataIndex = 0; auto onOp = [&](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, void* voidVM, void const* voidExt) { VM& vm = *static_cast<VM*>(voidVM); ExtVM const& ext = *static_cast<ExtVM const*>(voidExt); if (lastCode == nullptr || lastCode != &ext.code) { auto const& iter = codeIndexes.find(&ext.code); if (iter != codeIndexes.end()) codeIndex = iter->second; else { codeIndex = codes.size(); codes.push_back(MachineCode({ext.myAddress, ext.code})); codeIndexes[&ext.code] = codeIndex; } lastCode = &ext.code; } if (lastData == nullptr || lastData != &ext.data) { auto const& iter = dataIndexes.find(&ext.data); if (iter != dataIndexes.end()) dataIndex = iter->second; else { dataIndex = data.size(); data.push_back(ext.data.toBytes()); dataIndexes[&ext.data] = dataIndex; } lastData = &ext.data; } if (levels.size() < ext.depth) levels.push_back(machineStates.size() - 1); else levels.resize(ext.depth); machineStates.push_back(MachineState{ steps, vm.curPC(), inst, newMemSize, static_cast<u256>(gas), vm.stack(), vm.memory(), gasCost, ext.state().storage(ext.myAddress), std::move(levels), codeIndex, dataIndex }); }; execution.go(onOp); execution.finalize(); switch (er.excepted) { case TransactionException::None: break; case TransactionException::NotEnoughCash: BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Insufficient balance for contract deployment")); case TransactionException::OutOfGasIntrinsic: case TransactionException::OutOfGasBase: case TransactionException::OutOfGas: BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas")); case TransactionException::BlockGasLimitReached: BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Block gas limit reached")); case TransactionException::BadJumpDestination: BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Solidity exception (bad jump)")); case TransactionException::OutOfStack: BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Out of stack")); case TransactionException::StackUnderflow: BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Stack underflow")); //these should not happen in mix case TransactionException::Unknown: case TransactionException::BadInstruction: case TransactionException::InvalidSignature: case TransactionException::InvalidNonce: case TransactionException::InvalidFormat: case TransactionException::BadRLP: BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Internal execution error")); } ExecutionResult d; d.inputParameters = t.data(); d.result = er; d.machineStates = machineStates; d.executionCode = std::move(codes); d.transactionData = std::move(data); d.address = _t.receiveAddress(); d.sender = _t.sender(); d.value = _t.value(); d.gasUsed = er.gasUsed + er.gasRefunded + c_callStipend; if (_t.isCreation()) d.contractAddress = right160(sha3(rlpList(_t.sender(), _t.nonce()))); if (!_call) d.transactionIndex = m_state.pending().size(); d.executonIndex = m_executions.size(); // execute on a state if (!_call) { t = _gasAuto ? replaceGas(_t, d.gasUsed, _secret) : _t; er = _state.execute(lastHashes, t); if (t.isCreation() && _state.code(d.contractAddress).empty()) BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas for contract deployment")); d.gasUsed = er.gasUsed + er.gasRefunded + er.gasForDeposit + c_callStipend; LocalisedLogEntries logs; TransactionReceipt const& tr = _state.receipt(_state.pending().size() - 1); //auto trHash = _state.pending().at(_state.pending().size() - 1).sha3(); LogEntries le = tr.log(); if (le.size()) for (unsigned j = 0; j < le.size(); ++j) logs.insert(logs.begin(), LocalisedLogEntry(le[j])); d.logs = logs; } WriteGuard l(x_executions); m_executions.emplace_back(std::move(d)); } void MixClient::mine() { WriteGuard l(x_state); m_state.commitToMine(bc()); NoProof::BlockHeader h(m_state.info()); RLPStream header; h.streamRLP(header); m_state.sealBlock(header.out()); bc().import(m_state.blockData(), m_state.db(), ImportRequirements::Default & ~ImportRequirements::ValidSeal); m_state.sync(bc()); m_startState = m_state; } ExecutionResult MixClient::lastExecution() const { ReadGuard l(x_executions); return m_executions.empty() ? ExecutionResult() : m_executions.back(); } ExecutionResult MixClient::execution(unsigned _index) const { ReadGuard l(x_executions); return m_executions.at(_index); } State MixClient::asOf(h256 const& _block) const { ReadGuard l(x_state); State ret(m_stateDB); ret.populateFromChain(bc(), _block); return ret; } pair<h256, Address> MixClient::submitTransaction(eth::TransactionSkeleton const& _ts, Secret const& _secret, bool _gasAuto) { WriteGuard l(x_state); TransactionSkeleton ts = _ts; ts.from = toAddress(_secret); ts.nonce = m_state.transactionsFrom(ts.from); eth::Transaction t(ts, _secret); executeTransaction(t, m_state, false, _gasAuto, _secret); return make_pair(t.sha3(), toAddress(ts.from, ts.nonce)); } dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, bool _gasAuto, FudgeFactor _ff) { (void)_blockNumber; State temp = asOf(eth::PendingBlock); u256 n = temp.transactionsFrom(_from); Transaction t(_value, _gasPrice, _gas, _dest, _data, n); t.forceSender(_from); if (_ff == FudgeFactor::Lenient) temp.addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); WriteGuard lw(x_state); //TODO: lock is required only for last execution state executeTransaction(t, temp, true, _gasAuto); return lastExecution().result; } dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) { return call(_from, _value, _dest, _data, _gas, _gasPrice, _blockNumber, false, _ff); } dev::eth::ExecutionResult MixClient::create(Address const& _from, u256 _value, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) { (void)_blockNumber; u256 n; State temp; { ReadGuard lr(x_state); temp = asOf(eth::PendingBlock); n = temp.transactionsFrom(_from); } Transaction t(_value, _gasPrice, _gas, _data, n); t.forceSender(_from); if (_ff == FudgeFactor::Lenient) temp.addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); WriteGuard lw(x_state); //TODO: lock is required only for last execution state executeTransaction(t, temp, true, false); return lastExecution().result; } eth::BlockInfo MixClient::blockInfo() const { ReadGuard l(x_state); return BlockInfo(bc().block()); } void MixClient::setAddress(Address _us) { WriteGuard l(x_state); m_state.setAddress(_us); } void MixClient::startMining() { //no-op } void MixClient::stopMining() { //no-op } bool MixClient::isMining() const { return false; } uint64_t MixClient::hashrate() const { return 0; } eth::WorkingProgress MixClient::miningProgress() const { return eth::WorkingProgress(); } } } <commit_msg>started tests refactoring<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file MixClient.cpp * @author Arkadiy Paronyan arkadiy@ethdev.com * @date 2015 * Ethereum IDE client. */ #include "MixClient.h" #include <vector> #include <utility> #include <libdevcore/Exceptions.h> #include <libethcore/Params.h> #include <libethcore/BasicAuthority.h> #include <libethereum/CanonBlockChain.h> #include <libethereum/Transaction.h> #include <libethereum/Executive.h> #include <libethereum/ExtVM.h> #include <libethereum/BlockChain.h> #include <libevm/VM.h> #include "Exceptions.h" using namespace std; using namespace dev; using namespace dev::eth; namespace dev { namespace mix { u256 const c_mixGenesisDifficulty = 131072; //TODO: make it lower for Mix somehow namespace { } MixBlockChain::MixBlockChain(std::string const& _path, h256 _stateRoot): FullBlockChain<NoProof>(createGenesisBlock(_stateRoot), std::unordered_map<Address, Account>(), _path, WithExisting::Kill) { } bytes MixBlockChain::createGenesisBlock(h256 _stateRoot) { RLPStream block(3); block.appendList(13) << h256() << EmptyListSHA3 << h160() << _stateRoot << EmptyTrie << EmptyTrie << LogBloom() << c_mixGenesisDifficulty << 0 << c_genesisGasLimit << 0 << (unsigned)0 << std::string(); block.appendRaw(RLPEmptyList); block.appendRaw(RLPEmptyList); return block.out(); } MixClient::MixClient(std::string const& _dbPath): m_dbPath(_dbPath) { resetState(std::unordered_map<Address, Account>()); } MixClient::~MixClient() { } void MixClient::resetState(std::unordered_map<Address, Account> const& _accounts, Secret const& _miner) { WriteGuard l(x_state); Guard fl(x_filtersWatches); m_filters.clear(); for (auto& i: m_specialFilters) i.second.clear(); m_watches.clear(); m_stateDB = OverlayDB(); SecureTrieDB<Address, MemoryDB> accountState(&m_stateDB); accountState.init(); dev::eth::commit(_accounts, accountState); h256 stateRoot = accountState.root(); m_bc.reset(); m_bc.reset(new MixBlockChain(m_dbPath, stateRoot)); State s(m_stateDB, BaseState::PreExisting, KeyPair(_miner).address()); s.sync(bc()); m_state = s; m_startState = m_state; WriteGuard lx(x_executions); m_executions.clear(); } Transaction MixClient::replaceGas(Transaction const& _t, u256 const& _gas, Secret const& _secret) { Transaction ret; if (_secret) { if (_t.isCreation()) ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce(), _secret); else ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce(), _secret); } else { if (_t.isCreation()) ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce()); else ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce()); ret.forceSender(_t.safeSender()); } return ret; } void MixClient::executeTransaction(Transaction const& _t, State& _state, bool _call, bool _gasAuto, Secret const& _secret) { Transaction t = _gasAuto ? replaceGas(_t, m_state.gasLimitRemaining()) : _t; // do debugging run first LastHashes lastHashes(256); lastHashes[0] = bc().numberHash(bc().number()); for (unsigned i = 1; i < 256; ++i) lastHashes[i] = lastHashes[i - 1] ? bc().details(lastHashes[i - 1]).parent : h256(); State execState = _state; execState.addBalance(t.sender(), t.gas() * t.gasPrice()); //give it enough balance for gas estimation eth::ExecutionResult er; Executive execution(execState, lastHashes, 0); execution.setResultRecipient(er); execution.initialize(t); execution.execute(); std::vector<MachineState> machineStates; std::vector<unsigned> levels; std::vector<MachineCode> codes; std::map<bytes const*, unsigned> codeIndexes; std::vector<bytes> data; std::map<bytesConstRef const*, unsigned> dataIndexes; bytes const* lastCode = nullptr; bytesConstRef const* lastData = nullptr; unsigned codeIndex = 0; unsigned dataIndex = 0; auto onOp = [&](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, void* voidVM, void const* voidExt) { VM& vm = *static_cast<VM*>(voidVM); ExtVM const& ext = *static_cast<ExtVM const*>(voidExt); if (lastCode == nullptr || lastCode != &ext.code) { auto const& iter = codeIndexes.find(&ext.code); if (iter != codeIndexes.end()) codeIndex = iter->second; else { codeIndex = codes.size(); codes.push_back(MachineCode({ext.myAddress, ext.code})); codeIndexes[&ext.code] = codeIndex; } lastCode = &ext.code; } if (lastData == nullptr || lastData != &ext.data) { auto const& iter = dataIndexes.find(&ext.data); if (iter != dataIndexes.end()) dataIndex = iter->second; else { dataIndex = data.size(); data.push_back(ext.data.toBytes()); dataIndexes[&ext.data] = dataIndex; } lastData = &ext.data; } if (levels.size() < ext.depth) levels.push_back(machineStates.size() - 1); else levels.resize(ext.depth); machineStates.push_back(MachineState{ steps, vm.curPC(), inst, newMemSize, static_cast<u256>(gas), vm.stack(), vm.memory(), gasCost, ext.state().storage(ext.myAddress), std::move(levels), codeIndex, dataIndex }); }; execution.go(onOp); execution.finalize(); switch (er.excepted) { case TransactionException::None: break; case TransactionException::NotEnoughCash: BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Insufficient balance for contract deployment")); case TransactionException::OutOfGasIntrinsic: case TransactionException::OutOfGasBase: case TransactionException::OutOfGas: BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas")); case TransactionException::BlockGasLimitReached: BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Block gas limit reached")); case TransactionException::BadJumpDestination: BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Solidity exception (bad jump)")); case TransactionException::OutOfStack: BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Out of stack")); case TransactionException::StackUnderflow: BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Stack underflow")); //these should not happen in mix case TransactionException::Unknown: case TransactionException::BadInstruction: case TransactionException::InvalidSignature: case TransactionException::InvalidNonce: case TransactionException::InvalidFormat: case TransactionException::BadRLP: BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Internal execution error")); } ExecutionResult d; d.inputParameters = t.data(); d.result = er; d.machineStates = machineStates; d.executionCode = std::move(codes); d.transactionData = std::move(data); d.address = _t.receiveAddress(); d.sender = _t.sender(); d.value = _t.value(); d.gasUsed = er.gasUsed + er.gasRefunded + c_callStipend; if (_t.isCreation()) d.contractAddress = right160(sha3(rlpList(_t.sender(), _t.nonce()))); if (!_call) d.transactionIndex = m_state.pending().size(); d.executonIndex = m_executions.size(); // execute on a state if (!_call) { t = _gasAuto ? replaceGas(_t, d.gasUsed, _secret) : _t; er = _state.execute(lastHashes, t); if (t.isCreation() && _state.code(d.contractAddress).empty()) BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas for contract deployment")); d.gasUsed = er.gasUsed + er.gasRefunded + er.gasForDeposit + c_callStipend; LocalisedLogEntries logs; TransactionReceipt const& tr = _state.receipt(_state.pending().size() - 1); //auto trHash = _state.pending().at(_state.pending().size() - 1).sha3(); LogEntries le = tr.log(); if (le.size()) for (unsigned j = 0; j < le.size(); ++j) logs.insert(logs.begin(), LocalisedLogEntry(le[j])); d.logs = logs; } WriteGuard l(x_executions); m_executions.emplace_back(std::move(d)); } void MixClient::mine() { WriteGuard l(x_state); m_state.commitToMine(bc()); NoProof::BlockHeader h(m_state.info()); RLPStream header; h.streamRLP(header); m_state.sealBlock(header.out()); bc().import(m_state.blockData(), m_state.db(), ImportRequirements::Everything & ~ImportRequirements::ValidSeal); m_state.sync(bc()); m_startState = m_state; } ExecutionResult MixClient::lastExecution() const { ReadGuard l(x_executions); return m_executions.empty() ? ExecutionResult() : m_executions.back(); } ExecutionResult MixClient::execution(unsigned _index) const { ReadGuard l(x_executions); return m_executions.at(_index); } State MixClient::asOf(h256 const& _block) const { ReadGuard l(x_state); State ret(m_stateDB); ret.populateFromChain(bc(), _block); return ret; } pair<h256, Address> MixClient::submitTransaction(eth::TransactionSkeleton const& _ts, Secret const& _secret, bool _gasAuto) { WriteGuard l(x_state); TransactionSkeleton ts = _ts; ts.from = toAddress(_secret); ts.nonce = m_state.transactionsFrom(ts.from); eth::Transaction t(ts, _secret); executeTransaction(t, m_state, false, _gasAuto, _secret); return make_pair(t.sha3(), toAddress(ts.from, ts.nonce)); } dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, bool _gasAuto, FudgeFactor _ff) { (void)_blockNumber; State temp = asOf(eth::PendingBlock); u256 n = temp.transactionsFrom(_from); Transaction t(_value, _gasPrice, _gas, _dest, _data, n); t.forceSender(_from); if (_ff == FudgeFactor::Lenient) temp.addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); WriteGuard lw(x_state); //TODO: lock is required only for last execution state executeTransaction(t, temp, true, _gasAuto); return lastExecution().result; } dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) { return call(_from, _value, _dest, _data, _gas, _gasPrice, _blockNumber, false, _ff); } dev::eth::ExecutionResult MixClient::create(Address const& _from, u256 _value, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff) { (void)_blockNumber; u256 n; State temp; { ReadGuard lr(x_state); temp = asOf(eth::PendingBlock); n = temp.transactionsFrom(_from); } Transaction t(_value, _gasPrice, _gas, _data, n); t.forceSender(_from); if (_ff == FudgeFactor::Lenient) temp.addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value())); WriteGuard lw(x_state); //TODO: lock is required only for last execution state executeTransaction(t, temp, true, false); return lastExecution().result; } eth::BlockInfo MixClient::blockInfo() const { ReadGuard l(x_state); return BlockInfo(bc().block()); } void MixClient::setAddress(Address _us) { WriteGuard l(x_state); m_state.setAddress(_us); } void MixClient::startMining() { //no-op } void MixClient::stopMining() { //no-op } bool MixClient::isMining() const { return false; } uint64_t MixClient::hashrate() const { return 0; } eth::WorkingProgress MixClient::miningProgress() const { return eth::WorkingProgress(); } } } <|endoftext|>
<commit_before>/* * VHDL code generation for scopes. * * Copyright (C) 2008 Nick Gasson (nick@nickg.me.uk) * * 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 "vhdl_target.h" #include "vhdl_element.hh" #include <iostream> #include <sstream> #include <cassert> /* * Create a VHDL entity for scopes of type IVL_SCT_MODULE. */ static vhdl_entity *create_entity_for(ivl_scope_t scope) { assert(ivl_scope_type(scope) == IVL_SCT_MODULE); // The type name will become the entity name const char *tname = ivl_scope_tname(scope); // Remember the scope name this entity was derived from so // the correct processes can be added later const char *derived_from = ivl_scope_name(scope); // Verilog does not have the entity/architecture distinction // so we always create a pair and associate the architecture // with the entity for convenience (this also means that we // retain a 1-to-1 mapping of scope to VHDL element) vhdl_arch *arch = new vhdl_arch(tname); vhdl_entity *ent = new vhdl_entity(tname, derived_from, arch); // Build a comment to add to the entity/architecture std::ostringstream ss; ss << "Generated from " << ivl_scope_name(scope); ss << " (" << ivl_scope_def_file(scope) << ":"; ss << ivl_scope_def_lineno(scope) << ")"; arch->set_comment(ss.str()); ent->set_comment(ss.str()); std::cout << "Generated entity " << tname; std::cout << " from " << ivl_scope_name(scope) << std::endl; remember_entity(ent); return ent; } /* * Instantiate an entity in the hierarchy, and possibly create * that entity if it hasn't been encountered yet. */ static int draw_module(ivl_scope_t scope, ivl_scope_t parent) { assert(ivl_scope_type(scope) == IVL_SCT_MODULE); // Maybe we need to create this entity first? vhdl_entity *ent = find_entity(ivl_scope_tname(scope)); if (NULL == ent) ent = create_entity_for(scope); assert(ent); // Is this module instantiated inside another? if (parent != NULL) { vhdl_entity *parent_ent = find_entity(ivl_scope_tname(parent)); assert(parent_ent != NULL); vhdl_arch *parent_arch = parent_ent->get_arch(); assert(parent_arch != NULL); // Create a forward declaration for it if (!parent_arch->have_declared_component(ent->get_name())) { vhdl_decl *comp_decl = vhdl_component_decl::component_decl_for(ent); parent_arch->add_decl(comp_decl); } // And an instantiation statement const char *inst_name = ivl_scope_basename(scope); vhdl_comp_inst *inst = new vhdl_comp_inst(inst_name, ent->get_name().c_str()); std::ostringstream ss; ss << "Scope name " << ivl_scope_name(scope); inst->set_comment(ss.str()); parent_arch->add_stmt(inst); } return 0; } int draw_scope(ivl_scope_t scope, void *_parent) { ivl_scope_t parent = static_cast<ivl_scope_t>(_parent); const char *name = ivl_scope_name(scope); const char *basename = ivl_scope_basename(scope); std::cout << "scope " << name << " (" << basename << ")" << std::endl; ivl_scope_type_t type = ivl_scope_type(scope); int rc = 0; switch (type) { case IVL_SCT_MODULE: rc = draw_module(scope, parent); break; default: error("No VHDL conversion for %s (at %s)", ivl_scope_tname(scope), ivl_scope_name(scope)); break; } if (rc != 0) return rc; rc = ivl_scope_children(scope, draw_scope, scope); if (rc != 0) return rc; return 0; } <commit_msg>Fix a bug where the same instantiation appeared multiple times<commit_after>/* * VHDL code generation for scopes. * * Copyright (C) 2008 Nick Gasson (nick@nickg.me.uk) * * 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 "vhdl_target.h" #include "vhdl_element.hh" #include <iostream> #include <sstream> #include <cassert> /* * Create a VHDL entity for scopes of type IVL_SCT_MODULE. */ static vhdl_entity *create_entity_for(ivl_scope_t scope) { assert(ivl_scope_type(scope) == IVL_SCT_MODULE); // The type name will become the entity name const char *tname = ivl_scope_tname(scope); // Remember the scope name this entity was derived from so // the correct processes can be added later const char *derived_from = ivl_scope_name(scope); // Verilog does not have the entity/architecture distinction // so we always create a pair and associate the architecture // with the entity for convenience (this also means that we // retain a 1-to-1 mapping of scope to VHDL element) vhdl_arch *arch = new vhdl_arch(tname); vhdl_entity *ent = new vhdl_entity(tname, derived_from, arch); // Build a comment to add to the entity/architecture std::ostringstream ss; ss << "Generated from " << ivl_scope_name(scope); ss << " (" << ivl_scope_def_file(scope) << ":"; ss << ivl_scope_def_lineno(scope) << ")"; arch->set_comment(ss.str()); ent->set_comment(ss.str()); std::cout << "Generated entity " << tname; std::cout << " from " << ivl_scope_name(scope) << std::endl; remember_entity(ent); return ent; } /* * Instantiate an entity in the hierarchy, and possibly create * that entity if it hasn't been encountered yet. */ static int draw_module(ivl_scope_t scope, ivl_scope_t parent) { assert(ivl_scope_type(scope) == IVL_SCT_MODULE); // Maybe we need to create this entity first? vhdl_entity *ent = find_entity(ivl_scope_tname(scope)); if (NULL == ent) ent = create_entity_for(scope); assert(ent); // Is this module instantiated inside another? if (parent != NULL) { vhdl_entity *parent_ent = find_entity(ivl_scope_tname(parent)); assert(parent_ent != NULL); // Make sure we only collect instantiations from *one* // example of this module in the hieararchy if (parent_ent->get_derived_from() == ivl_scope_name(parent)) { vhdl_arch *parent_arch = parent_ent->get_arch(); assert(parent_arch != NULL); // Create a forward declaration for it if (!parent_arch->have_declared_component(ent->get_name())) { vhdl_decl *comp_decl = vhdl_component_decl::component_decl_for(ent); parent_arch->add_decl(comp_decl); } // And an instantiation statement const char *inst_name = ivl_scope_basename(scope); vhdl_comp_inst *inst = new vhdl_comp_inst(inst_name, ent->get_name().c_str()); std::ostringstream ss; ss << "Generated from " << ivl_scope_name(scope); inst->set_comment(ss.str()); parent_arch->add_stmt(inst); } else { std::cout << "Ignoring instantiation " << ivl_scope_name(scope); std::cout << " (already accounted for)" << std::endl; } } return 0; } int draw_scope(ivl_scope_t scope, void *_parent) { ivl_scope_t parent = static_cast<ivl_scope_t>(_parent); const char *name = ivl_scope_name(scope); const char *basename = ivl_scope_basename(scope); std::cout << "scope " << name << " (" << basename << ")" << std::endl; ivl_scope_type_t type = ivl_scope_type(scope); int rc = 0; switch (type) { case IVL_SCT_MODULE: rc = draw_module(scope, parent); break; default: error("No VHDL conversion for %s (at %s)", ivl_scope_tname(scope), ivl_scope_name(scope)); break; } if (rc != 0) return rc; rc = ivl_scope_children(scope, draw_scope, scope); if (rc != 0) return rc; return 0; } <|endoftext|>
<commit_before>// Here's a wirish include: #include <wirish/wirish.h> #include "fpga-comm/test.h" void setup(void) { // init the FPGA comm and bind interrupt comm_init(); pinMode(BOARD_LED_PIN, OUTPUT); } void loop(void) { if (newData) { // print out the information SerialUSB.println("Interrupt Triggered!\n"); SerialUSB.print("Pin 5: "); SerialUSB.print(pin5); SerialUSB.println(); newData = 0; } } // Standard libmaple init() and main. // // The init() part makes sure your board gets set up correctly. It's // best to leave that alone unless you know what you're doing. main() // is the usual "call setup(), then loop() forever", but of course can // be whatever you want. __attribute__((constructor)) void premain() { init(); } int main(void) { setup(); while (true) { loop(); } return 0; } <commit_msg>prettyfied the output<commit_after>// Here's a wirish include: #include <wirish/wirish.h> #include "fpga-comm/test.h" void setup(void) { // init the FPGA comm and bind interrupt comm_init(); pinMode(BOARD_LED_PIN, OUTPUT); } void loop(void) { if (newData) { // print out the information SerialUSB.println("Interrupt Triggered!"); SerialUSB.print("Pin 5: "); SerialUSB.print(pin5); SerialUSB.println(); newData = 0; } } // Standard libmaple init() and main. // // The init() part makes sure your board gets set up correctly. It's // best to leave that alone unless you know what you're doing. main() // is the usual "call setup(), then loop() forever", but of course can // be whatever you want. __attribute__((constructor)) void premain() { init(); } int main(void) { setup(); while (true) { loop(); } return 0; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_FUN_TRACE_GEN_QUAD_FORM_HPP #define STAN_MATH_PRIM_FUN_TRACE_GEN_QUAD_FORM_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/trace.hpp> #include <stan/math/prim/fun/multiply.hpp> #include <stan/math/prim/fun/to_ref.hpp> #include <stan/math/prim/fun/transpose.hpp> #include <exception> namespace stan { namespace math { /** * Return the trace of D times the quadratic form of B and A. * That is, `trace_gen_quad_form(D, A, B) = trace(D * B' * A * B).` * * @tparam TD type of the first matrix or expression * @tparam TA type of the second matrix or expression * @tparam TB type of the third matrix or expression * * @param D multiplier * @param A outside term in quadratic form * @param B inner term in quadratic form * @return trace(D * B' * A * B) * @throw std::domain_error if A or D is not square * @throw std::domain_error if A cannot be multiplied by B or B cannot * be multiplied by D. */ template <typename TD, typename TA, typename TB, typename = require_all_eigen_t<TD, TA, TB>, typename = require_all_not_vt_var<TD, TA, TB>, typename = require_any_not_vt_arithmetic<TD, TA, TB>> inline auto trace_gen_quad_form(const TD& D, const TA& A, const TB& B) { check_square("trace_gen_quad_form", "A", A); check_square("trace_gen_quad_form", "D", D); check_multiplicable("trace_gen_quad_form", "A", A, "B", B); check_multiplicable("trace_gen_quad_form", "B", B, "D", D); const auto &B_ref = to_ref(B); return multiply(B_ref, D.transpose()).cwiseProduct(multiply(A, B_ref)).sum(); } /** * Return the trace of D times the quadratic form of B and A. * That is, `trace_gen_quad_form(D, A, B) = trace(D * B' * A * B).` * This is the overload for arithmetic types to allow Eigen's expression * templates to be used for efficiency. * * @tparam EigMatD type of the first matrix or expression * @tparam EigMatA type of the second matrix or expression * @tparam EigMatB type of the third matrix or expression * * @param D multiplier * @param A outside term in quadratic form * @param B inner term in quadratic form * @return trace(D * B' * A * B) * @throw std::domain_error if A or D is not square * @throw std::domain_error if A cannot be multiplied by B or B cannot * be multiplied by D. */ template <typename EigMatD, typename EigMatA, typename EigMatB, require_all_eigen_vt<std::is_arithmetic, EigMatD, EigMatA, EigMatB>* = nullptr> inline double trace_gen_quad_form(const EigMatD& D, const EigMatA& A, const EigMatB& B) { check_square("trace_gen_quad_form", "A", A); check_square("trace_gen_quad_form", "D", D); check_multiplicable("trace_gen_quad_form", "A", A, "B", B); check_multiplicable("trace_gen_quad_form", "B", B, "D", D); const auto &B_ref = to_ref(B); return (B_ref * D.transpose()).cwiseProduct(A * B_ref).sum(); } } // namespace math } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_PRIM_FUN_TRACE_GEN_QUAD_FORM_HPP #define STAN_MATH_PRIM_FUN_TRACE_GEN_QUAD_FORM_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/trace.hpp> #include <stan/math/prim/fun/multiply.hpp> #include <stan/math/prim/fun/to_ref.hpp> #include <stan/math/prim/fun/transpose.hpp> #include <exception> namespace stan { namespace math { /** * Return the trace of D times the quadratic form of B and A. * That is, `trace_gen_quad_form(D, A, B) = trace(D * B' * A * B).` * * @tparam TD type of the first matrix or expression * @tparam TA type of the second matrix or expression * @tparam TB type of the third matrix or expression * * @param D multiplier * @param A outside term in quadratic form * @param B inner term in quadratic form * @return trace(D * B' * A * B) * @throw std::domain_error if A or D is not square * @throw std::domain_error if A cannot be multiplied by B or B cannot * be multiplied by D. */ template <typename TD, typename TA, typename TB, typename = require_all_eigen_t<TD, TA, TB>, typename = require_all_not_vt_var<TD, TA, TB>, typename = require_any_not_vt_arithmetic<TD, TA, TB>> inline auto trace_gen_quad_form(const TD& D, const TA& A, const TB& B) { check_square("trace_gen_quad_form", "A", A); check_square("trace_gen_quad_form", "D", D); check_multiplicable("trace_gen_quad_form", "A", A, "B", B); check_multiplicable("trace_gen_quad_form", "B", B, "D", D); const auto& B_ref = to_ref(B); return multiply(B_ref, D.transpose()).cwiseProduct(multiply(A, B_ref)).sum(); } /** * Return the trace of D times the quadratic form of B and A. * That is, `trace_gen_quad_form(D, A, B) = trace(D * B' * A * B).` * This is the overload for arithmetic types to allow Eigen's expression * templates to be used for efficiency. * * @tparam EigMatD type of the first matrix or expression * @tparam EigMatA type of the second matrix or expression * @tparam EigMatB type of the third matrix or expression * * @param D multiplier * @param A outside term in quadratic form * @param B inner term in quadratic form * @return trace(D * B' * A * B) * @throw std::domain_error if A or D is not square * @throw std::domain_error if A cannot be multiplied by B or B cannot * be multiplied by D. */ template <typename EigMatD, typename EigMatA, typename EigMatB, require_all_eigen_vt<std::is_arithmetic, EigMatD, EigMatA, EigMatB>* = nullptr> inline double trace_gen_quad_form(const EigMatD& D, const EigMatA& A, const EigMatB& B) { check_square("trace_gen_quad_form", "A", A); check_square("trace_gen_quad_form", "D", D); check_multiplicable("trace_gen_quad_form", "A", A, "B", B); check_multiplicable("trace_gen_quad_form", "B", B, "D", D); const auto& B_ref = to_ref(B); return (B_ref * D.transpose()).cwiseProduct(A * B_ref).sum(); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>// -*- c++ -*- /*! * This file is part of CameraPlus. * * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "devicesettings.h" #include "settings.h" #define IMAGE_RESOLUTION_KEY "imageResolution" #define IMAGE_ASPECT_RATIO_KEY "imageAspectRatio" #define VIDEO_RESOLUTION_KEY "videoResolution" #define VIDEO_ASPECT_RATIO_KEY "videoAspectRatio" #define IMAGE_SCENE_MODE_KEY "imageSceneMode" #define VIDEO_SCENE_MODE_KEY "videoSceneMode" #define IMAGE_COLOR_FILTER_KEY "imageColorFilter" #define VIDEO_COLOR_FILTER_KEY "videoColorFilter" #define IMAGE_WHITE_BALANCE_KEY "imageWhiteBalance" #define VIDEO_WHITE_BALANCE_KEY "videoWhiteBalance" #define IMAGE_EV_COMP_KEY "imageEvComp" #define VIDEO_EV_COMP_KEY "videoEvComp" #define IMAGE_FLASH_MODE_KEY "imageFlashMode" #define VIDEO_TORCH_ON_KEY "videoTorchOn" #define IMAGE_ISO_KEY "imageIso" #define VIDEO_MUTE_KEY "videoMute" PrimaryDeviceSettings::PrimaryDeviceSettings(QObject *parent) : DeviceSettings(parent) { QHash<QString, QVariant> props; props[IMAGE_RESOLUTION_KEY] = "high"; props[IMAGE_ASPECT_RATIO_KEY] = "16:9"; props[VIDEO_RESOLUTION_KEY] = "high"; props[VIDEO_ASPECT_RATIO_KEY] = "16:9"; props[IMAGE_SCENE_MODE_KEY] = 6; props[VIDEO_SCENE_MODE_KEY] = 6; props[IMAGE_COLOR_FILTER_KEY] = 0; props[VIDEO_COLOR_FILTER_KEY] = 0; props[IMAGE_WHITE_BALANCE_KEY] = 0; props[VIDEO_WHITE_BALANCE_KEY] = 0; props[IMAGE_EV_COMP_KEY] = 0.0; props[VIDEO_EV_COMP_KEY] = 0.0; props[IMAGE_FLASH_MODE_KEY] = 0; props[VIDEO_TORCH_ON_KEY] = false; props[IMAGE_ISO_KEY] = 0; props[VIDEO_MUTE_KEY] = false; init("primary", props); } SecondaryDeviceSettings::SecondaryDeviceSettings(QObject *parent) : DeviceSettings(parent) { QHash<QString, QVariant> props; props[IMAGE_RESOLUTION_KEY] = "low"; props[IMAGE_ASPECT_RATIO_KEY] = "4:3"; props[VIDEO_RESOLUTION_KEY] = "low"; props[VIDEO_ASPECT_RATIO_KEY] = "4:3"; props[IMAGE_SCENE_MODE_KEY] = 6; props[VIDEO_SCENE_MODE_KEY] = 6; props[IMAGE_COLOR_FILTER_KEY] = 0; props[VIDEO_COLOR_FILTER_KEY] = 0; props[IMAGE_WHITE_BALANCE_KEY] = 0; props[VIDEO_WHITE_BALANCE_KEY] = 0; props[IMAGE_EV_COMP_KEY] = 0.0; props[VIDEO_EV_COMP_KEY] = 0.0; props[IMAGE_FLASH_MODE_KEY] = 0; props[VIDEO_TORCH_ON_KEY] = false; props[IMAGE_ISO_KEY] = 0; props[VIDEO_MUTE_KEY] = false; init("secondary", props); } DeviceSettings::DeviceSettings(QObject *parent) : QObject(parent), m_settings(0) { } DeviceSettings::~DeviceSettings() { m_settings = 0; } void DeviceSettings::init(const QString& id, const QHash<QString, QVariant>& props) { m_id = id; m_props = props; } Settings *DeviceSettings::settings() const { return m_settings; } void DeviceSettings::setSettings(Settings *settings) { if (m_settings != settings) { m_settings = settings; emit settingsChanged(); } } QVariant DeviceSettings::get(const QString& settingsKey, const QString& hashKey) const { if (!m_props.contains(hashKey)) { qFatal("%s not found", qPrintable(hashKey)); return QVariant(); } QVariant defaultValue = m_props[hashKey]; QString key = QString("%1/%2").arg(m_id).arg(settingsKey); return m_settings->value(key, defaultValue); } void DeviceSettings::set(const QString& key, const QVariant& value) { QString settingsKey = QString("%1/%2").arg(m_id).arg(key); m_settings->setValue(settingsKey, value); } int DeviceSettings::imageSceneMode() const { return get("image/sceneMode", IMAGE_SCENE_MODE_KEY).toInt(); } void DeviceSettings::setImageSceneMode(int mode) { if (imageSceneMode() != mode) { set("image/sceneMode", mode); emit imageSceneModeChanged(); } } int DeviceSettings::imageColorFilter() const { return get("image/colorFilter", IMAGE_COLOR_FILTER_KEY).toInt(); } void DeviceSettings::setImageColorFilter(int filter) { if (imageColorFilter() != filter) { set("image/colorFilter", filter); emit imageColorFilterChanged(); } } int DeviceSettings::imageWhiteBalance() const { return get("image/whiteBalance", IMAGE_WHITE_BALANCE_KEY).toInt(); } void DeviceSettings::setImageWhiteBalance(int wb) { if (imageWhiteBalance() != wb) { set("image/whiteBalance", wb); emit imageWhiteBalanceChanged(); } } qreal DeviceSettings::imageEvComp() const { return get("image/evComp", IMAGE_EV_COMP_KEY).toReal(); } void DeviceSettings::setImageEvComp(qreal ev) { if (!qFuzzyCompare(imageEvComp(), ev)) { set("image/evComp", ev); emit imageEvCompChanged(); } } int DeviceSettings::videoSceneMode() const { return get("video/sceneMode", VIDEO_SCENE_MODE_KEY).toInt(); } void DeviceSettings::setVideoSceneMode(int mode) { if (videoSceneMode() != mode) { set("video/sceneMode", mode); emit videoSceneModeChanged(); } } int DeviceSettings::videoColorFilter() const { return get("video/colorFilter", VIDEO_COLOR_FILTER_KEY).toInt(); } void DeviceSettings::setVideoColorFilter(int filter) { if (videoColorFilter() != filter) { set("video/colorFilter", filter); emit videoColorFilterChanged(); } } int DeviceSettings::videoWhiteBalance() const { return get("video/whiteBalance", VIDEO_WHITE_BALANCE_KEY).toInt(); } void DeviceSettings::setVideoWhiteBalance(int wb) { if (videoWhiteBalance() != wb) { set("video/whiteBalance", wb); emit videoWhiteBalanceChanged(); } } qreal DeviceSettings::videoEvComp() const { return get("video/evComp", VIDEO_EV_COMP_KEY).toReal(); } void DeviceSettings::setVideoEvComp(qreal ev) { if (!qFuzzyCompare(videoEvComp(), ev)) { set("video/evComp", ev); emit videoEvCompChanged(); } } int DeviceSettings::imageFlashMode() const { return get("image/flashMode", IMAGE_FLASH_MODE_KEY).toInt(); } void DeviceSettings::setImageFlashMode(int mode) { if (imageFlashMode() != mode) { set("image/flashMode", mode); emit imageFlashModeChanged(); } } int DeviceSettings::imageIso() const { return get("image/iso", IMAGE_ISO_KEY).toInt(); } void DeviceSettings::setImageIso(int iso) { if (imageIso() != iso) { set("image/iso", iso); emit imageIsoChanged(); } } QString DeviceSettings::imageAspectRatio() const { return get("image/aspectRatio", IMAGE_ASPECT_RATIO_KEY).toString(); } void DeviceSettings::setImageAspectRatio(const QString& aspectRatio) { if (imageAspectRatio() != aspectRatio) { set("image/aspectRatio", aspectRatio); emit imageAspectRatioChanged(); } } QString DeviceSettings::imageResolution() const { return get("image/resolution", IMAGE_RESOLUTION_KEY).toString(); } void DeviceSettings::setImageResolution(const QString& resolution) { if (imageResolution() != resolution) { set("image/resolution", resolution); emit imageResolutionChanged(); } } QString DeviceSettings::videoAspectRatio() const { return get("video/aspectRatio", VIDEO_ASPECT_RATIO_KEY).toString(); } void DeviceSettings::setVideoAspectRatio(const QString& aspectRatio) { if (videoAspectRatio() != aspectRatio) { set("video/aspectRatio", aspectRatio); emit videoAspectRatioChanged(); } } QString DeviceSettings::videoResolution() const { return get("video/resolution", VIDEO_RESOLUTION_KEY).toString(); } void DeviceSettings::setVideoResolution(const QString& resolution) { if (videoResolution() != resolution) { set("video/resolution", resolution); emit videoResolutionChanged(); } } bool DeviceSettings::isVideoTorchOn() const { return get("video/torchOn", VIDEO_TORCH_ON_KEY).toBool(); } void DeviceSettings::setVideoTorchOn(bool on) { if (isVideoTorchOn() != on) { set("video/torchOn", on); emit videoTorchOnChanged(); } } bool DeviceSettings::isVideoMuted() const { return get("video/mute", VIDEO_MUTE_KEY).toBool(); } void DeviceSettings::setVideoMuted(bool muted) { if (isVideoMuted() != muted) { set("video/mute", muted); emit videoMutedChanged(); } } <commit_msg>sailfish: Fix secondary camera image and video default<commit_after>// -*- c++ -*- /*! * This file is part of CameraPlus. * * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "devicesettings.h" #include "settings.h" #define IMAGE_RESOLUTION_KEY "imageResolution" #define IMAGE_ASPECT_RATIO_KEY "imageAspectRatio" #define VIDEO_RESOLUTION_KEY "videoResolution" #define VIDEO_ASPECT_RATIO_KEY "videoAspectRatio" #define IMAGE_SCENE_MODE_KEY "imageSceneMode" #define VIDEO_SCENE_MODE_KEY "videoSceneMode" #define IMAGE_COLOR_FILTER_KEY "imageColorFilter" #define VIDEO_COLOR_FILTER_KEY "videoColorFilter" #define IMAGE_WHITE_BALANCE_KEY "imageWhiteBalance" #define VIDEO_WHITE_BALANCE_KEY "videoWhiteBalance" #define IMAGE_EV_COMP_KEY "imageEvComp" #define VIDEO_EV_COMP_KEY "videoEvComp" #define IMAGE_FLASH_MODE_KEY "imageFlashMode" #define VIDEO_TORCH_ON_KEY "videoTorchOn" #define IMAGE_ISO_KEY "imageIso" #define VIDEO_MUTE_KEY "videoMute" PrimaryDeviceSettings::PrimaryDeviceSettings(QObject *parent) : DeviceSettings(parent) { QHash<QString, QVariant> props; props[IMAGE_RESOLUTION_KEY] = "high"; props[IMAGE_ASPECT_RATIO_KEY] = "16:9"; props[VIDEO_RESOLUTION_KEY] = "high"; props[VIDEO_ASPECT_RATIO_KEY] = "16:9"; props[IMAGE_SCENE_MODE_KEY] = 6; props[VIDEO_SCENE_MODE_KEY] = 6; props[IMAGE_COLOR_FILTER_KEY] = 0; props[VIDEO_COLOR_FILTER_KEY] = 0; props[IMAGE_WHITE_BALANCE_KEY] = 0; props[VIDEO_WHITE_BALANCE_KEY] = 0; props[IMAGE_EV_COMP_KEY] = 0.0; props[VIDEO_EV_COMP_KEY] = 0.0; props[IMAGE_FLASH_MODE_KEY] = 0; props[VIDEO_TORCH_ON_KEY] = false; props[IMAGE_ISO_KEY] = 0; props[VIDEO_MUTE_KEY] = false; init("primary", props); } SecondaryDeviceSettings::SecondaryDeviceSettings(QObject *parent) : DeviceSettings(parent) { QHash<QString, QVariant> props; #ifdef SAILFISH props[IMAGE_RESOLUTION_KEY] = "high"; props[IMAGE_ASPECT_RATIO_KEY] = "16:9"; props[VIDEO_RESOLUTION_KEY] = "high"; props[VIDEO_ASPECT_RATIO_KEY] = "16:9"; #else props[IMAGE_RESOLUTION_KEY] = "low"; props[IMAGE_ASPECT_RATIO_KEY] = "4:3"; props[VIDEO_RESOLUTION_KEY] = "low"; props[VIDEO_ASPECT_RATIO_KEY] = "4:3"; #endif props[IMAGE_SCENE_MODE_KEY] = 6; props[VIDEO_SCENE_MODE_KEY] = 6; props[IMAGE_COLOR_FILTER_KEY] = 0; props[VIDEO_COLOR_FILTER_KEY] = 0; props[IMAGE_WHITE_BALANCE_KEY] = 0; props[VIDEO_WHITE_BALANCE_KEY] = 0; props[IMAGE_EV_COMP_KEY] = 0.0; props[VIDEO_EV_COMP_KEY] = 0.0; props[IMAGE_FLASH_MODE_KEY] = 0; props[VIDEO_TORCH_ON_KEY] = false; props[IMAGE_ISO_KEY] = 0; props[VIDEO_MUTE_KEY] = false; init("secondary", props); } DeviceSettings::DeviceSettings(QObject *parent) : QObject(parent), m_settings(0) { } DeviceSettings::~DeviceSettings() { m_settings = 0; } void DeviceSettings::init(const QString& id, const QHash<QString, QVariant>& props) { m_id = id; m_props = props; } Settings *DeviceSettings::settings() const { return m_settings; } void DeviceSettings::setSettings(Settings *settings) { if (m_settings != settings) { m_settings = settings; emit settingsChanged(); } } QVariant DeviceSettings::get(const QString& settingsKey, const QString& hashKey) const { if (!m_props.contains(hashKey)) { qFatal("%s not found", qPrintable(hashKey)); return QVariant(); } QVariant defaultValue = m_props[hashKey]; QString key = QString("%1/%2").arg(m_id).arg(settingsKey); return m_settings->value(key, defaultValue); } void DeviceSettings::set(const QString& key, const QVariant& value) { QString settingsKey = QString("%1/%2").arg(m_id).arg(key); m_settings->setValue(settingsKey, value); } int DeviceSettings::imageSceneMode() const { return get("image/sceneMode", IMAGE_SCENE_MODE_KEY).toInt(); } void DeviceSettings::setImageSceneMode(int mode) { if (imageSceneMode() != mode) { set("image/sceneMode", mode); emit imageSceneModeChanged(); } } int DeviceSettings::imageColorFilter() const { return get("image/colorFilter", IMAGE_COLOR_FILTER_KEY).toInt(); } void DeviceSettings::setImageColorFilter(int filter) { if (imageColorFilter() != filter) { set("image/colorFilter", filter); emit imageColorFilterChanged(); } } int DeviceSettings::imageWhiteBalance() const { return get("image/whiteBalance", IMAGE_WHITE_BALANCE_KEY).toInt(); } void DeviceSettings::setImageWhiteBalance(int wb) { if (imageWhiteBalance() != wb) { set("image/whiteBalance", wb); emit imageWhiteBalanceChanged(); } } qreal DeviceSettings::imageEvComp() const { return get("image/evComp", IMAGE_EV_COMP_KEY).toReal(); } void DeviceSettings::setImageEvComp(qreal ev) { if (!qFuzzyCompare(imageEvComp(), ev)) { set("image/evComp", ev); emit imageEvCompChanged(); } } int DeviceSettings::videoSceneMode() const { return get("video/sceneMode", VIDEO_SCENE_MODE_KEY).toInt(); } void DeviceSettings::setVideoSceneMode(int mode) { if (videoSceneMode() != mode) { set("video/sceneMode", mode); emit videoSceneModeChanged(); } } int DeviceSettings::videoColorFilter() const { return get("video/colorFilter", VIDEO_COLOR_FILTER_KEY).toInt(); } void DeviceSettings::setVideoColorFilter(int filter) { if (videoColorFilter() != filter) { set("video/colorFilter", filter); emit videoColorFilterChanged(); } } int DeviceSettings::videoWhiteBalance() const { return get("video/whiteBalance", VIDEO_WHITE_BALANCE_KEY).toInt(); } void DeviceSettings::setVideoWhiteBalance(int wb) { if (videoWhiteBalance() != wb) { set("video/whiteBalance", wb); emit videoWhiteBalanceChanged(); } } qreal DeviceSettings::videoEvComp() const { return get("video/evComp", VIDEO_EV_COMP_KEY).toReal(); } void DeviceSettings::setVideoEvComp(qreal ev) { if (!qFuzzyCompare(videoEvComp(), ev)) { set("video/evComp", ev); emit videoEvCompChanged(); } } int DeviceSettings::imageFlashMode() const { return get("image/flashMode", IMAGE_FLASH_MODE_KEY).toInt(); } void DeviceSettings::setImageFlashMode(int mode) { if (imageFlashMode() != mode) { set("image/flashMode", mode); emit imageFlashModeChanged(); } } int DeviceSettings::imageIso() const { return get("image/iso", IMAGE_ISO_KEY).toInt(); } void DeviceSettings::setImageIso(int iso) { if (imageIso() != iso) { set("image/iso", iso); emit imageIsoChanged(); } } QString DeviceSettings::imageAspectRatio() const { return get("image/aspectRatio", IMAGE_ASPECT_RATIO_KEY).toString(); } void DeviceSettings::setImageAspectRatio(const QString& aspectRatio) { if (imageAspectRatio() != aspectRatio) { set("image/aspectRatio", aspectRatio); emit imageAspectRatioChanged(); } } QString DeviceSettings::imageResolution() const { return get("image/resolution", IMAGE_RESOLUTION_KEY).toString(); } void DeviceSettings::setImageResolution(const QString& resolution) { if (imageResolution() != resolution) { set("image/resolution", resolution); emit imageResolutionChanged(); } } QString DeviceSettings::videoAspectRatio() const { return get("video/aspectRatio", VIDEO_ASPECT_RATIO_KEY).toString(); } void DeviceSettings::setVideoAspectRatio(const QString& aspectRatio) { if (videoAspectRatio() != aspectRatio) { set("video/aspectRatio", aspectRatio); emit videoAspectRatioChanged(); } } QString DeviceSettings::videoResolution() const { return get("video/resolution", VIDEO_RESOLUTION_KEY).toString(); } void DeviceSettings::setVideoResolution(const QString& resolution) { if (videoResolution() != resolution) { set("video/resolution", resolution); emit videoResolutionChanged(); } } bool DeviceSettings::isVideoTorchOn() const { return get("video/torchOn", VIDEO_TORCH_ON_KEY).toBool(); } void DeviceSettings::setVideoTorchOn(bool on) { if (isVideoTorchOn() != on) { set("video/torchOn", on); emit videoTorchOnChanged(); } } bool DeviceSettings::isVideoMuted() const { return get("video/mute", VIDEO_MUTE_KEY).toBool(); } void DeviceSettings::setVideoMuted(bool muted) { if (isVideoMuted() != muted) { set("video/mute", muted); emit videoMutedChanged(); } } <|endoftext|>
<commit_before> #include <planet/common.hpp> #include <planet/fs_core.hpp> #include <planet/basic_operation.hpp> #include <planet/operation_layer.hpp> #include <planet/utils.hpp> #include <planet/module_loader/module_loader.hpp> #include <planet/request_parser.hpp> #include <mutex> namespace planet { // // module_loader_op // module_loader_op::module_loader_op(shared_ptr<core_file_system> fs_root) : fs_root_(fs_root) { } module_loader_op::module_loader_op( shared_ptr<core_file_system> fs_root, std::vector<string_type> const& paths ) : fs_root_(fs_root), paths_(paths) { } int module_loader_op::open(shared_ptr<fs_entry> file_ent, path_type const& path) { return 0; } int module_loader_op::read(shared_ptr<fs_entry> file_ent, char *buf, size_t size, off_t offset) { int ret = 0; std::call_once(once_flag_, [this](){ this->info_ = fs_root_->get_ops_db().info(); this->it_ = info_.begin(); }); if (it_ != info_.end()) { string_type line = std::get<0>(*it_) + '\t' + lexical_cast<string_type>(std::get<1>(*it_)); ret = (line.length() + 2 > size) ? size : line.length() + 2; std::copy_n(line.begin(), ret - 2, buf); buf[ret - 2] = '\n'; buf[ret - 1] = '\0'; ++it_; } return ret; } int module_loader_op::write(shared_ptr<fs_entry> file_ent, char const *buf, size_t size, off_t offset) { int ret = size; request_parser parser; if (parser.parse(string_type(buf, size))) { typedef core_file_system::priority priority; if (parser.get_command() == "load") for (auto&& mod_name : parser.get_args()) fs_root_->install_module(priority::normal, mod_name[0], paths_); else if (parser.get_command() == "unload") for (auto&& mod_name : parser.get_args()) fs_root_->uninstall_module(mod_name[0]); } else ret = -ENOTSUP; return ret; } int module_loader_op::release(shared_ptr<fs_entry> file_ent) { return 0; } // // module_loader // string_type const module_loader::file_path = "/modules"; module_loader::module_loader() : file_ops_type("planet.module_loader") { char cwd[PATH_MAX]; if (!::getcwd(cwd, sizeof cwd)) throw_system_error(errno, "getting cwd"); cwd_ = cwd; } int module_loader::install(shared_ptr<core_file_system> fs_root) { fs_root->mknod(module_loader::file_path, 0666); return 0; } int module_loader::uninstall(shared_ptr<core_file_system> fs_root) { fs_root->unlink(module_loader::file_path); return 0; } shared_ptr<entry_op> module_loader::create_op(shared_ptr<core_file_system> fs_root) { return make_shared<module_loader_op>(fs_root, std::vector<string_type>{cwd_}); } bool module_loader::match_path(path_type const& path, file_type type) { return path == module_loader::file_path && type == file_type::regular_file; } } // namespace planet <commit_msg>module_loader: don't insert '\0' into each module info<commit_after> #include <planet/common.hpp> #include <planet/fs_core.hpp> #include <planet/basic_operation.hpp> #include <planet/operation_layer.hpp> #include <planet/utils.hpp> #include <planet/module_loader/module_loader.hpp> #include <planet/request_parser.hpp> #include <mutex> namespace planet { // // module_loader_op // module_loader_op::module_loader_op(shared_ptr<core_file_system> fs_root) : fs_root_(fs_root) { } module_loader_op::module_loader_op( shared_ptr<core_file_system> fs_root, std::vector<string_type> const& paths ) : fs_root_(fs_root), paths_(paths) { } int module_loader_op::open(shared_ptr<fs_entry> file_ent, path_type const& path) { return 0; } int module_loader_op::read(shared_ptr<fs_entry> file_ent, char *buf, size_t size, off_t offset) { int ret = 0; std::call_once(once_flag_, [this](){ this->info_ = fs_root_->get_ops_db().info(); this->it_ = info_.begin(); }); if (it_ != info_.end()) { string_type line = std::get<0>(*it_) + '\t' + lexical_cast<string_type>(std::get<1>(*it_)); ret = (line.length() + 1 > size) ? size : line.length() + 1; std::copy_n(line.begin(), ret - 1, buf); buf[ret - 1] = '\n'; ++it_; } return ret; } int module_loader_op::write(shared_ptr<fs_entry> file_ent, char const *buf, size_t size, off_t offset) { int ret = size; request_parser parser; if (parser.parse(string_type(buf, size))) { typedef core_file_system::priority priority; if (parser.get_command() == "load") for (auto&& mod_name : parser.get_args()) fs_root_->install_module(priority::normal, mod_name[0], paths_); else if (parser.get_command() == "unload") for (auto&& mod_name : parser.get_args()) fs_root_->uninstall_module(mod_name[0]); } else ret = -ENOTSUP; return ret; } int module_loader_op::release(shared_ptr<fs_entry> file_ent) { return 0; } // // module_loader // string_type const module_loader::file_path = "/modules"; module_loader::module_loader() : file_ops_type("planet.module_loader") { char cwd[PATH_MAX]; if (!::getcwd(cwd, sizeof cwd)) throw_system_error(errno, "getting cwd"); cwd_ = cwd; } int module_loader::install(shared_ptr<core_file_system> fs_root) { fs_root->mknod(module_loader::file_path, 0666); return 0; } int module_loader::uninstall(shared_ptr<core_file_system> fs_root) { fs_root->unlink(module_loader::file_path); return 0; } shared_ptr<entry_op> module_loader::create_op(shared_ptr<core_file_system> fs_root) { return make_shared<module_loader_op>(fs_root, std::vector<string_type>{cwd_}); } bool module_loader::match_path(path_type const& path, file_type type) { return path == module_loader::file_path && type == file_type::regular_file; } } // namespace planet <|endoftext|>
<commit_before>#include "onig-scanner-worker.h" #include "unicode-utils.h" using ::v8::Array; using ::v8::Local; using ::v8::Null; using ::v8::Number; using ::v8::Object; using ::v8::String; using ::v8::Value; void OnigScannerWorker::Execute() { bestResult = searcher->Search(stringToSearch, utf16StringToSearch.get(), hasMultibyteCharacters, charOffset); } void OnigScannerWorker::HandleOKCallback() { NanScope(); // Try to reuse the cached results across async searches cache->Reset(searcher->GetCache()); if (bestResult != NULL) { Local<Object> result = Object::New(); result->Set(String::NewSymbol("index"), Number::New(bestResult.get()->Index())); int resultCount = bestResult->Count(); Local<Array> captures = Array::New(resultCount); for (int index = 0; index < resultCount; index++) { int captureLength = bestResult->LengthAt(index); int captureStart = bestResult->LocationAt(index); if (hasMultibyteCharacters) { captureLength = UnicodeUtils::characters_in_bytes(stringToSearch.data() + captureStart, captureLength); captureStart = UnicodeUtils::characters_in_bytes(stringToSearch.data(), captureStart); } Local<Object> capture = Object::New(); capture->Set(String::NewSymbol("index"), Number::New(index)); capture->Set(String::NewSymbol("start"), Number::New(captureStart)); capture->Set(String::NewSymbol("end"), Number::New(captureStart + captureLength)); capture->Set(String::NewSymbol("length"), Number::New(captureLength)); captures->Set(index, capture); } result->Set(String::NewSymbol("captureIndices"), captures); Local<Value> argv[] = { Local<Value>::New(Null()), Local<Value>::New(result) }; callback->Call(2, argv); } else { Local<Value> argv[] = { Local<Value>::New(Null()), Local<Value>::New(Null()) }; callback->Call(2, argv); } } <commit_msg>Remove unneeded get()<commit_after>#include "onig-scanner-worker.h" #include "unicode-utils.h" using ::v8::Array; using ::v8::Local; using ::v8::Null; using ::v8::Number; using ::v8::Object; using ::v8::String; using ::v8::Value; void OnigScannerWorker::Execute() { bestResult = searcher->Search(stringToSearch, utf16StringToSearch.get(), hasMultibyteCharacters, charOffset); } void OnigScannerWorker::HandleOKCallback() { NanScope(); // Try to reuse the cached results across async searches cache->Reset(searcher->GetCache()); if (bestResult != NULL) { Local<Object> result = Object::New(); result->Set(String::NewSymbol("index"), Number::New(bestResult->Index())); int resultCount = bestResult->Count(); Local<Array> captures = Array::New(resultCount); for (int index = 0; index < resultCount; index++) { int captureLength = bestResult->LengthAt(index); int captureStart = bestResult->LocationAt(index); if (hasMultibyteCharacters) { captureLength = UnicodeUtils::characters_in_bytes(stringToSearch.data() + captureStart, captureLength); captureStart = UnicodeUtils::characters_in_bytes(stringToSearch.data(), captureStart); } Local<Object> capture = Object::New(); capture->Set(String::NewSymbol("index"), Number::New(index)); capture->Set(String::NewSymbol("start"), Number::New(captureStart)); capture->Set(String::NewSymbol("end"), Number::New(captureStart + captureLength)); capture->Set(String::NewSymbol("length"), Number::New(captureLength)); captures->Set(index, capture); } result->Set(String::NewSymbol("captureIndices"), captures); Local<Value> argv[] = { Local<Value>::New(Null()), Local<Value>::New(result) }; callback->Call(2, argv); } else { Local<Value> argv[] = { Local<Value>::New(Null()), Local<Value>::New(Null()) }; callback->Call(2, argv); } } <|endoftext|>
<commit_before>/* * This File is part of Davix, The IO library for HTTP based protocols * Copyright (C) CERN 2015 * Author: Georgios Bitzes <georgios.bitzes@cern.ch> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <utils/davix_azure_utils.hpp> #include <datetime/datetime_utils.hpp> #include <davix_internal.hpp> #include <utils/davix_logger_internal.hpp> #include <alibxx/crypto/hmacsha.hpp> #include <alibxx/crypto/base64.hpp> #define AZURE_TIME_LEEWAY 300 namespace Davix { namespace Azure { std::string extract_azure_account(const Uri & url) { std::string host = url.getHost(); return host.substr(0, host.find(".")); } std::string extract_azure_container(const Uri & url) { std::string path = url.getPath(); std::string name = path.substr(1, path.find("/", 1)); if(name.compare(name.size()-1,1,"/") == 0) { name.erase(name.size()-1, name.size()); } return name; } std::string extract_azure_filename(const Uri & url) { std::string path = url.getPath(); std::size_t sep = path.find("/", 1); if(sep == std::string::npos) return ""; return path.substr(path.find("/", 1)+1, path.size()); } std::string hexEncode(std::string input, std::string separator="") { std::ostringstream ss; for(std::string::iterator it = input.begin(); it != input.end(); it++) { ss << std::setw(2) << std::setfill('0') << std::hex << (unsigned int) ( (unsigned char) *it) << separator; } return ss.str(); } Uri transformURI(const Uri & original_url, const RequestParams & params, const bool addDelimiter) { Uri newUri = original_url; newUri.setPath("/" + extract_azure_container(original_url) + "/"); newUri.addQueryParam("restype", "container"); newUri.addQueryParam("comp", "list"); std::string filename = extract_azure_filename(original_url); if(filename[filename.size()-1] != '/') { filename.append("/"); } // special case: listing top-dir if(filename == "/") filename = ""; newUri.addQueryParam("prefix", filename); newUri.addQueryParam("delimiter", "/"); return newUri; } // wrapper function, try to figure out what resourceType and permissions to use, // based on the URL and the method. // Try to always give as restrictive permissions as possible. Uri signURI(const AzureSecretKey key, const std::string method, const Uri & url, const time_t signDuration) { if(method == "DELETE") { return signURI(key, Azure::Resource::BLOB, Azure::Permission::DELETE, url, signDuration); } else if(method == "PUT") { return signURI(key, Azure::Resource::BLOB, Azure::Permission::WRITE, url, signDuration); } else if(method == "GET") { const std::string filename = extract_azure_filename(url); if(filename.size() == 0) { return signURI(key, Azure::Resource::CONTAINER, Azure::Permission::LIST, url, signDuration); } return signURI(key, Azure::Resource::BLOB, Azure::Permission::READ, url, signDuration); } else if(method == "HEAD") { return signURI(key, Azure::Resource::BLOB, Azure::Permission::READ, url, signDuration); } throw std::runtime_error("unsupported method given to azure"); } Uri signURI(const AzureSecretKey key, const Azure::Resource::Type resourceType, const Azure::Permission::Type permissions, const Uri & url, const time_t signDuration) { // reference: https://msdn.microsoft.com/en-us/library/azure/dn140255.aspx DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_S3, "Signing Azure URL"); // build string to sign const std::string format("%Y-%m-%dT%H:%M:%SZ"); time_t present = time(NULL); std::string signedpermissions = permissions; std::string signedstart = time_as_string(present-AZURE_TIME_LEEWAY, format); std::string signedexpiry = time_as_string(present+signDuration, format); std::string canonicalizedresource; if(resourceType == Resource::CONTAINER) { canonicalizedresource = "/blob/" + extract_azure_account(url) + "/" + extract_azure_container(url); } else if(resourceType == Resource::BLOB) { canonicalizedresource = "/blob/" + extract_azure_account(url) + url.getPath(); } std::string signedidentifier; std::string signedIP; std::string signedProtocol; std::string signedversion("2015-04-05"); std::string rscc; std::string rscd; std::string rsce; std::string rscl; std::string rsct; std::ostringstream stringToSign; stringToSign << signedpermissions << "\n" << signedstart << "\n" << signedexpiry << "\n" << canonicalizedresource << "\n" << signedidentifier << "\n" << signedIP << "\n" << signedProtocol << "\n" << signedversion << "\n" << rscc << "\n" << rscd << "\n" << rsce << "\n" << rscl << "\n" << rsct; DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_S3, "string to sign: \n{}", stringToSign.str()); std::string decoded_key = Base64::base64_decode(key); std::string signature = hmac_sha256(decoded_key, stringToSign.str()); std::string base64sig = Base64::base64_encode((unsigned char*) signature.c_str(), signature.size()); DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_S3, "signature: {}", base64sig); // add query parameters std::string signedresource; if(resourceType == Resource::CONTAINER) { signedresource = "c"; } else if(resourceType == Resource::BLOB) { signedresource = "b"; } Uri signedUrl(url); signedUrl.addQueryParam("sv", signedversion); signedUrl.addQueryParam("st", signedstart); signedUrl.addQueryParam("se", signedexpiry); signedUrl.addQueryParam("sr", signedresource); signedUrl.addQueryParam("sp", signedpermissions); signedUrl.addQueryParam("sig", base64sig); DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_S3, "signed url: {}", signedUrl); return signedUrl; } } } <commit_msg>Update Azure API version to increase maximum BlobSize<commit_after>/* * This File is part of Davix, The IO library for HTTP based protocols * Copyright (C) CERN 2015 * Author: Georgios Bitzes <georgios.bitzes@cern.ch> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <utils/davix_azure_utils.hpp> #include <datetime/datetime_utils.hpp> #include <davix_internal.hpp> #include <utils/davix_logger_internal.hpp> #include <alibxx/crypto/hmacsha.hpp> #include <alibxx/crypto/base64.hpp> #define AZURE_TIME_LEEWAY 300 namespace Davix { namespace Azure { std::string extract_azure_account(const Uri & url) { std::string host = url.getHost(); return host.substr(0, host.find(".")); } std::string extract_azure_container(const Uri & url) { std::string path = url.getPath(); std::string name = path.substr(1, path.find("/", 1)); if(name.compare(name.size()-1,1,"/") == 0) { name.erase(name.size()-1, name.size()); } return name; } std::string extract_azure_filename(const Uri & url) { std::string path = url.getPath(); std::size_t sep = path.find("/", 1); if(sep == std::string::npos) return ""; return path.substr(path.find("/", 1)+1, path.size()); } std::string hexEncode(std::string input, std::string separator="") { std::ostringstream ss; for(std::string::iterator it = input.begin(); it != input.end(); it++) { ss << std::setw(2) << std::setfill('0') << std::hex << (unsigned int) ( (unsigned char) *it) << separator; } return ss.str(); } Uri transformURI(const Uri & original_url, const RequestParams & params, const bool addDelimiter) { Uri newUri = original_url; newUri.setPath("/" + extract_azure_container(original_url) + "/"); newUri.addQueryParam("restype", "container"); newUri.addQueryParam("comp", "list"); std::string filename = extract_azure_filename(original_url); if(filename[filename.size()-1] != '/') { filename.append("/"); } // special case: listing top-dir if(filename == "/") filename = ""; newUri.addQueryParam("prefix", filename); newUri.addQueryParam("delimiter", "/"); return newUri; } // wrapper function, try to figure out what resourceType and permissions to use, // based on the URL and the method. // Try to always give as restrictive permissions as possible. Uri signURI(const AzureSecretKey key, const std::string method, const Uri & url, const time_t signDuration) { if(method == "DELETE") { return signURI(key, Azure::Resource::BLOB, Azure::Permission::DELETE, url, signDuration); } else if(method == "PUT") { return signURI(key, Azure::Resource::BLOB, Azure::Permission::WRITE, url, signDuration); } else if(method == "GET") { const std::string filename = extract_azure_filename(url); if(filename.size() == 0) { return signURI(key, Azure::Resource::CONTAINER, Azure::Permission::LIST, url, signDuration); } return signURI(key, Azure::Resource::BLOB, Azure::Permission::READ, url, signDuration); } else if(method == "HEAD") { return signURI(key, Azure::Resource::BLOB, Azure::Permission::READ, url, signDuration); } throw std::runtime_error("unsupported method given to azure"); } Uri signURI(const AzureSecretKey key, const Azure::Resource::Type resourceType, const Azure::Permission::Type permissions, const Uri & url, const time_t signDuration) { // reference: https://msdn.microsoft.com/en-us/library/azure/dn140255.aspx DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_S3, "Signing Azure URL"); // build string to sign const std::string format("%Y-%m-%dT%H:%M:%SZ"); time_t present = time(NULL); std::string signedpermissions = permissions; std::string signedstart = time_as_string(present-AZURE_TIME_LEEWAY, format); std::string signedexpiry = time_as_string(present+signDuration, format); std::string canonicalizedresource; if(resourceType == Resource::CONTAINER) { canonicalizedresource = "/blob/" + extract_azure_account(url) + "/" + extract_azure_container(url); } else if(resourceType == Resource::BLOB) { canonicalizedresource = "/blob/" + extract_azure_account(url) + url.getPath(); } std::string signedidentifier; std::string signedIP; std::string signedProtocol; std::string signedversion("2016-05-31"); std::string rscc; std::string rscd; std::string rsce; std::string rscl; std::string rsct; std::ostringstream stringToSign; stringToSign << signedpermissions << "\n" << signedstart << "\n" << signedexpiry << "\n" << canonicalizedresource << "\n" << signedidentifier << "\n" << signedIP << "\n" << signedProtocol << "\n" << signedversion << "\n" << rscc << "\n" << rscd << "\n" << rsce << "\n" << rscl << "\n" << rsct; DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_S3, "string to sign: \n{}", stringToSign.str()); std::string decoded_key = Base64::base64_decode(key); std::string signature = hmac_sha256(decoded_key, stringToSign.str()); std::string base64sig = Base64::base64_encode((unsigned char*) signature.c_str(), signature.size()); DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_S3, "signature: {}", base64sig); // add query parameters std::string signedresource; if(resourceType == Resource::CONTAINER) { signedresource = "c"; } else if(resourceType == Resource::BLOB) { signedresource = "b"; } Uri signedUrl(url); signedUrl.addQueryParam("sv", signedversion); signedUrl.addQueryParam("st", signedstart); signedUrl.addQueryParam("se", signedexpiry); signedUrl.addQueryParam("sr", signedresource); signedUrl.addQueryParam("sp", signedpermissions); signedUrl.addQueryParam("sig", base64sig); DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_S3, "signed url: {}", signedUrl); return signedUrl; } } } <|endoftext|>
<commit_before>#undef _FORTIFY_SOURCE #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <vector> #include <string> #include <map> #include <reader.h> #include "nanosvg.h" #include "nanosvgrast.h" using namespace std; map<string, int> layer_offsets; int sx, sx8, sy; void bad_pixel(const char *layer, int pix, int p2, const unsigned char *src) { int x = (pix % sx8) * 8 + p2; int y = sy - 1 - pix / sx8; fprintf(stderr, "Bad pixel in layer %s, x=%d y=%d color=#%02x%02x%02x%02x\n", layer, x, y, src[3], src[2], src[1], src[0]); exit(1); } static int iabs(int v) { return v >= 0 ? v : -v; } void test_pixel_blue(const char *layer, int pix, int p2, const unsigned char *src) { if(src[0] || src[1]) bad_pixel(layer, pix, p2, src); } void test_pixel_red(const char *layer, int pix, int p2, const unsigned char *src) { if(src[1] || src[2]) bad_pixel(layer, pix, p2, src); } void test_pixel_black(const char *layer, int pix, int p2, const unsigned char *src) { if(src[2] || src[1] || src[0]) bad_pixel(layer, pix, p2, src); } void test_pixel_pink(const char *layer, int pix, int p2, const unsigned char *src) { if(src[1] || !src[0] || src[0] != src[2]) bad_pixel(layer, pix, p2, src); } void test_pixel_vias(const char *layer, int pix, int p2, const unsigned char *src) { if(src[0] != src[1] || src[0] != src[2]) bad_pixel(layer, pix, p2, src); } void test_pixel_green(const char *layer, int pix, int p2, const unsigned char *src) { if(src[0] || src[2]) bad_pixel(layer, pix, p2, src); } void test_pixel_yellow(const char *layer, int pix, int p2, const unsigned char *src) { if(src[0] || !src[2] || src[2] != src[3]) bad_pixel(layer, pix, p2, src); } struct test_f { const char *name; void (*test_function)(const char *, int, int, const unsigned char *); }; test_f test_functions[] = { { "blue", test_pixel_blue }, { "red", test_pixel_red }, { "black", test_pixel_black }, { "pink", test_pixel_pink }, { "vias", test_pixel_vias }, { "green", test_pixel_green }, { "yellow", test_pixel_yellow }, { NULL, NULL }, }; int main(int argc, char **argv) { if(argc != 2) { fprintf(stderr, "Usage:\n%s config.txt\n", argv[0]); exit(1); } reader rd(argv[1]); const char *fname = rd.gw(); sx = rd.gi(); sy = rd.gi(); rd.nl(); sx8 = (sx+7)/8; char buf[4096]; vector<char> svg; vector<unsigned char> pbm; pbm.resize(256); int off = sprintf((char *)&pbm[0], "P4\n%d %d\n", sx, sy); pbm.resize(off + sx8*sy); sprintf(buf, "Open %s", fname); int fd = open(fname, O_RDONLY); if(fd<0) { perror(buf); exit(2); } int size = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); svg.resize(size+1); read(fd, &svg[0], size); svg[size] = 0; close(fd); for(int pos=0; pos < int(svg.size()) - 32; pos++) { if(!memcmp(&svg[pos], "inkscape:label=\"", 16)) { int l = 0; while(l < 511) { if(svg[pos+16+l] == '"') break; buf[l] = svg[pos+16+l]; l++; } buf[l] = 0; while(memcmp(&svg[pos], "style=\"display:", 15)) pos++; pos += 15; if(!memcmp(&svg[pos], "none\"", 5)) { svg.resize(svg.size()+2); memmove(&svg[pos]+2, &svg[pos], svg.size()-2-pos); } memcpy(&svg[pos], "none\" ", 7); layer_offsets[buf] = pos; fprintf(stderr, "layer [%s]\n", buf); } } unsigned char *out = new unsigned char[sx*sy*4]; NSVGrasterizer *rast = nsvgCreateRasterizer(); while(!rd.eof()) { const char *image_name = rd.gw(); const char *test_name = rd.gw(); const char *layer_name = rd.gwnl(); rd.nl(); printf("%s\n", layer_name); fflush(stdout); for(map<string, int>::const_iterator j = layer_offsets.begin(); j != layer_offsets.end(); j++) memcpy(&svg[j->second], j->first == layer_name ? "inline\"" : "none\" ", 7); char *s = strdup(&svg[0]); NSVGimage *svgimg = nsvgParse(s, "px", 72); free(s); nsvgRasterize(rast, svgimg, 0, 0, 1, out, sx, sy, sx*4); nsvgDelete(svgimg); unsigned char *src = out; unsigned char *dst = &pbm[off]; void (*test_pixel)(const char *layer, int, int, const unsigned char *) = NULL; for(int j=0; test_functions[j].name; j++) if(!strcmp(test_name, test_functions[j].name)) { test_pixel = test_functions[j].test_function; break; } if(!test_pixel) { fprintf(stderr, "Error: test function %s not found\n", test_name); exit(1); } for(int pix=0; pix<sx8*sy; pix++) { unsigned char v = 0; for(int p2=0; p2<8; p2++) { if((pix % sx8)*8 + p2 >= sx) v |= 0x80 >> p2; else { if(!src[3]) v |= 0x80 >> p2; else test_pixel(layer_name, pix, p2, src); src += 4; } } *dst++ = v; } sprintf(buf, "%s.pbm", image_name); fd = open(buf, O_RDWR|O_CREAT|O_TRUNC, 0666); if(fd<0) { perror(buf); exit(2); } write(fd, &pbm[0], pbm.size()); close(fd); } delete[] out; nsvgDeleteRasterizer(rast); return 0; } <commit_msg>fix yellow<commit_after>#undef _FORTIFY_SOURCE #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <vector> #include <string> #include <map> #include <reader.h> #include "nanosvg.h" #include "nanosvgrast.h" using namespace std; map<string, int> layer_offsets; int sx, sx8, sy; void bad_pixel(const char *layer, int pix, int p2, const unsigned char *src) { int x = (pix % sx8) * 8 + p2; int y = sy - 1 - pix / sx8; fprintf(stderr, "Bad pixel in layer %s, x=%d y=%d color=#%02x%02x%02x%02x\n", layer, x, y, src[3], src[2], src[1], src[0]); exit(1); } static int iabs(int v) { return v >= 0 ? v : -v; } void test_pixel_blue(const char *layer, int pix, int p2, const unsigned char *src) { if(src[0] || src[1]) bad_pixel(layer, pix, p2, src); } void test_pixel_red(const char *layer, int pix, int p2, const unsigned char *src) { if(src[1] || src[2]) bad_pixel(layer, pix, p2, src); } void test_pixel_black(const char *layer, int pix, int p2, const unsigned char *src) { if(src[2] || src[1] || src[0]) bad_pixel(layer, pix, p2, src); } void test_pixel_pink(const char *layer, int pix, int p2, const unsigned char *src) { if(src[1] || !src[0] || src[0] != src[2]) bad_pixel(layer, pix, p2, src); } void test_pixel_vias(const char *layer, int pix, int p2, const unsigned char *src) { if(src[0] != src[1] || src[0] != src[2]) bad_pixel(layer, pix, p2, src); } void test_pixel_green(const char *layer, int pix, int p2, const unsigned char *src) { if(src[0] || src[2]) bad_pixel(layer, pix, p2, src); } void test_pixel_yellow(const char *layer, int pix, int p2, const unsigned char *src) { if(src[2] || !src[3] || src[0] != src[1]) bad_pixel(layer, pix, p2, src); } struct test_f { const char *name; void (*test_function)(const char *, int, int, const unsigned char *); }; test_f test_functions[] = { { "blue", test_pixel_blue }, { "red", test_pixel_red }, { "black", test_pixel_black }, { "pink", test_pixel_pink }, { "vias", test_pixel_vias }, { "green", test_pixel_green }, { "yellow", test_pixel_yellow }, { NULL, NULL }, }; int main(int argc, char **argv) { if(argc != 2) { fprintf(stderr, "Usage:\n%s config.txt\n", argv[0]); exit(1); } reader rd(argv[1]); const char *fname = rd.gw(); sx = rd.gi(); sy = rd.gi(); rd.nl(); sx8 = (sx+7)/8; char buf[4096]; vector<char> svg; vector<unsigned char> pbm; pbm.resize(256); int off = sprintf((char *)&pbm[0], "P4\n%d %d\n", sx, sy); pbm.resize(off + sx8*sy); sprintf(buf, "Open %s", fname); int fd = open(fname, O_RDONLY); if(fd<0) { perror(buf); exit(2); } int size = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); svg.resize(size+1); read(fd, &svg[0], size); svg[size] = 0; close(fd); for(int pos=0; pos < int(svg.size()) - 32; pos++) { if(!memcmp(&svg[pos], "inkscape:label=\"", 16)) { int l = 0; while(l < 511) { if(svg[pos+16+l] == '"') break; buf[l] = svg[pos+16+l]; l++; } buf[l] = 0; while(memcmp(&svg[pos], "style=\"display:", 15)) pos++; pos += 15; if(!memcmp(&svg[pos], "none\"", 5)) { svg.resize(svg.size()+2); memmove(&svg[pos]+2, &svg[pos], svg.size()-2-pos); } memcpy(&svg[pos], "none\" ", 7); layer_offsets[buf] = pos; fprintf(stderr, "layer [%s]\n", buf); } } unsigned char *out = new unsigned char[sx*sy*4]; NSVGrasterizer *rast = nsvgCreateRasterizer(); while(!rd.eof()) { const char *image_name = rd.gw(); const char *test_name = rd.gw(); const char *layer_name = rd.gwnl(); rd.nl(); printf("%s\n", layer_name); fflush(stdout); for(map<string, int>::const_iterator j = layer_offsets.begin(); j != layer_offsets.end(); j++) memcpy(&svg[j->second], j->first == layer_name ? "inline\"" : "none\" ", 7); char *s = strdup(&svg[0]); NSVGimage *svgimg = nsvgParse(s, "px", 72); free(s); nsvgRasterize(rast, svgimg, 0, 0, 1, out, sx, sy, sx*4); nsvgDelete(svgimg); unsigned char *src = out; unsigned char *dst = &pbm[off]; void (*test_pixel)(const char *layer, int, int, const unsigned char *) = NULL; for(int j=0; test_functions[j].name; j++) if(!strcmp(test_name, test_functions[j].name)) { test_pixel = test_functions[j].test_function; break; } if(!test_pixel) { fprintf(stderr, "Error: test function %s not found\n", test_name); exit(1); } for(int pix=0; pix<sx8*sy; pix++) { unsigned char v = 0; for(int p2=0; p2<8; p2++) { if((pix % sx8)*8 + p2 >= sx) v |= 0x80 >> p2; else { if(!src[3]) v |= 0x80 >> p2; else test_pixel(layer_name, pix, p2, src); src += 4; } } *dst++ = v; } sprintf(buf, "%s.pbm", image_name); fd = open(buf, O_RDWR|O_CREAT|O_TRUNC, 0666); if(fd<0) { perror(buf); exit(2); } write(fd, &pbm[0], pbm.size()); close(fd); } delete[] out; nsvgDeleteRasterizer(rast); return 0; } <|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) 2012 Sergey Lisitsyn * Copyright (C) 2012 Jiayu Zhou and Jieping Ye */ #include <shogun/lib/malsar/malsar_clustered.h> #ifdef HAVE_EIGEN3 #include <shogun/mathematics/Math.h> #include <shogun/mathematics/eigen3.h> #include <iostream> #include <shogun/lib/external/libqp.h> using namespace Eigen; using namespace std; namespace shogun { static double* H_diag_matrix; static int H_diag_matrix_ld; static const double* get_col(uint32_t j) { return H_diag_matrix + j*H_diag_matrix_ld; } malsar_result_t malsar_clustered( CDotFeatures* features, double* y, double rho1, double rho2, const malsar_options& options) { int task; int n_feats = features->get_dim_feature_space(); SG_SDEBUG("n feats = %d\n", n_feats); int n_vecs = features->get_num_vectors(); SG_SDEBUG("n vecs = %d\n", n_vecs); int n_tasks = options.n_tasks; SG_SDEBUG("n tasks = %d\n", n_tasks); H_diag_matrix = SG_CALLOC(double, n_tasks*n_tasks); for (int i=0; i<n_tasks; i++) H_diag_matrix[i*n_tasks+i] = 2.0; H_diag_matrix_ld = n_tasks; int iter = 0; // initialize weight vector and bias for each task MatrixXd Ws = MatrixXd::Zero(n_feats, n_tasks); VectorXd Cs = VectorXd::Zero(n_tasks); MatrixXd Ms = MatrixXd::Identity(n_tasks, n_tasks)*options.n_clusters/n_tasks; MatrixXd IM = Ms; MatrixXd IMsqinv = Ms; MatrixXd invEtaMWt = Ms; MatrixXd Wz=Ws, Wzp=Ws, Wz_old=Ws, delta_Wzp=Ws, gWs=Ws; VectorXd Cz=Cs, Czp=Cs, Cz_old=Cs, delta_Czp=Cs, gCs=Cs; MatrixXd Mz=Ms, Mzp=Ms, Mz_old=Ms, delta_Mzp=Ms, gMs=Ms; MatrixXd Mzp_Pz; double eta = rho2/rho1; double c = rho1*eta*(1+eta); double t=1, t_old=0; double gamma=1, gamma_inc=2; double obj=0.0, obj_old=0.0; double* diag_H = SG_MALLOC(double, n_tasks); double* f = SG_MALLOC(double, n_tasks); double* a = SG_MALLOC(double, n_tasks); double* lb = SG_MALLOC(double, n_tasks); double* ub = SG_MALLOC(double, n_tasks); double* x = SG_CALLOC(double, n_tasks); internal::set_is_malloc_allowed(false); bool done = false; while (!done && iter <= options.max_iter) { double alpha = double(t_old - 1)/t; SG_SDEBUG("alpha=%f\n",alpha); // compute search point Ws = (1+alpha)*Wz - alpha*Wz_old; Cs = (1+alpha)*Cz - alpha*Cz_old; Ms = (1+alpha)*Mz - alpha*Mz_old; // zero gradient gWs.setZero(); gCs.setZero(); internal::set_is_malloc_allowed(true); SG_SDEBUG("Computing gradient\n"); IM = (eta*MatrixXd::Identity(n_tasks,n_tasks)+Ms); // cout << "M" << endl << Ms << endl; // cout << "IM" << endl << IM << endl; IMsqinv = (IM*IM).inverse(); invEtaMWt = IM.inverse()*Ws.transpose(); //cout << "invEtaMWt" << endl << invEtaMWt << endl; gMs.noalias() = -c*(Ws.transpose()*Ws)*IMsqinv; gWs.noalias() += 2*c*invEtaMWt.transpose(); internal::set_is_malloc_allowed(false); // compute gradient and objective at search point double Fs = 0; for (task=0; task<n_tasks; task++) { SGVector<index_t> task_idx = options.tasks_indices[task]; int n_vecs_task = task_idx.vlen; for (int i=0; i<n_vecs_task; i++) { double aa = -y[task_idx[i]]*(features->dense_dot(task_idx[i], Ws.col(task).data(), n_feats)+Cs[task]); double bb = CMath::max(aa,0.0); // avoid underflow when computing exponential loss Fs += (CMath::log(CMath::exp(-bb) + CMath::exp(aa-bb)) + bb)/n_vecs_task; double b = -y[task_idx[i]]*(1 - 1/(1+CMath::exp(aa)))/n_vecs_task; gCs[task] += b; features->add_to_dense_vec(b, task_idx[i], gWs.col(task).data(), n_feats); } } //cout << "gWs" << endl << gWs << endl; //cout << "gCs" << endl << gCs << endl; SG_SDEBUG("Computed gradient\n"); // add regularizer Fs += c*(Ws*invEtaMWt).trace(); SG_SDEBUG("Fs = %f \n", Fs); double Fzp = 0.0; int inner_iter = 0; // line search, Armijo-Goldstein scheme while (inner_iter <= 1000) { Wzp = Ws - gWs/gamma; Czp = Cs - gCs/gamma; // compute singular projection of Ms - gMs/gamma with k internal::set_is_malloc_allowed(true); EigenSolver<MatrixXd> eigensolver(Ms-gMs/gamma); // solve problem // min sum_i (s_i - s*_i)^2 s.t. sum_i s_i = k, 0<=s_i<=1 for (int i=0; i<n_tasks; i++) { diag_H[i] = 2.0; f[i] = -2*eigensolver.eigenvalues()[i].real(); SG_SDEBUG("%dth eigenvalue %f\n",i,eigensolver.eigenvalues()[i].real()); a[i] = 1.0; lb[i] = 0.0; ub[i] = 1.0; x[i] = double(options.n_clusters)/n_tasks; } double b = options.n_clusters;//eigensolver.eigenvalues().sum().real(); SG_SDEBUG("b = %f\n", b); SG_SDEBUG("Calling libqp\n"); libqp_state_T problem_state = libqp_gsmo_solver(&get_col,diag_H,f,a,b,lb,ub,x,n_tasks,1000,1e-6,NULL); SG_SDEBUG("Libqp objective = %f\n",problem_state.QP); SG_SDEBUG("Exit code = %d\n",problem_state.exitflag); SG_SDEBUG("%d iteration passed\n",problem_state.nIter); SG_SDEBUG("Solution is \n [ "); for (int i=0; i<n_tasks; i++) SG_SDEBUG("%f ", x[i]); SG_SDEBUG("]\n"); Map<VectorXd> Mzp_DiagSigz(x,n_tasks); Mzp_Pz = eigensolver.eigenvectors().real(); Mzp = Mzp_Pz*Mzp_DiagSigz.asDiagonal()*Mzp_Pz.transpose(); internal::set_is_malloc_allowed(false); // walk in direction of antigradient for (int i=0; i<n_tasks; i++) Mzp_DiagSigz[i] += eta; internal::set_is_malloc_allowed(true); invEtaMWt = (Mzp_Pz* (Mzp_DiagSigz.cwiseInverse().asDiagonal())* Mzp_Pz.transpose())* Wzp.transpose(); internal::set_is_malloc_allowed(false); // compute objective at line search point Fzp = 0.0; for (task=0; task<n_tasks; task++) { SGVector<index_t> task_idx = options.tasks_indices[task]; int n_vecs_task = task_idx.vlen; for (int i=0; i<n_vecs_task; i++) { double aa = -y[task_idx[i]]*(features->dense_dot(task_idx[i], Wzp.col(task).data(), n_feats)+Cs[task]); double bb = CMath::max(aa,0.0); Fzp += (CMath::log(CMath::exp(-bb) + CMath::exp(aa-bb)) + bb)/n_vecs_task; } } Fzp += c*(Wzp*invEtaMWt).trace(); // compute delta between line search point and search point delta_Wzp = Wzp - Ws; delta_Czp = Czp - Cs; delta_Mzp = Mzp - Ms; // norms of delta double nrm_delta_Wzp = delta_Wzp.squaredNorm(); double nrm_delta_Czp = delta_Czp.squaredNorm(); double nrm_delta_Mzp = delta_Mzp.squaredNorm(); double r_sum = (nrm_delta_Wzp + nrm_delta_Czp + nrm_delta_Mzp)/3; double Fzp_gamma = 0.0; if (n_feats > n_tasks) { Fzp_gamma = Fs + (delta_Wzp.transpose()*gWs).trace() + (delta_Czp.transpose()*gCs).trace() + (delta_Mzp.transpose()*gMs).trace() + (gamma/2)*nrm_delta_Wzp + (gamma/2)*nrm_delta_Czp + (gamma/2)*nrm_delta_Mzp; } else { Fzp_gamma = Fs + (gWs.transpose()*delta_Wzp).trace() + (gCs.transpose()*delta_Czp).trace() + (gMs.transpose()*delta_Mzp).trace() + (gamma/2)*nrm_delta_Wzp + (gamma/2)*nrm_delta_Czp + (gamma/2)*nrm_delta_Mzp; } // break if delta is getting too small if (r_sum <= 1e-20) { done = true; break; } // break if objective at line searc point is smaller than Fzp_gamma if (Fzp <= Fzp_gamma) break; else gamma *= gamma_inc; inner_iter++; } Wz_old = Wz; Cz_old = Cz; Mz_old = Mz; Wz = Wzp; Cz = Czp; Mz = Mzp; // compute objective value obj_old = obj; obj = Fzp; // check if process should be terminated switch (options.termination) { case 0: if (iter>=2) { // if ( CMath::abs(obj-obj_old) <= options.tolerance ) // done = true; } break; case 1: if (iter>=2) { if ( CMath::abs(obj-obj_old) <= options.tolerance*CMath::abs(obj_old)) done = true; } break; case 2: if (CMath::abs(obj) <= options.tolerance) done = true; break; case 3: if (iter>=options.max_iter) done = true; break; } iter++; t_old = t; t = 0.5 * (1 + CMath::sqrt(1.0 + 4*t*t)); } internal::set_is_malloc_allowed(true); SG_SDEBUG("%d iteration passed, objective = %f\n",iter,obj); SG_FREE(H_diag_matrix); SG_FREE(diag_H); SG_FREE(f); SG_FREE(a); SG_FREE(lb); SG_FREE(ub); SG_FREE(x); SGMatrix<float64_t> tasks_w(n_feats, n_tasks); for (int i=0; i<n_feats; i++) { for (task=0; task<n_tasks; task++) tasks_w(i,task) = Wzp(i,task); } //tasks_w.display_matrix(); SGVector<float64_t> tasks_c(n_tasks); for (int i=0; i<n_tasks; i++) tasks_c[i] = Czp[i]; return malsar_result_t(tasks_w, tasks_c); }; }; #endif <commit_msg>Restored termination check in clustered MTL<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) 2012 Sergey Lisitsyn * Copyright (C) 2012 Jiayu Zhou and Jieping Ye */ #include <shogun/lib/malsar/malsar_clustered.h> #ifdef HAVE_EIGEN3 #include <shogun/mathematics/Math.h> #include <shogun/mathematics/eigen3.h> #include <iostream> #include <shogun/lib/external/libqp.h> using namespace Eigen; using namespace std; namespace shogun { static double* H_diag_matrix; static int H_diag_matrix_ld; static const double* get_col(uint32_t j) { return H_diag_matrix + j*H_diag_matrix_ld; } malsar_result_t malsar_clustered( CDotFeatures* features, double* y, double rho1, double rho2, const malsar_options& options) { int task; int n_feats = features->get_dim_feature_space(); SG_SDEBUG("n feats = %d\n", n_feats); int n_vecs = features->get_num_vectors(); SG_SDEBUG("n vecs = %d\n", n_vecs); int n_tasks = options.n_tasks; SG_SDEBUG("n tasks = %d\n", n_tasks); H_diag_matrix = SG_CALLOC(double, n_tasks*n_tasks); for (int i=0; i<n_tasks; i++) H_diag_matrix[i*n_tasks+i] = 2.0; H_diag_matrix_ld = n_tasks; int iter = 0; // initialize weight vector and bias for each task MatrixXd Ws = MatrixXd::Zero(n_feats, n_tasks); VectorXd Cs = VectorXd::Zero(n_tasks); MatrixXd Ms = MatrixXd::Identity(n_tasks, n_tasks)*options.n_clusters/n_tasks; MatrixXd IM = Ms; MatrixXd IMsqinv = Ms; MatrixXd invEtaMWt = Ms; MatrixXd Wz=Ws, Wzp=Ws, Wz_old=Ws, delta_Wzp=Ws, gWs=Ws; VectorXd Cz=Cs, Czp=Cs, Cz_old=Cs, delta_Czp=Cs, gCs=Cs; MatrixXd Mz=Ms, Mzp=Ms, Mz_old=Ms, delta_Mzp=Ms, gMs=Ms; MatrixXd Mzp_Pz; double eta = rho2/rho1; double c = rho1*eta*(1+eta); double t=1, t_old=0; double gamma=1, gamma_inc=2; double obj=0.0, obj_old=0.0; double* diag_H = SG_MALLOC(double, n_tasks); double* f = SG_MALLOC(double, n_tasks); double* a = SG_MALLOC(double, n_tasks); double* lb = SG_MALLOC(double, n_tasks); double* ub = SG_MALLOC(double, n_tasks); double* x = SG_CALLOC(double, n_tasks); internal::set_is_malloc_allowed(false); bool done = false; while (!done && iter <= options.max_iter) { double alpha = double(t_old - 1)/t; SG_SDEBUG("alpha=%f\n",alpha); // compute search point Ws = (1+alpha)*Wz - alpha*Wz_old; Cs = (1+alpha)*Cz - alpha*Cz_old; Ms = (1+alpha)*Mz - alpha*Mz_old; // zero gradient gWs.setZero(); gCs.setZero(); internal::set_is_malloc_allowed(true); SG_SDEBUG("Computing gradient\n"); IM = (eta*MatrixXd::Identity(n_tasks,n_tasks)+Ms); // cout << "M" << endl << Ms << endl; // cout << "IM" << endl << IM << endl; IMsqinv = (IM*IM).inverse(); invEtaMWt = IM.inverse()*Ws.transpose(); //cout << "invEtaMWt" << endl << invEtaMWt << endl; gMs.noalias() = -c*(Ws.transpose()*Ws)*IMsqinv; gWs.noalias() += 2*c*invEtaMWt.transpose(); internal::set_is_malloc_allowed(false); // compute gradient and objective at search point double Fs = 0; for (task=0; task<n_tasks; task++) { SGVector<index_t> task_idx = options.tasks_indices[task]; int n_vecs_task = task_idx.vlen; for (int i=0; i<n_vecs_task; i++) { double aa = -y[task_idx[i]]*(features->dense_dot(task_idx[i], Ws.col(task).data(), n_feats)+Cs[task]); double bb = CMath::max(aa,0.0); // avoid underflow when computing exponential loss Fs += (CMath::log(CMath::exp(-bb) + CMath::exp(aa-bb)) + bb)/n_vecs_task; double b = -y[task_idx[i]]*(1 - 1/(1+CMath::exp(aa)))/n_vecs_task; gCs[task] += b; features->add_to_dense_vec(b, task_idx[i], gWs.col(task).data(), n_feats); } } //cout << "gWs" << endl << gWs << endl; //cout << "gCs" << endl << gCs << endl; SG_SDEBUG("Computed gradient\n"); // add regularizer Fs += c*(Ws*invEtaMWt).trace(); SG_SDEBUG("Fs = %f \n", Fs); double Fzp = 0.0; int inner_iter = 0; // line search, Armijo-Goldstein scheme while (inner_iter <= 1000) { Wzp = Ws - gWs/gamma; Czp = Cs - gCs/gamma; // compute singular projection of Ms - gMs/gamma with k internal::set_is_malloc_allowed(true); EigenSolver<MatrixXd> eigensolver(Ms-gMs/gamma); // solve problem // min sum_i (s_i - s*_i)^2 s.t. sum_i s_i = k, 0<=s_i<=1 for (int i=0; i<n_tasks; i++) { diag_H[i] = 2.0; f[i] = -2*eigensolver.eigenvalues()[i].real(); SG_SDEBUG("%dth eigenvalue %f\n",i,eigensolver.eigenvalues()[i].real()); a[i] = 1.0; lb[i] = 0.0; ub[i] = 1.0; x[i] = double(options.n_clusters)/n_tasks; } double b = options.n_clusters;//eigensolver.eigenvalues().sum().real(); SG_SDEBUG("b = %f\n", b); SG_SDEBUG("Calling libqp\n"); libqp_state_T problem_state = libqp_gsmo_solver(&get_col,diag_H,f,a,b,lb,ub,x,n_tasks,1000,1e-6,NULL); SG_SDEBUG("Libqp objective = %f\n",problem_state.QP); SG_SDEBUG("Exit code = %d\n",problem_state.exitflag); SG_SDEBUG("%d iteration passed\n",problem_state.nIter); SG_SDEBUG("Solution is \n [ "); for (int i=0; i<n_tasks; i++) SG_SDEBUG("%f ", x[i]); SG_SDEBUG("]\n"); Map<VectorXd> Mzp_DiagSigz(x,n_tasks); Mzp_Pz = eigensolver.eigenvectors().real(); Mzp = Mzp_Pz*Mzp_DiagSigz.asDiagonal()*Mzp_Pz.transpose(); internal::set_is_malloc_allowed(false); // walk in direction of antigradient for (int i=0; i<n_tasks; i++) Mzp_DiagSigz[i] += eta; internal::set_is_malloc_allowed(true); invEtaMWt = (Mzp_Pz* (Mzp_DiagSigz.cwiseInverse().asDiagonal())* Mzp_Pz.transpose())* Wzp.transpose(); internal::set_is_malloc_allowed(false); // compute objective at line search point Fzp = 0.0; for (task=0; task<n_tasks; task++) { SGVector<index_t> task_idx = options.tasks_indices[task]; int n_vecs_task = task_idx.vlen; for (int i=0; i<n_vecs_task; i++) { double aa = -y[task_idx[i]]*(features->dense_dot(task_idx[i], Wzp.col(task).data(), n_feats)+Cs[task]); double bb = CMath::max(aa,0.0); Fzp += (CMath::log(CMath::exp(-bb) + CMath::exp(aa-bb)) + bb)/n_vecs_task; } } Fzp += c*(Wzp*invEtaMWt).trace(); // compute delta between line search point and search point delta_Wzp = Wzp - Ws; delta_Czp = Czp - Cs; delta_Mzp = Mzp - Ms; // norms of delta double nrm_delta_Wzp = delta_Wzp.squaredNorm(); double nrm_delta_Czp = delta_Czp.squaredNorm(); double nrm_delta_Mzp = delta_Mzp.squaredNorm(); double r_sum = (nrm_delta_Wzp + nrm_delta_Czp + nrm_delta_Mzp)/3; double Fzp_gamma = 0.0; if (n_feats > n_tasks) { Fzp_gamma = Fs + (delta_Wzp.transpose()*gWs).trace() + (delta_Czp.transpose()*gCs).trace() + (delta_Mzp.transpose()*gMs).trace() + (gamma/2)*nrm_delta_Wzp + (gamma/2)*nrm_delta_Czp + (gamma/2)*nrm_delta_Mzp; } else { Fzp_gamma = Fs + (gWs.transpose()*delta_Wzp).trace() + (gCs.transpose()*delta_Czp).trace() + (gMs.transpose()*delta_Mzp).trace() + (gamma/2)*nrm_delta_Wzp + (gamma/2)*nrm_delta_Czp + (gamma/2)*nrm_delta_Mzp; } // break if delta is getting too small if (r_sum <= 1e-20) { done = true; break; } // break if objective at line searc point is smaller than Fzp_gamma if (Fzp <= Fzp_gamma) break; else gamma *= gamma_inc; inner_iter++; } Wz_old = Wz; Cz_old = Cz; Mz_old = Mz; Wz = Wzp; Cz = Czp; Mz = Mzp; // compute objective value obj_old = obj; obj = Fzp; // check if process should be terminated switch (options.termination) { case 0: if (iter>=2) { if ( CMath::abs(obj-obj_old) <= options.tolerance ) done = true; } break; case 1: if (iter>=2) { if ( CMath::abs(obj-obj_old) <= options.tolerance*CMath::abs(obj_old)) done = true; } break; case 2: if (CMath::abs(obj) <= options.tolerance) done = true; break; case 3: if (iter>=options.max_iter) done = true; break; } iter++; t_old = t; t = 0.5 * (1 + CMath::sqrt(1.0 + 4*t*t)); } internal::set_is_malloc_allowed(true); SG_SDEBUG("%d iteration passed, objective = %f\n",iter,obj); SG_FREE(H_diag_matrix); SG_FREE(diag_H); SG_FREE(f); SG_FREE(a); SG_FREE(lb); SG_FREE(ub); SG_FREE(x); SGMatrix<float64_t> tasks_w(n_feats, n_tasks); for (int i=0; i<n_feats; i++) { for (task=0; task<n_tasks; task++) tasks_w(i,task) = Wzp(i,task); } //tasks_w.display_matrix(); SGVector<float64_t> tasks_c(n_tasks); for (int i=0; i<n_tasks; i++) tasks_c[i] = Czp[i]; return malsar_result_t(tasks_w, tasks_c); }; }; #endif <|endoftext|>
<commit_before>/************************************************************************** ** ** Copyright (C) 2011 - 2013 Research In Motion ** ** Contact: Research In Motion (blackberry-qt@qnx.com) ** Contact: KDAB (info@kdab.com) ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "blackberrycsjregistrar.h" #include "blackberryconfiguration.h" #include <utils/hostosinfo.h> #include <QProcess> #include <QStringList> #include <QString> namespace Qnx { namespace Internal { BlackBerryCsjRegistrar::BlackBerryCsjRegistrar(QObject *parent) : QObject(parent), m_process(new QProcess(this)) { connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished())); connect(m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(processError(QProcess::ProcessError))); } void BlackBerryCsjRegistrar::tryRegister(const QStringList &csjFiles, const QString &csjPin, const QString &cskPassword) { if (m_process->state() != QProcess::NotRunning) return; QString command = BlackBerryConfiguration::instance() .qnxEnv().value(QLatin1String("QNX_HOST")) + (QLatin1String("/usr/bin/blackberry-signer")); if (Utils::HostOsInfo::isWindowsHost()) command += QLatin1String(".bat"); QStringList arguments; arguments << QLatin1String("-register") << QLatin1String("-cskpass") << cskPassword << QLatin1String("-csjpin") << csjPin << csjFiles; m_process->start(command, arguments); } void BlackBerryCsjRegistrar::processFinished() { QByteArray result = m_process->readAllStandardOutput(); if (result.contains("Successfully registered with server.")) emit finished(RegisterSuccess, QString()); else emit finished(Error, QLatin1String(result)); } void BlackBerryCsjRegistrar::processError(QProcess::ProcessError error) { QString errorMessage; switch (error) { case QProcess::FailedToStart: errorMessage = tr("Failed to start blackberry-signer process."); break; case QProcess::Timedout: errorMessage = tr("Process timed out."); case QProcess::Crashed: errorMessage = tr("Child process has crashed."); break; case QProcess::WriteError: case QProcess::ReadError: errorMessage = tr("Process I/O error."); break; case QProcess::UnknownError: errorMessage = tr("Unknown process error."); break; } emit finished(Error, errorMessage); } } // namespace Internal } // namespace Qnx <commit_msg>QNX: Added missing break in switch statement<commit_after>/************************************************************************** ** ** Copyright (C) 2011 - 2013 Research In Motion ** ** Contact: Research In Motion (blackberry-qt@qnx.com) ** Contact: KDAB (info@kdab.com) ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "blackberrycsjregistrar.h" #include "blackberryconfiguration.h" #include <utils/hostosinfo.h> #include <QProcess> #include <QStringList> #include <QString> namespace Qnx { namespace Internal { BlackBerryCsjRegistrar::BlackBerryCsjRegistrar(QObject *parent) : QObject(parent), m_process(new QProcess(this)) { connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished())); connect(m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(processError(QProcess::ProcessError))); } void BlackBerryCsjRegistrar::tryRegister(const QStringList &csjFiles, const QString &csjPin, const QString &cskPassword) { if (m_process->state() != QProcess::NotRunning) return; QString command = BlackBerryConfiguration::instance() .qnxEnv().value(QLatin1String("QNX_HOST")) + (QLatin1String("/usr/bin/blackberry-signer")); if (Utils::HostOsInfo::isWindowsHost()) command += QLatin1String(".bat"); QStringList arguments; arguments << QLatin1String("-register") << QLatin1String("-cskpass") << cskPassword << QLatin1String("-csjpin") << csjPin << csjFiles; m_process->start(command, arguments); } void BlackBerryCsjRegistrar::processFinished() { QByteArray result = m_process->readAllStandardOutput(); if (result.contains("Successfully registered with server.")) emit finished(RegisterSuccess, QString()); else emit finished(Error, QLatin1String(result)); } void BlackBerryCsjRegistrar::processError(QProcess::ProcessError error) { QString errorMessage; switch (error) { case QProcess::FailedToStart: errorMessage = tr("Failed to start blackberry-signer process."); break; case QProcess::Timedout: errorMessage = tr("Process timed out."); break; case QProcess::Crashed: errorMessage = tr("Child process has crashed."); break; case QProcess::WriteError: case QProcess::ReadError: errorMessage = tr("Process I/O error."); break; case QProcess::UnknownError: errorMessage = tr("Unknown process error."); break; } emit finished(Error, errorMessage); } } // namespace Internal } // namespace Qnx <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: http://www.qt-project.org/ ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** **************************************************************************/ #include "qtkitinformation.h" #include "qtkitconfigwidget.h" #include "qtversionmanager.h" #include <utils/environment.h> namespace QtSupport { namespace Internal { const char QT_INFORMATION[] = "QtSupport.QtInformation"; } // namespace Internal QtKitInformation::QtKitInformation() { setObjectName(QLatin1String("QtKitInformation")); connect(QtVersionManager::instance(), SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)), this, SIGNAL(validationNeeded())); } Core::Id QtKitInformation::dataId() const { static Core::Id id = Core::Id(Internal::QT_INFORMATION); return id; } unsigned int QtKitInformation::priority() const { return 26000; } QVariant QtKitInformation::defaultValue(ProjectExplorer::Kit *k) const { Q_UNUSED(k); QtVersionManager *mgr = QtVersionManager::instance(); // find "Qt in PATH": Utils::Environment env = Utils::Environment::systemEnvironment(); Utils::FileName qmake = Utils::FileName::fromString(env.searchInPath(QLatin1String("qmake"))); if (qmake.isEmpty()) return -1; QList<BaseQtVersion *> versionList = mgr->versions(); foreach (BaseQtVersion *v, versionList) { if (qmake == v->qmakeCommand()) return v->uniqueId(); } return -1; } QList<ProjectExplorer::Task> QtKitInformation::validate(ProjectExplorer::Kit *k) const { int id = qtVersionId(k); if (id == -1) return QList<ProjectExplorer::Task>(); BaseQtVersion *version = QtVersionManager::instance()->version(id); if (!version) { setQtVersionId(k, -1); return QList<ProjectExplorer::Task>(); } return version->validateKit(k); } ProjectExplorer::KitConfigWidget *QtKitInformation::createConfigWidget(ProjectExplorer::Kit *k) const { return new Internal::QtKitConfigWidget(k); } QString QtKitInformation::displayNamePostfix(const ProjectExplorer::Kit *k) const { BaseQtVersion *version = qtVersion(k); return version ? version->displayName() : QString(); } ProjectExplorer::KitInformation::ItemList QtKitInformation::toUserOutput(ProjectExplorer::Kit *k) const { BaseQtVersion *version = qtVersion(k); return ItemList() << qMakePair(tr("Qt version"), version ? version->displayName() : tr("None")); } void QtKitInformation::addToEnvironment(const ProjectExplorer::Kit *k, Utils::Environment &env) const { BaseQtVersion *version = qtVersion(k); if (version) version->addToEnvironment(k, env); } int QtKitInformation::qtVersionId(const ProjectExplorer::Kit *k) { if (!k) return -1; int id = -1; QVariant data = k->value(Core::Id(Internal::QT_INFORMATION), -1); if (data.type() == QVariant::Int) { bool ok; id = data.toInt(&ok); if (!ok) id = -1; } else { QString source = data.toString(); foreach (BaseQtVersion *v, QtVersionManager::instance()->versions()) { if (v->autodetectionSource() != source) continue; id = v->uniqueId(); break; } } return id; } void QtKitInformation::setQtVersionId(ProjectExplorer::Kit *k, const int id) { k->setValue(Core::Id(Internal::QT_INFORMATION), id); } BaseQtVersion *QtKitInformation::qtVersion(const ProjectExplorer::Kit *k) { return QtVersionManager::instance()->version(qtVersionId(k)); } void QtKitInformation::setQtVersion(ProjectExplorer::Kit *k, const BaseQtVersion *v) { if (!v) setQtVersionId(k, -1); else setQtVersionId(k, v->uniqueId()); } QtPlatformKitMatcher::QtPlatformKitMatcher(const QString &platform) : m_platform(platform) { } bool QtPlatformKitMatcher::matches(const ProjectExplorer::Kit *k) const { BaseQtVersion *version = QtKitInformation::qtVersion(k); return version && version->platformName() == m_platform; } bool QtVersionKitMatcher::matches(const ProjectExplorer::Kit *k) const { BaseQtVersion *version = QtKitInformation::qtVersion(k); if (!version) return false; QtVersionNumber current = version->qtVersion(); if (m_min.majorVersion > -1 && current < m_min) return false; if (m_max.majorVersion > -1 && current > m_max) return false; return version->availableFeatures().contains(m_features); } } // namespace QtSupport <commit_msg>Qt: Use any desktop Qt version if the Qt in PATH is not found<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: http://www.qt-project.org/ ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** **************************************************************************/ #include "qtkitinformation.h" #include "qtkitconfigwidget.h" #include "qtsupportconstants.h" #include "qtversionmanager.h" #include <utils/environment.h> namespace QtSupport { namespace Internal { const char QT_INFORMATION[] = "QtSupport.QtInformation"; } // namespace Internal QtKitInformation::QtKitInformation() { setObjectName(QLatin1String("QtKitInformation")); connect(QtVersionManager::instance(), SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)), this, SIGNAL(validationNeeded())); } Core::Id QtKitInformation::dataId() const { static Core::Id id = Core::Id(Internal::QT_INFORMATION); return id; } unsigned int QtKitInformation::priority() const { return 26000; } QVariant QtKitInformation::defaultValue(ProjectExplorer::Kit *k) const { Q_UNUSED(k); QtVersionManager *mgr = QtVersionManager::instance(); // find "Qt in PATH": Utils::Environment env = Utils::Environment::systemEnvironment(); Utils::FileName qmake = Utils::FileName::fromString(env.searchInPath(QLatin1String("qmake"))); if (qmake.isEmpty()) return -1; QList<BaseQtVersion *> versionList = mgr->versions(); BaseQtVersion *fallBack = 0; foreach (BaseQtVersion *v, versionList) { if (qmake == v->qmakeCommand()) return v->uniqueId(); if (v->type() == QLatin1String(QtSupport::Constants::DESKTOPQT) && !fallBack) fallBack = v; } if (fallBack) return fallBack->uniqueId(); return -1; } QList<ProjectExplorer::Task> QtKitInformation::validate(ProjectExplorer::Kit *k) const { int id = qtVersionId(k); if (id == -1) return QList<ProjectExplorer::Task>(); BaseQtVersion *version = QtVersionManager::instance()->version(id); if (!version) { setQtVersionId(k, -1); return QList<ProjectExplorer::Task>(); } return version->validateKit(k); } ProjectExplorer::KitConfigWidget *QtKitInformation::createConfigWidget(ProjectExplorer::Kit *k) const { return new Internal::QtKitConfigWidget(k); } QString QtKitInformation::displayNamePostfix(const ProjectExplorer::Kit *k) const { BaseQtVersion *version = qtVersion(k); return version ? version->displayName() : QString(); } ProjectExplorer::KitInformation::ItemList QtKitInformation::toUserOutput(ProjectExplorer::Kit *k) const { BaseQtVersion *version = qtVersion(k); return ItemList() << qMakePair(tr("Qt version"), version ? version->displayName() : tr("None")); } void QtKitInformation::addToEnvironment(const ProjectExplorer::Kit *k, Utils::Environment &env) const { BaseQtVersion *version = qtVersion(k); if (version) version->addToEnvironment(k, env); } int QtKitInformation::qtVersionId(const ProjectExplorer::Kit *k) { if (!k) return -1; int id = -1; QVariant data = k->value(Core::Id(Internal::QT_INFORMATION), -1); if (data.type() == QVariant::Int) { bool ok; id = data.toInt(&ok); if (!ok) id = -1; } else { QString source = data.toString(); foreach (BaseQtVersion *v, QtVersionManager::instance()->versions()) { if (v->autodetectionSource() != source) continue; id = v->uniqueId(); break; } } return id; } void QtKitInformation::setQtVersionId(ProjectExplorer::Kit *k, const int id) { k->setValue(Core::Id(Internal::QT_INFORMATION), id); } BaseQtVersion *QtKitInformation::qtVersion(const ProjectExplorer::Kit *k) { return QtVersionManager::instance()->version(qtVersionId(k)); } void QtKitInformation::setQtVersion(ProjectExplorer::Kit *k, const BaseQtVersion *v) { if (!v) setQtVersionId(k, -1); else setQtVersionId(k, v->uniqueId()); } QtPlatformKitMatcher::QtPlatformKitMatcher(const QString &platform) : m_platform(platform) { } bool QtPlatformKitMatcher::matches(const ProjectExplorer::Kit *k) const { BaseQtVersion *version = QtKitInformation::qtVersion(k); return version && version->platformName() == m_platform; } bool QtVersionKitMatcher::matches(const ProjectExplorer::Kit *k) const { BaseQtVersion *version = QtKitInformation::qtVersion(k); if (!version) return false; QtVersionNumber current = version->qtVersion(); if (m_min.majorVersion > -1 && current < m_min) return false; if (m_max.majorVersion > -1 && current > m_max) return false; return version->availableFeatures().contains(m_features); } } // namespace QtSupport <|endoftext|>
<commit_before>/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/profiling/memory/shared_ring_buffer.h" #include <atomic> #include <type_traits> #include <inttypes.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include "perfetto/base/build_config.h" #include "perfetto/base/scoped_file.h" #include "perfetto/base/temp_file.h" #include "src/profiling/memory/scoped_spinlock.h" #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) #include <linux/memfd.h> #include <sys/syscall.h> #endif namespace perfetto { namespace profiling { namespace { constexpr auto kMetaPageSize = base::kPageSize; constexpr auto kAlignment = 8; // 64 bits to use aligned memcpy(). constexpr auto kHeaderSize = kAlignment; constexpr auto kGuardSize = base::kPageSize * 1024 * 16; // 64 MB. #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) constexpr auto kFDSeals = F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL; #endif } // namespace SharedRingBuffer::SharedRingBuffer(CreateFlag, size_t size) { size_t size_with_meta = size + kMetaPageSize; // TODO(primiano): this is copy/pasted from posix_shared_memory.cc . Refactor. base::ScopedFile fd; #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) bool is_memfd = false; fd.reset(static_cast<int>(syscall(__NR_memfd_create, "heaprofd_ringbuf", MFD_CLOEXEC | MFD_ALLOW_SEALING))); is_memfd = !!fd; if (!fd) { // TODO: if this fails on Android we should fall back on ashmem. #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD) // In-tree builds should only allow mem_fd, so we can inspect the seals // to verify the fd is appropriately sealed. PERFETTO_ELOG("memfd_create() failed"); return; #else PERFETTO_DPLOG("memfd_create() failed"); #endif } #endif if (!fd) fd = base::TempFile::CreateUnlinked().ReleaseFD(); PERFETTO_CHECK(fd); int res = ftruncate(fd.get(), static_cast<off_t>(size_with_meta)); PERFETTO_CHECK(res == 0); #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) if (is_memfd) { res = fcntl(*fd, F_ADD_SEALS, kFDSeals); PERFETTO_DCHECK(res == 0); } #endif Initialize(std::move(fd)); new (meta_) MetadataPage(); } SharedRingBuffer::~SharedRingBuffer() { static_assert(std::is_trivially_constructible<MetadataPage>::value, "MetadataPage must be trivially constructible"); static_assert(std::is_trivially_destructible<MetadataPage>::value, "MetadataPage must be trivially destructible"); if (is_valid()) { size_t outer_size = kMetaPageSize + size_ * 2 + kGuardSize; munmap(meta_, outer_size); } } void SharedRingBuffer::Initialize(base::ScopedFile mem_fd) { #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD) int seals = fcntl(*mem_fd, F_GET_SEALS); if ((seals & kFDSeals) != kFDSeals) { PERFETTO_ELOG("FD not properly sealed. Expected %x, got %x", kFDSeals, seals); return; } #endif struct stat stat_buf = {}; int res = fstat(*mem_fd, &stat_buf); if (res != 0 || stat_buf.st_size == 0) { PERFETTO_PLOG("Could not attach to fd."); return; } auto size_with_meta = static_cast<size_t>(stat_buf.st_size); auto size = size_with_meta - kMetaPageSize; // |size_with_meta| must be a power of two number of pages + 1 page (for // metadata). if (size_with_meta < 2 * base::kPageSize || size % base::kPageSize || (size & (size - 1))) { PERFETTO_ELOG("SharedRingBuffer size is invalid (%zu)", size_with_meta); return; } // First of all reserve the whole virtual region to fit the buffer twice // + metadata page + red zone at the end. size_t outer_size = kMetaPageSize + size * 2 + kGuardSize; uint8_t* region = reinterpret_cast<uint8_t*>( mmap(nullptr, outer_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); if (region == MAP_FAILED) { PERFETTO_PLOG("mmap(PROT_NONE) failed"); return; } // Map first the whole buffer (including the initial metadata page) @ off=0. void* reg1 = mmap(region, size_with_meta, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, *mem_fd, 0); // Then map again the buffer, skipping the metadata page. The final result is: // [ METADATA ] [ RING BUFFER SHMEM ] [ RING BUFFER SHMEM ] void* reg2 = mmap(region + size_with_meta, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, *mem_fd, /*offset=*/kMetaPageSize); if (reg1 != region || reg2 != region + size_with_meta) { PERFETTO_PLOG("mmap(MAP_SHARED) failed"); munmap(region, outer_size); return; } size_ = size; meta_ = reinterpret_cast<MetadataPage*>(region); mem_ = region + kMetaPageSize; mem_fd_ = std::move(mem_fd); } SharedRingBuffer::Buffer SharedRingBuffer::BeginWrite( const ScopedSpinlock& spinlock, size_t size) { PERFETTO_DCHECK(spinlock.locked()); Buffer result; base::Optional<PointerPositions> opt_pos = GetPointerPositions(spinlock); if (!opt_pos) { errno = EBADFD; return result; } auto pos = opt_pos.value(); const uint64_t size_with_header = base::AlignUp<kAlignment>(size + kHeaderSize); if (size_with_header > write_avail(pos)) { errno = EAGAIN; meta_->num_writes_failed++; return result; } uint8_t* wr_ptr = at(pos.write_pos); result.size = size; result.data = wr_ptr + kHeaderSize; meta_->write_pos += size_with_header; meta_->bytes_written += size; meta_->num_writes_succeeded++; // By making this a release store, we can save grabbing the spinlock in // EndWrite. reinterpret_cast<std::atomic<uint32_t>*>(wr_ptr)->store( 0, std::memory_order_release); return result; } void SharedRingBuffer::EndWrite(Buffer buf) { if (!buf) return; uint8_t* wr_ptr = buf.data - kHeaderSize; PERFETTO_DCHECK(reinterpret_cast<uintptr_t>(wr_ptr) % kAlignment == 0); reinterpret_cast<std::atomic<uint32_t>*>(wr_ptr)->store( static_cast<uint32_t>(buf.size), std::memory_order_release); } SharedRingBuffer::Buffer SharedRingBuffer::BeginRead() { ScopedSpinlock spinlock(&meta_->spinlock, ScopedSpinlock::Mode::Blocking); base::Optional<PointerPositions> opt_pos = GetPointerPositions(spinlock); if (!opt_pos) return Buffer(); auto pos = opt_pos.value(); size_t avail_read = read_avail(pos); if (avail_read < kHeaderSize) return Buffer(); // No data uint8_t* rd_ptr = at(pos.read_pos); PERFETTO_DCHECK(reinterpret_cast<uintptr_t>(rd_ptr) % kAlignment == 0); const size_t size = reinterpret_cast<std::atomic<uint32_t>*>(rd_ptr)->load( std::memory_order_acquire); if (size == 0) return Buffer(); const size_t size_with_header = base::AlignUp<kAlignment>(size + kHeaderSize); if (size_with_header > avail_read) { PERFETTO_ELOG( "Corrupted header detected, size=%zu" ", read_avail=%zu, rd=%" PRIu64 ", wr=%" PRIu64, size, avail_read, pos.read_pos, pos.write_pos); meta_->num_reads_failed++; return Buffer(); } rd_ptr += kHeaderSize; PERFETTO_DCHECK(reinterpret_cast<uintptr_t>(rd_ptr) % kAlignment == 0); return Buffer(rd_ptr, size); } void SharedRingBuffer::EndRead(Buffer buf) { if (!buf) return; ScopedSpinlock spinlock(&meta_->spinlock, ScopedSpinlock::Mode::Blocking); size_t size_with_header = base::AlignUp<kAlignment>(buf.size + kHeaderSize); meta_->read_pos += size_with_header; } bool SharedRingBuffer::IsCorrupt(const PointerPositions& pos) { if (pos.write_pos < pos.read_pos || pos.write_pos - pos.read_pos > size_ || pos.write_pos % kAlignment || pos.read_pos % kAlignment) { PERFETTO_ELOG("Ring buffer corrupted, rd=%" PRIu64 ", wr=%" PRIu64 ", size=%zu", pos.read_pos, pos.write_pos, size_); return true; } return false; } SharedRingBuffer::SharedRingBuffer(SharedRingBuffer&& other) noexcept { *this = std::move(other); } SharedRingBuffer& SharedRingBuffer::operator=(SharedRingBuffer&& other) { mem_fd_ = std::move(other.mem_fd_); std::tie(meta_, mem_, size_) = std::tie(other.meta_, other.mem_, other.size_); std::tie(other.meta_, other.mem_, other.size_) = std::make_tuple(nullptr, nullptr, 0); return *this; } // static base::Optional<SharedRingBuffer> SharedRingBuffer::Create(size_t size) { auto buf = SharedRingBuffer(CreateFlag(), size); if (!buf.is_valid()) return base::nullopt; return base::make_optional(std::move(buf)); } // static base::Optional<SharedRingBuffer> SharedRingBuffer::Attach( base::ScopedFile mem_fd) { auto buf = SharedRingBuffer(AttachFlag(), std::move(mem_fd)); if (!buf.is_valid()) return base::nullopt; return base::make_optional(std::move(buf)); } } // namespace profiling } // namespace perfetto <commit_msg>Fix mac build: EBADFD -> EBADF am: ac7b61edde am: 3faaf6db4b<commit_after>/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/profiling/memory/shared_ring_buffer.h" #include <atomic> #include <type_traits> #include <errno.h> #include <inttypes.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include "perfetto/base/build_config.h" #include "perfetto/base/scoped_file.h" #include "perfetto/base/temp_file.h" #include "src/profiling/memory/scoped_spinlock.h" #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) #include <linux/memfd.h> #include <sys/syscall.h> #endif namespace perfetto { namespace profiling { namespace { constexpr auto kMetaPageSize = base::kPageSize; constexpr auto kAlignment = 8; // 64 bits to use aligned memcpy(). constexpr auto kHeaderSize = kAlignment; constexpr auto kGuardSize = base::kPageSize * 1024 * 16; // 64 MB. #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) constexpr auto kFDSeals = F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL; #endif } // namespace SharedRingBuffer::SharedRingBuffer(CreateFlag, size_t size) { size_t size_with_meta = size + kMetaPageSize; // TODO(primiano): this is copy/pasted from posix_shared_memory.cc . Refactor. base::ScopedFile fd; #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) bool is_memfd = false; fd.reset(static_cast<int>(syscall(__NR_memfd_create, "heaprofd_ringbuf", MFD_CLOEXEC | MFD_ALLOW_SEALING))); is_memfd = !!fd; if (!fd) { // TODO: if this fails on Android we should fall back on ashmem. #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD) // In-tree builds should only allow mem_fd, so we can inspect the seals // to verify the fd is appropriately sealed. PERFETTO_ELOG("memfd_create() failed"); return; #else PERFETTO_DPLOG("memfd_create() failed"); #endif } #endif if (!fd) fd = base::TempFile::CreateUnlinked().ReleaseFD(); PERFETTO_CHECK(fd); int res = ftruncate(fd.get(), static_cast<off_t>(size_with_meta)); PERFETTO_CHECK(res == 0); #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) if (is_memfd) { res = fcntl(*fd, F_ADD_SEALS, kFDSeals); PERFETTO_DCHECK(res == 0); } #endif Initialize(std::move(fd)); new (meta_) MetadataPage(); } SharedRingBuffer::~SharedRingBuffer() { static_assert(std::is_trivially_constructible<MetadataPage>::value, "MetadataPage must be trivially constructible"); static_assert(std::is_trivially_destructible<MetadataPage>::value, "MetadataPage must be trivially destructible"); if (is_valid()) { size_t outer_size = kMetaPageSize + size_ * 2 + kGuardSize; munmap(meta_, outer_size); } } void SharedRingBuffer::Initialize(base::ScopedFile mem_fd) { #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD) int seals = fcntl(*mem_fd, F_GET_SEALS); if ((seals & kFDSeals) != kFDSeals) { PERFETTO_ELOG("FD not properly sealed. Expected %x, got %x", kFDSeals, seals); return; } #endif struct stat stat_buf = {}; int res = fstat(*mem_fd, &stat_buf); if (res != 0 || stat_buf.st_size == 0) { PERFETTO_PLOG("Could not attach to fd."); return; } auto size_with_meta = static_cast<size_t>(stat_buf.st_size); auto size = size_with_meta - kMetaPageSize; // |size_with_meta| must be a power of two number of pages + 1 page (for // metadata). if (size_with_meta < 2 * base::kPageSize || size % base::kPageSize || (size & (size - 1))) { PERFETTO_ELOG("SharedRingBuffer size is invalid (%zu)", size_with_meta); return; } // First of all reserve the whole virtual region to fit the buffer twice // + metadata page + red zone at the end. size_t outer_size = kMetaPageSize + size * 2 + kGuardSize; uint8_t* region = reinterpret_cast<uint8_t*>( mmap(nullptr, outer_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); if (region == MAP_FAILED) { PERFETTO_PLOG("mmap(PROT_NONE) failed"); return; } // Map first the whole buffer (including the initial metadata page) @ off=0. void* reg1 = mmap(region, size_with_meta, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, *mem_fd, 0); // Then map again the buffer, skipping the metadata page. The final result is: // [ METADATA ] [ RING BUFFER SHMEM ] [ RING BUFFER SHMEM ] void* reg2 = mmap(region + size_with_meta, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, *mem_fd, /*offset=*/kMetaPageSize); if (reg1 != region || reg2 != region + size_with_meta) { PERFETTO_PLOG("mmap(MAP_SHARED) failed"); munmap(region, outer_size); return; } size_ = size; meta_ = reinterpret_cast<MetadataPage*>(region); mem_ = region + kMetaPageSize; mem_fd_ = std::move(mem_fd); } SharedRingBuffer::Buffer SharedRingBuffer::BeginWrite( const ScopedSpinlock& spinlock, size_t size) { PERFETTO_DCHECK(spinlock.locked()); Buffer result; base::Optional<PointerPositions> opt_pos = GetPointerPositions(spinlock); if (!opt_pos) { errno = EBADF; return result; } auto pos = opt_pos.value(); const uint64_t size_with_header = base::AlignUp<kAlignment>(size + kHeaderSize); if (size_with_header > write_avail(pos)) { errno = EAGAIN; meta_->num_writes_failed++; return result; } uint8_t* wr_ptr = at(pos.write_pos); result.size = size; result.data = wr_ptr + kHeaderSize; meta_->write_pos += size_with_header; meta_->bytes_written += size; meta_->num_writes_succeeded++; // By making this a release store, we can save grabbing the spinlock in // EndWrite. reinterpret_cast<std::atomic<uint32_t>*>(wr_ptr)->store( 0, std::memory_order_release); return result; } void SharedRingBuffer::EndWrite(Buffer buf) { if (!buf) return; uint8_t* wr_ptr = buf.data - kHeaderSize; PERFETTO_DCHECK(reinterpret_cast<uintptr_t>(wr_ptr) % kAlignment == 0); reinterpret_cast<std::atomic<uint32_t>*>(wr_ptr)->store( static_cast<uint32_t>(buf.size), std::memory_order_release); } SharedRingBuffer::Buffer SharedRingBuffer::BeginRead() { ScopedSpinlock spinlock(&meta_->spinlock, ScopedSpinlock::Mode::Blocking); base::Optional<PointerPositions> opt_pos = GetPointerPositions(spinlock); if (!opt_pos) return Buffer(); auto pos = opt_pos.value(); size_t avail_read = read_avail(pos); if (avail_read < kHeaderSize) return Buffer(); // No data uint8_t* rd_ptr = at(pos.read_pos); PERFETTO_DCHECK(reinterpret_cast<uintptr_t>(rd_ptr) % kAlignment == 0); const size_t size = reinterpret_cast<std::atomic<uint32_t>*>(rd_ptr)->load( std::memory_order_acquire); if (size == 0) return Buffer(); const size_t size_with_header = base::AlignUp<kAlignment>(size + kHeaderSize); if (size_with_header > avail_read) { PERFETTO_ELOG( "Corrupted header detected, size=%zu" ", read_avail=%zu, rd=%" PRIu64 ", wr=%" PRIu64, size, avail_read, pos.read_pos, pos.write_pos); meta_->num_reads_failed++; return Buffer(); } rd_ptr += kHeaderSize; PERFETTO_DCHECK(reinterpret_cast<uintptr_t>(rd_ptr) % kAlignment == 0); return Buffer(rd_ptr, size); } void SharedRingBuffer::EndRead(Buffer buf) { if (!buf) return; ScopedSpinlock spinlock(&meta_->spinlock, ScopedSpinlock::Mode::Blocking); size_t size_with_header = base::AlignUp<kAlignment>(buf.size + kHeaderSize); meta_->read_pos += size_with_header; } bool SharedRingBuffer::IsCorrupt(const PointerPositions& pos) { if (pos.write_pos < pos.read_pos || pos.write_pos - pos.read_pos > size_ || pos.write_pos % kAlignment || pos.read_pos % kAlignment) { PERFETTO_ELOG("Ring buffer corrupted, rd=%" PRIu64 ", wr=%" PRIu64 ", size=%zu", pos.read_pos, pos.write_pos, size_); return true; } return false; } SharedRingBuffer::SharedRingBuffer(SharedRingBuffer&& other) noexcept { *this = std::move(other); } SharedRingBuffer& SharedRingBuffer::operator=(SharedRingBuffer&& other) { mem_fd_ = std::move(other.mem_fd_); std::tie(meta_, mem_, size_) = std::tie(other.meta_, other.mem_, other.size_); std::tie(other.meta_, other.mem_, other.size_) = std::make_tuple(nullptr, nullptr, 0); return *this; } // static base::Optional<SharedRingBuffer> SharedRingBuffer::Create(size_t size) { auto buf = SharedRingBuffer(CreateFlag(), size); if (!buf.is_valid()) return base::nullopt; return base::make_optional(std::move(buf)); } // static base::Optional<SharedRingBuffer> SharedRingBuffer::Attach( base::ScopedFile mem_fd) { auto buf = SharedRingBuffer(AttachFlag(), std::move(mem_fd)); if (!buf.is_valid()) return base::nullopt; return base::make_optional(std::move(buf)); } } // namespace profiling } // namespace perfetto <|endoftext|>
<commit_before>#include <boost/cast.hpp> #include "messageHandler.h" #include <libwatcher/messageStatus.h> using namespace std; using namespace watcher; using namespace watcher::event; using namespace boost; INIT_LOGGER(MessageHandler, "MessageHandler"); MessageHandler::MessageHandler() { TRACE_ENTER(); TRACE_EXIT(); } MessageHandler::~MessageHandler() { TRACE_ENTER(); TRACE_EXIT(); } MessageHandler::ConnectionCommand MessageHandler::produceReply(const MessagePtr &request, MessagePtr &reply) { TRACE_ENTER(); LOG_DEBUG("Producing reply for message: " << *request); reply=MessageStatusPtr(new MessageStatus(MessageStatus::status_ack)); LOG_DEBUG("Produced reply: " << *reply); TRACE_EXIT_RET("writeMessage"); return writeMessage; } MessageHandler::ConnectionCommand MessageHandler::handleReply(const MessagePtr &request, const MessagePtr &reply) { TRACE_ENTER(); LOG_INFO("Recv'd :" << "\n\t" << *reply << endl << "In reply to: " << "\n\t" << *request); if (reply->type != MESSAGE_STATUS_TYPE) { LOG_WARN("Got a non-message status message in reply."); TRACE_EXIT_RET("closeConnection"); return closeConnection; } MessageStatusPtr mess=boost::dynamic_pointer_cast<MessageStatus>(reply); if(mess->status!=MessageStatus::status_ack && mess->status!=MessageStatus::status_ok) { LOG_WARN("Recv'd non ack reply to request: " << MessageStatus::statusToString(mess->status)); } else { LOG_INFO("Recv'd ack to request, all is well."); } TRACE_EXIT_RET("stayConnected"); return stayConnected; } void MessageHandler::handleMessageArrive(const MessagePtr message) { TRACE_ENTER(); LOG_INFO("Recv'd message: " << message); TRACE_EXIT(); } <commit_msg>Check return value of dynamic_cast<> of Message reply from server. Currently is NOT casting from base ---> derived. Which is bad.<commit_after>#include <boost/cast.hpp> #include "messageHandler.h" #include <libwatcher/messageStatus.h> using namespace std; using namespace watcher; using namespace watcher::event; using namespace boost; INIT_LOGGER(MessageHandler, "MessageHandler"); MessageHandler::MessageHandler() { TRACE_ENTER(); TRACE_EXIT(); } MessageHandler::~MessageHandler() { TRACE_ENTER(); TRACE_EXIT(); } MessageHandler::ConnectionCommand MessageHandler::produceReply(const MessagePtr &request, MessagePtr &reply) { TRACE_ENTER(); LOG_DEBUG("Producing reply for message: " << *request); reply=MessageStatusPtr(new MessageStatus(MessageStatus::status_ack)); LOG_DEBUG("Produced reply: " << *reply); TRACE_EXIT_RET("writeMessage"); return writeMessage; } MessageHandler::ConnectionCommand MessageHandler::handleReply(const MessagePtr &request, const MessagePtr &reply) { TRACE_ENTER(); LOG_INFO("Recv'd :" << "\n\t" << *reply << endl << "In reply to: " << "\n\t" << *request); if (reply->type != MESSAGE_STATUS_TYPE) { LOG_WARN("Got a non-message status message in reply."); TRACE_EXIT_RET("closeConnection"); return closeConnection; } MessageStatusPtr mess=boost::dynamic_pointer_cast<MessageStatus>(reply); if(mess) { if(mess->status!=MessageStatus::status_ack && mess->status!=MessageStatus::status_ok) { LOG_WARN("Recv'd non ack reply to request: " << MessageStatus::statusToString(mess->status)); } else { LOG_INFO("Recv'd ack to request, all is well."); } } else { LOG_ERROR("Look into this: unable to dynamically cast a shared_ptr<base> to shared_ptr<derived> even though it is the right type"); } TRACE_EXIT_RET("closeConnection"); return closeConnection; } void MessageHandler::handleMessageArrive(const MessagePtr message) { TRACE_ENTER(); LOG_INFO("Recv'd message: " << message); TRACE_EXIT(); } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mcommonpixmaps.h" #include "mthemedaemon.h" #include "mdebug.h" #include <QFile> #include <QDir> using namespace M::MThemeDaemonProtocol; #define VERSION(major, minor) ((major << 16) | minor) const unsigned int PRELOAD_FILE_VERSION = VERSION(0, 1); MCommonPixmaps::MCommonPixmaps(MThemeDaemon *daemon) : minRequestsForCache(0), daemon(daemon) { connect(&cpuMonitor, SIGNAL(newCpuFrameAvailable()), SLOT(loadOne())); } MCommonPixmaps::~MCommonPixmaps() { // please call clear before destroying this object Q_ASSERT(mostUsedPixmaps.count() == 0); } void MCommonPixmaps::clear() { // release all most used pixmaps foreach(const PixmapIdentifier & id, mostUsedPixmaps) { if (toLoadList.contains(id)) continue; ImageResource *resource = daemon->findImageResource(id.imageId); resource->releasePixmap(id.size); } cpuMonitor.stop(); mostUsedPixmaps.clear(); toLoadList.clear(); requestCounts.clear(); minRequestsForCache = 0; } bool MCommonPixmaps::load(const QString &filename) { // clear the old ones. clear(); QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { return false; } QDataStream stream(&file); unsigned int version; stream >> version; if (version != PRELOAD_FILE_VERSION) return false; QString path = cachePath(); while (file.bytesAvailable()) { QString imageId; QSize size; quint32 requestCount; bool isMostUsed; stream >> imageId >> size >> requestCount >> isMostUsed; PixmapIdentifier id(imageId, size); requestCounts.insert(id, requestCount); if (isMostUsed) { bool resourceLoaded = false; QFile pixmapFile(path + id.imageId + '(' + QString::number(id.size.width()) + ',' + QString::number(id.size.height()) + ')'); if(pixmapFile.open(QIODevice::ReadOnly)) { // find this resource ImageResource* resource = daemon->findImageResource(imageId); if(resource) { // try to load pre-rasterized pixmap from file resourceLoaded = resource->load(&pixmapFile, size); } pixmapFile.close(); } // if there was no pre-rasterized pixmap for this resource, // it will be added to load list. if(!resourceLoaded) { toLoadList.insert(PixmapIdentifier(imageId, size)); } mostUsedPixmaps.insert(PixmapIdentifier(imageId, size)); } } if (!toLoadList.isEmpty()) { cpuMonitor.start(2000); } file.close(); return true; } bool MCommonPixmaps::save(const QString &filename) const { QFile file(filename); if (!file.open(QIODevice::WriteOnly)) { return false; } QDataStream stream(&file); stream << PRELOAD_FILE_VERSION; QHash<PixmapIdentifier, quint32>::const_iterator i = requestCounts.begin(); QString path = cachePath(); for (; i != requestCounts.end(); ++i) { const PixmapIdentifier& id = i.key(); bool isMostUsed = mostUsedPixmaps.contains(id); stream << id.imageId << id.size << i.value() << isMostUsed; if(isMostUsed) { QFile pixmapFile(path + id.imageId + '(' + QString::number(id.size.width()) + ',' + QString::number(id.size.height()) + ')'); if(!pixmapFile.exists()) { if(pixmapFile.open(QIODevice::WriteOnly)) { ImageResource* resource = daemon->findImageResource(id.imageId); if(resource && resource->save(&pixmapFile, id.size)) { pixmapFile.close(); } else { pixmapFile.remove(); } } } } } file.close(); return true; } void MCommonPixmaps::loadOne() { // stop the timer, so we can adjust the frequency depending on the usage cpuMonitor.stop(); if (0 <= cpuMonitor.usage() || cpuMonitor.usage() < 10) { PixmapIdentifier id = *toLoadList.begin(); toLoadList.erase(toLoadList.begin()); if (!toLoadList.isEmpty()) { // there's still items in the list, so start the timer with small delay cpuMonitor.start(250); } ImageResource *resource = daemon->findImageResource(id.imageId); if (resource) resource->fetchPixmap(id.size); else { mWarning("MCommonPixmaps") << QString("Themedaemon could not find resource %1 while loading most used pixmaps. Removing from list.").arg(id.imageId); requestCounts.remove(id); mostUsedPixmaps.remove(id); } } else { // the cpu usage was too high, so start start the timer with longer delay cpuMonitor.start(2000); } } void MCommonPixmaps::increaseRequestCount(const M::MThemeDaemonProtocol::PixmapIdentifier &id, ImageResource *resource) { QHash<PixmapIdentifier, quint32>::iterator requestCount = requestCounts.find(id); if (requestCount == requestCounts.end()) { requestCount = requestCounts.insert(id, 0); } ++requestCount.value(); // does this pixmap has higher request count value than the current minimum for cache? if (requestCount.value() > minRequestsForCache && !mostUsedPixmaps.contains(id)) { // this pixmap might end up to mostUsedPixmaps list // check if there's still room for this pixmap if (mostUsedPixmaps.count() < MCommonPixmaps::CacheSize) { // yep, just add this pixmap and return resource->fetchPixmap(id.size); mostUsedPixmaps.insert(id); return; } // there was no room, so we'll check if we can make it QSet<PixmapIdentifier>::iterator i = mostUsedPixmaps.begin(); QSet<PixmapIdentifier>::iterator leastUsed = i; quint32 leastUsedRequests = requestCounts[*leastUsed]; quint32 secondlyLeastUsedRequests = leastUsedRequests; ++i; // find the least used pixmap from most used list for (; i != mostUsedPixmaps.end(); ++i) { const PixmapIdentifier &curId = *i; quint32 count = requestCounts[curId]; if (count < leastUsedRequests) { secondlyLeastUsedRequests = leastUsedRequests; leastUsedRequests = count; leastUsed = i; } } // if the least used is still above the current, we'll just update the limit if (leastUsedRequests >= requestCount.value()) { minRequestsForCache = leastUsedRequests; return; } // otherwise we have a new pixmap for the list // update the limit, there may be duplicate request counts in the most used list minRequestsForCache = (secondlyLeastUsedRequests > requestCount.value()) ? requestCount.value() : secondlyLeastUsedRequests; // allocate one pixmap for the list resource->fetchPixmap(id.size); // release the old one from the list if (!toLoadList.remove(*leastUsed)) { // resource was loaded resource = daemon->findImageResource(leastUsed->imageId); resource->releasePixmap(leastUsed->size); } remove(*leastUsed); mostUsedPixmaps.insert(id); } } void MCommonPixmaps::reload(const PixmapIdentifier &id, ImageResource *oldResource) { if (toLoadList.contains(id) || !mostUsedPixmaps.contains(id)) { // no need to do anything return; } oldResource->releasePixmap(id.size); toLoadList.insert(id); } void MCommonPixmaps::remove(const M::MThemeDaemonProtocol::PixmapIdentifier &id) { // path to theme-specific cache QString path = cachePath() + id.imageId + '(' + QString::number(id.size.width()) + ',' + QString::number(id.size.height()) + ')'; // remove pixmap file from disk if there is one if(QFile::exists(path)) { QFile::remove(path); } mostUsedPixmaps.remove(id); } QString MCommonPixmaps::cachePath() const { return MThemeDaemon::systemThemeCacheDirectory() + QDir::separator() + daemon->currentTheme() + QDir::separator(); } <commit_msg>Fixes: NB#177613 - MCommonPixmaps crash happened<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mcommonpixmaps.h" #include "mthemedaemon.h" #include "mdebug.h" #include <QFile> #include <QDir> using namespace M::MThemeDaemonProtocol; #define VERSION(major, minor) ((major << 16) | minor) const unsigned int PRELOAD_FILE_VERSION = VERSION(0, 1); MCommonPixmaps::MCommonPixmaps(MThemeDaemon *daemon) : minRequestsForCache(0), daemon(daemon) { connect(&cpuMonitor, SIGNAL(newCpuFrameAvailable()), SLOT(loadOne())); } MCommonPixmaps::~MCommonPixmaps() { // please call clear before destroying this object Q_ASSERT(mostUsedPixmaps.count() == 0); } void MCommonPixmaps::clear() { // release all most used pixmaps foreach(const PixmapIdentifier & id, mostUsedPixmaps) { if (toLoadList.contains(id)) continue; ImageResource *resource = daemon->findImageResource(id.imageId); resource->releasePixmap(id.size); } cpuMonitor.stop(); mostUsedPixmaps.clear(); toLoadList.clear(); requestCounts.clear(); minRequestsForCache = 0; } bool MCommonPixmaps::load(const QString &filename) { // clear the old ones. clear(); QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { return false; } QDataStream stream(&file); unsigned int version; stream >> version; if (version != PRELOAD_FILE_VERSION) return false; QString path = cachePath(); while (file.bytesAvailable()) { QString imageId; QSize size; quint32 requestCount; bool isMostUsed; stream >> imageId >> size >> requestCount >> isMostUsed; PixmapIdentifier id(imageId, size); requestCounts.insert(id, requestCount); if (isMostUsed) { bool resourceLoaded = false; QFile pixmapFile(path + id.imageId + '(' + QString::number(id.size.width()) + ',' + QString::number(id.size.height()) + ')'); if(pixmapFile.open(QIODevice::ReadOnly)) { // find this resource ImageResource* resource = daemon->findImageResource(imageId); if(resource) { // try to load pre-rasterized pixmap from file resourceLoaded = resource->load(&pixmapFile, size); } pixmapFile.close(); } // if there was no pre-rasterized pixmap for this resource, // it will be added to load list. if(!resourceLoaded) { toLoadList.insert(PixmapIdentifier(imageId, size)); } mostUsedPixmaps.insert(PixmapIdentifier(imageId, size)); } } if (!toLoadList.isEmpty()) { cpuMonitor.start(2000); } file.close(); return true; } bool MCommonPixmaps::save(const QString &filename) const { QFile file(filename); if (!file.open(QIODevice::WriteOnly)) { return false; } QDataStream stream(&file); stream << PRELOAD_FILE_VERSION; QHash<PixmapIdentifier, quint32>::const_iterator i = requestCounts.begin(); QString path = cachePath(); for (; i != requestCounts.end(); ++i) { const PixmapIdentifier& id = i.key(); bool isMostUsed = mostUsedPixmaps.contains(id); stream << id.imageId << id.size << i.value() << isMostUsed; if(isMostUsed) { QFile pixmapFile(path + id.imageId + '(' + QString::number(id.size.width()) + ',' + QString::number(id.size.height()) + ')'); if(!pixmapFile.exists()) { if(pixmapFile.open(QIODevice::WriteOnly)) { ImageResource* resource = daemon->findImageResource(id.imageId); if(resource && resource->save(&pixmapFile, id.size)) { pixmapFile.close(); } else { pixmapFile.remove(); } } } } } file.close(); return true; } void MCommonPixmaps::loadOne() { // stop the timer, so we can adjust the frequency depending on the usage cpuMonitor.stop(); if (0 <= cpuMonitor.usage() || cpuMonitor.usage() < 10) { //check if there really is something to load if (!toLoadList.isEmpty()) { PixmapIdentifier id = *toLoadList.begin(); toLoadList.erase(toLoadList.begin()); if (!toLoadList.isEmpty()) { // there's still items in the list, so start the timer with small delay cpuMonitor.start(250); } ImageResource *resource = daemon->findImageResource(id.imageId); if (resource) resource->fetchPixmap(id.size); else { mWarning("MCommonPixmaps") << QString("Themedaemon could not find resource %1 while loading most used pixmaps. Removing from list.").arg(id.imageId); requestCounts.remove(id); mostUsedPixmaps.remove(id); } } } else { // the cpu usage was too high, so start start the timer with longer delay cpuMonitor.start(2000); } } void MCommonPixmaps::increaseRequestCount(const M::MThemeDaemonProtocol::PixmapIdentifier &id, ImageResource *resource) { QHash<PixmapIdentifier, quint32>::iterator requestCount = requestCounts.find(id); if (requestCount == requestCounts.end()) { requestCount = requestCounts.insert(id, 0); } ++requestCount.value(); // does this pixmap has higher request count value than the current minimum for cache? if (requestCount.value() > minRequestsForCache && !mostUsedPixmaps.contains(id)) { // this pixmap might end up to mostUsedPixmaps list // check if there's still room for this pixmap if (mostUsedPixmaps.count() < MCommonPixmaps::CacheSize) { // yep, just add this pixmap and return resource->fetchPixmap(id.size); mostUsedPixmaps.insert(id); return; } // there was no room, so we'll check if we can make it QSet<PixmapIdentifier>::iterator i = mostUsedPixmaps.begin(); QSet<PixmapIdentifier>::iterator leastUsed = i; quint32 leastUsedRequests = requestCounts[*leastUsed]; quint32 secondlyLeastUsedRequests = leastUsedRequests; ++i; // find the least used pixmap from most used list for (; i != mostUsedPixmaps.end(); ++i) { const PixmapIdentifier &curId = *i; quint32 count = requestCounts[curId]; if (count < leastUsedRequests) { secondlyLeastUsedRequests = leastUsedRequests; leastUsedRequests = count; leastUsed = i; } } // if the least used is still above the current, we'll just update the limit if (leastUsedRequests >= requestCount.value()) { minRequestsForCache = leastUsedRequests; return; } // otherwise we have a new pixmap for the list // update the limit, there may be duplicate request counts in the most used list minRequestsForCache = (secondlyLeastUsedRequests > requestCount.value()) ? requestCount.value() : secondlyLeastUsedRequests; // allocate one pixmap for the list resource->fetchPixmap(id.size); // release the old one from the list if (!toLoadList.remove(*leastUsed)) { // resource was loaded resource = daemon->findImageResource(leastUsed->imageId); resource->releasePixmap(leastUsed->size); } remove(*leastUsed); mostUsedPixmaps.insert(id); } } void MCommonPixmaps::reload(const PixmapIdentifier &id, ImageResource *oldResource) { if (toLoadList.contains(id) || !mostUsedPixmaps.contains(id)) { // no need to do anything return; } oldResource->releasePixmap(id.size); toLoadList.insert(id); } void MCommonPixmaps::remove(const M::MThemeDaemonProtocol::PixmapIdentifier &id) { // path to theme-specific cache QString path = cachePath() + id.imageId + '(' + QString::number(id.size.width()) + ',' + QString::number(id.size.height()) + ')'; // remove pixmap file from disk if there is one if(QFile::exists(path)) { QFile::remove(path); } mostUsedPixmaps.remove(id); } QString MCommonPixmaps::cachePath() const { return MThemeDaemon::systemThemeCacheDirectory() + QDir::separator() + daemon->currentTheme() + QDir::separator(); } <|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 QtCore module 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 "qtimestamp.h" #include <windows.h> typedef ULONGLONG (WINAPI *PtrGetTickCount64)(void); static PtrGetTickCount64 ptrGetTickCount64 = 0; QT_BEGIN_NAMESPACE static void resolveLibs() { static bool done = false; if (done) return; // try to get GetTickCount64 from the system HMODULE kernel32 = GetModuleHandleW(L"kernel32"); if (!kernel32) return; #if defined(Q_OS_WINCE) // does this function exist on WinCE, or will ever exist? ptrGetTickCount64 = (PtrGetTickCount64)GetProcAddress(kernel32, L"GetTickCount64"); #else ptrGetTickCount64 = (PtrGetTickCount64)GetProcAddress(kernel32, "GetTickCount64"); #endif done = true; } static quint64 getTickCount() { resolveLibs(); if (ptrGetTickCount64) return ptrGetTickCount64(); return GetTickCount(); } bool QTimestamp::isMonotonic() { return true; } void QTimestamp::start() { t1 = getTickCount(); t2 = 0; } qint64 QTimestamp::restart() { qint64 oldt1 = t1; t1 = getTickCount(); return t1 - oldt1; } qint64 QTimestamp::elapsed() const { return getTickCount() - t1; } qint64 QTimestamp::msecsTo(const QTimestamp &other) const { return other.t1 - t1; } void QTimestamp::addMSecs(int ms) { t1 += ms; } qint64 QTimestamp::secsTo(const QTimestamp &other) const { return msecsTo(other) / 1000; } void QTimestamp::addSecs(int secs) { t1 += secs * 1000; } bool operator<(const QTimestamp &v1, const QTimestamp &v2) { return v1.t1 < v2.t1; } QT_END_NAMESPACE <commit_msg>Add support for 32-bit rollovers on Windows<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 QtCore module 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 "qtimestamp.h" #include <windows.h> typedef ULONGLONG (WINAPI *PtrGetTickCount64)(void); static PtrGetTickCount64 ptrGetTickCount64 = 0; QT_BEGIN_NAMESPACE static void resolveLibs() { static bool done = false; if (done) return; // try to get GetTickCount64 from the system HMODULE kernel32 = GetModuleHandleW(L"kernel32"); if (!kernel32) return; #if defined(Q_OS_WINCE) // does this function exist on WinCE, or will ever exist? ptrGetTickCount64 = (PtrGetTickCount64)GetProcAddress(kernel32, L"GetTickCount64"); #else ptrGetTickCount64 = (PtrGetTickCount64)GetProcAddress(kernel32, "GetTickCount64"); #endif done = true; } static quint64 getTickCount() { resolveLibs(); if (ptrGetTickCount64) return ptrGetTickCount64(); return GetTickCount(); } static qint64 difference(qint64 a, qint64 b) { qint64 retval = a - b; // if we're not using GetTickCount64, then there can be 32-bit rollover // assume there were rollovers if the difference is negative by more than // 75% of the 32-bit range if (!ptrGetTickCount64 && retval < Q_INT64_C(-0xc0000000)) retval += Q_UINT64_C(0x100000000); return retval; } bool QTimestamp::isMonotonic() { return true; } void QTimestamp::start() { t1 = getTickCount(); t2 = 0; } qint64 QTimestamp::restart() { qint64 oldt1 = t1; t1 = getTickCount(); return difference(t1, oldt1); } qint64 QTimestamp::elapsed() const { return difference(getTickCount(), t1); } qint64 QTimestamp::msecsTo(const QTimestamp &other) const { return difference(other.t1, t1); } void QTimestamp::addMSecs(int ms) { t1 += ms; // do we need to simulate rolling over? if (!ptrGetTickCount64) t1 = quint32(t1); } qint64 QTimestamp::secsTo(const QTimestamp &other) const { return msecsTo(other) / 1000; } void QTimestamp::addSecs(int secs) { addMSecs(secs * 1000); } bool operator<(const QTimestamp &v1, const QTimestamp &v2) { return difference(v1.t1, v2.t1) < 0; } QT_END_NAMESPACE <|endoftext|>
<commit_before>/** * @file multi_wrapper_impls.hpp * * @brief Implementations of methods or functions requiring the definitions of * multiple CUDA entity proxy classes. In some cases these are declared in the * individual proxy class files, with the other classes forward-declared. */ #pragma once #ifndef MULTI_WRAPPER_IMPLS_HPP_ #define MULTI_WRAPPER_IMPLS_HPP_ #include <cuda/api/stream.hpp> #include <cuda/api/device.hpp> #include <cuda/api/event.hpp> #include <cuda/api/pointer.hpp> namespace cuda { namespace event { /** * @brief creates a new execution stream on a device. * * @note The CUDA API runtime defaults to creating * which you synchronize on by busy-waiting. This function does * the same for compatibility. * * @param device The device on which to create the new stream * @param uses_blocking_sync When synchronizing on this new evet, * shall a thread busy-wait for it, or * @param records_timing Can this event be used to record time * values (e.g. duration between events) * @param interprocess Can multiple processes work with the constructed * event? * @return The constructed event proxy class */ template <bool DeviceAssumedCurrent> inline event_t create( device_t<DeviceAssumedCurrent> device, bool uses_blocking_sync, bool records_timing, bool interprocess) { auto device_id = device.id(); // Yes, we need the ID explicitly even on the current device, // because event_t's don't have an implicit device ID. return event::detail::create(device_id , uses_blocking_sync, records_timing, interprocess); } } // namespace event_t // device_t methods template <bool AssumedCurrent> inline void device_t<AssumedCurrent>::synchronize(event_t& event) { return synchronize_event(event.id()); } template <bool AssumedCurrent> inline void device_t<AssumedCurrent>::synchronize(stream_t<detail::do_not_assume_device_is_current>& stream) { return synchronize_stream(stream.id()); } template <bool AssumedCurrent> inline stream_t<AssumedCurrent> device_t<AssumedCurrent>::default_stream() const noexcept { // TODO: Perhaps support not-knowing our ID here as well, somehow? return stream_t<AssumedCurrent>(id(), stream::default_stream_id); } template <bool AssumedCurrent> inline stream_t<detail::do_not_assume_device_is_current> device_t<AssumedCurrent>::create_stream( bool will_synchronize_with_default_stream, stream::priority_t priority) { device::current::scoped_override_t<AssumedCurrent> set_device_for_this_scope(id_); constexpr const auto take_ownership = true; return stream::wrap(id(), stream::detail::create_on_current_device( will_synchronize_with_default_stream, priority), take_ownership); } template <bool AssumedCurrent> inline event_t device_t<AssumedCurrent>::create_event( bool uses_blocking_sync, bool records_timing, bool interprocess) { // The current implementation of event::create is not super-smart, // but it's probably not worth it trying to improve just this function return event::create<AssumedCurrent>(*this, uses_blocking_sync, records_timing, interprocess); } // event_t methods inline device_t<detail::do_not_assume_device_is_current> event_t::device() const { return cuda::device::get(device_id_); } // stream_t methods template <bool AssumesDeviceIsCurrent> inline device_t<detail::do_not_assume_device_is_current> stream_t<AssumesDeviceIsCurrent>::device() const { return cuda::device::get(device_id_); } template <bool AssumesDeviceIsCurrent> inline void stream_t<AssumesDeviceIsCurrent>::enqueue_t::wait(const event_t& event_) { #ifndef NDEBUG if (event_.device_id() != device_id_) { throw std::invalid_argument("Attempt to have a stream on CUDA device " + std::to_string(device_id_) + " wait for an event on another device (" "device " + std::to_string(event_.device_id()) + ")"); } #endif // Required by the CUDA runtime API; the flags value is // currently unused constexpr const unsigned int flags = 0; auto status = cudaStreamWaitEvent(stream_id_, event_.id(), flags); throw_if_error(status, std::string("Failed scheduling a wait for event ") + cuda::detail::ptr_as_hex(event_.id()) + " on stream " + cuda::detail::ptr_as_hex(stream_id_) + " on CUDA device " + std::to_string(device_id_)); } template <bool AssumesDeviceIsCurrent> inline event_t& stream_t<AssumesDeviceIsCurrent>::enqueue_t::event(event_t& existing_event) { #ifndef NDEBUG if (existing_event.device_id() != device_id_) { throw std::invalid_argument("Attempt to have a stream on CUDA device " + std::to_string(device_id_) + " wait for an event on another device (" "device " + std::to_string(existing_event.device_id()) + ")"); } #endif auto status = cudaEventRecord(existing_event.id(), stream_id_); throw_if_error(status, "Failed scheduling event " + cuda::detail::ptr_as_hex(existing_event.id()) + " to occur" + " on stream " + cuda::detail::ptr_as_hex(stream_id_) + " on CUDA device " + std::to_string(device_id_)); return existing_event; } template <bool AssumesDeviceIsCurrent> inline event_t stream_t<AssumesDeviceIsCurrent>::enqueue_t::event( bool uses_blocking_sync, bool records_timing, bool interprocess) { event_t ev { event::detail::create(device_id(), uses_blocking_sync, records_timing, interprocess) }; // Note that, at this point, the event is not associated with this enqueue object's stream. this->event(ev); return ev; } namespace memory { template <typename T> inline device_t<cuda::detail::do_not_assume_device_is_current> pointer_t<T>::device() const { return cuda::device::get(attributes().device); } namespace async { template <bool StreamIsOnCurrentDevice> inline void copy(void *destination, const void *source, size_t num_bytes, stream_t<StreamIsOnCurrentDevice>& stream) { detail::copy(destination, source, num_bytes, stream.id()); } template <typename T, bool StreamIsOnCurrentDevice> inline void copy_single(T& destination, const T& source, stream_t<StreamIsOnCurrentDevice>& stream) { detail::copy(&destination, &source, sizeof(T), stream.id()); } } // namespace async namespace device { template <bool AssumedCurrent> inline void* allocate(cuda::device_t<AssumedCurrent>& device, size_t size_in_bytes) { return memory::device::allocate(device.id(), size_in_bytes); } namespace async { template <bool StreamIsOnCurrentDevice> inline void set(void* start, int byte_value, size_t num_bytes, stream_t<StreamIsOnCurrentDevice>& stream) { detail::set(start, byte_value, num_bytes, stream.id()); } template <bool StreamIsOnCurrentDevice> inline void zero(void* start, size_t num_bytes, stream_t<StreamIsOnCurrentDevice>& stream) { detail::zero(start, num_bytes, stream.id()); } } // namespace async } // namespace device namespace managed { namespace async { template <bool DestinationIsCurrentDevice> inline void prefetch( const void* managed_ptr, size_t num_bytes, cuda::device_t<DestinationIsCurrentDevice>& destination, cuda::stream_t<DestinationIsCurrentDevice>& stream_id) { detail::prefetch(managed_ptr, num_bytes, destination.id(), stream_id.id()); } } // namespace async template <bool AssumedCurrent> inline void* allocate( cuda::device_t<AssumedCurrent>& device, size_t num_bytes, initial_visibility_t initial_visibility) { return detail::allocate(device.id(), num_bytes, initial_visibility); } } // namespace managed namespace mapped { template <bool AssumedCurrent> inline region_pair allocate( cuda::device_t<AssumedCurrent>& device, size_t size_in_bytes, region_pair::allocation_options options) { return cuda::memory::mapped::allocate(device.id(), size_in_bytes, options); } } // namespace mapped } // namespace memory namespace device_function { inline grid_dimension_t maximum_active_blocks_per_multiprocessor( device_t<> device, const device_function_t& device_function, grid_block_dimension_t num_threads_per_block, memory::shared::size_t dynamic_shared_memory_per_block, bool disable_caching_override) { device::current::scoped_override_t<> set_device_for_this_context(device.id()); int result; unsigned int flags = disable_caching_override ? cudaOccupancyDisableCachingOverride : cudaOccupancyDefault; auto status = cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( &result, device_function.ptr(), num_threads_per_block, dynamic_shared_memory_per_block, flags); throw_if_error(status, "Failed calculating the maximum occupancy " "of device function blocks per multiprocessor"); return result; } } // namespace device_function } // namespace cuda #endif // MULTI_WRAPPER_IMPLS_HPP_ <commit_msg>Fixes #148.<commit_after>/** * @file multi_wrapper_impls.hpp * * @brief Implementations of methods or functions requiring the definitions of * multiple CUDA entity proxy classes. In some cases these are declared in the * individual proxy class files, with the other classes forward-declared. */ #pragma once #ifndef MULTI_WRAPPER_IMPLS_HPP_ #define MULTI_WRAPPER_IMPLS_HPP_ #include <cuda/api/stream.hpp> #include <cuda/api/device.hpp> #include <cuda/api/event.hpp> #include <cuda/api/pointer.hpp> namespace cuda { namespace event { /** * @brief creates a new execution stream on a device. * * @note The CUDA API runtime defaults to creating * which you synchronize on by busy-waiting. This function does * the same for compatibility. * * @param device The device on which to create the new stream * @param uses_blocking_sync When synchronizing on this new evet, * shall a thread busy-wait for it, or * @param records_timing Can this event be used to record time * values (e.g. duration between events) * @param interprocess Can multiple processes work with the constructed * event? * @return The constructed event proxy class */ template <bool DeviceAssumedCurrent> inline event_t create( device_t<DeviceAssumedCurrent> device, bool uses_blocking_sync, bool records_timing, bool interprocess) { auto device_id = device.id(); // Yes, we need the ID explicitly even on the current device, // because event_t's don't have an implicit device ID. return event::detail::create(device_id , uses_blocking_sync, records_timing, interprocess); } } // namespace event_t // device_t methods template <bool AssumedCurrent> inline void device_t<AssumedCurrent>::synchronize(event_t& event) { return synchronize_event(event.id()); } template <bool AssumedCurrent> inline void device_t<AssumedCurrent>::synchronize(stream_t<detail::do_not_assume_device_is_current>& stream) { return synchronize_stream(stream.id()); } template <bool AssumedCurrent> inline stream_t<AssumedCurrent> device_t<AssumedCurrent>::default_stream() const noexcept { // TODO: Perhaps support not-knowing our ID here as well, somehow? return stream_t<AssumedCurrent>(id(), stream::default_stream_id); } template <bool AssumedCurrent> inline stream_t<detail::do_not_assume_device_is_current> device_t<AssumedCurrent>::create_stream( bool will_synchronize_with_default_stream, stream::priority_t priority) { device::current::scoped_override_t<AssumedCurrent> set_device_for_this_scope(id_); constexpr const auto take_ownership = true; return stream::wrap(id(), stream::detail::create_on_current_device( will_synchronize_with_default_stream, priority), take_ownership); } template <bool AssumedCurrent> inline event_t device_t<AssumedCurrent>::create_event( bool uses_blocking_sync, bool records_timing, bool interprocess) { // The current implementation of event::create is not super-smart, // but it's probably not worth it trying to improve just this function return event::create<AssumedCurrent>(*this, uses_blocking_sync, records_timing, interprocess); } // event_t methods inline device_t<detail::do_not_assume_device_is_current> event_t::device() const { return cuda::device::get(device_id_); } // stream_t methods template <bool AssumesDeviceIsCurrent> inline device_t<detail::do_not_assume_device_is_current> stream_t<AssumesDeviceIsCurrent>::device() const { return cuda::device::get(device_id_); } template <bool AssumesDeviceIsCurrent> inline void stream_t<AssumesDeviceIsCurrent>::enqueue_t::wait(const event_t& event_) { #ifndef NDEBUG if (event_.device_id() != device_id_) { throw std::invalid_argument("Attempt to have a stream on CUDA device " + std::to_string(device_id_) + " wait for an event on another device (" "device " + std::to_string(event_.device_id()) + ")"); } #endif // Required by the CUDA runtime API; the flags value is // currently unused constexpr const unsigned int flags = 0; auto status = cudaStreamWaitEvent(stream_id_, event_.id(), flags); throw_if_error(status, std::string("Failed scheduling a wait for event ") + cuda::detail::ptr_as_hex(event_.id()) + " on stream " + cuda::detail::ptr_as_hex(stream_id_) + " on CUDA device " + std::to_string(device_id_)); } template <bool AssumesDeviceIsCurrent> inline event_t& stream_t<AssumesDeviceIsCurrent>::enqueue_t::event(event_t& existing_event) { #ifndef NDEBUG if (existing_event.device_id() != device_id_) { throw std::invalid_argument("Attempt to have a stream on CUDA device " + std::to_string(device_id_) + " wait for an event on another device (" "device " + std::to_string(existing_event.device_id()) + ")"); } #endif auto status = cudaEventRecord(existing_event.id(), stream_id_); throw_if_error(status, "Failed scheduling event " + cuda::detail::ptr_as_hex(existing_event.id()) + " to occur" + " on stream " + cuda::detail::ptr_as_hex(stream_id_) + " on CUDA device " + std::to_string(device_id_)); return existing_event; } template <bool AssumesDeviceIsCurrent> inline event_t stream_t<AssumesDeviceIsCurrent>::enqueue_t::event( bool uses_blocking_sync, bool records_timing, bool interprocess) { event_t ev { event::detail::create(device_id(), uses_blocking_sync, records_timing, interprocess) }; // Note that, at this point, the event is not associated with this enqueue object's stream. this->event(ev); return ev; } namespace memory { template <typename T> inline device_t<cuda::detail::do_not_assume_device_is_current> pointer_t<T>::device() const { return cuda::device::get(attributes().device); } namespace async { template <bool StreamIsOnCurrentDevice> inline void copy(void *destination, const void *source, size_t num_bytes, stream_t<StreamIsOnCurrentDevice>& stream) { detail::copy(destination, source, num_bytes, stream.id()); } template <typename T, bool StreamIsOnCurrentDevice> inline void copy_single(T& destination, const T& source, stream_t<StreamIsOnCurrentDevice>& stream) { detail::copy(&destination, &source, sizeof(T), stream.id()); } } // namespace async namespace device { template <bool AssumedCurrent> inline void* allocate(cuda::device_t<AssumedCurrent>& device, size_t size_in_bytes) { return memory::device::detail::allocate(device.id(), size_in_bytes); } namespace async { template <bool StreamIsOnCurrentDevice> inline void set(void* start, int byte_value, size_t num_bytes, stream_t<StreamIsOnCurrentDevice>& stream) { detail::set(start, byte_value, num_bytes, stream.id()); } template <bool StreamIsOnCurrentDevice> inline void zero(void* start, size_t num_bytes, stream_t<StreamIsOnCurrentDevice>& stream) { detail::zero(start, num_bytes, stream.id()); } } // namespace async } // namespace device namespace managed { namespace async { template <bool DestinationIsCurrentDevice> inline void prefetch( const void* managed_ptr, size_t num_bytes, cuda::device_t<DestinationIsCurrentDevice>& destination, cuda::stream_t<DestinationIsCurrentDevice>& stream_id) { detail::prefetch(managed_ptr, num_bytes, destination.id(), stream_id.id()); } } // namespace async template <bool AssumedCurrent> inline void* allocate( cuda::device_t<AssumedCurrent>& device, size_t num_bytes, initial_visibility_t initial_visibility) { return detail::allocate(device.id(), num_bytes, initial_visibility); } } // namespace managed namespace mapped { template <bool AssumedCurrent> inline region_pair allocate( cuda::device_t<AssumedCurrent>& device, size_t size_in_bytes, region_pair::allocation_options options) { return cuda::memory::mapped::allocate(device.id(), size_in_bytes, options); } } // namespace mapped } // namespace memory namespace device_function { inline grid_dimension_t maximum_active_blocks_per_multiprocessor( device_t<> device, const device_function_t& device_function, grid_block_dimension_t num_threads_per_block, memory::shared::size_t dynamic_shared_memory_per_block, bool disable_caching_override) { device::current::scoped_override_t<> set_device_for_this_context(device.id()); int result; unsigned int flags = disable_caching_override ? cudaOccupancyDisableCachingOverride : cudaOccupancyDefault; auto status = cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( &result, device_function.ptr(), num_threads_per_block, dynamic_shared_memory_per_block, flags); throw_if_error(status, "Failed calculating the maximum occupancy " "of device function blocks per multiprocessor"); return result; } } // namespace device_function } // namespace cuda #endif // MULTI_WRAPPER_IMPLS_HPP_ <|endoftext|>
<commit_before>#include "userexchangemanager.h" #include "userexchangemanager_p.h" #include "message_p.h" using namespace QtDataSync; #if QT_HAS_INCLUDE(<chrono>) #define scdtime(x) x #else #define scdtime(x) std::chrono::duration_cast<std::chrono::milliseconds>(x).count() #endif const quint16 UserExchangeManager::DataExchangePort(13742); UserExchangeManager::UserExchangeManager(QObject *parent) : UserExchangeManager(DefaultSetup, parent) {} UserExchangeManager::UserExchangeManager(const QString &setupName, QObject *parent) : UserExchangeManager(new AccountManager(setupName), parent) { d->manager->setParent(this); } UserExchangeManager::UserExchangeManager(AccountManager *manager, QObject *parent) : QObject(parent), d(new UserExchangeManagerPrivate(manager, this)) { d->timer->setInterval(scdtime(std::chrono::seconds(2))); d->timer->setTimerType(Qt::VeryCoarseTimer); connect(d->timer, &QTimer::timeout, this, &UserExchangeManager::timeout); connect(d->socket, &QUdpSocket::readyRead, this, &UserExchangeManager::readDatagram); connect(d->socket, QOverload<QAbstractSocket::SocketError>::of(&QUdpSocket::error), this, [this]() { emit exchangeError(d->socket->errorString()); }); } UserExchangeManager::~UserExchangeManager() {} AccountManager *UserExchangeManager::accountManager() const { return d->manager; } quint16 UserExchangeManager::port() const { return d->socket->localPort(); } bool UserExchangeManager::isActive() const { return d->socket->state() == QAbstractSocket::BoundState; } QList<UserInfo> UserExchangeManager::devices() const { return d->devices.keys(); } bool UserExchangeManager::startExchange(const QHostAddress &listenAddress, quint16 port, bool allowReuseAddress) { d->devices.clear(); d->exchangeData.clear(); d->timer->stop(); emit devicesChanged(d->devices.keys()); if(d->socket->isOpen()) d->socket->close(); if(!d->socket->bind(listenAddress, port, allowReuseAddress ? QAbstractSocket::ShareAddress : QAbstractSocket::DontShareAddress)) { return false; } d->timer->start(); emit activeChanged(true); return true; } void UserExchangeManager::stopExchange() { d->timer->stop(); if(d->socket->isOpen()) d->socket->close(); emit activeChanged(false); d->devices.clear(); d->exchangeData.clear(); emit devicesChanged(d->devices.keys()); } void UserExchangeManager::exportTo(const UserInfo &userInfo, bool includeServer) { QPointer<UserExchangeManager> thisPtr(this); d->manager->exportAccount(includeServer, [thisPtr, this, userInfo](QByteArray exportData) { if(!thisPtr) return; QByteArray datagram; QDataStream stream(&datagram, QIODevice::WriteOnly | QIODevice::Unbuffered); Message::setupStream(stream); stream << static_cast<qint32>(UserExchangeManagerPrivate::DeviceDataUntrusted) << exportData; d->socket->writeDatagram(datagram, userInfo.address(), userInfo.port()); }, [thisPtr, this](QString error) { if(!thisPtr) return; emit exchangeError(error); }); } void UserExchangeManager::exportTrustedTo(const UserInfo &userInfo, bool includeServer, const QString &password) { QPointer<UserExchangeManager> thisPtr(this); d->manager->exportAccountTrusted(includeServer, password, [thisPtr, this, userInfo](QByteArray exportData) { if(!thisPtr) return; QByteArray datagram; QDataStream stream(&datagram, QIODevice::WriteOnly | QIODevice::Unbuffered); Message::setupStream(stream); stream << static_cast<qint32>(UserExchangeManagerPrivate::DeviceDataTrusted) << exportData; d->socket->writeDatagram(datagram, userInfo.address(), userInfo.port()); }, [thisPtr, this](QString error) { if(!thisPtr) return; emit exchangeError(error); }); } void UserExchangeManager::importFrom(const UserInfo &userInfo, const std::function<void(bool,QString)> &completedFn, bool keepData) { auto data = d->exchangeData.take(userInfo); if(data.isNull()) emit exchangeError(tr("No exchange data received from passed user"));//TODO is the rest translated too? (manager) else d->manager->importAccount(data, completedFn, keepData); } void UserExchangeManager::importTrustedFrom(const UserInfo &userInfo, const QString &password, const std::function<void(bool,QString)> &completedFn, bool keepData) { auto data = d->exchangeData.take(userInfo); if(data.isNull()) emit exchangeError(tr("No exchange data received from passed user"));//TODO is the rest translated too? (manager) else d->manager->importAccountTrusted(data, password, completedFn, keepData); } void UserExchangeManager::timeout() { for(auto it = d->devices.begin(); it != d->devices.end();) { if(*it >= 5) { d->exchangeData.remove(it.key()); it = d->devices.erase(it); } else { (*it)++; it++; } } QByteArray datagram; QDataStream stream(&datagram, QIODevice::WriteOnly | QIODevice::Unbuffered); Message::setupStream(stream); stream << static_cast<qint32>(UserExchangeManagerPrivate::DeviceInfo) << d->manager->deviceName(); } void UserExchangeManager::readDatagram() { while(d->socket->hasPendingDatagrams()) { auto datagram = d->socket->receiveDatagram(); QDataStream stream(datagram.data()); Message::setupStream(stream); qint32 type; stream.startTransaction(); stream >> type; auto isInfo = true; QString name; auto trusted = false; QByteArray data; switch (type) { case UserExchangeManagerPrivate::DeviceInfo: isInfo = true; stream >> name; break; case UserExchangeManagerPrivate::DeviceDataUntrusted: isInfo = false; trusted = false; stream >> data; break; case UserExchangeManagerPrivate::DeviceDataTrusted: isInfo = false; trusted = true; stream >> data; break; default: qWarning() << "UserExchangeManager: Skipped invalid message from" << UserInfo(new UserInfoPrivate(name, datagram)); continue; //jump to next loop iteration } if(stream.commitTransaction()) { if(name.isEmpty()) name = tr("<Unnamed>"); UserInfo info(new UserInfoPrivate(name, datagram)); //try to find the already existing user info for that data bool found = false; foreach(auto key, d->devices.keys()) { if(info == key) { found = true; if(isInfo) { //isInfo -> reset timeout, update name if neccessary d->devices.insert(info, 0); if(info.name() != key.name()) emit devicesChanged(d->devices.keys()); } else //!isInfo -> get the entry name info = key; break; } } if(isInfo) { if(!found) {//if not found -> simpy add to list d->devices.insert(info, 0); emit devicesChanged(d->devices.keys()); } } else { //data -> store it and emit d->exchangeData.insert(info, data); emit userDataReceived(info, trusted); } } else { emit exchangeError(tr("Invalid data received from %1:%2") .arg(datagram.senderAddress().toString()) .arg(datagram.senderPort())); } } } UserExchangeManagerPrivate::UserExchangeManagerPrivate(AccountManager *manager, UserExchangeManager *q_ptr) : manager(manager), socket(new QUdpSocket(q_ptr)), timer(new QTimer(q_ptr)), devices(), exchangeData() {} // ------------- UserInfo Implementation ------------- UserInfo::UserInfo() : d(new UserInfoPrivate()) {} UserInfo::UserInfo(const UserInfo &other) : d(other.d) {} UserInfo::UserInfo(UserInfoPrivate *data) : d(data) {} UserInfo::~UserInfo() {} QString UserInfo::name() const { return d->name; } QHostAddress UserInfo::address() const { return d->address; } quint16 UserInfo::port() const { return d->port; } UserInfo &UserInfo::operator=(const UserInfo &other) { d = other.d; return *this; } bool UserInfo::operator==(const UserInfo &other) const { return d->address == other.d->address && d->port == other.d->port; } uint QtDataSync::qHash(const UserInfo &info, uint seed) { return ::qHash(info.address(), seed) ^ ::qHash(info.port(), seed); } QDebug QtDataSync::operator<<(QDebug stream, const UserInfo &userInfo) { QDebugStateSaver saver(stream); stream.noquote().nospace() << "[" << userInfo.name() << "](" << userInfo.address() << ":" << userInfo.port() << ")"; return stream; } UserInfoPrivate::UserInfoPrivate(const QString &name, const QNetworkDatagram &datagram) : QSharedData(), name(name), address(datagram.senderAddress()), port(static_cast<quint16>(datagram.senderPort())) {} UserInfoPrivate::UserInfoPrivate(const UserInfoPrivate &other) : QSharedData(other), name(other.name), address(other.address), port(other.port) {} <commit_msg>fix missing include<commit_after>#include "userexchangemanager.h" #include "userexchangemanager_p.h" #include "message_p.h" #include <QtCore/QPointer> using namespace QtDataSync; #if QT_HAS_INCLUDE(<chrono>) #define scdtime(x) x #else #define scdtime(x) std::chrono::duration_cast<std::chrono::milliseconds>(x).count() #endif const quint16 UserExchangeManager::DataExchangePort(13742); UserExchangeManager::UserExchangeManager(QObject *parent) : UserExchangeManager(DefaultSetup, parent) {} UserExchangeManager::UserExchangeManager(const QString &setupName, QObject *parent) : UserExchangeManager(new AccountManager(setupName), parent) { d->manager->setParent(this); } UserExchangeManager::UserExchangeManager(AccountManager *manager, QObject *parent) : QObject(parent), d(new UserExchangeManagerPrivate(manager, this)) { d->timer->setInterval(scdtime(std::chrono::seconds(2))); d->timer->setTimerType(Qt::VeryCoarseTimer); connect(d->timer, &QTimer::timeout, this, &UserExchangeManager::timeout); connect(d->socket, &QUdpSocket::readyRead, this, &UserExchangeManager::readDatagram); connect(d->socket, QOverload<QAbstractSocket::SocketError>::of(&QUdpSocket::error), this, [this]() { emit exchangeError(d->socket->errorString()); }); } UserExchangeManager::~UserExchangeManager() {} AccountManager *UserExchangeManager::accountManager() const { return d->manager; } quint16 UserExchangeManager::port() const { return d->socket->localPort(); } bool UserExchangeManager::isActive() const { return d->socket->state() == QAbstractSocket::BoundState; } QList<UserInfo> UserExchangeManager::devices() const { return d->devices.keys(); } bool UserExchangeManager::startExchange(const QHostAddress &listenAddress, quint16 port, bool allowReuseAddress) { d->devices.clear(); d->exchangeData.clear(); d->timer->stop(); emit devicesChanged(d->devices.keys()); if(d->socket->isOpen()) d->socket->close(); if(!d->socket->bind(listenAddress, port, allowReuseAddress ? QAbstractSocket::ShareAddress : QAbstractSocket::DontShareAddress)) { return false; } d->timer->start(); emit activeChanged(true); return true; } void UserExchangeManager::stopExchange() { d->timer->stop(); if(d->socket->isOpen()) d->socket->close(); emit activeChanged(false); d->devices.clear(); d->exchangeData.clear(); emit devicesChanged(d->devices.keys()); } void UserExchangeManager::exportTo(const UserInfo &userInfo, bool includeServer) { QPointer<UserExchangeManager> thisPtr(this); d->manager->exportAccount(includeServer, [thisPtr, this, userInfo](QByteArray exportData) { if(!thisPtr) return; QByteArray datagram; QDataStream stream(&datagram, QIODevice::WriteOnly | QIODevice::Unbuffered); Message::setupStream(stream); stream << static_cast<qint32>(UserExchangeManagerPrivate::DeviceDataUntrusted) << exportData; d->socket->writeDatagram(datagram, userInfo.address(), userInfo.port()); }, [thisPtr, this](QString error) { if(!thisPtr) return; emit exchangeError(error); }); } void UserExchangeManager::exportTrustedTo(const UserInfo &userInfo, bool includeServer, const QString &password) { QPointer<UserExchangeManager> thisPtr(this); d->manager->exportAccountTrusted(includeServer, password, [thisPtr, this, userInfo](QByteArray exportData) { if(!thisPtr) return; QByteArray datagram; QDataStream stream(&datagram, QIODevice::WriteOnly | QIODevice::Unbuffered); Message::setupStream(stream); stream << static_cast<qint32>(UserExchangeManagerPrivate::DeviceDataTrusted) << exportData; d->socket->writeDatagram(datagram, userInfo.address(), userInfo.port()); }, [thisPtr, this](QString error) { if(!thisPtr) return; emit exchangeError(error); }); } void UserExchangeManager::importFrom(const UserInfo &userInfo, const std::function<void(bool,QString)> &completedFn, bool keepData) { auto data = d->exchangeData.take(userInfo); if(data.isNull()) emit exchangeError(tr("No exchange data received from passed user"));//TODO is the rest translated too? (manager) else d->manager->importAccount(data, completedFn, keepData); } void UserExchangeManager::importTrustedFrom(const UserInfo &userInfo, const QString &password, const std::function<void(bool,QString)> &completedFn, bool keepData) { auto data = d->exchangeData.take(userInfo); if(data.isNull()) emit exchangeError(tr("No exchange data received from passed user"));//TODO is the rest translated too? (manager) else d->manager->importAccountTrusted(data, password, completedFn, keepData); } void UserExchangeManager::timeout() { for(auto it = d->devices.begin(); it != d->devices.end();) { if(*it >= 5) { d->exchangeData.remove(it.key()); it = d->devices.erase(it); } else { (*it)++; it++; } } QByteArray datagram; QDataStream stream(&datagram, QIODevice::WriteOnly | QIODevice::Unbuffered); Message::setupStream(stream); stream << static_cast<qint32>(UserExchangeManagerPrivate::DeviceInfo) << d->manager->deviceName(); } void UserExchangeManager::readDatagram() { while(d->socket->hasPendingDatagrams()) { auto datagram = d->socket->receiveDatagram(); QDataStream stream(datagram.data()); Message::setupStream(stream); qint32 type; stream.startTransaction(); stream >> type; auto isInfo = true; QString name; auto trusted = false; QByteArray data; switch (type) { case UserExchangeManagerPrivate::DeviceInfo: isInfo = true; stream >> name; break; case UserExchangeManagerPrivate::DeviceDataUntrusted: isInfo = false; trusted = false; stream >> data; break; case UserExchangeManagerPrivate::DeviceDataTrusted: isInfo = false; trusted = true; stream >> data; break; default: qWarning() << "UserExchangeManager: Skipped invalid message from" << UserInfo(new UserInfoPrivate(name, datagram)); continue; //jump to next loop iteration } if(stream.commitTransaction()) { if(name.isEmpty()) name = tr("<Unnamed>"); UserInfo info(new UserInfoPrivate(name, datagram)); //try to find the already existing user info for that data bool found = false; foreach(auto key, d->devices.keys()) { if(info == key) { found = true; if(isInfo) { //isInfo -> reset timeout, update name if neccessary d->devices.insert(info, 0); if(info.name() != key.name()) emit devicesChanged(d->devices.keys()); } else //!isInfo -> get the entry name info = key; break; } } if(isInfo) { if(!found) {//if not found -> simpy add to list d->devices.insert(info, 0); emit devicesChanged(d->devices.keys()); } } else { //data -> store it and emit d->exchangeData.insert(info, data); emit userDataReceived(info, trusted); } } else { emit exchangeError(tr("Invalid data received from %1:%2") .arg(datagram.senderAddress().toString()) .arg(datagram.senderPort())); } } } UserExchangeManagerPrivate::UserExchangeManagerPrivate(AccountManager *manager, UserExchangeManager *q_ptr) : manager(manager), socket(new QUdpSocket(q_ptr)), timer(new QTimer(q_ptr)), devices(), exchangeData() {} // ------------- UserInfo Implementation ------------- UserInfo::UserInfo() : d(new UserInfoPrivate()) {} UserInfo::UserInfo(const UserInfo &other) : d(other.d) {} UserInfo::UserInfo(UserInfoPrivate *data) : d(data) {} UserInfo::~UserInfo() {} QString UserInfo::name() const { return d->name; } QHostAddress UserInfo::address() const { return d->address; } quint16 UserInfo::port() const { return d->port; } UserInfo &UserInfo::operator=(const UserInfo &other) { d = other.d; return *this; } bool UserInfo::operator==(const UserInfo &other) const { return d->address == other.d->address && d->port == other.d->port; } uint QtDataSync::qHash(const UserInfo &info, uint seed) { return ::qHash(info.address(), seed) ^ ::qHash(info.port(), seed); } QDebug QtDataSync::operator<<(QDebug stream, const UserInfo &userInfo) { QDebugStateSaver saver(stream); stream.noquote().nospace() << "[" << userInfo.name() << "](" << userInfo.address() << ":" << userInfo.port() << ")"; return stream; } UserInfoPrivate::UserInfoPrivate(const QString &name, const QNetworkDatagram &datagram) : QSharedData(), name(name), address(datagram.senderAddress()), port(static_cast<quint16>(datagram.senderPort())) {} UserInfoPrivate::UserInfoPrivate(const UserInfoPrivate &other) : QSharedData(other), name(other.name), address(other.address), port(other.port) {} <|endoftext|>
<commit_before>#include "server.hpp" namespace po = boost::program_options; using std::cout; using std::cerr; using std::endl; using std::string; int main(int argc, char* argv[]) { po::options_description desc("Bananagrams multiplayer dedicated server"); desc.add_options() ("help", "show options") ("dict", po::value<string>(), "dictionary file") ("port", po::value<unsigned int>()->default_value(default_port), "TCP/UDP listening port") ("bunch", po::value<string>()->default_value("1"), "bunch multiplier (0.5 or a positive integer)") ; // TODO usage string // TODO print help on unrecognized options po::variables_map opts; po::store(po::parse_command_line(argc, argv, desc), opts); po::notify(opts); if (opts.count("help")) { cerr << desc << endl; return 1; } // check port option unsigned int server_port {opts["port"].as<unsigned int>()}; if (server_port == 0 || server_port > 65535) { cerr << "Invalid listening port: " << server_port << "!\n"; return 1; } // check bunch multiplier option std::stringstream multi_s; multi_s << opts["bunch"].as<string>(); unsigned int b_num {1}; unsigned int b_den {1}; if (multi_s.str() == "0.5") b_den = 2; else multi_s >> b_num; // check dictionary option if (!opts.count("dict")) { cerr << "No dictionary file specified!\n"; return 1; } string dict = opts["dict"].as<string>(); std::map<string, string> dictionary; cout << "Loading dictionary... "; cout.flush(); std::ifstream words(dict); if (!words.is_open()) { std::cerr << "\nFailed to open " << dict << "!\n"; return 1; } // parse dictionary string line; while (std::getline(words, line)) { auto pos = line.find_first_of(' '); if (pos == string::npos) dictionary[line] = ""; else dictionary[line.substr(0, pos)] = line.substr(pos + 1, string::npos); } words.close(); cout << dictionary.size() << " words found"; cout.flush(); // LET'S GO!!! std::list<char> bunch; for (char ch = 'A'; ch <= 'Z'; ++ch) for (unsigned int i = 0; i < ((letter_count[ch - 'A'] * b_num) / b_den); ++i) random_insert(bunch, ch); std::map<sf::IpAddress, string> players; sf::UdpSocket socket; // TODO catch failure socket.bind(server_port); cout << "\nWaiting for player connections..."; cout.flush(); while (true) { sf::Packet packet; sf::IpAddress client_ip; unsigned short client_port; socket.receive(packet, client_ip, client_port); cout << "\nReceived packet from " << client_ip << ":" << client_port; cout.flush(); sf::Uint8 type; packet >> type; switch(type) { case 0: { string name; packet >> name; if (players.count(client_ip) == 0) { players[client_ip] = name; cout << "\n" << name << " has joined the game"; cout.flush(); } break; } case 1: { if (players.count(client_ip) > 0) { cout << "\n" << players[client_ip] << " has left the game"; cout.flush(); players.erase(client_ip); } break; } default: cout << "\nUnrecognized packet type: " << type; cout.flush(); } } return 0; } <commit_msg>Minor TODO, text change<commit_after>#include "server.hpp" namespace po = boost::program_options; using std::cout; using std::cerr; using std::endl; using std::string; int main(int argc, char* argv[]) { po::options_description desc("Bananagrams multiplayer dedicated server"); desc.add_options() ("help", "show options") ("dict", po::value<string>(), "dictionary file") ("port", po::value<unsigned int>()->default_value(default_port), "TCP/UDP listening port") ("bunch", po::value<string>()->default_value("1"), "bunch multiplier (0.5 or a positive integer)") ; // TODO usage string // TODO print help on unrecognized options po::variables_map opts; po::store(po::parse_command_line(argc, argv, desc), opts); po::notify(opts); if (opts.count("help")) { cerr << desc << endl; return 1; } // check port option unsigned int server_port {opts["port"].as<unsigned int>()}; if (server_port == 0 || server_port > 65535) { cerr << "Invalid listening port: " << server_port << "!\n"; return 1; } // check bunch multiplier option std::stringstream multi_s; multi_s << opts["bunch"].as<string>(); unsigned int b_num {1}; unsigned int b_den {1}; if (multi_s.str() == "0.5") b_den = 2; else multi_s >> b_num; // check dictionary option if (!opts.count("dict")) { cerr << "No dictionary file specified!\n"; return 1; } string dict = opts["dict"].as<string>(); std::map<string, string> dictionary; cout << "Loading dictionary... "; cout.flush(); std::ifstream words(dict); if (!words.is_open()) { std::cerr << "\nFailed to open " << dict << "!\n"; return 1; } // parse dictionary string line; while (std::getline(words, line)) { auto pos = line.find_first_of(' '); if (pos == string::npos) dictionary[line] = ""; else dictionary[line.substr(0, pos)] = line.substr(pos + 1, string::npos); } words.close(); cout << dictionary.size() << " words found"; cout.flush(); // LET'S GO!!! std::list<char> bunch; for (char ch = 'A'; ch <= 'Z'; ++ch) for (unsigned int i = 0; i < ((letter_count[ch - 'A'] * b_num) / b_den); ++i) random_insert(bunch, ch); std::map<sf::IpAddress, string> players; sf::UdpSocket socket; // TODO catch failure socket.bind(server_port); cout << "\nWaiting for players to join..."; cout.flush(); while (true) { sf::Packet packet; sf::IpAddress client_ip; unsigned short client_port; socket.receive(packet, client_ip, client_port); cout << "\nReceived packet from " << client_ip << ":" << client_port; cout.flush(); sf::Uint8 type; packet >> type; switch(type) { case 0: { string name; packet >> name; if (players.count(client_ip) == 0) { players[client_ip] = name; cout << "\n" << name << " has joined the game"; cout.flush(); } break; } case 1: { if (players.count(client_ip) > 0) { cout << "\n" << players[client_ip] << " has left the game"; cout.flush(); players.erase(client_ip); } break; } default: cout << "\nUnrecognized packet type: " << type; cout.flush(); } } // TODO catch interrupt and inform clients return 0; } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #undef NDEBUG #include "sg/geometry/Spheres.h" #include "sg/common/Data.h" #include "sg/common/World.h" // xml parser #include "common/xml/XML.h" namespace ospray { namespace sg { Spheres::Spheres() : Geometry("spheres") {} box3f Spheres::bounds() const { box3f bounds = empty; if (hasChild("spheres")) { auto spheres = child("spheres").nodeAs<DataBuffer>(); auto *base = (byte_t*)spheres->base(); auto sphereBytes = child("bytes_per_sphere").valueAs<int>(); auto offset_center = child("offset_center").valueAs<int>(); auto offset_radius = child("offset_radius").valueAs<int>(); for (int i = 0; i < spheres->numBytes(); i += sphereBytes) { vec3f &center = *(vec3f*)(base + i + offset_center); float &radius = *(float*)(base + i + offset_radius); box3f sphereBounds(center - radius, center + radius); bounds.extend(sphereBounds); } } return bounds; } //! \brief Initialize this node's value from given XML node /*! \detailed This allows a plug-and-play concept where a XML file can specify all kind of nodes wihout needing to know their actual types: The XML parser only needs to be able to create a proper C++ instance of the given node type (the OSP_REGISTER_SG_NODE() macro will allow it to do so), and can tell the node to parse itself from the given XML content and XML children \param node The XML node specifying this node's fields \param binBasePtr A pointer to an accompanying binary file (if existant) that contains additional binary data that the xml node fields may point into */ void Spheres::setFromXML(const xml::Node &node, const unsigned char *binBasePtr) { throw std::runtime_error("setFromXML no longer makes sense with the" " new scene graph design"); } OSP_REGISTER_SG_NODE(Spheres); }// ::ospray::sg }// ::ospray <commit_msg>More flexible sg::Sphere (use defaults, support const radius)<commit_after>// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #undef NDEBUG #include "sg/geometry/Spheres.h" #include "sg/common/Data.h" #include "sg/common/World.h" // xml parser #include "common/xml/XML.h" namespace ospray { namespace sg { Spheres::Spheres() : Geometry("spheres") {} box3f Spheres::bounds() const { box3f bounds = empty; if (hasChild("spheres")) { auto spheres = child("spheres").nodeAs<DataBuffer>(); auto *base = (byte_t*)spheres->base(); int sphereBytes = 16; if (hasChild("bytes_per_sphere")) sphereBytes = child("bytes_per_sphere").valueAs<int>(); int offset_center = 0; if (hasChild("offset_center")) offset_center = child("offset_center").valueAs<int>(); int offset_radius = -1; if (hasChild("offset_radius")) offset_radius = child("offset_radius").valueAs<int>(); float radius = 0.01f; if (hasChild("radius")) radius = child("radius").valueAs<float>(); for (int i = 0; i < spheres->numBytes(); i += sphereBytes) { vec3f &center = *(vec3f*)(base + i + offset_center); if (offset_radius >= 0) radius = *(float*)(base + i + offset_radius); box3f sphereBounds(center - radius, center + radius); bounds.extend(sphereBounds); } } return bounds; } //! \brief Initialize this node's value from given XML node /*! \detailed This allows a plug-and-play concept where a XML file can specify all kind of nodes wihout needing to know their actual types: The XML parser only needs to be able to create a proper C++ instance of the given node type (the OSP_REGISTER_SG_NODE() macro will allow it to do so), and can tell the node to parse itself from the given XML content and XML children \param node The XML node specifying this node's fields \param binBasePtr A pointer to an accompanying binary file (if existant) that contains additional binary data that the xml node fields may point into */ void Spheres::setFromXML(const xml::Node &node, const unsigned char *binBasePtr) { throw std::runtime_error("setFromXML no longer makes sense with the" " new scene graph design"); } OSP_REGISTER_SG_NODE(Spheres); }// ::ospray::sg }// ::ospray <|endoftext|>
<commit_before>#include "cmainwindow.h" #include "ui_cmainwindow.h" #include "settings/settings.h" #include "settings/csettings.h" #include "settingsui/csettingsdialog.h" #include "settings/csettingspagecamera.h" DISABLE_COMPILER_WARNINGS #include <QCameraInfo> #include <QDebug> #include <QImageReader> #include <QPainter> #include <QTimer> RESTORE_COMPILER_WARNINGS #define PROBING_ENABLED_SETTING QStringLiteral("UI/ProbingEnabled") CMainWindow::CMainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::CMainWindow) { ui->setupUi(this); ui->_displayWidget->installEventFilter(this); ui->actionProbing_enabled->setChecked(CSettings().value(PROBING_ENABLED_SETTING, true).toBool()); connect(ui->actionProbing_enabled, &QAction::triggered, [](bool checked){ CSettings().setValue(PROBING_ENABLED_SETTING, checked); }); connect(&_frameGrabber, &ProxyVideoSurface::frameReceived, this, &CMainWindow::processFrame); connect(ui->actionConnect, &QAction::triggered, [this](bool connect){ ui->actionConnect->setChecked(!connect); if (connect) startCamera(); else stopCamera(); }); connect(ui->actionSettings, &QAction::triggered, [this](){ CSettingsDialog(this) .addSettingsPage(new CSettingsPageCamera()) .exec(); }); // Some streaming devices seem to malfunction if they are connected to too soon after Windows startup. This is a safeguard against that. QTimer::singleShot(7000, [this](){ startCamera(); }); } CMainWindow::~CMainWindow() { stopCamera(); delete ui; } bool CMainWindow::eventFilter(QObject* /*object*/, QEvent* event) { if (event->type() == QEvent::Paint) { QWidget * widget = ui->_displayWidget; QPainter painter(widget); // Fill the background according the the color assigned to this widget painter.fillRect(widget->rect(), painter.background()); if (!_frame.isNull()) { const QSize scaledImagesize = _frame.size().scaled(widget->size(), Qt::KeepAspectRatio); QRect imageDrawRect = widget->geometry(); imageDrawRect.setSize(scaledImagesize); imageDrawRect.translate((widget->width() - scaledImagesize.width()) / 2, (widget->height() - scaledImagesize.height()) / 2); painter.drawImage(imageDrawRect, _frame); } if (_currentFrameContentsMetric != -1) { painter.setRenderHint(QPainter::TextAntialiasing, false); painter.setPen(QColor(0, 255, 255)); painter.drawText(5, painter.fontMetrics().height()+5, QString::number(_currentFrameContentsMetric)); } painter.end(); return true; } return false; } void CMainWindow::startCamera() { if (!_camera) { const auto cameras = QCameraInfo::availableCameras(); for (const QCameraInfo& cameraInfo : cameras) { if (cameraInfo.isNull()) continue; qDebug() << "Creating the camera" << cameraInfo.description(); _camera = std::make_shared<QCamera>(cameraInfo); if (!_camera->isAvailable()) { _camera.reset(); continue; } _camera->setViewfinder(&_frameGrabber); connect(_camera.get(), &QCamera::stateChanged, [this](const QCamera::State state){ if (state == QCamera::ActiveState) { ui->actionConnect->setChecked(true); setWindowTitle("Connected"); } else { ui->actionConnect->setChecked(false); setWindowTitle("Not Connected"); } }); break; } } if (_camera) { qDebug() << "Connecting to the camera"; _camera->load(); qDebug() << "Supported resolutions:"; QSize minSize {31000, 31000}; for (const QSize& size: _camera->supportedViewfinderResolutions()) { qDebug() << size; if (size.width() * size.height() < minSize.width() * minSize.height()) minSize = size; } QCameraViewfinderSettings viewFinderSettings =_camera->viewfinderSettings(); viewFinderSettings.setResolution(minSize); _camera->setViewfinderSettings(viewFinderSettings); _camera->start(); } _frameScanFilter.reset(); } void CMainWindow::stopCamera() { if (_camera) { qDebug() << "Disconnecting from the camera"; _camera->stop(); _camera->unload(); _frame = QImage(); _currentFrameContentsMetric = -1; ui->_displayWidget->update(); } setWindowTitle("Not Connected"); } inline int analyzeFrame(const QImage& frame) { if (frame.depth() != 32) return true; const int w = frame.width(), h = frame.height(); const int sampleSquareSize = 20; const int sampleStrideW = w / sampleSquareSize, sampleStrideH = h / sampleSquareSize; uint64_t pixelsValueSum = 0; for (int y = 0; y < h; y += sampleStrideH) { const uint32_t* scanLine = (const uint32_t*) frame.scanLine(y); for (int x = 0; x < w; x += sampleStrideW) { // TODO: support non-32 bpp images // TODO: vectorization const uint32_t pixel = scanLine[y]; pixelsValueSum += ((pixel & 0x00FF0000) >> 16) + ((pixel & 0x0000FF00) >> 8) + (pixel & 0x000000FF); } } const int result = (int) (pixelsValueSum / ((uint64_t) w / sampleStrideW * (uint64_t) h / sampleStrideH * 3ull)); return result; } void CMainWindow::processFrame(QImage frame) { if (!frame.isNull() && ui->actionProbing_enabled->isChecked()) { const int threshold = CSettings().value(IMAGE_PIXEL_VALUE_THRESHOLD_SETTING, IMAGE_PIXEL_VALUE_THRESHOLD_DEFAULT).toInt(); // This is the first frame upon connecting to the camera if (_frame.isNull()) { _currentFrameContentsMetric = analyzeFrame(frame); const auto frameScanResult = _frameScanFilter.processSample(_currentFrameContentsMetric >= threshold); if (frameScanResult == Filter::Invalid) { // Disconnect and schedule re-check stopCamera(); QTimer::singleShot(5000, [this](){ startCamera(); }); return; } else if (frameScanResult == Filter::Undefined) return; // To avoid assigning _frame, which would prevent the following frames from being scanned else { // We've detected valid image! showFullScreen(); raise(); } } else // Not the first frame - apparently, we're streaming a live picture // Avoid checking every single frame { static uint32_t frameCounter = 0; ++frameCounter; if (frameCounter > 30) { frameCounter = 0; _currentFrameContentsMetric = analyzeFrame(frame); if (_currentFrameContentsMetric < threshold) { // Disconnect and schedule re-check stopCamera(); QTimer::singleShot(5000, [this](){ startCamera(); }); showNormal(); showMinimized(); return; } } } } _frame = frame; ui->_displayWidget->update(); } <commit_msg>Mirroring implemented<commit_after>#include "cmainwindow.h" #include "ui_cmainwindow.h" #include "settings/settings.h" #include "settings/csettings.h" #include "settingsui/csettingsdialog.h" #include "settings/csettingspagecamera.h" DISABLE_COMPILER_WARNINGS #include <QCameraInfo> #include <QDebug> #include <QImageReader> #include <QPainter> #include <QTimer> RESTORE_COMPILER_WARNINGS #define PROBING_ENABLED_SETTING QStringLiteral("UI/ProbingEnabled") CMainWindow::CMainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::CMainWindow) { ui->setupUi(this); ui->_displayWidget->installEventFilter(this); ui->actionProbing_enabled->setChecked(CSettings().value(PROBING_ENABLED_SETTING, true).toBool()); connect(ui->actionProbing_enabled, &QAction::triggered, [](bool checked){ CSettings().setValue(PROBING_ENABLED_SETTING, checked); }); connect(&_frameGrabber, &ProxyVideoSurface::frameReceived, this, &CMainWindow::processFrame); connect(ui->actionConnect, &QAction::triggered, [this](bool connect){ ui->actionConnect->setChecked(!connect); if (connect) startCamera(); else stopCamera(); }); connect(ui->actionSettings, &QAction::triggered, [this](){ CSettingsDialog(this) .addSettingsPage(new CSettingsPageCamera()) .exec(); }); if (ui->actionProbing_enabled->isChecked()) { // Some streaming devices seem to malfunction if they are connected to too soon after Windows startup. This is a safeguard against that. QTimer::singleShot(7000, [this](){ startCamera(); }); } } CMainWindow::~CMainWindow() { stopCamera(); delete ui; } bool CMainWindow::eventFilter(QObject* /*object*/, QEvent* event) { if (event->type() == QEvent::Paint) { QWidget * widget = ui->_displayWidget; QPainter painter(widget); // Fill the background according the the color assigned to this widget painter.fillRect(widget->rect(), painter.background()); if (!_frame.isNull()) { const QSize scaledImagesize = _frame.size().scaled(widget->size(), Qt::KeepAspectRatio); QRect imageDrawRect = widget->geometry(); imageDrawRect.setSize(scaledImagesize); imageDrawRect.translate((widget->width() - scaledImagesize.width()) / 2, (widget->height() - scaledImagesize.height()) / 2); CSettings s; const bool mirrorH = s.value(IMAGE_HORIZONTAL_MIRROR_SETTING, false).toBool(), mirrorV = s.value(IMAGE_VERTICAL_MIRROR_SETTING, false).toBool(); painter.drawImage(imageDrawRect, mirrorH || mirrorV ? _frame.mirrored(mirrorH, mirrorV) : _frame); } if (_currentFrameContentsMetric != -1) { painter.setRenderHint(QPainter::TextAntialiasing, false); painter.setPen(QColor(0, 255, 255)); painter.drawText(5, painter.fontMetrics().height()+5, QString::number(_currentFrameContentsMetric)); } painter.end(); return true; } return false; } void CMainWindow::startCamera() { if (!_camera) { const auto cameras = QCameraInfo::availableCameras(); for (const QCameraInfo& cameraInfo : cameras) { if (cameraInfo.isNull()) continue; qDebug() << "Creating the camera" << cameraInfo.description(); _camera = std::make_shared<QCamera>(cameraInfo); if (!_camera->isAvailable()) { _camera.reset(); continue; } _camera->setViewfinder(&_frameGrabber); connect(_camera.get(), &QCamera::stateChanged, [this](const QCamera::State state){ if (state == QCamera::ActiveState) { ui->actionConnect->setChecked(true); setWindowTitle("Connected"); } else { ui->actionConnect->setChecked(false); setWindowTitle("Not Connected"); } }); break; } } if (_camera) { qDebug() << "Connecting to the camera"; _camera->load(); qDebug() << "Supported resolutions:"; QSize minSize {31000, 31000}; for (const QSize& size: _camera->supportedViewfinderResolutions()) { qDebug() << size; if (size.width() * size.height() < minSize.width() * minSize.height()) minSize = size; } QCameraViewfinderSettings viewFinderSettings =_camera->viewfinderSettings(); viewFinderSettings.setResolution(minSize); _camera->setViewfinderSettings(viewFinderSettings); _camera->start(); } _frameScanFilter.reset(); } void CMainWindow::stopCamera() { if (_camera) { qDebug() << "Disconnecting from the camera"; _camera->stop(); _camera->unload(); _frame = QImage(); _currentFrameContentsMetric = -1; ui->_displayWidget->update(); } setWindowTitle("Not Connected"); } inline int analyzeFrame(const QImage& frame) { if (frame.depth() != 32) return true; const int w = frame.width(), h = frame.height(); const int sampleSquareSize = 20; const int sampleStrideW = w / sampleSquareSize, sampleStrideH = h / sampleSquareSize; uint64_t pixelsValueSum = 0; for (int y = 0; y < h; y += sampleStrideH) { const uint32_t* scanLine = (const uint32_t*) frame.scanLine(y); for (int x = 0; x < w; x += sampleStrideW) { // TODO: support non-32 bpp images // TODO: vectorization const uint32_t pixel = scanLine[y]; pixelsValueSum += ((pixel & 0x00FF0000) >> 16) + ((pixel & 0x0000FF00) >> 8) + (pixel & 0x000000FF); } } const int result = (int) (pixelsValueSum / ((uint64_t) w / sampleStrideW * (uint64_t) h / sampleStrideH * 3ull)); return result; } void CMainWindow::processFrame(QImage frame) { if (!frame.isNull() && ui->actionProbing_enabled->isChecked()) { const int threshold = CSettings().value(IMAGE_PIXEL_VALUE_THRESHOLD_SETTING, IMAGE_PIXEL_VALUE_THRESHOLD_DEFAULT).toInt(); // This is the first frame upon connecting to the camera if (_frame.isNull()) { _currentFrameContentsMetric = analyzeFrame(frame); const auto frameScanResult = _frameScanFilter.processSample(_currentFrameContentsMetric >= threshold); if (frameScanResult == Filter::Invalid) { // Disconnect and schedule re-check stopCamera(); QTimer::singleShot(5000, [this](){ startCamera(); }); return; } else if (frameScanResult == Filter::Undefined) return; // To avoid assigning _frame, which would prevent the following frames from being scanned else { // We've detected valid image! showFullScreen(); raise(); } } else // Not the first frame - apparently, we're streaming a live picture // Avoid checking every single frame { static uint32_t frameCounter = 0; ++frameCounter; if (frameCounter > 30) { frameCounter = 0; _currentFrameContentsMetric = analyzeFrame(frame); if (_currentFrameContentsMetric < threshold) { // Disconnect and schedule re-check stopCamera(); QTimer::singleShot(5000, [this](){ startCamera(); }); showNormal(); showMinimized(); return; } } } } _frame = frame; ui->_displayWidget->update(); } <|endoftext|>
<commit_before>/* * Arduino-serial * -------------- * * A simple command-line example program showing how a computer can * communicate with an Arduino board. Works on any POSIX system (Mac/Unix/PC) * * * Compile with something like: * gcc -o arduino-serial arduino-serial.c * * Created 5 December 2006 * Copyleft (c) 2006, Tod E. Kurt, tod@todbot.com * * * * Updated 8 December 2006: * Justin McBride discoevered B14400 & B28800 aren't in Linux's termios.h. * I've included his patch, but commented out for now. One really needs a * real make system when doing cross-platform C and I wanted to avoid that * for this little program. Those baudrates aren't used much anyway. :) * * Updated 26 December 2007: * Added ability to specify a delay (so you can wait for Arduino Diecimila) * Added ability to send a binary byte number * */ #include <stdio.h> /* Standard input/output definitions */ #include <stdlib.h> #include <stdint.h> /* Standard types */ #include <string.h> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <sys/ioctl.h> #include <getopt.h> #include <iostream> void usage(void); int serialport_init(const char* serialport, int baud); int serialport_writebyte(int fd, uint8_t b); int serialport_write(int fd, const char* str); int serialport_read_until(int fd, char* buf, char until); void usage(void) { printf("Usage: arduino-serial -p <serialport> [OPTIONS]\n" "\n" "Options:\n" " -h, --help Print this help message\n" " -p, --port=serialport Serial port Arduino is on\n" " -b, --baud=baudrate Baudrate (bps) of Arduino\n" " -s, --send=data Send data to Arduino\n" " -r, --receive Receive data from Arduino & print it out\n" " -n --num=num Send a number as a single byte\n" " -d --delay=millis Delay for specified milliseconds\n" "\n" "Note: Order is important. Set '-b' before doing '-p'. \n" " Used to make series of actions: '-d 2000 -s hello -d 100 -r' \n" " means 'wait 2secs, send 'hello', wait 100msec, get reply'\n" "\n"); } int main(int argc, char *argv[]) { int fd = 0; char serialport[256]; int baudrate = B115200; // default char buf[20], dat[20], use[1]; int rc,n; //baudrate = 9600; fd = serialport_init("/dev/cu.usbmodem1411", baudrate); if(fd==-1) return -1; // usleep(3000 * 1000 ); std::cout << "passed here" << std::endl; while(1) { strcpy(dat, "00000000:\0"); gets(use); if(use[0] == 'f') { dat[0] = 'f'; dat[1] = 5; } else if(use[0] == 'k') { dat[0] = 'b'; dat[1] = 5; } else if(use[0] == 'j') { dat[2] = 'f'; dat[3] = 5; } else if(use[0] == 'l') { dat[2] = 'b'; dat[3] = 5; } rc = serialport_write(fd, dat); if(rc==-1) return -1; //printf("Waiting until UART buffer clears: %d\n", tcdrain(fd)); n = serialport_read_until(fd, buf, ':'); printf("wrote %d bytes, read %d bytes: %s\n", rc, n, buf); } close(fd); exit(EXIT_SUCCESS); } // end main int serialport_writebyte( int fd, uint8_t b) { int n = write(fd,&b,1); if( n!=1) return -1; return 0; } int serialport_write(int fd, const char* str) { int len = strlen(str); int n = write(fd, str, len); if( n!=len ) return -1; return n; } int serialport_read_until(int fd, char* buf, char until) { char b[1]; int i=0; do { int n = read(fd, b, 1); // read a char at a time if( n==-1) return -1; // couldn't read if( n==0 ) { usleep( 10 * 1000 ); // wait 10 msec try again continue; } buf[i] = b[0]; i++; } while( b[0] != until ); buf[i] = 0; // null terminate the string return i; } // takes the string name of the serial port (e.g. "/dev/tty.usbserial","COM1") // and a baud rate (bps) and connects to that port at that speed and 8N1. // opens the port in fully raw mode so you can send binary data. // returns valid fd, or -1 on error int serialport_init(const char* serialport, int baud) { struct termios toptions; int fd; //fprintf(stderr,"init_serialport: opening port %s @ %d bps\n", // serialport,baud); //fd = open(serialport, O_RDWR | O_NOCTTY | O_NDELAY); fd = open(serialport, O_RDWR | O_NOCTTY); if (fd == -1) { perror("init_serialport: Unable to open port "); return -1; } if (tcgetattr(fd, &toptions) < 0) { perror("init_serialport: Couldn't get term attributes"); return -1; } speed_t brate = baud; // let you override switch below if needed switch(baud) { case 4800: brate=B4800; break; case 9600: brate=B9600; break; // if you want these speeds, uncomment these and set #defines if Linux //#ifndef OSNAME_LINUX // case 14400: brate=B14400; break; //#endif case 19200: brate=B19200; break; //#ifndef OSNAME_LINUX // case 28800: brate=B28800; break; //#endif //case 28800: brate=B28800; break; case 38400: brate=B38400; break; case 57600: brate=B57600; break; case 115200: brate=B115200; break; } cfsetispeed(&toptions, brate); cfsetospeed(&toptions, brate); // 8N1 toptions.c_cflag &= ~PARENB; toptions.c_cflag &= ~CSTOPB; toptions.c_cflag &= ~CSIZE; toptions.c_cflag |= CS8; // no flow control toptions.c_cflag &= ~CRTSCTS; toptions.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw toptions.c_oflag &= ~OPOST; // make raw // see: http://unixwiz.net/techtips/termios-vmin-vtime.html toptions.c_cc[VMIN] = 0; toptions.c_cc[VTIME] = 20; if( tcsetattr(fd, TCSANOW, &toptions) < 0) { perror("init_serialport: Couldn't set term attributes"); return -1; } return fd; } <commit_msg>Delete TestFile2.cpp<commit_after><|endoftext|>
<commit_before>#ifndef TOML11_ACCEPTOR #define TOML11_ACCEPTOR #include <type_traits> #include <iterator> #include <limits> #include "exception.hpp" namespace toml { template<typename charT, charT c> struct is_character { typedef charT value_type; constexpr static value_type target = c; template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> constexpr static Iterator invoke(Iterator iter, Iterator end) { return iter == end ? iter : *iter == c ? std::next(iter) : iter; } }; template<typename charT, charT lw, charT up> struct is_in_range { typedef charT value_type; constexpr static value_type upper = up; constexpr static value_type lower = lw; static_assert(lower <= upper, "lower <= upper"); template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> constexpr static Iterator invoke(Iterator iter, Iterator end) { return iter == end ? iter : (lower <= *iter && *iter <= upper) ? std::next(iter) : iter; } }; template<typename headT, typename ... condT> struct is_one_of { typedef typename headT::value_type value_type; static_assert( std::is_same<value_type, typename is_one_of<condT...>::value_type>::value, "different value_type"); template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end) { const Iterator tmp = headT::invoke(iter, end); return (tmp != iter) ? tmp : is_one_of<condT...>::invoke(iter, end); } }; template<typename tailT> struct is_one_of<tailT> { typedef typename tailT::value_type value_type; template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end) { const Iterator tmp = tailT::invoke(iter, end); return (tmp != iter) ? tmp : iter; } }; // just a wrapper for maybe_ignored template<typename condT> struct is_ignorable { typedef typename condT::value_type value_type; template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end) { const Iterator tmp = condT::invoke(iter, end); return (tmp != iter) ? tmp : iter; } }; template<typename condT> struct maybe_ignored : std::false_type{}; template<typename condT> struct maybe_ignored<is_ignorable<condT>> : std::true_type{}; template<typename headT, typename ... condT> struct is_chain_of_impl { typedef typename headT::value_type value_type; static_assert(std::is_same<value_type, typename is_chain_of_impl<condT...>::value_type>::value, "different value_type"); constexpr static bool ignorable = maybe_ignored<headT>::value; template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end, Iterator rollback) { const Iterator tmp = headT::invoke(iter, end); return (tmp == iter && !ignorable) ? rollback : is_chain_of_impl<condT...>::invoke(tmp, end, rollback); } }; template<typename tailT> struct is_chain_of_impl<tailT> { typedef typename tailT::value_type value_type; constexpr static bool ignorable = maybe_ignored<tailT>::value; template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end, Iterator rollback) { const Iterator tmp = tailT::invoke(iter, end); return (tmp == iter) ? (ignorable ? iter : rollback) : tmp; } }; template<typename headT, typename ...condT> struct is_chain_of { typedef typename is_chain_of_impl<headT, condT...>::value_type value_type; template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end) { return is_chain_of_impl<headT, condT...>::invoke(iter, end, iter); } }; constexpr inline std::size_t repeat_infinite(){return 0ul;} template<typename condT, std::size_t N> struct is_repeat_of { typedef typename condT::value_type value_type; template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end) { const Iterator rollback = iter; Iterator tmp; for(auto i=0ul; i<N; ++i) { tmp = condT::invoke(iter, end); if(tmp == iter) return rollback; iter = tmp; } return iter; } }; template<typename condT> struct is_repeat_of<condT, 0> { typedef typename condT::value_type value_type; template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end) { Iterator tmp = condT::invoke(iter, end); while(tmp != iter) { iter = tmp; tmp = condT::invoke(iter, end); } return iter; } }; template<typename headT, typename ... tailT> struct is_none_of { typedef typename headT::value_type value_type; static_assert( std::is_same<value_type, typename is_one_of<tailT...>::value_type>::value, "different value_type"); template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end) { const Iterator tmp = headT::invoke(iter, end); return (tmp != iter) ? iter : is_none_of<tailT...>::invoke(iter, end); } }; template<typename tailT> struct is_none_of<tailT> { typedef typename tailT::value_type value_type; template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end) { const Iterator tmp = tailT::invoke(iter, end); return (tmp != iter) ? iter : std::next(iter); } }; template<typename notT, typename butT> struct is_not_but { typedef typename notT::value_type value_type; static_assert( std::is_same<value_type, typename butT::value_type>::value, "different value type"); template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end) { return (iter != notT::invoke(iter, end)) ? iter : butT::invoke(iter, end); } }; template<typename charT> using is_space = is_character<charT, ' '>; template<typename charT> using is_tab = is_character<charT, '\t'>; template<typename charT> using is_number = is_in_range<charT, '0', '9'>; template<typename charT> using is_lowercase = is_in_range<charT, 'a', 'z'>; template<typename charT> using is_uppercase = is_in_range<charT, 'A', 'Z'>; template<typename charT> using is_alphabet = is_one_of<is_lowercase<charT>, is_uppercase<charT>>; template<typename charT> using is_hex = is_one_of<is_number<charT>, is_in_range<charT, 'a', 'f'>, is_in_range<charT, 'A', 'F'>>; template<typename charT> using is_whitespace = is_one_of<is_space<charT>, is_tab<charT>>; template<typename charT> using is_any_num_of_ws = is_ignorable<is_repeat_of<is_whitespace<charT>, repeat_infinite()>>; template<typename charT> using is_newline = is_one_of<is_character<charT, '\n'>, is_chain_of<is_character<charT, '\r'>, is_character<charT, '\n'>>>; template<typename charT> using is_barekey_component = is_one_of<is_alphabet<charT>, is_number<charT>, is_character<charT, '_'>, is_character<charT, '-'>>; template<typename charT> using is_barekey = is_repeat_of<is_barekey_component<charT>, repeat_infinite()>; template<typename charT> using is_comment = is_chain_of< is_character<charT, '#'>, is_repeat_of<is_none_of<is_newline<charT>>, repeat_infinite()>, is_newline<charT> >; template<typename charT> using is_basic_inline_string_component = is_one_of< is_none_of< is_in_range<charT, '\0', '\31'>, is_character<charT, '\"'>, is_character<charT, '\\'>, is_newline<charT>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, '\"'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, '\\'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 'b'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 't'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 'n'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 'f'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 'r'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 'u'>, is_repeat_of<is_hex<charT>, 4>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 'U'>, is_repeat_of<is_hex<charT>, 8>> >; template<typename charT> using is_basic_inline_string = is_not_but< is_repeat_of<is_character<charT, '\"'>, 3>, // not multiline is_chain_of< is_character<charT, '\"'>, is_ignorable<is_repeat_of<is_basic_inline_string_component<charT>, repeat_infinite()>>, is_character<charT, '\"'> > >; template<typename charT> using is_basic_multiline_string_component = is_one_of< is_none_of< is_in_range<charT, '\0', '\31'>, is_repeat_of<is_character<charT, '\"'>, 3>, is_character<charT, '\\'>>, is_newline<charT>, is_chain_of<is_character<charT, '\\'>, is_newline<charT>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, '\"'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, '\\'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 'b'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 't'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 'n'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 'f'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 'r'>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 'u'>, is_repeat_of<is_hex<charT>, 4>>, is_chain_of<is_character<charT, '\\'>, is_character<charT, 'U'>, is_repeat_of<is_hex<charT>, 8>> >; template<typename charT> using is_basic_multiline_string = is_chain_of< is_repeat_of<is_character<charT, '\"'>, 3>, is_ignorable<is_repeat_of<is_basic_multiline_string_component<charT>, repeat_infinite()>>, is_repeat_of<is_character<charT, '\"'>, 3> >; template<typename charT> using is_literal_inline_string_component = is_none_of<is_in_range<charT, '\0', '\31'>, is_character<charT, '\''>>; template<typename charT> using is_literal_inline_string = is_not_but< is_repeat_of<is_character<charT, '\''>, 3>, is_chain_of< is_character<charT, '\''>, is_ignorable<is_repeat_of<is_literal_inline_string_component<charT>, repeat_infinite()>>, is_character<charT, '\''> > >; template<typename charT> using is_literal_multiline_string_component = is_one_of< is_none_of<is_in_range<charT, '\0', '\31'>, is_repeat_of<is_character<charT, '\''>, 3>>, is_newline<charT> >; template<typename charT> using is_literal_multiline_string = is_chain_of< is_repeat_of<is_character<charT, '\''>, 3>, is_ignorable<is_repeat_of<is_literal_multiline_string_component<charT>, repeat_infinite()>>, is_repeat_of<is_character<charT, '\''>, 3> >; template<typename charT> using is_string = is_one_of< is_basic_inline_string<charT>, is_basic_multiline_string<charT>, is_literal_inline_string<charT>, is_literal_multiline_string<charT> >; template<typename charT> using is_sign = is_one_of<is_character<charT, '+'>, is_character<charT, '-'>>; template<typename charT> using is_nonzero_number = is_in_range<charT, '1', '9'>; template<typename charT> using is_integer_component = is_not_but< is_repeat_of<is_character<charT, '_'>, 2>, is_one_of< is_character<charT, '_'>, is_number<charT> > >; template<typename charT> using is_integer = is_chain_of< is_ignorable<is_sign<charT>>, is_one_of< is_character<charT, '0'>, is_chain_of< is_nonzero_number<charT>, is_ignorable<is_repeat_of<is_integer_component<charT>, repeat_infinite()> > > > >; template<typename charT> using is_fractional_part = is_chain_of< is_character<charT, '.'>, is_repeat_of<is_integer_component<charT>, repeat_infinite()> >; template<typename charT> using is_exponent_part = is_chain_of< is_one_of<is_character<charT, 'e'>, is_character<charT, 'E'>>, is_integer<charT> >; template<typename charT> using is_float = is_one_of< is_chain_of< is_integer<charT>, is_fractional_part<charT>, is_exponent_part<charT> >, is_chain_of< is_integer<charT>, is_fractional_part<charT> >, is_chain_of< is_integer<charT>, is_exponent_part<charT> > >; template<typename charT> using is_boolean = is_one_of< is_chain_of< is_character<charT, 't'>, is_character<charT, 'r'>, is_character<charT, 'u'>, is_character<charT, 'e'> >, is_chain_of< is_character<charT, 'f'>, is_character<charT, 'a'>, is_character<charT, 'l'>, is_character<charT, 's'>, is_character<charT, 'e'> > >; template<typename charT> using is_local_time = is_chain_of< is_repeat_of<is_number<charT>, 2>, is_character<charT, ':'>, is_repeat_of<is_number<charT>, 2>, is_character<charT, ':'>, is_repeat_of<is_number<charT>, 2>, is_ignorable< is_chain_of< is_character<charT, '.'>, is_repeat_of<is_number<charT>, repeat_infinite()> > > >; template<typename charT> using is_local_date = is_chain_of< is_repeat_of<is_number<charT>, 4>, is_character<charT, '-'>, is_repeat_of<is_number<charT>, 2>, is_character<charT, '-'>, is_repeat_of<is_number<charT>, 2> >; template<typename charT> using is_local_date_time = is_chain_of< is_local_date<charT>, is_character<charT, 'T'>, is_local_time<charT> >; template<typename charT> using is_offset = is_one_of< is_character<charT, 'Z'>, is_chain_of< is_sign<charT>, is_repeat_of<is_number<charT>, 2>, is_character<charT, ':'>, is_repeat_of<is_number<charT>, 2> > >; template<typename charT> using is_offset_date_time = is_chain_of< is_local_date_time<charT>, is_offset<charT> >; template<typename charT> using is_datetime = is_one_of< is_offset_date_time<charT>, is_local_date_time<charT>, is_local_date<charT>, is_local_time<charT> >; template<typename charT> using is_fundamental_type = is_one_of< is_basic_inline_string<charT>, is_basic_multiline_string<charT>, is_literal_inline_string<charT>, is_literal_multiline_string<charT>, is_offset_date_time<charT>, is_local_date_time<charT>, is_local_date<charT>, is_local_time<charT>, is_boolean<charT>, is_float<charT>, is_integer<charT> >; template<typename charT> using is_skippable_in_array = is_repeat_of< is_one_of<is_whitespace<charT>, is_newline<charT>, is_comment<charT>>, repeat_infinite() >; template<typename charT> struct is_inline_table; template<typename charT> using is_key = is_one_of< is_barekey<charT>, is_string<charT> >; template<typename charT, typename is_array_component> using is_fixed_type_array = is_chain_of< is_character<charT, '['>, is_ignorable< is_repeat_of< is_chain_of< is_ignorable<is_skippable_in_array<charT>>, is_array_component, is_ignorable<is_skippable_in_array<charT>>, is_character<charT, ','> >, repeat_infinite() > >, is_ignorable< is_chain_of< is_ignorable<is_skippable_in_array<charT>>, is_array_component, is_ignorable<is_skippable_in_array<charT>>, is_ignorable<is_character<charT, ','>> > >, is_ignorable<is_skippable_in_array<charT>>, is_character<charT, ']'> >; template<typename charT> struct is_array { typedef charT value_type; template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end) { return is_one_of< is_fixed_type_array<charT, is_boolean<charT>>, is_fixed_type_array<charT, is_integer<charT>>, is_fixed_type_array<charT, is_float<charT>>, is_fixed_type_array<charT, is_string<charT>>, is_fixed_type_array<charT, is_datetime<charT>>, is_fixed_type_array<charT, is_array<charT>>, is_fixed_type_array<charT, is_inline_table<charT>> >::invoke(iter, end); } }; template<typename charT> struct is_inline_table { typedef charT value_type; template<typename Iterator, class = typename std::enable_if< std::is_same<typename std::iterator_traits<Iterator>::value_type, value_type>::value>::type> static Iterator invoke(Iterator iter, Iterator end) { typedef is_one_of<is_fundamental_type<charT>, is_array<charT>, is_inline_table<charT>> is_component; typedef is_chain_of< is_any_num_of_ws<charT>, is_key<charT>, is_any_num_of_ws<charT>, is_character<charT, '='>, is_any_num_of_ws<charT>, is_component, is_any_num_of_ws<charT> > is_inline_key_value_pair; typedef is_chain_of< is_character<charT, '{'>, is_ignorable< is_repeat_of< is_chain_of< is_any_num_of_ws<charT>, is_inline_key_value_pair, is_any_num_of_ws<charT>, is_character<charT, ','> >, repeat_infinite() > >, is_ignorable< is_chain_of< is_any_num_of_ws<charT>, is_inline_key_value_pair, is_any_num_of_ws<charT>, is_ignorable<is_character<charT, ','>> > >, is_any_num_of_ws<charT>, is_character<charT, '}'> > entity; return entity::invoke(iter, end); } }; template<typename charT> using is_value = is_one_of<is_fundamental_type<charT>, is_array<charT>, is_inline_table<charT>>; // [] template<typename charT> using is_table_definition = is_chain_of< is_any_num_of_ws<charT>, is_character<charT, '['>, is_any_num_of_ws<charT>, is_key<charT>, is_ignorable< is_repeat_of< is_chain_of< is_any_num_of_ws<charT>, is_character<charT, '.'>, is_any_num_of_ws<charT>, is_key<charT>, is_any_num_of_ws<charT> >, repeat_infinite()> >, is_character<charT, ']'> >; template<typename charT> using is_array_of_table_definition = is_chain_of< is_any_num_of_ws<charT>, is_repeat_of<is_character<charT, '['>, 2>, is_any_num_of_ws<charT>, is_key<charT>, is_ignorable< is_repeat_of< is_chain_of< is_any_num_of_ws<charT>, is_character<charT, '.'>, is_any_num_of_ws<charT>, is_key<charT>, is_any_num_of_ws<charT> >, repeat_infinite()> >, is_repeat_of<is_character<charT, ']'>, 2> >; template<typename charT> using is_key_value_pair = is_chain_of< is_any_num_of_ws<charT>, is_key<charT>, is_any_num_of_ws<charT>, is_character<charT, '='>, is_any_num_of_ws<charT>, is_value<charT>, is_any_num_of_ws<charT> >; template<typename charT> using is_empty_line = is_chain_of< is_any_num_of_ws<charT>, is_one_of<is_comment<charT>, is_newline<charT>> >; template<typename charT> using is_empty_lines = is_repeat_of< is_chain_of< is_any_num_of_ws<charT>, is_one_of<is_comment<charT>, is_newline<charT>> >, repeat_infinite() >; template<typename charT> using is_table_contents = is_repeat_of< is_one_of< is_empty_lines<charT>, is_chain_of< is_key_value_pair<charT>, is_one_of< is_comment<charT>, is_newline<charT> > > >, repeat_infinite() >; template<typename charT> using is_standard_table = is_chain_of< is_table_definition<charT>, is_any_num_of_ws<charT>, is_one_of<is_comment<charT>, is_newline<charT>>, is_table_contents<charT> >; template<typename charT> using is_array_of_table = is_chain_of< is_array_of_table_definition<charT>, is_any_num_of_ws<charT>, is_one_of<is_comment<charT>, is_newline<charT>>, is_table_contents<charT> >; template<typename charT> using is_toml_data = is_chain_of< is_ignorable<is_table_contents<charT>>, is_ignorable< is_repeat_of< is_one_of< is_standard_table<charT>, is_array_of_table<charT> >, repeat_infinite() > > >; }//toml #endif// TOML11_ACCEPTOR <commit_msg>remove old code<commit_after><|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. */ /** * @author Matthew Hoyt (mhoyt@ca.ibm.com) */ #if !defined(XALANSET_HEADER_GUARD_1357924680) #define XALANSET_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #include <xalanc/Include/XalanMap.hpp> #include <xalanc/Include/XalanMemoryManagement.hpp> XALAN_CPP_NAMESPACE_BEGIN template <class Value, class MapIterator> struct XalanSetIterator { typedef Value value_type; typedef Value& reference; typedef Value* pointer; typedef ptrdiff_t difference_type; typedef XALAN_STD_QUALIFIER bidirectional_iterator_tag iterator_category; XalanSetIterator(const MapIterator & iter) : m_mapIterator(iter) { } reference operator*() const { return m_mapIterator->first; }; bool operator==(const XalanSetIterator& theRhs) const { return theRhs.m_mapIterator == m_mapIterator; } bool operator!=(const XalanSetIterator& theRhs) const { return !(theRhs == *this); } XalanSetIterator operator++() { ++m_mapIterator; return *this; } XalanSetIterator operator++(int) { XalanSetIterator orig(m_mapIterator); ++(*this); return orig; } protected: MapIterator m_mapIterator; }; /** * Xalan set implementation. * * Set relies on the XalanMap hashtable. Users must ensure the right key * traits specialization is aviable to define the proper hash functor. */ template <class Value> class XalanSet { public: typedef Value value_type; typedef size_t size_type; typedef XalanMap<value_type, bool> SetMapType; typedef XalanSetIterator<value_type, typename SetMapType::iterator> iterator; typedef XalanSetIterator<const value_type, typename SetMapType::const_iterator> const_iterator; XalanSet(MemoryManagerType& theMemoryManager) : m_map(theMemoryManager) { } XalanSet(const XalanSet& other, MemoryManagerType& theMemoryManager) : m_map(other.m_map, theMemoryManager) { } MemoryManagerType& getMemoryManager() { return m_map.getMemoryManager(); } const_iterator begin() const { return m_map.begin(); } const_iterator end() const { return m_map.end(); } size_type size() const { return m_map.size(); } size_type count(const value_type & value) const { if (find(value) != end()) { return 1; } else { return 0; } } const_iterator find(const value_type& value) const { return m_map.find(value); } void insert(const value_type& value) { typedef typename SetMapType::value_type MapValueType; m_map.insert(value, true); } size_type erase(const value_type& value) { return m_map.erase(value); } void clear() { m_map.clear(); } SetMapType m_map; }; XALAN_CPP_NAMESPACE_END #endif // XALANSET_HEADER_GUARD_1357924680 <commit_msg>Made data member private.<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. */ #if !defined(XALANSET_HEADER_GUARD_1357924680) #define XALANSET_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #include <xalanc/Include/XalanMap.hpp> #include <xalanc/Include/XalanMemoryManagement.hpp> XALAN_CPP_NAMESPACE_BEGIN template <class Value, class MapIterator> struct XalanSetIterator { typedef Value value_type; typedef Value& reference; typedef Value* pointer; typedef ptrdiff_t difference_type; typedef XALAN_STD_QUALIFIER bidirectional_iterator_tag iterator_category; XalanSetIterator(const MapIterator& iter) : m_mapIterator(iter) { } reference operator*() const { return m_mapIterator->first; }; bool operator==(const XalanSetIterator& theRhs) const { return theRhs.m_mapIterator == m_mapIterator; } bool operator!=(const XalanSetIterator& theRhs) const { return !(theRhs == *this); } XalanSetIterator operator++() { ++m_mapIterator; return *this; } XalanSetIterator operator++(int) { XalanSetIterator orig(m_mapIterator); ++(*this); return orig; } protected: MapIterator m_mapIterator; }; /** * Xalan set implementation. * * Set relies on the XalanMap hashtable. Users must ensure the right key * traits specialization is aviable to define the proper hash functor. */ template <class Value> class XalanSet { public: typedef Value value_type; typedef size_t size_type; typedef XalanMap<value_type, bool> SetMapType; typedef XalanSetIterator<value_type, typename SetMapType::iterator> iterator; typedef XalanSetIterator<const value_type, typename SetMapType::const_iterator> const_iterator; XalanSet(MemoryManager& theMemoryManager) : m_map(theMemoryManager) { } XalanSet( const XalanSet& other, MemoryManager& theMemoryManager) : m_map(other.m_map, theMemoryManager) { } MemoryManager& getMemoryManager() { return m_map.getMemoryManager(); } const_iterator begin() const { return m_map.begin(); } const_iterator end() const { return m_map.end(); } size_type size() const { return m_map.size(); } size_type count(const value_type& value) const { return find(value) != end() ? 1 : 0; } const_iterator find(const value_type& value) const { return m_map.find(value); } void insert(const value_type& value) { m_map.insert(value, true); } size_type erase(const value_type& value) { return m_map.erase(value); } void clear() { m_map.clear(); } private: SetMapType m_map; }; XALAN_CPP_NAMESPACE_END #endif // XALANSET_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>#include <archivepp/archive_rar.hpp> #include <archivepp/except.hpp> #include <cmath> #include <cstring> namespace archivepp { namespace unrar { static std::error_code get_last_error(RAROpenArchiveDataEx & data) { return std::error_code(data.OpenResult, std::system_category()); } static HANDLE open(archivepp::string const & path, RAROpenArchiveDataEx & data, std::error_code & ec) { data.OpenMode = RAR_OM_EXTRACT; #ifdef ARCHIVEPP_USE_WSTRING data.ArcNameW = const_cast<char*>(path.c_str()); #else data.ArcName = const_cast<char*>(path.c_str()); #endif HANDLE handle = ::RAROpenArchiveEx(&data); ec = handle == nullptr ? get_last_error(data) : std::error_code(); return handle; } static std::error_code close(HANDLE handle) { return std::error_code(::RARCloseArchive(handle), std::system_category()); } static int64_t get_number_of_entries(archivepp::string const & path, std::error_code & ec) { RAROpenArchiveDataEx data {}; RARHeaderDataEx header {}; HANDLE handle = unrar::open(path, data, ec); if (handle == nullptr) throw archivepp::null_pointer_error("handle", __FUNCTION__); int64_t count = 0; ec = std::error_code(::RARReadHeaderEx(handle, &header), std::system_category()); while (!ec) { ::RARProcessFile(handle, RAR_SKIP, NULL, NULL); ++count; ec = std::error_code(::RARReadHeaderEx(handle, &header), std::system_category()); } // Expected error if (ec.value() == ERAR_END_ARCHIVE) ec = std::error_code(); unrar::close(handle); return count; } static std::pair<uint64_t, uint64_t> get_size_from_header(RARHeaderDataEx const & header) { // Initialize the size values with their upper and lower 32 bits int64_t unpacked_size = (static_cast<int64_t>(header.UnpSizeHigh) << 32) | header.UnpSize; int64_t packed_size = (static_cast<int64_t>(header.PackSizeHigh) << 32) | header.PackSize; return std::make_pair(unpacked_size, packed_size); } static archivepp::string get_name_from_header(RARHeaderDataEx const & header) { #ifdef ARCHIVEPP_USE_WSTRING return archivepp::string(&header.FileNameW[0]); #else return archivepp::string(&header.FileName[0]); #endif } struct cb_context { std::string buffer; archivepp::string password; cb_context() = default; }; /** * Callback that the unrar library calls whenever an event occurs during extraction. * * @param msg The event. * @param context A pointer to custom data. * @param data A chunk of unpacked data. * @param size The size of the unpacked chunk. */ static int CALLBACK callback(UINT msg, LPARAM context, LPARAM data, LPARAM size) { cb_context * context_ptr = reinterpret_cast<cb_context*>(context); // Ensure it's a valid pointer if (context_ptr == nullptr) return -1; switch (msg) { case UCM_PROCESSDATA: { // A chunk of data has been unpacked and is ready for further processing char const * const unpacked_data = reinterpret_cast<char *>(data); // Reserve (size) + (size / 2). // This takes into account that there might be more than one chunk context_ptr->buffer.reserve(context_ptr->buffer.size() + (std::ceil(static_cast<float>(size) * 1.5f))); // Copy the chunk of unpacked data to our buffer // Use std::back_inserter to ensure that the unpacked data is always appended to our buffer std::copy(&unpacked_data[0], &unpacked_data[size], std::back_inserter(context_ptr->buffer)); return 1; } #ifdef ARCHIVEPP_USE_WSTRING case UCM_NEEDPASSWORDW: { // Ensure there's a password for the context if (context_ptr->password.empty() != true) { // Copy the password to data and assign the size // No need to check if data and size are valid pointers // They are allocated on the stack in libunrar's function CmdExtract::ExtrDllGetPassword() auto length = context_ptr->password.length() > 128 ? 128 : context_ptr->password.length(); std::wcsncpy(reinterpret_cast<wchar_t*>(data), context_ptr->password.c_str(), length); *reinterpret_cast<size_t*>(size) = length; return 1; } } #else case UCM_NEEDPASSWORD: { // Ensure there's a password for the context if (context_ptr->password.empty() != true) { // Copy the password to data and assign the size // No need to check if data and size are valid pointers // They are allocated on the stack in libunrar's function CmdExtract::ExtrDllGetPassword() auto length = context_ptr->password.length() > 128 ? 128 : context_ptr->password.length(); std::strncpy(reinterpret_cast<char*>(data), context_ptr->password.c_str(), length); *reinterpret_cast<size_t*>(size) = length; return 1; } } #endif default: return -1; } } std::string fread(archivepp::string const & path, archivepp::string const & name, archivepp::string const & password, std::error_code & ec) { RAROpenArchiveDataEx data {}; RARHeaderDataEx header {}; HANDLE handle = unrar::open(path, data, ec); if (handle == nullptr) return std::string(); std::unique_ptr<unrar::cb_context> context_ptr(new unrar::cb_context()); if (context_ptr == nullptr) throw archivepp::null_pointer_error("context_ptr", __FUNCTION__); context_ptr->password = password; #ifdef ARCHIVEPP_USE_WSTRING ::RARSetPassword(handle, const_cast<char*>(to_utf8(password).c_str())); #else ::RARSetPassword(handle, const_cast<char*>(password.c_str())); #endif ::RARSetCallback(handle, unrar::callback, reinterpret_cast<LPARAM>(context_ptr.get())); ec = std::error_code(::RARReadHeaderEx(handle, &header), std::system_category()); while (ec.value() == ERAR_SUCCESS) { archivepp::string current_name = get_name_from_header(header); if (current_name == name) { ec = std::error_code(::RARProcessFile(handle, RAR_TEST, nullptr, nullptr), std::system_category()); break; } ::RARProcessFile(handle, RAR_SKIP, nullptr, nullptr); ec = std::error_code(::RARReadHeaderEx(handle, &header), std::system_category()); } unrar::close(handle); return std::string(std::move(context_ptr->buffer)); } } archive_rar::archive_rar(archivepp::string path, std::error_code & ec) : basic_archive(std::move(path)) { RAROpenArchiveDataEx data {}; HANDLE handle = unrar::open(get_path(), data, ec); unrar::close(handle); } archive_rar::archive_rar(archivepp::string path, archivepp::string password, std::error_code & ec) : basic_archive(std::move(path), std::move(password)) { RAROpenArchiveDataEx data {}; HANDLE handle = unrar::open(get_path(), data, ec); unrar::close(handle); } archive_rar::~archive_rar() { } int64_t archive_rar::get_number_of_entries() const { std::error_code ec; return unrar::get_number_of_entries(get_path(), ec); } std::string archive_rar::get_contents(entry_pointer const & entry, std::error_code & ec) const { return get_contents(entry, "", ec); } std::string archive_rar::get_contents(entry_pointer const & entry, archivepp::string const & password, std::error_code & ec) const { if (entry == nullptr) throw archivepp::null_argument_error("entry", __FUNCTION__); return get_contents(entry->get_index(), password, ec); } std::string archive_rar::get_contents(uint64_t index, std::error_code & ec) const { return get_contents(index, "", ec); } std::string archive_rar::get_contents(uint64_t index, archivepp::string const & password, std::error_code & ec) const { return std::string(); } std::string archive_rar::get_contents(archivepp::string const & name, std::error_code & ec) const { return get_contents(name, "", ec); } std::string archive_rar::get_contents(archivepp::string const & name, archivepp::string const & password, std::error_code & ec) const { archivepp::string real_password = get_password().empty() == true ? password : get_password(); return unrar::fread(get_path(), name, real_password, ec); } auto archive_rar::get_entries(filter_function filter_fn) const -> std::vector<entry_pointer> { std::vector<entry_pointer> entries; RAROpenArchiveDataEx data {}; std::error_code ec; HANDLE handle = unrar::open(get_path(), data, ec); if (handle == nullptr) throw archivepp::null_pointer_error("handle", __FUNCTION__); RARHeaderDataEx header {}; uint64_t index = 0; while (::RARReadHeaderEx(handle, &header) == ERAR_SUCCESS) { std::error_code ec; archivepp::string name = unrar::get_name_from_header(header); auto size_pair = unrar::get_size_from_header(header); entry_pointer entry_ptr(new archive_entry_rar(name, index, size_pair.first, size_pair.second, ec)); if(!ec) { bool skip = filter_fn != nullptr ? filter_fn(entry_ptr) : false; if (skip == false) entries.emplace_back(std::move(entry_ptr)); } ::RARProcessFile(handle, RAR_SKIP, nullptr, nullptr); ++index; } unrar::close(handle); return entries; } } <commit_msg>Fix segfault in unrar::callback<commit_after>#include <archivepp/archive_rar.hpp> #include <archivepp/except.hpp> #include <cmath> #include <cstring> namespace archivepp { namespace unrar { static std::error_code get_last_error(RAROpenArchiveDataEx & data) { return std::error_code(data.OpenResult, std::system_category()); } static HANDLE open(archivepp::string const & path, RAROpenArchiveDataEx & data, std::error_code & ec) { data.OpenMode = RAR_OM_EXTRACT; #ifdef ARCHIVEPP_USE_WSTRING data.ArcNameW = const_cast<char*>(path.c_str()); #else data.ArcName = const_cast<char*>(path.c_str()); #endif HANDLE handle = ::RAROpenArchiveEx(&data); ec = handle == nullptr ? get_last_error(data) : std::error_code(); return handle; } static std::error_code close(HANDLE handle) { return std::error_code(::RARCloseArchive(handle), std::system_category()); } static int64_t get_number_of_entries(archivepp::string const & path, std::error_code & ec) { RAROpenArchiveDataEx data {}; RARHeaderDataEx header {}; HANDLE handle = unrar::open(path, data, ec); if (handle == nullptr) throw archivepp::null_pointer_error("handle", __FUNCTION__); int64_t count = 0; ec = std::error_code(::RARReadHeaderEx(handle, &header), std::system_category()); while (!ec) { ::RARProcessFile(handle, RAR_SKIP, NULL, NULL); ++count; ec = std::error_code(::RARReadHeaderEx(handle, &header), std::system_category()); } // Expected error if (ec.value() == ERAR_END_ARCHIVE) ec = std::error_code(); unrar::close(handle); return count; } static std::pair<uint64_t, uint64_t> get_size_from_header(RARHeaderDataEx const & header) { // Initialize the size values with their upper and lower 32 bits int64_t unpacked_size = (static_cast<int64_t>(header.UnpSizeHigh) << 32) | header.UnpSize; int64_t packed_size = (static_cast<int64_t>(header.PackSizeHigh) << 32) | header.PackSize; return std::make_pair(unpacked_size, packed_size); } static archivepp::string get_name_from_header(RARHeaderDataEx const & header) { #ifdef ARCHIVEPP_USE_WSTRING return archivepp::string(&header.FileNameW[0]); #else return archivepp::string(&header.FileName[0]); #endif } struct cb_context { std::string buffer; archivepp::string password; cb_context() = default; }; /** * Callback that the unrar library calls whenever an event occurs during extraction. * * @param msg The event. * @param context A pointer to custom data. * @param data A chunk of unpacked data. * @param size The size of the unpacked chunk. */ static int CALLBACK callback(UINT msg, LPARAM context, LPARAM data, LPARAM size) { cb_context * context_ptr = reinterpret_cast<cb_context*>(context); // Ensure it's a valid pointer if (context_ptr == nullptr) return -1; switch (msg) { case UCM_PROCESSDATA: { // A chunk of data has been unpacked and is ready for further processing char const * const unpacked_data = reinterpret_cast<char *>(data); // Reserve (size) + (size / 2). // This takes into account that there might be more than one chunk context_ptr->buffer.reserve(context_ptr->buffer.size() + (std::ceil(static_cast<float>(size) * 1.5f))); // Copy the chunk of unpacked data to our buffer // Use std::back_inserter to ensure that the unpacked data is always appended to our buffer std::copy(&unpacked_data[0], &unpacked_data[size], std::back_inserter(context_ptr->buffer)); return 1; } #ifdef ARCHIVEPP_USE_WSTRING case UCM_NEEDPASSWORDW: { // Ensure there's a password for the context if (context_ptr->password.empty() != true) { // Copy the password to data // No need to check if data is a valid pointer // It is allocated on the stack in libunrar's function CmdExtract::ExtrDllGetPassword() auto length = context_ptr->password.length() > size ? size : context_ptr->password.length(); std::wcsncpy(reinterpret_cast<wchar_t*>(data), context_ptr->password.c_str(), length); return 1; } break; } #else case UCM_NEEDPASSWORD: { //Ensure there's a password for the context if (context_ptr->password.empty() != true) { // Copy the password to data // No need to check if data is a valid pointer // It is allocated on the stack in libunrar's function CmdExtract::ExtrDllGetPassword() auto length = static_cast<LPARAM>(context_ptr->password.length()) > size ? size : context_ptr->password.length(); std::strncpy(reinterpret_cast<char*>(data), context_ptr->password.c_str(), length); return 1; } break; } #endif default: break; } return -1; } std::string fread(archivepp::string const & path, archivepp::string const & name, archivepp::string const & password, std::error_code & ec) { RAROpenArchiveDataEx data {}; RARHeaderDataEx header {}; HANDLE handle = unrar::open(path, data, ec); if (handle == nullptr) return std::string(); std::unique_ptr<unrar::cb_context> context_ptr(new unrar::cb_context()); if (context_ptr == nullptr) throw archivepp::null_pointer_error("context_ptr", __FUNCTION__); context_ptr->password = password; // #ifdef ARCHIVEPP_USE_WSTRING // ::RARSetPassword(handle, const_cast<char*>(to_utf8(password).c_str())); // #else // ::RARSetPassword(handle, const_cast<char*>(password.c_str())); // #endif ::RARSetCallback(handle, unrar::callback, reinterpret_cast<LPARAM>(context_ptr.get())); ec = std::error_code(::RARReadHeaderEx(handle, &header), std::system_category()); while (ec.value() == ERAR_SUCCESS) { archivepp::string current_name = get_name_from_header(header); if (current_name == name) { ec = std::error_code(::RARProcessFile(handle, RAR_TEST, nullptr, nullptr), std::system_category()); break; } ::RARProcessFile(handle, RAR_SKIP, nullptr, nullptr); ec = std::error_code(::RARReadHeaderEx(handle, &header), std::system_category()); } unrar::close(handle); return std::string(std::move(context_ptr->buffer)); } } archive_rar::archive_rar(archivepp::string path, std::error_code & ec) : basic_archive(std::move(path)) { RAROpenArchiveDataEx data {}; HANDLE handle = unrar::open(get_path(), data, ec); unrar::close(handle); } archive_rar::archive_rar(archivepp::string path, archivepp::string password, std::error_code & ec) : basic_archive(std::move(path), std::move(password)) { RAROpenArchiveDataEx data {}; HANDLE handle = unrar::open(get_path(), data, ec); unrar::close(handle); } archive_rar::~archive_rar() { } int64_t archive_rar::get_number_of_entries() const { std::error_code ec; return unrar::get_number_of_entries(get_path(), ec); } std::string archive_rar::get_contents(entry_pointer const & entry, std::error_code & ec) const { return get_contents(entry, "", ec); } std::string archive_rar::get_contents(entry_pointer const & entry, archivepp::string const & password, std::error_code & ec) const { if (entry == nullptr) throw archivepp::null_argument_error("entry", __FUNCTION__); return get_contents(entry->get_index(), password, ec); } std::string archive_rar::get_contents(uint64_t index, std::error_code & ec) const { return get_contents(index, "", ec); } std::string archive_rar::get_contents(uint64_t index, archivepp::string const & password, std::error_code & ec) const { return std::string(); } std::string archive_rar::get_contents(archivepp::string const & name, std::error_code & ec) const { return get_contents(name, "", ec); } std::string archive_rar::get_contents(archivepp::string const & name, archivepp::string const & password, std::error_code & ec) const { archivepp::string real_password = get_password().empty() == true ? password : get_password(); return unrar::fread(get_path(), name, real_password, ec); } auto archive_rar::get_entries(filter_function filter_fn) const -> std::vector<entry_pointer> { std::vector<entry_pointer> entries; RAROpenArchiveDataEx data {}; std::error_code ec; HANDLE handle = unrar::open(get_path(), data, ec); if (handle == nullptr) throw archivepp::null_pointer_error("handle", __FUNCTION__); RARHeaderDataEx header {}; uint64_t index = 0; while (::RARReadHeaderEx(handle, &header) == ERAR_SUCCESS) { std::error_code ec; archivepp::string name = unrar::get_name_from_header(header); auto size_pair = unrar::get_size_from_header(header); entry_pointer entry_ptr(new archive_entry_rar(name, index, size_pair.first, size_pair.second, ec)); if(!ec) { bool skip = filter_fn != nullptr ? filter_fn(entry_ptr) : false; if (skip == false) entries.emplace_back(std::move(entry_ptr)); } ::RARProcessFile(handle, RAR_SKIP, nullptr, nullptr); ++index; } unrar::close(handle); return entries; } } <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include "libtorrent/socket.hpp" #include <boost/bind.hpp> #include <boost/mpl/max_element.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/sizeof.hpp> #include <boost/mpl/transform_view.hpp> #include <boost/mpl/deref.hpp> #include <boost/lexical_cast.hpp> #include <libtorrent/io.hpp> #include <libtorrent/invariant_check.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/logging.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/find_data.hpp> #include <libtorrent/kademlia/closest_nodes.hpp> #include <libtorrent/kademlia/refresh.hpp> #include <libtorrent/kademlia/node.hpp> #include <libtorrent/kademlia/observer.hpp> #include <libtorrent/hasher.hpp> #include <fstream> using boost::shared_ptr; using boost::bind; namespace libtorrent { namespace dht { namespace io = libtorrent::detail; namespace mpl = boost::mpl; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DEFINE_LOG(rpc) #endif void intrusive_ptr_add_ref(observer const* o) { TORRENT_ASSERT(o->m_refs >= 0); TORRENT_ASSERT(o != 0); ++o->m_refs; } void intrusive_ptr_release(observer const* o) { TORRENT_ASSERT(o->m_refs > 0); TORRENT_ASSERT(o != 0); if (--o->m_refs == 0) { boost::pool<>& p = o->pool_allocator; o->~observer(); p.free(const_cast<observer*>(o)); } } node_id generate_id(); typedef mpl::vector< closest_nodes_observer , find_data_observer , announce_observer , get_peers_observer , refresh_observer , ping_observer , null_observer > observer_types; typedef mpl::max_element< mpl::transform_view<observer_types, mpl::sizeof_<mpl::_1> > >::type max_observer_type_iter; rpc_manager::rpc_manager(fun const& f, node_id const& our_id , routing_table& table, send_fun const& sf) : m_pool_allocator(sizeof(mpl::deref<max_observer_type_iter::base>::type)) , m_next_transaction_id(rand() % max_transactions) , m_oldest_transaction_id(m_next_transaction_id) , m_incoming(f) , m_send(sf) , m_our_id(our_id) , m_table(table) , m_timer(time_now()) , m_random_number(generate_id()) , m_destructing(false) { std::srand(time(0)); } rpc_manager::~rpc_manager() { m_destructing = true; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Destructing"; #endif std::for_each(m_aborted_transactions.begin(), m_aborted_transactions.end() , bind(&observer::abort, _1)); for (transactions_t::iterator i = m_transactions.begin() , end(m_transactions.end()); i != end; ++i) { if (*i) (*i)->abort(); } } #ifndef NDEBUG void rpc_manager::check_invariant() const { TORRENT_ASSERT(m_oldest_transaction_id >= 0); TORRENT_ASSERT(m_oldest_transaction_id < max_transactions); TORRENT_ASSERT(m_next_transaction_id >= 0); TORRENT_ASSERT(m_next_transaction_id < max_transactions); TORRENT_ASSERT(!m_transactions[m_next_transaction_id]); for (int i = (m_next_transaction_id + 1) % max_transactions; i != m_oldest_transaction_id; i = (i + 1) % max_transactions) { TORRENT_ASSERT(!m_transactions[i]); } } #endif bool rpc_manager::incoming(msg const& m) { INVARIANT_CHECK; if (m_destructing) return false; if (m.reply) { // if we don't have the transaction id in our // request list, ignore the packet if (m.transaction_id.size() < 2) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Reply with invalid transaction id size: " << m.transaction_id.size() << " from " << m.addr; #endif msg reply; reply.reply = true; reply.message_id = messages::error; reply.error_code = 203; // Protocol error reply.error_msg = "reply with invalid transaction id, size " + boost::lexical_cast<std::string>(m.transaction_id.size()); reply.addr = m.addr; reply.transaction_id = ""; m_send(reply); return false; } std::string::const_iterator i = m.transaction_id.begin(); int tid = io::read_uint16(i); if (tid >= (int)m_transactions.size() || tid < 0) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Reply with invalid transaction id: " << tid << " from " << m.addr; #endif msg reply; reply.reply = true; reply.message_id = messages::error; reply.error_code = 203; // Protocol error reply.error_msg = "reply with invalid transaction id"; reply.addr = m.addr; reply.transaction_id = ""; m_send(reply); return false; } observer_ptr o = m_transactions[tid]; if (!o) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Reply with unknown transaction id: " << tid << " from " << m.addr << " (possibly timed out)"; #endif return false; } if (m.addr != o->target_addr) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Reply with incorrect address and valid transaction id: " << tid << " from " << m.addr; #endif return false; } #ifdef TORRENT_DHT_VERBOSE_LOGGING std::ofstream reply_stats("libtorrent_logs/round_trip_ms.log", std::ios::app); reply_stats << m.addr << "\t" << total_milliseconds(time_now() - o->sent) << std::endl; #endif o->reply(m); m_transactions[tid] = 0; if (m.piggy_backed_ping) { // there is a ping request piggy // backed in this reply msg ph; ph.message_id = messages::ping; ph.transaction_id = m.ping_transaction_id; ph.addr = m.addr; ph.reply = true; reply(ph); } return m_table.node_seen(m.id, m.addr); } else { TORRENT_ASSERT(m.message_id != messages::error); // this is an incoming request m_incoming(m); } return false; } time_duration rpc_manager::tick() { INVARIANT_CHECK; const int timeout_ms = 10 * 1000; // look for observers that has timed out if (m_next_transaction_id == m_oldest_transaction_id) return milliseconds(timeout_ms); std::vector<observer_ptr > timeouts; for (;m_next_transaction_id != m_oldest_transaction_id; m_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions) { TORRENT_ASSERT(m_oldest_transaction_id >= 0); TORRENT_ASSERT(m_oldest_transaction_id < max_transactions); observer_ptr o = m_transactions[m_oldest_transaction_id]; if (!o) continue; time_duration diff = o->sent + milliseconds(timeout_ms) - time_now(); if (diff > seconds(0)) { if (diff < seconds(1)) return seconds(1); return diff; } try { m_transactions[m_oldest_transaction_id] = 0; timeouts.push_back(o); } catch (std::exception) {} } std::for_each(timeouts.begin(), timeouts.end(), bind(&observer::timeout, _1)); timeouts.clear(); // clear the aborted transactions, will likely // generate new requests. We need to swap, since the // destrutors may add more observers to the m_aborted_transactions std::vector<observer_ptr >().swap(m_aborted_transactions); return milliseconds(timeout_ms); } unsigned int rpc_manager::new_transaction_id(observer_ptr o) { INVARIANT_CHECK; unsigned int tid = m_next_transaction_id; m_next_transaction_id = (m_next_transaction_id + 1) % max_transactions; if (m_transactions[m_next_transaction_id]) { // moving the observer into the set of aborted transactions // it will prevent it from spawning new requests right now, // since that would break the invariant m_aborted_transactions.push_back(m_transactions[m_next_transaction_id]); m_transactions[m_next_transaction_id] = 0; TORRENT_ASSERT(m_oldest_transaction_id == m_next_transaction_id); } TORRENT_ASSERT(!m_transactions[tid]); m_transactions[tid] = o; if (m_oldest_transaction_id == m_next_transaction_id) { m_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "WARNING: transaction limit reached! Too many concurrent" " messages! limit: " << (int)max_transactions; #endif update_oldest_transaction_id(); } return tid; } void rpc_manager::update_oldest_transaction_id() { INVARIANT_CHECK; TORRENT_ASSERT(m_oldest_transaction_id != m_next_transaction_id); while (!m_transactions[m_oldest_transaction_id]) { m_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions; if (m_oldest_transaction_id == m_next_transaction_id) break; } } void rpc_manager::invoke(int message_id, udp::endpoint target_addr , observer_ptr o) { INVARIANT_CHECK; if (m_destructing) { o->abort(); return; } msg m; m.message_id = message_id; m.reply = false; m.id = m_our_id; m.addr = target_addr; TORRENT_ASSERT(!m_transactions[m_next_transaction_id]); #ifndef NDEBUG int potential_new_id = m_next_transaction_id; #endif try { m.transaction_id.clear(); std::back_insert_iterator<std::string> out(m.transaction_id); io::write_uint16(m_next_transaction_id, out); o->send(m); o->sent = time_now(); o->target_addr = target_addr; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Invoking " << messages::ids[message_id] << " -> " << target_addr; #endif m_send(m); new_transaction_id(o); } catch (std::exception& e) { // m_send may fail with "no route to host" TORRENT_ASSERT(potential_new_id == m_next_transaction_id); o->abort(); } } void rpc_manager::reply(msg& m) { INVARIANT_CHECK; if (m_destructing) return; TORRENT_ASSERT(m.reply); m.piggy_backed_ping = false; m.id = m_our_id; m_send(m); } void rpc_manager::reply_with_ping(msg& m) { INVARIANT_CHECK; if (m_destructing) return; TORRENT_ASSERT(m.reply); m.piggy_backed_ping = true; m.id = m_our_id; m.ping_transaction_id.clear(); std::back_insert_iterator<std::string> out(m.ping_transaction_id); io::write_uint16(m_next_transaction_id, out); observer_ptr o(new (allocator().malloc()) null_observer(allocator())); TORRENT_ASSERT(!m_transactions[m_next_transaction_id]); o->sent = time_now(); o->target_addr = m.addr; m_send(m); new_transaction_id(o); } } } // namespace libtorrent::dht <commit_msg>updated dht verbose logging to try to catch #176<commit_after>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include "libtorrent/socket.hpp" #include <boost/bind.hpp> #include <boost/mpl/max_element.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/sizeof.hpp> #include <boost/mpl/transform_view.hpp> #include <boost/mpl/deref.hpp> #include <boost/lexical_cast.hpp> #include <libtorrent/io.hpp> #include <libtorrent/invariant_check.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/logging.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/find_data.hpp> #include <libtorrent/kademlia/closest_nodes.hpp> #include <libtorrent/kademlia/refresh.hpp> #include <libtorrent/kademlia/node.hpp> #include <libtorrent/kademlia/observer.hpp> #include <libtorrent/hasher.hpp> #include <fstream> using boost::shared_ptr; using boost::bind; namespace libtorrent { namespace dht { namespace io = libtorrent::detail; namespace mpl = boost::mpl; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DEFINE_LOG(rpc) #endif void intrusive_ptr_add_ref(observer const* o) { TORRENT_ASSERT(o->m_refs >= 0); TORRENT_ASSERT(o != 0); ++o->m_refs; } void intrusive_ptr_release(observer const* o) { TORRENT_ASSERT(o->m_refs > 0); TORRENT_ASSERT(o != 0); if (--o->m_refs == 0) { boost::pool<>& p = o->pool_allocator; o->~observer(); p.free(const_cast<observer*>(o)); } } node_id generate_id(); typedef mpl::vector< closest_nodes_observer , find_data_observer , announce_observer , get_peers_observer , refresh_observer , ping_observer , null_observer > observer_types; typedef mpl::max_element< mpl::transform_view<observer_types, mpl::sizeof_<mpl::_1> > >::type max_observer_type_iter; rpc_manager::rpc_manager(fun const& f, node_id const& our_id , routing_table& table, send_fun const& sf) : m_pool_allocator(sizeof(mpl::deref<max_observer_type_iter::base>::type)) , m_next_transaction_id(rand() % max_transactions) , m_oldest_transaction_id(m_next_transaction_id) , m_incoming(f) , m_send(sf) , m_our_id(our_id) , m_table(table) , m_timer(time_now()) , m_random_number(generate_id()) , m_destructing(false) { std::srand(time(0)); } rpc_manager::~rpc_manager() { m_destructing = true; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Destructing"; #endif std::for_each(m_aborted_transactions.begin(), m_aborted_transactions.end() , bind(&observer::abort, _1)); for (transactions_t::iterator i = m_transactions.begin() , end(m_transactions.end()); i != end; ++i) { if (*i) (*i)->abort(); } } #ifndef NDEBUG void rpc_manager::check_invariant() const { TORRENT_ASSERT(m_oldest_transaction_id >= 0); TORRENT_ASSERT(m_oldest_transaction_id < max_transactions); TORRENT_ASSERT(m_next_transaction_id >= 0); TORRENT_ASSERT(m_next_transaction_id < max_transactions); TORRENT_ASSERT(!m_transactions[m_next_transaction_id]); for (int i = (m_next_transaction_id + 1) % max_transactions; i != m_oldest_transaction_id; i = (i + 1) % max_transactions) { TORRENT_ASSERT(!m_transactions[i]); } } #endif bool rpc_manager::incoming(msg const& m) { INVARIANT_CHECK; if (m_destructing) return false; if (m.reply) { // if we don't have the transaction id in our // request list, ignore the packet if (m.transaction_id.size() < 2) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Reply with invalid transaction id size: " << m.transaction_id.size() << " from " << m.addr; #endif msg reply; reply.reply = true; reply.message_id = messages::error; reply.error_code = 203; // Protocol error reply.error_msg = "reply with invalid transaction id, size " + boost::lexical_cast<std::string>(m.transaction_id.size()); reply.addr = m.addr; reply.transaction_id = ""; m_send(reply); return false; } std::string::const_iterator i = m.transaction_id.begin(); int tid = io::read_uint16(i); if (tid >= (int)m_transactions.size() || tid < 0) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Reply with invalid transaction id: " << tid << " from " << m.addr; #endif msg reply; reply.reply = true; reply.message_id = messages::error; reply.error_code = 203; // Protocol error reply.error_msg = "reply with invalid transaction id"; reply.addr = m.addr; reply.transaction_id = ""; m_send(reply); return false; } observer_ptr o = m_transactions[tid]; if (!o) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Reply with unknown transaction id: " << tid << " from " << m.addr << " (possibly timed out)"; #endif return false; } if (m.addr != o->target_addr) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Reply with incorrect address and valid transaction id: " << tid << " from " << m.addr; #endif return false; } #ifdef TORRENT_DHT_VERBOSE_LOGGING std::ofstream reply_stats("libtorrent_logs/round_trip_ms.log", std::ios::app); reply_stats << m.addr << "\t" << total_milliseconds(time_now() - o->sent) << std::endl; #endif #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Reply with transaction id: " << tid << " from " << m.addr; #endif o->reply(m); m_transactions[tid] = 0; if (m.piggy_backed_ping) { // there is a ping request piggy // backed in this reply msg ph; ph.message_id = messages::ping; ph.transaction_id = m.ping_transaction_id; ph.addr = m.addr; ph.reply = true; reply(ph); } return m_table.node_seen(m.id, m.addr); } else { TORRENT_ASSERT(m.message_id != messages::error); // this is an incoming request m_incoming(m); } return false; } time_duration rpc_manager::tick() { INVARIANT_CHECK; const int timeout_ms = 10 * 1000; // look for observers that has timed out if (m_next_transaction_id == m_oldest_transaction_id) return milliseconds(timeout_ms); std::vector<observer_ptr > timeouts; for (;m_next_transaction_id != m_oldest_transaction_id; m_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions) { TORRENT_ASSERT(m_oldest_transaction_id >= 0); TORRENT_ASSERT(m_oldest_transaction_id < max_transactions); observer_ptr o = m_transactions[m_oldest_transaction_id]; if (!o) continue; time_duration diff = o->sent + milliseconds(timeout_ms) - time_now(); if (diff > seconds(0)) { if (diff < seconds(1)) return seconds(1); return diff; } try { m_transactions[m_oldest_transaction_id] = 0; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Timing out transaction id: " << m_oldest_transaction_id << " from " << o->target_addr; #endif timeouts.push_back(o); } catch (std::exception) {} } std::for_each(timeouts.begin(), timeouts.end(), bind(&observer::timeout, _1)); timeouts.clear(); // clear the aborted transactions, will likely // generate new requests. We need to swap, since the // destrutors may add more observers to the m_aborted_transactions std::vector<observer_ptr >().swap(m_aborted_transactions); return milliseconds(timeout_ms); } unsigned int rpc_manager::new_transaction_id(observer_ptr o) { INVARIANT_CHECK; unsigned int tid = m_next_transaction_id; m_next_transaction_id = (m_next_transaction_id + 1) % max_transactions; if (m_transactions[m_next_transaction_id]) { // moving the observer into the set of aborted transactions // it will prevent it from spawning new requests right now, // since that would break the invariant observer_ptr o = m_transactions[m_next_transaction_id]; m_aborted_transactions.push_back(o); #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "[new_transaction_id] Aborting message with transaction id: " << m_next_transaction_id << " sent to " << o->target_addr << " at " << o->sent; #endif m_transactions[m_next_transaction_id] = 0; TORRENT_ASSERT(m_oldest_transaction_id == m_next_transaction_id); } TORRENT_ASSERT(!m_transactions[tid]); m_transactions[tid] = o; if (m_oldest_transaction_id == m_next_transaction_id) { m_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "WARNING: transaction limit reached! Too many concurrent" " messages! limit: " << (int)max_transactions; #endif update_oldest_transaction_id(); } return tid; } void rpc_manager::update_oldest_transaction_id() { INVARIANT_CHECK; TORRENT_ASSERT(m_oldest_transaction_id != m_next_transaction_id); while (!m_transactions[m_oldest_transaction_id]) { m_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions; if (m_oldest_transaction_id == m_next_transaction_id) break; } } void rpc_manager::invoke(int message_id, udp::endpoint target_addr , observer_ptr o) { INVARIANT_CHECK; if (m_destructing) { o->abort(); return; } msg m; m.message_id = message_id; m.reply = false; m.id = m_our_id; m.addr = target_addr; TORRENT_ASSERT(!m_transactions[m_next_transaction_id]); #ifndef NDEBUG int potential_new_id = m_next_transaction_id; #endif try { m.transaction_id.clear(); std::back_insert_iterator<std::string> out(m.transaction_id); io::write_uint16(m_next_transaction_id, out); o->send(m); o->sent = time_now(); o->target_addr = target_addr; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(rpc) << "Invoking " << messages::ids[message_id] << " -> " << target_addr; #endif m_send(m); new_transaction_id(o); } catch (std::exception& e) { // m_send may fail with "no route to host" TORRENT_ASSERT(potential_new_id == m_next_transaction_id); o->abort(); } } void rpc_manager::reply(msg& m) { INVARIANT_CHECK; if (m_destructing) return; TORRENT_ASSERT(m.reply); m.piggy_backed_ping = false; m.id = m_our_id; m_send(m); } void rpc_manager::reply_with_ping(msg& m) { INVARIANT_CHECK; if (m_destructing) return; TORRENT_ASSERT(m.reply); m.piggy_backed_ping = true; m.id = m_our_id; m.ping_transaction_id.clear(); std::back_insert_iterator<std::string> out(m.ping_transaction_id); io::write_uint16(m_next_transaction_id, out); observer_ptr o(new (allocator().malloc()) null_observer(allocator())); TORRENT_ASSERT(!m_transactions[m_next_transaction_id]); o->sent = time_now(); o->target_addr = m.addr; m_send(m); new_transaction_id(o); } } } // namespace libtorrent::dht <|endoftext|>
<commit_before>/* * Copyright (c) 2014, Julien Bernard * * 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 <mm/hydraulic_erosion.h> namespace mm { heightmap hydraulic_erosion::operator()(const heightmap& src) const { heightmap water_map(size_only, src); heightmap water_diff(size_only, src); heightmap material_map(size_only, src); heightmap material_diff(size_only, src); heightmap map(src); double d[3][3]; for (size_type k = 0; k < m_iterations; ++k) { // 1. appearance of new water for (size_type x = 0; x < water_map.width(); ++x) { for (size_type y = 0; y < water_map.height(); ++y) { water_map(x, y) += m_rain_amount; } } // 2. water erosion of the terrain for (size_type x = 0; x < water_map.width(); ++x) { for (size_type y = 0; y < water_map.height(); ++y) { double material = m_solubility * water_map(x, y); map(x, y) -= material; material_map(x, y) += material; } } // 3. transportation of water for (size_type x = 1; x < water_diff.width() - 1; ++x) { for (size_type y = 1; y < water_diff.height() - 1; ++y) { water_diff(x, y) = 0.0; } } for (size_type x = 1; x < material_diff.width() - 1; ++x) { for (size_type y = 1; y < material_diff.height() - 1; ++y) { material_diff(x, y) = 0.0; } } for (size_type x = 1; x < map.width() - 1; ++x) { for (size_type y = 1; y < map.height() - 1; ++y) { double d_total = 0.0; double a_total = 0.0; double alt = map(x, y) + water_map(x, y); size_type n = 0; for (int i = -1; i <= 1; ++i) { for (int j = -1; j <= 1; ++j) { double alt_local = map(x+i, y+j) + water_map(x+i, y+j); double diff = alt - alt_local; d[1+i][1+j] = diff; if (diff > 0.0) { d_total += diff; a_total += alt_local; n++; } } } if (n == 0) { continue; } double a_avg = a_total / n; double da = std::min(water_map(x, y), alt - a_avg); for (int i = -1; i <= 1; ++i) { for (int j = -1; j <= 1; ++j) { double diff = d[1+i][1+j]; if (diff > 0.0) { double dw = da * (diff / d_total); water_diff(x+i, y+j) += dw; water_diff(x, y) -= dw; double dm = material_map(x, y) * (dw / water_map(x, y)); material_diff(x+i, y+j) += dm; material_diff(x, y) -= dm; } } } } } for (size_type x = 1; x < water_map.width() - 1; ++x) { for (size_type y = 1; y < water_map.height() - 1; ++y) { water_map(x, y) += water_diff(x, y); } } for (size_type x = 1; x < material_map.width() - 1; ++x) { for (size_type y = 1; y < material_map.height() - 1; ++y) { material_map(x, y) += material_diff(x, y); } } // 4. evaporation of water for (size_type x = 0; x < water_map.width(); ++x) { for (size_type y = 0; y < water_map.height(); ++y) { double water = water_map(x, y) * (1 - m_evaporation); water_map(x, y) = water; double m_max = m_capacity * water; double dm = std::max(double(0), material_map(x, y) - m_max); material_map(x, y) -= dm; map(x, y) += dm; } } } return std::move(map); } } <commit_msg>missing include<commit_after>/* * Copyright (c) 2014, Julien Bernard * * 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 <mm/hydraulic_erosion.h> #include <algorithm> namespace mm { heightmap hydraulic_erosion::operator()(const heightmap& src) const { heightmap water_map(size_only, src); heightmap water_diff(size_only, src); heightmap material_map(size_only, src); heightmap material_diff(size_only, src); heightmap map(src); double d[3][3]; for (size_type k = 0; k < m_iterations; ++k) { // 1. appearance of new water for (size_type x = 0; x < water_map.width(); ++x) { for (size_type y = 0; y < water_map.height(); ++y) { water_map(x, y) += m_rain_amount; } } // 2. water erosion of the terrain for (size_type x = 0; x < water_map.width(); ++x) { for (size_type y = 0; y < water_map.height(); ++y) { double material = m_solubility * water_map(x, y); map(x, y) -= material; material_map(x, y) += material; } } // 3. transportation of water for (size_type x = 1; x < water_diff.width() - 1; ++x) { for (size_type y = 1; y < water_diff.height() - 1; ++y) { water_diff(x, y) = 0.0; } } for (size_type x = 1; x < material_diff.width() - 1; ++x) { for (size_type y = 1; y < material_diff.height() - 1; ++y) { material_diff(x, y) = 0.0; } } for (size_type x = 1; x < map.width() - 1; ++x) { for (size_type y = 1; y < map.height() - 1; ++y) { double d_total = 0.0; double a_total = 0.0; double alt = map(x, y) + water_map(x, y); size_type n = 0; for (int i = -1; i <= 1; ++i) { for (int j = -1; j <= 1; ++j) { double alt_local = map(x+i, y+j) + water_map(x+i, y+j); double diff = alt - alt_local; d[1+i][1+j] = diff; if (diff > 0.0) { d_total += diff; a_total += alt_local; n++; } } } if (n == 0) { continue; } double a_avg = a_total / n; double da = std::min(water_map(x, y), alt - a_avg); for (int i = -1; i <= 1; ++i) { for (int j = -1; j <= 1; ++j) { double diff = d[1+i][1+j]; if (diff > 0.0) { double dw = da * (diff / d_total); water_diff(x+i, y+j) += dw; water_diff(x, y) -= dw; double dm = material_map(x, y) * (dw / water_map(x, y)); material_diff(x+i, y+j) += dm; material_diff(x, y) -= dm; } } } } } for (size_type x = 1; x < water_map.width() - 1; ++x) { for (size_type y = 1; y < water_map.height() - 1; ++y) { water_map(x, y) += water_diff(x, y); } } for (size_type x = 1; x < material_map.width() - 1; ++x) { for (size_type y = 1; y < material_map.height() - 1; ++y) { material_map(x, y) += material_diff(x, y); } } // 4. evaporation of water for (size_type x = 0; x < water_map.width(); ++x) { for (size_type y = 0; y < water_map.height(); ++y) { double water = water_map(x, y) * (1 - m_evaporation); water_map(x, y) = water; double m_max = m_capacity * water; double dm = std::max(double(0), material_map(x, y) - m_max); material_map(x, y) -= dm; map(x, y) += dm; } } } return std::move(map); } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// /// \file main.cpp /// \brief Main file for testing different system classes /// and functionality. /// Author: Andrew Watson /// Created: 1/22/13 /// Email: watsontandrew@gmail.com /// //////////////////////////////////////////////////////////////////////////////// #include <hokuyo.hpp> #include <time.h> #include <wiringPi.h> //wiringpi testing //Webserver testing #include <ctime> #include <iostream> #include <string> #include <boost/asio.hpp> //end webserver testing //#define TESTHOKUYO #ifdef TESTHOKUYO class ExampleLaserCallback : public Laser::Callback { public: ExampleLaserCallback(){} ~ExampleLaserCallback(){} virtual void ProcessLaserData(const std::vector<CvPoint3D64f>& scan, const time_t& timestamp) { mLaserScan = scan; mTimeStamp = timestamp; } std::vector<CvPoint3D64f> mLaserScan; time_t mTimeStamp; }; double MiddleScanDistanceInches (const std::vector<CvPoint3D64f>& scan) { if(scan.size() > 0) return scan.at(scan.size() / 2.).x * 1000. / 25.4; else return 0; } int main() { Laser::Hokuyo* laser = new Laser::Hokuyo(); ExampleLaserCallback callback; laser->RegisterCallback(&callback); if(laser->Initialize()) { if(laser->StartCaptureThread()) { while (1) { std::cout << MiddleScanDistanceInches(callback.mLaserScan) << std::endl; boost::this_thread::sleep(boost::posix_time::millisec(10)); } laser->Shutdown(); delete laser; } } return 0; } #endif //#define TESTDYNAMIXEL #ifdef TESTDYNAMIXEL int main() { int x = 1234; char bytes[sizeof x]; std::copy(static_cast<const char*>(static_cast<const void*>(&x)), static_cast<const char*>(static_cast<const void*>(&x)) + sizeof x, bytes); char a = bytes[0]; char b = bytes[1]; return 0; } #endif //#define TESTTIMING #ifdef TESTTIMING timespec diff(timespec start, timespec end); int main() { // clockid_t types[] = {CLOCK_REALTIME, CLOCK_MONOTONIC, // CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, // (clockid_t) - 1}; // struct timespec spec; // for (int i = 0; types[i] != (clockid_t) - 1; i++) // { // if(clock_getres(types[i], &spec) != 0) // { // std::cout << "Timer " << types[i] << " not supported" << std::endl; // } // else // { // std::cout << "Timer: " << i << " Seconds: " << spec.tv_sec // << " Nanos: " << spec.tv_nsec << std::endl; // } // } timespec t1, t2; clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t1); clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t2); while(1) { if(diff(t1, t2).tv_nsec > 2000000) { std::cout << "1 Sec Elapsed" << std::endl; clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t1); clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t2); } else { clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t2); } std::cout << diff(t1, t2).tv_nsec << std::endl; nanosleep((struct timespec[]){{0, 100000000}}, NULL); } return 0; } timespec diff(timespec start, timespec end) { timespec temp; if((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec - start.tv_sec - 1; temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec; } else { temp.tv_sec = end.tv_sec - start.tv_sec; temp.tv_nsec = end.tv_nsec - start.tv_nsec; } return temp; } #endif #define TESTSERVER #ifdef TESTSERVER //Requires SUDO to run in order to bind to port using boost::asio::ip::tcp; std::string make_daytime_string() { using namespace std; // For time_t, time and ctime; time_t now = time(0); return ctime(&now); } int main() { try { boost::asio::io_service io_service; tcp::endpoint endpoint(tcp::v4(), 13); tcp::acceptor acceptor(io_service, endpoint); for (;;) { tcp::iostream stream; acceptor.accept(*stream.rdbuf()); stream << make_daytime_string(); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; } #endif //#define TESTISR #ifdef TESTISR #define BUTTON_PIN 0 volatile int eventCounter = 0; void myInterrupt(void) {eventCounter++;} int main() { if (wiringPiSetup () < 0) { fprintf (stderr, "Unable to setup wiringPi: %s\n", strerror (errno)); return 1; } // set Pin 17/0 generate an interrupt on high-to-low transitions // and attach myInterrupt() to the interrupt if ( wiringPiISR (BUTTON_PIN, INT_EDGE_FALLING, &myInterrupt) < 0 ) { fprintf (stderr, "Unable to setup ISR: %s\n", strerror (errno)); return 1; } // display counter value every second. while ( 1 ) { printf( "%d\n", eventCounter ); eventCounter = 0; delay( 1000 ); // wait 1 second } return 0; } #endif /** End of File */ <commit_msg>Fixed the time example<commit_after>//////////////////////////////////////////////////////////////////////////////// /// /// \file main.cpp /// \brief Main file for testing different system classes /// and functionality. /// Author: Andrew Watson /// Created: 1/22/13 /// Email: watsontandrew@gmail.com /// //////////////////////////////////////////////////////////////////////////////// #include <hokuyo.hpp> #include <time.h> #include <wiringPi.h> //wiringpi testing //Webserver testing #include <ctime> #include <iostream> #include <string> #include <boost/asio.hpp> //end webserver testing //#define TESTHOKUYO #ifdef TESTHOKUYO class ExampleLaserCallback : public Laser::Callback { public: ExampleLaserCallback(){} ~ExampleLaserCallback(){} virtual void ProcessLaserData(const std::vector<CvPoint3D64f>& scan, const time_t& timestamp) { mLaserScan = scan; mTimeStamp = timestamp; } std::vector<CvPoint3D64f> mLaserScan; time_t mTimeStamp; }; double MiddleScanDistanceInches (const std::vector<CvPoint3D64f>& scan) { if(scan.size() > 0) return scan.at(scan.size() / 2.).x * 1000. / 25.4; else return 0; } int main() { Laser::Hokuyo* laser = new Laser::Hokuyo(); ExampleLaserCallback callback; laser->RegisterCallback(&callback); if(laser->Initialize()) { if(laser->StartCaptureThread()) { while (1) { std::cout << MiddleScanDistanceInches(callback.mLaserScan) << std::endl; boost::this_thread::sleep(boost::posix_time::millisec(10)); } laser->Shutdown(); delete laser; } } return 0; } #endif //#define TESTDYNAMIXEL #ifdef TESTDYNAMIXEL int main() { int x = 1234; char bytes[sizeof x]; std::copy(static_cast<const char*>(static_cast<const void*>(&x)), static_cast<const char*>(static_cast<const void*>(&x)) + sizeof x, bytes); char a = bytes[0]; char b = bytes[1]; return 0; } #endif #define TESTTIMING #ifdef TESTTIMING timespec diff(timespec start, timespec end); int main() { // clockid_t types[] = {CLOCK_REALTIME, CLOCK_MONOTONIC, // CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, // (clockid_t) - 1}; // struct timespec spec; // for (int i = 0; types[i] != (clockid_t) - 1; i++) // { // if(clock_getres(types[i], &spec) != 0) // { // std::cout << "Timer " << types[i] << " not supported" << std::endl; // } // else // { // std::cout << "Timer: " << i << " Seconds: " << spec.tv_sec // << " Nanos: " << spec.tv_nsec << std::endl; // } // } timespec t1, t2; clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t1); clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t2); unsigned int i = 0; while(1) { if(diff(t1, t2).tv_nsec > 1000000000L) { i++; std::cout << i <<" Sec Elapsed" << std::endl; clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t1); clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t2); } else { clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t2); } // std::cout << diff(t1, t2).tv_nsec << std::endl; // nanosleep((struct timespec[]){{0, 100000000}}, NULL); } return 0; } timespec diff(timespec start, timespec end) { timespec temp; if((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec - start.tv_sec - 1; temp.tv_nsec = 1000000000L + end.tv_nsec - start.tv_nsec; } else { temp.tv_sec = end.tv_sec - start.tv_sec; temp.tv_nsec = end.tv_nsec - start.tv_nsec; } return temp; } #endif //#define TESTSERVER #ifdef TESTSERVER //Requires SUDO to run in order to bind to port using boost::asio::ip::tcp; std::string make_daytime_string() { using namespace std; // For time_t, time and ctime; time_t now = time(0); return ctime(&now); } int main() { try { boost::asio::io_service io_service; tcp::endpoint endpoint(tcp::v4(), 13); tcp::acceptor acceptor(io_service, endpoint); for (;;) { tcp::iostream stream; acceptor.accept(*stream.rdbuf()); stream << make_daytime_string(); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; } #endif //#define TESTISR #ifdef TESTISR #define BUTTON_PIN 0 volatile int eventCounter = 0; void myInterrupt(void) {eventCounter++;} int main() { if (wiringPiSetup () < 0) { fprintf (stderr, "Unable to setup wiringPi: %s\n", strerror (errno)); return 1; } // set Pin 17/0 generate an interrupt on high-to-low transitions // and attach myInterrupt() to the interrupt if ( wiringPiISR (BUTTON_PIN, INT_EDGE_FALLING, &myInterrupt) < 0 ) { fprintf (stderr, "Unable to setup ISR: %s\n", strerror (errno)); return 1; } // display counter value every second. while ( 1 ) { printf( "%d\n", eventCounter ); eventCounter = 0; delay( 1000 ); // wait 1 second } return 0; } #endif /** End of File */ <|endoftext|>
<commit_before>#include <validation.hpp> #include <kdb> #include <iostream> #include <string> using namespace std; using namespace kdb; ValidationCommand::ValidationCommand() {} int ValidationCommand::execute(int argc, char** argv) { string prog = argv[0]; string command = argv[1]; if (argc != 6) { cerr << "Usage: " << prog << " " << command << " <key-name> <value> <validation-regex> <validation-message>" << endl; return 1; } string keyname = argv[2]; KeySet conf; Key parentKey(keyname, KEY_END); kdb.get(conf, parentKey); Key k = conf.lookup(keyname); if (!k) k = Key(keyname, KEY_END); if (!k.isValid()) { cout << "Could not create key" << endl; return 1; } string value = argv[3]; string validationregex = argv[4]; string validationmessage = argv[5]; k.setString (value); k.setMeta<string> ("validation/regex", validationregex); k.setMeta<string> ("validation/message", validationmessage); kdb.set(conf,parentKey); return 0; } ValidationCommand::~ValidationCommand() {} <commit_msg>fixed validation-set for new key<commit_after>#include <validation.hpp> #include <kdb> #include <iostream> #include <string> using namespace std; using namespace kdb; ValidationCommand::ValidationCommand() {} int ValidationCommand::execute(int argc, char** argv) { string prog = argv[0]; string command = argv[1]; if (argc != 6) { cerr << "Usage: " << prog << " " << command << " <key-name> <value> <validation-regex> <validation-message>" << endl; return 1; } string keyname = argv[2]; KeySet conf; Key parentKey(keyname, KEY_END); kdb.get(conf, parentKey); Key k = conf.lookup(keyname); if (!k) { k = Key(keyname, KEY_END); conf.append (k); } if (!k.isValid()) { cout << "Could not create key" << endl; return 1; } string value = argv[3]; string validationregex = argv[4]; string validationmessage = argv[5]; k.setString (value); k.setMeta<string> ("validation/regex", validationregex); k.setMeta<string> ("validation/message", validationmessage); kdb.set(conf,parentKey); return 0; } ValidationCommand::~ValidationCommand() {} <|endoftext|>