text
stringlengths
54
60.6k
<commit_before>68abafd4-2e4d-11e5-9284-b827eb9e62be<commit_msg>68b0b9d4-2e4d-11e5-9284-b827eb9e62be<commit_after>68b0b9d4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f0407906-2e4e-11e5-9284-b827eb9e62be<commit_msg>f0456c40-2e4e-11e5-9284-b827eb9e62be<commit_after>f0456c40-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/****************** <SNX heading BEGIN do not edit this line> ***************** * * sonix * * Original Authors: * Kevin Meinert, Carolina Cruz-Neira * ****************** <SNX heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2007 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <snx/snxConfig.h> #include <stdlib.h> #include <gmtl/Math.h> #include <gmtl/Vec.h> #include <gmtl/MatrixOps.h> #include <gmtl/VecOps.h> #include <gmtl/Xforms.h> #include <vpr/Util/Assert.h> #include <vpr/Util/Debug.h> #include <snx/Util/Debug.h> #include <snx/SoundFactory.h> #include <snx/sonix.h> namespace snx { vprSingletonImp(sonix); // Destructor. sonix::~sonix() { // release the implementation if (mImplementation != NULL) { // unload all sound data mImplementation->unbindAll(); // shutdown old api if exists mImplementation->shutdownAPI(); delete mImplementation; mImplementation = NULL; } } /** * @input alias of the sound to trigger, and number of times to play, -1 to * repeat infinately, 1 (single shot) is default. * @preconditions alias does not have to be associated with a loaded sound. * @postconditions if it is, then the loaded sound is triggered. if it isn't * then nothing happens. * @semantics Triggers a sound */ void sonix::trigger( const std::string& alias, const int& repeat ) { this->impl().trigger( alias, repeat ); } bool sonix::isPlaying( const std::string& alias ) { return this->impl().isPlaying( alias ); } void sonix::setRetriggerable( const std::string& alias, bool onOff ) { this->impl().setRetriggerable( alias, onOff ); } bool sonix::isRetriggerable( const std::string& alias ) { return this->impl().isRetriggerable( alias ); } /** * @semantics stop the sound * @input alias of the sound to be stopped */ void sonix::stop( const std::string& alias ) { this->impl().stop( alias ); } void sonix::pause( const std::string& alias ) { this->impl().pause( alias ); } void sonix::unpause(const std::string& alias) { this->impl().unpause( alias ); } bool sonix::isPaused(const std::string& alias) { return this->impl().isPaused( alias ); } void sonix::setAmbient(const std::string& alias, const bool ambient) { this->impl().setAmbient(alias, ambient); } bool sonix::isAmbient(const std::string& alias) { return this->impl().isAmbient( alias ); } void sonix::setPitchBend(const std::string& alias, float amount) { this->impl().setPitchBend( alias, amount ); } void sonix::setVolume(const std::string& alias, float amount) { this->impl().setVolume( alias, amount ); } void sonix::setCutoff(const std::string& alias, float amount) { this->impl().setCutoff( alias, amount ); } void sonix::setPosition(const std::string& alias, const float& x, const float& y, const float& z) { this->impl().setPosition( alias, x, y, z ); } void sonix::getPosition(const std::string& alias, float& x, float& y, float& z) { this->impl().getPosition( alias, x, y, z ); } void sonix::setListenerPosition(const gmtl::Matrix44f& mat) { this->impl().setListenerPosition( mat ); } void sonix::getListenerPosition(gmtl::Matrix44f& mat) { this->impl().getListenerPosition( mat ); } /** * change the underlying sound API to something else. * @input usually a name of a valid registered sound API implementation * @preconditions sound implementation should be registered * @postconditions underlying API is changed to the requested API name. if * apiName's implementation is not registered, then underlying * API is changed to the stub version. * @semantics function is safe: always returns a valid implementation. * @time O(1) * @output a valid sound API. if apiName is invalid, then a stub * implementation is returned. */ void sonix::changeAPI(const std::string& apiName) { snx::ISoundImplementation& oldImpl = this->impl(); vprASSERT(&oldImpl != NULL && "this->impl() should ensure that oldImpl is non-NULL"); // change the current api to the newly requested one. snx::SoundFactory::instance()->createImplementation(apiName, mImplementation); vprDEBUG(snxDBG, vprDBG_CRITICAL_LVL) << "Changing sound API from '" << oldImpl.name() << "' to '" << mImplementation->name() << "'\n" << vprDEBUG_FLUSH; // copy sound state from old to current (doesn't do binding yet) snx::SoundImplementation* si = dynamic_cast<snx::SoundImplementation*>(mImplementation); vprASSERT(NULL != si && "implementation is not of type SoundImplementation, cast fails"); snx::SoundImplementation& old_si = dynamic_cast<snx::SoundImplementation&>(oldImpl); vprASSERT(NULL != &old_si && "implementation is not of type SoundImplementation, cast fails"); si->copy( old_si ); // unload all sound data oldImpl.unbindAll(); // shutdown old api if exists oldImpl.shutdownAPI(); // delete old api, we're done with it... delete &oldImpl; // startup the new API // if it fails to start then we revert back to stub if ( ! mImplementation->startAPI() ) { vprDEBUG(snxDBG, vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED, "ERROR:") << " Failed to start new API--" << "changing back to Stub\n" << vprDEBUG_FLUSH; changeAPI("stub"); } // load all sound data mImplementation->bindAll(); } void sonix::configure(const snx::SoundAPIInfo& sai) { this->impl().configure( sai ); } /** * configure/reconfigure a sound * configure: associate a name (alias) to the description if not already done * reconfigure: change properties of the sound to the descriptino provided. * @preconditions provide an alias and a SoundInfo which describes the sound * @postconditions alias will point to loaded sound data * @semantics associate an alias to sound data. later this alias can be used * to operate on this sound data. */ void sonix::configure(const std::string& alias, const snx::SoundInfo& description) { this->impl().configure( alias, description ); } void sonix::remove(const std::string alias) { this->impl().remove( alias ); } /** * @semantics call once per sound frame (doesn't have to be same as your * graphics frame) * @input time elapsed since last frame */ void sonix::step(const float& timeElapsed) { this->impl().step( timeElapsed ); } snx::ISoundImplementation& sonix::impl() { if (mImplementation == NULL) { snx::SoundFactory::instance()->createImplementation("stub", mImplementation); mImplementation->startAPI(); mImplementation->bindAll(); } return *mImplementation; } } // namespace snx <commit_msg>The Audiere and OpenAL plug-ins crash on exit (at least on Windows) when they are told to clean up after themselves. By skipping that step in the destructor, we avoid the crash problems, but we of course end up leaking memory. On the bright side, it is memory that gets freed up when the process terminates, an event that occurs shortly after the snx::sonix destructor is invoked.<commit_after>/****************** <SNX heading BEGIN do not edit this line> ***************** * * sonix * * Original Authors: * Kevin Meinert, Carolina Cruz-Neira * ****************** <SNX heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2007 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <snx/snxConfig.h> #include <stdlib.h> #include <gmtl/Math.h> #include <gmtl/Vec.h> #include <gmtl/MatrixOps.h> #include <gmtl/VecOps.h> #include <gmtl/Xforms.h> #include <vpr/Util/Assert.h> #include <vpr/Util/Debug.h> #include <snx/Util/Debug.h> #include <snx/SoundFactory.h> #include <snx/sonix.h> namespace snx { vprSingletonImp(sonix); // Destructor. sonix::~sonix() { // XXX: The Audiere and OpenAL plug-ins exhibit crash-on-exit behavior // when they attempt to clean themselves up. Why this happens is unclear, // but having the following commented out avoids the crash problems. This // definitely needs to be fixed. -PH 9/25/2007 /* // release the implementation if (mImplementation != NULL) { // unload all sound data mImplementation->unbindAll(); // shutdown old api if exists mImplementation->shutdownAPI(); delete mImplementation; mImplementation = NULL; } */ } /** * @input alias of the sound to trigger, and number of times to play, -1 to * repeat infinately, 1 (single shot) is default. * @preconditions alias does not have to be associated with a loaded sound. * @postconditions if it is, then the loaded sound is triggered. if it isn't * then nothing happens. * @semantics Triggers a sound */ void sonix::trigger( const std::string& alias, const int& repeat ) { this->impl().trigger( alias, repeat ); } bool sonix::isPlaying( const std::string& alias ) { return this->impl().isPlaying( alias ); } void sonix::setRetriggerable( const std::string& alias, bool onOff ) { this->impl().setRetriggerable( alias, onOff ); } bool sonix::isRetriggerable( const std::string& alias ) { return this->impl().isRetriggerable( alias ); } /** * @semantics stop the sound * @input alias of the sound to be stopped */ void sonix::stop( const std::string& alias ) { this->impl().stop( alias ); } void sonix::pause( const std::string& alias ) { this->impl().pause( alias ); } void sonix::unpause(const std::string& alias) { this->impl().unpause( alias ); } bool sonix::isPaused(const std::string& alias) { return this->impl().isPaused( alias ); } void sonix::setAmbient(const std::string& alias, const bool ambient) { this->impl().setAmbient(alias, ambient); } bool sonix::isAmbient(const std::string& alias) { return this->impl().isAmbient( alias ); } void sonix::setPitchBend(const std::string& alias, float amount) { this->impl().setPitchBend( alias, amount ); } void sonix::setVolume(const std::string& alias, float amount) { this->impl().setVolume( alias, amount ); } void sonix::setCutoff(const std::string& alias, float amount) { this->impl().setCutoff( alias, amount ); } void sonix::setPosition(const std::string& alias, const float& x, const float& y, const float& z) { this->impl().setPosition( alias, x, y, z ); } void sonix::getPosition(const std::string& alias, float& x, float& y, float& z) { this->impl().getPosition( alias, x, y, z ); } void sonix::setListenerPosition(const gmtl::Matrix44f& mat) { this->impl().setListenerPosition( mat ); } void sonix::getListenerPosition(gmtl::Matrix44f& mat) { this->impl().getListenerPosition( mat ); } /** * change the underlying sound API to something else. * @input usually a name of a valid registered sound API implementation * @preconditions sound implementation should be registered * @postconditions underlying API is changed to the requested API name. if * apiName's implementation is not registered, then underlying * API is changed to the stub version. * @semantics function is safe: always returns a valid implementation. * @time O(1) * @output a valid sound API. if apiName is invalid, then a stub * implementation is returned. */ void sonix::changeAPI(const std::string& apiName) { snx::ISoundImplementation& oldImpl = this->impl(); vprASSERT(&oldImpl != NULL && "this->impl() should ensure that oldImpl is non-NULL"); // change the current api to the newly requested one. snx::SoundFactory::instance()->createImplementation(apiName, mImplementation); vprDEBUG(snxDBG, vprDBG_CRITICAL_LVL) << "Changing sound API from '" << oldImpl.name() << "' to '" << mImplementation->name() << "'\n" << vprDEBUG_FLUSH; // copy sound state from old to current (doesn't do binding yet) snx::SoundImplementation* si = dynamic_cast<snx::SoundImplementation*>(mImplementation); vprASSERT(NULL != si && "implementation is not of type SoundImplementation, cast fails"); snx::SoundImplementation& old_si = dynamic_cast<snx::SoundImplementation&>(oldImpl); vprASSERT(NULL != &old_si && "implementation is not of type SoundImplementation, cast fails"); si->copy( old_si ); // unload all sound data oldImpl.unbindAll(); // shutdown old api if exists oldImpl.shutdownAPI(); // delete old api, we're done with it... delete &oldImpl; // startup the new API // if it fails to start then we revert back to stub if ( ! mImplementation->startAPI() ) { vprDEBUG(snxDBG, vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED, "ERROR:") << " Failed to start new API--" << "changing back to Stub\n" << vprDEBUG_FLUSH; changeAPI("stub"); } // load all sound data mImplementation->bindAll(); } void sonix::configure(const snx::SoundAPIInfo& sai) { this->impl().configure( sai ); } /** * configure/reconfigure a sound * configure: associate a name (alias) to the description if not already done * reconfigure: change properties of the sound to the descriptino provided. * @preconditions provide an alias and a SoundInfo which describes the sound * @postconditions alias will point to loaded sound data * @semantics associate an alias to sound data. later this alias can be used * to operate on this sound data. */ void sonix::configure(const std::string& alias, const snx::SoundInfo& description) { this->impl().configure( alias, description ); } void sonix::remove(const std::string alias) { this->impl().remove( alias ); } /** * @semantics call once per sound frame (doesn't have to be same as your * graphics frame) * @input time elapsed since last frame */ void sonix::step(const float& timeElapsed) { this->impl().step( timeElapsed ); } snx::ISoundImplementation& sonix::impl() { if (mImplementation == NULL) { snx::SoundFactory::instance()->createImplementation("stub", mImplementation); mImplementation->startAPI(); mImplementation->bindAll(); } return *mImplementation; } } // namespace snx <|endoftext|>
<commit_before>#ifndef NEK_UTILITY_HAS_XXX_HPP #define NEK_UTILITY_HAS_XXX_HPP #include <nek/type_traits/integral_constant.hpp> #define NEK_HAS_XXX_TYPE_DEF(type)\ namespace type##_detail\ {\ template <class T, class = typename T::##type>\ nek::true_type has_##type(int);\ \ template <class>\ nek::false_type has_##type(long);\ }\ template <class T>\ struct has_##type\ : public decltype(type##_detail::has_##type<T>(0))\ {\ } #endif<commit_msg>fix \#\#<commit_after>#ifndef NEK_UTILITY_HAS_XXX_HPP #define NEK_UTILITY_HAS_XXX_HPP #include <nek/type_traits/integral_constant.hpp> #define NEK_HAS_XXX_TYPE_DEF(type)\ namespace type##_detail\ {\ template <class T, class = typename T::type>\ nek::true_type has_##type(int);\ \ template <class>\ nek::false_type has_##type(long);\ }\ template <class T>\ struct has_##type\ : public decltype(type##_detail::has_##type<T>(0))\ {\ } #endif<|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // The MIT License (MIT) // Copyright (c) 2016 Albert D Yang // ------------------------------------------------------------------------- // Module: luabind_plus_test // File name: inline_test.cpp // Created: 2016/04/09 by Albert D Yang // Description: // ------------------------------------------------------------------------- // 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. // //////////////////////////////////////////////////////////////////////////// #ifdef _MSC_VER # include <vld.h> #endif #include <vtd/rtti.h> extern "C" { # include <lua.h> # include <lualib.h> # include <lauxlib.h> } #include <stdio.h> #include <assert.h> #define LB_ASSERT assert #define LB_LOG_W printf #define LB_LOG_E printf #include <luabind/luabind.h> <commit_msg>mod for gcc<commit_after>//////////////////////////////////////////////////////////////////////////// // // The MIT License (MIT) // Copyright (c) 2016 Albert D Yang // ------------------------------------------------------------------------- // Module: luabind_plus_test // File name: inline_test.cpp // Created: 2016/04/09 by Albert D Yang // Description: // ------------------------------------------------------------------------- // 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. // //////////////////////////////////////////////////////////////////////////// #ifdef _MSC_VER # include <vld.h> #endif #include <stdio.h> #include <vtd/rtti.h> extern "C" { # include <lua.h> # include <lualib.h> # include <lauxlib.h> } #include <stdio.h> #include <assert.h> #define LB_ASSERT assert #define LB_LOG_W printf #define LB_LOG_E printf #include <luabind/luabind.h> <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.h" #include "../src/assets/neuron_interface.h" #include "../src/assets/input_neuron.h" #include "../src/assets/synapse.h" #include "../src/assets/neuron.h" #include "../src/assets/soma.h" #include <iostream> TEST_CASE( "synapse - get from_neuron's output_value #1 ") { /* InputNeuron has a public data member called output_value. This is the first layer. */ InputNeuron from_neuron; from_neuron.outgoing_value = 0.5; Neuron to_neuron; Synapse new_synapse(from_neuron, to_neuron); new_synapse.weight = 1.0; float expected_result = 0.5; float actual_result = new_synapse.get_weighted_incoming_value(); REQUIRE(actual_result == expected_result); } TEST_CASE( "synapse - get from_neuron's output_value #2 ") { InputNeuron from_neuron; from_neuron.outgoing_value = 4.0; Neuron to_neuron; Synapse new_synapse(from_neuron, to_neuron); new_synapse.weight = 0.75; float expected_result = 3.0; float actual_result = new_synapse.get_weighted_incoming_value(); REQUIRE(actual_result == expected_result); } TEST_CASE( "synapse - get to_neuron's incoming_values ") { InputNeuron from_neuron1; from_neuron1.outgoing_value = 4.0; InputNeuron from_neuron2; from_neuron2.outgoing_value = 8.0; Neuron to_neuron; Synapse new_synapse1(from_neuron1, to_neuron); new_synapse1.weight = 0.75; Synapse new_synapse2(from_neuron2, to_neuron); new_synapse2.weight = 0.5; to_neuron.add_incoming_synapse(new_synapse1); to_neuron.add_incoming_synapse(new_synapse2); to_neuron.set_in_out_values(); /* to_neuron will have the incoming values 4.0*0.75 + 8.0*0.5*/ float expected_result = 7.0; float actual_result = new_synapse1.to_neuron.get_incoming_values(); REQUIRE(actual_result == expected_result); } TEST_CASE( "synapse - update the weight with the value to change, would occur during back propagation") { Neuron from_neuron; Neuron to_neuron; Synapse new_synapse(from_neuron, to_neuron); new_synapse.weight = 1.0; float change_value = 0.4; new_synapse.update_weight(change_value); float expected_result = 0.6; float actual_result = new_synapse.weight; REQUIRE(actual_result == expected_result); } TEST_CASE( "soma - test this soma's sum function works - combine all incoming values") { /* Both synapses have the same to neuron and it's not used in the function. */ Neuron to_neuron; InputNeuron from_neuron_1; from_neuron_1.outgoing_value = 0.7; InputNeuron from_neuron_2; from_neuron_2.outgoing_value = 0.25; Synapse new_synapse_1(from_neuron_1, to_neuron); new_synapse_1.weight = 0.5; Synapse new_synapse_2(from_neuron_2, to_neuron); new_synapse_2.weight = 0.8; Soma soma; soma.incoming_synapses.emplace_back(new_synapse_1); soma.incoming_synapses.emplace_back(new_synapse_2); /* Result = 0.7*0.5 + 0.25*0.8 = 0.55 */ float expected_result = 0.55; float actual_result = soma.calculate_incoming_values(); REQUIRE(actual_result == expected_result); } TEST_CASE( "soma - test this soma's activation function works.") { /* This is logistic regression, check the soma.cpp file */ /* Also, watch tests that return floats, as returned floats have a max precision of 5 decimal * places. */ Soma soma; float test_value_1 = 0.0; float actual_result_1 = soma.activate(test_value_1); float expected_result_1 = 0.5; REQUIRE(actual_result_1 == expected_result_1); float test_value_2 = 0.5; float actual_result_2 = soma.activate(test_value_2); float expected_result_2 = 0.622459; REQUIRE(actual_result_2 == expected_result_2); float test_value_3 = 1.0; float actual_result_3 = soma.activate(test_value_3); float expected_result_3 = 0.73106; REQUIRE(actual_result_3 == expected_result_3); /* I can't think of a situation where incoming values would be below zero, unless the weights on * synapses were negative, and I guess that could happen. It could occur if the activation was * using another function, like TanH. */ float test_value_4 = -1.0; float actual_result_4 = soma.activate(test_value_4); float expected_result_4 = 0.26894; REQUIRE(actual_result_4 == expected_result_4); } TEST_CASE( "neuron - activate, via one incoming synapse #1 ") { /* For a neuron to activate, the synapses coming in must all have weights, and the neurons those * synapses originate from must have an output_value */ InputNeuron neuron1; neuron1.outgoing_value = 1.0; Neuron neuron2; Synapse new_synapse(neuron1, neuron2); new_synapse.weight = 0.8; neuron2.add_incoming_synapse(new_synapse); /* Incoming weights are equal to 1.0*0.8 = 0.8 */ neuron2.set_in_out_values(); float expected_result = 0.689974; float actual_result = neuron2.get_outgoing_value(); REQUIRE(actual_result == expected_result); } TEST_CASE( "neuron - activate, via one incoming synapse #2 ") { /* For a neuron to activate, the synapses coming in must all have weights, and the neurons those * synapses originate from must have an output_value */ InputNeuron neuron1; neuron1.outgoing_value = 0.8; Neuron neuron2; Synapse new_synapse(neuron1, neuron2); new_synapse.weight = 0.5; neuron2.add_incoming_synapse(new_synapse); /* Incoming weights are equal to 0.5*0.8 = 0.4*/ neuron2.set_in_out_values(); float expected_result = 0.598688; float actual_result = neuron2.get_outgoing_value(); REQUIRE(actual_result == expected_result); } TEST_CASE( "neuron - activate, via several incoming synapses ") { /* For a neuron to activate, the synapses coming in must all have weights, and the neurons those * synapses originate from must have an output_value */ InputNeuron neuron1; neuron1.outgoing_value = 0.4; InputNeuron neuron2; neuron2.outgoing_value = 1.0; InputNeuron neuron3; neuron3.outgoing_value = 0.3; Neuron neuron4; Synapse new_synapse_1(neuron1, neuron4); new_synapse_1.weight = 0.75; Synapse new_synapse_2(neuron2, neuron4); new_synapse_2.weight = 0.2; Synapse new_synapse_3(neuron3, neuron4); new_synapse_3.weight = 0.5; neuron4.add_incoming_synapse(new_synapse_1); neuron4.add_incoming_synapse(new_synapse_2); neuron4.add_incoming_synapse(new_synapse_3); neuron4.set_in_out_values(); /* Incoming values should be = 0.4*0.75 + 1.0*0.2 + 0.3*0.5 = 0.65 */ float expected_result = 0.65701; float actual_result = neuron4.get_outgoing_value(); REQUIRE(actual_result == expected_result); } <commit_msg>Tests changed to reflect composition changes<commit_after>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.h" #include "../src/assets/neuron_interface.h" #include "../src/assets/input_neuron.h" #include "../src/assets/synapse.h" #include "../src/assets/neuron.h" #include "../src/assets/soma.h" #include <iostream> TEST_CASE( "synapse - get from_neuron's output_value #1 ") { /* InputNeuron has a public data member called output_value. This is the first layer. */ InputNeuron from_neuron; from_neuron.outgoing_value = 0.5; Neuron to_neuron; Synapse new_synapse(from_neuron, to_neuron); new_synapse.weight = 1.0; float expected_result = 0.5; float actual_result = new_synapse.get_weighted_incoming_value(); REQUIRE(actual_result == expected_result); } TEST_CASE( "synapse - get from_neuron's output_value #2 ") { InputNeuron from_neuron; from_neuron.outgoing_value = 4.0; Neuron to_neuron; Synapse new_synapse(from_neuron, to_neuron); new_synapse.weight = 0.75; float expected_result = 3.0; float actual_result = new_synapse.get_weighted_incoming_value(); REQUIRE(actual_result == expected_result); } TEST_CASE( "synapse - get to_neuron's incoming_values ") { InputNeuron from_neuron1; from_neuron1.outgoing_value = 4.0; InputNeuron from_neuron2; from_neuron2.outgoing_value = 8.0; Neuron to_neuron; Synapse new_synapse1(from_neuron1, to_neuron); new_synapse1.weight = 0.75; Synapse new_synapse2(from_neuron2, to_neuron); new_synapse2.weight = 0.5; to_neuron.add_incoming_synapse(new_synapse1); to_neuron.add_incoming_synapse(new_synapse2); to_neuron.set_in_out_values(); /* to_neuron will have the incoming values 4.0*0.75 + 8.0*0.5*/ float expected_result = 7.0; float actual_result = new_synapse1.to_neuron.get_incoming_values(); REQUIRE(actual_result == expected_result); } TEST_CASE( "synapse - update the weight with the value to change, would occur during back propagation") { Neuron from_neuron; Neuron to_neuron; Synapse new_synapse(from_neuron, to_neuron); new_synapse.weight = 1.0; float change_value = 0.4; new_synapse.update_weight(change_value); float expected_result = 0.6; float actual_result = new_synapse.weight; REQUIRE(actual_result == expected_result); } TEST_CASE( "soma - test this soma's sum function works - combine all incoming values") { /* Both synapses have the same to neuron and it's not used in the function. */ Neuron to_neuron; InputNeuron from_neuron_1; from_neuron_1.outgoing_value = 0.7; InputNeuron from_neuron_2; from_neuron_2.outgoing_value = 0.25; Synapse new_synapse_1(from_neuron_1, to_neuron); new_synapse_1.weight = 0.5; Synapse new_synapse_2(from_neuron_2, to_neuron); new_synapse_2.weight = 0.8; /* Usually, this is a data member of Neuron class */ std::vector <Synapse> incoming_synapses; incoming_synapses.emplace_back(new_synapse_1); incoming_synapses.emplace_back(new_synapse_2); Soma soma; /* Result = 0.7*0.5 + 0.25*0.8 = 0.55 */ float expected_result = 0.55; float actual_result = soma.calculate_incoming_values(incoming_synapses); REQUIRE(actual_result == expected_result); } TEST_CASE( "soma - test this soma's activation function works.") { /* This is logistic regression, check the soma.cpp file */ /* Also, watch tests that return floats, as returned floats have a max precision of 5 decimal * places. */ Soma soma; float test_value_1 = 0.0; float actual_result_1 = soma.activate(test_value_1); float expected_result_1 = 0.5; REQUIRE(actual_result_1 == expected_result_1); float test_value_2 = 0.5; float actual_result_2 = soma.activate(test_value_2); float expected_result_2 = 0.622459; REQUIRE(actual_result_2 == expected_result_2); float test_value_3 = 1.0; float actual_result_3 = soma.activate(test_value_3); float expected_result_3 = 0.73106; REQUIRE(actual_result_3 == expected_result_3); /* I can't think of a situation where incoming values would be below zero, unless the weights on * synapses were negative, and I guess that could happen. It could occur if the activation was * using another function, like TanH. */ float test_value_4 = -1.0; float actual_result_4 = soma.activate(test_value_4); float expected_result_4 = 0.26894; REQUIRE(actual_result_4 == expected_result_4); } TEST_CASE( "neuron - activate, via one incoming synapse #1 ") { /* For a neuron to activate, the synapses coming in must all have weights, and the neurons those * synapses originate from must have an output_value */ InputNeuron neuron1; neuron1.outgoing_value = 1.0; Neuron neuron2; Synapse new_synapse(neuron1, neuron2); new_synapse.weight = 0.8; neuron2.add_incoming_synapse(new_synapse); /* Incoming weights are equal to 1.0*0.8 = 0.8 */ neuron2.set_in_out_values(); float expected_result = 0.689974; float actual_result = neuron2.get_outgoing_value(); REQUIRE(actual_result == expected_result); } TEST_CASE( "neuron - activate, via one incoming synapse #2 ") { /* For a neuron to activate, the synapses coming in must all have weights, and the neurons those * synapses originate from must have an output_value */ InputNeuron neuron1; neuron1.outgoing_value = 0.8; Neuron neuron2; Synapse new_synapse(neuron1, neuron2); new_synapse.weight = 0.5; neuron2.add_incoming_synapse(new_synapse); /* Incoming weights are equal to 0.5*0.8 = 0.4*/ neuron2.set_in_out_values(); float expected_result = 0.598688; float actual_result = neuron2.get_outgoing_value(); REQUIRE(actual_result == expected_result); } TEST_CASE( "neuron - activate, via several incoming synapses ") { /* For a neuron to activate, the synapses coming in must all have weights, and the neurons those * synapses originate from must have an output_value */ InputNeuron neuron1; neuron1.outgoing_value = 0.4; InputNeuron neuron2; neuron2.outgoing_value = 1.0; InputNeuron neuron3; neuron3.outgoing_value = 0.3; Neuron neuron4; Synapse new_synapse_1(neuron1, neuron4); new_synapse_1.weight = 0.75; Synapse new_synapse_2(neuron2, neuron4); new_synapse_2.weight = 0.2; Synapse new_synapse_3(neuron3, neuron4); new_synapse_3.weight = 0.5; neuron4.add_incoming_synapse(new_synapse_1); neuron4.add_incoming_synapse(new_synapse_2); neuron4.add_incoming_synapse(new_synapse_3); neuron4.set_in_out_values(); /* Incoming values should be = 0.4*0.75 + 1.0*0.2 + 0.3*0.5 = 0.65 */ float expected_result = 0.65701; float actual_result = neuron4.get_outgoing_value(); REQUIRE(actual_result == expected_result); } <|endoftext|>
<commit_before>constexpr inline nlohmann::json::size_type operator"" _S(unsigned long long v) { return static_cast<nlohmann::json::size_type>(v); } inline std::string operator"" _S(const char *v, std::size_t) { return std::string(v); } static inline nlohmann::json find(nlohmann::json &array, const char *path, const char *value) { nlohmann::json::json_pointer pointer(path); nlohmann::json res; for (auto &item : array) { if (item.at(pointer).get<std::string>() == value) { res = item; break; } } return res; } <commit_msg>Add missing include<commit_after>#include <nlohmann/json.hpp> constexpr inline nlohmann::json::size_type operator"" _S(unsigned long long v) { return static_cast<nlohmann::json::size_type>(v); } inline std::string operator"" _S(const char *v, std::size_t) { return std::string(v); } static inline nlohmann::json find(nlohmann::json &array, const char *path, const char *value) { nlohmann::json::json_pointer pointer(path); nlohmann::json res; for (auto &item : array) { if (item.at(pointer).get<std::string>() == value) { res = item; break; } } return res; } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr> // Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com> // // Eigen 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. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. // work around "uninitialized" warnings and give that option some testing #define EIGEN_INITIALIZE_MATRICES_BY_ZERO #ifndef EIGEN_NO_STATIC_ASSERT #define EIGEN_NO_STATIC_ASSERT // turn static asserts into runtime asserts in order to check them #endif // #ifndef EIGEN_DONT_VECTORIZE // #define EIGEN_DONT_VECTORIZE // SSE intrinsics aren't designed to allow mixing types // #endif #include "main.h" using namespace std; template<int SizeAtCompileType> void mixingtypes(int size = SizeAtCompileType) { typedef std::complex<float> CF; typedef std::complex<double> CD; typedef Matrix<float, SizeAtCompileType, SizeAtCompileType> Mat_f; typedef Matrix<double, SizeAtCompileType, SizeAtCompileType> Mat_d; typedef Matrix<std::complex<float>, SizeAtCompileType, SizeAtCompileType> Mat_cf; typedef Matrix<std::complex<double>, SizeAtCompileType, SizeAtCompileType> Mat_cd; typedef Matrix<float, SizeAtCompileType, 1> Vec_f; typedef Matrix<double, SizeAtCompileType, 1> Vec_d; typedef Matrix<std::complex<float>, SizeAtCompileType, 1> Vec_cf; typedef Matrix<std::complex<double>, SizeAtCompileType, 1> Vec_cd; Mat_f mf = Mat_f::Random(size,size); Mat_d md = mf.template cast<double>(); Mat_cf mcf = Mat_cf::Random(size,size); Mat_cd mcd = mcf.template cast<complex<double> >(); Vec_f vf = Vec_f::Random(size,1); Vec_d vd = vf.template cast<double>(); Vec_cf vcf = Vec_cf::Random(size,1); Vec_cd vcd = vcf.template cast<complex<double> >(); float sf = internal::random<float>(); double sd = internal::random<double>(); complex<float> scf = internal::random<complex<float> >(); complex<double> scd = internal::random<complex<double> >(); mf+mf; VERIFY_RAISES_ASSERT(mf+md); VERIFY_RAISES_ASSERT(mf+mcf); VERIFY_RAISES_ASSERT(vf=vd); VERIFY_RAISES_ASSERT(vf+=vd); VERIFY_RAISES_ASSERT(mcd=md); // check scalar products VERIFY_IS_APPROX(vcf * sf , vcf * complex<float>(sf)); VERIFY_IS_APPROX(sd * vcd, complex<double>(sd) * vcd); VERIFY_IS_APPROX(vf * scf , vf.template cast<complex<float> >() * scf); VERIFY_IS_APPROX(scd * vd, scd * vd.template cast<complex<double> >()); // check dot product vf.dot(vf); #if 0 // we get other compilation errors here than just static asserts VERIFY_RAISES_ASSERT(vd.dot(vf)); #endif VERIFY_RAISES_ASSERT(vcf.dot(vf)); // yeah eventually we should allow this but i'm too lazy to make that change now in Dot.h // especially as that might be rewritten as cwise product .sum() which would make that automatic. // check diagonal product VERIFY_IS_APPROX(vf.asDiagonal() * mcf, vf.template cast<complex<float> >().asDiagonal() * mcf); VERIFY_IS_APPROX(vcd.asDiagonal() * md, vcd.asDiagonal() * md.template cast<complex<double> >()); VERIFY_IS_APPROX(mcf * vf.asDiagonal(), mcf * vf.template cast<complex<float> >().asDiagonal()); VERIFY_IS_APPROX(md * vcd.asDiagonal(), md.template cast<complex<double> >() * vcd.asDiagonal()); // vd.asDiagonal() * mf; // does not even compile // vcd.asDiagonal() * mf; // does not even compile // check inner product VERIFY_IS_APPROX((vf.transpose() * vcf).value(), (vf.template cast<complex<float> >().transpose() * vcf).value()); // check outer product VERIFY_IS_APPROX((vf * vcf.transpose()).eval(), (vf.template cast<complex<float> >() * vcf.transpose()).eval()); // coeff wise product VERIFY_IS_APPROX((vf * vcf.transpose()).eval(), (vf.template cast<complex<float> >() * vcf.transpose()).eval()); Mat_cd mcd2 = mcd; VERIFY_IS_APPROX(mcd.array() *= md.array(), mcd2.array() *= md.array().template cast<std::complex<double> >()); // check matrix-matrix products VERIFY_IS_APPROX(sd*md*mcd, (sd*md).template cast<CD>().eval()*mcd); VERIFY_IS_APPROX(sd*mcd*md, sd*mcd*md.template cast<CD>()); VERIFY_IS_APPROX(scd*md*mcd, scd*md.template cast<CD>().eval()*mcd); VERIFY_IS_APPROX(scd*mcd*md, scd*mcd*md.template cast<CD>()); VERIFY_IS_APPROX(sf*mf*mcf, sf*mf.template cast<CF>()*mcf); VERIFY_IS_APPROX(sf*mcf*mf, sf*mcf*mf.template cast<CF>()); VERIFY_IS_APPROX(scf*mf*mcf, scf*mf.template cast<CF>()*mcf); VERIFY_IS_APPROX(scf*mcf*mf, scf*mcf*mf.template cast<CF>()); VERIFY_IS_APPROX(sf*mf*vcf, (sf*mf).template cast<CF>().eval()*vcf); VERIFY_IS_APPROX(scf*mf*vcf,(scf*mf.template cast<CF>()).eval()*vcf); VERIFY_IS_APPROX(sf*mcf*vf, sf*mcf*vf.template cast<CF>()); VERIFY_IS_APPROX(scf*mcf*vf,scf*mcf*vf.template cast<CF>()); VERIFY_IS_APPROX(sf*vcf.adjoint()*mf, sf*vcf.adjoint()*mf.template cast<CF>().eval()); VERIFY_IS_APPROX(scf*vcf.adjoint()*mf, scf*vcf.adjoint()*mf.template cast<CF>().eval()); VERIFY_IS_APPROX(sf*vf.adjoint()*mcf, sf*vf.adjoint().template cast<CF>().eval()*mcf); VERIFY_IS_APPROX(scf*vf.adjoint()*mcf, scf*vf.adjoint().template cast<CF>().eval()*mcf); VERIFY_IS_APPROX(sd*md*vcd, (sd*md).template cast<CD>().eval()*vcd); VERIFY_IS_APPROX(scd*md*vcd,(scd*md.template cast<CD>()).eval()*vcd); VERIFY_IS_APPROX(sd*mcd*vd, sd*mcd*vd.template cast<CD>().eval()); VERIFY_IS_APPROX(scd*mcd*vd,scd*mcd*vd.template cast<CD>().eval()); VERIFY_IS_APPROX(sd*vcd.adjoint()*md, sd*vcd.adjoint()*md.template cast<CD>().eval()); VERIFY_IS_APPROX(scd*vcd.adjoint()*md, scd*vcd.adjoint()*md.template cast<CD>().eval()); VERIFY_IS_APPROX(sd*vd.adjoint()*mcd, sd*vd.adjoint().template cast<CD>().eval()*mcd); VERIFY_IS_APPROX(scd*vd.adjoint()*mcd, scd*vd.adjoint().template cast<CD>().eval()*mcd); } void test_mixingtypes() { CALL_SUBTEST_1(mixingtypes<3>()); CALL_SUBTEST_2(mixingtypes<4>()); CALL_SUBTEST_3(mixingtypes<Dynamic>(internal::random<int>(1,310))); } <commit_msg>fix mixingtypes unit test<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr> // Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com> // // Eigen 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. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. // work around "uninitialized" warnings and give that option some testing #define EIGEN_INITIALIZE_MATRICES_BY_ZERO #ifndef EIGEN_NO_STATIC_ASSERT #define EIGEN_NO_STATIC_ASSERT // turn static asserts into runtime asserts in order to check them #endif // #ifndef EIGEN_DONT_VECTORIZE // #define EIGEN_DONT_VECTORIZE // SSE intrinsics aren't designed to allow mixing types // #endif #include "main.h" using namespace std; template<int SizeAtCompileType> void mixingtypes(int size = SizeAtCompileType) { typedef std::complex<float> CF; typedef std::complex<double> CD; typedef Matrix<float, SizeAtCompileType, SizeAtCompileType> Mat_f; typedef Matrix<double, SizeAtCompileType, SizeAtCompileType> Mat_d; typedef Matrix<std::complex<float>, SizeAtCompileType, SizeAtCompileType> Mat_cf; typedef Matrix<std::complex<double>, SizeAtCompileType, SizeAtCompileType> Mat_cd; typedef Matrix<float, SizeAtCompileType, 1> Vec_f; typedef Matrix<double, SizeAtCompileType, 1> Vec_d; typedef Matrix<std::complex<float>, SizeAtCompileType, 1> Vec_cf; typedef Matrix<std::complex<double>, SizeAtCompileType, 1> Vec_cd; Mat_f mf = Mat_f::Random(size,size); Mat_d md = mf.template cast<double>(); Mat_cf mcf = Mat_cf::Random(size,size); Mat_cd mcd = mcf.template cast<complex<double> >(); Vec_f vf = Vec_f::Random(size,1); Vec_d vd = vf.template cast<double>(); Vec_cf vcf = Vec_cf::Random(size,1); Vec_cd vcd = vcf.template cast<complex<double> >(); float sf = internal::random<float>(); double sd = internal::random<double>(); complex<float> scf = internal::random<complex<float> >(); complex<double> scd = internal::random<complex<double> >(); mf+mf; VERIFY_RAISES_ASSERT(mf+md); VERIFY_RAISES_ASSERT(mf+mcf); VERIFY_RAISES_ASSERT(vf=vd); VERIFY_RAISES_ASSERT(vf+=vd); VERIFY_RAISES_ASSERT(mcd=md); // check scalar products VERIFY_IS_APPROX(vcf * sf , vcf * complex<float>(sf)); VERIFY_IS_APPROX(sd * vcd, complex<double>(sd) * vcd); VERIFY_IS_APPROX(vf * scf , vf.template cast<complex<float> >() * scf); VERIFY_IS_APPROX(scd * vd, scd * vd.template cast<complex<double> >()); // check dot product vf.dot(vf); #if 0 // we get other compilation errors here than just static asserts VERIFY_RAISES_ASSERT(vd.dot(vf)); #endif VERIFY_IS_APPROX(vcf.dot(vf), vcf.dot(vf.template cast<complex<float> >())); // check diagonal product VERIFY_IS_APPROX(vf.asDiagonal() * mcf, vf.template cast<complex<float> >().asDiagonal() * mcf); VERIFY_IS_APPROX(vcd.asDiagonal() * md, vcd.asDiagonal() * md.template cast<complex<double> >()); VERIFY_IS_APPROX(mcf * vf.asDiagonal(), mcf * vf.template cast<complex<float> >().asDiagonal()); VERIFY_IS_APPROX(md * vcd.asDiagonal(), md.template cast<complex<double> >() * vcd.asDiagonal()); // vd.asDiagonal() * mf; // does not even compile // vcd.asDiagonal() * mf; // does not even compile // check inner product VERIFY_IS_APPROX((vf.transpose() * vcf).value(), (vf.template cast<complex<float> >().transpose() * vcf).value()); // check outer product VERIFY_IS_APPROX((vf * vcf.transpose()).eval(), (vf.template cast<complex<float> >() * vcf.transpose()).eval()); // coeff wise product VERIFY_IS_APPROX((vf * vcf.transpose()).eval(), (vf.template cast<complex<float> >() * vcf.transpose()).eval()); Mat_cd mcd2 = mcd; VERIFY_IS_APPROX(mcd.array() *= md.array(), mcd2.array() *= md.array().template cast<std::complex<double> >()); // check matrix-matrix products VERIFY_IS_APPROX(sd*md*mcd, (sd*md).template cast<CD>().eval()*mcd); VERIFY_IS_APPROX(sd*mcd*md, sd*mcd*md.template cast<CD>()); VERIFY_IS_APPROX(scd*md*mcd, scd*md.template cast<CD>().eval()*mcd); VERIFY_IS_APPROX(scd*mcd*md, scd*mcd*md.template cast<CD>()); VERIFY_IS_APPROX(sf*mf*mcf, sf*mf.template cast<CF>()*mcf); VERIFY_IS_APPROX(sf*mcf*mf, sf*mcf*mf.template cast<CF>()); VERIFY_IS_APPROX(scf*mf*mcf, scf*mf.template cast<CF>()*mcf); VERIFY_IS_APPROX(scf*mcf*mf, scf*mcf*mf.template cast<CF>()); VERIFY_IS_APPROX(sf*mf*vcf, (sf*mf).template cast<CF>().eval()*vcf); VERIFY_IS_APPROX(scf*mf*vcf,(scf*mf.template cast<CF>()).eval()*vcf); VERIFY_IS_APPROX(sf*mcf*vf, sf*mcf*vf.template cast<CF>()); VERIFY_IS_APPROX(scf*mcf*vf,scf*mcf*vf.template cast<CF>()); VERIFY_IS_APPROX(sf*vcf.adjoint()*mf, sf*vcf.adjoint()*mf.template cast<CF>().eval()); VERIFY_IS_APPROX(scf*vcf.adjoint()*mf, scf*vcf.adjoint()*mf.template cast<CF>().eval()); VERIFY_IS_APPROX(sf*vf.adjoint()*mcf, sf*vf.adjoint().template cast<CF>().eval()*mcf); VERIFY_IS_APPROX(scf*vf.adjoint()*mcf, scf*vf.adjoint().template cast<CF>().eval()*mcf); VERIFY_IS_APPROX(sd*md*vcd, (sd*md).template cast<CD>().eval()*vcd); VERIFY_IS_APPROX(scd*md*vcd,(scd*md.template cast<CD>()).eval()*vcd); VERIFY_IS_APPROX(sd*mcd*vd, sd*mcd*vd.template cast<CD>().eval()); VERIFY_IS_APPROX(scd*mcd*vd,scd*mcd*vd.template cast<CD>().eval()); VERIFY_IS_APPROX(sd*vcd.adjoint()*md, sd*vcd.adjoint()*md.template cast<CD>().eval()); VERIFY_IS_APPROX(scd*vcd.adjoint()*md, scd*vcd.adjoint()*md.template cast<CD>().eval()); VERIFY_IS_APPROX(sd*vd.adjoint()*mcd, sd*vd.adjoint().template cast<CD>().eval()*mcd); VERIFY_IS_APPROX(scd*vd.adjoint()*mcd, scd*vd.adjoint().template cast<CD>().eval()*mcd); } void test_mixingtypes() { CALL_SUBTEST_1(mixingtypes<3>()); CALL_SUBTEST_2(mixingtypes<4>()); CALL_SUBTEST_3(mixingtypes<Dynamic>(internal::random<int>(1,310))); } <|endoftext|>
<commit_before>/* godot-cpp integration testing project. * * This is free and unencumbered software released into the public domain. */ #include "example.h" #include <godot_cpp/core/class_db.hpp> #include <godot_cpp/classes/global_constants.hpp> #include <godot_cpp/classes/label.hpp> #include <godot_cpp/variant/utility_functions.hpp> using namespace godot; ExampleRef::ExampleRef() { UtilityFunctions::print("ExampleRef created."); } ExampleRef::~ExampleRef() { UtilityFunctions::print("ExampleRef destroyed."); } int Example::test_static(int p_a, int p_b) { return p_a + p_b; } void Example::test_static2() { UtilityFunctions::print(" void static"); } int Example::def_args(int p_a, int p_b) { return p_a + p_b; } void Example::_notification(int p_what) { UtilityFunctions::print("Notification: ", String::num(p_what)); } bool Example::_set(const StringName &p_name, const Variant &p_value) { String name = p_name; if (name.begins_with("dproperty")) { int index = name.get_slicec('_', 1).to_int(); dprop[index] = p_value; return true; } if (name == "property_from_list") { property_from_list = p_value; return true; } return false; } bool Example::_get(const StringName &p_name, Variant &r_ret) const { String name = p_name; if (name.begins_with("dproperty")) { int index = name.get_slicec('_', 1).to_int(); r_ret = dprop[index]; return true; } if (name == "property_from_list") { r_ret = property_from_list; return true; } return false; } String Example::_to_string() const { return "[ GDExtension::Example <--> Instance ID:" + itos(get_instance_id()) + " ]"; } void Example::_get_property_list(List<PropertyInfo> *p_list) const { p_list->push_back(PropertyInfo(Variant::VECTOR3, "property_from_list")); for (int i = 0; i < 3; i++) { p_list->push_back(PropertyInfo(Variant::VECTOR2, "dproperty_" + itos(i))); } } bool Example::_property_can_revert(const StringName &p_name) const { if (p_name == StringName("property_from_list") && property_from_list != Vector3(42, 42, 42)) { return true; } else { return false; } }; bool Example::_property_get_revert(const StringName &p_name, Variant &r_property) const { if (p_name == StringName("property_from_list")) { r_property = Vector3(42, 42, 42); return true; } else { return false; } }; void Example::_bind_methods() { // Methods. ClassDB::bind_method(D_METHOD("simple_func"), &Example::simple_func); ClassDB::bind_method(D_METHOD("simple_const_func"), &Example::simple_const_func); ClassDB::bind_method(D_METHOD("return_something"), &Example::return_something); ClassDB::bind_method(D_METHOD("return_something_const"), &Example::return_something_const); ClassDB::bind_method(D_METHOD("return_extended_ref"), &Example::return_extended_ref); ClassDB::bind_method(D_METHOD("extended_ref_checks"), &Example::extended_ref_checks); ClassDB::bind_method(D_METHOD("test_array"), &Example::test_array); ClassDB::bind_method(D_METHOD("test_tarray_arg", "array"), &Example::test_tarray_arg); ClassDB::bind_method(D_METHOD("test_tarray"), &Example::test_tarray); ClassDB::bind_method(D_METHOD("test_dictionary"), &Example::test_dictionary); ClassDB::bind_method(D_METHOD("def_args", "a", "b"), &Example::def_args, DEFVAL(100), DEFVAL(200)); ClassDB::bind_static_method("Example", D_METHOD("test_static", "a", "b"), &Example::test_static); ClassDB::bind_static_method("Example", D_METHOD("test_static2"), &Example::test_static2); { MethodInfo mi; mi.arguments.push_back(PropertyInfo(Variant::STRING, "some_argument")); mi.name = "varargs_func"; ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "varargs_func", &Example::varargs_func, mi); } { MethodInfo mi; mi.arguments.push_back(PropertyInfo(Variant::STRING, "some_argument")); mi.name = "varargs_func_nv"; ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "varargs_func_nv", &Example::varargs_func_nv, mi); } { MethodInfo mi; mi.arguments.push_back(PropertyInfo(Variant::STRING, "some_argument")); mi.name = "varargs_func_void"; ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "varargs_func_void", &Example::varargs_func_void, mi); } // Properties. ADD_GROUP("Test group", "group_"); ADD_SUBGROUP("Test subgroup", "group_subgroup_"); ClassDB::bind_method(D_METHOD("get_custom_position"), &Example::get_custom_position); ClassDB::bind_method(D_METHOD("get_v4"), &Example::get_v4); ClassDB::bind_method(D_METHOD("set_custom_position", "position"), &Example::set_custom_position); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "group_subgroup_custom_position"), "set_custom_position", "get_custom_position"); // Signals. ADD_SIGNAL(MethodInfo("custom_signal", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::INT, "value"))); ClassDB::bind_method(D_METHOD("emit_custom_signal", "name", "value"), &Example::emit_custom_signal); // Constants. BIND_ENUM_CONSTANT(FIRST); BIND_ENUM_CONSTANT(ANSWER_TO_EVERYTHING); BIND_CONSTANT(CONSTANT_WITHOUT_ENUM); } Example::Example() { UtilityFunctions::print("Constructor."); } Example::~Example() { UtilityFunctions::print("Destructor."); } // Methods. void Example::simple_func() { UtilityFunctions::print(" Simple func called."); } void Example::simple_const_func() const { UtilityFunctions::print(" Simple const func called."); } String Example::return_something(const String &base) { UtilityFunctions::print(" Return something called."); return base; } Viewport *Example::return_something_const() const { UtilityFunctions::print(" Return something const called."); if (is_inside_tree()) { Viewport *result = get_viewport(); return result; } return nullptr; } ExampleRef *Example::return_extended_ref() const { return memnew(ExampleRef()); } Ref<ExampleRef> Example::extended_ref_checks(Ref<ExampleRef> p_ref) const { Ref<ExampleRef> ref; ref.instantiate(); // TODO the returned value gets dereferenced too early and return a null object otherwise. ref->reference(); UtilityFunctions::print(" Example ref checks called with value: ", p_ref->get_instance_id(), ", returning value: ", ref->get_instance_id()); return ref; } Variant Example::varargs_func(const Variant **args, GDNativeInt arg_count, GDNativeCallError &error) { UtilityFunctions::print(" Varargs (Variant return) called with ", String::num((double)arg_count), " arguments"); return arg_count; } int Example::varargs_func_nv(const Variant **args, GDNativeInt arg_count, GDNativeCallError &error) { UtilityFunctions::print(" Varargs (int return) called with ", String::num((double)arg_count), " arguments"); return 42; } void Example::varargs_func_void(const Variant **args, GDNativeInt arg_count, GDNativeCallError &error) { UtilityFunctions::print(" Varargs (no return) called with ", String::num((double)arg_count), " arguments"); } void Example::emit_custom_signal(const String &name, int value) { emit_signal("custom_signal", name, value); } Array Example::test_array() const { Array arr; arr.resize(2); arr[0] = Variant(1); arr[1] = Variant(2); return arr; } void Example::test_tarray_arg(const TypedArray<int64_t> &p_array) { for (int i = 0; i < p_array.size(); i++) { UtilityFunctions::print(p_array[i]); } } TypedArray<Vector2> Example::test_tarray() const { TypedArray<Vector2> arr; arr.resize(2); arr[0] = Vector2(1, 2); arr[1] = Vector2(2, 3); return arr; } Dictionary Example::test_dictionary() const { Dictionary dict; dict["hello"] = "world"; dict["foo"] = "bar"; return dict; } // Properties. void Example::set_custom_position(const Vector2 &pos) { custom_position = pos; } Vector2 Example::get_custom_position() const { return custom_position; } Vector4 Example::get_v4() const { return Vector4(1.2, 3.4, 5.6, 7.8); } // Virtual function override. bool Example::_has_point(const Vector2 &point) const { Label *label = get_node<Label>("Label"); label->set_text("Got point: " + Variant(point).stringify()); return false; } <commit_msg>Fix some type warnings in example<commit_after>/* godot-cpp integration testing project. * * This is free and unencumbered software released into the public domain. */ #include "example.h" #include <godot_cpp/core/class_db.hpp> #include <godot_cpp/classes/global_constants.hpp> #include <godot_cpp/classes/label.hpp> #include <godot_cpp/variant/utility_functions.hpp> using namespace godot; ExampleRef::ExampleRef() { UtilityFunctions::print("ExampleRef created."); } ExampleRef::~ExampleRef() { UtilityFunctions::print("ExampleRef destroyed."); } int Example::test_static(int p_a, int p_b) { return p_a + p_b; } void Example::test_static2() { UtilityFunctions::print(" void static"); } int Example::def_args(int p_a, int p_b) { return p_a + p_b; } void Example::_notification(int p_what) { UtilityFunctions::print("Notification: ", String::num(p_what)); } bool Example::_set(const StringName &p_name, const Variant &p_value) { String name = p_name; if (name.begins_with("dproperty")) { int64_t index = name.get_slicec('_', 1).to_int(); dprop[index] = p_value; return true; } if (name == "property_from_list") { property_from_list = p_value; return true; } return false; } bool Example::_get(const StringName &p_name, Variant &r_ret) const { String name = p_name; if (name.begins_with("dproperty")) { int64_t index = name.get_slicec('_', 1).to_int(); r_ret = dprop[index]; return true; } if (name == "property_from_list") { r_ret = property_from_list; return true; } return false; } String Example::_to_string() const { return "[ GDExtension::Example <--> Instance ID:" + uitos(get_instance_id()) + " ]"; } void Example::_get_property_list(List<PropertyInfo> *p_list) const { p_list->push_back(PropertyInfo(Variant::VECTOR3, "property_from_list")); for (int i = 0; i < 3; i++) { p_list->push_back(PropertyInfo(Variant::VECTOR2, "dproperty_" + itos(i))); } } bool Example::_property_can_revert(const StringName &p_name) const { if (p_name == StringName("property_from_list") && property_from_list != Vector3(42, 42, 42)) { return true; } else { return false; } }; bool Example::_property_get_revert(const StringName &p_name, Variant &r_property) const { if (p_name == StringName("property_from_list")) { r_property = Vector3(42, 42, 42); return true; } else { return false; } }; void Example::_bind_methods() { // Methods. ClassDB::bind_method(D_METHOD("simple_func"), &Example::simple_func); ClassDB::bind_method(D_METHOD("simple_const_func"), &Example::simple_const_func); ClassDB::bind_method(D_METHOD("return_something"), &Example::return_something); ClassDB::bind_method(D_METHOD("return_something_const"), &Example::return_something_const); ClassDB::bind_method(D_METHOD("return_extended_ref"), &Example::return_extended_ref); ClassDB::bind_method(D_METHOD("extended_ref_checks"), &Example::extended_ref_checks); ClassDB::bind_method(D_METHOD("test_array"), &Example::test_array); ClassDB::bind_method(D_METHOD("test_tarray_arg", "array"), &Example::test_tarray_arg); ClassDB::bind_method(D_METHOD("test_tarray"), &Example::test_tarray); ClassDB::bind_method(D_METHOD("test_dictionary"), &Example::test_dictionary); ClassDB::bind_method(D_METHOD("def_args", "a", "b"), &Example::def_args, DEFVAL(100), DEFVAL(200)); ClassDB::bind_static_method("Example", D_METHOD("test_static", "a", "b"), &Example::test_static); ClassDB::bind_static_method("Example", D_METHOD("test_static2"), &Example::test_static2); { MethodInfo mi; mi.arguments.push_back(PropertyInfo(Variant::STRING, "some_argument")); mi.name = "varargs_func"; ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "varargs_func", &Example::varargs_func, mi); } { MethodInfo mi; mi.arguments.push_back(PropertyInfo(Variant::STRING, "some_argument")); mi.name = "varargs_func_nv"; ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "varargs_func_nv", &Example::varargs_func_nv, mi); } { MethodInfo mi; mi.arguments.push_back(PropertyInfo(Variant::STRING, "some_argument")); mi.name = "varargs_func_void"; ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "varargs_func_void", &Example::varargs_func_void, mi); } // Properties. ADD_GROUP("Test group", "group_"); ADD_SUBGROUP("Test subgroup", "group_subgroup_"); ClassDB::bind_method(D_METHOD("get_custom_position"), &Example::get_custom_position); ClassDB::bind_method(D_METHOD("get_v4"), &Example::get_v4); ClassDB::bind_method(D_METHOD("set_custom_position", "position"), &Example::set_custom_position); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "group_subgroup_custom_position"), "set_custom_position", "get_custom_position"); // Signals. ADD_SIGNAL(MethodInfo("custom_signal", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::INT, "value"))); ClassDB::bind_method(D_METHOD("emit_custom_signal", "name", "value"), &Example::emit_custom_signal); // Constants. BIND_ENUM_CONSTANT(FIRST); BIND_ENUM_CONSTANT(ANSWER_TO_EVERYTHING); BIND_CONSTANT(CONSTANT_WITHOUT_ENUM); } Example::Example() { UtilityFunctions::print("Constructor."); } Example::~Example() { UtilityFunctions::print("Destructor."); } // Methods. void Example::simple_func() { UtilityFunctions::print(" Simple func called."); } void Example::simple_const_func() const { UtilityFunctions::print(" Simple const func called."); } String Example::return_something(const String &base) { UtilityFunctions::print(" Return something called."); return base; } Viewport *Example::return_something_const() const { UtilityFunctions::print(" Return something const called."); if (is_inside_tree()) { Viewport *result = get_viewport(); return result; } return nullptr; } ExampleRef *Example::return_extended_ref() const { return memnew(ExampleRef()); } Ref<ExampleRef> Example::extended_ref_checks(Ref<ExampleRef> p_ref) const { Ref<ExampleRef> ref; ref.instantiate(); // TODO the returned value gets dereferenced too early and return a null object otherwise. ref->reference(); UtilityFunctions::print(" Example ref checks called with value: ", p_ref->get_instance_id(), ", returning value: ", ref->get_instance_id()); return ref; } Variant Example::varargs_func(const Variant **args, GDNativeInt arg_count, GDNativeCallError &error) { UtilityFunctions::print(" Varargs (Variant return) called with ", String::num((double)arg_count), " arguments"); return arg_count; } int Example::varargs_func_nv(const Variant **args, GDNativeInt arg_count, GDNativeCallError &error) { UtilityFunctions::print(" Varargs (int return) called with ", String::num((double)arg_count), " arguments"); return 42; } void Example::varargs_func_void(const Variant **args, GDNativeInt arg_count, GDNativeCallError &error) { UtilityFunctions::print(" Varargs (no return) called with ", String::num((double)arg_count), " arguments"); } void Example::emit_custom_signal(const String &name, int value) { emit_signal("custom_signal", name, value); } Array Example::test_array() const { Array arr; arr.resize(2); arr[0] = Variant(1); arr[1] = Variant(2); return arr; } void Example::test_tarray_arg(const TypedArray<int64_t> &p_array) { for (int i = 0; i < p_array.size(); i++) { UtilityFunctions::print(p_array[i]); } } TypedArray<Vector2> Example::test_tarray() const { TypedArray<Vector2> arr; arr.resize(2); arr[0] = Vector2(1, 2); arr[1] = Vector2(2, 3); return arr; } Dictionary Example::test_dictionary() const { Dictionary dict; dict["hello"] = "world"; dict["foo"] = "bar"; return dict; } // Properties. void Example::set_custom_position(const Vector2 &pos) { custom_position = pos; } Vector2 Example::get_custom_position() const { return custom_position; } Vector4 Example::get_v4() const { return Vector4(1.2, 3.4, 5.6, 7.8); } // Virtual function override. bool Example::_has_point(const Vector2 &point) const { Label *label = get_node<Label>("Label"); label->set_text("Got point: " + Variant(point).stringify()); return false; } <|endoftext|>
<commit_before>#include <filter.hpp> #include "helpers.hpp" #include <vector> #include <string> #include <iterator> #include "catch.hpp" using iter::filter; using Vec = const std::vector<int>; namespace { bool less_than_five(int i) { return i < 5; } class LessThanValue { private: int compare_val; public: LessThanValue(int v) : compare_val(v) {} bool operator()(int i) { return i < this->compare_val; } }; } TEST_CASE("filter: handles different functor types", "[filter]") { Vec ns = {1, 2, 5, 6, 3, 1, 7, -1, 5}; Vec vc = {1, 2, 3, 1, -1}; SECTION("with function pointer") { auto f = filter(less_than_five, ns); Vec v(std::begin(f), std::end(f)); REQUIRE(v == vc); } SECTION("with callable object") { auto f = filter(LessThanValue{5}, ns); Vec v(std::begin(f), std::end(f)); REQUIRE(v == vc); } SECTION("with lambda") { auto ltf = [](int i) { return i < 5; }; auto f = filter(ltf, ns); Vec v(std::begin(f), std::end(f)); REQUIRE(v == vc); } } TEST_CASE("filter: iterator with lambda can be assigned", "[filter]") { Vec ns{}; auto ltf = [](int i) { return i < 5; }; auto f = filter(ltf, ns); auto it = std::begin(f); it = std::begin(f); } TEST_CASE("filter: using identity", "[filter]") { Vec ns{0, 1, 2, 0, 3, 0, 0, 0, 4, 5, 0}; auto f = filter(ns); Vec v(std::begin(f), std::end(f)); Vec vc = {1, 2, 3, 4, 5}; REQUIRE(v == vc); } TEST_CASE("filter: skips null pointers", "[filter]") { int a = 1; int b = 2; const std::vector<int*> ns = {0, &a, nullptr, nullptr, &b, nullptr}; auto f = filter(ns); const std::vector<int*> v(std::begin(f), std::end(f)); const std::vector<int*> vc = {&a, &b}; REQUIRE(v == vc); } TEST_CASE("filter: binds to lvalues, moves rvales", "[filter]") { itertest::BasicIterable<int> bi{1, 2, 3, 4}; SECTION("one-arg binds to lvalues") { filter(bi); REQUIRE_FALSE(bi.was_moved_from()); } SECTION("two-arg binds to lvalues") { filter(less_than_five, bi); REQUIRE_FALSE(bi.was_moved_from()); } SECTION("one-arg moves rvalues") { filter(std::move(bi)); REQUIRE(bi.was_moved_from()); } SECTION("two-arg moves rvalues") { filter(less_than_five, std::move(bi)); REQUIRE(bi.was_moved_from()); } } TEST_CASE("filter: operator->", "[filter]") { std::vector<std::string> vs = {"ab", "abc", "abcdef"}; auto f = filter([](const std::string& str) { return str.size() > 4; }, vs); auto it = std::begin(f); REQUIRE(it->size() == 6); } TEST_CASE("filter: all elements fail predicate", "[filter]") { Vec ns{10, 20, 30, 40, 50}; auto f = filter(less_than_five, ns); REQUIRE(std::begin(f) == std::end(f)); } TEST_CASE("filter: doesn't move or copy elements of iterable", "[filter]") { constexpr itertest::SolidInt arr[] = {{1}, {0}, {2}}; for (auto&& i : filter([](const itertest::SolidInt& si) { return si.getint(); }, arr)) { (void)i; } } TEST_CASE("filter: works with pipe", "[filter]") { Vec ns = {1, 2, 5, 6, 3, 1, 7, -1, 5}; Vec vc = {1, 2, 3, 1, -1}; auto f = ns | filter(LessThanValue{5}); Vec v(std::begin(f), std::end(f)); REQUIRE(v == vc); } TEST_CASE("filter: works with initializer_list", "[filter]") { auto f = filter(LessThanValue{5}, {1, 2, 5, 6, 3, 1, 7, -1, 5}); Vec v(std::begin(f), std::end(f)); Vec vc = {1, 2, 3, 1, -1}; REQUIRE(v == vc); auto f2 = filter({1, 2, 5, 6, 3, 1, 7, -1, 5}); Vec v2(std::begin(f2), std::end(f2)); } TEST_CASE("filter: using identity and pipe", "[filter]") { Vec ns{0, 1, 2, 0, 3, 0, 0, 0, 4, 5, 0}; auto f = ns | filter; Vec v(std::begin(f), std::end(f)); Vec vc = {1, 2, 3, 4, 5}; REQUIRE(v == vc); } TEST_CASE("filter: iterator meets requirements", "[filter]") { std::string s{}; auto c = filter([] { return true; }, s); REQUIRE(itertest::IsIterator<decltype(std::begin(c))>::value); } template <typename T, typename U> using ImpT = decltype(filter(std::declval<T>(), std::declval<U>())); TEST_CASE("filter: has correct ctor and assign ops", "[filter]") { using T1 = ImpT<bool (*)(char c), std::string&>; auto lam = [](char) { return false; }; using T2 = ImpT<decltype(lam), std::string>; REQUIRE(itertest::IsMoveConstructibleOnly<T1>::value); REQUIRE(itertest::IsMoveConstructibleOnly<T2>::value); } <commit_msg>removes filter init list test<commit_after>#include <filter.hpp> #include "helpers.hpp" #include <vector> #include <string> #include <iterator> #include "catch.hpp" using iter::filter; using Vec = const std::vector<int>; namespace { bool less_than_five(int i) { return i < 5; } class LessThanValue { private: int compare_val; public: LessThanValue(int v) : compare_val(v) {} bool operator()(int i) { return i < this->compare_val; } }; } TEST_CASE("filter: handles different functor types", "[filter]") { Vec ns = {1, 2, 5, 6, 3, 1, 7, -1, 5}; Vec vc = {1, 2, 3, 1, -1}; SECTION("with function pointer") { auto f = filter(less_than_five, ns); Vec v(std::begin(f), std::end(f)); REQUIRE(v == vc); } SECTION("with callable object") { auto f = filter(LessThanValue{5}, ns); Vec v(std::begin(f), std::end(f)); REQUIRE(v == vc); } SECTION("with lambda") { auto ltf = [](int i) { return i < 5; }; auto f = filter(ltf, ns); Vec v(std::begin(f), std::end(f)); REQUIRE(v == vc); } } TEST_CASE("filter: iterator with lambda can be assigned", "[filter]") { Vec ns{}; auto ltf = [](int i) { return i < 5; }; auto f = filter(ltf, ns); auto it = std::begin(f); it = std::begin(f); } TEST_CASE("filter: using identity", "[filter]") { Vec ns{0, 1, 2, 0, 3, 0, 0, 0, 4, 5, 0}; auto f = filter(ns); Vec v(std::begin(f), std::end(f)); Vec vc = {1, 2, 3, 4, 5}; REQUIRE(v == vc); } TEST_CASE("filter: skips null pointers", "[filter]") { int a = 1; int b = 2; const std::vector<int*> ns = {0, &a, nullptr, nullptr, &b, nullptr}; auto f = filter(ns); const std::vector<int*> v(std::begin(f), std::end(f)); const std::vector<int*> vc = {&a, &b}; REQUIRE(v == vc); } TEST_CASE("filter: binds to lvalues, moves rvales", "[filter]") { itertest::BasicIterable<int> bi{1, 2, 3, 4}; SECTION("one-arg binds to lvalues") { filter(bi); REQUIRE_FALSE(bi.was_moved_from()); } SECTION("two-arg binds to lvalues") { filter(less_than_five, bi); REQUIRE_FALSE(bi.was_moved_from()); } SECTION("one-arg moves rvalues") { filter(std::move(bi)); REQUIRE(bi.was_moved_from()); } SECTION("two-arg moves rvalues") { filter(less_than_five, std::move(bi)); REQUIRE(bi.was_moved_from()); } } TEST_CASE("filter: operator->", "[filter]") { std::vector<std::string> vs = {"ab", "abc", "abcdef"}; auto f = filter([](const std::string& str) { return str.size() > 4; }, vs); auto it = std::begin(f); REQUIRE(it->size() == 6); } TEST_CASE("filter: all elements fail predicate", "[filter]") { Vec ns{10, 20, 30, 40, 50}; auto f = filter(less_than_five, ns); REQUIRE(std::begin(f) == std::end(f)); } TEST_CASE("filter: doesn't move or copy elements of iterable", "[filter]") { constexpr itertest::SolidInt arr[] = {{1}, {0}, {2}}; for (auto&& i : filter([](const itertest::SolidInt& si) { return si.getint(); }, arr)) { (void)i; } } TEST_CASE("filter: works with pipe", "[filter]") { Vec ns = {1, 2, 5, 6, 3, 1, 7, -1, 5}; Vec vc = {1, 2, 3, 1, -1}; auto f = ns | filter(LessThanValue{5}); Vec v(std::begin(f), std::end(f)); REQUIRE(v == vc); } TEST_CASE("filter: using identity and pipe", "[filter]") { Vec ns{0, 1, 2, 0, 3, 0, 0, 0, 4, 5, 0}; auto f = ns | filter; Vec v(std::begin(f), std::end(f)); Vec vc = {1, 2, 3, 4, 5}; REQUIRE(v == vc); } TEST_CASE("filter: iterator meets requirements", "[filter]") { std::string s{}; auto c = filter([] { return true; }, s); REQUIRE(itertest::IsIterator<decltype(std::begin(c))>::value); } template <typename T, typename U> using ImpT = decltype(filter(std::declval<T>(), std::declval<U>())); TEST_CASE("filter: has correct ctor and assign ops", "[filter]") { using T1 = ImpT<bool (*)(char c), std::string&>; auto lam = [](char) { return false; }; using T2 = ImpT<decltype(lam), std::string>; REQUIRE(itertest::IsMoveConstructibleOnly<T1>::value); REQUIRE(itertest::IsMoveConstructibleOnly<T2>::value); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: localfilehelper.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: hr $ $Date: 2006-06-19 14:09:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTACCESS_HPP_ #include <com/sun/star/ucb/XContentAccess.hpp> #endif #ifndef _COM_SUN_STAR_UCB_COMMANDABORTEDEXCEPTION_HPP_ #include <com/sun/star/ucb/CommandAbortedException.hpp> #endif #include <unotools/localfilehelper.hxx> #include <ucbhelper/fileidentifierconverter.hxx> #include <ucbhelper/contentbroker.hxx> #include <rtl/ustring.hxx> #include <osl/file.hxx> #include <tools/debug.hxx> #include <tools/list.hxx> #include <tools/urlobj.hxx> #include <ucbhelper/content.hxx> using namespace ::osl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ucb; namespace utl { sal_Bool LocalFileHelper::ConvertSystemPathToURL( const String& rName, const String& rBaseURL, String& rReturn ) { rReturn = ::rtl::OUString(); ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get(); if ( !pBroker ) { rtl::OUString aRet; if ( FileBase::getFileURLFromSystemPath( rName, aRet ) == FileBase::E_None ) rReturn = aRet; } else { ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager = pBroker->getContentProviderManagerInterface(); try { rReturn = ::ucb::getFileURLFromSystemPath( xManager, rBaseURL, rName ); } catch ( ::com::sun::star::uno::RuntimeException& ) { return sal_False; } } return ( rReturn.Len() != 0 ); } sal_Bool LocalFileHelper::ConvertURLToSystemPath( const String& rName, String& rReturn ) { rReturn = ::rtl::OUString(); ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get(); if ( !pBroker ) { rtl::OUString aRet; if( FileBase::getSystemPathFromFileURL( rName, aRet ) == FileBase::E_None ) rReturn = aRet; } else { ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager = pBroker->getContentProviderManagerInterface(); try { rReturn = ::ucb::getSystemPathFromFileURL( xManager, rName ); } catch ( ::com::sun::star::uno::RuntimeException& ) { } } return ( rReturn.Len() != 0 ); } sal_Bool LocalFileHelper::ConvertPhysicalNameToURL( const String& rName, String& rReturn ) { rReturn = ::rtl::OUString(); ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get(); if ( !pBroker ) { rtl::OUString aRet; if ( FileBase::getFileURLFromSystemPath( rName, aRet ) == FileBase::E_None ) rReturn = aRet; } else { ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager = pBroker->getContentProviderManagerInterface(); try { rtl::OUString aBase( ::ucb::getLocalFileURL( xManager ) ); rReturn = ::ucb::getFileURLFromSystemPath( xManager, aBase, rName ); } catch ( ::com::sun::star::uno::RuntimeException& ) { } } return ( rReturn.Len() != 0 ); } sal_Bool LocalFileHelper::ConvertURLToPhysicalName( const String& rName, String& rReturn ) { rReturn = ::rtl::OUString(); ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get(); if ( !pBroker ) { ::rtl::OUString aRet; if ( FileBase::getSystemPathFromFileURL( rName, aRet ) == FileBase::E_None ) rReturn = aRet; } else { ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager = pBroker->getContentProviderManagerInterface(); try { INetURLObject aObj( rName ); INetURLObject aLocal( ::ucb::getLocalFileURL( xManager ) ); if ( aObj.GetProtocol() == aLocal.GetProtocol() ) rReturn = ::ucb::getSystemPathFromFileURL( xManager, rName ); } catch ( ::com::sun::star::uno::RuntimeException& ) { } } return ( rReturn.Len() != 0 ); } sal_Bool LocalFileHelper::IsLocalFile( const String& rName ) { String aTmp; return ConvertURLToPhysicalName( rName, aTmp ); } sal_Bool LocalFileHelper::IsFileContent( const String& rName ) { String aTmp; return ConvertURLToSystemPath( rName, aTmp ); } DECLARE_LIST( StringList_Impl, ::rtl::OUString* ) ::com::sun::star::uno::Sequence < ::rtl::OUString > LocalFileHelper::GetFolderContents( const ::rtl::OUString& rFolder, sal_Bool bFolder ) { StringList_Impl* pFiles = NULL; try { ::ucb::Content aCnt( rFolder, Reference< XCommandEnvironment > () ); Reference< ::com::sun::star::sdbc::XResultSet > xResultSet; ::com::sun::star::uno::Sequence< ::rtl::OUString > aProps(1); ::rtl::OUString* pProps = aProps.getArray(); pProps[0] = ::rtl::OUString::createFromAscii( "Url" ); try { ::ucb::ResultSetInclude eInclude = bFolder ? ::ucb::INCLUDE_FOLDERS_AND_DOCUMENTS : ::ucb::INCLUDE_DOCUMENTS_ONLY; xResultSet = aCnt.createCursor( aProps, eInclude ); } catch( ::com::sun::star::ucb::CommandAbortedException& ) { } catch( Exception& ) { } if ( xResultSet.is() ) { pFiles = new StringList_Impl; Reference< XContentAccess > xContentAccess( xResultSet, UNO_QUERY ); try { while ( xResultSet->next() ) { ::rtl::OUString aId = xContentAccess->queryContentIdentifierString(); ::rtl::OUString* pFile = new ::rtl::OUString( aId ); pFiles->Insert( pFile, LIST_APPEND ); } } catch( ::com::sun::star::ucb::CommandAbortedException& ) { } catch( Exception& ) { } } } catch( Exception& ) { } if ( pFiles ) { ULONG nCount = pFiles->Count(); Sequence < ::rtl::OUString > aRet( nCount ); ::rtl::OUString* pRet = aRet.getArray(); for ( USHORT i = 0; i < nCount; ++i ) { ::rtl::OUString* pFile = pFiles->GetObject(i); pRet[i] = *( pFile ); delete pFile; } delete pFiles; return aRet; } else return Sequence < ::rtl::OUString > (); } } <commit_msg>INTEGRATION: CWS pchfix02 (1.16.16); FILE MERGED 2006/09/01 17:56:25 kaib 1.16.16.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: localfilehelper.cxx,v $ * * $Revision: 1.17 $ * * last change: $Author: obo $ $Date: 2006-09-17 01:29:27 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_unotools.hxx" #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTACCESS_HPP_ #include <com/sun/star/ucb/XContentAccess.hpp> #endif #ifndef _COM_SUN_STAR_UCB_COMMANDABORTEDEXCEPTION_HPP_ #include <com/sun/star/ucb/CommandAbortedException.hpp> #endif #include <unotools/localfilehelper.hxx> #include <ucbhelper/fileidentifierconverter.hxx> #include <ucbhelper/contentbroker.hxx> #include <rtl/ustring.hxx> #include <osl/file.hxx> #include <tools/debug.hxx> #include <tools/list.hxx> #include <tools/urlobj.hxx> #include <ucbhelper/content.hxx> using namespace ::osl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ucb; namespace utl { sal_Bool LocalFileHelper::ConvertSystemPathToURL( const String& rName, const String& rBaseURL, String& rReturn ) { rReturn = ::rtl::OUString(); ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get(); if ( !pBroker ) { rtl::OUString aRet; if ( FileBase::getFileURLFromSystemPath( rName, aRet ) == FileBase::E_None ) rReturn = aRet; } else { ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager = pBroker->getContentProviderManagerInterface(); try { rReturn = ::ucb::getFileURLFromSystemPath( xManager, rBaseURL, rName ); } catch ( ::com::sun::star::uno::RuntimeException& ) { return sal_False; } } return ( rReturn.Len() != 0 ); } sal_Bool LocalFileHelper::ConvertURLToSystemPath( const String& rName, String& rReturn ) { rReturn = ::rtl::OUString(); ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get(); if ( !pBroker ) { rtl::OUString aRet; if( FileBase::getSystemPathFromFileURL( rName, aRet ) == FileBase::E_None ) rReturn = aRet; } else { ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager = pBroker->getContentProviderManagerInterface(); try { rReturn = ::ucb::getSystemPathFromFileURL( xManager, rName ); } catch ( ::com::sun::star::uno::RuntimeException& ) { } } return ( rReturn.Len() != 0 ); } sal_Bool LocalFileHelper::ConvertPhysicalNameToURL( const String& rName, String& rReturn ) { rReturn = ::rtl::OUString(); ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get(); if ( !pBroker ) { rtl::OUString aRet; if ( FileBase::getFileURLFromSystemPath( rName, aRet ) == FileBase::E_None ) rReturn = aRet; } else { ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager = pBroker->getContentProviderManagerInterface(); try { rtl::OUString aBase( ::ucb::getLocalFileURL( xManager ) ); rReturn = ::ucb::getFileURLFromSystemPath( xManager, aBase, rName ); } catch ( ::com::sun::star::uno::RuntimeException& ) { } } return ( rReturn.Len() != 0 ); } sal_Bool LocalFileHelper::ConvertURLToPhysicalName( const String& rName, String& rReturn ) { rReturn = ::rtl::OUString(); ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get(); if ( !pBroker ) { ::rtl::OUString aRet; if ( FileBase::getSystemPathFromFileURL( rName, aRet ) == FileBase::E_None ) rReturn = aRet; } else { ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager = pBroker->getContentProviderManagerInterface(); try { INetURLObject aObj( rName ); INetURLObject aLocal( ::ucb::getLocalFileURL( xManager ) ); if ( aObj.GetProtocol() == aLocal.GetProtocol() ) rReturn = ::ucb::getSystemPathFromFileURL( xManager, rName ); } catch ( ::com::sun::star::uno::RuntimeException& ) { } } return ( rReturn.Len() != 0 ); } sal_Bool LocalFileHelper::IsLocalFile( const String& rName ) { String aTmp; return ConvertURLToPhysicalName( rName, aTmp ); } sal_Bool LocalFileHelper::IsFileContent( const String& rName ) { String aTmp; return ConvertURLToSystemPath( rName, aTmp ); } DECLARE_LIST( StringList_Impl, ::rtl::OUString* ) ::com::sun::star::uno::Sequence < ::rtl::OUString > LocalFileHelper::GetFolderContents( const ::rtl::OUString& rFolder, sal_Bool bFolder ) { StringList_Impl* pFiles = NULL; try { ::ucb::Content aCnt( rFolder, Reference< XCommandEnvironment > () ); Reference< ::com::sun::star::sdbc::XResultSet > xResultSet; ::com::sun::star::uno::Sequence< ::rtl::OUString > aProps(1); ::rtl::OUString* pProps = aProps.getArray(); pProps[0] = ::rtl::OUString::createFromAscii( "Url" ); try { ::ucb::ResultSetInclude eInclude = bFolder ? ::ucb::INCLUDE_FOLDERS_AND_DOCUMENTS : ::ucb::INCLUDE_DOCUMENTS_ONLY; xResultSet = aCnt.createCursor( aProps, eInclude ); } catch( ::com::sun::star::ucb::CommandAbortedException& ) { } catch( Exception& ) { } if ( xResultSet.is() ) { pFiles = new StringList_Impl; Reference< XContentAccess > xContentAccess( xResultSet, UNO_QUERY ); try { while ( xResultSet->next() ) { ::rtl::OUString aId = xContentAccess->queryContentIdentifierString(); ::rtl::OUString* pFile = new ::rtl::OUString( aId ); pFiles->Insert( pFile, LIST_APPEND ); } } catch( ::com::sun::star::ucb::CommandAbortedException& ) { } catch( Exception& ) { } } } catch( Exception& ) { } if ( pFiles ) { ULONG nCount = pFiles->Count(); Sequence < ::rtl::OUString > aRet( nCount ); ::rtl::OUString* pRet = aRet.getArray(); for ( USHORT i = 0; i < nCount; ++i ) { ::rtl::OUString* pFile = pFiles->GetObject(i); pRet[i] = *( pFile ); delete pFile; } delete pFiles; return aRet; } else return Sequence < ::rtl::OUString > (); } } <|endoftext|>
<commit_before>/* * Source MUD * Copyright (C) 2000-2005 Sean Middleditch * See the file COPYING for license details * http://www.sourcemud.org */ #include <assert.h> #include "mud/efactory.h" #include "common/log.h" #include "mud/entity.h" SEntityFactoryManager EntityFactoryManager; SEntityFactoryManager::FactoryList* SEntityFactoryManager::factories = 0; int SEntityFactoryManager::initialize () { return 0; } void SEntityFactoryManager::shutdown () { } void SEntityFactoryManager::register_factory (const IEntityFactory* factory) { assert(factory != NULL); if (factories == 0) factories = new FactoryList(); factories->insert(std::pair<std::string, const IEntityFactory*>(strlower(factory->get_name()), factory)); } Entity* SEntityFactoryManager::create (std::string name) const { assert(factories != NULL); // find factory FactoryList::const_iterator i = factories->find(name); if (i == factories->end()) { Log::Warning << "Factory not found: " << name; return NULL; } // invoke return i->second->create(); } Entity* Entity::create (std::string name) { return EntityFactoryManager.create(name); } <commit_msg>free memory<commit_after>/* * Source MUD * Copyright (C) 2000-2005 Sean Middleditch * See the file COPYING for license details * http://www.sourcemud.org */ #include <assert.h> #include "mud/efactory.h" #include "common/log.h" #include "mud/entity.h" SEntityFactoryManager EntityFactoryManager; SEntityFactoryManager::FactoryList* SEntityFactoryManager::factories = 0; int SEntityFactoryManager::initialize () { return 0; } void SEntityFactoryManager::shutdown () { delete factories; } void SEntityFactoryManager::register_factory (const IEntityFactory* factory) { assert(factory != NULL); if (factories == 0) factories = new FactoryList(); factories->insert(std::pair<std::string, const IEntityFactory*>(strlower(factory->get_name()), factory)); } Entity* SEntityFactoryManager::create (std::string name) const { assert(factories != NULL); // find factory FactoryList::const_iterator i = factories->find(name); if (i == factories->end()) { Log::Warning << "Factory not found: " << name; return NULL; } // invoke return i->second->create(); } Entity* Entity::create (std::string name) { return EntityFactoryManager.create(name); } <|endoftext|>
<commit_before>/* Copyright 2015-2018 Egor Yusov * * 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 * * 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 OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include <queue> #include <mutex> #include "SampleApp.h" #include "AntTweakBar.h" using namespace Diligent; class SampleAppMacOS final : public SampleApp { public: SampleAppMacOS() { m_DeviceType = DeviceType::OpenGL; } virtual void Initialize(void* view)override final { m_DeviceType = view == nullptr ? DeviceType::OpenGL : DeviceType::Vulkan; InitializeDiligentEngine(view); m_TheSample->SetUIScale(2); InitializeSample(); } virtual void Render()override { std::lock_guard<std::mutex> lock(AppMutex); m_pImmediateContext->SetRenderTargets(0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); // Handle all TwBar events here as the event handlers call draw commands // and thus cannot be used in the UI thread while(!TwBarEvents.empty()) { const auto& event = TwBarEvents.front(); switch (event.type) { case TwEvent::LMB_PRESSED: case TwEvent::RMB_PRESSED: TwMouseButton(TW_MOUSE_PRESSED, event.type == TwEvent::LMB_PRESSED ? TW_MOUSE_LEFT : TW_MOUSE_RIGHT); break; case TwEvent::LMB_RELEASED: case TwEvent::RMB_RELEASED: TwMouseButton(TW_MOUSE_RELEASED, event.type == TwEvent::LMB_RELEASED ? TW_MOUSE_LEFT : TW_MOUSE_RIGHT); break; case TwEvent::MOUSE_MOVE: TwMouseMotion(event.mouseX, event.mouseY); break; case TwEvent::KEY_PRESSED: TwKeyPressed(event.key, 0); break; } TwBarEvents.pop(); } SampleApp::Render(); } virtual void Update(double CurrTime, double ElapsedTime)override { std::lock_guard<std::mutex> lock(AppMutex); SampleApp::Update(CurrTime, ElapsedTime); } virtual void WindowResize(int width, int height)override { std::lock_guard<std::mutex> lock(AppMutex); SampleApp::WindowResize(width, height); } virtual void Present()override { std::lock_guard<std::mutex> lock(AppMutex); SampleApp::Present(); } void OnMouseDown(int button)override final { std::lock_guard<std::mutex> lock(AppMutex); TwBarEvents.emplace(button == 1 ? TwEvent::LMB_PRESSED : TwEvent::RMB_PRESSED); } void OnMouseUp(int button)override final { std::lock_guard<std::mutex> lock(AppMutex); TwBarEvents.emplace(button == 1 ? TwEvent::LMB_RELEASED : TwEvent::RMB_RELEASED); } void OnMouseMove(int x, int y)override final { std::lock_guard<std::mutex> lock(AppMutex); TwBarEvents.emplace(x, y); } void OnKeyPressed(int key)override final { std::lock_guard<std::mutex> lock(AppMutex); TwBarEvents.emplace(key); } private: // Render functions are called from high-priority Display Link thread, // so all methods must be protected by mutex std::mutex AppMutex; // Unfortunately TwBar library calls rendering // functions from event handlers, which does not work on MacOS // as UI events and rendering are handled by separate threads struct TwEvent { enum EVENT_TYPE { LMB_PRESSED, LMB_RELEASED, RMB_PRESSED, RMB_RELEASED, MOUSE_MOVE, KEY_PRESSED }type; int mouseX = 0; int mouseY = 0; int key = 0; TwEvent(EVENT_TYPE _type) : type(_type){} TwEvent(int x, int y) : type(MOUSE_MOVE), mouseX(x), mouseY(y){} TwEvent(int k) : type(KEY_PRESSED), key(k){} }; std::queue<TwEvent> TwBarEvents; }; NativeAppBase* CreateApplication() { return new SampleAppMacOS; } <commit_msg>Updated coyright notice<commit_after>/* Copyright 2015-2019 Egor Yusov * * 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 * * 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 OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include <queue> #include <mutex> #include "SampleApp.h" #include "AntTweakBar.h" using namespace Diligent; class SampleAppMacOS final : public SampleApp { public: SampleAppMacOS() { m_DeviceType = DeviceType::OpenGL; } virtual void Initialize(void* view)override final { m_DeviceType = view == nullptr ? DeviceType::OpenGL : DeviceType::Vulkan; InitializeDiligentEngine(view); m_TheSample->SetUIScale(2); InitializeSample(); } virtual void Render()override { std::lock_guard<std::mutex> lock(AppMutex); m_pImmediateContext->SetRenderTargets(0, nullptr, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); // Handle all TwBar events here as the event handlers call draw commands // and thus cannot be used in the UI thread while(!TwBarEvents.empty()) { const auto& event = TwBarEvents.front(); switch (event.type) { case TwEvent::LMB_PRESSED: case TwEvent::RMB_PRESSED: TwMouseButton(TW_MOUSE_PRESSED, event.type == TwEvent::LMB_PRESSED ? TW_MOUSE_LEFT : TW_MOUSE_RIGHT); break; case TwEvent::LMB_RELEASED: case TwEvent::RMB_RELEASED: TwMouseButton(TW_MOUSE_RELEASED, event.type == TwEvent::LMB_RELEASED ? TW_MOUSE_LEFT : TW_MOUSE_RIGHT); break; case TwEvent::MOUSE_MOVE: TwMouseMotion(event.mouseX, event.mouseY); break; case TwEvent::KEY_PRESSED: TwKeyPressed(event.key, 0); break; } TwBarEvents.pop(); } SampleApp::Render(); } virtual void Update(double CurrTime, double ElapsedTime)override { std::lock_guard<std::mutex> lock(AppMutex); SampleApp::Update(CurrTime, ElapsedTime); } virtual void WindowResize(int width, int height)override { std::lock_guard<std::mutex> lock(AppMutex); SampleApp::WindowResize(width, height); } virtual void Present()override { std::lock_guard<std::mutex> lock(AppMutex); SampleApp::Present(); } void OnMouseDown(int button)override final { std::lock_guard<std::mutex> lock(AppMutex); TwBarEvents.emplace(button == 1 ? TwEvent::LMB_PRESSED : TwEvent::RMB_PRESSED); } void OnMouseUp(int button)override final { std::lock_guard<std::mutex> lock(AppMutex); TwBarEvents.emplace(button == 1 ? TwEvent::LMB_RELEASED : TwEvent::RMB_RELEASED); } void OnMouseMove(int x, int y)override final { std::lock_guard<std::mutex> lock(AppMutex); TwBarEvents.emplace(x, y); } void OnKeyPressed(int key)override final { std::lock_guard<std::mutex> lock(AppMutex); TwBarEvents.emplace(key); } private: // Render functions are called from high-priority Display Link thread, // so all methods must be protected by mutex std::mutex AppMutex; // Unfortunately TwBar library calls rendering // functions from event handlers, which does not work on MacOS // as UI events and rendering are handled by separate threads struct TwEvent { enum EVENT_TYPE { LMB_PRESSED, LMB_RELEASED, RMB_PRESSED, RMB_RELEASED, MOUSE_MOVE, KEY_PRESSED }type; int mouseX = 0; int mouseY = 0; int key = 0; TwEvent(EVENT_TYPE _type) : type(_type){} TwEvent(int x, int y) : type(MOUSE_MOVE), mouseX(x), mouseY(y){} TwEvent(int k) : type(KEY_PRESSED), key(k){} }; std::queue<TwEvent> TwBarEvents; }; NativeAppBase* CreateApplication() { return new SampleAppMacOS; } <|endoftext|>
<commit_before>#include "dialect.hpp" #include <boost/assert.hpp> #include <bitcoin/net/messages.hpp> #include <bitcoin/util/assert.hpp> #include <bitcoin/util/logger.hpp> namespace libbitcoin { namespace net { serializer::stream construct_header_from(serializer::stream payload, std::string command) { serializer header; // magic header.write_4_bytes(0xd9b4bef9); // command header.write_command(command); // payload length uint32_t length = payload.size(); header.write_4_bytes(length); // checksum is not in verson or verack if (command != "version" && command != "verack") { //uint32_t checksum = 0; //write_to_stream(header, checksum); } return header.get_data(); } serializer::stream header_only_message(std::string command) { serializer payload; serializer::stream msg_body = payload.get_data(); // No data serializer::stream header = construct_header_from(msg_body, "verack"); return header; } serializer::stream original_dialect::to_network( message::version version) const { serializer payload; payload.write_4_bytes(version.version); payload.write_8_bytes(version.services); payload.write_8_bytes(version.timestamp); payload.write_net_addr(version.addr_me); payload.write_net_addr(version.addr_you); payload.write_8_bytes(version.nonce); // do sub_version_num payload.write_byte(0); payload.write_4_bytes(version.start_height); serializer::stream msg_body = payload.get_data(); serializer::stream message = construct_header_from(msg_body, "version"); // Extend message with actual payload message.reserve(message.size() + distance(msg_body.begin(), msg_body.end())); message.insert(message.end(), msg_body.begin(), msg_body.end()); return message; } serializer::stream original_dialect::to_network(message::verack verack) const { return header_only_message("verack"); } serializer::stream original_dialect::to_network(message::getaddr getaddr) const { return header_only_message("getaddr"); } message::header original_dialect::header_from_network( const serializer::stream& stream) const { deserializer deserial(stream); message::header header; header.magic = deserial.read_4_bytes(); header.command = deserial.read_fixed_len_str(12); header.payload_length = deserial.read_4_bytes(); return header; } message::version original_dialect::version_from_network( const message::header header_msg, const serializer::stream& stream, bool& ec) const { ec = false; deserializer deserial(stream); message::version payload; payload.version = deserial.read_4_bytes(); payload.services = deserial.read_8_bytes(); payload.timestamp = deserial.read_8_bytes(); payload.addr_me = deserial.read_net_addr(); if (payload.version < 106) { BITCOIN_ASSERT(stream.size() == 4 + 8 + 8 + 26); return payload; } payload.addr_you = deserial.read_net_addr(); payload.nonce = deserial.read_8_bytes(); // sub_version_num payload.sub_version_num = deserial.read_byte(); if (payload.version < 209) { BITCOIN_ASSERT(stream.size() == 4 + 8 + 8 + 26 + 26 + 8 + 1); return payload; } payload.start_height = deserial.read_4_bytes(); BITCOIN_ASSERT(stream.size() == 4 + 8 + 8 + 26 + 26 + 8 + 1 + 4); return payload; } message::addr original_dialect::addr_from_network( const message::header header_msg, const serializer::stream& stream, bool& ec) const { ec = false; deserializer deserial(stream); message::addr payload; uint64_t count = deserial.read_var_uint(); for (size_t i = 0; i < count; ++i) { message::net_addr addr = deserial.read_net_addr(); payload.addr_list.push_back(addr); } return payload; } message::inv original_dialect::inv_from_network( const message::header header_msg, const serializer::stream& stream, bool& ec) const { ec = false; deserializer deserial(stream); message::inv payload; uint64_t count = deserial.read_var_uint(); for (size_t i = 0; i < count; ++i) { message::inv_vect inv_vect; uint32_t raw_type = deserial.read_4_bytes(); switch (raw_type) { case 0: inv_vect.type = message::inv_type::error; break; case 1: inv_vect.type = message::inv_type::transaction; break; case 2: inv_vect.type = message::inv_type::block; break; default: inv_vect.type = message::inv_type::none; break; } inv_vect.hash = deserial.read_hash(); payload.inv_list.push_back(inv_vect); } return payload; } bool original_dialect::verify_header(net::message::header header_msg) const { if (header_msg.magic != 0xd9b4bef9) return false; if (header_msg.command == "version") { if (header_msg.payload_length != 85) return false; } else if (header_msg.command == "verack" || header_msg.command == "getaddr" || header_msg.command == "ping") { if (header_msg.payload_length != 0) return false; } else if (header_msg.command == "inv" || header_msg.command == "addr" || header_msg.command == "getdata" || header_msg.command == "getblocks" || header_msg.command == "getheaders" || header_msg.command == "tx" || header_msg.command == "block" || header_msg.command == "headers" || header_msg.command == "alert") { // Should check if sizes make sense // i.e for addr should be multiple of 30x + 1 byte // Also then add ASSERTS to handlers above. } else { // Unknown header return false; } return true; } } // net } // libbitcoin <commit_msg>read timestamp from addr packet.<commit_after>#include "dialect.hpp" #include <boost/assert.hpp> #include <bitcoin/net/messages.hpp> #include <bitcoin/util/assert.hpp> #include <bitcoin/util/logger.hpp> namespace libbitcoin { namespace net { serializer::stream construct_header_from(serializer::stream payload, std::string command) { serializer header; // magic header.write_4_bytes(0xd9b4bef9); // command header.write_command(command); // payload length uint32_t length = payload.size(); header.write_4_bytes(length); // checksum is not in verson or verack if (command != "version" && command != "verack") { //uint32_t checksum = 0; //write_to_stream(header, checksum); } return header.get_data(); } serializer::stream header_only_message(std::string command) { serializer payload; serializer::stream msg_body = payload.get_data(); // No data serializer::stream header = construct_header_from(msg_body, "verack"); return header; } serializer::stream original_dialect::to_network( message::version version) const { serializer payload; payload.write_4_bytes(version.version); payload.write_8_bytes(version.services); payload.write_8_bytes(version.timestamp); payload.write_net_addr(version.addr_me); payload.write_net_addr(version.addr_you); payload.write_8_bytes(version.nonce); // do sub_version_num payload.write_byte(0); payload.write_4_bytes(version.start_height); serializer::stream msg_body = payload.get_data(); serializer::stream message = construct_header_from(msg_body, "version"); // Extend message with actual payload message.reserve(message.size() + distance(msg_body.begin(), msg_body.end())); message.insert(message.end(), msg_body.begin(), msg_body.end()); return message; } serializer::stream original_dialect::to_network(message::verack verack) const { return header_only_message("verack"); } serializer::stream original_dialect::to_network(message::getaddr getaddr) const { return header_only_message("getaddr"); } message::header original_dialect::header_from_network( const serializer::stream& stream) const { deserializer deserial(stream); message::header header; header.magic = deserial.read_4_bytes(); header.command = deserial.read_fixed_len_str(12); header.payload_length = deserial.read_4_bytes(); return header; } message::version original_dialect::version_from_network( const message::header header_msg, const serializer::stream& stream, bool& ec) const { ec = false; deserializer deserial(stream); message::version payload; payload.version = deserial.read_4_bytes(); payload.services = deserial.read_8_bytes(); payload.timestamp = deserial.read_8_bytes(); payload.addr_me = deserial.read_net_addr(); // Ignored field payload.addr_me.timestamp = 0; if (payload.version < 106) { BITCOIN_ASSERT(stream.size() == 4 + 8 + 8 + 26); return payload; } payload.addr_you = deserial.read_net_addr(); // Ignored field payload.addr_you.timestamp = 0; payload.nonce = deserial.read_8_bytes(); // sub_version_num payload.sub_version_num = deserial.read_byte(); if (payload.version < 209) { BITCOIN_ASSERT(stream.size() == 4 + 8 + 8 + 26 + 26 + 8 + 1); return payload; } payload.start_height = deserial.read_4_bytes(); BITCOIN_ASSERT(stream.size() == 4 + 8 + 8 + 26 + 26 + 8 + 1 + 4); return payload; } message::addr original_dialect::addr_from_network( const message::header header_msg, const serializer::stream& stream, bool& ec) const { ec = false; deserializer deserial(stream); message::addr payload; uint64_t count = deserial.read_var_uint(); for (size_t i = 0; i < count; ++i) { uint32_t timestamp = deserial.read_4_bytes(); message::net_addr addr = deserial.read_net_addr(); addr.timestamp = timestamp; payload.addr_list.push_back(addr); } return payload; } message::inv original_dialect::inv_from_network( const message::header header_msg, const serializer::stream& stream, bool& ec) const { ec = false; deserializer deserial(stream); message::inv payload; uint64_t count = deserial.read_var_uint(); for (size_t i = 0; i < count; ++i) { message::inv_vect inv_vect; uint32_t raw_type = deserial.read_4_bytes(); switch (raw_type) { case 0: inv_vect.type = message::inv_type::error; break; case 1: inv_vect.type = message::inv_type::transaction; break; case 2: inv_vect.type = message::inv_type::block; break; default: inv_vect.type = message::inv_type::none; break; } inv_vect.hash = deserial.read_hash(); payload.inv_list.push_back(inv_vect); } return payload; } bool original_dialect::verify_header(net::message::header header_msg) const { if (header_msg.magic != 0xd9b4bef9) return false; if (header_msg.command == "version") { if (header_msg.payload_length != 85) return false; } else if (header_msg.command == "verack" || header_msg.command == "getaddr" || header_msg.command == "ping") { if (header_msg.payload_length != 0) return false; } else if (header_msg.command == "inv" || header_msg.command == "addr" || header_msg.command == "getdata" || header_msg.command == "getblocks" || header_msg.command == "getheaders" || header_msg.command == "tx" || header_msg.command == "block" || header_msg.command == "headers" || header_msg.command == "alert") { // Should check if sizes make sense // i.e for addr should be multiple of 30x + 1 byte // Also then add ASSERTS to handlers above. } else { // Unknown header return false; } return true; } } // net } // libbitcoin <|endoftext|>
<commit_before>#include <iostream> #include <sys/types.h> #include <sys/sysctl.h> #include <sys/socket.h> #include <sys/user.h> #define PF_LIST_INET 1 #ifdef INET6 #define PF_LIST_INET6 2 #endif int main() { int mib[4]; size_t len=4; kinfo_proc kp; std::cout<<sysctlnametomib("kern.proc.pid",mib,&len)<<std::endl; for(int ii=0;ii<100;++ii) { mib[3]=ii; len=sizeof(kp); if(sysctl(mib,4,&kp,&len,NULL,0)==-1) std::cout<<"["<<ii<<"]\tfail"<<std::endl; std::cout<<"["<<ii<<"]\tsuccess"<<std::endl; } return 0; } /*void get_sockets(const char *mib) { void *v; size_t sz; int rc, n, name[CTL_MAXNAME]; u_int namelen; sz = CTL_MAXNAME; rc = sysctlnametomib(mib, &name[0], &sz); if (rc == -1) { if (errno == ENOENT) return; err(1, "sysctlnametomib: %s", mib); } namelen = sz; name[namelen++] = PF_INET; name[namelen++] = 0; // XXX all pids name[namelen++] = 10000 name[namelen++] = INT_MAX; // all of them sysctl_sucker(&name[0], namelen, &v, &sz); n = sz / 10000; socket_add_hash(v, n); } */ <commit_msg>BSD dev...<commit_after>#include <iostream> #include <sys/types.h> #include <sys/sysctl.h> #include <sys/socket.h> #include <sys/user.h> #define PF_LIST_INET 1 #ifdef INET6 #define PF_LIST_INET6 2 #endif int main() { int mib[4]; size_t len=4; kinfo_proc kp; std::cout<<sysctlnametomib("kern.proc.pid",mib,&len)<<std::endl; for(int ii=0;ii<10;++ii) { mib[3]=ii; len=sizeof(kp); if(sysctl(mib,4,&kp,&len,NULL,0)==-1) std::cout<<"["<<ii<<"]\tfail"<<std::endl; std::cout<<"["<<ii<<"]\tsuccess"<<std::endl; } return 0; } /*void get_sockets(const char *mib) { void *v; size_t sz; int rc, n, name[CTL_MAXNAME]; u_int namelen; sz = CTL_MAXNAME; rc = sysctlnametomib(mib, &name[0], &sz); if (rc == -1) { if (errno == ENOENT) return; err(1, "sysctlnametomib: %s", mib); } namelen = sz; name[namelen++] = PF_INET; name[namelen++] = 0; // XXX all pids name[namelen++] = 10000 name[namelen++] = INT_MAX; // all of them sysctl_sucker(&name[0], namelen, &v, &sz); n = sz / 10000; socket_add_hash(v, n); } */ <|endoftext|>
<commit_before>#include <iostream> #include <sys/types.h> #include <sys/param.h> #include <sys/sysctl.h> #include <sys/socket.h> #include <sys/socketvar.h> #include <sys/un.h> #include <netinet/in.h> #include <net/route.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/in_pcb.h> #include <netinet/in_pcb_hdr.h> #include <netinet/tcp_fsm.h> #define PF_LIST_INET 1 #ifdef INET6 #define PF_LIST_INET6 2 #endif void sysctl_sucker(int *name, u_int namelen, void **vp, size_t *szp); void get_sockets(const char *mib); int main() { get_sockets("net.inet6.tcp6.pcblist"); get_sockets("net.inet6.udp6.pcblist"); return 0; } void sysctl_sucker(int *name, u_int namelen, void **vp, size_t *szp) { int rc; void *v; size_t sz; /* printf("name %p, namelen %u\n", name, namelen); */ v = NULL; sz = 0; do { rc = sysctl(&name[0], namelen, v, &sz, NULL, 0); if (rc == -1 && errno != ENOMEM) err(1, "sysctl"); if (rc == -1 && v != NULL) { free(v); v = NULL; } if (v == NULL) { v = malloc(sz); rc = -1; } if (v == NULL) err(1, "malloc"); } while (rc == -1); *vp = v; *szp = sz; /* printf("got %zu at %p\n", sz, v); */ } void get_sockets(const char *mib) { void *v; size_t sz; int rc, n, name[CTL_MAXNAME]; u_int namelen; sz = CTL_MAXNAME; rc = sysctlnametomib(mib, &name[0], &sz); if (rc == -1) { if (errno == ENOENT) return; err(1, "sysctlnametomib: %s", mib); } namelen = sz; name[namelen++] = PCB_ALL; name[namelen++] = 0; /* XXX all pids */ name[namelen++] = sizeof(struct kinfo_pcb); name[namelen++] = INT_MAX; /* all of them */ sysctl_sucker(&name[0], namelen, &v, &sz); n = sz / sizeof(struct kinfo_pcb); socket_add_hash(v, n); }<commit_msg>BSD dev...<commit_after>#include <iostream> #include <sys/types.h> #include <sys/param.h> #include <sys/sysctl.h> #include <sys/socket.h> #include <sys/socketvar.h> #include <sys/un.h> #include <netinet/in.h> #include <net/route.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/in_pcb.h> #include <netinet/in_pcb_hdr.h> #include <netinet/tcp_fsm.h> #include <arpa/inet.h> #include <bitstring.h> #include <ctype.h> #include <err.h> #include <errno.h> #include <netdb.h> #include <pwd.h> #include <stdio.h> #include <strings.h> #include <stdlib.h> #include <unistd.h> #include <util.h> #define PF_LIST_INET 1 #ifdef INET6 #define PF_LIST_INET6 2 #endif void sysctl_sucker(int *name, u_int namelen, void **vp, size_t *szp); void get_sockets(const char *mib); int main() { get_sockets("net.inet6.tcp6.pcblist"); get_sockets("net.inet6.udp6.pcblist"); return 0; } void sysctl_sucker(int *name, u_int namelen, void **vp, size_t *szp) { int rc; void *v; size_t sz; /* printf("name %p, namelen %u\n", name, namelen); */ v = NULL; sz = 0; do { rc = sysctl(&name[0], namelen, v, &sz, NULL, 0); if (rc == -1 && errno != ENOMEM) err(1, "sysctl"); if (rc == -1 && v != NULL) { free(v); v = NULL; } if (v == NULL) { v = malloc(sz); rc = -1; } if (v == NULL) err(1, "malloc"); } while (rc == -1); *vp = v; *szp = sz; /* printf("got %zu at %p\n", sz, v); */ } void get_sockets(const char *mib) { void *v; size_t sz; int rc, n, name[CTL_MAXNAME]; u_int namelen; sz = CTL_MAXNAME; rc = sysctlnametomib(mib, &name[0], &sz); if (rc == -1) { if (errno == ENOENT) return; err(1, "sysctlnametomib: %s", mib); } namelen = sz; name[namelen++] = PCB_ALL; name[namelen++] = 0; /* XXX all pids */ name[namelen++] = sizeof(struct kinfo_pcb); name[namelen++] = INT_MAX; /* all of them */ sysctl_sucker(&name[0], namelen, &v, &sz); n = sz / sizeof(struct kinfo_pcb); socket_add_hash(v, n); }<|endoftext|>
<commit_before> #include "FlareCompanyMenu.h" #include "../../Flare.h" #include "../Components/FlarePartInfo.h" #include "../Components/FlareCompanyInfo.h" #include "../../Data/FlareSpacecraftComponentsCatalog.h" #include "../../Data/FlareCustomizationCatalog.h" #include "../../Game/FlareGame.h" #include "../../Game/FlareCompany.h" #include "../../Player/FlareMenuManager.h" #include "../../Player/FlareMenuPawn.h" #include "../../Player/FlarePlayerController.h" #define LOCTEXT_NAMESPACE "FlareCompanyMenu" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareCompanyMenu::Construct(const FArguments& InArgs) { // Data Company = NULL; MenuManager = InArgs._MenuManager; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); AFlarePlayerController* PC = MenuManager->GetPC(); // Build structure ChildSlot .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) .Padding(FMargin(0, AFlareMenuManager::GetMainOverlayHeight(), 0, 0)) [ SNew(SHorizontalBox) // Content block + SHorizontalBox::Slot() .HAlign(HAlign_Left) .AutoWidth() [ SNew(SScrollBox) .Style(&Theme.ScrollBoxStyle) .ScrollBarStyle(&Theme.ScrollBarStyle) + SScrollBox::Slot() .Padding(Theme.TitlePadding) [ SNew(STextBlock) .TextStyle(&Theme.SubTitleFont) .Text(LOCTEXT("CompanyInfoTitle", "Company")) ] // Company info + SScrollBox::Slot() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(0.8 * Theme.ContentWidth) [ SAssignNew(CompanyInfo, SFlareCompanyInfo) .Player(PC) ] ] // TR info + SScrollBox::Slot() [ SAssignNew(TradeRouteInfo, SFlareTradeRouteInfo) .MenuManager(MenuManager) ] // Property list + SScrollBox::Slot() [ SNew(SBox) .WidthOverride(Theme.ContentWidth) .HAlign(HAlign_Left) [ SAssignNew(ShipList, SFlareList) .MenuManager(MenuManager) .Title(LOCTEXT("Property", "Property")) ] ] ] // Company customization + SHorizontalBox::Slot() .HAlign(HAlign_Right) [ SNew(SVerticalBox) + SVerticalBox::Slot() .Padding(Theme.TitlePadding) .AutoHeight() [ SNew(STextBlock) .TextStyle(&Theme.SubTitleFont) .Text(LOCTEXT("CompanyEditTitle", "Company appearance")) ] // Company name + SVerticalBox::Slot() .Padding(Theme.ContentPadding) .AutoHeight() .HAlign(HAlign_Fill) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .VAlign(VAlign_Center) .AutoWidth() [ SNew(STextBlock) .TextStyle(&Theme.TextFont) .Text(LOCTEXT("EditCompanyName", "Company name")) ] + SHorizontalBox::Slot() .HAlign(HAlign_Right) [ SNew(SBox) .WidthOverride(0.4 * Theme.ContentWidth) [ SNew(SBorder) .BorderImage(&Theme.BackgroundBrush) .Padding(Theme.ContentPadding) [ SAssignNew(CompanyName, SEditableText) .AllowContextMenu(false) .Style(&Theme.TextInputStyle) ] ] ] + SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Right) [ SNew(SFlareButton) .Text(LOCTEXT("Rename", "Rename")) .HelpText(LOCTEXT("RenameInfo", "Rename this company")) .Icon(FFlareStyleSet::GetIcon("OK")) .OnClicked(this, &SFlareCompanyMenu::OnRename) .IsDisabled(this, &SFlareCompanyMenu::IsRenameDisabled) .Width(4) ] ] // Color picker + SVerticalBox::Slot() .Padding(Theme.ContentPadding) .AutoHeight() [ SAssignNew(ColorBox, SFlareColorPanel) .MenuManager(MenuManager) ] // Emblem + SVerticalBox::Slot() .Padding(Theme.ContentPadding) .HAlign(HAlign_Right) .VAlign(VAlign_Top) [ SAssignNew(EmblemPicker, SFlareDropList<int32>) .LineSize(1) .HeaderWidth(3) .HeaderHeight(3) .ItemWidth(3) .ItemHeight(2.7) .ShowColorWheel(false) .MaximumHeight(600) .OnItemPicked(this, &SFlareCompanyMenu::OnEmblemPicked) ] ] ]; } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ bool SFlareCompanyMenu::IsRenameDisabled() const { FString CompanyNameData = CompanyName->GetText().ToString(); if (CompanyNameData.Len() > 25) { return true; } if (CompanyNameData == Company->GetCompanyName().ToString()) { return true; } else { return false; } } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareCompanyMenu::Setup() { SetEnabled(false); SetVisibility(EVisibility::Collapsed); } void SFlareCompanyMenu::Enter(UFlareCompany* Target) { FLOG("SFlareCompanyMenu::Enter"); SetEnabled(true); // Company data Company = Target; SetVisibility(EVisibility::Visible); CompanyInfo->SetCompany(Company); CompanyName->SetText(Company->GetCompanyName()); TradeRouteInfo->UpdateTradeRouteList(); // Player specific AFlarePlayerController* PC = MenuManager->GetPC(); if (PC && Target) { // Colors FFlarePlayerSave Data; FFlareCompanyDescription Unused; PC->Save(Data, Unused); ColorBox->Setup(Data); // Emblems UFlareCustomizationCatalog* CustomizationCatalog = MenuManager->GetGame()->GetCustomizationCatalog(); for (int i = 0; i < CustomizationCatalog->GetEmblemCount(); i++) { EmblemPicker->AddItem(SNew(SImage).Image(CustomizationCatalog->GetEmblemBrush(i))); } EmblemPicker->SetSelectedIndex(PC->GetPlayerData()->PlayerEmblemIndex); // Menu PC->GetMenuPawn()->SetCameraOffset(FVector2D(100, -30)); if (PC->GetPlayerShip()) { PC->GetMenuPawn()->ShowShip(PC->GetPlayerShip()); } else { const FFlareSpacecraftComponentDescription* PartDesc = PC->GetGame()->GetShipPartsCatalog()->Get("object-safe"); PC->GetMenuPawn()->ShowPart(PartDesc); } // Station list TArray<UFlareSimulatedSpacecraft*>& CompanyStations = Target->GetCompanyStations(); for (int32 i = 0; i < CompanyStations.Num(); i++) { if (CompanyStations[i]->GetDamageSystem()->IsAlive()) { ShipList->AddShip(CompanyStations[i]); } } // Ship list TArray<UFlareSimulatedSpacecraft*>& CompanyShips = Target->GetCompanyShips(); for (int32 i = 0; i < CompanyShips.Num(); i++) { if (CompanyShips[i]->GetDamageSystem()->IsAlive()) { ShipList->AddShip(CompanyShips[i]); } } } ShipList->RefreshList(); ShipList->SetVisibility(EVisibility::Visible); } void SFlareCompanyMenu::Exit() { SetEnabled(false); ShipList->Reset(); ShipList->SetVisibility(EVisibility::Collapsed); EmblemPicker->ClearItems(); TradeRouteInfo->Clear(); Company = NULL; SetVisibility(EVisibility::Collapsed); } void SFlareCompanyMenu::OnRename() { AFlarePlayerController* PC = MenuManager->GetPC(); FFlareCompanyDescription CompanyDescription = *PC->GetCompanyDescription(); CompanyDescription.Name = CompanyName->GetText(); PC->SetCompanyDescription(CompanyDescription); } void SFlareCompanyMenu::OnEmblemPicked(int32 Index) { AFlarePlayerController* PC = MenuManager->GetPC(); UFlareCustomizationCatalog* CustomizationCatalog = MenuManager->GetGame()->GetCustomizationCatalog(); FFlareCompanyDescription CompanyDescription = *PC->GetCompanyDescription(); CompanyDescription.Emblem = CustomizationCatalog->GetEmblem(Index); PC->SetCompanyDescription(CompanyDescription); PC->GetPlayerData()->PlayerEmblemIndex = EmblemPicker->GetSelectedIndex(); PC->OnLoadComplete(); } #undef LOCTEXT_NAMESPACE <commit_msg>Split the company menu into tabs to allow a future economy log<commit_after> #include "FlareCompanyMenu.h" #include "../../Flare.h" #include "../Components/FlarePartInfo.h" #include "../Components/FlareCompanyInfo.h" #include "../Components/FlareTabView.h" #include "../../Data/FlareSpacecraftComponentsCatalog.h" #include "../../Data/FlareCustomizationCatalog.h" #include "../../Game/FlareGame.h" #include "../../Game/FlareCompany.h" #include "../../Player/FlareMenuManager.h" #include "../../Player/FlareMenuPawn.h" #include "../../Player/FlarePlayerController.h" #define LOCTEXT_NAMESPACE "FlareCompanyMenu" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareCompanyMenu::Construct(const FArguments& InArgs) { // Data Company = NULL; MenuManager = InArgs._MenuManager; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); AFlarePlayerController* PC = MenuManager->GetPC(); // Build structure ChildSlot .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) .Padding(FMargin(0, AFlareMenuManager::GetMainOverlayHeight(), 0, 0)) [ SNew(SFlareTabView) // Content block + SFlareTabView::Slot() .Header(LOCTEXT("CompanyMainTab", "Company")) .HeaderHelp(LOCTEXT("CompanyMainTabHelp", "General information about your company")) [ SNew(SVerticalBox) + SVerticalBox::Slot() .Padding(Theme.TitlePadding) .AutoHeight() [ SNew(STextBlock) .TextStyle(&Theme.SubTitleFont) .Text(LOCTEXT("CompanyInfoTitle", "Company")) ] // Company info + SVerticalBox::Slot() .Padding(Theme.ContentPadding) .AutoHeight() [ SNew(SBox) .WidthOverride(0.8 * Theme.ContentWidth) [ SAssignNew(CompanyInfo, SFlareCompanyInfo) .Player(PC) ] ] // TR info + SVerticalBox::Slot() .AutoHeight() [ SAssignNew(TradeRouteInfo, SFlareTradeRouteInfo) .MenuManager(MenuManager) ] ] // Property block + SFlareTabView::Slot() .Header(LOCTEXT("CompanyPropertyTab", "Property")) .HeaderHelp(LOCTEXT("CompanyPropertyTabHelp", "Fleets, ships and stations")) [ SNew(SBox) .WidthOverride(Theme.ContentWidth) .HAlign(HAlign_Left) [ SAssignNew(ShipList, SFlareList) .MenuManager(MenuManager) .Title(LOCTEXT("Property", "Property")) ] ] // Company customization + SFlareTabView::Slot() .Header(LOCTEXT("CompanyCustomizationTab", "Appearance")) .HeaderHelp(LOCTEXT("CompanyCustomizationTabHelp", "Appearance settings for your company")) [ SNew(SBox) .WidthOverride(Theme.ContentWidth) .HAlign(HAlign_Left) [ SNew(SVerticalBox) + SVerticalBox::Slot() .Padding(Theme.TitlePadding) .AutoHeight() [ SNew(STextBlock) .TextStyle(&Theme.SubTitleFont) .Text(LOCTEXT("CompanyEditTitle", "Appearance")) ] // Company name + SVerticalBox::Slot() .Padding(Theme.ContentPadding) .AutoHeight() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .VAlign(VAlign_Center) [ SNew(STextBlock) .TextStyle(&Theme.TextFont) .Text(LOCTEXT("EditCompanyName", "Company name")) ] + SHorizontalBox::Slot() .HAlign(HAlign_Right) [ SNew(SBox) .WidthOverride(0.4 * Theme.ContentWidth) [ SNew(SBorder) .BorderImage(&Theme.BackgroundBrush) .Padding(Theme.ContentPadding) [ SAssignNew(CompanyName, SEditableText) .AllowContextMenu(false) .Style(&Theme.TextInputStyle) ] ] ] + SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Right) [ SNew(SFlareButton) .Text(LOCTEXT("Rename", "Rename")) .HelpText(LOCTEXT("RenameInfo", "Rename this company")) .Icon(FFlareStyleSet::GetIcon("OK")) .OnClicked(this, &SFlareCompanyMenu::OnRename) .IsDisabled(this, &SFlareCompanyMenu::IsRenameDisabled) .Width(4) ] ] // Color picker + SVerticalBox::Slot() .Padding(Theme.ContentPadding) .AutoHeight() [ SAssignNew(ColorBox, SFlareColorPanel) .MenuManager(MenuManager) ] // Emblem + SVerticalBox::Slot() .Padding(Theme.ContentPadding) .VAlign(VAlign_Top) [ SAssignNew(EmblemPicker, SFlareDropList<int32>) .LineSize(1) .HeaderWidth(3) .HeaderHeight(3) .ItemWidth(3) .ItemHeight(2.7) .ShowColorWheel(false) .MaximumHeight(600) .OnItemPicked(this, &SFlareCompanyMenu::OnEmblemPicked) ] ] ] ]; } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ bool SFlareCompanyMenu::IsRenameDisabled() const { FString CompanyNameData = CompanyName->GetText().ToString(); if (CompanyNameData.Len() > 25) { return true; } if (CompanyNameData == Company->GetCompanyName().ToString()) { return true; } else { return false; } } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareCompanyMenu::Setup() { SetEnabled(false); SetVisibility(EVisibility::Collapsed); } void SFlareCompanyMenu::Enter(UFlareCompany* Target) { FLOG("SFlareCompanyMenu::Enter"); SetEnabled(true); // Company data Company = Target; SetVisibility(EVisibility::Visible); CompanyInfo->SetCompany(Company); CompanyName->SetText(Company->GetCompanyName()); TradeRouteInfo->UpdateTradeRouteList(); // Player specific AFlarePlayerController* PC = MenuManager->GetPC(); if (PC && Target) { // Colors FFlarePlayerSave Data; FFlareCompanyDescription Unused; PC->Save(Data, Unused); ColorBox->Setup(Data); // Emblems UFlareCustomizationCatalog* CustomizationCatalog = MenuManager->GetGame()->GetCustomizationCatalog(); for (int i = 0; i < CustomizationCatalog->GetEmblemCount(); i++) { EmblemPicker->AddItem(SNew(SImage).Image(CustomizationCatalog->GetEmblemBrush(i))); } EmblemPicker->SetSelectedIndex(PC->GetPlayerData()->PlayerEmblemIndex); // Menu PC->GetMenuPawn()->SetCameraOffset(FVector2D(100, -30)); if (PC->GetPlayerShip()) { PC->GetMenuPawn()->ShowShip(PC->GetPlayerShip()); } else { const FFlareSpacecraftComponentDescription* PartDesc = PC->GetGame()->GetShipPartsCatalog()->Get("object-safe"); PC->GetMenuPawn()->ShowPart(PartDesc); } // Station list TArray<UFlareSimulatedSpacecraft*>& CompanyStations = Target->GetCompanyStations(); for (int32 i = 0; i < CompanyStations.Num(); i++) { if (CompanyStations[i]->GetDamageSystem()->IsAlive()) { ShipList->AddShip(CompanyStations[i]); } } // Ship list TArray<UFlareSimulatedSpacecraft*>& CompanyShips = Target->GetCompanyShips(); for (int32 i = 0; i < CompanyShips.Num(); i++) { if (CompanyShips[i]->GetDamageSystem()->IsAlive()) { ShipList->AddShip(CompanyShips[i]); } } } ShipList->RefreshList(); ShipList->SetVisibility(EVisibility::Visible); } void SFlareCompanyMenu::Exit() { SetEnabled(false); ShipList->Reset(); ShipList->SetVisibility(EVisibility::Collapsed); EmblemPicker->ClearItems(); TradeRouteInfo->Clear(); Company = NULL; SetVisibility(EVisibility::Collapsed); } void SFlareCompanyMenu::OnRename() { AFlarePlayerController* PC = MenuManager->GetPC(); FFlareCompanyDescription CompanyDescription = *PC->GetCompanyDescription(); CompanyDescription.Name = CompanyName->GetText(); PC->SetCompanyDescription(CompanyDescription); } void SFlareCompanyMenu::OnEmblemPicked(int32 Index) { AFlarePlayerController* PC = MenuManager->GetPC(); UFlareCustomizationCatalog* CustomizationCatalog = MenuManager->GetGame()->GetCustomizationCatalog(); FFlareCompanyDescription CompanyDescription = *PC->GetCompanyDescription(); CompanyDescription.Emblem = CustomizationCatalog->GetEmblem(Index); PC->SetCompanyDescription(CompanyDescription); PC->GetPlayerData()->PlayerEmblemIndex = EmblemPicker->GetSelectedIndex(); PC->OnLoadComplete(); } #undef LOCTEXT_NAMESPACE <|endoftext|>
<commit_before>#include <node/v8.h> #include <node/node.h> #include <cstring> //strlen #include <cstdlib> #include "uno/game/game_wrapper.h" using namespace v8; using namespace node; /** @todo remove this */ static Handle<Value> Hello( const Arguments &args ) { HandleScope scope; const char *str = "Hello from host"; return String::New(str, strlen(str)); } extern "C" void init( Handle<Object> target ) { HandleScope scope; /** @todo remove this */ NODE_SET_METHOD(target, "hello", Hello); Casino::Node::Uno::Game::GameWrapper::Initialize(target); } //NODE_MODULE(casino, Casino::Node::Uno::Game::GameWrapper::Initialize); <commit_msg>initialize JavascriptPlayerWrapepr<commit_after>#include <node/v8.h> #include <node/node.h> #include <cstring> //strlen #include <cstdlib> #include "uno/game/game_wrapper.h" #include "uno/player/javascript_player_wrapper.h" using namespace v8; using namespace node; /** @todo remove this */ static Handle<Value> Hello( const Arguments &args ) { HandleScope scope; const char *str = "Hello from host"; return String::New(str, strlen(str)); } extern "C" void init( Handle<Object> target ) { HandleScope scope; /** @todo remove this */ NODE_SET_METHOD(target, "hello", Hello); Casino::Node::Uno::Game::GameWrapper::Initialize(target); Casino::Node::Uno::Player::JavascriptPlayerWrapper::Initialize(target); } //NODE_MODULE(casino, Casino::Node::Uno::Game::GameWrapper::Initialize); <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * 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 "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN Const make_value(string &value) { if (GetSize(value) >= 2 && value.front() == '"' && value.back() == '"') return Const(value.substr(1, GetSize(value)-2)); SigSpec sig; SigSpec::parse(sig, nullptr, value); return sig.as_const(); } bool match_name(string &name, IdString &id, bool ignore_case=false) { string str1 = RTLIL::escape_id(name); string str2 = id.str(); if (ignore_case) return !strcasecmp(str1.c_str(), str2.c_str()); return str1 == str2; } bool match_value(string &value, Const &val, bool ignore_case=false) { if (ignore_case && ((val.flags & RTLIL::CONST_FLAG_STRING) != 0) && GetSize(value) && value.front() == '"' && value.back() == '"') { string str1 = value.substr(1, GetSize(value)-2); string str2 = val.decode_string(); return !strcasecmp(str1.c_str(), str2.c_str()); } return make_value(value) == val; } struct AttrmapAction { virtual ~AttrmapAction() { } virtual bool apply(IdString &id, Const &val) = 0; }; struct AttrmapTocase : AttrmapAction { string name; virtual bool apply(IdString &id, Const&) { if (match_name(name, id, true)) id = RTLIL::escape_id(name); return true; } }; struct AttrmapRename : AttrmapAction { string old_name, new_name; virtual bool apply(IdString &id, Const&) { if (match_name(old_name, id)) id = RTLIL::escape_id(new_name); return true; } }; struct AttrmapMap : AttrmapAction { bool imap; string old_name, new_name; string old_value, new_value; virtual bool apply(IdString &id, Const &val) { if (match_name(old_name, id) && match_value(old_value, val, true)) { id = RTLIL::escape_id(new_name); val = make_value(new_value); } return true; } }; struct AttrmapRemove : AttrmapAction { string name, value; virtual bool apply(IdString &id, Const &val) { return !(match_name(name, id) && match_value(value, val)); } }; void attrmap_apply(string objname, vector<std::unique_ptr<AttrmapAction>> &actions, dict<RTLIL::IdString, RTLIL::Const> &attributes) { dict<RTLIL::IdString, RTLIL::Const> new_attributes; for (auto attr : attributes) { auto new_attr = attr; for (auto &action : actions) if (!action->apply(new_attr.first, new_attr.second)) goto delete_this_attr; if (new_attr != attr) log("Changed attribute on %s: %s=%s -> %s=%s\n", objname.c_str(), log_id(attr.first), log_const(attr.second), log_id(new_attr.first), log_const(new_attr.second)); new_attributes[new_attr.first] = new_attr.second; if (0) delete_this_attr: log("Removed attribute on %s: %s=%s\n", objname.c_str(), log_id(attr.first), log_const(attr.second)); } attributes.swap(new_attributes); } struct AttrmapPass : public Pass { AttrmapPass() : Pass("attrmap", "renaming attributes") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" attrmap [options] [selection]\n"); log("\n"); log("This command renames attributes and/or mapps key/value pairs to\n"); log("other key/value pairs.\n"); log("\n"); log(" -tocase <name>\n"); log(" Match attribute names case-insensitively and set it to the specified\n"); log(" name.\n"); log("\n"); log(" -rename <old_name> <new_name>\n"); log(" Rename attributes as specified\n"); log("\n"); log(" -map <old_name>=<old_value> <new_name>=<new_value>\n"); log(" Map key/value pairs as indicated.\n"); log("\n"); log(" -imap <old_name>=<old_value> <new_name>=<new_value>\n"); log(" Like -map, but use case-insensitive match for <old_value> when\n"); log(" it is a string value.\n"); log("\n"); log(" -remove <name>=<value>\n"); log(" Remove attributes matching this pattern.\n"); log("\n"); log(" -modattr\n"); log(" Operate on module attributes instead of attributes on wires and cells.\n"); log("\n"); log("For example, mapping Xilinx-style \"keep\" attributes to Yosys-style:\n"); log("\n"); log(" attrmap -tocase keep -imap keep=\"true\" keep=1 \\\n"); log(" -imap keep=\"false\" keep=0 -remove keep=0\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { log_header(design, "Executing ATTRMAP pass (move or copy attributes).\n"); bool modattr_mode = false; vector<std::unique_ptr<AttrmapAction>> actions; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { std::string arg = args[argidx]; if (arg == "-tocase" && argidx+1 < args.size()) { auto action = new AttrmapTocase; action->name = args[++argidx]; actions.push_back(std::move(std::unique_ptr<AttrmapAction>(action))); continue; } if (arg == "-rename" && argidx+2 < args.size()) { auto action = new AttrmapRename; action->old_name = args[++argidx]; action->new_name = args[++argidx]; actions.push_back(std::move(std::unique_ptr<AttrmapAction>(action))); continue; } if ((arg == "-map" || arg == "-imap") && argidx+2 < args.size()) { string arg1 = args[++argidx]; string arg2 = args[++argidx]; string val1, val2; size_t p = arg1.find("="); if (p != string::npos) { val1 = arg1.substr(p+1); arg1 = arg1.substr(0, p); } p = arg2.find("="); if (p != string::npos) { val2 = arg2.substr(p+1); arg2 = arg2.substr(0, p); } auto action = new AttrmapMap; action->imap = (arg == "-map"); action->old_name = arg1; action->new_name = arg2; action->old_value = val1; action->new_value = val2; actions.push_back(std::move(std::unique_ptr<AttrmapAction>(action))); continue; } if (arg == "-remove" && argidx+1 < args.size()) { string arg1 = args[++argidx], val1; size_t p = arg1.find("="); if (p != string::npos) { val1 = arg1.substr(p+1); arg1 = arg1.substr(0, p); } auto action = new AttrmapRemove; action->name = arg1; action->value = val1; actions.push_back(std::move(std::unique_ptr<AttrmapAction>(action))); continue; } if (arg == "-modattr") { modattr_mode = true; continue; } break; } extra_args(args, argidx, design); if (modattr_mode) { for (auto module : design->selected_whole_modules()) attrmap_apply(stringf("%s", log_id(module)), actions, module->attributes); } else { for (auto module : design->selected_modules()) { for (auto wire : module->selected_wires()) attrmap_apply(stringf("%s.%s", log_id(module), log_id(wire)), actions, wire->attributes); for (auto cell : module->selected_cells()) attrmap_apply(stringf("%s.%s", log_id(module), log_id(cell)), actions, cell->attributes); } } } } AttrmapPass; PRIVATE_NAMESPACE_END <commit_msg>Fixed some compiler warnings in attrmap command<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * 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 "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN Const make_value(string &value) { if (GetSize(value) >= 2 && value.front() == '"' && value.back() == '"') return Const(value.substr(1, GetSize(value)-2)); SigSpec sig; SigSpec::parse(sig, nullptr, value); return sig.as_const(); } bool match_name(string &name, IdString &id, bool ignore_case=false) { string str1 = RTLIL::escape_id(name); string str2 = id.str(); if (ignore_case) return !strcasecmp(str1.c_str(), str2.c_str()); return str1 == str2; } bool match_value(string &value, Const &val, bool ignore_case=false) { if (ignore_case && ((val.flags & RTLIL::CONST_FLAG_STRING) != 0) && GetSize(value) && value.front() == '"' && value.back() == '"') { string str1 = value.substr(1, GetSize(value)-2); string str2 = val.decode_string(); return !strcasecmp(str1.c_str(), str2.c_str()); } return make_value(value) == val; } struct AttrmapAction { virtual ~AttrmapAction() { } virtual bool apply(IdString &id, Const &val) = 0; }; struct AttrmapTocase : AttrmapAction { string name; virtual bool apply(IdString &id, Const&) { if (match_name(name, id, true)) id = RTLIL::escape_id(name); return true; } }; struct AttrmapRename : AttrmapAction { string old_name, new_name; virtual bool apply(IdString &id, Const&) { if (match_name(old_name, id)) id = RTLIL::escape_id(new_name); return true; } }; struct AttrmapMap : AttrmapAction { bool imap; string old_name, new_name; string old_value, new_value; virtual bool apply(IdString &id, Const &val) { if (match_name(old_name, id) && match_value(old_value, val, true)) { id = RTLIL::escape_id(new_name); val = make_value(new_value); } return true; } }; struct AttrmapRemove : AttrmapAction { string name, value; virtual bool apply(IdString &id, Const &val) { return !(match_name(name, id) && match_value(value, val)); } }; void attrmap_apply(string objname, vector<std::unique_ptr<AttrmapAction>> &actions, dict<RTLIL::IdString, RTLIL::Const> &attributes) { dict<RTLIL::IdString, RTLIL::Const> new_attributes; for (auto attr : attributes) { auto new_attr = attr; for (auto &action : actions) if (!action->apply(new_attr.first, new_attr.second)) goto delete_this_attr; if (new_attr != attr) log("Changed attribute on %s: %s=%s -> %s=%s\n", objname.c_str(), log_id(attr.first), log_const(attr.second), log_id(new_attr.first), log_const(new_attr.second)); new_attributes[new_attr.first] = new_attr.second; if (0) delete_this_attr: log("Removed attribute on %s: %s=%s\n", objname.c_str(), log_id(attr.first), log_const(attr.second)); } attributes.swap(new_attributes); } struct AttrmapPass : public Pass { AttrmapPass() : Pass("attrmap", "renaming attributes") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" attrmap [options] [selection]\n"); log("\n"); log("This command renames attributes and/or mapps key/value pairs to\n"); log("other key/value pairs.\n"); log("\n"); log(" -tocase <name>\n"); log(" Match attribute names case-insensitively and set it to the specified\n"); log(" name.\n"); log("\n"); log(" -rename <old_name> <new_name>\n"); log(" Rename attributes as specified\n"); log("\n"); log(" -map <old_name>=<old_value> <new_name>=<new_value>\n"); log(" Map key/value pairs as indicated.\n"); log("\n"); log(" -imap <old_name>=<old_value> <new_name>=<new_value>\n"); log(" Like -map, but use case-insensitive match for <old_value> when\n"); log(" it is a string value.\n"); log("\n"); log(" -remove <name>=<value>\n"); log(" Remove attributes matching this pattern.\n"); log("\n"); log(" -modattr\n"); log(" Operate on module attributes instead of attributes on wires and cells.\n"); log("\n"); log("For example, mapping Xilinx-style \"keep\" attributes to Yosys-style:\n"); log("\n"); log(" attrmap -tocase keep -imap keep=\"true\" keep=1 \\\n"); log(" -imap keep=\"false\" keep=0 -remove keep=0\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { log_header(design, "Executing ATTRMAP pass (move or copy attributes).\n"); bool modattr_mode = false; vector<std::unique_ptr<AttrmapAction>> actions; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { std::string arg = args[argidx]; if (arg == "-tocase" && argidx+1 < args.size()) { auto action = new AttrmapTocase; action->name = args[++argidx]; actions.push_back(std::unique_ptr<AttrmapAction>(action)); continue; } if (arg == "-rename" && argidx+2 < args.size()) { auto action = new AttrmapRename; action->old_name = args[++argidx]; action->new_name = args[++argidx]; actions.push_back(std::unique_ptr<AttrmapAction>(action)); continue; } if ((arg == "-map" || arg == "-imap") && argidx+2 < args.size()) { string arg1 = args[++argidx]; string arg2 = args[++argidx]; string val1, val2; size_t p = arg1.find("="); if (p != string::npos) { val1 = arg1.substr(p+1); arg1 = arg1.substr(0, p); } p = arg2.find("="); if (p != string::npos) { val2 = arg2.substr(p+1); arg2 = arg2.substr(0, p); } auto action = new AttrmapMap; action->imap = (arg == "-map"); action->old_name = arg1; action->new_name = arg2; action->old_value = val1; action->new_value = val2; actions.push_back(std::unique_ptr<AttrmapAction>(action)); continue; } if (arg == "-remove" && argidx+1 < args.size()) { string arg1 = args[++argidx], val1; size_t p = arg1.find("="); if (p != string::npos) { val1 = arg1.substr(p+1); arg1 = arg1.substr(0, p); } auto action = new AttrmapRemove; action->name = arg1; action->value = val1; actions.push_back(std::unique_ptr<AttrmapAction>(action)); continue; } if (arg == "-modattr") { modattr_mode = true; continue; } break; } extra_args(args, argidx, design); if (modattr_mode) { for (auto module : design->selected_whole_modules()) attrmap_apply(stringf("%s", log_id(module)), actions, module->attributes); } else { for (auto module : design->selected_modules()) { for (auto wire : module->selected_wires()) attrmap_apply(stringf("%s.%s", log_id(module), log_id(wire)), actions, wire->attributes); for (auto cell : module->selected_cells()) attrmap_apply(stringf("%s.%s", log_id(module), log_id(cell)), actions, cell->attributes); } } } } AttrmapPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_METRIC_REGRESSION_METRIC_HPP_ #define LIGHTGBM_METRIC_REGRESSION_METRIC_HPP_ #include <LightGBM/metric.h> #include <LightGBM/utils/log.h> #include <string> #include <algorithm> #include <cmath> #include <vector> namespace LightGBM { /*! * \brief Metric for regression task. * Use static class "PointWiseLossCalculator" to calculate loss point-wise */ template<typename PointWiseLossCalculator> class RegressionMetric: public Metric { public: explicit RegressionMetric(const Config& config) :config_(config) { } virtual ~RegressionMetric() { } const std::vector<std::string>& GetName() const override { return name_; } double factor_to_bigger_better() const override { return -1.0f; } void Init(const Metadata& metadata, data_size_t num_data) override { name_.emplace_back(PointWiseLossCalculator::Name()); num_data_ = num_data; // get label label_ = metadata.label(); // get weights weights_ = metadata.weights(); if (weights_ == nullptr) { sum_weights_ = static_cast<double>(num_data_); } else { sum_weights_ = 0.0f; for (data_size_t i = 0; i < num_data_; ++i) { sum_weights_ += weights_[i]; } } for (data_size_t i = 0; i < num_data_; ++i) { PointWiseLossCalculator::CheckLabel(label_[i]); } } std::vector<double> Eval(const double* score, const ObjectiveFunction* objective) const override { double sum_loss = 0.0f; if (objective == nullptr) { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { // add loss sum_loss += PointWiseLossCalculator::LossOnPoint(label_[i], score[i], config_); } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { // add loss sum_loss += PointWiseLossCalculator::LossOnPoint(label_[i], score[i], config_) * weights_[i]; } } } else { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { // add loss double t = 0; objective->ConvertOutput(&score[i], &t); sum_loss += PointWiseLossCalculator::LossOnPoint(label_[i], t, config_); } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { // add loss double t = 0; objective->ConvertOutput(&score[i], &t); sum_loss += PointWiseLossCalculator::LossOnPoint(label_[i], t, config_) * weights_[i]; } } } double loss = PointWiseLossCalculator::AverageLoss(sum_loss, sum_weights_); return std::vector<double>(1, loss); } inline static double AverageLoss(double sum_loss, double sum_weights) { return sum_loss / sum_weights; } inline static void CheckLabel(label_t) { } private: /*! \brief Number of data */ data_size_t num_data_; /*! \brief Pointer of label */ const label_t* label_; /*! \brief Pointer of weighs */ const label_t* weights_; /*! \brief Sum weights */ double sum_weights_; /*! \brief Name of this test set */ Config config_; std::vector<std::string> name_; }; /*! \brief RMSE loss for regression task */ class RMSEMetric: public RegressionMetric<RMSEMetric> { public: explicit RMSEMetric(const Config& config) :RegressionMetric<RMSEMetric>(config) {} inline static double LossOnPoint(label_t label, double score, const Config&) { return (score - label)*(score - label); } inline static double AverageLoss(double sum_loss, double sum_weights) { // need sqrt the result for RMSE loss return std::sqrt(sum_loss / sum_weights); } inline static const char* Name() { return "rmse"; } }; /*! \brief L2 loss for regression task */ class L2Metric: public RegressionMetric<L2Metric> { public: explicit L2Metric(const Config& config) :RegressionMetric<L2Metric>(config) {} inline static double LossOnPoint(label_t label, double score, const Config&) { return (score - label)*(score - label); } inline static const char* Name() { return "l2"; } }; /*! \brief L2 loss for regression task */ class QuantileMetric : public RegressionMetric<QuantileMetric> { public: explicit QuantileMetric(const Config& config) :RegressionMetric<QuantileMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config& config) { double delta = label - score; if (delta < 0) { return (config.alpha - 1.0f) * delta; } else { return config.alpha * delta; } } inline static const char* Name() { return "quantile"; } }; /*! \brief L1 loss for regression task */ class L1Metric: public RegressionMetric<L1Metric> { public: explicit L1Metric(const Config& config) :RegressionMetric<L1Metric>(config) {} inline static double LossOnPoint(label_t label, double score, const Config&) { return std::fabs(score - label); } inline static const char* Name() { return "l1"; } }; /*! \brief Huber loss for regression task */ class HuberLossMetric: public RegressionMetric<HuberLossMetric> { public: explicit HuberLossMetric(const Config& config) :RegressionMetric<HuberLossMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config& config) { const double diff = score - label; if (std::abs(diff) <= config.alpha) { return 0.5f * diff * diff; } else { return config.alpha * (std::abs(diff) - 0.5f * config.alpha); } } inline static const char* Name() { return "huber"; } }; /*! \brief Fair loss for regression task */ // http://research.microsoft.com/en-us/um/people/zhang/INRIA/Publis/Tutorial-Estim/node24.html class FairLossMetric: public RegressionMetric<FairLossMetric> { public: explicit FairLossMetric(const Config& config) :RegressionMetric<FairLossMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config& config) { const double x = std::fabs(score - label); const double c = config.fair_c; return c * x - c * c * std::log(1.0f + x / c); } inline static const char* Name() { return "fair"; } }; /*! \brief Poisson regression loss for regression task */ class PoissonMetric: public RegressionMetric<PoissonMetric> { public: explicit PoissonMetric(const Config& config) :RegressionMetric<PoissonMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config&) { const double eps = 1e-10f; if (score < eps) { score = eps; } return score - label * std::log(score); } inline static const char* Name() { return "poisson"; } }; /*! \brief Mape regression loss for regression task */ class MAPEMetric : public RegressionMetric<MAPEMetric> { public: explicit MAPEMetric(const Config& config) :RegressionMetric<MAPEMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config&) { return std::fabs((label - score)) / std::max(1.0f, std::fabs(label)); } inline static const char* Name() { return "mape"; } }; class GammaMetric : public RegressionMetric<GammaMetric> { public: explicit GammaMetric(const Config& config) :RegressionMetric<GammaMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config&) { const double psi = 1.0; const double theta = -1.0 / score; const double a = psi; const double b = -Common::SafeLog(-theta); const double c = 1. / psi * Common::SafeLog(label / psi) - Common::SafeLog(label) - 0; // 0 = std::lgamma(1.0 / psi) = std::lgamma(1.0); return -((label * theta - b) / a + c); } inline static const char* Name() { return "gamma"; } inline static void CheckLabel(label_t label) { CHECK(label > 0); } }; class GammaDevianceMetric : public RegressionMetric<GammaDevianceMetric> { public: explicit GammaDevianceMetric(const Config& config) :RegressionMetric<GammaDevianceMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config&) { const double epsilon = 1.0e-9; const double tmp = label / (score + epsilon); return tmp - Common::SafeLog(tmp) - 1; } inline static const char* Name() { return "gamma-deviance"; } inline static double AverageLoss(double sum_loss, double) { return sum_loss * 2; } inline static void CheckLabel(label_t label) { CHECK(label > 0); } }; class TweedieMetric : public RegressionMetric<TweedieMetric> { public: explicit TweedieMetric(const Config& config) :RegressionMetric<TweedieMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config& config) { const double rho = config.tweedie_variance_power; const double eps = 1e-10f; if (score < eps) { score = eps; } const double a = label * std::exp((1 - rho) * std::log(score)) / (1 - rho); const double b = std::exp((2 - rho) * std::log(score)) / (2 - rho); return -a + b; } inline static const char* Name() { return "tweedie"; } }; } // namespace LightGBM #endif // LightGBM_METRIC_REGRESSION_METRIC_HPP_ <commit_msg>Fixed typo in regression_metric.hpp (#2111)<commit_after>/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_METRIC_REGRESSION_METRIC_HPP_ #define LIGHTGBM_METRIC_REGRESSION_METRIC_HPP_ #include <LightGBM/metric.h> #include <LightGBM/utils/log.h> #include <string> #include <algorithm> #include <cmath> #include <vector> namespace LightGBM { /*! * \brief Metric for regression task. * Use static class "PointWiseLossCalculator" to calculate loss point-wise */ template<typename PointWiseLossCalculator> class RegressionMetric: public Metric { public: explicit RegressionMetric(const Config& config) :config_(config) { } virtual ~RegressionMetric() { } const std::vector<std::string>& GetName() const override { return name_; } double factor_to_bigger_better() const override { return -1.0f; } void Init(const Metadata& metadata, data_size_t num_data) override { name_.emplace_back(PointWiseLossCalculator::Name()); num_data_ = num_data; // get label label_ = metadata.label(); // get weights weights_ = metadata.weights(); if (weights_ == nullptr) { sum_weights_ = static_cast<double>(num_data_); } else { sum_weights_ = 0.0f; for (data_size_t i = 0; i < num_data_; ++i) { sum_weights_ += weights_[i]; } } for (data_size_t i = 0; i < num_data_; ++i) { PointWiseLossCalculator::CheckLabel(label_[i]); } } std::vector<double> Eval(const double* score, const ObjectiveFunction* objective) const override { double sum_loss = 0.0f; if (objective == nullptr) { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { // add loss sum_loss += PointWiseLossCalculator::LossOnPoint(label_[i], score[i], config_); } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { // add loss sum_loss += PointWiseLossCalculator::LossOnPoint(label_[i], score[i], config_) * weights_[i]; } } } else { if (weights_ == nullptr) { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { // add loss double t = 0; objective->ConvertOutput(&score[i], &t); sum_loss += PointWiseLossCalculator::LossOnPoint(label_[i], t, config_); } } else { #pragma omp parallel for schedule(static) reduction(+:sum_loss) for (data_size_t i = 0; i < num_data_; ++i) { // add loss double t = 0; objective->ConvertOutput(&score[i], &t); sum_loss += PointWiseLossCalculator::LossOnPoint(label_[i], t, config_) * weights_[i]; } } } double loss = PointWiseLossCalculator::AverageLoss(sum_loss, sum_weights_); return std::vector<double>(1, loss); } inline static double AverageLoss(double sum_loss, double sum_weights) { return sum_loss / sum_weights; } inline static void CheckLabel(label_t) { } private: /*! \brief Number of data */ data_size_t num_data_; /*! \brief Pointer of label */ const label_t* label_; /*! \brief Pointer of weighs */ const label_t* weights_; /*! \brief Sum weights */ double sum_weights_; /*! \brief Name of this test set */ Config config_; std::vector<std::string> name_; }; /*! \brief RMSE loss for regression task */ class RMSEMetric: public RegressionMetric<RMSEMetric> { public: explicit RMSEMetric(const Config& config) :RegressionMetric<RMSEMetric>(config) {} inline static double LossOnPoint(label_t label, double score, const Config&) { return (score - label)*(score - label); } inline static double AverageLoss(double sum_loss, double sum_weights) { // need sqrt the result for RMSE loss return std::sqrt(sum_loss / sum_weights); } inline static const char* Name() { return "rmse"; } }; /*! \brief L2 loss for regression task */ class L2Metric: public RegressionMetric<L2Metric> { public: explicit L2Metric(const Config& config) :RegressionMetric<L2Metric>(config) {} inline static double LossOnPoint(label_t label, double score, const Config&) { return (score - label)*(score - label); } inline static const char* Name() { return "l2"; } }; /*! \brief Quantile loss for regression task */ class QuantileMetric : public RegressionMetric<QuantileMetric> { public: explicit QuantileMetric(const Config& config) :RegressionMetric<QuantileMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config& config) { double delta = label - score; if (delta < 0) { return (config.alpha - 1.0f) * delta; } else { return config.alpha * delta; } } inline static const char* Name() { return "quantile"; } }; /*! \brief L1 loss for regression task */ class L1Metric: public RegressionMetric<L1Metric> { public: explicit L1Metric(const Config& config) :RegressionMetric<L1Metric>(config) {} inline static double LossOnPoint(label_t label, double score, const Config&) { return std::fabs(score - label); } inline static const char* Name() { return "l1"; } }; /*! \brief Huber loss for regression task */ class HuberLossMetric: public RegressionMetric<HuberLossMetric> { public: explicit HuberLossMetric(const Config& config) :RegressionMetric<HuberLossMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config& config) { const double diff = score - label; if (std::abs(diff) <= config.alpha) { return 0.5f * diff * diff; } else { return config.alpha * (std::abs(diff) - 0.5f * config.alpha); } } inline static const char* Name() { return "huber"; } }; /*! \brief Fair loss for regression task */ // http://research.microsoft.com/en-us/um/people/zhang/INRIA/Publis/Tutorial-Estim/node24.html class FairLossMetric: public RegressionMetric<FairLossMetric> { public: explicit FairLossMetric(const Config& config) :RegressionMetric<FairLossMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config& config) { const double x = std::fabs(score - label); const double c = config.fair_c; return c * x - c * c * std::log(1.0f + x / c); } inline static const char* Name() { return "fair"; } }; /*! \brief Poisson regression loss for regression task */ class PoissonMetric: public RegressionMetric<PoissonMetric> { public: explicit PoissonMetric(const Config& config) :RegressionMetric<PoissonMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config&) { const double eps = 1e-10f; if (score < eps) { score = eps; } return score - label * std::log(score); } inline static const char* Name() { return "poisson"; } }; /*! \brief Mape regression loss for regression task */ class MAPEMetric : public RegressionMetric<MAPEMetric> { public: explicit MAPEMetric(const Config& config) :RegressionMetric<MAPEMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config&) { return std::fabs((label - score)) / std::max(1.0f, std::fabs(label)); } inline static const char* Name() { return "mape"; } }; class GammaMetric : public RegressionMetric<GammaMetric> { public: explicit GammaMetric(const Config& config) :RegressionMetric<GammaMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config&) { const double psi = 1.0; const double theta = -1.0 / score; const double a = psi; const double b = -Common::SafeLog(-theta); const double c = 1. / psi * Common::SafeLog(label / psi) - Common::SafeLog(label) - 0; // 0 = std::lgamma(1.0 / psi) = std::lgamma(1.0); return -((label * theta - b) / a + c); } inline static const char* Name() { return "gamma"; } inline static void CheckLabel(label_t label) { CHECK(label > 0); } }; class GammaDevianceMetric : public RegressionMetric<GammaDevianceMetric> { public: explicit GammaDevianceMetric(const Config& config) :RegressionMetric<GammaDevianceMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config&) { const double epsilon = 1.0e-9; const double tmp = label / (score + epsilon); return tmp - Common::SafeLog(tmp) - 1; } inline static const char* Name() { return "gamma-deviance"; } inline static double AverageLoss(double sum_loss, double) { return sum_loss * 2; } inline static void CheckLabel(label_t label) { CHECK(label > 0); } }; class TweedieMetric : public RegressionMetric<TweedieMetric> { public: explicit TweedieMetric(const Config& config) :RegressionMetric<TweedieMetric>(config) { } inline static double LossOnPoint(label_t label, double score, const Config& config) { const double rho = config.tweedie_variance_power; const double eps = 1e-10f; if (score < eps) { score = eps; } const double a = label * std::exp((1 - rho) * std::log(score)) / (1 - rho); const double b = std::exp((2 - rho) * std::log(score)) / (2 - rho); return -a + b; } inline static const char* Name() { return "tweedie"; } }; } // namespace LightGBM #endif // LightGBM_METRIC_REGRESSION_METRIC_HPP_ <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011-2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #define BOOST_NO_RTTI #define BOOST_NO_TYPEID #include <boost/range/adaptors.hpp> #include "Type.hpp" #include "FunctionContext.hpp" #include "GlobalContext.hpp" #include "Variable.hpp" #include "mtac/DeadCodeElimination.hpp" #include "mtac/GlobalOptimizations.hpp" #include "mtac/LiveVariableAnalysisProblem.hpp" #include "mtac/Utils.hpp" #include "mtac/Offset.hpp" #include "mtac/Quadruple.hpp" using namespace eddic; bool mtac::dead_code_elimination::operator()(mtac::Function& function){ bool optimized = false; std::vector<std::size_t> to_delete; //1. DCE based on data-flow analysis mtac::LiveVariableAnalysisProblem problem; auto results = mtac::data_flow(function, problem); for(auto& block : function){ auto& out = results->OUT[block]; for(auto& quadruple : boost::adaptors::reverse(block->statements)){ if(quadruple.result && mtac::erase_result(quadruple.op)){ if(out.top() || out.values().find(quadruple.result) == out.values().end()){ to_delete.push_back(quadruple.uid()); } } problem.transfer(block, quadruple, out); } } //Delete what has been found on previous steps if(!to_delete.empty()){ optimized = true; for(auto& block : function){ for(auto& quadruple : block->statements){ if(std::find(to_delete.begin(), to_delete.end(), quadruple.uid()) != to_delete.end()){ mtac::transform_to_nop(quadruple); } } } } //2. Remove variables that contribute only to themselves //TODO This could probably be done directly in the data-flow DCE std::unordered_set<std::shared_ptr<Variable>> candidates; for(auto& block : function){ for(auto& quadruple : block->statements){ if(quadruple.result && mtac::erase_result(quadruple.op)){ if_init_equals(quadruple.arg1, quadruple.result, [&candidates, &quadruple](){ candidates.insert(quadruple.result);}); if_init_equals(quadruple.arg2, quadruple.result, [&candidates, &quadruple](){ candidates.insert(quadruple.result);}); } } } for(auto& block : function){ for(auto& quadruple : block->statements){ if(quadruple.result && mtac::erase_result(quadruple.op)){ if_init_not_equals<std::shared_ptr<Variable>>(quadruple.arg1, quadruple.result, [&candidates](std::shared_ptr<Variable>& var){ candidates.erase(var);}); if_init_not_equals<std::shared_ptr<Variable>>(quadruple.arg2, quadruple.result, [&candidates](std::shared_ptr<Variable>& var){ candidates.erase(var);}); } else { candidates.erase(quadruple.result); if_init<std::shared_ptr<Variable>>(quadruple.arg1, [&candidates](std::shared_ptr<Variable>& var){ candidates.erase(var); }); if_init<std::shared_ptr<Variable>>(quadruple.arg2, [&candidates](std::shared_ptr<Variable>& var){ candidates.erase(var); }); } } } if(!candidates.empty()){ for(auto& block : function){ for(auto& quadruple : block->statements){ if(quadruple.result && mtac::erase_result(quadruple.op) && candidates.find(quadruple.result) != candidates.end()){ mtac::transform_to_nop(quadruple); optimized = true; } } } } //TODO Review or remove this optimization, this is quite unsafe std::unordered_set<Offset, mtac::OffsetHash> used_offsets; std::unordered_set<std::shared_ptr<Variable>> invalidated_offsets; for(auto& block : function){ for(auto& quadruple : block->statements){ if(quadruple.op == mtac::Operator::DOT || quadruple.op == mtac::Operator::FDOT || quadruple.op == mtac::Operator::PDOT){ if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){ if(auto* offset_ptr = boost::get<int>(&*quadruple.arg2)){ mtac::Offset offset(*var_ptr, *offset_ptr); used_offsets.insert(offset); } else { invalidated_offsets.insert(*var_ptr); } } } } } for(auto& block : function){ auto it = iterate(block->statements); while(it.has_next()){ auto& quadruple = *it; if(quadruple.op == mtac::Operator::DOT_ASSIGN || quadruple.op == mtac::Operator::DOT_FASSIGN || quadruple.op == mtac::Operator::DOT_PASSIGN){ if(invalidated_offsets.find(quadruple.result) == invalidated_offsets.end()){ //Arrays are a problem because they are not considered as escaped after being passed in parameters if(!quadruple.result->type()->is_pointer() && !quadruple.result->type()->is_array()){ if(auto* offset_ptr = boost::get<int>(&*quadruple.arg1)){ if(quadruple.result->type()->is_custom_type() || quadruple.result->type()->is_template_type()){ auto struct_type = function.context->global()->get_struct(quadruple.result->type()->mangle()); auto member_type = function.context->global()->member_type(struct_type, *offset_ptr); if(member_type->is_pointer()){ ++it; continue; } } mtac::Offset offset(quadruple.result, *offset_ptr); if(problem.pointer_escaped->find(quadruple.result) == problem.pointer_escaped->end() && used_offsets.find(offset) == used_offsets.end()){ mtac::transform_to_nop(quadruple); optimized=true; } } } } } ++it; } } return optimized; } <commit_msg>Refactor<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011-2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #define BOOST_NO_RTTI #define BOOST_NO_TYPEID #include <boost/range/adaptors.hpp> #include "Type.hpp" #include "FunctionContext.hpp" #include "GlobalContext.hpp" #include "Variable.hpp" #include "mtac/DeadCodeElimination.hpp" #include "mtac/GlobalOptimizations.hpp" #include "mtac/LiveVariableAnalysisProblem.hpp" #include "mtac/Utils.hpp" #include "mtac/Offset.hpp" #include "mtac/Quadruple.hpp" using namespace eddic; bool mtac::dead_code_elimination::operator()(mtac::Function& function){ bool optimized = false; std::vector<std::size_t> to_delete; //1. DCE based on data-flow analysis mtac::LiveVariableAnalysisProblem problem; auto results = mtac::data_flow(function, problem); for(auto& block : function){ auto& out = results->OUT[block]; for(auto& quadruple : boost::adaptors::reverse(block->statements)){ if(quadruple.result && mtac::erase_result(quadruple.op)){ if(out.top() || out.values().find(quadruple.result) == out.values().end()){ to_delete.push_back(quadruple.uid()); } } problem.transfer(block, quadruple, out); } } //Delete what has been found on previous steps if(!to_delete.empty()){ optimized = true; for(auto& block : function){ for(auto& quadruple : block->statements){ if(std::find(to_delete.begin(), to_delete.end(), quadruple.uid()) != to_delete.end()){ mtac::transform_to_nop(quadruple); } } } } //2. Remove variables that contribute only to themselves //TODO This could probably be done directly in the data-flow DCE std::unordered_set<std::shared_ptr<Variable>> candidates; for(auto& block : function){ for(auto& quadruple : block->statements){ if(quadruple.result && mtac::erase_result(quadruple.op)){ if_init_equals(quadruple.arg1, quadruple.result, [&candidates, &quadruple](){ candidates.insert(quadruple.result);}); if_init_equals(quadruple.arg2, quadruple.result, [&candidates, &quadruple](){ candidates.insert(quadruple.result);}); } } } for(auto& block : function){ for(auto& quadruple : block->statements){ if(quadruple.result && mtac::erase_result(quadruple.op)){ if_init_not_equals<std::shared_ptr<Variable>>(quadruple.arg1, quadruple.result, [&candidates](std::shared_ptr<Variable>& var){ candidates.erase(var);}); if_init_not_equals<std::shared_ptr<Variable>>(quadruple.arg2, quadruple.result, [&candidates](std::shared_ptr<Variable>& var){ candidates.erase(var);}); } else { candidates.erase(quadruple.result); if_init<std::shared_ptr<Variable>>(quadruple.arg1, [&candidates](std::shared_ptr<Variable>& var){ candidates.erase(var); }); if_init<std::shared_ptr<Variable>>(quadruple.arg2, [&candidates](std::shared_ptr<Variable>& var){ candidates.erase(var); }); } } } if(!candidates.empty()){ for(auto& block : function){ for(auto& quadruple : block->statements){ if(quadruple.result && mtac::erase_result(quadruple.op) && candidates.find(quadruple.result) != candidates.end()){ mtac::transform_to_nop(quadruple); optimized = true; } } } } //TODO Review or remove this optimization, this is quite unsafe std::unordered_set<Offset, mtac::OffsetHash> used_offsets; std::unordered_set<std::shared_ptr<Variable>> invalidated_offsets; for(auto& block : function){ for(auto& quadruple : block->statements){ if(quadruple.op == mtac::Operator::DOT || quadruple.op == mtac::Operator::FDOT || quadruple.op == mtac::Operator::PDOT){ if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){ if(auto* offset_ptr = boost::get<int>(&*quadruple.arg2)){ mtac::Offset offset(*var_ptr, *offset_ptr); used_offsets.insert(offset); } else { invalidated_offsets.insert(*var_ptr); } } } } } for(auto& block : function){ for(auto& quadruple : block->statements){ if(quadruple.op == mtac::Operator::DOT_ASSIGN || quadruple.op == mtac::Operator::DOT_FASSIGN || quadruple.op == mtac::Operator::DOT_PASSIGN){ if(invalidated_offsets.find(quadruple.result) == invalidated_offsets.end()){ //Arrays are a problem because they are not considered as escaped after being passed in parameters if(!quadruple.result->type()->is_pointer() && !quadruple.result->type()->is_array()){ if(auto* offset_ptr = boost::get<int>(&*quadruple.arg1)){ if(quadruple.result->type()->is_custom_type() || quadruple.result->type()->is_template_type()){ auto struct_type = function.context->global()->get_struct(quadruple.result->type()->mangle()); auto member_type = function.context->global()->member_type(struct_type, *offset_ptr); if(member_type->is_pointer()){ continue; } } mtac::Offset offset(quadruple.result, *offset_ptr); if(problem.pointer_escaped->find(quadruple.result) == problem.pointer_escaped->end() && used_offsets.find(offset) == used_offsets.end()){ mtac::transform_to_nop(quadruple); optimized=true; } } } } } } } return optimized; } <|endoftext|>
<commit_before>#include "planning/jet/jet_model.hh" #include "geometry/visualization/put_collada.hh" #include "viewer/primitives/simple_geometry.hh" // TODO #include <set> namespace planning { namespace jet { void JetModel::insert(viewer::SceneTree& tree) const { const SE3 world_from_jet = SE3(); const auto dummy_geo = std::make_shared<viewer::SimpleGeometry>(); tree.add_primitive("root", world_from_jet, model_.root(), dummy_geo); std::map<std::string, SE3> world_from_node; world_from_node[model_.root()] = world_from_jet; std::stack<std::string> to_visit; to_visit.push(model_.root()); const auto& adj = model_.adjacency(); const auto& meshes = model_.meshes(); const auto& colors = model_.colors(); while (!to_visit.empty()) { const auto key = to_visit.top(); to_visit.pop(); std::cout << "Visiting: " << key << std::endl; if (adj.count(key) == 0) { continue; } const SE3 world_from_parent = world_from_node.at(key); for (const auto& edge : adj.at(key)) { world_from_node[edge.child_name] = world_from_parent * edge.child_from_parent.inverse(); to_visit.push(edge.child_name); const auto geo = std::make_shared<viewer::SimpleGeometry>(); const auto& mesh = meshes.at(edge.child_name); if (colors.count(edge.child_name)) { const jcc::Vec4 color = colors.at(edge.child_name); geo->add_triangle_mesh({mesh, SE3(), color, true, 3.0, false}); } geo->flip(); tree.add_primitive(key, edge.child_from_parent.inverse(), edge.child_name, geo); } } } } // namespace jet } // namespace planning<commit_msg>Remove printouts from model<commit_after>#include "planning/jet/jet_model.hh" #include "geometry/visualization/put_collada.hh" #include "viewer/primitives/simple_geometry.hh" // TODO #include <set> namespace planning { namespace jet { void JetModel::insert(viewer::SceneTree& tree) const { const SE3 world_from_jet = SE3(); const auto dummy_geo = std::make_shared<viewer::SimpleGeometry>(); tree.add_primitive("root", world_from_jet, model_.root(), dummy_geo); std::map<std::string, SE3> world_from_node; world_from_node[model_.root()] = world_from_jet; std::stack<std::string> to_visit; to_visit.push(model_.root()); const auto& adj = model_.adjacency(); const auto& meshes = model_.meshes(); const auto& colors = model_.colors(); while (!to_visit.empty()) { const auto key = to_visit.top(); to_visit.pop(); if (adj.count(key) == 0) { continue; } const SE3 world_from_parent = world_from_node.at(key); for (const auto& edge : adj.at(key)) { world_from_node[edge.child_name] = world_from_parent * edge.child_from_parent.inverse(); to_visit.push(edge.child_name); const auto geo = std::make_shared<viewer::SimpleGeometry>(); const auto& mesh = meshes.at(edge.child_name); if (colors.count(edge.child_name)) { const jcc::Vec4 color = colors.at(edge.child_name); geo->add_triangle_mesh({mesh, SE3(), color, true, 3.0, false}); } geo->flip(); tree.add_primitive(key, edge.child_from_parent.inverse(), edge.child_name, geo); } } } } // namespace jet } // namespace planning<|endoftext|>
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OS_POSIX_FORK_HPP__ #define __STOUT_OS_POSIX_FORK_HPP__ #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #ifdef __FreeBSD__ #include <sys/stat.h> #endif // __FreeBSD__ #include <sys/types.h> #include <sys/wait.h> #include <atomic> #include <list> #include <memory> #include <set> #include <string> #include <stout/abort.hpp> #include <stout/check.hpp> #include <stout/error.hpp> #include <stout/exit.hpp> #include <stout/foreach.hpp> #include <stout/os/strerror.hpp> #include <stout/stringify.hpp> #include <stout/try.hpp> #include <stout/os/close.hpp> #include <stout/os/ftruncate.hpp> #include <stout/os/process.hpp> // Abstractions around forking process trees. You can declare a // process tree "template" using 'Fork', 'Exec', and 'Wait'. For // example, to describe a simple "fork/exec" you can do: // // Fork f = Fork(Exec("sleep 10)); // // The command passed to an 'Exec' is run via 'sh -c'. You can // construct more complicated templates via nesting, for example: // // Fork f = // Fork(None(), // Fork(Exec("echo 'grandchild 1'")), // Fork(None(), // Fork(Exec("echo 'great-grandchild'")), // Exec("echo 'grandchild 2'")) // Exec("echo 'child'")); // // Note that the first argument to 'Fork' here is an optional function // that can be invoked before forking any more children or executing a // command. THIS FUNCTION SHOULD BE ASYNC SIGNAL SAFE. // // To wait for children, you can use 'Wait' instead of 'Exec', for // example: // // Fork f = // Fork(None(), // Fork(Exec("echo 'grandchild 1'")), // Fork(Exec("echo 'grandchild 2'")), // Wait()); // // You can also omit either an 'Exec' or a 'Wait' and the forked // process will just 'exit(0)'. For example, the following will cause // to processes to get reparented by 'init'. // // Fork f = // Fork(None(), // Fork(Exec("echo 'grandchild 1'")), // Fork(Exec("echo 'grandchild 2'"))); // // A template can be instantiated by invoking the 'Fork' as a // functor. For example, using any of the templates above we can do: // // Try<ProcessTree> tree = f(); // // It's important to note that the process tree returned represents // the instant in time after the forking has completed but before // 'Exec', 'Wait' or 'exit(0)' has occurred (i.e., the process tree // will be complete). namespace os { // Forward declaration. inline Result<Process> process(pid_t); struct Exec { Exec(const std::string& _command) : command(_command) {} const std::string command; }; struct Wait {}; struct Fork { // -+- parent. Fork(const Option<void(*)()>& _function, const Exec& _exec) : function(_function), exec(_exec) {} Fork(const Exec& _exec) : exec(_exec) {} // -+- parent // \--- child. Fork(const Option<void(*)()>& _function, const Fork& fork1) : function(_function) { children.push_back(fork1); } Fork(const Option<void(*)()>& _function, const Fork& fork1, const Exec& _exec) : function(_function), exec(_exec) { children.push_back(fork1); } Fork(const Option<void(*)()>& _function, const Fork& fork1, const Wait& _wait) : function(_function), wait(_wait) { children.push_back(fork1); } // -+- parent // |--- child // \--- child. Fork(const Option<void(*)()>& _function, const Fork& fork1, const Fork& fork2) : function(_function) { children.push_back(fork1); children.push_back(fork2); } Fork(const Option<void(*)()>& _function, const Fork& fork1, const Fork& fork2, const Exec& _exec) : function(_function), exec(_exec) { children.push_back(fork1); children.push_back(fork2); } Fork(const Option<void(*)()>& _function, const Fork& fork1, const Fork& fork2, const Wait& _wait) : function(_function), wait(_wait) { children.push_back(fork1); children.push_back(fork2); } // -+- parent // |--- child // |--- child // \--- child. Fork(const Option<void(*)()>& _function, const Fork& fork1, const Fork& fork2, const Fork& fork3) : function(_function) { children.push_back(fork1); children.push_back(fork2); children.push_back(fork3); } Fork(const Option<void(*)()>& _function, const Fork& fork1, const Fork& fork2, const Fork& fork3, const Exec& _exec) : function(_function), exec(_exec) { children.push_back(fork1); children.push_back(fork2); children.push_back(fork3); } Fork(const Option<void(*)()>& _function, const Fork& fork1, const Fork& fork2, const Fork& fork3, const Wait& _wait) : function(_function), wait(_wait) { children.push_back(fork1); children.push_back(fork2); children.push_back(fork3); } private: // Represents the "tree" of descendants where each node has a // pointer (into shared memory) from which we can read the // descendants process information as well as a vector of children. struct Tree { // NOTE: This struct is stored in shared memory and thus cannot // hold any pointers to heap allocated memory. struct Memory { pid_t pid; pid_t parent; pid_t group; pid_t session; std::atomic_bool set; // Has this been initialized? }; std::shared_ptr<Memory> memory; std::vector<Tree> children; }; // We use shared memory to "share" the pids of forked descendants. // The benefit of shared memory over pipes is that each forked // process can read its descendants' pids leading to a simpler // implementation (with pipes, only one reader can ever read the // value from the pipe, forcing much more complicated coordination). // // Shared memory works like a file (in memory) that gets deleted by // "unlinking" it, but it won't get completely deleted until all // open file descriptors referencing it have been closed. Each // forked process has the shared memory mapped into it as well as an // open file descriptor, both of which should get cleaned up // automagically when the process exits, but we use a special // "deleter" (in combination with shared_ptr) in order to clean this // stuff up when we are actually finished using the shared memory. struct SharedMemoryDeleter { SharedMemoryDeleter(int _fd) : fd(_fd) {} void operator()(Tree::Memory* process) const { if (munmap(process, sizeof(Tree::Memory)) == -1) { ABORT(std::string("Failed to unmap memory: ") + os::strerror(errno)); } if (::close(fd) == -1) { ABORT(std::string("Failed to close shared memory file descriptor: ") + os::strerror(errno)); } } const int fd; }; // Constructs a Tree (see above) from this fork template. Try<Tree> prepare() const { static std::atomic_int forks(0); // Each "instance" of an instantiated Fork needs a unique name for // creating shared memory. int instance = forks.fetch_add(1); std::string name = "/stout-forks-" + stringify(getpid()) + stringify(instance); int fd = shm_open(name.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); if (fd == -1) { return ErrnoError("Failed to open a shared memory object"); } Try<Nothing> truncated = ftruncate(fd, sizeof(Tree::Memory)); if (truncated.isError()) { return Error( "Failed to set size of shared memory object: " + truncated.error()); } void* memory = mmap( nullptr, sizeof(Tree::Memory), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (memory == MAP_FAILED) { return ErrnoError("Failed to map shared memory object"); } if (shm_unlink(name.c_str()) == -1) { return ErrnoError("Failed to unlink shared memory object"); } SharedMemoryDeleter deleter(fd); Tree tree; tree.memory = std::shared_ptr<Tree::Memory>((Tree::Memory*)memory, deleter); tree.memory->set.store(false); for (size_t i = 0; i < children.size(); i++) { Try<Tree> tree_ = children[i].prepare(); if (tree_.isError()) { return Error(tree_.error()); } tree.children.push_back(tree_.get()); } return tree; } // Performs the fork, executes the function, recursively // instantiates any children, and then executes/waits/exits. pid_t instantiate(const Tree& tree) const { pid_t pid = ::fork(); if (pid > 0) { return pid; } // Set the basic process information. Tree::Memory process; process.pid = getpid(); process.parent = getppid(); process.group = getpgid(0); process.session = getsid(0); process.set.store(true); // Copy it into shared memory. memcpy(tree.memory.get(), &process, sizeof(Tree::Memory)); // Execute the function, if any. if (function.isSome()) { function.get()(); } // Fork the children, if any. CHECK(children.size() == tree.children.size()); std::set<pid_t> pids; for (size_t i = 0; i < children.size(); i++) { pids.insert(children[i].instantiate(tree.children[i])); } // Execute or wait. if (exec.isSome()) { // Execute the command (via '/bin/sh -c command'). const char* command = exec->command.c_str(); execlp("sh", "sh", "-c", command, (char*) nullptr); EXIT(EXIT_FAILURE) << "Failed to execute '" << command << "': " << os::strerror(errno); } else if (wait.isSome()) { foreach (pid_t pid, pids) { // TODO(benh): Check for signal interruption or other errors. waitpid(pid, nullptr, 0); } } exit(0); return -1; } // Waits for all of the descendant processes in the tree to update // their pids and constructs a ProcessTree using the Tree::Memory // information from shared memory. static Try<ProcessTree> coordinate(const Tree& tree) { // Wait for the forked process. // TODO(benh): Don't wait forever? while (!tree.memory->set.load()); // All processes in the returned ProcessTree will have the // command-line of the top level process, since we construct the // tree using post-fork pre-exec information. So, we'll grab the // command of the current process here. Result<Process> self = os::process(getpid()); Process process = Process( tree.memory->pid, tree.memory->parent, tree.memory->group, tree.memory->session, None(), None(), None(), self.isSome() ? self->command : "", false); std::list<ProcessTree> children; for (size_t i = 0; i < tree.children.size(); i++) { Try<ProcessTree> child = coordinate(tree.children[i]); if (child.isError()) { return Error(child.error()); } children.push_back(child.get()); } return ProcessTree(process, children); } public: // Prepares and instantiates the process tree. Try<ProcessTree> operator()() const { Try<Tree> tree = prepare(); if (tree.isError()) { return Error(tree.error()); } Try<pid_t> pid = instantiate(tree.get()); if (pid.isError()) { return Error(pid.error()); } return coordinate(tree.get()); } private: Option<void(*)()> function; Option<const Exec> exec; Option<const Wait> wait; std::vector<Fork> children; }; } // namespace os { #endif // __STOUT_OS_POSIX_FORK_HPP__ <commit_msg>Removed memcpy from os::Fork::instantiate.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OS_POSIX_FORK_HPP__ #define __STOUT_OS_POSIX_FORK_HPP__ #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #ifdef __FreeBSD__ #include <sys/stat.h> #endif // __FreeBSD__ #include <sys/types.h> #include <sys/wait.h> #include <atomic> #include <list> #include <memory> #include <set> #include <string> #include <stout/abort.hpp> #include <stout/check.hpp> #include <stout/error.hpp> #include <stout/exit.hpp> #include <stout/foreach.hpp> #include <stout/os/strerror.hpp> #include <stout/stringify.hpp> #include <stout/try.hpp> #include <stout/os/close.hpp> #include <stout/os/ftruncate.hpp> #include <stout/os/process.hpp> // Abstractions around forking process trees. You can declare a // process tree "template" using 'Fork', 'Exec', and 'Wait'. For // example, to describe a simple "fork/exec" you can do: // // Fork f = Fork(Exec("sleep 10)); // // The command passed to an 'Exec' is run via 'sh -c'. You can // construct more complicated templates via nesting, for example: // // Fork f = // Fork(None(), // Fork(Exec("echo 'grandchild 1'")), // Fork(None(), // Fork(Exec("echo 'great-grandchild'")), // Exec("echo 'grandchild 2'")) // Exec("echo 'child'")); // // Note that the first argument to 'Fork' here is an optional function // that can be invoked before forking any more children or executing a // command. THIS FUNCTION SHOULD BE ASYNC SIGNAL SAFE. // // To wait for children, you can use 'Wait' instead of 'Exec', for // example: // // Fork f = // Fork(None(), // Fork(Exec("echo 'grandchild 1'")), // Fork(Exec("echo 'grandchild 2'")), // Wait()); // // You can also omit either an 'Exec' or a 'Wait' and the forked // process will just 'exit(0)'. For example, the following will cause // to processes to get reparented by 'init'. // // Fork f = // Fork(None(), // Fork(Exec("echo 'grandchild 1'")), // Fork(Exec("echo 'grandchild 2'"))); // // A template can be instantiated by invoking the 'Fork' as a // functor. For example, using any of the templates above we can do: // // Try<ProcessTree> tree = f(); // // It's important to note that the process tree returned represents // the instant in time after the forking has completed but before // 'Exec', 'Wait' or 'exit(0)' has occurred (i.e., the process tree // will be complete). namespace os { // Forward declaration. inline Result<Process> process(pid_t); struct Exec { Exec(const std::string& _command) : command(_command) {} const std::string command; }; struct Wait {}; struct Fork { // -+- parent. Fork(const Option<void(*)()>& _function, const Exec& _exec) : function(_function), exec(_exec) {} Fork(const Exec& _exec) : exec(_exec) {} // -+- parent // \--- child. Fork(const Option<void(*)()>& _function, const Fork& fork1) : function(_function) { children.push_back(fork1); } Fork(const Option<void(*)()>& _function, const Fork& fork1, const Exec& _exec) : function(_function), exec(_exec) { children.push_back(fork1); } Fork(const Option<void(*)()>& _function, const Fork& fork1, const Wait& _wait) : function(_function), wait(_wait) { children.push_back(fork1); } // -+- parent // |--- child // \--- child. Fork(const Option<void(*)()>& _function, const Fork& fork1, const Fork& fork2) : function(_function) { children.push_back(fork1); children.push_back(fork2); } Fork(const Option<void(*)()>& _function, const Fork& fork1, const Fork& fork2, const Exec& _exec) : function(_function), exec(_exec) { children.push_back(fork1); children.push_back(fork2); } Fork(const Option<void(*)()>& _function, const Fork& fork1, const Fork& fork2, const Wait& _wait) : function(_function), wait(_wait) { children.push_back(fork1); children.push_back(fork2); } // -+- parent // |--- child // |--- child // \--- child. Fork(const Option<void(*)()>& _function, const Fork& fork1, const Fork& fork2, const Fork& fork3) : function(_function) { children.push_back(fork1); children.push_back(fork2); children.push_back(fork3); } Fork(const Option<void(*)()>& _function, const Fork& fork1, const Fork& fork2, const Fork& fork3, const Exec& _exec) : function(_function), exec(_exec) { children.push_back(fork1); children.push_back(fork2); children.push_back(fork3); } Fork(const Option<void(*)()>& _function, const Fork& fork1, const Fork& fork2, const Fork& fork3, const Wait& _wait) : function(_function), wait(_wait) { children.push_back(fork1); children.push_back(fork2); children.push_back(fork3); } private: // Represents the "tree" of descendants where each node has a // pointer (into shared memory) from which we can read the // descendants process information as well as a vector of children. struct Tree { // NOTE: This struct is stored in shared memory and thus cannot // hold any pointers to heap allocated memory. struct Memory { pid_t pid; pid_t parent; pid_t group; pid_t session; std::atomic_bool set; // Has this been initialized? }; std::shared_ptr<Memory> memory; std::vector<Tree> children; }; // We use shared memory to "share" the pids of forked descendants. // The benefit of shared memory over pipes is that each forked // process can read its descendants' pids leading to a simpler // implementation (with pipes, only one reader can ever read the // value from the pipe, forcing much more complicated coordination). // // Shared memory works like a file (in memory) that gets deleted by // "unlinking" it, but it won't get completely deleted until all // open file descriptors referencing it have been closed. Each // forked process has the shared memory mapped into it as well as an // open file descriptor, both of which should get cleaned up // automagically when the process exits, but we use a special // "deleter" (in combination with shared_ptr) in order to clean this // stuff up when we are actually finished using the shared memory. struct SharedMemoryDeleter { SharedMemoryDeleter(int _fd) : fd(_fd) {} void operator()(Tree::Memory* process) const { if (munmap(process, sizeof(Tree::Memory)) == -1) { ABORT(std::string("Failed to unmap memory: ") + os::strerror(errno)); } if (::close(fd) == -1) { ABORT(std::string("Failed to close shared memory file descriptor: ") + os::strerror(errno)); } } const int fd; }; // Constructs a Tree (see above) from this fork template. Try<Tree> prepare() const { static std::atomic_int forks(0); // Each "instance" of an instantiated Fork needs a unique name for // creating shared memory. int instance = forks.fetch_add(1); std::string name = "/stout-forks-" + stringify(getpid()) + stringify(instance); int fd = shm_open(name.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); if (fd == -1) { return ErrnoError("Failed to open a shared memory object"); } Try<Nothing> truncated = ftruncate(fd, sizeof(Tree::Memory)); if (truncated.isError()) { return Error( "Failed to set size of shared memory object: " + truncated.error()); } void* memory = mmap( nullptr, sizeof(Tree::Memory), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (memory == MAP_FAILED) { return ErrnoError("Failed to map shared memory object"); } if (shm_unlink(name.c_str()) == -1) { return ErrnoError("Failed to unlink shared memory object"); } SharedMemoryDeleter deleter(fd); Tree tree; tree.memory = std::shared_ptr<Tree::Memory>((Tree::Memory*)memory, deleter); tree.memory->set.store(false); for (size_t i = 0; i < children.size(); i++) { Try<Tree> tree_ = children[i].prepare(); if (tree_.isError()) { return Error(tree_.error()); } tree.children.push_back(tree_.get()); } return tree; } // Performs the fork, executes the function, recursively // instantiates any children, and then executes/waits/exits. pid_t instantiate(const Tree& tree) const { pid_t pid = ::fork(); if (pid > 0) { return pid; } // Set the basic process information into shared memory. tree.memory->pid = getpid(); tree.memory->parent = getppid(); tree.memory->group = getpgid(0); tree.memory->session = getsid(0); tree.memory->set.store(true); // Execute the function, if any. if (function.isSome()) { function.get()(); } // Fork the children, if any. CHECK(children.size() == tree.children.size()); std::set<pid_t> pids; for (size_t i = 0; i < children.size(); i++) { pids.insert(children[i].instantiate(tree.children[i])); } // Execute or wait. if (exec.isSome()) { // Execute the command (via '/bin/sh -c command'). const char* command = exec->command.c_str(); execlp("sh", "sh", "-c", command, (char*) nullptr); EXIT(EXIT_FAILURE) << "Failed to execute '" << command << "': " << os::strerror(errno); } else if (wait.isSome()) { foreach (pid_t pid, pids) { // TODO(benh): Check for signal interruption or other errors. waitpid(pid, nullptr, 0); } } exit(0); return -1; } // Waits for all of the descendant processes in the tree to update // their pids and constructs a ProcessTree using the Tree::Memory // information from shared memory. static Try<ProcessTree> coordinate(const Tree& tree) { // Wait for the forked process. // TODO(benh): Don't wait forever? while (!tree.memory->set.load()); // All processes in the returned ProcessTree will have the // command-line of the top level process, since we construct the // tree using post-fork pre-exec information. So, we'll grab the // command of the current process here. Result<Process> self = os::process(getpid()); Process process = Process( tree.memory->pid, tree.memory->parent, tree.memory->group, tree.memory->session, None(), None(), None(), self.isSome() ? self->command : "", false); std::list<ProcessTree> children; for (size_t i = 0; i < tree.children.size(); i++) { Try<ProcessTree> child = coordinate(tree.children[i]); if (child.isError()) { return Error(child.error()); } children.push_back(child.get()); } return ProcessTree(process, children); } public: // Prepares and instantiates the process tree. Try<ProcessTree> operator()() const { Try<Tree> tree = prepare(); if (tree.isError()) { return Error(tree.error()); } Try<pid_t> pid = instantiate(tree.get()); if (pid.isError()) { return Error(pid.error()); } return coordinate(tree.get()); } private: Option<void(*)()> function; Option<const Exec> exec; Option<const Wait> wait; std::vector<Fork> children; }; } // namespace os { #endif // __STOUT_OS_POSIX_FORK_HPP__ <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2011 Shantanu Tushar <jhahoneyk@gmail.com> * * 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 "licensejob.h" #include <attica/provider.h> using namespace GluonPlayer; class LicenseItem::Private { public: Private() { } QString id; QString licenseName; QString licenseWebsite; }; LicenseItem::LicenseItem( const QString& id, const QString& licenseName, const QString& licenseWebsite, QObject* parent ) : QObject( parent ), d( new Private() ) { d->id = id; d->licenseName = licenseName; d->licenseWebsite = licenseWebsite; } LicenseItem::~LicenseItem() { delete d; } QString LicenseItem::licenseName() const { return d->licenseName; } QString LicenseItem::id() const { return d->id; } QString LicenseItem::licenseWebsite() const { return d->licenseWebsite; } class LicenseJob::Private { public: Private() { } QList<LicenseItem*> licenseList; }; LicenseJob::LicenseJob( Attica::Provider* provider, QObject* parent ) : AbstractSocialServicesJob(provider) , d(new Private()) { } LicenseJob::~LicenseJob() { delete d; } void LicenseJob::startSocialService() { Attica::ListJob<Attica::License> *job = provider()->requestLicenses(); connect( job, SIGNAL( finished( Attica::BaseJob* ) ), SLOT( processFetchedLicenses( Attica::BaseJob* ) ) ); job->start(); } void LicenseJob::processFetchedLicenses( Attica::BaseJob* job ) { Attica::ListJob<Attica::License> *licensesJob = static_cast<Attica::ListJob<Attica::License> *>( job ); if( licensesJob->metadata().error() == Attica::Metadata::NoError ) { foreach( Attica::License license, licensesJob->itemList() ) { LicenseItem* newLicense = new LicenseItem( QString::number( license.id() ), license.name(), license.url().toString(), this ); d->licenseList.append( newLicense ); } emitSucceeded(); } else { emitFailed(); } } QVariant LicenseJob::data() { return QVariant::fromValue(d->licenseList); } #include "licensejob.moc" <commit_msg>Use const reference in for each loops as much as possible<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2011 Shantanu Tushar <jhahoneyk@gmail.com> * * 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 "licensejob.h" #include <attica/provider.h> using namespace GluonPlayer; class LicenseItem::Private { public: Private() { } QString id; QString licenseName; QString licenseWebsite; }; LicenseItem::LicenseItem( const QString& id, const QString& licenseName, const QString& licenseWebsite, QObject* parent ) : QObject( parent ), d( new Private() ) { d->id = id; d->licenseName = licenseName; d->licenseWebsite = licenseWebsite; } LicenseItem::~LicenseItem() { delete d; } QString LicenseItem::licenseName() const { return d->licenseName; } QString LicenseItem::id() const { return d->id; } QString LicenseItem::licenseWebsite() const { return d->licenseWebsite; } class LicenseJob::Private { public: Private() { } QList<LicenseItem*> licenseList; }; LicenseJob::LicenseJob( Attica::Provider* provider, QObject* parent ) : AbstractSocialServicesJob(provider) , d(new Private()) { } LicenseJob::~LicenseJob() { delete d; } void LicenseJob::startSocialService() { Attica::ListJob<Attica::License> *job = provider()->requestLicenses(); connect( job, SIGNAL( finished( Attica::BaseJob* ) ), SLOT( processFetchedLicenses( Attica::BaseJob* ) ) ); job->start(); } void LicenseJob::processFetchedLicenses( Attica::BaseJob* job ) { Attica::ListJob<Attica::License> *licensesJob = static_cast<Attica::ListJob<Attica::License> *>( job ); if( licensesJob->metadata().error() == Attica::Metadata::NoError ) { foreach( const Attica::License& license, licensesJob->itemList() ) { LicenseItem* newLicense = new LicenseItem( QString::number( license.id() ), license.name(), license.url().toString(), this ); d->licenseList.append( newLicense ); } emitSucceeded(); } else { emitFailed(); } } QVariant LicenseJob::data() { return QVariant::fromValue(d->licenseList); } #include "licensejob.moc" <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "protocol.h" #include <cpptools/cpptoolsconstants.h> #include <qmljseditor/qmljseditorconstants.h> #include <coreplugin/icore.h> #include <coreplugin/dialogs/ioptionspage.h> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkRequest> #include <QtNetwork/QNetworkReply> #include <QtCore/QUrl> #include <QtCore/QDebug> #include <QtGui/QMessageBox> #include <QtGui/QApplication> #include <QtGui/QMainWindow> #include <QtGui/QPushButton> namespace CodePaster { Protocol::Protocol() : QObject() { } Protocol::~Protocol() { } bool Protocol::hasSettings() const { return false; } bool Protocol::checkConfiguration(QString *) { return true; } Core::IOptionsPage *Protocol::settingsPage() const { return 0; } void Protocol::list() { qFatal("Base Protocol list() called"); } Protocol::ContentType Protocol::contentType(const QString &mt) { if (mt == QLatin1String(CppTools::Constants::C_SOURCE_MIMETYPE) || mt == QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE) || mt == QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE) || mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE) || mt == QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)) return C; if (mt == QLatin1String(QmlJSEditor::Constants::QML_MIMETYPE) || mt == QLatin1String(QmlJSEditor::Constants::JS_MIMETYPE)) return JavaScript; if (mt == QLatin1String("text/x-patch")) return Diff; if (mt == QLatin1String("text/xml") || mt == QLatin1String("application/xml")) return Xml; return Text; } QString Protocol::fixNewLines(QString data) { // Copied from cpaster. Otherwise lineendings will screw up // HTML requires "\r\n". if (data.contains(QLatin1String("\r\n"))) return data; if (data.contains(QLatin1Char('\n'))) { data.replace(QLatin1Char('\n'), QLatin1String("\r\n")); return data; } if (data.contains(QLatin1Char('\r'))) data.replace(QLatin1Char('\r'), QLatin1String("\r\n")); return data; } QString Protocol::textFromHtml(QString data) { data.remove(QLatin1Char('\r')); data.replace(QLatin1String("&lt;"), QString(QLatin1Char('<'))); data.replace(QLatin1String("&gt;"), QString(QLatin1Char('>'))); data.replace(QLatin1String("&amp;"), QString(QLatin1Char('&'))); data.replace(QLatin1String("&quot;"), QString(QLatin1Char('"'))); return data; } bool Protocol::ensureConfiguration(Protocol *p, QWidget *parent) { QString errorMessage; bool ok = false; while (true) { if (p->checkConfiguration(&errorMessage)) { ok = true; break; } // Cancel returns empty error message. if (errorMessage.isEmpty() || !showConfigurationError(p, errorMessage, parent)) break; } return ok; } bool Protocol::showConfigurationError(const Protocol *p, const QString &message, QWidget *parent, bool showConfig) { if (!p->settingsPage()) showConfig = false; if (!parent) parent = Core::ICore::instance()->mainWindow(); const QString title = tr("%1 - Configuration Error").arg(p->name()); QMessageBox mb(QMessageBox::Warning, title, message, QMessageBox::Cancel, parent); QPushButton *settingsButton = 0; if (showConfig) settingsButton = mb.addButton(tr("Settings..."), QMessageBox::AcceptRole); mb.exec(); bool rc = false; if (mb.clickedButton() == settingsButton) rc = Core::ICore::instance()->showOptionsDialog(p->settingsPage()->category(), p->settingsPage()->id(), parent); return rc; } // ------------ NetworkAccessManagerProxy NetworkAccessManagerProxy::NetworkAccessManagerProxy() { } NetworkAccessManagerProxy::~NetworkAccessManagerProxy() { } QNetworkReply *NetworkAccessManagerProxy::httpGet(const QString &link) { QUrl url(link); QNetworkRequest r(url); return networkAccessManager()->get(r); } QNetworkReply *NetworkAccessManagerProxy::httpPost(const QString &link, const QByteArray &data) { QUrl url(link); QNetworkRequest r(url); return networkAccessManager()->post(r, data); } QNetworkAccessManager *NetworkAccessManagerProxy::networkAccessManager() { if (m_networkAccessManager.isNull()) m_networkAccessManager.reset(new QNetworkAccessManager); return m_networkAccessManager.data(); } // --------- NetworkProtocol NetworkProtocol::NetworkProtocol(const NetworkAccessManagerProxyPtr &nw) : m_networkAccessManager(nw) { } NetworkProtocol::~NetworkProtocol() { } bool NetworkProtocol::httpStatus(QString url, QString *errorMessage) { // Connect to host and display a message box, using its event loop. errorMessage->clear(); const QString httpPrefix = QLatin1String("http://"); if (!url.startsWith(httpPrefix)) { url.prepend(httpPrefix); url.append(QLatin1Char('/')); } QScopedPointer<QNetworkReply> reply(httpGet(url)); QMessageBox box(QMessageBox::Information, tr("Checking connection"), tr("Connecting to %1...").arg(url), QMessageBox::Cancel, Core::ICore::instance()->mainWindow()); connect(reply.data(), SIGNAL(finished()), &box, SLOT(close())); QApplication::setOverrideCursor(Qt::WaitCursor); box.exec(); QApplication::restoreOverrideCursor(); // User canceled, discard and be happy. if (!reply->isFinished()) { QNetworkReply *replyPtr = reply.take(); connect(replyPtr, SIGNAL(finished()), replyPtr, SLOT(deleteLater())); return false; } // Passed if (reply->error() == QNetworkReply::NoError) return true; // Error. *errorMessage = reply->errorString(); return false; } } //namespace CodePaster <commit_msg>CodePaster: Specify correct content type for Qt 4.8.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "protocol.h" #include <cpptools/cpptoolsconstants.h> #include <qmljseditor/qmljseditorconstants.h> #include <coreplugin/icore.h> #include <coreplugin/dialogs/ioptionspage.h> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkRequest> #include <QtNetwork/QNetworkReply> #include <QtCore/QUrl> #include <QtCore/QDebug> #include <QtCore/QVariant> #include <QtGui/QMessageBox> #include <QtGui/QApplication> #include <QtGui/QMainWindow> #include <QtGui/QPushButton> namespace CodePaster { Protocol::Protocol() : QObject() { } Protocol::~Protocol() { } bool Protocol::hasSettings() const { return false; } bool Protocol::checkConfiguration(QString *) { return true; } Core::IOptionsPage *Protocol::settingsPage() const { return 0; } void Protocol::list() { qFatal("Base Protocol list() called"); } Protocol::ContentType Protocol::contentType(const QString &mt) { if (mt == QLatin1String(CppTools::Constants::C_SOURCE_MIMETYPE) || mt == QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE) || mt == QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE) || mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE) || mt == QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)) return C; if (mt == QLatin1String(QmlJSEditor::Constants::QML_MIMETYPE) || mt == QLatin1String(QmlJSEditor::Constants::JS_MIMETYPE)) return JavaScript; if (mt == QLatin1String("text/x-patch")) return Diff; if (mt == QLatin1String("text/xml") || mt == QLatin1String("application/xml")) return Xml; return Text; } QString Protocol::fixNewLines(QString data) { // Copied from cpaster. Otherwise lineendings will screw up // HTML requires "\r\n". if (data.contains(QLatin1String("\r\n"))) return data; if (data.contains(QLatin1Char('\n'))) { data.replace(QLatin1Char('\n'), QLatin1String("\r\n")); return data; } if (data.contains(QLatin1Char('\r'))) data.replace(QLatin1Char('\r'), QLatin1String("\r\n")); return data; } QString Protocol::textFromHtml(QString data) { data.remove(QLatin1Char('\r')); data.replace(QLatin1String("&lt;"), QString(QLatin1Char('<'))); data.replace(QLatin1String("&gt;"), QString(QLatin1Char('>'))); data.replace(QLatin1String("&amp;"), QString(QLatin1Char('&'))); data.replace(QLatin1String("&quot;"), QString(QLatin1Char('"'))); return data; } bool Protocol::ensureConfiguration(Protocol *p, QWidget *parent) { QString errorMessage; bool ok = false; while (true) { if (p->checkConfiguration(&errorMessage)) { ok = true; break; } // Cancel returns empty error message. if (errorMessage.isEmpty() || !showConfigurationError(p, errorMessage, parent)) break; } return ok; } bool Protocol::showConfigurationError(const Protocol *p, const QString &message, QWidget *parent, bool showConfig) { if (!p->settingsPage()) showConfig = false; if (!parent) parent = Core::ICore::instance()->mainWindow(); const QString title = tr("%1 - Configuration Error").arg(p->name()); QMessageBox mb(QMessageBox::Warning, title, message, QMessageBox::Cancel, parent); QPushButton *settingsButton = 0; if (showConfig) settingsButton = mb.addButton(tr("Settings..."), QMessageBox::AcceptRole); mb.exec(); bool rc = false; if (mb.clickedButton() == settingsButton) rc = Core::ICore::instance()->showOptionsDialog(p->settingsPage()->category(), p->settingsPage()->id(), parent); return rc; } // ------------ NetworkAccessManagerProxy NetworkAccessManagerProxy::NetworkAccessManagerProxy() { } NetworkAccessManagerProxy::~NetworkAccessManagerProxy() { } QNetworkReply *NetworkAccessManagerProxy::httpGet(const QString &link) { QUrl url(link); QNetworkRequest r(url); return networkAccessManager()->get(r); } QNetworkReply *NetworkAccessManagerProxy::httpPost(const QString &link, const QByteArray &data) { QUrl url(link); QNetworkRequest r(url); // Required for Qt 4.8 r.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(QByteArray("application/x-www-form-urlencoded"))); return networkAccessManager()->post(r, data); } QNetworkAccessManager *NetworkAccessManagerProxy::networkAccessManager() { if (m_networkAccessManager.isNull()) m_networkAccessManager.reset(new QNetworkAccessManager); return m_networkAccessManager.data(); } // --------- NetworkProtocol NetworkProtocol::NetworkProtocol(const NetworkAccessManagerProxyPtr &nw) : m_networkAccessManager(nw) { } NetworkProtocol::~NetworkProtocol() { } bool NetworkProtocol::httpStatus(QString url, QString *errorMessage) { // Connect to host and display a message box, using its event loop. errorMessage->clear(); const QString httpPrefix = QLatin1String("http://"); if (!url.startsWith(httpPrefix)) { url.prepend(httpPrefix); url.append(QLatin1Char('/')); } QScopedPointer<QNetworkReply> reply(httpGet(url)); QMessageBox box(QMessageBox::Information, tr("Checking connection"), tr("Connecting to %1...").arg(url), QMessageBox::Cancel, Core::ICore::instance()->mainWindow()); connect(reply.data(), SIGNAL(finished()), &box, SLOT(close())); QApplication::setOverrideCursor(Qt::WaitCursor); box.exec(); QApplication::restoreOverrideCursor(); // User canceled, discard and be happy. if (!reply->isFinished()) { QNetworkReply *replyPtr = reply.take(); connect(replyPtr, SIGNAL(finished()), replyPtr, SLOT(deleteLater())); return false; } // Passed if (reply->error() == QNetworkReply::NoError) return true; // Error. *errorMessage = reply->errorString(); return false; } } //namespace CodePaster <|endoftext|>
<commit_before>/* * AbstractNormProbe.cpp * * Created on: Aug 11, 2015 * Author: pschultz */ #include "AbstractNormProbe.hpp" #include "columns/HyPerCol.hpp" #include "layers/HyPerLayer.hpp" #include <limits> namespace PV { AbstractNormProbe::AbstractNormProbe() : LayerProbe() { initialize_base(); } AbstractNormProbe::AbstractNormProbe(const char *name, HyPerCol *hc) : LayerProbe() { initialize_base(); initialize(name, hc); } AbstractNormProbe::~AbstractNormProbe() { free(normDescription); normDescription = NULL; free(maskLayerName); maskLayerName = NULL; // Don't free maskLayer, which belongs to the HyPerCol. } int AbstractNormProbe::initialize_base() { normDescription = NULL; maskLayerName = NULL; maskLayer = NULL; singleFeatureMask = false; timeLastComputed = -std::numeric_limits<double>::infinity(); return PV_SUCCESS; } int AbstractNormProbe::initialize(const char *name, HyPerCol *hc) { int status = LayerProbe::initialize(name, hc); if (status == PV_SUCCESS) { status = setNormDescription(); } return status; } int AbstractNormProbe::ioParamsFillGroup(enum ParamsIOFlag ioFlag) { int status = LayerProbe::ioParamsFillGroup(ioFlag); ioParam_maskLayerName(ioFlag); return status; } void AbstractNormProbe::ioParam_maskLayerName(enum ParamsIOFlag ioFlag) { parent->parameters()->ioParamString( ioFlag, name, "maskLayerName", &maskLayerName, NULL, false /*warnIfAbsent*/); } int AbstractNormProbe::communicateInitInfo( std::shared_ptr<CommunicateInitInfoMessage const> message) { int status = LayerProbe::communicateInitInfo(message); assert(targetLayer); if (maskLayerName && maskLayerName[0]) { maskLayer = message->lookup<HyPerLayer>(std::string(maskLayerName)); if (maskLayer == NULL) { if (parent->columnId() == 0) { ErrorLog().printf( "%s: maskLayerName \"%s\" is not a layer in the HyPerCol.\n", getDescription_c(), maskLayerName); } MPI_Barrier(parent->getCommunicator()->communicator()); exit(EXIT_FAILURE); } const PVLayerLoc *maskLoc = maskLayer->getLayerLoc(); const PVLayerLoc *loc = targetLayer->getLayerLoc(); assert(maskLoc != NULL && loc != NULL); if (maskLoc->nxGlobal != loc->nxGlobal || maskLoc->nyGlobal != loc->nyGlobal) { if (parent->columnId() == 0) { ErrorLog(maskLayerBadSize); maskLayerBadSize.printf( "%s: maskLayerName \"%s\" does not have the " "same x and y dimensions.\n", getDescription_c(), maskLayerName); maskLayerBadSize.printf( " original (nx=%d, ny=%d, nf=%d) versus (nx=%d, ny=%d, nf=%d)\n", maskLoc->nxGlobal, maskLoc->nyGlobal, maskLoc->nf, loc->nxGlobal, loc->nyGlobal, loc->nf); } MPI_Barrier(parent->getCommunicator()->communicator()); exit(EXIT_FAILURE); } if (maskLoc->nf != 1 && maskLoc->nf != loc->nf) { if (parent->columnId() == 0) { ErrorLog(maskLayerBadSize); maskLayerBadSize.printf( "%s: maskLayerName \"%s\" must either have the " "same number of features as this " "layer, or one feature.\n", getDescription_c(), maskLayerName); maskLayerBadSize.printf( " original (nx=%d, ny=%d, nf=%d) versus (nx=%d, ny=%d, nf=%d)\n", maskLoc->nxGlobal, maskLoc->nyGlobal, maskLoc->nf, loc->nxGlobal, loc->nyGlobal, loc->nf); } MPI_Barrier(parent->getCommunicator()->communicator()); exit(EXIT_FAILURE); } assert(maskLoc->nx == loc->nx && maskLoc->ny == loc->ny); singleFeatureMask = maskLoc->nf == 1 && loc->nf != 1; } return status; } int AbstractNormProbe::setNormDescription() { return setNormDescriptionToString("norm"); } int AbstractNormProbe::setNormDescriptionToString(char const *s) { normDescription = strdup(s); return normDescription ? PV_SUCCESS : PV_FAILURE; } void AbstractNormProbe::initOutputStreams(const char *filename, Checkpointer *checkpointer) { LayerProbe::initOutputStreams(filename, checkpointer); int const nBatch = getNumValues(); for (auto &s : mOutputStreams) { if (getMessage() != nullptr and getMessage()[0] != '\0') { s->printf("%s\n", getMessage()); } s->printf("time, batch, numNeurons, \"%s\"\n", getNormDescription()); } } int AbstractNormProbe::calcValues(double timeValue) { double *valuesBuffer = this->getValuesBuffer(); for (int b = 0; b < this->getNumValues(); b++) { valuesBuffer[b] = getValueInternal(timeValue, b); } MPI_Allreduce( MPI_IN_PLACE, valuesBuffer, getNumValues(), MPI_DOUBLE, MPI_SUM, parent->getCommunicator()->communicator()); return PV_SUCCESS; } int AbstractNormProbe::outputState(double timevalue) { getValues(timevalue); double *valuesBuffer = this->getValuesBuffer(); if (!mOutputStreams.empty()) { int nBatch = getNumValues(); int nk = getTargetLayer()->getNumGlobalNeurons(); for (int b = 0; b < nBatch; b++) { output(b).printf( "%6.3f, %d, %8d, %f", getMessage(), timevalue, b, nk, getNormDescription(), valuesBuffer[b]); output(b) << std::endl; } } return PV_SUCCESS; } } // end namespace PV <commit_msg>Hotfix: Fix AbstractNormProbe printf bug.<commit_after>/* * AbstractNormProbe.cpp * * Created on: Aug 11, 2015 * Author: pschultz */ #include "AbstractNormProbe.hpp" #include "columns/HyPerCol.hpp" #include "layers/HyPerLayer.hpp" #include <limits> namespace PV { AbstractNormProbe::AbstractNormProbe() : LayerProbe() { initialize_base(); } AbstractNormProbe::AbstractNormProbe(const char *name, HyPerCol *hc) : LayerProbe() { initialize_base(); initialize(name, hc); } AbstractNormProbe::~AbstractNormProbe() { free(normDescription); normDescription = NULL; free(maskLayerName); maskLayerName = NULL; // Don't free maskLayer, which belongs to the HyPerCol. } int AbstractNormProbe::initialize_base() { normDescription = NULL; maskLayerName = NULL; maskLayer = NULL; singleFeatureMask = false; timeLastComputed = -std::numeric_limits<double>::infinity(); return PV_SUCCESS; } int AbstractNormProbe::initialize(const char *name, HyPerCol *hc) { int status = LayerProbe::initialize(name, hc); if (status == PV_SUCCESS) { status = setNormDescription(); } return status; } int AbstractNormProbe::ioParamsFillGroup(enum ParamsIOFlag ioFlag) { int status = LayerProbe::ioParamsFillGroup(ioFlag); ioParam_maskLayerName(ioFlag); return status; } void AbstractNormProbe::ioParam_maskLayerName(enum ParamsIOFlag ioFlag) { parent->parameters()->ioParamString( ioFlag, name, "maskLayerName", &maskLayerName, NULL, false /*warnIfAbsent*/); } int AbstractNormProbe::communicateInitInfo( std::shared_ptr<CommunicateInitInfoMessage const> message) { int status = LayerProbe::communicateInitInfo(message); assert(targetLayer); if (maskLayerName && maskLayerName[0]) { maskLayer = message->lookup<HyPerLayer>(std::string(maskLayerName)); if (maskLayer == NULL) { if (parent->columnId() == 0) { ErrorLog().printf( "%s: maskLayerName \"%s\" is not a layer in the HyPerCol.\n", getDescription_c(), maskLayerName); } MPI_Barrier(parent->getCommunicator()->communicator()); exit(EXIT_FAILURE); } const PVLayerLoc *maskLoc = maskLayer->getLayerLoc(); const PVLayerLoc *loc = targetLayer->getLayerLoc(); assert(maskLoc != NULL && loc != NULL); if (maskLoc->nxGlobal != loc->nxGlobal || maskLoc->nyGlobal != loc->nyGlobal) { if (parent->columnId() == 0) { ErrorLog(maskLayerBadSize); maskLayerBadSize.printf( "%s: maskLayerName \"%s\" does not have the " "same x and y dimensions.\n", getDescription_c(), maskLayerName); maskLayerBadSize.printf( " original (nx=%d, ny=%d, nf=%d) versus (nx=%d, ny=%d, nf=%d)\n", maskLoc->nxGlobal, maskLoc->nyGlobal, maskLoc->nf, loc->nxGlobal, loc->nyGlobal, loc->nf); } MPI_Barrier(parent->getCommunicator()->communicator()); exit(EXIT_FAILURE); } if (maskLoc->nf != 1 && maskLoc->nf != loc->nf) { if (parent->columnId() == 0) { ErrorLog(maskLayerBadSize); maskLayerBadSize.printf( "%s: maskLayerName \"%s\" must either have the " "same number of features as this " "layer, or one feature.\n", getDescription_c(), maskLayerName); maskLayerBadSize.printf( " original (nx=%d, ny=%d, nf=%d) versus (nx=%d, ny=%d, nf=%d)\n", maskLoc->nxGlobal, maskLoc->nyGlobal, maskLoc->nf, loc->nxGlobal, loc->nyGlobal, loc->nf); } MPI_Barrier(parent->getCommunicator()->communicator()); exit(EXIT_FAILURE); } assert(maskLoc->nx == loc->nx && maskLoc->ny == loc->ny); singleFeatureMask = maskLoc->nf == 1 && loc->nf != 1; } return status; } int AbstractNormProbe::setNormDescription() { return setNormDescriptionToString("norm"); } int AbstractNormProbe::setNormDescriptionToString(char const *s) { normDescription = strdup(s); return normDescription ? PV_SUCCESS : PV_FAILURE; } void AbstractNormProbe::initOutputStreams(const char *filename, Checkpointer *checkpointer) { LayerProbe::initOutputStreams(filename, checkpointer); int const nBatch = getNumValues(); for (auto &s : mOutputStreams) { if (getMessage() != nullptr and getMessage()[0] != '\0') { s->printf("%s\n", getMessage()); } s->printf("time, batch, numNeurons, \"%s\"\n", getNormDescription()); } } int AbstractNormProbe::calcValues(double timeValue) { double *valuesBuffer = this->getValuesBuffer(); for (int b = 0; b < this->getNumValues(); b++) { valuesBuffer[b] = getValueInternal(timeValue, b); } MPI_Allreduce( MPI_IN_PLACE, valuesBuffer, getNumValues(), MPI_DOUBLE, MPI_SUM, parent->getCommunicator()->communicator()); return PV_SUCCESS; } int AbstractNormProbe::outputState(double timevalue) { getValues(timevalue); double *valuesBuffer = this->getValuesBuffer(); if (!mOutputStreams.empty()) { int nBatch = getNumValues(); int nk = getTargetLayer()->getNumGlobalNeurons(); for (int b = 0; b < nBatch; b++) { output(b).printf( "%6.3f, %d, %8d, %f", timevalue, b, nk, valuesBuffer[b]); output(b) << std::endl; } } return PV_SUCCESS; } } // end namespace PV <|endoftext|>
<commit_before>#include <pybind11/pybind11.h> #include <iostream> namespace py = pybind11; PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); namespace nifty{ namespace graph{ namespace opt{ } // namespace nifty::graph::opt } } PYBIND11_MODULE(_opt, module) { module.doc() = "_opt", "opt submodule of nifty.graph"; using namespace nifty::graph::opt; } <commit_msg>Fix clang warning<commit_after>#include <pybind11/pybind11.h> #include <iostream> namespace py = pybind11; PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); namespace nifty{ namespace graph{ namespace opt{ } // namespace nifty::graph::opt } } PYBIND11_MODULE(_opt, module) { module.doc() = "opt submodule of nifty.graph"; using namespace nifty::graph::opt; } <|endoftext|>
<commit_before>#include "inscriptiontablemodel.h" #include "guiutil.h" #include "bitcoinrpc.h" #include "base58.h" #include "walletmodel.h" #include "util.h" #include "ui_interface.h" #include <QFont> #include <QColor> #include <QDateTime> /* #include "json/json_spirit_reader_template.h" #include "json/json_spirit_writer_template.h" #include "json/json_spirit_utils.h" */ #include <boost/algorithm/string.hpp> #include <stdlib.h> using namespace boost; // using namespace json_spirit; struct InscriptionTableEntry { QString inscription; QDateTime date; InscriptionTableEntry() {} InscriptionTableEntry(const QString &inscription, const QDateTime &date): inscription(inscription),date(date) {} }; class InscriptionTablePriv { public: InscriptionTablePriv(CWallet *wallet, InscriptionTableModel *parent): wallet(wallet), parent(parent) { } CWallet *wallet; InscriptionTableModel *parent; QList<InscriptionTableEntry> cachedInscriptionTable; void getLastInscription() { std::vector<std::pair<std::string, int> > vTxResults; this->wallet->GetTxMessages(vTxResults); QDateTime inscription_date = QDateTime::currentDateTime(); std::string inscription = vTxResults[0].first; inscription_date.setMSecsSinceEpoch((qint64)vTxResults[0].second*1000); cachedInscriptionTable.append( InscriptionTableEntry( QString::fromStdString(inscription), inscription_date )); } void getAllInscriptions() { std::vector<std::pair<std::string, int> > vTxResults; this->wallet->GetTxMessages(vTxResults); QDateTime inscription_date = QDateTime::currentDateTime(); for(std::vector<std::pair<std::string, int> >::size_type i = 0; i != vTxResults.size(); i++) { std::string inscription = vTxResults[i].first; inscription_date.setMSecsSinceEpoch((qint64)vTxResults[i].second*1000); cachedInscriptionTable.append( InscriptionTableEntry( QString::fromStdString(inscription), inscription_date )); } } void getInscriptions() { std::vector<std::pair<std::string, int> > vTxResults; this->wallet->GetMyTxMessages(vTxResults); QDateTime inscription_date = QDateTime::currentDateTime(); for(std::vector<std::pair<std::string, int> >::size_type i = 0; i != vTxResults.size(); i++) { std::string inscription = vTxResults[i].first; inscription_date.setMSecsSinceEpoch((qint64)vTxResults[i].second*1000); cachedInscriptionTable.append( InscriptionTableEntry( QString::fromStdString(inscription), inscription_date )); } } void refreshTable() { cachedInscriptionTable.clear(); getInscriptions(); } int size() { return cachedInscriptionTable.size(); } InscriptionTableEntry *index(int idx) { if(idx >= 0 && idx < cachedInscriptionTable.size()) { return &cachedInscriptionTable[idx]; } else { return 0; } } QString describe(InscriptionTableEntry *rec) { QString strHTML; strHTML.reserve(4000); strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>"; strHTML += "<b>Inscription content:</b> " + rec->inscription + "<br>"; strHTML += "<b>Inscription date:</b> " + rec->date.toString() + "<br>"; return strHTML; } }; InscriptionTableModel::InscriptionTableModel(CWallet *wallet, WalletModel *parent) : QAbstractTableModel(parent), wallet(wallet), priv(0) { columns << tr("Inscription content") ; columns << tr("Inscription date") ; priv = new InscriptionTablePriv(wallet, this); priv->refreshTable(); } InscriptionTableModel::~InscriptionTableModel() { delete priv; } int InscriptionTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int InscriptionTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } void InscriptionTableModel::refreshInscriptionTable() { if (this) { printf("Refreshing inscription table"); priv->refreshTable(); Q_EMIT layoutChanged(); } else { printf("Inscriptiontable uninitialised."); } } QVariant InscriptionTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); InscriptionTableEntry *rec = static_cast<InscriptionTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole) { switch(index.column()) { case Inscription: return rec->inscription; case Date: return GUIUtil::dateTimeStr(rec->date); } } else if(role == InscriptionRole) { return priv->describe(rec); } return QVariant(); } QVariant InscriptionTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } } return QVariant(); } QModelIndex InscriptionTableModel::index(int row, int column, const QModelIndex & parent) const { Q_UNUSED(parent); InscriptionTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } <commit_msg>compat<commit_after>#include "inscriptiontablemodel.h" #include "guiutil.h" #include "bitcoinrpc.h" #include "base58.h" #include "walletmodel.h" #include "util.h" #include "ui_interface.h" #include <QFont> #include <QColor> #include <QDateTime> /* #include "json/json_spirit_reader_template.h" #include "json/json_spirit_writer_template.h" #include "json/json_spirit_utils.h" */ #include <boost/algorithm/string.hpp> #include <stdlib.h> using namespace boost; // using namespace json_spirit; struct InscriptionTableEntry { QString inscription; QDateTime date; InscriptionTableEntry() {} InscriptionTableEntry(const QString &inscription, const QDateTime &date): inscription(inscription),date(date) {} }; class InscriptionTablePriv { public: InscriptionTablePriv(CWallet *wallet, InscriptionTableModel *parent): wallet(wallet), parent(parent) { } CWallet *wallet; InscriptionTableModel *parent; QList<InscriptionTableEntry> cachedInscriptionTable; void getLastInscription() { std::vector<std::pair<std::string, int> > vTxResults; this->wallet->GetTxMessages(vTxResults); QDateTime inscription_date = QDateTime::currentDateTime(); std::string inscription = vTxResults[0].first; #if QT_VERSION < 0x058000 inscription_date.setMSecsSinceEpoch((qint64)vTxResults[0].second*1000); #else inscription_date.setSecsSinceEpoch((qint64)vTxResults[0].second); #endif cachedInscriptionTable.append( InscriptionTableEntry( QString::fromStdString(inscription), inscription_date )); } void getAllInscriptions() { std::vector<std::pair<std::string, int> > vTxResults; this->wallet->GetTxMessages(vTxResults); QDateTime inscription_date = QDateTime::currentDateTime(); for(std::vector<std::pair<std::string, int> >::size_type i = 0; i != vTxResults.size(); i++) { std::string inscription = vTxResults[i].first; #if QT_VERSION < 0x058000 inscription_date.setMSecsSinceEpoch((qint64)vTxResults[i].second*1000); #else inscription_date.setSecsSinceEpoch((qint64)vTxResults[i].second); #endif cachedInscriptionTable.append( InscriptionTableEntry( QString::fromStdString(inscription), inscription_date )); } } void getInscriptions() { std::vector<std::pair<std::string, int> > vTxResults; this->wallet->GetMyTxMessages(vTxResults); QDateTime inscription_date = QDateTime::currentDateTime(); for(std::vector<std::pair<std::string, int> >::size_type i = 0; i != vTxResults.size(); i++) { std::string inscription = vTxResults[i].first; #if QT_VERSION < 0x058000 inscription_date.setMSecsSinceEpoch((qint64)vTxResults[i].second*1000); #else inscription_date.setSecsSinceEpoch((qint64)vTxResults[i].second); #endif cachedInscriptionTable.append( InscriptionTableEntry( QString::fromStdString(inscription), inscription_date )); } } void refreshTable() { cachedInscriptionTable.clear(); getInscriptions(); } int size() { return cachedInscriptionTable.size(); } InscriptionTableEntry *index(int idx) { if(idx >= 0 && idx < cachedInscriptionTable.size()) { return &cachedInscriptionTable[idx]; } else { return 0; } } QString describe(InscriptionTableEntry *rec) { QString strHTML; strHTML.reserve(4000); strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>"; strHTML += "<b>Inscription content:</b> " + rec->inscription + "<br>"; strHTML += "<b>Inscription date:</b> " + rec->date.toString() + "<br>"; return strHTML; } }; InscriptionTableModel::InscriptionTableModel(CWallet *wallet, WalletModel *parent) : QAbstractTableModel(parent), wallet(wallet), priv(0) { columns << tr("Inscription content") ; columns << tr("Inscription date") ; priv = new InscriptionTablePriv(wallet, this); priv->refreshTable(); } InscriptionTableModel::~InscriptionTableModel() { delete priv; } int InscriptionTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int InscriptionTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } void InscriptionTableModel::refreshInscriptionTable() { if (this) { printf("Refreshing inscription table"); priv->refreshTable(); Q_EMIT layoutChanged(); } else { printf("Inscriptiontable uninitialised."); } } QVariant InscriptionTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); InscriptionTableEntry *rec = static_cast<InscriptionTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole) { switch(index.column()) { case Inscription: return rec->inscription; case Date: return GUIUtil::dateTimeStr(rec->date); } } else if(role == InscriptionRole) { return priv->describe(rec); } return QVariant(); } QVariant InscriptionTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } } return QVariant(); } QModelIndex InscriptionTableModel::index(int row, int column, const QModelIndex & parent) const { Q_UNUSED(parent); InscriptionTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } <|endoftext|>
<commit_before>#ifndef _HIDA_STAR_HPP_ #define _HIDA_STAR_HPP_ #include <cassert> #include <vector> #include <boost/array.hpp> #include <boost/optional.hpp> #include <boost/pool/pool_alloc.hpp> #include <boost/unordered_map.hpp> #include <boost/utility.hpp> #include "search/Constants.hpp" #include "util/PointerOps.hpp" template < class Domain, class Node > class HIDAStar : boost::noncopyable { private: typedef typename Node::Cost Cost; typedef typename Node::State State; typedef boost::unordered_map< State, std::pair<Cost, bool> // ,boost::hash<State>, // std::equal_to<State>, // boost::fast_pool_allocator< std::pair<State const, std::pair<Cost, bool> > > > Cache; typedef typename Cache::iterator CacheIterator; typedef typename Cache::const_iterator CacheConstIterator; struct BoundedResult { union Result { Cost cutoff; const Node *goal; } result; typedef enum {Cutoff, Goal, Failure} ResultType; ResultType result_type; BoundedResult(Cost cutoff) { result.cutoff = cutoff; result_type = Cutoff; } BoundedResult(const Node *goal) { assert(goal != NULL); result.goal = goal; result_type = Goal; } BoundedResult() { result_type = Failure; } bool is_failure() const { return result_type == Failure; } bool is_goal() const { return result_type == Goal; } bool is_cutoff() const { return result_type == Cutoff; } const Node * get_goal() const { assert(is_goal()); return result.goal; } Cost get_cutoff() const { assert(is_cutoff()); return result.cutoff; } }; private: const static unsigned hierarchy_height = Domain::num_abstraction_levels + 1; const Node *goal; bool searched; Domain &domain; boost::array<unsigned, hierarchy_height> num_expanded; boost::array<unsigned, hierarchy_height> num_generated; boost::array<State, hierarchy_height> abstract_goals; Cache cache; boost::pool<> node_pool; public: HIDAStar(Domain &domain) : goal(NULL) , searched(false) , domain(domain) , num_expanded() , num_generated() , abstract_goals() , cache() , node_pool(sizeof(Node)) { num_expanded.assign(0); num_generated.assign(0); for (unsigned level = 0; level < hierarchy_height; level += 1) abstract_goals[level] = domain.abstract(level, domain.get_goal_state()); } const Node * get_goal() const { return goal; } const Domain & get_domain() const { return domain; } unsigned get_num_generated() const { unsigned sum = 0; for (unsigned i = 0; i < hierarchy_height; i += 1) sum += num_generated[i]; return sum; } unsigned get_num_generated(const unsigned level) const { return num_generated[level]; } unsigned get_num_expanded() const { unsigned sum = 0; for (unsigned i = 0; i < hierarchy_height; i += 1) sum += num_expanded[i]; return sum; } unsigned get_num_expanded(const unsigned level) const { return num_expanded[level]; } void search() { if (searched) return; searched = true; Node *start_node = new (node_pool.malloc()) Node(domain.get_start_state(), 0, 0); goal = hidastar_search(0, start_node); } private: const Node * hidastar_search(const unsigned level, Node *start_node) { Cost bound = heuristic(level, start_node); bool failed = false; const Node *goal_node = NULL; while ( goal_node == NULL && !failed ) { #ifdef OUTPUT_SEARCH_PROGRESS std::cerr << "hidastar_search at level " << level << std::endl; std::cerr << "doing cost-bounded search with cutoff " << bound << std::endl; std::cerr << get_num_expanded() << " total nodes expanded" << std::endl << get_num_generated() << " total nodes generated" << std::endl; #endif BoundedResult res = cost_bounded_search(level, start_node, bound); if (res.is_failure()) { assert(!res.is_goal()); assert(!res.is_cutoff()); failed = true; } else if (res.is_goal()) { assert(!res.is_cutoff()); assert(!res.is_failure()); goal_node = res.get_goal(); assert(goal_node != NULL); } else if (res.is_cutoff()) { assert(!res.is_goal()); assert(!res.is_failure()); bound = res.get_cutoff(); } else { assert(false); } } if (goal_node != NULL) { // cache_optimal_path(level, *goal_node); return goal_node; } else { std::cerr << "no solution found at level " << level << "!" << std::endl; assert(false); return NULL; } } BoundedResult cost_bounded_search(const unsigned level, Node *start_node, const Cost bound) { if (start_node->get_state() == abstract_goals[level]) { BoundedResult res(start_node); assert(res.is_goal()); return res; } std::vector<Node *> succs; domain.compute_successors(*start_node, succs, node_pool); num_expanded[level] += 1; num_generated[level] += succs.size(); #ifdef OUTPUT_SEARCH_PROGRESS if (get_num_expanded() % 1000000 == 0) { std::cerr << "progress update:" << std::endl; std::cerr << get_num_expanded() << " total nodes expanded" << std::endl << get_num_generated() << " total nodes generated" << std::endl; dump_cache_size(std::cerr); } #endif boost::optional<Cost> new_cutoff; for (unsigned i = 0; i < succs.size(); i += 1) { Node *succ = succs[i]; Cost hval = heuristic(level, succ); // // P-g caching // const Cost p_minus_g = bound - succ->get_g(); // hval = std::max(hval, p_minus_g); // CacheIterator cache_it = cache.find(succ->get_state()); // if (cache_it != cache.end()) { // hval = std::max(hval, cache_it->second.first); // cache_it->second.first = hval; // } // else { // cache[succ->get_state()] = std::make_pair(hval, false); // } // // end P-g caching succ->set_h(hval); // Optimal path caching // end Optimal path caching // Normal IDA* stuff if (succ->get_f() <= bound) { BoundedResult res = cost_bounded_search(level, succ, bound); if (res.is_goal()) { assert(!res.is_cutoff()); assert(!res.is_failure()); return res; } else if (res.is_cutoff()) { assert(!res.is_goal()); assert(!res.is_failure()); if (new_cutoff) new_cutoff = std::min(*new_cutoff, res.get_cutoff()); else new_cutoff = res.get_cutoff(); } } else { if (new_cutoff) new_cutoff = std::min(*new_cutoff, succ->get_f()); else new_cutoff = succ->get_f(); } node_pool.free(succ); } /* end for */ if (new_cutoff) { BoundedResult res(*new_cutoff); assert(res.is_cutoff()); assert(!res.is_goal()); assert(!res.is_failure()); return res; } else { // std::cerr << "returning failure!" << std::endl; BoundedResult res; assert(res.is_failure()); assert(!res.is_cutoff()); assert(!res.is_failure()); return res; } } void cache_optimal_path(const unsigned level, const Node &goal_node) { assert(goal_node.get_state() == abstract_goals[level]); const Node *parent = goal_node.get_parent(); while (parent != NULL) { assert(goal_node.get_g() > parent->get_g()); const Cost distance = goal_node.get_g() - parent->get_g(); CacheIterator cache_it = cache.find(parent->get_state()); cache.insert(cache_it, std::make_pair(parent->get_state(), std::make_pair(distance, true))); } } Cost heuristic(const unsigned level, Node *node) { if (node->get_parent() != NULL) domain.compute_heuristic(*node->get_parent(), *node); else domain.compute_heuristic(*node); return node->get_h(); // if (node.get_state() == abstract_goals[level]) // return 0; // if (level == Domain::num_abstraction_levels) // return domain.get_epsilon(node.get_state()); // const unsigned next_level = level + 1; // Node node_abstraction = Node(domain.abstract(next_level, node.get_state()), // 0, // 0); // CacheConstIterator cache_it = cache.find(node_abstraction.get_state()); // if (cache_it == cache.end() || !cache_it->second.second) { // const Node *res = hidastar_search(next_level, node_abstraction); // cache[node_abstraction.get_state()] = std::make_pair(res->get_h(), false); // } // assert(cache.find(node_abstraction.get_state()) != cache.end()); // return cache.find(node_abstraction.get_state())->second.first; } void dump_cache_size(std::ostream &o) const { o << "cache size: " << cache.size() << std::endl; } }; #endif /* !_HIDA_STAR_HPP_ */ <commit_msg>Working HIDA*?<commit_after>#ifndef _HIDA_STAR_HPP_ #define _HIDA_STAR_HPP_ #include <cassert> #include <vector> #include <boost/array.hpp> #include <boost/optional.hpp> #include <boost/pool/pool_alloc.hpp> #include <boost/unordered_map.hpp> #include <boost/utility.hpp> #include "search/Constants.hpp" #include "util/PointerOps.hpp" template < class Domain, class Node > class HIDAStar : boost::noncopyable { private: typedef typename Node::Cost Cost; typedef typename Node::State State; typedef boost::unordered_map< State, std::pair<Cost, bool> // ,boost::hash<State>, // std::equal_to<State>, // boost::fast_pool_allocator< std::pair<State const, std::pair<Cost, bool> > > > Cache; typedef typename Cache::iterator CacheIterator; typedef typename Cache::const_iterator CacheConstIterator; struct BoundedResult { union Result { Cost cutoff; Node *goal; } result; typedef enum {Cutoff, Goal, Failure} ResultType; ResultType result_type; BoundedResult(Cost cutoff) { result.cutoff = cutoff; result_type = Cutoff; } BoundedResult(Node *goal) { assert(goal != NULL); result.goal = goal; result_type = Goal; } BoundedResult() { result_type = Failure; } bool is_failure() const { return result_type == Failure; } bool is_goal() const { return result_type == Goal; } bool is_cutoff() const { return result_type == Cutoff; } Node * get_goal() const { assert(is_goal()); return result.goal; } Cost get_cutoff() const { assert(is_cutoff()); return result.cutoff; } }; private: const static unsigned hierarchy_height = Domain::num_abstraction_levels + 1; const Node *goal; bool searched; Domain &domain; boost::array<unsigned, hierarchy_height> num_expanded; boost::array<unsigned, hierarchy_height> num_generated; boost::array<State, hierarchy_height> abstract_goals; Cache cache; boost::pool<> node_pool; public: HIDAStar(Domain &domain) : goal(NULL) , searched(false) , domain(domain) , num_expanded() , num_generated() , abstract_goals() , cache() , node_pool(sizeof(Node)) { num_expanded.assign(0); num_generated.assign(0); for (unsigned level = 0; level < hierarchy_height; level += 1) abstract_goals[level] = domain.abstract(level, domain.get_goal_state()); } const Node * get_goal() const { return goal; } const Domain & get_domain() const { return domain; } unsigned get_num_generated() const { unsigned sum = 0; for (unsigned i = 0; i < hierarchy_height; i += 1) sum += num_generated[i]; return sum; } unsigned get_num_generated(const unsigned level) const { return num_generated[level]; } unsigned get_num_expanded() const { unsigned sum = 0; for (unsigned i = 0; i < hierarchy_height; i += 1) sum += num_expanded[i]; return sum; } unsigned get_num_expanded(const unsigned level) const { return num_expanded[level]; } void search() { if (searched) return; searched = true; Node *start_node = new (node_pool.malloc()) Node(domain.get_start_state(), 0, 0); goal = hidastar_search(0, start_node); } private: Node * hidastar_search(const unsigned level, Node *start_node) { Cost bound = heuristic(level, start_node); bool failed = false; Node *goal_node = NULL; while ( goal_node == NULL && !failed ) { #ifdef OUTPUT_SEARCH_PROGRESS std::cerr << "hidastar_search at level " << level << std::endl; std::cerr << "doing cost-bounded search with cutoff " << bound << std::endl; std::cerr << get_num_expanded() << " total nodes expanded" << std::endl << get_num_generated() << " total nodes generated" << std::endl; #endif BoundedResult res = cost_bounded_search(level, start_node, bound); if (res.is_failure()) { assert(!res.is_goal()); assert(!res.is_cutoff()); failed = true; } else if (res.is_goal()) { assert(!res.is_cutoff()); assert(!res.is_failure()); goal_node = res.get_goal(); assert(goal_node != NULL); } else if (res.is_cutoff()) { assert(!res.is_goal()); assert(!res.is_failure()); bound = res.get_cutoff(); } else { assert(false); } } if (goal_node != NULL) { cache_optimal_path(level, *goal_node); return goal_node; } else { std::cerr << "no solution found at level " << level << "!" << std::endl; assert(false); return NULL; } } BoundedResult cost_bounded_search(const unsigned level, Node *start_node, const Cost bound) { if (start_node->get_state() == abstract_goals[level]) { BoundedResult res(start_node); assert(res.is_goal()); return res; } std::vector<Node *> succs; domain.compute_successors(*start_node, succs, node_pool); num_expanded[level] += 1; num_generated[level] += succs.size(); #ifdef OUTPUT_SEARCH_PROGRESS if (get_num_expanded() % 1000000 == 0) { std::cerr << "progress update:" << std::endl; std::cerr << get_num_expanded() << " total nodes expanded" << std::endl << get_num_generated() << " total nodes generated" << std::endl; dump_cache_size(std::cerr); } #endif boost::optional<Cost> new_cutoff; for (unsigned i = 0; i < succs.size(); i += 1) { Node *succ = succs[i]; Cost hval = heuristic(level, succ); // P-g caching const Cost p_minus_g = bound - succ->get_g(); hval = std::max(hval, p_minus_g); CacheIterator cache_it = cache.find(succ->get_state()); if (cache_it != cache.end()) { hval = std::max(hval, cache_it->second.first); cache_it->second.first = hval; } else { cache[succ->get_state()] = std::make_pair(hval, false); } // end P-g caching succ->set_h(hval); // Optimal path caching { CacheConstIterator cache_it = cache.find(succ->get_state()); bool is_exact_cost = cache_it != cache.end() && cache_it->second.second; if (succ->get_f() == bound && is_exact_cost) { assert(level > 0); Node *synthesized_goal = new (node_pool.malloc()) Node(abstract_goals[level], succ->get_g() + cache_it->second.first, 0, succ); BoundedResult res(synthesized_goal); assert(res.is_goal()); return res; } } // end Optimal path caching // Normal IDA* stuff if (succ->get_f() <= bound) { BoundedResult res = cost_bounded_search(level, succ, bound); if (res.is_goal()) { assert(!res.is_cutoff()); assert(!res.is_failure()); return res; } else if (res.is_cutoff()) { assert(!res.is_goal()); assert(!res.is_failure()); if (new_cutoff) new_cutoff = std::min(*new_cutoff, res.get_cutoff()); else new_cutoff = res.get_cutoff(); } } else { if (new_cutoff) new_cutoff = std::min(*new_cutoff, succ->get_f()); else new_cutoff = succ->get_f(); } // end Normal IDA* stuff node_pool.free(succ); } /* end for */ if (new_cutoff) { BoundedResult res(*new_cutoff); assert(res.is_cutoff()); assert(!res.is_goal()); assert(!res.is_failure()); return res; } else { BoundedResult res; assert(res.is_failure()); assert(!res.is_cutoff()); assert(!res.is_failure()); return res; } } void cache_optimal_path(const unsigned level, const Node &goal_node) { assert(goal_node.get_state() == abstract_goals[level]); const Node *parent = goal_node.get_parent(); while (parent != NULL) { assert(goal_node.get_g() > parent->get_g()); const Cost distance = goal_node.get_g() - parent->get_g(); CacheIterator cache_it = cache.find(parent->get_state()); cache.insert(cache_it, std::make_pair(parent->get_state(), std::make_pair(distance, true))); } } Cost heuristic(const unsigned level, Node *node) { if (node->get_state() == abstract_goals[level]) return 0; if (level == Domain::num_abstraction_levels) return domain.get_epsilon(node->get_state()); const unsigned next_level = level + 1; Node *node_abstraction = new (node_pool.malloc()) Node(domain.abstract(next_level, node->get_state()), 0, 0); CacheConstIterator cache_it = cache.find(node_abstraction->get_state()); if (cache_it == cache.end() || !cache_it->second.second) { Node *res = hidastar_search(next_level, node_abstraction); cache[node_abstraction->get_state()] = std::make_pair(res->get_h(), false); node_pool.free(res); } node_pool.free(node_abstraction); assert(cache.find(node_abstraction->get_state()) != cache.end()); return cache.find(node_abstraction->get_state())->second.first; } void dump_cache_size(std::ostream &o) const { o << "cache size: " << cache.size() << std::endl; } }; #endif /* !_HIDA_STAR_HPP_ */ <|endoftext|>
<commit_before>/** Copyright (C) 2016 Ultimaker - Released under terms of the AGPLv3 License */ #include "SettingRegistry.h" #include <sstream> #include <iostream> // debug IO #include <libgen.h> // dirname #include <string> #include <cstring> // strtok (split string using delimiters) strcpy #include <fstream> // ifstream (to see if file exists) #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "../utils/logoutput.h" namespace cura { SettingRegistry SettingRegistry::instance; // define settingRegistry std::string SettingRegistry::toString(rapidjson::Type type) { switch (type) { case rapidjson::Type::kNullType: return "null"; case rapidjson::Type::kFalseType: return "false"; case rapidjson::Type::kTrueType: return "true"; case rapidjson::Type::kObjectType: return "object"; case rapidjson::Type::kArrayType: return "array"; case rapidjson::Type::kStringType: return "string"; case rapidjson::Type::kNumberType: return "number"; default: return "Unknown"; } } SettingConfig::SettingConfig(std::string key, std::string label) : SettingContainer(key, label) { // std::cerr << key << std::endl; // debug output to show all frontend registered settings... } bool SettingRegistry::settingExists(std::string key) const { return setting_key_to_config.find(key) != setting_key_to_config.end(); } SettingConfig* SettingRegistry::getSettingConfig(std::string key) const { auto it = setting_key_to_config.find(key); if (it == setting_key_to_config.end()) return nullptr; return it->second; } SettingRegistry::SettingRegistry() : setting_definitions("settings", "Settings") { // load search paths from environment variable CURA_ENGINE_SEARCH_PATH char* paths = getenv("CURA_ENGINE_SEARCH_PATH"); if (paths) { #if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__)) char delims[] = ":"; // colon #else char delims[] = ";"; // semicolon #endif char* path = strtok(paths, delims); // search for next path delimited by any of the characters in delims while (path != NULL) { search_paths.emplace(path); path = strtok(NULL, ";:,"); // continue searching in last call to strtok } } } int SettingRegistry::loadJSON(std::string filename, rapidjson::Document& json_document) { FILE* f = fopen(filename.c_str(), "rb"); if (!f) { cura::logError("Couldn't open JSON file.\n"); return 1; } char read_buffer[4096]; rapidjson::FileReadStream reader_stream(f, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); fclose(f); if (json_document.HasParseError()) { cura::logError("Error parsing JSON(offset %u): %s\n", (unsigned)json_document.GetErrorOffset(), GetParseError_En(json_document.GetParseError())); return 2; } return 0; } /*! * Check whether a file exists. * from https://techoverflow.net/blog/2013/01/11/cpp-check-if-file-exists/ * * \param filename The path to a filename to check if it exists * \return Whether the file exists. */ bool fexists(const char *filename) { std::ifstream ifile(filename); return (bool)ifile; } bool SettingRegistry::getDefinitionFile(const std::string machine_id, std::string& result) { for (const std::string& search_path : search_paths) { result = search_path + std::string("/") + machine_id + std::string(".def.json"); if (fexists(result.c_str())) { return true; } } return false; } int SettingRegistry::loadExtruderJSONsettings(unsigned int extruder_nr, SettingsBase* settings_base) { if (extruder_nr >= extruder_train_ids.size()) { return -1; } std::string definition_file; bool found = getDefinitionFile(extruder_train_ids[extruder_nr], definition_file); if (!found) { return -1; } bool warn_base_file_duplicates = false; return loadJSONsettings(definition_file, settings_base, warn_base_file_duplicates); } int SettingRegistry::loadJSONsettings(std::string filename, SettingsBase* settings_base, bool warn_base_file_duplicates) { rapidjson::Document json_document; log("Loading %s...\n", filename.c_str()); int err = loadJSON(filename, json_document); if (err) { return err; } { // add parent folder to search paths char filename_cstr[filename.size()]; std::strcpy(filename_cstr, filename.c_str()); // copy the string because dirname(.) changes the input string!!! std::string folder_name = std::string(dirname(filename_cstr)); search_paths.emplace(folder_name); } if (json_document.HasMember("inherits") && json_document["inherits"].IsString()) { std::string child_filename; bool found = getDefinitionFile(json_document["inherits"].GetString(), child_filename); if (!found) { return -1; } err = loadJSONsettings(child_filename, settings_base, warn_base_file_duplicates); // load child first if (err) { return err; } err = loadJSONsettingsFromDoc(json_document, settings_base, false); } else { err = loadJSONsettingsFromDoc(json_document, settings_base, warn_base_file_duplicates); } if (json_document.HasMember("metadata") && json_document["metadata"].IsObject()) { const rapidjson::Value& json_metadata = json_document["metadata"]; if (json_metadata.HasMember("machine_extruder_trains") && json_metadata["machine_extruder_trains"].IsObject()) { const rapidjson::Value& json_machine_extruder_trains = json_metadata["machine_extruder_trains"]; for (rapidjson::Value::ConstMemberIterator extr_train_iterator = json_machine_extruder_trains.MemberBegin(); extr_train_iterator != json_machine_extruder_trains.MemberEnd(); ++extr_train_iterator) { int extruder_train_nr = atoi(extr_train_iterator->name.GetString()); if (extruder_train_nr < 0) { continue; } const rapidjson::Value& json_id = extr_train_iterator->value; if (!json_id.IsString()) { continue; } const char* id = json_id.GetString(); if (extruder_train_nr >= (int) extruder_train_ids.size()) { extruder_train_ids.resize(extruder_train_nr + 1); } extruder_train_ids[extruder_train_nr] = std::string(id); } } } return err; } int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, SettingsBase* settings_base, bool warn_duplicates) { if (!json_document.IsObject()) { cura::logError("JSON file is not an object.\n"); return 3; } { // handle machine name std::string machine_name = "Unknown"; if (json_document.HasMember("name")) { const rapidjson::Value& machine_name_field = json_document["name"]; if (machine_name_field.IsString()) { machine_name = machine_name_field.GetString(); } } SettingConfig& machine_name_setting = addSetting("machine_name", "Machine Name"); machine_name_setting.setDefault(machine_name); machine_name_setting.setType("string"); settings_base->_setSetting(machine_name_setting.getKey(), machine_name_setting.getDefaultValue()); } if (json_document.HasMember("settings")) { std::list<std::string> path; handleChildren(json_document["settings"], path, settings_base, warn_duplicates); } if (json_document.HasMember("overrides")) { const rapidjson::Value& json_object_container = json_document["overrides"]; for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator) { std::string setting = override_iterator->name.GetString(); SettingConfig* conf = getSettingConfig(setting); if (!conf) //Setting could not be found. { logWarning("Trying to override unknown setting %s.\n", setting.c_str()); continue; } _loadSettingValues(conf, override_iterator, settings_base); } } return 0; } void SettingRegistry::handleChildren(const rapidjson::Value& settings_list, std::list<std::string>& path, SettingsBase* settings_base, bool warn_duplicates) { if (!settings_list.IsObject()) { logError("ERROR: json settings list is not an object!\n"); return; } for (rapidjson::Value::ConstMemberIterator setting_iterator = settings_list.MemberBegin(); setting_iterator != settings_list.MemberEnd(); ++setting_iterator) { handleSetting(setting_iterator, path, settings_base, warn_duplicates); if (setting_iterator->value.HasMember("children")) { std::list<std::string> path_here = path; path_here.push_back(setting_iterator->name.GetString()); handleChildren(setting_iterator->value["children"], path_here, settings_base, warn_duplicates); } } } bool SettingRegistry::settingIsUsedByEngine(const rapidjson::Value& setting) { if (setting.HasMember("children")) { return false; } else { return true; } } void SettingRegistry::handleSetting(const rapidjson::Value::ConstMemberIterator& json_setting_it, std::list<std::string>& path, SettingsBase* settings_base, bool warn_duplicates) { const rapidjson::Value& json_setting = json_setting_it->value; if (!json_setting.IsObject()) { logError("ERROR: json setting is not an object!\n"); return; } std::string name = json_setting_it->name.GetString(); if (json_setting.HasMember("type") && json_setting["type"].IsString() && json_setting["type"].GetString() == std::string("category")) { // skip category objects setting_key_to_config[name] = nullptr; // add the category name to the mapping, but don't instantiate a setting config for it. return; } if (settingIsUsedByEngine(json_setting)) { if (!json_setting.HasMember("label") || !json_setting["label"].IsString()) { logError("ERROR: json setting \"%s\" has no label!\n", name.c_str()); return; } std::string label = json_setting["label"].GetString(); SettingConfig* setting = getSettingConfig(name); if (warn_duplicates && setting) { cura::logError("Duplicate definition of setting: %s a.k.a. \"%s\" was already claimed by \"%s\"\n", name.c_str(), label.c_str(), getSettingConfig(name)->getLabel().c_str()); } if (!setting) { setting = &addSetting(name, label); } _loadSettingValues(setting, json_setting_it, settings_base); } else { setting_key_to_config[name] = nullptr; // add the setting name to the mapping, but don't instantiate a setting config for it. } } SettingConfig& SettingRegistry::addSetting(std::string name, std::string label) { SettingConfig* config = setting_definitions.addChild(name, label); setting_key_to_config[name] = config; return *config; } void SettingRegistry::loadDefault(const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, SettingConfig* config) { const rapidjson::Value& setting_content = json_object_it->value; if (setting_content.HasMember("default_value")) { const rapidjson::Value& dflt = setting_content["default_value"]; if (dflt.IsString()) { config->setDefault(dflt.GetString()); } else if (dflt.IsTrue()) { config->setDefault("true"); } else if (dflt.IsFalse()) { config->setDefault("false"); } else if (dflt.IsNumber()) { std::ostringstream ss; ss << dflt.GetDouble(); config->setDefault(ss.str()); } // arrays are ignored because machine_extruder_trains needs to be handled separately else { logWarning("WARNING: Unrecognized data type in JSON: %s has type %s\n", json_object_it->name.GetString(), toString(dflt.GetType()).c_str()); } } } void SettingRegistry::_loadSettingValues(SettingConfig* config, const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, SettingsBase* settings_base) { const rapidjson::Value& data = json_object_it->value; /// Fill the setting config object with data we have in the json file. if (data.HasMember("type") && data["type"].IsString()) { config->setType(data["type"].GetString()); } if (config->getType() == std::string("polygon") || config->getType() == std::string("polygons")) { // skip polygon settings : not implemented yet and not used yet (TODO) // logWarning("WARNING: Loading polygon setting %s not implemented...\n", json_object_it->name.GetString()); return; } loadDefault(json_object_it, config); if (data.HasMember("unit") && data["unit"].IsString()) { config->setUnit(data["unit"].GetString()); } settings_base->_setSetting(config->getKey(), config->getDefaultValue()); } }//namespace cura <commit_msg>Added error message if inherited JSON file can't be found.<commit_after>/** Copyright (C) 2016 Ultimaker - Released under terms of the AGPLv3 License */ #include "SettingRegistry.h" #include <sstream> #include <iostream> // debug IO #include <libgen.h> // dirname #include <string> #include <cstring> // strtok (split string using delimiters) strcpy #include <fstream> // ifstream (to see if file exists) #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "../utils/logoutput.h" namespace cura { SettingRegistry SettingRegistry::instance; // define settingRegistry std::string SettingRegistry::toString(rapidjson::Type type) { switch (type) { case rapidjson::Type::kNullType: return "null"; case rapidjson::Type::kFalseType: return "false"; case rapidjson::Type::kTrueType: return "true"; case rapidjson::Type::kObjectType: return "object"; case rapidjson::Type::kArrayType: return "array"; case rapidjson::Type::kStringType: return "string"; case rapidjson::Type::kNumberType: return "number"; default: return "Unknown"; } } SettingConfig::SettingConfig(std::string key, std::string label) : SettingContainer(key, label) { // std::cerr << key << std::endl; // debug output to show all frontend registered settings... } bool SettingRegistry::settingExists(std::string key) const { return setting_key_to_config.find(key) != setting_key_to_config.end(); } SettingConfig* SettingRegistry::getSettingConfig(std::string key) const { auto it = setting_key_to_config.find(key); if (it == setting_key_to_config.end()) return nullptr; return it->second; } SettingRegistry::SettingRegistry() : setting_definitions("settings", "Settings") { // load search paths from environment variable CURA_ENGINE_SEARCH_PATH char* paths = getenv("CURA_ENGINE_SEARCH_PATH"); if (paths) { #if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__)) char delims[] = ":"; // colon #else char delims[] = ";"; // semicolon #endif char* path = strtok(paths, delims); // search for next path delimited by any of the characters in delims while (path != NULL) { search_paths.emplace(path); path = strtok(NULL, ";:,"); // continue searching in last call to strtok } } } int SettingRegistry::loadJSON(std::string filename, rapidjson::Document& json_document) { FILE* f = fopen(filename.c_str(), "rb"); if (!f) { cura::logError("Couldn't open JSON file.\n"); return 1; } char read_buffer[4096]; rapidjson::FileReadStream reader_stream(f, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); fclose(f); if (json_document.HasParseError()) { cura::logError("Error parsing JSON(offset %u): %s\n", (unsigned)json_document.GetErrorOffset(), GetParseError_En(json_document.GetParseError())); return 2; } return 0; } /*! * Check whether a file exists. * from https://techoverflow.net/blog/2013/01/11/cpp-check-if-file-exists/ * * \param filename The path to a filename to check if it exists * \return Whether the file exists. */ bool fexists(const char *filename) { std::ifstream ifile(filename); return (bool)ifile; } bool SettingRegistry::getDefinitionFile(const std::string machine_id, std::string& result) { for (const std::string& search_path : search_paths) { result = search_path + std::string("/") + machine_id + std::string(".def.json"); if (fexists(result.c_str())) { return true; } } return false; } int SettingRegistry::loadExtruderJSONsettings(unsigned int extruder_nr, SettingsBase* settings_base) { if (extruder_nr >= extruder_train_ids.size()) { return -1; } std::string definition_file; bool found = getDefinitionFile(extruder_train_ids[extruder_nr], definition_file); if (!found) { return -1; } bool warn_base_file_duplicates = false; return loadJSONsettings(definition_file, settings_base, warn_base_file_duplicates); } int SettingRegistry::loadJSONsettings(std::string filename, SettingsBase* settings_base, bool warn_base_file_duplicates) { rapidjson::Document json_document; log("Loading %s...\n", filename.c_str()); int err = loadJSON(filename, json_document); if (err) { return err; } { // add parent folder to search paths char filename_cstr[filename.size()]; std::strcpy(filename_cstr, filename.c_str()); // copy the string because dirname(.) changes the input string!!! std::string folder_name = std::string(dirname(filename_cstr)); search_paths.emplace(folder_name); } if (json_document.HasMember("inherits") && json_document["inherits"].IsString()) { std::string child_filename; bool found = getDefinitionFile(json_document["inherits"].GetString(), child_filename); if (!found) { cura::logError("Inherited JSON file \"%s\" not found\n", json_document["inherits"].GetString()); return -1; } err = loadJSONsettings(child_filename, settings_base, warn_base_file_duplicates); // load child first if (err) { return err; } err = loadJSONsettingsFromDoc(json_document, settings_base, false); } else { err = loadJSONsettingsFromDoc(json_document, settings_base, warn_base_file_duplicates); } if (json_document.HasMember("metadata") && json_document["metadata"].IsObject()) { const rapidjson::Value& json_metadata = json_document["metadata"]; if (json_metadata.HasMember("machine_extruder_trains") && json_metadata["machine_extruder_trains"].IsObject()) { const rapidjson::Value& json_machine_extruder_trains = json_metadata["machine_extruder_trains"]; for (rapidjson::Value::ConstMemberIterator extr_train_iterator = json_machine_extruder_trains.MemberBegin(); extr_train_iterator != json_machine_extruder_trains.MemberEnd(); ++extr_train_iterator) { int extruder_train_nr = atoi(extr_train_iterator->name.GetString()); if (extruder_train_nr < 0) { continue; } const rapidjson::Value& json_id = extr_train_iterator->value; if (!json_id.IsString()) { continue; } const char* id = json_id.GetString(); if (extruder_train_nr >= (int) extruder_train_ids.size()) { extruder_train_ids.resize(extruder_train_nr + 1); } extruder_train_ids[extruder_train_nr] = std::string(id); } } } return err; } int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, SettingsBase* settings_base, bool warn_duplicates) { if (!json_document.IsObject()) { cura::logError("JSON file is not an object.\n"); return 3; } { // handle machine name std::string machine_name = "Unknown"; if (json_document.HasMember("name")) { const rapidjson::Value& machine_name_field = json_document["name"]; if (machine_name_field.IsString()) { machine_name = machine_name_field.GetString(); } } SettingConfig& machine_name_setting = addSetting("machine_name", "Machine Name"); machine_name_setting.setDefault(machine_name); machine_name_setting.setType("string"); settings_base->_setSetting(machine_name_setting.getKey(), machine_name_setting.getDefaultValue()); } if (json_document.HasMember("settings")) { std::list<std::string> path; handleChildren(json_document["settings"], path, settings_base, warn_duplicates); } if (json_document.HasMember("overrides")) { const rapidjson::Value& json_object_container = json_document["overrides"]; for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator) { std::string setting = override_iterator->name.GetString(); SettingConfig* conf = getSettingConfig(setting); if (!conf) //Setting could not be found. { logWarning("Trying to override unknown setting %s.\n", setting.c_str()); continue; } _loadSettingValues(conf, override_iterator, settings_base); } } return 0; } void SettingRegistry::handleChildren(const rapidjson::Value& settings_list, std::list<std::string>& path, SettingsBase* settings_base, bool warn_duplicates) { if (!settings_list.IsObject()) { logError("ERROR: json settings list is not an object!\n"); return; } for (rapidjson::Value::ConstMemberIterator setting_iterator = settings_list.MemberBegin(); setting_iterator != settings_list.MemberEnd(); ++setting_iterator) { handleSetting(setting_iterator, path, settings_base, warn_duplicates); if (setting_iterator->value.HasMember("children")) { std::list<std::string> path_here = path; path_here.push_back(setting_iterator->name.GetString()); handleChildren(setting_iterator->value["children"], path_here, settings_base, warn_duplicates); } } } bool SettingRegistry::settingIsUsedByEngine(const rapidjson::Value& setting) { if (setting.HasMember("children")) { return false; } else { return true; } } void SettingRegistry::handleSetting(const rapidjson::Value::ConstMemberIterator& json_setting_it, std::list<std::string>& path, SettingsBase* settings_base, bool warn_duplicates) { const rapidjson::Value& json_setting = json_setting_it->value; if (!json_setting.IsObject()) { logError("ERROR: json setting is not an object!\n"); return; } std::string name = json_setting_it->name.GetString(); if (json_setting.HasMember("type") && json_setting["type"].IsString() && json_setting["type"].GetString() == std::string("category")) { // skip category objects setting_key_to_config[name] = nullptr; // add the category name to the mapping, but don't instantiate a setting config for it. return; } if (settingIsUsedByEngine(json_setting)) { if (!json_setting.HasMember("label") || !json_setting["label"].IsString()) { logError("ERROR: json setting \"%s\" has no label!\n", name.c_str()); return; } std::string label = json_setting["label"].GetString(); SettingConfig* setting = getSettingConfig(name); if (warn_duplicates && setting) { cura::logError("Duplicate definition of setting: %s a.k.a. \"%s\" was already claimed by \"%s\"\n", name.c_str(), label.c_str(), getSettingConfig(name)->getLabel().c_str()); } if (!setting) { setting = &addSetting(name, label); } _loadSettingValues(setting, json_setting_it, settings_base); } else { setting_key_to_config[name] = nullptr; // add the setting name to the mapping, but don't instantiate a setting config for it. } } SettingConfig& SettingRegistry::addSetting(std::string name, std::string label) { SettingConfig* config = setting_definitions.addChild(name, label); setting_key_to_config[name] = config; return *config; } void SettingRegistry::loadDefault(const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, SettingConfig* config) { const rapidjson::Value& setting_content = json_object_it->value; if (setting_content.HasMember("default_value")) { const rapidjson::Value& dflt = setting_content["default_value"]; if (dflt.IsString()) { config->setDefault(dflt.GetString()); } else if (dflt.IsTrue()) { config->setDefault("true"); } else if (dflt.IsFalse()) { config->setDefault("false"); } else if (dflt.IsNumber()) { std::ostringstream ss; ss << dflt.GetDouble(); config->setDefault(ss.str()); } // arrays are ignored because machine_extruder_trains needs to be handled separately else { logWarning("WARNING: Unrecognized data type in JSON: %s has type %s\n", json_object_it->name.GetString(), toString(dflt.GetType()).c_str()); } } } void SettingRegistry::_loadSettingValues(SettingConfig* config, const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, SettingsBase* settings_base) { const rapidjson::Value& data = json_object_it->value; /// Fill the setting config object with data we have in the json file. if (data.HasMember("type") && data["type"].IsString()) { config->setType(data["type"].GetString()); } if (config->getType() == std::string("polygon") || config->getType() == std::string("polygons")) { // skip polygon settings : not implemented yet and not used yet (TODO) // logWarning("WARNING: Loading polygon setting %s not implemented...\n", json_object_it->name.GetString()); return; } loadDefault(json_object_it, config); if (data.HasMember("unit") && data["unit"].IsString()) { config->setUnit(data["unit"].GetString()); } settings_base->_setSetting(config->getKey(), config->getDefaultValue()); } }//namespace cura <|endoftext|>
<commit_before>namespace shader { const char* buff_frag_shader = R"( uniform sampler2D sampler; uniform vec4 brightness_contrast[2]; uniform vec2 buffer_dimension; uniform int enable_borders; // Ouput data varying vec2 uv; vec2 roundVec2(vec2 f) { return vec2(float(int(f.x+0.5)), float(int(f.y+0.5))); } void main() { vec4 color; #if defined(FORMAT_R) // Output color = grayscale color = texture2D(sampler, uv).rrra; color.rgb = color.rgb * brightness_contrast[0].xxx + brightness_contrast[1].xxx; #elif defined(FORMAT_RG) // Output color = two channels color = texture2D(sampler, uv); color.rg = color.rg * brightness_contrast[0].xy + brightness_contrast[1].xy; color.b = 0.0; #elif defined(FORMAT_RGB) // Output color = rgb color = texture2D(sampler, uv); color.rgb = color.rgb * brightness_contrast[0].xyz + brightness_contrast[1].xyz; #else // Output color = rgba color = texture2D(sampler, uv); color = color * brightness_contrast[0] + brightness_contrast[1]; #endif vec2 buffer_position = uv*buffer_dimension; vec2 err = roundVec2(buffer_position)-buffer_position; if(enable_borders==1) { float alpha = dFdx(buffer_position.x); float x_ = fract(buffer_position.x); float y_ = fract(buffer_position.y); float vertical_border = clamp(abs(-1.0/alpha * x_ + 0.5/alpha) - (0.5/alpha-1.0), 0.0, 1.0); float horizontal_border = clamp(abs(-1.0/alpha * y_ + 0.5/alpha) - (0.5/alpha-1.0), 0.0, 1.0); color.rgb += vec3(vertical_border+horizontal_border); } gl_FragColor = color.PIXEL_LAYOUT; } )"; } // namespace shader <commit_msg>Compute pixel border robustly to buffer rotation<commit_after>namespace shader { const char* buff_frag_shader = R"( uniform sampler2D sampler; uniform vec4 brightness_contrast[2]; uniform vec2 buffer_dimension; uniform int enable_borders; // Ouput data varying vec2 uv; void main() { vec4 color; #if defined(FORMAT_R) // Output color = grayscale color = texture2D(sampler, uv).rrra; color.rgb = color.rgb * brightness_contrast[0].xxx + brightness_contrast[1].xxx; #elif defined(FORMAT_RG) // Output color = two channels color = texture2D(sampler, uv); color.rg = color.rg * brightness_contrast[0].xy + brightness_contrast[1].xy; color.b = 0.0; #elif defined(FORMAT_RGB) // Output color = rgb color = texture2D(sampler, uv); color.rgb = color.rgb * brightness_contrast[0].xyz + brightness_contrast[1].xyz; #else // Output color = rgba color = texture2D(sampler, uv); color = color * brightness_contrast[0] + brightness_contrast[1]; #endif vec2 buffer_position = uv*buffer_dimension; if(enable_borders == 1) { float alpha = max(abs(dFdx(buffer_position.x)), abs(dFdx(buffer_position.y))); float x_ = fract(buffer_position.x); float y_ = fract(buffer_position.y); float vertical_border = clamp(abs(-1.0/alpha * x_ + 0.5/alpha) - (0.5/alpha-1.0), 0.0, 1.0); float horizontal_border = clamp(abs(-1.0/alpha * y_ + 0.5/alpha) - (0.5/alpha-1.0), 0.0, 1.0); color.rgb += vec3(vertical_border + horizontal_border); } gl_FragColor = color.PIXEL_LAYOUT; } )"; } // namespace shader <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/base/ParameterMap.h> #include <shogun/base/Parameter.h> #include <shogun/mathematics/Math.h> using namespace shogun; SGParamInfo::SGParamInfo() { m_name=NULL; m_ctype=(EContainerType) -1; m_stype=(EStructType) -1; m_ptype=(EPrimitiveType) -1; m_param_version=-1; } SGParamInfo::SGParamInfo(const SGParamInfo& orig) { /* copy name if existent */ m_name=orig.m_name ? strdup(orig.m_name) : NULL; m_ctype=orig.m_ctype; m_stype=orig.m_stype; m_ptype=orig.m_ptype; m_param_version=orig.m_param_version; } SGParamInfo::SGParamInfo(const char* name, EContainerType ctype, EStructType stype, EPrimitiveType ptype, int32_t param_version) { /* copy name if existent */ m_name=name ? strdup(name) : NULL; m_ctype=ctype; m_stype=stype; m_ptype=ptype; m_param_version=param_version; } SGParamInfo::SGParamInfo(const TParameter* param, int32_t param_version) { /* copy name if existent */ m_name=param->m_name ? strdup(param->m_name) : NULL; TSGDataType type=param->m_datatype; m_ctype=type.m_ctype; m_stype=type.m_stype; m_ptype=type.m_ptype; m_param_version=param_version; } SGParamInfo::~SGParamInfo() { SG_FREE(m_name); } char* SGParamInfo::to_string() const { char* buffer=SG_MALLOC(char, 200); strcpy(buffer, "SGParamInfo with: "); strcat(buffer, "name=\""); strcat(buffer, m_name ? m_name : "NULL"); strcat(buffer, "\", type="); char* b; /* only cat type if it is defined (is not when std constructor was used)*/ if (!is_empty()) { TSGDataType t(m_ctype, m_stype, m_ptype); index_t l=100; b=SG_MALLOC(char, l); t.to_string(b, l); strcat(buffer, b); SG_FREE(b); } else strcat(buffer, "no type"); b=SG_MALLOC(char, 10); sprintf(b, "%d", m_param_version); strcat(buffer, ", version="); strcat(buffer, b); SG_FREE(b); return buffer; } void SGParamInfo::print_param_info(const char* prefix) const { char* s=to_string(); SG_SPRINT("%s%s\n", prefix, s); SG_FREE(s); } SGParamInfo* SGParamInfo::duplicate() const { return new SGParamInfo(m_name, m_ctype, m_stype, m_ptype, m_param_version); } bool SGParamInfo::operator==(const SGParamInfo& other) const { bool result=true; /* handle NULL strings */ if ((!m_name && other.m_name) || (m_name && !other.m_name)) return false; if (m_name && other.m_name) result&=!strcmp(m_name, other.m_name); result&=m_ctype==other.m_ctype; result&=m_stype==other.m_stype; result&=m_ptype==other.m_ptype; result&=m_param_version==other.m_param_version; return result; } bool SGParamInfo::operator!=(const SGParamInfo& other) const { return !operator ==(other); } bool SGParamInfo::operator<(const SGParamInfo& other) const { /* NULL here is always smaller than anything */ if (!m_name) { if (!other.m_name) return false; else return true; } else if (!other.m_name) return true; int32_t result=strcmp(m_name, other.m_name); if (result==0) { if (m_param_version==other.m_param_version) { if (m_ctype==other.m_ctype) { if (m_stype==other.m_stype) { if (m_ptype==other.m_ptype) { return false; } else return m_ptype<other.m_ptype; } else return m_stype<other.m_stype; } else return m_ctype<other.m_ctype; } else return m_param_version<other.m_param_version; } else return result<0; } bool SGParamInfo::operator>(const SGParamInfo& other) const { return !(*this<(other)) && !(*this==other); } bool SGParamInfo::is_empty() const { /* return true if this info is for empty parameter */ return m_ctype<0 && m_stype<0 && m_ptype<0 && !m_name; } ParameterMapElement::ParameterMapElement() { m_key=NULL; m_values=NULL; } ParameterMapElement::ParameterMapElement(const SGParamInfo* key, DynArray<const SGParamInfo*>* values) { m_key=key; m_values=values; } ParameterMapElement::~ParameterMapElement() { delete m_key; if (m_values) { for (index_t i=0; i<m_values->get_num_elements(); ++i) delete m_values->get_element(i); delete m_values; } } bool ParameterMapElement::operator==(const ParameterMapElement& other) const { return *m_key==*other.m_key; } bool ParameterMapElement::operator<(const ParameterMapElement& other) const { return *m_key<*other.m_key; } bool ParameterMapElement::operator>(const ParameterMapElement& other) const { return *m_key>*other.m_key; } ParameterMap::ParameterMap() { m_finalized=false; } ParameterMap::~ParameterMap() { for (index_t i=0; i<m_map_elements.get_num_elements(); ++i) delete m_map_elements[i]; for (index_t i=0; i<m_multi_map_elements.get_num_elements(); ++i) delete m_multi_map_elements[i]; } void ParameterMap::put(const SGParamInfo* key, const SGParamInfo* value) { /* assert that versions do differ exactly one if mapping is non-empty */ if(key->m_param_version-value->m_param_version!=1) { if (!key->is_empty() && !value->is_empty()) { char* s=key->to_string(); char* t=value->to_string(); SG_SERROR("Versions of parameter mappings from \"%s\" to \"%s\" have" " to differ exactly one\n", s, t); SG_FREE(s); SG_FREE(t); } } /* always add array of ONE element as values, will be processed later * in finalize map method */ DynArray<const SGParamInfo*>* values=new DynArray<const SGParamInfo*>(); values->append_element(value); m_map_elements.append_element(new ParameterMapElement(key, values)); m_finalized=false; } DynArray<const SGParamInfo*>* ParameterMap::get(const SGParamInfo key) const { return get(&key); } DynArray<const SGParamInfo*>* ParameterMap::get(const SGParamInfo* key) const { index_t num_elements=m_multi_map_elements.get_num_elements(); /* check if maps is finalized */ if (!m_finalized && num_elements) SG_SERROR("Call finalize_map() before calling get()\n"); /* do binary search in array of pointers */ /* dummy element for searching */ ParameterMapElement* dummy=new ParameterMapElement(key->duplicate(), NULL); index_t index=CMath::binary_search<ParameterMapElement> ( m_multi_map_elements.get_array(), num_elements, dummy); delete dummy; if (index==-1) return NULL; ParameterMapElement* element=m_multi_map_elements.get_element(index); return element->m_values; } void ParameterMap::finalize_map() { /* only do something if there are elements in map */ if (!m_map_elements.get_num_elements()) return; /* sort underlying array */ CMath::qsort<ParameterMapElement> (m_map_elements.get_array(), m_map_elements.get_num_elements()); SG_SPRINT("map elements before finalize\n"); for (index_t i=0; i<m_map_elements.get_num_elements(); ++i) { ParameterMapElement* current=m_map_elements[i]; SG_SPRINT("element %d:\n", i); SG_SPRINT("\tkey: "); current->m_key->print_param_info(); SG_SPRINT("\t%d values:\n", current->m_values->get_num_elements()); for (index_t j=0; j<current->m_values->get_num_elements(); ++j) current->m_values->get_element(j)->print_param_info("\t\t"); } /* clear old multi elements. These were copies. */ for (index_t i=0; i<m_multi_map_elements.get_num_elements(); ++i) delete m_multi_map_elements[i]; m_multi_map_elements.reset(); SG_SPRINT("\nstarting finalization\n"); /* iterate over all elements of map elements (have all one value (put)) and * add all values of same key to ONE map element of hidden structure */ DynArray<const SGParamInfo*>* values=new DynArray<const SGParamInfo*>(); const SGParamInfo* current_key=m_map_elements[0]->m_key; char* s=current_key->to_string(); SG_SPRINT("current key: %s\n", s); SG_FREE(s); for (index_t i=0; i<m_map_elements.get_num_elements(); ++i) { const ParameterMapElement* current=m_map_elements[i]; if (*current_key != *current->m_key) { /* create new values array to add and update key */ values=new DynArray<const SGParamInfo*>(); current_key=current->m_key; s=current_key->to_string(); SG_SPRINT("new current key: %s\n", s); SG_FREE(s); } /* add to values array */ char* t=current->m_values->get_element(0)->to_string(); SG_SPRINT("\tadding %s\n", t); SG_FREE(t); values->append_element(current->m_values->get_element(0)->duplicate()); /* if current values array has not been added to multi map elements, do * now */ index_t last_idx=m_multi_map_elements.get_num_elements()-1; if (last_idx<0 || m_multi_map_elements.get_element(last_idx)->m_values != values) { SG_SPRINT("adding values array\n"); m_multi_map_elements.append_element( new ParameterMapElement(current_key->duplicate(), values)); } } m_finalized=true; SG_SPRINT("leaving finalize_map()\n"); } void ParameterMap::print_map() { /* check if maps is finalized */ if (!m_finalized && m_map_elements.get_num_elements()) SG_SERROR("Call finalize_map() before calling print_map()\n"); SG_SPRINT("map with %d keys:\n", m_multi_map_elements.get_num_elements()); for (index_t i=0; i<m_multi_map_elements.get_num_elements(); ++i) { ParameterMapElement* current=m_multi_map_elements[i]; SG_SPRINT("element %d:\n", i); SG_SPRINT("\tkey: "); current->m_key->print_param_info(); SG_SPRINT("\t%d values:\n", current->m_values->get_num_elements()); for (index_t j=0; j<current->m_values->get_num_elements(); ++j) current->m_values->get_element(j)->print_param_info("\t\t"); } } <commit_msg>removed debug messages<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/base/ParameterMap.h> #include <shogun/base/Parameter.h> #include <shogun/mathematics/Math.h> using namespace shogun; SGParamInfo::SGParamInfo() { m_name=NULL; m_ctype=(EContainerType) -1; m_stype=(EStructType) -1; m_ptype=(EPrimitiveType) -1; m_param_version=-1; } SGParamInfo::SGParamInfo(const SGParamInfo& orig) { /* copy name if existent */ m_name=orig.m_name ? strdup(orig.m_name) : NULL; m_ctype=orig.m_ctype; m_stype=orig.m_stype; m_ptype=orig.m_ptype; m_param_version=orig.m_param_version; } SGParamInfo::SGParamInfo(const char* name, EContainerType ctype, EStructType stype, EPrimitiveType ptype, int32_t param_version) { /* copy name if existent */ m_name=name ? strdup(name) : NULL; m_ctype=ctype; m_stype=stype; m_ptype=ptype; m_param_version=param_version; } SGParamInfo::SGParamInfo(const TParameter* param, int32_t param_version) { /* copy name if existent */ m_name=param->m_name ? strdup(param->m_name) : NULL; TSGDataType type=param->m_datatype; m_ctype=type.m_ctype; m_stype=type.m_stype; m_ptype=type.m_ptype; m_param_version=param_version; } SGParamInfo::~SGParamInfo() { SG_FREE(m_name); } char* SGParamInfo::to_string() const { char* buffer=SG_MALLOC(char, 200); strcpy(buffer, "SGParamInfo with: "); strcat(buffer, "name=\""); strcat(buffer, m_name ? m_name : "NULL"); strcat(buffer, "\", type="); char* b; /* only cat type if it is defined (is not when std constructor was used)*/ if (!is_empty()) { TSGDataType t(m_ctype, m_stype, m_ptype); index_t l=100; b=SG_MALLOC(char, l); t.to_string(b, l); strcat(buffer, b); SG_FREE(b); } else strcat(buffer, "no type"); b=SG_MALLOC(char, 10); sprintf(b, "%d", m_param_version); strcat(buffer, ", version="); strcat(buffer, b); SG_FREE(b); return buffer; } void SGParamInfo::print_param_info(const char* prefix) const { char* s=to_string(); SG_SPRINT("%s%s\n", prefix, s); SG_FREE(s); } SGParamInfo* SGParamInfo::duplicate() const { return new SGParamInfo(m_name, m_ctype, m_stype, m_ptype, m_param_version); } bool SGParamInfo::operator==(const SGParamInfo& other) const { bool result=true; /* handle NULL strings */ if ((!m_name && other.m_name) || (m_name && !other.m_name)) return false; if (m_name && other.m_name) result&=!strcmp(m_name, other.m_name); result&=m_ctype==other.m_ctype; result&=m_stype==other.m_stype; result&=m_ptype==other.m_ptype; result&=m_param_version==other.m_param_version; return result; } bool SGParamInfo::operator!=(const SGParamInfo& other) const { return !operator ==(other); } bool SGParamInfo::operator<(const SGParamInfo& other) const { /* NULL here is always smaller than anything */ if (!m_name) { if (!other.m_name) return false; else return true; } else if (!other.m_name) return true; int32_t result=strcmp(m_name, other.m_name); if (result==0) { if (m_param_version==other.m_param_version) { if (m_ctype==other.m_ctype) { if (m_stype==other.m_stype) { if (m_ptype==other.m_ptype) { return false; } else return m_ptype<other.m_ptype; } else return m_stype<other.m_stype; } else return m_ctype<other.m_ctype; } else return m_param_version<other.m_param_version; } else return result<0; } bool SGParamInfo::operator>(const SGParamInfo& other) const { return !(*this<(other)) && !(*this==other); } bool SGParamInfo::is_empty() const { /* return true if this info is for empty parameter */ return m_ctype<0 && m_stype<0 && m_ptype<0 && !m_name; } ParameterMapElement::ParameterMapElement() { m_key=NULL; m_values=NULL; } ParameterMapElement::ParameterMapElement(const SGParamInfo* key, DynArray<const SGParamInfo*>* values) { m_key=key; m_values=values; } ParameterMapElement::~ParameterMapElement() { delete m_key; if (m_values) { for (index_t i=0; i<m_values->get_num_elements(); ++i) delete m_values->get_element(i); delete m_values; } } bool ParameterMapElement::operator==(const ParameterMapElement& other) const { return *m_key==*other.m_key; } bool ParameterMapElement::operator<(const ParameterMapElement& other) const { return *m_key<*other.m_key; } bool ParameterMapElement::operator>(const ParameterMapElement& other) const { return *m_key>*other.m_key; } ParameterMap::ParameterMap() { m_finalized=false; } ParameterMap::~ParameterMap() { for (index_t i=0; i<m_map_elements.get_num_elements(); ++i) delete m_map_elements[i]; for (index_t i=0; i<m_multi_map_elements.get_num_elements(); ++i) delete m_multi_map_elements[i]; } void ParameterMap::put(const SGParamInfo* key, const SGParamInfo* value) { /* assert that versions do differ exactly one if mapping is non-empty */ if(key->m_param_version-value->m_param_version!=1) { if (!key->is_empty() && !value->is_empty()) { char* s=key->to_string(); char* t=value->to_string(); SG_SERROR("Versions of parameter mappings from \"%s\" to \"%s\" have" " to differ exactly one\n", s, t); SG_FREE(s); SG_FREE(t); } } /* always add array of ONE element as values, will be processed later * in finalize map method */ DynArray<const SGParamInfo*>* values=new DynArray<const SGParamInfo*>(); values->append_element(value); m_map_elements.append_element(new ParameterMapElement(key, values)); m_finalized=false; } DynArray<const SGParamInfo*>* ParameterMap::get(const SGParamInfo key) const { return get(&key); } DynArray<const SGParamInfo*>* ParameterMap::get(const SGParamInfo* key) const { index_t num_elements=m_multi_map_elements.get_num_elements(); /* check if maps is finalized */ if (!m_finalized && num_elements) SG_SERROR("Call finalize_map() before calling get()\n"); /* do binary search in array of pointers */ /* dummy element for searching */ ParameterMapElement* dummy=new ParameterMapElement(key->duplicate(), NULL); index_t index=CMath::binary_search<ParameterMapElement> ( m_multi_map_elements.get_array(), num_elements, dummy); delete dummy; if (index==-1) return NULL; ParameterMapElement* element=m_multi_map_elements.get_element(index); return element->m_values; } void ParameterMap::finalize_map() { /* only do something if there are elements in map */ if (!m_map_elements.get_num_elements()) return; /* sort underlying array */ CMath::qsort<ParameterMapElement> (m_map_elements.get_array(), m_map_elements.get_num_elements()); // SG_SPRINT("map elements before finalize\n"); for (index_t i=0; i<m_map_elements.get_num_elements(); ++i) { ParameterMapElement* current=m_map_elements[i]; // SG_SPRINT("element %d:\n", i); // SG_SPRINT("\tkey: "); current->m_key->print_param_info(); // SG_SPRINT("\t%d values:\n", current->m_values->get_num_elements()); for (index_t j=0; j<current->m_values->get_num_elements(); ++j) current->m_values->get_element(j)->print_param_info("\t\t"); } /* clear old multi elements. These were copies. */ for (index_t i=0; i<m_multi_map_elements.get_num_elements(); ++i) delete m_multi_map_elements[i]; m_multi_map_elements.reset(); // SG_SPRINT("\nstarting finalization\n"); /* iterate over all elements of map elements (have all one value (put)) and * add all values of same key to ONE map element of hidden structure */ DynArray<const SGParamInfo*>* values=new DynArray<const SGParamInfo*>(); const SGParamInfo* current_key=m_map_elements[0]->m_key; char* s=current_key->to_string(); // SG_SPRINT("current key: %s\n", s); SG_FREE(s); for (index_t i=0; i<m_map_elements.get_num_elements(); ++i) { const ParameterMapElement* current=m_map_elements[i]; if (*current_key != *current->m_key) { /* create new values array to add and update key */ values=new DynArray<const SGParamInfo*>(); current_key=current->m_key; s=current_key->to_string(); // SG_SPRINT("new current key: %s\n", s); SG_FREE(s); } /* add to values array */ char* t=current->m_values->get_element(0)->to_string(); // SG_SPRINT("\tadding %s\n", t); SG_FREE(t); values->append_element(current->m_values->get_element(0)->duplicate()); /* if current values array has not been added to multi map elements, do * now */ index_t last_idx=m_multi_map_elements.get_num_elements()-1; if (last_idx<0 || m_multi_map_elements.get_element(last_idx)->m_values != values) { // SG_SPRINT("adding values array\n"); m_multi_map_elements.append_element( new ParameterMapElement(current_key->duplicate(), values)); } } m_finalized=true; // SG_SPRINT("leaving finalize_map()\n"); } void ParameterMap::print_map() { /* check if maps is finalized */ if (!m_finalized && m_map_elements.get_num_elements()) SG_SERROR("Call finalize_map() before calling print_map()\n"); // SG_SPRINT("map with %d keys:\n", m_multi_map_elements.get_num_elements()); for (index_t i=0; i<m_multi_map_elements.get_num_elements(); ++i) { ParameterMapElement* current=m_multi_map_elements[i]; // SG_SPRINT("element %d:\n", i); // SG_SPRINT("\tkey: "); current->m_key->print_param_info(); // SG_SPRINT("\t%d values:\n", current->m_values->get_num_elements()); for (index_t j=0; j<current->m_values->get_num_elements(); ++j) current->m_values->get_element(j)->print_param_info("\t\t"); } } <|endoftext|>
<commit_before>#include "neuralnetwork.h" #include "../util/mathutils.h" #include <iostream> NeuralNetwork::NeuralNetwork(uint32 input, uint32 hidden, uint32 output) : m_inputCount(input), m_hiddenCount(hidden), m_outputCount(output) { m_inputs = new real32[m_inputCount]; m_inputWeights = createMatrix(m_inputCount, m_hiddenCount); m_inputSums = new real32[m_hiddenCount]; m_inputBiases = new real32[m_hiddenCount]; m_inputOutputs = new real32[m_hiddenCount]; m_outputWeights = createMatrix(m_hiddenCount, m_outputCount); m_outputSums = new real32[m_outputCount]; m_outputBiases = new real32[m_outputCount]; m_outputs = new real32[m_outputCount]; std::cout << "neural network ctor" << std::endl; } NeuralNetwork::~NeuralNetwork() { std::cout << "neural network dtor" << std::endl; delete [] m_inputs; for (uint32 i = 0; i < m_inputCount; i++) { std::cout << m_inputs[i] << std::endl; } deleteMatrix(m_inputWeights, m_inputCount); for (uint32 i = 0; i < m_hiddenCount; i++) { std::cout << m_inputSums[i] << std::endl; } delete [] m_inputSums; delete [] m_inputBiases; delete [] m_inputOutputs; deleteMatrix(m_outputWeights, m_outputCount); delete [] m_outputSums; delete [] m_outputBiases; delete [] m_outputs; } void NeuralNetwork::setWeights(const real32* weights) { //TODO: Memcopy this shit. int k = 0; for (uint32 i = 0; i < m_inputCount; ++i) for (uint32 j = 0; j < m_hiddenCount; ++j) m_inputWeights[i][j] = weights[k++]; for (uint32 i = 0; i < m_hiddenCount; ++i) m_inputBiases[i] = weights[k++]; for (uint32 i = 0; i < m_hiddenCount; ++i) for (int j = 0; j < m_outputCount; ++j) m_outputWeights[i][j] = weights[k++]; for (uint32 i = 0; i < m_outputCount; ++i) m_outputBiases[i] = weights[k++]; } void NeuralNetwork::computeOutputs(real32* xValues) { // zero for (uint32 i = 0; i < m_hiddenCount; ++i) m_inputSums[i] = 0.0; for (uint32 i = 0; i < m_outputCount; ++i) m_outputSums[i] = 0.0; // Compute input-to-hidden weighted sums. for (uint32 j = 0; j < m_hiddenCount; ++j) for (uint32 i = 0; i < m_inputCount; ++i) m_inputSums[j] += xValues[i] * m_inputWeights[i][j]; // Add biases to input-to-hidden sums. for (uint32 i = 0; i < m_hiddenCount; ++i) m_inputSums[i] += m_inputBiases[i]; // Determine input-to-hidden output. // Step function for (uint32 i = 0; i < m_hiddenCount; ++i) m_inputOutputs[i] = HyperTanFunction(m_inputSums[i]); // Compute hidden-to-output weighted sums for (uint32 j = 0; j < m_outputCount; ++j) for (uint32 i = 0; i < m_hiddenCount; ++i) m_outputSums[j] += m_inputOutputs[i] * m_outputWeights[i][j]; // Add biases to input-to-hidden sums for (uint32 i = 0; i < m_outputCount; ++i) m_outputSums[i] += m_outputBiases[i]; // Determine hidden-to-output result HyperTanFunction for (uint32 i = 0; i < m_outputCount; ++i) m_outputs[i] = HyperTanFunction(m_outputSums[i]); } <commit_msg>Removed some old debug code from the neural network class.<commit_after>#include "neuralnetwork.h" #include "../util/mathutils.h" #include <iostream> NeuralNetwork::NeuralNetwork(uint32 input, uint32 hidden, uint32 output) : m_inputCount(input), m_hiddenCount(hidden), m_outputCount(output) { m_inputs = new real32[m_inputCount]; m_inputWeights = createMatrix(m_inputCount, m_hiddenCount); m_inputSums = new real32[m_hiddenCount]; m_inputBiases = new real32[m_hiddenCount]; m_inputOutputs = new real32[m_hiddenCount]; m_outputWeights = createMatrix(m_hiddenCount, m_outputCount); m_outputSums = new real32[m_outputCount]; m_outputBiases = new real32[m_outputCount]; m_outputs = new real32[m_outputCount]; } NeuralNetwork::~NeuralNetwork() { delete [] m_inputs; deleteMatrix(m_inputWeights, m_inputCount); delete [] m_inputSums; delete [] m_inputBiases; delete [] m_inputOutputs; deleteMatrix(m_outputWeights, m_outputCount); delete [] m_outputSums; delete [] m_outputBiases; delete [] m_outputs; } void NeuralNetwork::setWeights(const real32* weights) { //TODO: Memcopy this shit. int k = 0; for (uint32 i = 0; i < m_inputCount; ++i) for (uint32 j = 0; j < m_hiddenCount; ++j) m_inputWeights[i][j] = weights[k++]; for (uint32 i = 0; i < m_hiddenCount; ++i) m_inputBiases[i] = weights[k++]; for (uint32 i = 0; i < m_hiddenCount; ++i) for (int j = 0; j < m_outputCount; ++j) m_outputWeights[i][j] = weights[k++]; for (uint32 i = 0; i < m_outputCount; ++i) m_outputBiases[i] = weights[k++]; } void NeuralNetwork::computeOutputs(real32* xValues) { // zero for (uint32 i = 0; i < m_hiddenCount; ++i) m_inputSums[i] = 0.0; for (uint32 i = 0; i < m_outputCount; ++i) m_outputSums[i] = 0.0; // Compute input-to-hidden weighted sums. for (uint32 j = 0; j < m_hiddenCount; ++j) for (uint32 i = 0; i < m_inputCount; ++i) m_inputSums[j] += xValues[i] * m_inputWeights[i][j]; // Add biases to input-to-hidden sums. for (uint32 i = 0; i < m_hiddenCount; ++i) m_inputSums[i] += m_inputBiases[i]; // Determine input-to-hidden output. // Step function for (uint32 i = 0; i < m_hiddenCount; ++i) m_inputOutputs[i] = HyperTanFunction(m_inputSums[i]); // Compute hidden-to-output weighted sums for (uint32 j = 0; j < m_outputCount; ++j) for (uint32 i = 0; i < m_hiddenCount; ++i) m_outputSums[j] += m_inputOutputs[i] * m_outputWeights[i][j]; // Add biases to input-to-hidden sums for (uint32 i = 0; i < m_outputCount; ++i) m_outputSums[i] += m_outputBiases[i]; // Determine hidden-to-output result HyperTanFunction for (uint32 i = 0; i < m_outputCount; ++i) m_outputs[i] = HyperTanFunction(m_outputSums[i]); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libetonyek project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <string> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <libetonyek/libetonyek.h> #include <librevenge-stream/librevenge-stream.h> #if !defined ETONYEK_DETECTION_TEST_DIR #error ETONYEK_DETECTION_TEST_DIR not defined, cannot test #endif namespace test { using libetonyek::EtonyekDocument; using std::string; namespace { template<class Stream> void assertDetection(const string &name, const EtonyekDocument::Confidence expectedConfidence, const EtonyekDocument::Type *const expectedType = 0) { Stream input((string(ETONYEK_DETECTION_TEST_DIR) + "/" + name).c_str()); EtonyekDocument::Type type = EtonyekDocument::TYPE_UNKNOWN; const EtonyekDocument::Confidence confidence = EtonyekDocument::isSupported(&input, &type); CPPUNIT_ASSERT_EQUAL_MESSAGE(name + ": confidence", expectedConfidence, confidence); if (expectedType) CPPUNIT_ASSERT_EQUAL_MESSAGE(name + ": type", *expectedType, type); } void assertSupportedFile(const string &name, const EtonyekDocument::Confidence confidence, const EtonyekDocument::Type type) { assertDetection<librevenge::RVNGFileStream>(name, confidence, &type); } void assertSupportedPackage(const string &name, const EtonyekDocument::Confidence confidence, const EtonyekDocument::Type type) { assertDetection<librevenge::RVNGDirectoryStream>(name, confidence, &type); } void assertUnsupportedFile(const string &name) { assertDetection<librevenge::RVNGFileStream>(name, EtonyekDocument::CONFIDENCE_NONE); } void assertUnsupportedPackage(const string &name) { assertDetection<librevenge::RVNGDirectoryStream>(name, EtonyekDocument::CONFIDENCE_NONE); } static const EtonyekDocument::Confidence EXCELLENT = EtonyekDocument::CONFIDENCE_EXCELLENT; static const EtonyekDocument::Confidence SUPPORTED_PART = EtonyekDocument::CONFIDENCE_SUPPORTED_PART; } class EtonyekDocumentTest : public CPPUNIT_NS::TestFixture { public: virtual void setUp(); virtual void tearDown(); private: CPPUNIT_TEST_SUITE(EtonyekDocumentTest); CPPUNIT_TEST(testDetectKeynote); CPPUNIT_TEST(testDetectNumbers); CPPUNIT_TEST(testDetectPages); CPPUNIT_TEST(testUnsupported); CPPUNIT_TEST_SUITE_END(); private: void testDetectKeynote(); void testDetectNumbers(); void testDetectPages(); void testUnsupported(); }; void EtonyekDocumentTest::setUp() { } void EtonyekDocumentTest::tearDown() { } void EtonyekDocumentTest::testDetectKeynote() { const EtonyekDocument::Type type(EtonyekDocument::TYPE_KEYNOTE); // version 2-5 assertSupportedPackage("keynote4-package.key", EXCELLENT, type); assertSupportedFile("keynote4.apxl.gz", SUPPORTED_PART, type); assertSupportedFile("keynote4.apxl", SUPPORTED_PART, type); assertSupportedFile("keynote5-file.key", EXCELLENT, type); // version 6 assertSupportedPackage("keynote6-package.key", EXCELLENT, type); assertSupportedFile("keynote6.zip", SUPPORTED_PART, type); assertSupportedFile("keynote6-file.key", EXCELLENT, type); } void EtonyekDocumentTest::testDetectNumbers() { const EtonyekDocument::Type type(EtonyekDocument::TYPE_NUMBERS); // version 1-2 assertSupportedPackage("numbers2-package.numbers", EXCELLENT, type); assertSupportedFile("numbers2.xml", SUPPORTED_PART, type); assertSupportedFile("numbers2.xml.gz", SUPPORTED_PART, type); assertSupportedFile("numbers2-file.numbers", EXCELLENT, type); // version 3 assertSupportedPackage("numbers3-package.numbers", EXCELLENT, type); assertSupportedFile("numbers3.zip", SUPPORTED_PART, type); assertSupportedFile("numbers3-file.numbers", EXCELLENT, type); } void EtonyekDocumentTest::testDetectPages() { const EtonyekDocument::Type type(EtonyekDocument::TYPE_PAGES); // version 1-4 assertSupportedPackage("pages4-package.pages", EXCELLENT, type); assertSupportedFile("pages4.xml", SUPPORTED_PART, type); assertSupportedFile("pages4.xml.gz", SUPPORTED_PART, type); assertSupportedFile("pages4-file.pages", EXCELLENT, type); // version 5 assertSupportedPackage("pages5-package.pages", EXCELLENT, type); assertSupportedFile("pages5.zip", SUPPORTED_PART, type); assertSupportedFile("pages5-file.pages", EXCELLENT, type); } void EtonyekDocumentTest::testUnsupported() { // ensure the detection is not too broad assertUnsupportedPackage("unsupported1.package"); assertUnsupportedPackage("unsupported2.package"); assertUnsupportedFile("unsupported.xml"); assertUnsupportedFile("unsupported.zip"); } CPPUNIT_TEST_SUITE_REGISTRATION(EtonyekDocumentTest); } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <commit_msg>astyle<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libetonyek project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <string> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <libetonyek/libetonyek.h> #include <librevenge-stream/librevenge-stream.h> #if !defined ETONYEK_DETECTION_TEST_DIR #error ETONYEK_DETECTION_TEST_DIR not defined, cannot test #endif namespace test { using libetonyek::EtonyekDocument; using std::string; namespace { template<class Stream> void assertDetection(const string &name, const EtonyekDocument::Confidence expectedConfidence, const EtonyekDocument::Type *const expectedType = 0) { Stream input((string(ETONYEK_DETECTION_TEST_DIR) + "/" + name).c_str()); EtonyekDocument::Type type = EtonyekDocument::TYPE_UNKNOWN; const EtonyekDocument::Confidence confidence = EtonyekDocument::isSupported(&input, &type); CPPUNIT_ASSERT_EQUAL_MESSAGE(name + ": confidence", expectedConfidence, confidence); if (expectedType) CPPUNIT_ASSERT_EQUAL_MESSAGE(name + ": type", *expectedType, type); } void assertSupportedFile(const string &name, const EtonyekDocument::Confidence confidence, const EtonyekDocument::Type type) { assertDetection<librevenge::RVNGFileStream>(name, confidence, &type); } void assertSupportedPackage(const string &name, const EtonyekDocument::Confidence confidence, const EtonyekDocument::Type type) { assertDetection<librevenge::RVNGDirectoryStream>(name, confidence, &type); } void assertUnsupportedFile(const string &name) { assertDetection<librevenge::RVNGFileStream>(name, EtonyekDocument::CONFIDENCE_NONE); } void assertUnsupportedPackage(const string &name) { assertDetection<librevenge::RVNGDirectoryStream>(name, EtonyekDocument::CONFIDENCE_NONE); } static const EtonyekDocument::Confidence EXCELLENT = EtonyekDocument::CONFIDENCE_EXCELLENT; static const EtonyekDocument::Confidence SUPPORTED_PART = EtonyekDocument::CONFIDENCE_SUPPORTED_PART; } class EtonyekDocumentTest : public CPPUNIT_NS::TestFixture { public: virtual void setUp(); virtual void tearDown(); private: CPPUNIT_TEST_SUITE(EtonyekDocumentTest); CPPUNIT_TEST(testDetectKeynote); CPPUNIT_TEST(testDetectNumbers); CPPUNIT_TEST(testDetectPages); CPPUNIT_TEST(testUnsupported); CPPUNIT_TEST_SUITE_END(); private: void testDetectKeynote(); void testDetectNumbers(); void testDetectPages(); void testUnsupported(); }; void EtonyekDocumentTest::setUp() { } void EtonyekDocumentTest::tearDown() { } void EtonyekDocumentTest::testDetectKeynote() { const EtonyekDocument::Type type(EtonyekDocument::TYPE_KEYNOTE); // version 2-5 assertSupportedPackage("keynote4-package.key", EXCELLENT, type); assertSupportedFile("keynote4.apxl.gz", SUPPORTED_PART, type); assertSupportedFile("keynote4.apxl", SUPPORTED_PART, type); assertSupportedFile("keynote5-file.key", EXCELLENT, type); // version 6 assertSupportedPackage("keynote6-package.key", EXCELLENT, type); assertSupportedFile("keynote6.zip", SUPPORTED_PART, type); assertSupportedFile("keynote6-file.key", EXCELLENT, type); } void EtonyekDocumentTest::testDetectNumbers() { const EtonyekDocument::Type type(EtonyekDocument::TYPE_NUMBERS); // version 1-2 assertSupportedPackage("numbers2-package.numbers", EXCELLENT, type); assertSupportedFile("numbers2.xml", SUPPORTED_PART, type); assertSupportedFile("numbers2.xml.gz", SUPPORTED_PART, type); assertSupportedFile("numbers2-file.numbers", EXCELLENT, type); // version 3 assertSupportedPackage("numbers3-package.numbers", EXCELLENT, type); assertSupportedFile("numbers3.zip", SUPPORTED_PART, type); assertSupportedFile("numbers3-file.numbers", EXCELLENT, type); } void EtonyekDocumentTest::testDetectPages() { const EtonyekDocument::Type type(EtonyekDocument::TYPE_PAGES); // version 1-4 assertSupportedPackage("pages4-package.pages", EXCELLENT, type); assertSupportedFile("pages4.xml", SUPPORTED_PART, type); assertSupportedFile("pages4.xml.gz", SUPPORTED_PART, type); assertSupportedFile("pages4-file.pages", EXCELLENT, type); // version 5 assertSupportedPackage("pages5-package.pages", EXCELLENT, type); assertSupportedFile("pages5.zip", SUPPORTED_PART, type); assertSupportedFile("pages5-file.pages", EXCELLENT, type); } void EtonyekDocumentTest::testUnsupported() { // ensure the detection is not too broad assertUnsupportedPackage("unsupported1.package"); assertUnsupportedPackage("unsupported2.package"); assertUnsupportedFile("unsupported.xml"); assertUnsupportedFile("unsupported.zip"); } CPPUNIT_TEST_SUITE_REGISTRATION(EtonyekDocumentTest); } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <|endoftext|>
<commit_before>/** * This test tries out different command line options for a * generated model. */ #include <gtest/gtest.h> #include <stdexcept> class ModelCommand : public ::testing::TestWithParam<int> { public: static std::vector<std::string> arguments; static std::string model_path; static char get_path_separator() { char c; FILE *in; if(!(in = popen("make path_separator --no-print-directory", "r"))) throw std::runtime_error("\"make path_separator\" has failed."); c = fgetc(in); pclose(in); return c; } void static SetUpTestCase() { arguments.push_back("help"); arguments.push_back("data"); arguments.push_back("init"); arguments.push_back("samples"); arguments.push_back("append_samples"); arguments.push_back("seed"); arguments.push_back("chain_id"); arguments.push_back("iter"); arguments.push_back("warmup"); arguments.push_back("thin"); arguments.push_back("refresh"); arguments.push_back("leapfrog_steps"); arguments.push_back("max_treedepth"); arguments.push_back("epsilon"); arguments.push_back("epsilon_pm"); arguments.push_back("unit_mass_matrix"); arguments.push_back("delta"); arguments.push_back("gamma"); arguments.push_back("test_grad"); model_path.append("models"); model_path.append(1, get_path_separator()); model_path.append("command"); } }; std::vector<std::string> ModelCommand::arguments; std::string ModelCommand::model_path; TEST_F(ModelCommand, Arguments) { // std::cout << "model_path: " << model_path << std::endl; } /*TEST_P(ModelCommand, PTest) { std::cout << "PTest: " << GetParam() << std::endl; }*/ //INSTANTIATE_TEST_CASE_P(abc, ModelCommand, testing::Range(1, 10)); <commit_msg>test-models: created function to run command and return output<commit_after>/** * This test tries out different command line options for a * generated model. */ #include <gtest/gtest.h> #include <stdexcept> class ModelCommand : public ::testing::TestWithParam<int> { public: static std::vector<std::string> arguments; static std::string model_path; static char get_path_separator() { char c; FILE *in; if(!(in = popen("make path_separator --no-print-directory", "r"))) throw std::runtime_error("\"make path_separator\" has failed."); c = fgetc(in); pclose(in); return c; } void static SetUpTestCase() { arguments.push_back("help"); arguments.push_back("data"); arguments.push_back("init"); arguments.push_back("samples"); arguments.push_back("append_samples"); arguments.push_back("seed"); arguments.push_back("chain_id"); arguments.push_back("iter"); arguments.push_back("warmup"); arguments.push_back("thin"); arguments.push_back("refresh"); arguments.push_back("leapfrog_steps"); arguments.push_back("max_treedepth"); arguments.push_back("epsilon"); arguments.push_back("epsilon_pm"); arguments.push_back("unit_mass_matrix"); arguments.push_back("delta"); arguments.push_back("gamma"); arguments.push_back("test_grad"); model_path.append("models"); model_path.append(1, get_path_separator()); model_path.append("command"); } /** * Runs the command provided and returns the system output * as a string. * * @param command A command that can be run from the shell * @return the system output of the command */ std::string run_command(const std::string& command) { FILE *in; if(!(in = popen(command.c_str(), "r"))) { std::string err_msg; err_msg = "Could not run: \""; err_msg+= command; err_msg+= "\""; throw std::runtime_error(err_msg.c_str()); } std::string output; char buf[1024]; size_t count = fread(&buf, 1, 1024, in); while (count > 0) { output += std::string(&buf[0], &buf[count]); count = fread(&buf, 1, 1024, in); } pclose(in); return output; } std::vector<std::string> get_help_options(const std::string& help_output) { std::vector<std::string> help_options; //std::cout << "help_output: " << help_output << std::endl; return help_options; } }; std::vector<std::string> ModelCommand::arguments; std::string ModelCommand::model_path; TEST_F(ModelCommand, HelpMatchesArguments) { std::string help_command = model_path; help_command.append(" --help"); std::vector<std::string> help_options = get_help_options(run_command(help_command)); //std::cout << "Command output: " << run_command(command) << std::endl; } /*TEST_P(ModelCommand, PTest) { std::cout << "PTest: " << GetParam() << std::endl; }*/ //INSTANTIATE_TEST_CASE_P(abc, ModelCommand, testing::Range(1, 10)); <|endoftext|>
<commit_before>// Copyright (C) 2016 The Regents of the University of California (Regents). // 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 Regents or University of California 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 HOLDERS 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. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney (cmsweeney@cs.ucsb.edu) #include <Eigen/Core> #include <Eigen/LU> #include "gtest/gtest.h" #include "theia/math/qp_solver.h" #include "theia/util/random.h" namespace theia { // A rigged QP minimization problem with a known output. // // 1/2 * x' * P * x + q' * x + r // [ 5 -2 -1 ] // P = [ -2 4 3 ] // [ -1 3 5 ] // // q = [ 2 -35 -47 ]^t // r = 5 // // Minimizing this unbounded problem should result in: // x = [ 3 5 7 ]^t TEST(QPSolver, Unbounded) { static const double kTolerance = 1e-4; Eigen::MatrixXd P(3, 3); P << 5, -2, -1, -2, 4, 3, -1, 3, 5; Eigen::VectorXd q(3); q << 2, -35, -47; const double r = 5; QPSolver::Options options; options.max_num_iterations = 100; QPSolver qp_solver(options, P.sparseView(), q, r); Eigen::VectorXd solution; EXPECT_TRUE(qp_solver.Solve(&solution)); // Verify the solution is near (3, 5, 7). const Eigen::Vector3d gt_solution(3, 5, 7); for (int i = 0; i < 3; i++) { EXPECT_NEAR(solution(i), gt_solution(i), kTolerance); } // Check that the residual is near optimal. const double residual = 0.5 * solution.dot(P * solution) + solution.dot(q) + r; const double gt_residual = 0.5 * gt_solution.dot(P * gt_solution) + gt_solution.dot(q) + r; EXPECT_NEAR(residual, gt_residual, kTolerance); } TEST(QPSolver, LooseBounds) { static const double kTolerance = 1e-4; Eigen::MatrixXd P(3, 3); P << 5, -2, -1, -2, 4, 3, -1, 3, 5; Eigen::VectorXd q(3); q << 2, -35, -47; const double r = 5; QPSolver::Options options; options.max_num_iterations = 100; QPSolver qp_solver(options, P.sparseView(), q, r); // Set a lower bound that should not affect the output. Eigen::VectorXd lower_bound(3); lower_bound << 0, 0, 0; qp_solver.SetLowerBound(lower_bound); // Set an upper bound that should not affect the output. Eigen::VectorXd upper_bound(3); upper_bound << 10, 10, 10; qp_solver.SetUpperBound(upper_bound); Eigen::VectorXd solution; EXPECT_TRUE(qp_solver.Solve(&solution)); // Verify the solution is near (3, 5, 7). const Eigen::Vector3d gt_solution(3, 5, 7); for (int i = 0; i < 3; i++) { EXPECT_NEAR(solution(i), gt_solution(i), kTolerance); } // Check that the residual is near optimal. const double residual = 0.5 * solution.dot(P * solution) + solution.dot(q) + r; const double gt_residual = 0.5 * gt_solution.dot(P * gt_solution) + gt_solution.dot(q) + r; EXPECT_NEAR(residual, gt_residual, kTolerance); } TEST(QPSolver, TightBounds) { static const double kTolerance = 1e-4; Eigen::MatrixXd P(3, 3); P << 5, -2, -1, -2, 4, 3, -1, 3, 5; Eigen::VectorXd q(3); q << 2, -35, -47; const double r = 5; QPSolver::Options options; options.absolute_tolerance = 1e-8; options.relative_tolerance = 1e-8; QPSolver qp_solver(options, P.sparseView(), q, r); // Set a lower bound that constrains the output. Eigen::VectorXd lower_bound(3); lower_bound << 5, 7, 9; qp_solver.SetLowerBound(lower_bound); // Set an upper bound that constrains the output. Eigen::VectorXd upper_bound(3); upper_bound << 10, 12, 14; qp_solver.SetUpperBound(upper_bound); Eigen::VectorXd solution; EXPECT_TRUE(qp_solver.Solve(&solution)); // Verify the solution is near (5, 7, 9). const Eigen::Vector3d gt_solution(5, 7, 9); for (int i = 0; i < 3; i++) { EXPECT_NEAR(solution(i), gt_solution(i), kTolerance); } // Check that the residual is near optimal. const double residual = 0.5 * solution.dot(P * solution) + solution.dot(q) + r; const double gt_residual = 0.5 * gt_solution.dot(P * gt_solution) + gt_solution.dot(q) + r; EXPECT_NEAR(residual, gt_residual, kTolerance); } TEST(QPSolver, InvalidBounds) { Eigen::MatrixXd P(3, 3); P << 5, -2, -1, -2, 4, 3, -1, 3, 5; Eigen::VectorXd q(3); q << 2, -35, -47; const double r = 5; QPSolver::Options options; QPSolver qp_solver(options, P.sparseView(), q, r); // Set the upper bound as the lower bound. Eigen::VectorXd lower_bound(3); lower_bound << 5, 7, 9; qp_solver.SetUpperBound(lower_bound); // Set the lower bound as the upper bound, making the valid solution space // non-existant. Eigen::VectorXd upper_bound(3); upper_bound << 10, 12, 14; qp_solver.SetLowerBound(upper_bound); Eigen::VectorXd solution; EXPECT_FALSE(qp_solver.Solve(&solution)); } } // namespace theia <commit_msg>Fix broken QPSolver constructor call in the unit test<commit_after>// Copyright (C) 2016 The Regents of the University of California (Regents). // 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 Regents or University of California 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 HOLDERS 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. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney (cmsweeney@cs.ucsb.edu) #include <Eigen/Core> #include <Eigen/LU> #include "gtest/gtest.h" #include "theia/math/qp_solver.h" #include "theia/util/random.h" namespace theia { // A rigged QP minimization problem with a known output. // // 1/2 * x' * P * x + q' * x + r // [ 5 -2 -1 ] // P = [ -2 4 3 ] // [ -1 3 5 ] // // q = [ 2 -35 -47 ]^t // r = 5 // // Minimizing this unbounded problem should result in: // x = [ 3 5 7 ]^t TEST(QPSolver, Unbounded) { static const double kTolerance = 1e-4; Eigen::MatrixXd P(3, 3); P << 5, -2, -1, -2, 4, 3, -1, 3, 5; Eigen::VectorXd q(3); q << 2, -35, -47; const double r = 5; QPSolver::Options options; options.max_num_iterations = 100; Eigen::SparseMatrix<double> P_sparse(P.sparseView()); QPSolver qp_solver(options, P_sparse, q, r); Eigen::VectorXd solution; EXPECT_TRUE(qp_solver.Solve(&solution)); // Verify the solution is near (3, 5, 7). const Eigen::Vector3d gt_solution(3, 5, 7); for (int i = 0; i < 3; i++) { EXPECT_NEAR(solution(i), gt_solution(i), kTolerance); } // Check that the residual is near optimal. const double residual = 0.5 * solution.dot(P * solution) + solution.dot(q) + r; const double gt_residual = 0.5 * gt_solution.dot(P * gt_solution) + gt_solution.dot(q) + r; EXPECT_NEAR(residual, gt_residual, kTolerance); } TEST(QPSolver, LooseBounds) { static const double kTolerance = 1e-4; Eigen::MatrixXd P(3, 3); P << 5, -2, -1, -2, 4, 3, -1, 3, 5; Eigen::VectorXd q(3); q << 2, -35, -47; const double r = 5; QPSolver::Options options; options.max_num_iterations = 100; Eigen::SparseMatrix<double> P_sparse(P.sparseView()); QPSolver qp_solver(options, P_sparse, q, r); // Set a lower bound that should not affect the output. Eigen::VectorXd lower_bound(3); lower_bound << 0, 0, 0; qp_solver.SetLowerBound(lower_bound); // Set an upper bound that should not affect the output. Eigen::VectorXd upper_bound(3); upper_bound << 10, 10, 10; qp_solver.SetUpperBound(upper_bound); Eigen::VectorXd solution; EXPECT_TRUE(qp_solver.Solve(&solution)); // Verify the solution is near (3, 5, 7). const Eigen::Vector3d gt_solution(3, 5, 7); for (int i = 0; i < 3; i++) { EXPECT_NEAR(solution(i), gt_solution(i), kTolerance); } // Check that the residual is near optimal. const double residual = 0.5 * solution.dot(P * solution) + solution.dot(q) + r; const double gt_residual = 0.5 * gt_solution.dot(P * gt_solution) + gt_solution.dot(q) + r; EXPECT_NEAR(residual, gt_residual, kTolerance); } TEST(QPSolver, TightBounds) { static const double kTolerance = 1e-4; Eigen::MatrixXd P(3, 3); P << 5, -2, -1, -2, 4, 3, -1, 3, 5; Eigen::VectorXd q(3); q << 2, -35, -47; const double r = 5; QPSolver::Options options; options.absolute_tolerance = 1e-8; options.relative_tolerance = 1e-8; Eigen::SparseMatrix<double> P_sparse(P.sparseView()); QPSolver qp_solver(options, P_sparse, q, r); // Set a lower bound that constrains the output. Eigen::VectorXd lower_bound(3); lower_bound << 5, 7, 9; qp_solver.SetLowerBound(lower_bound); // Set an upper bound that constrains the output. Eigen::VectorXd upper_bound(3); upper_bound << 10, 12, 14; qp_solver.SetUpperBound(upper_bound); Eigen::VectorXd solution; EXPECT_TRUE(qp_solver.Solve(&solution)); // Verify the solution is near (5, 7, 9). const Eigen::Vector3d gt_solution(5, 7, 9); for (int i = 0; i < 3; i++) { EXPECT_NEAR(solution(i), gt_solution(i), kTolerance); } // Check that the residual is near optimal. const double residual = 0.5 * solution.dot(P * solution) + solution.dot(q) + r; const double gt_residual = 0.5 * gt_solution.dot(P * gt_solution) + gt_solution.dot(q) + r; EXPECT_NEAR(residual, gt_residual, kTolerance); } TEST(QPSolver, InvalidBounds) { Eigen::MatrixXd P(3, 3); P << 5, -2, -1, -2, 4, 3, -1, 3, 5; Eigen::VectorXd q(3); q << 2, -35, -47; const double r = 5; QPSolver::Options options; Eigen::SparseMatrix<double> P_sparse(P.sparseView()); QPSolver qp_solver(options, P_sparse, q, r); // Set the upper bound as the lower bound. Eigen::VectorXd lower_bound(3); lower_bound << 5, 7, 9; qp_solver.SetUpperBound(lower_bound); // Set the lower bound as the upper bound, making the valid solution space // non-existant. Eigen::VectorXd upper_bound(3); upper_bound << 10, 12, 14; qp_solver.SetLowerBound(upper_bound); Eigen::VectorXd solution; EXPECT_FALSE(qp_solver.Solve(&solution)); } } // namespace theia <|endoftext|>
<commit_before>/****************************************************************************** * @file hgpu_prng_test.cpp * @author Vadim Demchik <vadimdi@yahoo.com> * @version 1.0 * * @brief [PRNGCL library] * Pseudo-random number generators for HGPU package * tests submodule * * * @section LICENSE * * Copyright (c) 2013, Vadim Demchik * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ #include "hgpu_prng.h" unsigned int HGPU_PRNG_tests(HGPU_GPU_context* context){ unsigned int result = 0; // Toy PRNGs: result += HGPU_PRNG_test(context,HGPU_PRNG_PM, 1,HGPU_precision_single,10000,0.8641089363322169); result += HGPU_PRNG_test(context,HGPU_PRNG_CONSTANT,1,HGPU_precision_single,10000,0.0234896258916706); result += HGPU_PRNG_test(context,HGPU_PRNG_XOR128, 1,HGPU_precision_single,1000000,0.6839658189564943); result += HGPU_PRNG_test(context,HGPU_PRNG_XOR7, 1,HGPU_precision_single,1000000,0.09432704793289304); result += HGPU_PRNG_test(context,HGPU_PRNG_RANECU, 1,HGPU_precision_single,1000000,0.1810733857564628); result += HGPU_PRNG_test(context,HGPU_PRNG_RANMAR, 1,HGPU_precision_single,1000000,0.9911311864852905); result += HGPU_PRNG_test(context,HGPU_PRNG_RANLUX, 1,HGPU_precision_single,1000000,0.42132478952407837); result += HGPU_PRNG_test(context,HGPU_PRNG_MRG32K3A,1,HGPU_precision_single,1000000,0.8171486894057429); // Toy PRNGs: result += HGPU_PRNG_test(context,HGPU_PRNG_CONSTANT,1,HGPU_precision_double,1000000,0.023489625891670585); result += HGPU_PRNG_test(context,HGPU_PRNG_XOR128, 1,HGPU_precision_double,1000000,0.75871549689209505); result += HGPU_PRNG_test(context,HGPU_PRNG_XOR7, 1,HGPU_precision_double,1000000,0.75934357677468545); result += HGPU_PRNG_test(context,HGPU_PRNG_RANECU, 1,HGPU_precision_double,1000000,0.31995889215386432); result += HGPU_PRNG_test(context,HGPU_PRNG_RANMAR, 1,HGPU_precision_double,1000000,0.6419413344753124); result += HGPU_PRNG_test(context,HGPU_PRNG_RANLUX, 1,HGPU_precision_double,1000000,0.16665422447393138); result += HGPU_PRNG_test(context,HGPU_PRNG_MRG32K3A,1,HGPU_precision_double,1000000,0.00755252070810589); printf(" **************************************************\n"); if (result) printf(" %u test(s) failed!!!\n",result); else printf(" All tests passed\n"); printf(" **************************************************\n"); return result; } void HGPU_PRNG_benchmarks(HGPU_GPU_context* context){ double result = 0.0; result += HGPU_PRNG_benchmark(context,HGPU_PRNG_CONSTANT,HGPU_precision_single); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_PM, HGPU_precision_single); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_XOR128, HGPU_precision_single); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_XOR7, HGPU_precision_single); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_RANECU, HGPU_precision_single); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_RANMAR, HGPU_precision_single); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_RANLUX, HGPU_precision_single); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_MRG32K3A,HGPU_precision_single); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_CONSTANT,HGPU_precision_double); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_PM, HGPU_precision_double); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_XOR128, HGPU_precision_double); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_XOR7, HGPU_precision_double); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_RANECU, HGPU_precision_double); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_RANMAR, HGPU_precision_double); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_RANLUX, HGPU_precision_double); result += HGPU_PRNG_benchmark(context,HGPU_PRNG_MRG32K3A,HGPU_precision_double); } <commit_msg>Delete hgpu_prng_test.cpp<commit_after><|endoftext|>
<commit_before> class MinStack { public: stack<int> stk, minstk; MinStack() { // do initialization if necessary } void push(int number) { stk.push(number); if (minstk.empty() or number <= minstk.top()) { minstk.push(number); } } int pop() { int top = stk.top(); stk.pop(); if (top == minstk.top()) { minstk.pop(); } return top; } int min() { return minstk.top(); } };<commit_msg>Solved 12<commit_after> class MinStack { public: stack<int> stk, minstk; MinStack() { // do initialization if necessary } void push(int number) { stk.push(number); if (minstk.empty() or number <= minstk.top()) { minstk.push(number); //top of minstk is always the smallest } } int pop() { int top = stk.top(); stk.pop(); if (top == minstk.top()) { minstk.pop(); } return top; } int min() { return minstk.top(); } };<|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010, 2011 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 "mcolorcomboboxview.h" #include "mcolorcombobox.h" #include "mcolorlist.h" #include "mcolorlistview.h" #include "mcolorcomboboxbutton.h" #include "mlayout.h" #include "mdialog.h" #include "mgridlayoutpolicy.h" #include <QString> M_REGISTER_VIEW_NEW(MColorComboBoxView, MColorComboBox) MColorComboBoxViewPrivate::MColorComboBoxViewPrivate(MColorComboBoxView *q, MColorComboBox *controller) :q_ptr(q), controller(controller), button(0), popup(0), widget(0), layout(0), policy(0) { } MColorComboBoxViewPrivate::~MColorComboBoxViewPrivate() { delete popupWidget(); } void MColorComboBoxViewPrivate::init() { layout = new MLayout(); layout->setContentsMargins(0, 0, 0, 0); controller->setLayout(layout); policy = new MGridLayoutPolicy(layout); policy->setContentsMargins(0, 0, 0, 0); policy->setSpacing(0); policy->addItem(buttonWidget(),0,0); layout->setPolicy(policy); } void MColorComboBoxViewPrivate::updateTitle(const QString &title) { buttonWidget()->setTitle(title); popupWidget()->setTitle(title); } MColorComboBoxButton *MColorComboBoxViewPrivate::buttonWidget() { Q_Q(MColorComboBoxView); if (!button) { button = new MColorComboBoxButton(controller); QObject::connect(button, SIGNAL(clicked()), q, SLOT(_q_showPopup())); } return button; } MColorList *MColorComboBoxViewPrivate::colorWidget() { if (!widget) { widget = new MColorList(popupWidget()); widget->setView(new MColorListView(widget)); } return widget; } MDialog *MColorComboBoxViewPrivate::popupWidget() { if (!popup) { popup = new MDialog(); popup->setCentralWidget(colorWidget()); } return popup; } void MColorComboBoxViewPrivate::_q_showPopup() { Q_Q(MColorComboBoxView); popupWidget()->setTitle(q->model()->title()); colorWidget()->setSelectedColor(q->model()->color()); q->connect(popupWidget(), SIGNAL(disappeared()), q, SLOT(_q_popupDisappeared())); q->connect(colorWidget(), SIGNAL(colorPicked()), q, SLOT(_q_colorPicked())); popupWidget()->appear(); } void MColorComboBoxViewPrivate::_q_colorPicked() { Q_Q(MColorComboBoxView); q->model()->setColor(colorWidget()->selectedColor()); popupWidget()->disappear(); } void MColorComboBoxViewPrivate::_q_popupDisappeared() { Q_Q(MColorComboBoxView); q->disconnect(popupWidget(), SIGNAL(disappeared()), q, SLOT(_q_popupDisappeared())); q->disconnect(colorWidget(), SIGNAL(colorPicked()), q, SLOT(_q_colorPicked())); } MColorComboBoxView::MColorComboBoxView(MColorComboBox *controller) :MWidgetView(controller), d_ptr(new MColorComboBoxViewPrivate(this, controller)) { Q_D(MColorComboBoxView); d->init(); } MColorComboBoxView::~MColorComboBoxView() { delete d_ptr; } void MColorComboBoxView::applyStyle() { Q_D(MColorComboBoxView); MWidgetView::applyStyle(); d->buttonWidget()->setStyleName(style()->buttonStyleName()); d->buttonWidget()->setTitleStyleName(style()->titleStyleName()); d->buttonWidget()->setColorStyleName(style()->colorStyleName()); } void MColorComboBoxView::setupModel() { Q_D(MColorComboBoxView); MWidgetView::setupModel(); d->updateTitle(model()->title()); d->buttonWidget()->setColor(model()->color()); } void MColorComboBoxView::updateData(const QList<const char*> &modifications) { Q_D(MColorComboBoxView); MWidgetView::updateData(modifications); const char *member; foreach (member, modifications) { if (member == MColorComboBoxModel::Title) { d->updateTitle(model()->title()); } else if (member == MColorComboBoxModel::Color) { d->buttonWidget()->setColor(model()->color()); } } } <commit_msg>Fixes: NB#253948<commit_after>/*************************************************************************** ** ** Copyright (C) 2010, 2011 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 "mcolorcomboboxview.h" #include "mcolorcombobox.h" #include "mcolorlist.h" #include "mcolorlistview.h" #include "mcolorcomboboxbutton.h" #include "mlayout.h" #include "mdialog.h" #include "mgridlayoutpolicy.h" #include <QString> M_REGISTER_VIEW_NEW(MColorComboBoxView, MColorComboBox) MColorComboBoxViewPrivate::MColorComboBoxViewPrivate(MColorComboBoxView *q, MColorComboBox *controller) :q_ptr(q), controller(controller), button(0), popup(0), widget(0), layout(0), policy(0) { } MColorComboBoxViewPrivate::~MColorComboBoxViewPrivate() { delete popup; } void MColorComboBoxViewPrivate::init() { layout = new MLayout(); layout->setContentsMargins(0, 0, 0, 0); controller->setLayout(layout); policy = new MGridLayoutPolicy(layout); policy->setContentsMargins(0, 0, 0, 0); policy->setSpacing(0); policy->addItem(buttonWidget(),0,0); layout->setPolicy(policy); } void MColorComboBoxViewPrivate::updateTitle(const QString &title) { buttonWidget()->setTitle(title); popupWidget()->setTitle(title); } MColorComboBoxButton *MColorComboBoxViewPrivate::buttonWidget() { Q_Q(MColorComboBoxView); if (!button) { button = new MColorComboBoxButton(controller); QObject::connect(button, SIGNAL(clicked()), q, SLOT(_q_showPopup())); } return button; } MColorList *MColorComboBoxViewPrivate::colorWidget() { if (!widget) { widget = new MColorList(popupWidget()); widget->setView(new MColorListView(widget)); } return widget; } MDialog *MColorComboBoxViewPrivate::popupWidget() { if (!popup) { popup = new MDialog(); popup->setCentralWidget(colorWidget()); } return popup; } void MColorComboBoxViewPrivate::_q_showPopup() { Q_Q(MColorComboBoxView); popupWidget()->setTitle(q->model()->title()); colorWidget()->setSelectedColor(q->model()->color()); q->connect(popupWidget(), SIGNAL(disappeared()), q, SLOT(_q_popupDisappeared())); q->connect(colorWidget(), SIGNAL(colorPicked()), q, SLOT(_q_colorPicked())); popupWidget()->appear(); } void MColorComboBoxViewPrivate::_q_colorPicked() { Q_Q(MColorComboBoxView); q->model()->setColor(colorWidget()->selectedColor()); popupWidget()->disappear(); } void MColorComboBoxViewPrivate::_q_popupDisappeared() { Q_Q(MColorComboBoxView); q->disconnect(popupWidget(), SIGNAL(disappeared()), q, SLOT(_q_popupDisappeared())); q->disconnect(colorWidget(), SIGNAL(colorPicked()), q, SLOT(_q_colorPicked())); } MColorComboBoxView::MColorComboBoxView(MColorComboBox *controller) :MWidgetView(controller), d_ptr(new MColorComboBoxViewPrivate(this, controller)) { Q_D(MColorComboBoxView); d->init(); } MColorComboBoxView::~MColorComboBoxView() { delete d_ptr; } void MColorComboBoxView::applyStyle() { Q_D(MColorComboBoxView); MWidgetView::applyStyle(); d->buttonWidget()->setStyleName(style()->buttonStyleName()); d->buttonWidget()->setTitleStyleName(style()->titleStyleName()); d->buttonWidget()->setColorStyleName(style()->colorStyleName()); } void MColorComboBoxView::setupModel() { Q_D(MColorComboBoxView); MWidgetView::setupModel(); d->updateTitle(model()->title()); d->buttonWidget()->setColor(model()->color()); } void MColorComboBoxView::updateData(const QList<const char*> &modifications) { Q_D(MColorComboBoxView); MWidgetView::updateData(modifications); const char *member; foreach (member, modifications) { if (member == MColorComboBoxModel::Title) { d->updateTitle(model()->title()); } else if (member == MColorComboBoxModel::Color) { d->buttonWidget()->setColor(model()->color()); } } } <|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 "mnavigationbarview.h" #include "mnavigationbarview_p.h" #include <QGraphicsLinearLayout> #include <QGraphicsSceneMouseEvent> #include "mapplication.h" #include "mnavigationbar.h" #include "mnavigationbar_p.h" #include "mapplicationmenubutton.h" #include "mtoolbar.h" #include "mviewcreator.h" #include "mdeviceprofile.h" #include "mscalableimage.h" #include "mlayout.h" #include "mlinearlayoutpolicy.h" // -------------------------------------------------------------------------- // MNavigationBarViewPrivate // -------------------------------------------------------------------------- MNavigationBarViewPrivate::MNavigationBarViewPrivate() : layout(0), menuToolbarEscapePolicy(0), escapeToolbarMenuPolicy(0), escapeToolbarPolicy(0), toolbarPolicy(0), toolbarMenuPolicy(0), toolBarSlot(0), toolBarLayout(0), applicationMenuButton(0), toolBar(0), escapeButtonSlot(0), backButton(0), closeButton(0) { } MNavigationBarViewPrivate::~MNavigationBarViewPrivate() { if (toolBar) { toolBarLayout->removeItem(toolBar); toolBar->setParentItem(0); } delete applicationMenuButton; delete escapeButtonSlot; delete toolBarSlot; } void MNavigationBarViewPrivate::init() { applicationMenuButton = new MApplicationMenuButton(controller); applicationMenuButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); escapeButtonSlot = new MEscapeButtonSlot(controller); escapeButtonSlot->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); closeButton = new MButton(escapeButtonSlot); closeButton->setViewType("icon"); backButton = new MButton(escapeButtonSlot); backButton->setViewType("icon"); layout = new MLayout; layout->setContentsMargins(0, 0, 0, 0); controller->setLayout(layout); toolBarSlot = new QGraphicsWidget(controller); toolBarSlot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); toolBarLayout = new QGraphicsLinearLayout; toolBarLayout->setContentsMargins(0, 0, 0, 0); toolBarLayout->setSpacing(0); toolBarSlot->setLayout(toolBarLayout); menuToolbarEscapePolicy = new MLinearLayoutPolicy(layout, Qt::Horizontal); menuToolbarEscapePolicy->setSpacing(0); menuToolbarEscapePolicy->addItem(applicationMenuButton); menuToolbarEscapePolicy->addItem(toolBarSlot); menuToolbarEscapePolicy->addItem(escapeButtonSlot); escapeToolbarMenuPolicy = new MLinearLayoutPolicy(layout, Qt::Horizontal); escapeToolbarMenuPolicy->setSpacing(0); escapeToolbarMenuPolicy->addItem(escapeButtonSlot); escapeToolbarMenuPolicy->addItem(toolBarSlot); escapeToolbarMenuPolicy->addItem(applicationMenuButton); escapeToolbarPolicy = new MLinearLayoutPolicy(layout, Qt::Horizontal); escapeToolbarPolicy->setSpacing(0); escapeToolbarPolicy->addItem(escapeButtonSlot); escapeToolbarPolicy->addItem(toolBarSlot); toolbarPolicy = new MLinearLayoutPolicy(layout, Qt::Horizontal); toolbarPolicy->setSpacing(0); toolbarPolicy->addItem(toolBarSlot); toolbarMenuPolicy = new MLinearLayoutPolicy(layout, Qt::Horizontal); toolbarMenuPolicy->setSpacing(0); toolbarMenuPolicy->addItem(toolBarSlot); toolbarMenuPolicy->addItem(applicationMenuButton); // Connects button signals QObject::connect(applicationMenuButton, SIGNAL(clicked()), controller, SIGNAL(viewmenuTriggered())); QObject::connect(closeButton, SIGNAL(clicked()), controller, SIGNAL(closeButtonClicked())); QObject::connect(backButton, SIGNAL(clicked()), controller, SIGNAL(backButtonClicked())); } void MNavigationBarViewPrivate::notificationFlagChanged() { // FIXME: Add notification support! } void MNavigationBarViewPrivate::toolBarChanged() { Q_Q(MNavigationBarView); MToolBar *nextToolBar = q->model()->toolBar(); // Make sure the last toolbar is removed first... if (toolBar) { if (nextToolBar == toolBar) return; toolBarLayout->removeItem(toolBar); // previous toolBar is not ours anymore, so clean property we added toolBar->setProperty("buttonAlignment", QVariant::Invalid); toolBar->setParentItem(NULL); } if (nextToolBar) { toolBarLayout->addItem(nextToolBar); nextToolBar->show(); } toolBar = nextToolBar; } void MNavigationBarViewPrivate::updateEscapeButton() { Q_Q(MNavigationBarView); backButton->setVisible(q->model()->escapeButtonMode() == MNavigationBarModel::EscapeButtonBack); closeButton->setVisible(q->model()->escapeButtonMode() == MNavigationBarModel::EscapeButtonClose && q->style()->hasCloseButton()); } void MNavigationBarViewPrivate::updateMenuButton() { Q_Q(MNavigationBarView); if (q->style()->hasTitle()) { applicationMenuButton->setTextVisible(true); applicationMenuButton->setArrowIconVisible(q->model()->arrowIconVisible()); } else { applicationMenuButton->setTextVisible(false); applicationMenuButton->setArrowIconVisible(true); applicationMenuButton->setVisible(q->model()->arrowIconVisible()); } } void MNavigationBarViewPrivate::updateLayout() { Q_Q(MNavigationBarView); if (q->style()->hasTitle()) { layout->setPolicy(menuToolbarEscapePolicy); } else { bool escapeVisible = q->style()->hasCloseButton() || q->model()->escapeButtonMode() == MNavigationBarModel::EscapeButtonBack; bool menuVisible = q->model()->arrowIconVisible(); if (menuVisible && escapeVisible) { layout->setPolicy(escapeToolbarMenuPolicy); } else if (menuVisible && !escapeVisible) { layout->setPolicy(toolbarMenuPolicy); } else if (!menuVisible && escapeVisible) { layout->setPolicy(escapeToolbarPolicy); } else if (!menuVisible && !escapeVisible) { layout->setPolicy(toolbarPolicy); } } } void MNavigationBarViewPrivate::updateToolBarAlignment() { Q_Q(MNavigationBarView); if (!toolBar) return; QVariant alignment = QVariant::Invalid; if (!q->style()->hasTitle()) { bool escapeVisible = q->style()->hasCloseButton() || q->model()->escapeButtonMode() == MNavigationBarModel::EscapeButtonBack; bool menuVisible = q->model()->arrowIconVisible(); if (menuVisible && escapeVisible) { alignment = Qt::AlignHCenter; } else if (menuVisible && !escapeVisible) { alignment = Qt::AlignLeft; } else if (!menuVisible && escapeVisible) { alignment = Qt::AlignRight; } else if (!menuVisible && !escapeVisible) { alignment = Qt::AlignJustify; } } toolBar->setProperty("buttonAlignment", alignment); } // -------------------------------------------------------------------------- // MNavigationBarView // -------------------------------------------------------------------------- MNavigationBarView::MNavigationBarView(MNavigationBar *controller) : MSceneWindowView(*(new MNavigationBarViewPrivate()), controller) { Q_D(MNavigationBarView); d->init(); } MNavigationBarView::~MNavigationBarView() { } QRectF MNavigationBarView::boundingRect() const { QRectF br = MWidgetView::boundingRect(); if( style()->dropShadowImage() ) { br.setHeight(br.height() + style()->dropShadowImage()->pixmap()->size().height()); } return br; } QPainterPath MNavigationBarView::shape() const { QPainterPath path; // Get the base bounding rect, which excludes the shadow QRectF br = MWidgetView::boundingRect(); // The shape is not expanded by the margins+reactiveMargins, as the bar is // non-interactive by design path.addRect(br); return path; } void MNavigationBarView::updateData(const QList<const char *>& modifications) { Q_D(MNavigationBarView); MSceneWindowView::updateData(modifications); bool layoutNeedsUpdate = false; bool toolBarAlignmentNeedsUpdate = false; foreach( const char *member, modifications) { if (member == MNavigationBarModel::NotifyUser) { d->notificationFlagChanged(); } else if (member == MNavigationBarModel::ViewMenuDescription) { d->applicationMenuButton->setText(model()->viewMenuDescription()); } else if (member == MNavigationBarModel::ViewMenuIconID) { d->applicationMenuButton->setIconID(model()->viewMenuIconID()); } else if (member == MNavigationBarModel::ProgressIndicatorVisible) { d->applicationMenuButton->setProgressIndicatorVisible(model()->progressIndicatorVisible()); } else if (member == MNavigationBarModel::ArrowIconVisible) { d->updateMenuButton(); layoutNeedsUpdate = true; toolBarAlignmentNeedsUpdate = true; } else if (member == MNavigationBarModel::ToolBar) { d->toolBarChanged(); toolBarAlignmentNeedsUpdate = true; } else if (member == MNavigationBarModel::EscapeButtonMode) { d->updateEscapeButton(); layoutNeedsUpdate = true; toolBarAlignmentNeedsUpdate = true; } else if (member == MNavigationBarModel::EscapeButtonEnabled) { d->escapeButtonSlot->setEnabled(model()->escapeButtonEnabled()); } } if (layoutNeedsUpdate) d->updateLayout(); if (toolBarAlignmentNeedsUpdate) d->updateToolBarAlignment(); } void MNavigationBarView::setupModel() { MSceneWindowView::setupModel(); Q_D(MNavigationBarView); d->applicationMenuButton->setText(model()->viewMenuDescription()); d->applicationMenuButton->setIconID(model()->viewMenuIconID()); d->applicationMenuButton->setProgressIndicatorVisible(model()->progressIndicatorVisible()); d->escapeButtonSlot->setEnabled(model()->escapeButtonEnabled()); } void MNavigationBarView::applyStyle() { MSceneWindowView::applyStyle(); Q_D(MNavigationBarView); d->applicationMenuButton->setStyleName(style()->menuButtonStyleName()); d->escapeButtonSlot->setStyleName(style()->escapeButtonSlotStyleName()); d->closeButton->setStyleName(style()->closeButtonStyleName()); d->backButton->setStyleName(style()->backButtonStyleName()); d->updateEscapeButton(); d->updateMenuButton(); d->updateLayout(); d->toolBarChanged(); d->updateToolBarAlignment(); } void MNavigationBarView::mousePressEvent(QGraphicsSceneMouseEvent *event) { MWidgetView::mousePressEvent(event); bool transparent = qFuzzyIsNull(style()->backgroundOpacity()); // Don't let it propagate to widgets below if background is not transparent if (!transparent) event->accept(); } void MNavigationBarView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { MWidgetView::mouseReleaseEvent(event); bool transparent = qFuzzyIsNull(style()->backgroundOpacity()); // Don't let it propagate to widgets below if background is not transparent if (!transparent) event->accept(); } void MNavigationBarView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const { //draw shadow under the actual navigationbar if( style()->dropShadowImage() ) { style()->dropShadowImage()->draw(0, size().height(), boundingRect().width(), style()->dropShadowImage()->pixmap()->size().height(), painter); } MWidgetView::drawBackground(painter, option); } M_REGISTER_VIEW_NEW(MNavigationBarView, MNavigationBar) <commit_msg>Changes: Small refactoring of MNavigationBarView::toolBarChanged()<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 "mnavigationbarview.h" #include "mnavigationbarview_p.h" #include <QGraphicsLinearLayout> #include <QGraphicsSceneMouseEvent> #include "mapplication.h" #include "mnavigationbar.h" #include "mnavigationbar_p.h" #include "mapplicationmenubutton.h" #include "mtoolbar.h" #include "mviewcreator.h" #include "mdeviceprofile.h" #include "mscalableimage.h" #include "mlayout.h" #include "mlinearlayoutpolicy.h" // -------------------------------------------------------------------------- // MNavigationBarViewPrivate // -------------------------------------------------------------------------- MNavigationBarViewPrivate::MNavigationBarViewPrivate() : layout(0), menuToolbarEscapePolicy(0), escapeToolbarMenuPolicy(0), escapeToolbarPolicy(0), toolbarPolicy(0), toolbarMenuPolicy(0), toolBarSlot(0), toolBarLayout(0), applicationMenuButton(0), toolBar(0), escapeButtonSlot(0), backButton(0), closeButton(0) { } MNavigationBarViewPrivate::~MNavigationBarViewPrivate() { if (toolBar) { toolBarLayout->removeItem(toolBar); toolBar->setParentItem(0); } delete applicationMenuButton; delete escapeButtonSlot; delete toolBarSlot; } void MNavigationBarViewPrivate::init() { applicationMenuButton = new MApplicationMenuButton(controller); applicationMenuButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); escapeButtonSlot = new MEscapeButtonSlot(controller); escapeButtonSlot->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); closeButton = new MButton(escapeButtonSlot); closeButton->setViewType("icon"); backButton = new MButton(escapeButtonSlot); backButton->setViewType("icon"); layout = new MLayout; layout->setContentsMargins(0, 0, 0, 0); controller->setLayout(layout); toolBarSlot = new QGraphicsWidget(controller); toolBarSlot->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); toolBarLayout = new QGraphicsLinearLayout; toolBarLayout->setContentsMargins(0, 0, 0, 0); toolBarLayout->setSpacing(0); toolBarSlot->setLayout(toolBarLayout); menuToolbarEscapePolicy = new MLinearLayoutPolicy(layout, Qt::Horizontal); menuToolbarEscapePolicy->setSpacing(0); menuToolbarEscapePolicy->addItem(applicationMenuButton); menuToolbarEscapePolicy->addItem(toolBarSlot); menuToolbarEscapePolicy->addItem(escapeButtonSlot); escapeToolbarMenuPolicy = new MLinearLayoutPolicy(layout, Qt::Horizontal); escapeToolbarMenuPolicy->setSpacing(0); escapeToolbarMenuPolicy->addItem(escapeButtonSlot); escapeToolbarMenuPolicy->addItem(toolBarSlot); escapeToolbarMenuPolicy->addItem(applicationMenuButton); escapeToolbarPolicy = new MLinearLayoutPolicy(layout, Qt::Horizontal); escapeToolbarPolicy->setSpacing(0); escapeToolbarPolicy->addItem(escapeButtonSlot); escapeToolbarPolicy->addItem(toolBarSlot); toolbarPolicy = new MLinearLayoutPolicy(layout, Qt::Horizontal); toolbarPolicy->setSpacing(0); toolbarPolicy->addItem(toolBarSlot); toolbarMenuPolicy = new MLinearLayoutPolicy(layout, Qt::Horizontal); toolbarMenuPolicy->setSpacing(0); toolbarMenuPolicy->addItem(toolBarSlot); toolbarMenuPolicy->addItem(applicationMenuButton); // Connects button signals QObject::connect(applicationMenuButton, SIGNAL(clicked()), controller, SIGNAL(viewmenuTriggered())); QObject::connect(closeButton, SIGNAL(clicked()), controller, SIGNAL(closeButtonClicked())); QObject::connect(backButton, SIGNAL(clicked()), controller, SIGNAL(backButtonClicked())); } void MNavigationBarViewPrivate::notificationFlagChanged() { // FIXME: Add notification support! } void MNavigationBarViewPrivate::toolBarChanged() { Q_Q(MNavigationBarView); MToolBar *nextToolBar = q->model()->toolBar(); if (nextToolBar == toolBar) return; // Make sure the last toolbar is removed first... if (toolBar) { toolBarLayout->removeItem(toolBar); // previous toolBar is not ours anymore, so clean property we added toolBar->setProperty("buttonAlignment", QVariant::Invalid); toolBar->setParentItem(0); } if (nextToolBar) { toolBarLayout->addItem(nextToolBar); nextToolBar->show(); } toolBar = nextToolBar; } void MNavigationBarViewPrivate::updateEscapeButton() { Q_Q(MNavigationBarView); backButton->setVisible(q->model()->escapeButtonMode() == MNavigationBarModel::EscapeButtonBack); closeButton->setVisible(q->model()->escapeButtonMode() == MNavigationBarModel::EscapeButtonClose && q->style()->hasCloseButton()); } void MNavigationBarViewPrivate::updateMenuButton() { Q_Q(MNavigationBarView); if (q->style()->hasTitle()) { applicationMenuButton->setTextVisible(true); applicationMenuButton->setArrowIconVisible(q->model()->arrowIconVisible()); } else { applicationMenuButton->setTextVisible(false); applicationMenuButton->setArrowIconVisible(true); applicationMenuButton->setVisible(q->model()->arrowIconVisible()); } } void MNavigationBarViewPrivate::updateLayout() { Q_Q(MNavigationBarView); if (q->style()->hasTitle()) { layout->setPolicy(menuToolbarEscapePolicy); } else { bool escapeVisible = q->style()->hasCloseButton() || q->model()->escapeButtonMode() == MNavigationBarModel::EscapeButtonBack; bool menuVisible = q->model()->arrowIconVisible(); if (menuVisible && escapeVisible) { layout->setPolicy(escapeToolbarMenuPolicy); } else if (menuVisible && !escapeVisible) { layout->setPolicy(toolbarMenuPolicy); } else if (!menuVisible && escapeVisible) { layout->setPolicy(escapeToolbarPolicy); } else if (!menuVisible && !escapeVisible) { layout->setPolicy(toolbarPolicy); } } } void MNavigationBarViewPrivate::updateToolBarAlignment() { Q_Q(MNavigationBarView); if (!toolBar) return; QVariant alignment = QVariant::Invalid; if (!q->style()->hasTitle()) { bool escapeVisible = q->style()->hasCloseButton() || q->model()->escapeButtonMode() == MNavigationBarModel::EscapeButtonBack; bool menuVisible = q->model()->arrowIconVisible(); if (menuVisible && escapeVisible) { alignment = Qt::AlignHCenter; } else if (menuVisible && !escapeVisible) { alignment = Qt::AlignLeft; } else if (!menuVisible && escapeVisible) { alignment = Qt::AlignRight; } else if (!menuVisible && !escapeVisible) { alignment = Qt::AlignJustify; } } toolBar->setProperty("buttonAlignment", alignment); } // -------------------------------------------------------------------------- // MNavigationBarView // -------------------------------------------------------------------------- MNavigationBarView::MNavigationBarView(MNavigationBar *controller) : MSceneWindowView(*(new MNavigationBarViewPrivate()), controller) { Q_D(MNavigationBarView); d->init(); } MNavigationBarView::~MNavigationBarView() { } QRectF MNavigationBarView::boundingRect() const { QRectF br = MWidgetView::boundingRect(); if( style()->dropShadowImage() ) { br.setHeight(br.height() + style()->dropShadowImage()->pixmap()->size().height()); } return br; } QPainterPath MNavigationBarView::shape() const { QPainterPath path; // Get the base bounding rect, which excludes the shadow QRectF br = MWidgetView::boundingRect(); // The shape is not expanded by the margins+reactiveMargins, as the bar is // non-interactive by design path.addRect(br); return path; } void MNavigationBarView::updateData(const QList<const char *>& modifications) { Q_D(MNavigationBarView); MSceneWindowView::updateData(modifications); bool layoutNeedsUpdate = false; bool toolBarAlignmentNeedsUpdate = false; foreach( const char *member, modifications) { if (member == MNavigationBarModel::NotifyUser) { d->notificationFlagChanged(); } else if (member == MNavigationBarModel::ViewMenuDescription) { d->applicationMenuButton->setText(model()->viewMenuDescription()); } else if (member == MNavigationBarModel::ViewMenuIconID) { d->applicationMenuButton->setIconID(model()->viewMenuIconID()); } else if (member == MNavigationBarModel::ProgressIndicatorVisible) { d->applicationMenuButton->setProgressIndicatorVisible(model()->progressIndicatorVisible()); } else if (member == MNavigationBarModel::ArrowIconVisible) { d->updateMenuButton(); layoutNeedsUpdate = true; toolBarAlignmentNeedsUpdate = true; } else if (member == MNavigationBarModel::ToolBar) { d->toolBarChanged(); toolBarAlignmentNeedsUpdate = true; } else if (member == MNavigationBarModel::EscapeButtonMode) { d->updateEscapeButton(); layoutNeedsUpdate = true; toolBarAlignmentNeedsUpdate = true; } else if (member == MNavigationBarModel::EscapeButtonEnabled) { d->escapeButtonSlot->setEnabled(model()->escapeButtonEnabled()); } } if (layoutNeedsUpdate) d->updateLayout(); if (toolBarAlignmentNeedsUpdate) d->updateToolBarAlignment(); } void MNavigationBarView::setupModel() { MSceneWindowView::setupModel(); Q_D(MNavigationBarView); d->applicationMenuButton->setText(model()->viewMenuDescription()); d->applicationMenuButton->setIconID(model()->viewMenuIconID()); d->applicationMenuButton->setProgressIndicatorVisible(model()->progressIndicatorVisible()); d->escapeButtonSlot->setEnabled(model()->escapeButtonEnabled()); } void MNavigationBarView::applyStyle() { MSceneWindowView::applyStyle(); Q_D(MNavigationBarView); d->applicationMenuButton->setStyleName(style()->menuButtonStyleName()); d->escapeButtonSlot->setStyleName(style()->escapeButtonSlotStyleName()); d->closeButton->setStyleName(style()->closeButtonStyleName()); d->backButton->setStyleName(style()->backButtonStyleName()); d->updateEscapeButton(); d->updateMenuButton(); d->updateLayout(); d->toolBarChanged(); d->updateToolBarAlignment(); } void MNavigationBarView::mousePressEvent(QGraphicsSceneMouseEvent *event) { MWidgetView::mousePressEvent(event); bool transparent = qFuzzyIsNull(style()->backgroundOpacity()); // Don't let it propagate to widgets below if background is not transparent if (!transparent) event->accept(); } void MNavigationBarView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { MWidgetView::mouseReleaseEvent(event); bool transparent = qFuzzyIsNull(style()->backgroundOpacity()); // Don't let it propagate to widgets below if background is not transparent if (!transparent) event->accept(); } void MNavigationBarView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const { //draw shadow under the actual navigationbar if( style()->dropShadowImage() ) { style()->dropShadowImage()->draw(0, size().height(), boundingRect().width(), style()->dropShadowImage()->pixmap()->size().height(), painter); } MWidgetView::drawBackground(painter, option); } M_REGISTER_VIEW_NEW(MNavigationBarView, MNavigationBar) <|endoftext|>
<commit_before> // Methods for the class DAS - a class used to parse the dataset attribute // structure. // // jhrg 7/25/94 // $Log: DAS.cc,v $ // Revision 1.7 1994/10/13 15:46:57 jimg // Added compile-time switched instrumentation. // Removed the three definitions of DAS::print(). // Added DAS::print(ostream &os = cout) -- this is the only function for // printing the in-memory DAS. // // Revision 1.6 1994/10/05 16:34:12 jimg // Fixed bug in the parse function(s): the bison generated parser returns // 1 on error, 0 on success, but parse() was not checking for this. // Instead it returned the value of bison's parser function. // Changed types of `status' in print and parser functions from int to bool. // // Revision 1.5 1994/09/27 22:46:29 jimg // Changed the implementation of the class DAS from one which inherited // from DASVHMap to one which contains an instance of DASVHMap. // Added mfuncs to set/access the new instance variable. // // Revision 1.4 1994/09/09 15:33:38 jimg // Changed the base name of this class's parents from `Var' to DAS. // Added print() and removed operator<< (see the comments in AttrTable). // Added overloaded versions of print() and parse(). They can be called // using nothing (which defaults to std{in,out}), with a file descriptor, // with a FILE *, or with a String givin a file name. // // Revision 1.3 1994/08/02 20:11:25 jimg // Changes operator<< so that it writes a parsable version of the // attribute table. // // Revision 1.2 1994/08/02 19:17:40 jimg // Fixed log comments and rcsid[] variables (syntax errors due to // // comments caused compilation failures). // das.tab.c and .h are commited now as well. // // Revision 1.1 1994/08/02 18:40:09 jimg // Implemetation of the DAS class. This class is a container that maps // String objects which name variables to AttrTablePtr objects. // static char rcsid[]="$Id: DAS.cc,v 1.7 1994/10/13 15:46:57 jimg Exp $"; #ifdef __GNUG__ #pragma implementation #endif #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <iostream.h> #include <stdiostream.h> #include <Pix.h> #include <String.h> #include "debug.h" #include "DAS.h" // follows pragma since DAS.h is interface int dasrestart(FILE *yyin); int dasparse(DAS &table); // defined in das.tab.c DAS::DAS(AttrTablePtr dflt, unsigned int sz) : map(dflt, sz) { } // The class DASVHMap knows that it contains pointers to things and correctly // makes copies of those things when its copy ctor is called, so DAS can do a // simple member-wise copy. Similarly, we don't need to define our own op=. // This deletes the pointers to AttrTables allocated during the parse (and at // other times). jhrg 7/29/94 DAS::~DAS() { for(Pix p = map.first(); p; map.next(p)) { DBG(cerr << "map.contents() = " << map.contents(p) << endl); delete map.contents(p); } } Pix DAS::first_var() { return map.first(); } void DAS::next_var(Pix &p) { map.next(p); } String & DAS::get_name(Pix p) { return map.key(p); } AttrTable * DAS::get_table(Pix p) { return map.contents(p); } AttrTable * DAS::get_table(const String &name) { return map[name]; } // This function is necessary because (char *) arguments will be converted to // Pixs (and not Strings). Thus, get_table(name) needs a cast; it seems tough // to believe folks will always remember that. AttrTable * DAS::get_table(const char *name) { return map[name]; } AttrTable * DAS::add_table(const String &name, AttrTable *at) { return map[name] = at; } AttrTable * DAS::add_table(const char *name, AttrTable *at) { // DBG2(cerr << "In DAS::add_table(const char *, AttrTable *" << endl); return add_table((String)name, at); } /* Read attributes from a file. Returns false if unable to open the file, otherwise returns the result of the mfunc parse. */ bool DAS::parse(String fname) { FILE *in = fopen(fname, "r"); if (!in) { cerr << "Could not open: " << fname << endl; return false; } bool status = parse(in); fclose(in); return status; } /* Read attributes from a file descriptor. If the file descriptor cannot be fdopen'd, return false, otherwise return the status of the mfunc parse. NB: Added call to dup() within fdopen so that once the FILE * is closed the decriptor fd will not also be closed (instead the duplicate descriptor will be closed). Thus futeher information can be read from the descriptor fd. */ bool DAS::parse(int fd) { FILE *in = fdopen(dup(fd), "r"); if (!in) { cerr << "Could not access file" << endl; return false; } bool status = parse(in); fclose(in); return status; } /* Read attributes from in (which defaults to stdin). If dasrestart() fails, return false, otherwise return the status of dasparse(). */ bool DAS::parse(FILE *in) { if (!dasrestart(in)) { cerr << "Could not read from input source" << endl; return false; } return dasparse(*this) == 0; } #ifdef NEVER /* Write attributes from internal tables to a file. If the file cannot be opened for writing, return false, otherwise return the status of mfunc print. */ bool DAS::print(String fname) { FILE *out = fopen(fname, "w"); if (!out) { cerr << "Could not open: " << fname << endl; return false; } bool status = print(out); fclose(out); return status; } /* Write attributes from internal tables to a file descriptor. If the file descriptor cannot be fdopen'd, return false, otherwise return the status of the mfunc print. NB: See note for DAS::parse(int fd) about dup(). */ bool DAS::print(int fd) { FILE *out = fdopen(dup(fd), "w"); if (!out) { cerr << "Could not access the file descriptor for writing" << endl; return false; } bool status = print(out); fclose(out); return status; } #endif /* Write attributes from tables to `out' (which defaults to stdout). Return true. */ bool DAS::print(ostream &os) { // ostdiostream os(out); os << "Attributes {" << endl; for(Pix p = map.first(); p; map.next(p)) { os << " " << map.key(p) << " {" << endl; // map.contents(p) is an (AttrTable *) map.contents(p)->print(os, " "); os << " }" << endl; } os << "}" << endl; return true; } <commit_msg>dasrestart was incorrectly declared as void dasrestart(...) in DAS.cc. This caused the alpha to say `Could not read from file' whenever dasrestart was called (which happens whenever a new file is read). Fixed the declaration and removed the test on the (phantom) return value.<commit_after> // Methods for the class DAS - a class used to parse the dataset attribute // structure. // // jhrg 7/25/94 // $Log: DAS.cc,v $ // Revision 1.8 1994/10/13 16:42:59 jimg // dasrestart was incorrectly declared as void dasrestart(...) in DAS.cc. // This caused the alpha to say `Could not read from file' whenever // dasrestart was called (which happens whenever a new file is read). Fixed // the declaration and removed the test on the (phantom) return value. // // Revision 1.7 1994/10/13 15:46:57 jimg // Added compile-time switched instrumentation. // Removed the three definitions of DAS::print(). // Added DAS::print(ostream &os = cout) -- this is the only function for // printing the in-memory DAS. // // Revision 1.6 1994/10/05 16:34:12 jimg // Fixed bug in the parse function(s): the bison generated parser returns // 1 on error, 0 on success, but parse() was not checking for this. // Instead it returned the value of bison's parser function. // Changed types of `status' in print and parser functions from int to bool. // // Revision 1.5 1994/09/27 22:46:29 jimg // Changed the implementation of the class DAS from one which inherited // from DASVHMap to one which contains an instance of DASVHMap. // Added mfuncs to set/access the new instance variable. // // Revision 1.4 1994/09/09 15:33:38 jimg // Changed the base name of this class's parents from `Var' to DAS. // Added print() and removed operator<< (see the comments in AttrTable). // Added overloaded versions of print() and parse(). They can be called // using nothing (which defaults to std{in,out}), with a file descriptor, // with a FILE *, or with a String givin a file name. // // Revision 1.3 1994/08/02 20:11:25 jimg // Changes operator<< so that it writes a parsable version of the // attribute table. // // Revision 1.2 1994/08/02 19:17:40 jimg // Fixed log comments and rcsid[] variables (syntax errors due to // // comments caused compilation failures). // das.tab.c and .h are commited now as well. // // Revision 1.1 1994/08/02 18:40:09 jimg // Implemetation of the DAS class. This class is a container that maps // String objects which name variables to AttrTablePtr objects. // static char rcsid[]="$Id: DAS.cc,v 1.8 1994/10/13 16:42:59 jimg Exp $"; #ifdef __GNUG__ #pragma implementation #endif #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <iostream.h> #include <stdiostream.h> #include <Pix.h> #include <String.h> #include "debug.h" #include "DAS.h" // follows pragma since DAS.h is interface void dasrestart(FILE *yyin); int dasparse(DAS &table); // defined in das.tab.c DAS::DAS(AttrTablePtr dflt, unsigned int sz) : map(dflt, sz) { } // The class DASVHMap knows that it contains pointers to things and correctly // makes copies of those things when its copy ctor is called, so DAS can do a // simple member-wise copy. Similarly, we don't need to define our own op=. // This deletes the pointers to AttrTables allocated during the parse (and at // other times). jhrg 7/29/94 DAS::~DAS() { for(Pix p = map.first(); p; map.next(p)) { DBG(cerr << "map.contents() = " << map.contents(p) << endl); delete map.contents(p); } } Pix DAS::first_var() { return map.first(); } void DAS::next_var(Pix &p) { map.next(p); } String & DAS::get_name(Pix p) { return map.key(p); } AttrTable * DAS::get_table(Pix p) { return map.contents(p); } AttrTable * DAS::get_table(const String &name) { return map[name]; } // This function is necessary because (char *) arguments will be converted to // Pixs (and not Strings). Thus, get_table(name) needs a cast; it seems tough // to believe folks will always remember that. AttrTable * DAS::get_table(const char *name) { return map[name]; } AttrTable * DAS::add_table(const String &name, AttrTable *at) { return map[name] = at; } AttrTable * DAS::add_table(const char *name, AttrTable *at) { // DBG2(cerr << "In DAS::add_table(const char *, AttrTable *" << endl); return add_table((String)name, at); } /* Read attributes from a file. Returns false if unable to open the file, otherwise returns the result of the mfunc parse. */ bool DAS::parse(String fname) { FILE *in = fopen(fname, "r"); if (!in) { cerr << "Could not open: " << fname << endl; return false; } bool status = parse(in); fclose(in); return status; } /* Read attributes from a file descriptor. If the file descriptor cannot be fdopen'd, return false, otherwise return the status of the mfunc parse. NB: Added call to dup() within fdopen so that once the FILE * is closed the decriptor fd will not also be closed (instead the duplicate descriptor will be closed). Thus futeher information can be read from the descriptor fd. */ bool DAS::parse(int fd) { FILE *in = fdopen(dup(fd), "r"); if (!in) { cerr << "Could not access file" << endl; return false; } bool status = parse(in); fclose(in); return status; } /* Read attributes from in (which defaults to stdin). If dasrestart() fails, return false, otherwise return the status of dasparse(). */ bool DAS::parse(FILE *in) { dasrestart(in); return dasparse(*this) == 0; } #ifdef NEVER /* Write attributes from internal tables to a file. If the file cannot be opened for writing, return false, otherwise return the status of mfunc print. */ bool DAS::print(String fname) { FILE *out = fopen(fname, "w"); if (!out) { cerr << "Could not open: " << fname << endl; return false; } bool status = print(out); fclose(out); return status; } /* Write attributes from internal tables to a file descriptor. If the file descriptor cannot be fdopen'd, return false, otherwise return the status of the mfunc print. NB: See note for DAS::parse(int fd) about dup(). */ bool DAS::print(int fd) { FILE *out = fdopen(dup(fd), "w"); if (!out) { cerr << "Could not access the file descriptor for writing" << endl; return false; } bool status = print(out); fclose(out); return status; } #endif /* Write attributes from tables to `out' (which defaults to stdout). Return true. */ bool DAS::print(ostream &os) { // ostdiostream os(out); os << "Attributes {" << endl; for(Pix p = map.first(); p; map.next(p)) { os << " " << map.key(p) << " {" << endl; // map.contents(p) is an (AttrTable *) map.contents(p)->print(os, " "); os << " }" << endl; } os << "}" << endl; return true; } <|endoftext|>
<commit_before>#include <cmath> #include <Eigen/Eigenvalues> #include <float.h> #include "Ellipse.h" static std::ranlux24 G_engine(271828); std::ostream& operator<<(std::ostream& os, const EllipseGeometry& eg) { os << "{ C:" << eg.center.transpose() << "; R:" << eg.radius.transpose() << "; A:" << eg.angle << " }"; return os; } Eigen::Vector2f EllipseGenerator::operator()() { float phi = _arc_dist(G_engine); Eigen::Array2f circle_point(std::cos(phi), std::sin(phi)); Eigen::Array2f ellipse_point = _geometry.radius.array() * circle_point; Eigen::Vector2f noise(_noise_dist(G_engine), _noise_dist(G_engine)); Eigen::Vector2f rotated_ellipse_point = _rotation * (ellipse_point.matrix() + noise); return rotated_ellipse_point + _geometry.center; } // eccentricity: 0->circle, limit->1: line EllipseGenerator get_ellipse_generator(float max_center, float min_arc_angle, float sigma, Eigen::Vector2f radiusSpan, float max_eccentricity) { std::uniform_real_distribution<float> center_dist(0, max_center); std::uniform_real_distribution<float> radius_dist(radiusSpan(0), radiusSpan(1)); std::uniform_real_distribution<float> angle_dist(0, 2*M_PI); // Center. float cx = center_dist(G_engine); float cy = center_dist(G_engine); // Rotation. float angle = angle_dist(G_engine); // Radii; eccentricity must not be below min_eccentricity. float a, b; do { a = radius_dist(G_engine); b = radius_dist(G_engine); if (a < b) std::swap(a, b); } while (std::sqrt(a*a-b*b) >= max_eccentricity); // Arc span; must be at least min_arc_angle float phi_min, phi_max; do { phi_min = angle_dist(G_engine); phi_max = angle_dist(G_engine); if (phi_max < phi_min) std::swap(phi_max, phi_min); } while (phi_max - phi_min < min_arc_angle); EllipseGeometry geometry{Eigen::Vector2f(cx, cy), Eigen::Vector2f(a, b), angle}; return EllipseGenerator(geometry, Eigen::Vector2f(phi_min, phi_max), sigma); } ///////////////////////////////////////////////////////////////////////////// // FITTING based on the following paper: http://autotrace.sourceforge.net/WSCG98.pdf static Eigen::Vector2f get_offset(const Eigen::MatrixX2f& points) { auto sum = points.colwise().sum(); return sum / points.rows(); } static std::tuple<Eigen::Matrix3f,Eigen::Matrix3f,Eigen::Matrix3f> get_scatter_matrix(const Eigen::MatrixX2f& points, const Eigen::Vector2f& offset) { using namespace Eigen; const auto qf = [&](size_t i) { Vector2f p = points.row(i); auto pc = p - offset; return Vector3f(pc(0)*pc(0), pc(0)*pc(1), pc(1)*pc(1)); }; const auto lf = [&](size_t i) { Vector2f p = points.row(i); auto pc = p - offset; return Vector3f(pc(0), pc(1), 1); }; const size_t n = points.rows(); MatrixX3f D1(n,3), D2(n,3); // Construct the quadratic and linear parts. Doing it in two loops has better cache locality. for (size_t i = 0; i < n; ++i) D1.row(i) = qf(i); for (size_t i = 0; i < n; ++i) D2.row(i) = lf(i); // Construct the three parts of the symmetric scatter matrix. auto S1 = D1.transpose() * D1; auto S2 = D1.transpose() * D2; auto S3 = D2.transpose() * D2; return std::make_tuple(S1, S2, S3); } std::tuple<Eigen::Vector6f, Eigen::Vector2f> fit_solver(const Eigen::MatrixX2f& points) { using namespace Eigen; using std::get; static const struct C1_Initializer { Matrix3f matrix; Matrix3f inverse; C1_Initializer() { matrix << 0, 0, 2, 0, -1, 0, 2, 0, 0; inverse << 0, 0, 0.5, 0, -1, 0, 0.5, 0, 0; }; } C1; const auto offset = get_offset(points); const auto St = get_scatter_matrix(points, offset); const auto& S1 = std::get<0>(St); const auto& S2 = std::get<1>(St); const auto& S3 = std::get<2>(St); const auto T = -S3.inverse() * S2.transpose(); const auto M = C1.inverse * (S1 + S2*T); EigenSolver<Matrix3f> M_ev(M); Vector3f cond; { const auto evr = M_ev.eigenvectors().real().array(); cond = 4*evr.row(0)*evr.row(2) - evr.row(1)*evr.row(1); } float min = FLT_MAX; int imin = -1; for (int i = 0; i < 3; ++i) if (cond(i) > 0 && cond(i) < min) { imin = i; min = cond(i); } Vector6f ret = Matrix<float, 6, 1>::Zero(); if (imin >= 0) { Vector3f a1 = M_ev.eigenvectors().real().row(imin); Vector3f a2 = T*a1; ret.block<3,1>(0,0) = a1; ret.block<3,1>(3,0) = a2; } return std::make_tuple(ret, offset); } // Taken from OpenCV old code; see // https://github.com/Itseez/opencv/commit/4eda1662aa01a184e0391a2bb2e557454de7eb86#diff-97c8133c3c171e64ea0df0db4abd033c EllipseGeometry to_ellipse(const Conic& conic) { using namespace Eigen; auto coef = std::get<0>(conic); float idet = coef(0)*coef(2) - coef(1)*coef(1)/4; // ac-b^2/4 idet = idet > FLT_EPSILON ? 1.f/idet : 0; float scale = std::sqrt(idet/4); if (scale < FLT_EPSILON) throw std::domain_error("to_ellipse_2: singularity 1"); coef *= scale; float aa = coef(0), bb = coef(1), cc = coef(2), dd = coef(3), ee = coef(4), ff = coef(5); const Vector2f c = Vector2f(-dd*cc + ee*bb/2, -aa*ee + dd*bb/2) * 2; // offset ellipse to (x0,y0) ff += aa*c(0)*c(0) + bb*c(0)*c(1) + cc*c(1)*c(1) + dd*c(0) + ee*c(1); if (std::fabs(ff) < FLT_EPSILON) throw std::domain_error("to_ellipse_2: singularity 2"); Matrix2f S; S << aa, bb/2, bb/2, cc; S /= -ff; SelfAdjointEigenSolver<Matrix2f> es(S); Vector2f center = c + std::get<1>(conic); Vector2f radius = Vector2f(std::sqrt(1.f/es.eigenvalues()(0)), std::sqrt(1.f/es.eigenvalues()(1))); float angle = M_PI - std::atan2(es.eigenvectors()(1,0), es.eigenvectors()(1,1)); return EllipseGeometry{center, radius, angle}; } <commit_msg>Use SVD to determine semiaxes and angle.<commit_after>#include <cmath> #include <Eigen/Eigenvalues> #include <Eigen/SVD> #include <float.h> #include "Ellipse.h" static std::ranlux24 G_engine(271828); std::ostream& operator<<(std::ostream& os, const EllipseGeometry& eg) { os << "{ C:" << eg.center.transpose() << "; R:" << eg.radius.transpose() << "; A:" << eg.angle << " }"; return os; } Eigen::Vector2f EllipseGenerator::operator()() { float phi = _arc_dist(G_engine); Eigen::Array2f circle_point(std::cos(phi), std::sin(phi)); Eigen::Array2f ellipse_point = _geometry.radius.array() * circle_point; Eigen::Vector2f noise(_noise_dist(G_engine), _noise_dist(G_engine)); Eigen::Vector2f rotated_ellipse_point = _rotation * (ellipse_point.matrix() + noise); return rotated_ellipse_point + _geometry.center; } // eccentricity: 0->circle, limit->1: line EllipseGenerator get_ellipse_generator(float max_center, float min_arc_angle, float sigma, Eigen::Vector2f radiusSpan, float max_eccentricity) { std::uniform_real_distribution<float> center_dist(0, max_center); std::uniform_real_distribution<float> radius_dist(radiusSpan(0), radiusSpan(1)); std::uniform_real_distribution<float> angle_dist(0, 2*M_PI); // Center. float cx = center_dist(G_engine); float cy = center_dist(G_engine); // Rotation. float angle = angle_dist(G_engine); // Radii; eccentricity must not be below min_eccentricity. float a, b; do { a = radius_dist(G_engine); b = radius_dist(G_engine); if (a < b) std::swap(a, b); } while (std::sqrt(a*a-b*b) >= max_eccentricity); // Arc span; must be at least min_arc_angle float phi_min, phi_max; do { phi_min = angle_dist(G_engine); phi_max = angle_dist(G_engine); if (phi_max < phi_min) std::swap(phi_max, phi_min); } while (phi_max - phi_min < min_arc_angle); EllipseGeometry geometry{Eigen::Vector2f(cx, cy), Eigen::Vector2f(a, b), angle}; return EllipseGenerator(geometry, Eigen::Vector2f(phi_min, phi_max), sigma); } ///////////////////////////////////////////////////////////////////////////// // FITTING based on the following paper: http://autotrace.sourceforge.net/WSCG98.pdf static Eigen::Vector2f get_offset(const Eigen::MatrixX2f& points) { auto sum = points.colwise().sum(); return sum / points.rows(); } static std::tuple<Eigen::Matrix3f,Eigen::Matrix3f,Eigen::Matrix3f> get_scatter_matrix(const Eigen::MatrixX2f& points, const Eigen::Vector2f& offset) { using namespace Eigen; const auto qf = [&](size_t i) { Vector2f p = points.row(i); auto pc = p - offset; return Vector3f(pc(0)*pc(0), pc(0)*pc(1), pc(1)*pc(1)); }; const auto lf = [&](size_t i) { Vector2f p = points.row(i); auto pc = p - offset; return Vector3f(pc(0), pc(1), 1); }; const size_t n = points.rows(); MatrixX3f D1(n,3), D2(n,3); // Construct the quadratic and linear parts. Doing it in two loops has better cache locality. for (size_t i = 0; i < n; ++i) D1.row(i) = qf(i); for (size_t i = 0; i < n; ++i) D2.row(i) = lf(i); // Construct the three parts of the symmetric scatter matrix. auto S1 = D1.transpose() * D1; auto S2 = D1.transpose() * D2; auto S3 = D2.transpose() * D2; return std::make_tuple(S1, S2, S3); } std::tuple<Eigen::Vector6f, Eigen::Vector2f> fit_solver(const Eigen::MatrixX2f& points) { using namespace Eigen; using std::get; static const struct C1_Initializer { Matrix3f matrix; Matrix3f inverse; C1_Initializer() { matrix << 0, 0, 2, 0, -1, 0, 2, 0, 0; inverse << 0, 0, 0.5, 0, -1, 0, 0.5, 0, 0; }; } C1; const auto offset = get_offset(points); const auto St = get_scatter_matrix(points, offset); const auto& S1 = std::get<0>(St); const auto& S2 = std::get<1>(St); const auto& S3 = std::get<2>(St); const auto T = -S3.inverse() * S2.transpose(); const auto M = C1.inverse * (S1 + S2*T); EigenSolver<Matrix3f> M_ev(M); Vector3f cond; { const auto evr = M_ev.eigenvectors().real().array(); cond = 4*evr.row(0)*evr.row(2) - evr.row(1)*evr.row(1); } float min = FLT_MAX; int imin = -1; for (int i = 0; i < 3; ++i) if (cond(i) > 0 && cond(i) < min) { imin = i; min = cond(i); } Vector6f ret = Matrix<float, 6, 1>::Zero(); if (imin >= 0) { Vector3f a1 = M_ev.eigenvectors().real().row(imin); Vector3f a2 = T*a1; ret.block<3,1>(0,0) = a1; ret.block<3,1>(3,0) = a2; } return std::make_tuple(ret, offset); } // Taken from OpenCV old code; see // https://github.com/Itseez/opencv/commit/4eda1662aa01a184e0391a2bb2e557454de7eb86#diff-97c8133c3c171e64ea0df0db4abd033c EllipseGeometry to_ellipse(const Conic& conic) { using namespace Eigen; auto coef = std::get<0>(conic); float idet = coef(0)*coef(2) - coef(1)*coef(1)/4; // ac-b^2/4 idet = idet > FLT_EPSILON ? 1.f/idet : 0; float scale = std::sqrt(idet/4); if (scale < FLT_EPSILON) throw std::domain_error("to_ellipse_2: singularity 1"); coef *= scale; float aa = coef(0), bb = coef(1), cc = coef(2), dd = coef(3), ee = coef(4), ff = coef(5); const Vector2f c = Vector2f(-dd*cc + ee*bb/2, -aa*ee + dd*bb/2) * 2; // offset ellipse to (x0,y0) ff += aa*c(0)*c(0) + bb*c(0)*c(1) + cc*c(1)*c(1) + dd*c(0) + ee*c(1); if (std::fabs(ff) < FLT_EPSILON) throw std::domain_error("to_ellipse_2: singularity 2"); Matrix2f S; S << aa, bb/2, bb/2, cc; S /= -ff; // SVs are sorted from largest to smallest JacobiSVD<Matrix2f> svd(S, ComputeFullU); const auto& vals = svd.singularValues(); const auto& mat_u = svd.matrixU(); Vector2f center = c + std::get<1>(conic); Vector2f radius = Vector2f(std::sqrt(1.f/vals(1)), std::sqrt(1.f/vals(0))); float angle = M_PI - std::atan2(mat_u(1,0), mat_u(0,0)); return EllipseGeometry{center, radius, angle}; } <|endoftext|>
<commit_before>/***************************************************************************** * Project: BaBar detector at the SLAC PEP-II B-factory * Package: RooFitTools * File: $Id: RooKeysPdf.cc,v 1.7 2002/04/04 00:18:00 verkerke Exp $ * Authors: * GR, Gerhard Raven, UC, San Diego , Gerhard.Raven@slac.stanford.edu * DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu * History: * 04-Jul-2000 GR Created initial version * 01-Sep-2000 DK Override useParameters() method to fix the normalization * * Copyright (C) 2000 UC, San Diego *****************************************************************************/ //#include "BaBar/BaBar.hh" #include <math.h> #include <iostream.h> #include "RooFitModels/RooKeysPdf.hh" #include "RooFitCore/RooAbsReal.hh" #include "RooFitCore/RooRealVar.hh" #include "RooFitCore/RooRandom.hh" #include "RooFitCore/RooDataSet.hh" ClassImp(RooKeysPdf) RooKeysPdf::RooKeysPdf(const char *name, const char *title, RooAbsReal& x, RooDataSet& data, Mirror mirror, Double_t rho) : RooAbsPdf(name,title), _x("x","Dependent",this,x), _nEvents(0), _dataPts(0), _weights(0), _mirrorLeft(mirror==MirrorLeft || mirror==MirrorBoth || mirror==MirrorLeftAsymRight), _mirrorRight(mirror==MirrorRight || mirror==MirrorBoth || mirror==MirrorAsymLeftRight), _asymLeft(mirror==MirrorAsymLeft || mirror==MirrorAsymLeftRight || mirror==MirrorAsymBoth), _asymRight(mirror==MirrorAsymRight || mirror==MirrorLeftAsymRight || mirror==MirrorAsymBoth), _rho(rho) { // cache stuff about x sprintf(_varName, "%s", x.GetName()); RooRealVar real= (RooRealVar&)(_x.arg()); _lo = real.getFitMin(); _hi = real.getFitMax(); _binWidth = (_hi-_lo)/(_nPoints-1); // form the lookup table LoadDataSet(data); } RooKeysPdf::RooKeysPdf(const RooKeysPdf& other, const char* name): RooAbsPdf(other,name), _x("x",this,other._x), _nEvents(other._nEvents), _dataPts(0), _weights(0), _mirrorLeft( other._mirrorLeft ), _mirrorRight( other._mirrorRight ), _asymLeft(other._asymLeft), _asymRight(other._asymRight), _rho( other._rho ) { // cache stuff about x sprintf(_varName, "%s", other._varName ); _lo = other._lo; _hi = other._hi; _binWidth = other._binWidth; // copy over data and weights... not necessary, commented out for speed // _dataPts = new Double_t[_nEvents]; // _weights = new Double_t[_nEvents]; // for (Int_t i= 0; i<_nEvents; i++) { // _dataPts[i]= other._dataPts[i]; // _weights[i]= other._weights[i]; // } // copy over the lookup table for (Int_t i= 0; i<_nPoints+1; i++) _lookupTable[i]= other._lookupTable[i]; } RooKeysPdf::~RooKeysPdf() { delete[] _dataPts; delete[] _weights; } void RooKeysPdf::LoadDataSet( RooDataSet& data) { delete[] _dataPts; delete[] _weights; // make new arrays for data and weights to fill _nEvents= (Int_t)data.numEntries(); if (_mirrorLeft) _nEvents += data.numEntries(); if (_mirrorRight) _nEvents += data.numEntries(); _dataPts = new Double_t[_nEvents]; _weights = new Double_t[_nEvents]; Double_t x0(0); Double_t x1(0); Double_t x2(0); Int_t i, idata=0; for (i=0; i<data.numEntries(); i++) { const RooArgSet *values= data.get(i); RooRealVar real= (RooRealVar&)(values->operator[](_varName)); _dataPts[idata]= real.getVal(); x0++; x1+=_dataPts[idata]; x2+=_dataPts[idata]*_dataPts[idata]; idata++; if (_mirrorLeft) { _dataPts[idata]= 2*_lo - real.getVal(); x0++; x1+=_dataPts[idata]; x2+=_dataPts[idata]*_dataPts[idata]; idata++; } if (_mirrorRight) { _dataPts[idata]= 2*_hi - real.getVal(); x0++; x1+=_dataPts[idata]; x2+=_dataPts[idata]*_dataPts[idata]; idata++; } } Double_t mean=x1/x0; Double_t sigma=sqrt(x2/_nEvents-mean*mean); Double_t h=pow(Double_t(4)/Double_t(3),0.2)*pow(_nEvents,-0.2)*_rho; Double_t hmin=h*sigma*sqrt(2)/10; Double_t norm=h*sqrt(sigma)/(2.0*sqrt(3.0)); _weights=new Double_t[_nEvents]; for(Int_t j=0;j<_nEvents;++j) { _weights[j]=norm/sqrt(g(_dataPts[j],h*sigma)); if (_weights[j]<hmin) _weights[j]=hmin; } for (i=0;i<_nPoints+1;++i) _lookupTable[i]=evaluateFull( _lo+Double_t(i)*_binWidth ); } Double_t RooKeysPdf::evaluate() const { Int_t i = (Int_t)floor((Double_t(_x)-_lo)/_binWidth); if (i<0) { cerr << "got point below lower bound:" << Double_t(_x) << " < " << _lo << " -- performing linear extrapolation..." << endl; i=0; } if (i>_nPoints-1) { cerr << "got point above upper bound:" << Double_t(_x) << " > " << _hi << " -- performing linear extrapolation..." << endl; i=_nPoints-1; } Double_t dx = (Double_t(_x)-(_lo+i*_binWidth))/_binWidth; // for now do simple linear interpolation. // one day replace by splines... return (_lookupTable[i]+dx*(_lookupTable[i+1]-_lookupTable[i])); } Double_t RooKeysPdf::evaluateFull( Double_t x ) const { Double_t y=0; for (Int_t i=0;i<_nEvents;++i) { Double_t chi=(x-_dataPts[i])/_weights[i]; y+=exp(-0.5*chi*chi)/_weights[i]; // if mirroring the distribution across either edge of // the range ("Boundary Kernels"), pick up the additional // contributions // if (_mirrorLeft) { // chi=(x-(2*_lo-_dataPts[i]))/_weights[i]; // y+=exp(-0.5*chi*chi)/_weights[i]; // } if (_asymLeft) { chi=(x-(2*_lo-_dataPts[i]))/_weights[i]; y-=exp(-0.5*chi*chi)/_weights[i]; } // if (_mirrorRight) { // chi=(x-(2*_hi-_dataPts[i]))/_weights[i]; // y+=exp(-0.5*chi*chi)/_weights[i]; // } if (_asymRight) { chi=(x-(2*_hi-_dataPts[i]))/_weights[i]; y-=exp(-0.5*chi*chi)/_weights[i]; } } static const Double_t sqrt2pi(sqrt(2*M_PI)); return y/(sqrt2pi*_nEvents); } Double_t RooKeysPdf::g(Double_t x,Double_t sigma) const { Double_t c=Double_t(1)/(2*sigma*sigma); Double_t y=0; for (Int_t i=0;i<_nEvents;++i) { Double_t r=x-_dataPts[i]; y+=exp(-c*r*r); } static const Double_t sqrt2pi(sqrt(2*M_PI)); return y/(sigma*sqrt2pi*_nEvents); } <commit_msg>Fix sigma calculation for the new mirror<commit_after>/***************************************************************************** * Project: BaBar detector at the SLAC PEP-II B-factory * Package: RooFitTools * File: $Id: RooKeysPdf.cc,v 1.8 2002/05/24 14:58:45 giraudpf Exp $ * Authors: * GR, Gerhard Raven, UC, San Diego , Gerhard.Raven@slac.stanford.edu * DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu * History: * 04-Jul-2000 GR Created initial version * 01-Sep-2000 DK Override useParameters() method to fix the normalization * * Copyright (C) 2000 UC, San Diego *****************************************************************************/ //#include "BaBar/BaBar.hh" #include <math.h> #include <iostream.h> #include "RooFitModels/RooKeysPdf.hh" #include "RooFitCore/RooAbsReal.hh" #include "RooFitCore/RooRealVar.hh" #include "RooFitCore/RooRandom.hh" #include "RooFitCore/RooDataSet.hh" ClassImp(RooKeysPdf) RooKeysPdf::RooKeysPdf(const char *name, const char *title, RooAbsReal& x, RooDataSet& data, Mirror mirror, Double_t rho) : RooAbsPdf(name,title), _x("x","Dependent",this,x), _nEvents(0), _dataPts(0), _weights(0), _mirrorLeft(mirror==MirrorLeft || mirror==MirrorBoth || mirror==MirrorLeftAsymRight), _mirrorRight(mirror==MirrorRight || mirror==MirrorBoth || mirror==MirrorAsymLeftRight), _asymLeft(mirror==MirrorAsymLeft || mirror==MirrorAsymLeftRight || mirror==MirrorAsymBoth), _asymRight(mirror==MirrorAsymRight || mirror==MirrorLeftAsymRight || mirror==MirrorAsymBoth), _rho(rho) { // cache stuff about x sprintf(_varName, "%s", x.GetName()); RooRealVar real= (RooRealVar&)(_x.arg()); _lo = real.getFitMin(); _hi = real.getFitMax(); _binWidth = (_hi-_lo)/(_nPoints-1); // form the lookup table LoadDataSet(data); } RooKeysPdf::RooKeysPdf(const RooKeysPdf& other, const char* name): RooAbsPdf(other,name), _x("x",this,other._x), _nEvents(other._nEvents), _dataPts(0), _weights(0), _mirrorLeft( other._mirrorLeft ), _mirrorRight( other._mirrorRight ), _asymLeft(other._asymLeft), _asymRight(other._asymRight), _rho( other._rho ) { // cache stuff about x sprintf(_varName, "%s", other._varName ); _lo = other._lo; _hi = other._hi; _binWidth = other._binWidth; // copy over data and weights... not necessary, commented out for speed // _dataPts = new Double_t[_nEvents]; // _weights = new Double_t[_nEvents]; // for (Int_t i= 0; i<_nEvents; i++) { // _dataPts[i]= other._dataPts[i]; // _weights[i]= other._weights[i]; // } // copy over the lookup table for (Int_t i= 0; i<_nPoints+1; i++) _lookupTable[i]= other._lookupTable[i]; } RooKeysPdf::~RooKeysPdf() { delete[] _dataPts; delete[] _weights; } void RooKeysPdf::LoadDataSet( RooDataSet& data) { delete[] _dataPts; delete[] _weights; // make new arrays for data and weights to fill _nEvents= (Int_t)data.numEntries(); if (_mirrorLeft) _nEvents += data.numEntries(); if (_mirrorRight) _nEvents += data.numEntries(); _dataPts = new Double_t[_nEvents]; _weights = new Double_t[_nEvents]; Double_t x0(0); Double_t x1(0); Double_t x2(0); Int_t i, idata=0; for (i=0; i<data.numEntries(); i++) { const RooArgSet *values= data.get(i); RooRealVar real= (RooRealVar&)(values->operator[](_varName)); _dataPts[idata]= real.getVal(); x0++; x1+=_dataPts[idata]; x2+=_dataPts[idata]*_dataPts[idata]; idata++; if (_mirrorLeft) { _dataPts[idata]= 2*_lo - real.getVal(); idata++; } if (_mirrorRight) { _dataPts[idata]= 2*_hi - real.getVal(); idata++; } } Double_t mean=x1/x0; Double_t sigma=sqrt(x2/x0-mean*mean); Double_t h=pow(Double_t(4)/Double_t(3),0.2)*pow(_nEvents,-0.2)*_rho; Double_t hmin=h*sigma*sqrt(2)/10; Double_t norm=h*sqrt(sigma)/(2.0*sqrt(3.0)); _weights=new Double_t[_nEvents]; for(Int_t j=0;j<_nEvents;++j) { _weights[j]=norm/sqrt(g(_dataPts[j],h*sigma)); if (_weights[j]<hmin) _weights[j]=hmin; } for (i=0;i<_nPoints+1;++i) _lookupTable[i]=evaluateFull( _lo+Double_t(i)*_binWidth ); } Double_t RooKeysPdf::evaluate() const { Int_t i = (Int_t)floor((Double_t(_x)-_lo)/_binWidth); if (i<0) { cerr << "got point below lower bound:" << Double_t(_x) << " < " << _lo << " -- performing linear extrapolation..." << endl; i=0; } if (i>_nPoints-1) { cerr << "got point above upper bound:" << Double_t(_x) << " > " << _hi << " -- performing linear extrapolation..." << endl; i=_nPoints-1; } Double_t dx = (Double_t(_x)-(_lo+i*_binWidth))/_binWidth; // for now do simple linear interpolation. // one day replace by splines... return (_lookupTable[i]+dx*(_lookupTable[i+1]-_lookupTable[i])); } Double_t RooKeysPdf::evaluateFull( Double_t x ) const { Double_t y=0; for (Int_t i=0;i<_nEvents;++i) { Double_t chi=(x-_dataPts[i])/_weights[i]; y+=exp(-0.5*chi*chi)/_weights[i]; // if mirroring the distribution across either edge of // the range ("Boundary Kernels"), pick up the additional // contributions // if (_mirrorLeft) { // chi=(x-(2*_lo-_dataPts[i]))/_weights[i]; // y+=exp(-0.5*chi*chi)/_weights[i]; // } if (_asymLeft) { chi=(x-(2*_lo-_dataPts[i]))/_weights[i]; y-=exp(-0.5*chi*chi)/_weights[i]; } // if (_mirrorRight) { // chi=(x-(2*_hi-_dataPts[i]))/_weights[i]; // y+=exp(-0.5*chi*chi)/_weights[i]; // } if (_asymRight) { chi=(x-(2*_hi-_dataPts[i]))/_weights[i]; y-=exp(-0.5*chi*chi)/_weights[i]; } } static const Double_t sqrt2pi(sqrt(2*M_PI)); return y/(sqrt2pi*_nEvents); } Double_t RooKeysPdf::g(Double_t x,Double_t sigma) const { Double_t c=Double_t(1)/(2*sigma*sigma); Double_t y=0; for (Int_t i=0;i<_nEvents;++i) { Double_t r=x-_dataPts[i]; y+=exp(-c*r*r); } static const Double_t sqrt2pi(sqrt(2*M_PI)); return y/(sigma*sqrt2pi*_nEvents); } <|endoftext|>
<commit_before><commit_msg>-Werror,-Wunused-variable<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dbtoolsclient.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2004-08-02 16:46:02 $ * * 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 EXPRESS 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 SVX_DBTOOLSCLIENT_HXX #define SVX_DBTOOLSCLIENT_HXX #ifndef CONNECTIVITY_VIRTUAL_DBTOOLS_HXX #include <connectivity/virtualdbtools.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _OSL_MODULE_H_ #include <osl/module.h> #endif #ifndef _SOLAR_H #include <tools/solar.h> #endif //........................................................................ namespace svxform { //........................................................................ //==================================================================== //= ODbtoolsClient //==================================================================== /** base class for classes which want to use dbtools features with load-on-call of the dbtools lib. */ class ODbtoolsClient { private: static ::osl::Mutex s_aMutex; static sal_Int32 s_nClients; static oslModule s_hDbtoolsModule; static ::connectivity::simple::createDataAccessToolsFactoryFunction s_pFactoryCreationFunc; //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) mutable BOOL m_bCreateAlready; private: mutable ::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory > m_xDataAccessFactory; protected: const ::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory >& getFactory() const { return m_xDataAccessFactory; } protected: ODbtoolsClient(); ~ODbtoolsClient(); //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) void create() const; private: static void registerClient(); static void revokeClient(); }; //==================================================================== //= OStaticDataAccessTools //==================================================================== class OStaticDataAccessTools : public ODbtoolsClient { protected: mutable ::rtl::Reference< ::connectivity::simple::IDataAccessTools > m_xDataAccessTools; //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) void create() const; void checkIfLoaded() const; public: OStaticDataAccessTools(); const ::rtl::Reference< ::connectivity::simple::IDataAccessTools >& getDataAccessTools() const { return m_xDataAccessTools; } // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> getNumberFormats( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _rxConn, sal_Bool _bAllowDefault ) const; // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection_withFeedback( const ::rtl::OUString& _rDataSourceName, const ::rtl::OUString& _rUser, const ::rtl::OUString& _rPwd, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory ) const SAL_THROW ( (::com::sun::star::sdbc::SQLException) ); // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> calcConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet>& _rxRowSet, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory ) const SAL_THROW ( (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ); // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getRowSetConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet>& _rxRowSet) const SAL_THROW ( (::com::sun::star::uno::RuntimeException) ); // ------------------------------------------------ void TransferFormComponentProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxOld, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxNew, const ::com::sun::star::lang::Locale& _rLocale ) const; // ------------------------------------------------ ::rtl::OUString quoteName( const ::rtl::OUString& _rQuote, const ::rtl::OUString& _rName ) const; // ------------------------------------------------ ::rtl::OUString quoteTableName( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _rxMeta, const ::rtl::OUString& _rName ,sal_Bool _bUseCatalogInSelect = sal_True ,sal_Bool _bUseSchemaInSelect = sal_True ) const; // ------------------------------------------------ ::com::sun::star::sdb::SQLContext prependContextInfo( ::com::sun::star::sdbc::SQLException& _rException, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext, const ::rtl::OUString& _rContextDescription, const ::rtl::OUString& _rContextDetails ) const; // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource > getDataSource( const ::rtl::OUString& _rsRegisteredName, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory ) const; // ------------------------------------------------ /** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::INSERT @param _rxCursorSet the property set */ sal_Bool canInsert(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const; // ------------------------------------------------ /** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::UPDATE @param _rxCursorSet the property set */ sal_Bool canUpdate(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const; // ------------------------------------------------ /** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::DELETE @param _rxCursorSet the property set */ sal_Bool canDelete(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const; // ------------------------------------------------ virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > getFieldsByCommandDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand, ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& _rxKeepFieldsAlive, ::dbtools::SQLExceptionInfo* _pErrorInfo = NULL ) SAL_THROW( ( ) ); // ------------------------------------------------ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > getFieldNamesByCommandDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand, ::dbtools::SQLExceptionInfo* _pErrorInfo = NULL ) SAL_THROW( ( ) ); // ------------------------------------------------ virtual sal_Bool isDataSourcePropertyEnabled(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& _xProp ,const ::rtl::OUString& _sProperty, sal_Bool _bDefault = sal_False) const; }; //........................................................................ } // namespace svxform //........................................................................ #endif // SVX_DBTOOLSCLIENT_HXX <commit_msg>INTEGRATION: CWS improveforms (1.6.2); FILE MERGED 2004/08/31 08:34:05 fs 1.6.2.1: #i33308# +getComponentContextConnection<commit_after>/************************************************************************* * * $RCSfile: dbtoolsclient.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2004-09-09 10:23:53 $ * * 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 EXPRESS 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 SVX_DBTOOLSCLIENT_HXX #define SVX_DBTOOLSCLIENT_HXX #ifndef CONNECTIVITY_VIRTUAL_DBTOOLS_HXX #include <connectivity/virtualdbtools.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _OSL_MODULE_H_ #include <osl/module.h> #endif #ifndef _SOLAR_H #include <tools/solar.h> #endif //........................................................................ namespace svxform { //........................................................................ //==================================================================== //= ODbtoolsClient //==================================================================== /** base class for classes which want to use dbtools features with load-on-call of the dbtools lib. */ class ODbtoolsClient { private: static ::osl::Mutex s_aMutex; static sal_Int32 s_nClients; static oslModule s_hDbtoolsModule; static ::connectivity::simple::createDataAccessToolsFactoryFunction s_pFactoryCreationFunc; //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) mutable BOOL m_bCreateAlready; private: mutable ::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory > m_xDataAccessFactory; protected: const ::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory >& getFactory() const { return m_xDataAccessFactory; } protected: ODbtoolsClient(); ~ODbtoolsClient(); //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) void create() const; private: static void registerClient(); static void revokeClient(); }; //==================================================================== //= OStaticDataAccessTools //==================================================================== class OStaticDataAccessTools : public ODbtoolsClient { protected: mutable ::rtl::Reference< ::connectivity::simple::IDataAccessTools > m_xDataAccessTools; //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) void create() const; void checkIfLoaded() const; public: OStaticDataAccessTools(); const ::rtl::Reference< ::connectivity::simple::IDataAccessTools >& getDataAccessTools() const { return m_xDataAccessTools; } // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> getNumberFormats( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _rxConn, sal_Bool _bAllowDefault ) const; // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection_withFeedback( const ::rtl::OUString& _rDataSourceName, const ::rtl::OUString& _rUser, const ::rtl::OUString& _rPwd, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory ) const SAL_THROW ( (::com::sun::star::sdbc::SQLException) ); // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> calcConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet>& _rxRowSet, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory ) const SAL_THROW ( (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ); // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getRowSetConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet>& _rxRowSet) const SAL_THROW ( (::com::sun::star::uno::RuntimeException) ); // ------------------------------------------------ void TransferFormComponentProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxOld, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxNew, const ::com::sun::star::lang::Locale& _rLocale ) const; // ------------------------------------------------ ::rtl::OUString quoteName( const ::rtl::OUString& _rQuote, const ::rtl::OUString& _rName ) const; // ------------------------------------------------ ::rtl::OUString quoteTableName( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _rxMeta, const ::rtl::OUString& _rName ,sal_Bool _bUseCatalogInSelect = sal_True ,sal_Bool _bUseSchemaInSelect = sal_True ) const; // ------------------------------------------------ ::com::sun::star::sdb::SQLContext prependContextInfo( ::com::sun::star::sdbc::SQLException& _rException, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext, const ::rtl::OUString& _rContextDescription, const ::rtl::OUString& _rContextDetails ) const; // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource > getDataSource( const ::rtl::OUString& _rsRegisteredName, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory ) const; // ------------------------------------------------ /** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::INSERT @param _rxCursorSet the property set */ sal_Bool canInsert(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const; // ------------------------------------------------ /** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::UPDATE @param _rxCursorSet the property set */ sal_Bool canUpdate(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const; // ------------------------------------------------ /** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::DELETE @param _rxCursorSet the property set */ sal_Bool canDelete(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const; // ------------------------------------------------ virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > getFieldsByCommandDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand, ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& _rxKeepFieldsAlive, ::dbtools::SQLExceptionInfo* _pErrorInfo = NULL ) SAL_THROW( ( ) ); // ------------------------------------------------ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > getFieldNamesByCommandDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand, ::dbtools::SQLExceptionInfo* _pErrorInfo = NULL ) SAL_THROW( ( ) ); // ------------------------------------------------ virtual sal_Bool isDataSourcePropertyEnabled(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& _xProp ,const ::rtl::OUString& _sProperty, sal_Bool _bDefault = sal_False) const; // ------------------------------------------------ virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > getComponentContextConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxComponent ); }; //........................................................................ } // namespace svxform //........................................................................ #endif // SVX_DBTOOLSCLIENT_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dbtoolsclient.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: pjunck $ $Date: 2004-10-22 11:54:05 $ * * 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 EXPRESS 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 SVX_DBTOOLSCLIENT_HXX #define SVX_DBTOOLSCLIENT_HXX #ifndef CONNECTIVITY_VIRTUAL_DBTOOLS_HXX #include <connectivity/virtualdbtools.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _OSL_MODULE_H_ #include <osl/module.h> #endif #ifndef _SOLAR_H #include <tools/solar.h> #endif //........................................................................ namespace svxform { //........................................................................ //==================================================================== //= ODbtoolsClient //==================================================================== /** base class for classes which want to use dbtools features with load-on-call of the dbtools lib. */ class ODbtoolsClient { private: static ::osl::Mutex s_aMutex; static sal_Int32 s_nClients; static oslModule s_hDbtoolsModule; static ::connectivity::simple::createDataAccessToolsFactoryFunction s_pFactoryCreationFunc; //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) mutable BOOL m_bCreateAlready; private: mutable ::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory > m_xDataAccessFactory; protected: const ::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory >& getFactory() const { return m_xDataAccessFactory; } protected: ODbtoolsClient(); ~ODbtoolsClient(); //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) void create() const; private: static void registerClient(); static void revokeClient(); }; //==================================================================== //= OStaticDataAccessTools //==================================================================== class OStaticDataAccessTools : public ODbtoolsClient { protected: mutable ::rtl::Reference< ::connectivity::simple::IDataAccessTools > m_xDataAccessTools; //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) void create() const; void checkIfLoaded() const; public: OStaticDataAccessTools(); const ::rtl::Reference< ::connectivity::simple::IDataAccessTools >& getDataAccessTools() const { return m_xDataAccessTools; } // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> getNumberFormats( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _rxConn, sal_Bool _bAllowDefault ) const; // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection_withFeedback( const ::rtl::OUString& _rDataSourceName, const ::rtl::OUString& _rUser, const ::rtl::OUString& _rPwd, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory ) const SAL_THROW ( (::com::sun::star::sdbc::SQLException) ); // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> calcConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet>& _rxRowSet, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory ) const SAL_THROW ( (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ); // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getRowSetConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet>& _rxRowSet) const SAL_THROW ( (::com::sun::star::uno::RuntimeException) ); // ------------------------------------------------ void TransferFormComponentProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxOld, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxNew, const ::com::sun::star::lang::Locale& _rLocale ) const; // ------------------------------------------------ ::rtl::OUString quoteName( const ::rtl::OUString& _rQuote, const ::rtl::OUString& _rName ) const; // ------------------------------------------------ ::rtl::OUString quoteTableName( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _rxMeta, const ::rtl::OUString& _rName ,sal_Bool _bUseCatalogInSelect = sal_True ,sal_Bool _bUseSchemaInSelect = sal_True ) const; // ------------------------------------------------ ::com::sun::star::sdb::SQLContext prependContextInfo( ::com::sun::star::sdbc::SQLException& _rException, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext, const ::rtl::OUString& _rContextDescription, const ::rtl::OUString& _rContextDetails ) const; // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource > getDataSource( const ::rtl::OUString& _rsRegisteredName, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory ) const; // ------------------------------------------------ /** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::INSERT @param _rxCursorSet the property set */ sal_Bool canInsert(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const; // ------------------------------------------------ /** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::UPDATE @param _rxCursorSet the property set */ sal_Bool canUpdate(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const; // ------------------------------------------------ /** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::DELETE @param _rxCursorSet the property set */ sal_Bool canDelete(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const; // ------------------------------------------------ virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > getFieldsByCommandDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand, ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& _rxKeepFieldsAlive, ::dbtools::SQLExceptionInfo* _pErrorInfo = NULL ) SAL_THROW( ( ) ); // ------------------------------------------------ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > getFieldNamesByCommandDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand, ::dbtools::SQLExceptionInfo* _pErrorInfo = NULL ) SAL_THROW( ( ) ); // ------------------------------------------------ virtual sal_Bool isDataSourcePropertyEnabled(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& _xProp ,const ::rtl::OUString& _sProperty, sal_Bool _bDefault = sal_False) const; // ------------------------------------------------ bool isEmbeddedInDatabase( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxComponent, ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxActualConnection ); // ------------------------------------------------ bool isEmbeddedInDatabase( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxComponent ); }; //........................................................................ } // namespace svxform //........................................................................ #endif // SVX_DBTOOLSCLIENT_HXX <commit_msg>INTEGRATION: CWS dba23 (1.8.208); FILE MERGED 2005/01/17 14:48:32 fs 1.8.208.1: #i40463# connectRowSet can now also throw a WrappedTargetException<commit_after>/************************************************************************* * * $RCSfile: dbtoolsclient.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2005-02-17 10:57:43 $ * * 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 EXPRESS 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 SVX_DBTOOLSCLIENT_HXX #define SVX_DBTOOLSCLIENT_HXX #ifndef CONNECTIVITY_VIRTUAL_DBTOOLS_HXX #include <connectivity/virtualdbtools.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _OSL_MODULE_H_ #include <osl/module.h> #endif #ifndef _SOLAR_H #include <tools/solar.h> #endif //........................................................................ namespace svxform { //........................................................................ //==================================================================== //= ODbtoolsClient //==================================================================== /** base class for classes which want to use dbtools features with load-on-call of the dbtools lib. */ class ODbtoolsClient { private: static ::osl::Mutex s_aMutex; static sal_Int32 s_nClients; static oslModule s_hDbtoolsModule; static ::connectivity::simple::createDataAccessToolsFactoryFunction s_pFactoryCreationFunc; //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) mutable BOOL m_bCreateAlready; private: mutable ::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory > m_xDataAccessFactory; protected: const ::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory >& getFactory() const { return m_xDataAccessFactory; } protected: ODbtoolsClient(); ~ODbtoolsClient(); //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) void create() const; private: static void registerClient(); static void revokeClient(); }; //==================================================================== //= OStaticDataAccessTools //==================================================================== class OStaticDataAccessTools : public ODbtoolsClient { protected: mutable ::rtl::Reference< ::connectivity::simple::IDataAccessTools > m_xDataAccessTools; //add by BerryJia for fixing Bug97420 Time:2002-9-12-11:00(PRC time) void create() const; void checkIfLoaded() const; public: OStaticDataAccessTools(); const ::rtl::Reference< ::connectivity::simple::IDataAccessTools >& getDataAccessTools() const { return m_xDataAccessTools; } // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> getNumberFormats( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _rxConn, sal_Bool _bAllowDefault ) const; // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection_withFeedback( const ::rtl::OUString& _rDataSourceName, const ::rtl::OUString& _rUser, const ::rtl::OUString& _rPwd, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory ) const SAL_THROW ( (::com::sun::star::sdbc::SQLException) ); // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> connectRowset( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet>& _rxRowSet, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory, sal_Bool _bSetAsActiveConnection ) const SAL_THROW ( ( ::com::sun::star::sdbc::SQLException , ::com::sun::star::lang::WrappedTargetException , ::com::sun::star::uno::RuntimeException) ); // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getRowSetConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet>& _rxRowSet) const SAL_THROW ( (::com::sun::star::uno::RuntimeException) ); // ------------------------------------------------ void TransferFormComponentProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxOld, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxNew, const ::com::sun::star::lang::Locale& _rLocale ) const; // ------------------------------------------------ ::rtl::OUString quoteName( const ::rtl::OUString& _rQuote, const ::rtl::OUString& _rName ) const; // ------------------------------------------------ ::rtl::OUString quoteTableName( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _rxMeta, const ::rtl::OUString& _rName ,sal_Bool _bUseCatalogInSelect = sal_True ,sal_Bool _bUseSchemaInSelect = sal_True ) const; // ------------------------------------------------ ::com::sun::star::sdb::SQLContext prependContextInfo( ::com::sun::star::sdbc::SQLException& _rException, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContext, const ::rtl::OUString& _rContextDescription, const ::rtl::OUString& _rContextDetails ) const; // ------------------------------------------------ ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource > getDataSource( const ::rtl::OUString& _rsRegisteredName, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory ) const; // ------------------------------------------------ /** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::INSERT @param _rxCursorSet the property set */ sal_Bool canInsert(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const; // ------------------------------------------------ /** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::UPDATE @param _rxCursorSet the property set */ sal_Bool canUpdate(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const; // ------------------------------------------------ /** check if the property "Privileges" supports ::com::sun::star::sdbcx::Privilege::DELETE @param _rxCursorSet the property set */ sal_Bool canDelete(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxCursorSet) const; // ------------------------------------------------ virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > getFieldsByCommandDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand, ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& _rxKeepFieldsAlive, ::dbtools::SQLExceptionInfo* _pErrorInfo = NULL ) SAL_THROW( ( ) ); // ------------------------------------------------ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > getFieldNamesByCommandDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand, ::dbtools::SQLExceptionInfo* _pErrorInfo = NULL ) SAL_THROW( ( ) ); // ------------------------------------------------ virtual sal_Bool isDataSourcePropertyEnabled(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& _xProp ,const ::rtl::OUString& _sProperty, sal_Bool _bDefault = sal_False) const; // ------------------------------------------------ bool isEmbeddedInDatabase( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxComponent, ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxActualConnection ); // ------------------------------------------------ bool isEmbeddedInDatabase( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxComponent ); }; //........................................................................ } // namespace svxform //........................................................................ #endif // SVX_DBTOOLSCLIENT_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: tbxdrctl.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2005-01-31 09:14:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <string> // HACK: prevent conflict between STLPORT and Workshop headers #include <tools/ref.hxx> #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _AEITEM_HXX #include <svtools/aeitem.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SFXVIEWSH_HXX #include <sfx2/viewsh.hxx> #endif #include <sfx2/imagemgr.hxx> #include <sfx2/viewfrm.hxx> #include <vcl/toolbox.hxx> #pragma hdrstop #include "dialmgr.hxx" #include "dialogs.hrc" #include "tbxctl.hxx" #include "tbxdraw.hxx" #include "tbxcolor.hxx" #include "tbxdraw.hrc" #ifndef _DRAFTS_COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_ #include <drafts/com/sun/star/frame/XLayoutManager.hpp> #endif SFX_IMPL_TOOLBOX_CONTROL(SvxTbxCtlDraw, SfxAllEnumItem); using namespace ::com::sun::star::uno; using namespace ::drafts::com::sun::star::frame; // ----------------------------------------------------------------------- SvxTbxCtlDraw::SvxTbxCtlDraw( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) : SfxToolBoxControl( nSlotId, nId, rTbx ), m_sToolboxName( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/drawbar" ) ) { rTbx.SetItemBits( nId, TIB_CHECKABLE | rTbx.GetItemBits( nId ) ); rTbx.Invalidate(); } // ----------------------------------------------------------------------- void SvxTbxCtlDraw::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { GetToolBox().EnableItem( GetId(), ( eState != SFX_ITEM_DISABLED ) ); SfxToolBoxControl::StateChanged( nSID, eState, pState ); Reference< XLayoutManager > xLayoutMgr = getLayoutManager(); if ( xLayoutMgr.is() ) GetToolBox().CheckItem( GetId(), xLayoutMgr->isElementVisible( m_sToolboxName ) != sal_False ); } // ----------------------------------------------------------------------- SfxPopupWindowType SvxTbxCtlDraw::GetPopupWindowType() const { return SFX_POPUPWINDOW_ONCLICK; } // ----------------------------------------------------------------------- void SvxTbxCtlDraw::toggleToolbox() { Reference< XLayoutManager > xLayoutMgr = getLayoutManager(); if ( xLayoutMgr.is() ) { BOOL bCheck = FALSE; if ( xLayoutMgr->isElementVisible( m_sToolboxName ) ) { xLayoutMgr->hideElement( m_sToolboxName ); xLayoutMgr->destroyElement( m_sToolboxName ); } else { bCheck = TRUE; xLayoutMgr->createElement( m_sToolboxName ); xLayoutMgr->showElement( m_sToolboxName ); } GetToolBox().CheckItem( GetId(), bCheck ); } } // ----------------------------------------------------------------------- void SvxTbxCtlDraw::Select( BOOL bMod1 ) { toggleToolbox(); } <commit_msg>INTEGRATION: CWS removedrafts (1.10.46); FILE MERGED 2005/02/17 14:08:05 cd 1.10.46.1: #i42557# Move UNOIDL types from drafts to com<commit_after>/************************************************************************* * * $RCSfile: tbxdrctl.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: kz $ $Date: 2005-03-01 19:11:49 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <string> // HACK: prevent conflict between STLPORT and Workshop headers #include <tools/ref.hxx> #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _AEITEM_HXX #include <svtools/aeitem.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SFXVIEWSH_HXX #include <sfx2/viewsh.hxx> #endif #include <sfx2/imagemgr.hxx> #include <sfx2/viewfrm.hxx> #include <vcl/toolbox.hxx> #pragma hdrstop #include "dialmgr.hxx" #include "dialogs.hrc" #include "tbxctl.hxx" #include "tbxdraw.hxx" #include "tbxcolor.hxx" #include "tbxdraw.hrc" #ifndef _COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_ #include <com/sun/star/frame/XLayoutManager.hpp> #endif SFX_IMPL_TOOLBOX_CONTROL(SvxTbxCtlDraw, SfxAllEnumItem); using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; // ----------------------------------------------------------------------- SvxTbxCtlDraw::SvxTbxCtlDraw( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) : SfxToolBoxControl( nSlotId, nId, rTbx ), m_sToolboxName( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/drawbar" ) ) { rTbx.SetItemBits( nId, TIB_CHECKABLE | rTbx.GetItemBits( nId ) ); rTbx.Invalidate(); } // ----------------------------------------------------------------------- void SvxTbxCtlDraw::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { GetToolBox().EnableItem( GetId(), ( eState != SFX_ITEM_DISABLED ) ); SfxToolBoxControl::StateChanged( nSID, eState, pState ); Reference< XLayoutManager > xLayoutMgr = getLayoutManager(); if ( xLayoutMgr.is() ) GetToolBox().CheckItem( GetId(), xLayoutMgr->isElementVisible( m_sToolboxName ) != sal_False ); } // ----------------------------------------------------------------------- SfxPopupWindowType SvxTbxCtlDraw::GetPopupWindowType() const { return SFX_POPUPWINDOW_ONCLICK; } // ----------------------------------------------------------------------- void SvxTbxCtlDraw::toggleToolbox() { Reference< XLayoutManager > xLayoutMgr = getLayoutManager(); if ( xLayoutMgr.is() ) { BOOL bCheck = FALSE; if ( xLayoutMgr->isElementVisible( m_sToolboxName ) ) { xLayoutMgr->hideElement( m_sToolboxName ); xLayoutMgr->destroyElement( m_sToolboxName ); } else { bCheck = TRUE; xLayoutMgr->createElement( m_sToolboxName ); xLayoutMgr->showElement( m_sToolboxName ); } GetToolBox().CheckItem( GetId(), bCheck ); } } // ----------------------------------------------------------------------- void SvxTbxCtlDraw::Select( BOOL bMod1 ) { toggleToolbox(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: txtcache.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2003-04-17 14:29:57 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include "errhdl.hxx" #include "segmentc.hxx" #include "txtcache.hxx" #include "txtfrm.hxx" #include "porlay.hxx" /************************************************************************* |* |* SwTxtLine::SwTxtLine(), ~SwTxtLine() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 16. Mar. 94 |* |*************************************************************************/ SwTxtLine::SwTxtLine( SwTxtFrm *pFrm, SwParaPortion *pNew ) : SwCacheObj( (void*)pFrm ), pLine( pNew ) { } SwTxtLine::~SwTxtLine() { delete pLine; } /************************************************************************* |* |* SwTxtLineAccess::NewObj() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 16. Mar. 94 |* |*************************************************************************/ SwCacheObj *SwTxtLineAccess::NewObj() { return new SwTxtLine( (SwTxtFrm*)pOwner ); } /************************************************************************* |* |* SwTxtLineAccess::GetPara() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 16. Mar. 94 |* |*************************************************************************/ SwParaPortion *SwTxtLineAccess::GetPara() { SwTxtLine *pRet; if ( pObj ) pRet = (SwTxtLine*)pObj; else { pRet = (SwTxtLine*)Get(); ((SwTxtFrm*)pOwner)->SetCacheIdx( pRet->GetCachePos() ); } if ( !pRet->GetPara() ) pRet->SetPara( new SwParaPortion ); return pRet->GetPara(); } /************************************************************************* |* |* SwTxtLineAccess::SwTxtLineAccess() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 16. Mar. 94 |* |*************************************************************************/ SwTxtLineAccess::SwTxtLineAccess( const SwTxtFrm *pOwner ) : SwCacheAccess( *SwTxtFrm::GetTxtCache(), pOwner, pOwner->GetCacheIdx() ) { } /************************************************************************* |* |* SwTxtLineAccess::IsAvailable |* |* Ersterstellung MA 23. Mar. 94 |* Letzte Aenderung MA 23. Mar. 94 |* |*************************************************************************/ sal_Bool SwTxtLineAccess::IsAvailable() const { if ( pObj ) return ((SwTxtLine*)pObj)->GetPara() != 0; return sal_False; } /************************************************************************* |* |* SwTxtFrm::HasPara() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 22. Aug. 94 |* |*************************************************************************/ sal_Bool SwTxtFrm::_HasPara() const { SwTxtLine *pTxtLine = (SwTxtLine*)SwTxtFrm::GetTxtCache()-> Get( this, GetCacheIdx(), sal_False ); if ( pTxtLine ) { if ( pTxtLine->GetPara() ) return sal_True; } else ((SwTxtFrm*)this)->nCacheIdx = MSHRT_MAX; return sal_False; } /************************************************************************* |* |* SwTxtFrm::GetPara() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 22. Aug. 94 |* |*************************************************************************/ SwParaPortion *SwTxtFrm::GetPara() { if ( GetCacheIdx() != MSHRT_MAX ) { SwTxtLine *pLine = (SwTxtLine*)SwTxtFrm::GetTxtCache()-> Get( this, GetCacheIdx(), sal_False ); if ( pLine ) return pLine->GetPara(); else nCacheIdx = MSHRT_MAX; } return 0; } /************************************************************************* |* |* SwTxtFrm::ClearPara() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 22. Aug. 94 |* |*************************************************************************/ void SwTxtFrm::ClearPara() { ASSERT( !IsLocked(), "+SwTxtFrm::ClearPara: this is locked." ); if ( !IsLocked() && GetCacheIdx() != MSHRT_MAX ) { SwTxtLine *pTxtLine = (SwTxtLine*)SwTxtFrm::GetTxtCache()-> Get( this, GetCacheIdx(), sal_False ); if ( pTxtLine ) { delete pTxtLine->GetPara(); pTxtLine->SetPara( 0 ); } else nCacheIdx = MSHRT_MAX; } } /************************************************************************* |* |* SwTxtFrm::SetPara() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 22. Aug. 94 |* |*************************************************************************/ void SwTxtFrm::SetPara( SwParaPortion *pNew, sal_Bool bDelete ) { if ( GetCacheIdx() != MSHRT_MAX ) { //Nur die Information Auswechseln, das CacheObj bleibt stehen. SwTxtLine *pTxtLine = (SwTxtLine*)SwTxtFrm::GetTxtCache()-> Get( this, GetCacheIdx(), sal_False ); if ( pTxtLine ) { if( bDelete ) delete pTxtLine->GetPara(); pTxtLine->SetPara( pNew ); } else { ASSERT( !pNew, "+SetPara: Losing SwParaPortion" ); nCacheIdx = MSHRT_MAX; } } else if ( pNew ) { //Einen neuen einfuegen. SwTxtLine *pTxtLine = new SwTxtLine( this, pNew ); if ( SwTxtFrm::GetTxtCache()->Insert( pTxtLine ) ) nCacheIdx = pTxtLine->GetCachePos(); else { ASSERT( sal_False, "+SetPara: InsertCache failed." ); } } } <commit_msg>INTEGRATION: CWS qdiet01 (1.4.236); FILE MERGED 2003/10/09 14:48:11 mh 1.4.236.1: del: unused file, #i18390#<commit_after>/************************************************************************* * * $RCSfile: txtcache.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2003-10-20 16:51:12 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include "errhdl.hxx" #include "txtcache.hxx" #include "txtfrm.hxx" #include "porlay.hxx" /************************************************************************* |* |* SwTxtLine::SwTxtLine(), ~SwTxtLine() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 16. Mar. 94 |* |*************************************************************************/ SwTxtLine::SwTxtLine( SwTxtFrm *pFrm, SwParaPortion *pNew ) : SwCacheObj( (void*)pFrm ), pLine( pNew ) { } SwTxtLine::~SwTxtLine() { delete pLine; } /************************************************************************* |* |* SwTxtLineAccess::NewObj() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 16. Mar. 94 |* |*************************************************************************/ SwCacheObj *SwTxtLineAccess::NewObj() { return new SwTxtLine( (SwTxtFrm*)pOwner ); } /************************************************************************* |* |* SwTxtLineAccess::GetPara() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 16. Mar. 94 |* |*************************************************************************/ SwParaPortion *SwTxtLineAccess::GetPara() { SwTxtLine *pRet; if ( pObj ) pRet = (SwTxtLine*)pObj; else { pRet = (SwTxtLine*)Get(); ((SwTxtFrm*)pOwner)->SetCacheIdx( pRet->GetCachePos() ); } if ( !pRet->GetPara() ) pRet->SetPara( new SwParaPortion ); return pRet->GetPara(); } /************************************************************************* |* |* SwTxtLineAccess::SwTxtLineAccess() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 16. Mar. 94 |* |*************************************************************************/ SwTxtLineAccess::SwTxtLineAccess( const SwTxtFrm *pOwner ) : SwCacheAccess( *SwTxtFrm::GetTxtCache(), pOwner, pOwner->GetCacheIdx() ) { } /************************************************************************* |* |* SwTxtLineAccess::IsAvailable |* |* Ersterstellung MA 23. Mar. 94 |* Letzte Aenderung MA 23. Mar. 94 |* |*************************************************************************/ sal_Bool SwTxtLineAccess::IsAvailable() const { if ( pObj ) return ((SwTxtLine*)pObj)->GetPara() != 0; return sal_False; } /************************************************************************* |* |* SwTxtFrm::HasPara() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 22. Aug. 94 |* |*************************************************************************/ sal_Bool SwTxtFrm::_HasPara() const { SwTxtLine *pTxtLine = (SwTxtLine*)SwTxtFrm::GetTxtCache()-> Get( this, GetCacheIdx(), sal_False ); if ( pTxtLine ) { if ( pTxtLine->GetPara() ) return sal_True; } else ((SwTxtFrm*)this)->nCacheIdx = MSHRT_MAX; return sal_False; } /************************************************************************* |* |* SwTxtFrm::GetPara() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 22. Aug. 94 |* |*************************************************************************/ SwParaPortion *SwTxtFrm::GetPara() { if ( GetCacheIdx() != MSHRT_MAX ) { SwTxtLine *pLine = (SwTxtLine*)SwTxtFrm::GetTxtCache()-> Get( this, GetCacheIdx(), sal_False ); if ( pLine ) return pLine->GetPara(); else nCacheIdx = MSHRT_MAX; } return 0; } /************************************************************************* |* |* SwTxtFrm::ClearPara() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 22. Aug. 94 |* |*************************************************************************/ void SwTxtFrm::ClearPara() { ASSERT( !IsLocked(), "+SwTxtFrm::ClearPara: this is locked." ); if ( !IsLocked() && GetCacheIdx() != MSHRT_MAX ) { SwTxtLine *pTxtLine = (SwTxtLine*)SwTxtFrm::GetTxtCache()-> Get( this, GetCacheIdx(), sal_False ); if ( pTxtLine ) { delete pTxtLine->GetPara(); pTxtLine->SetPara( 0 ); } else nCacheIdx = MSHRT_MAX; } } /************************************************************************* |* |* SwTxtFrm::SetPara() |* |* Ersterstellung MA 16. Mar. 94 |* Letzte Aenderung MA 22. Aug. 94 |* |*************************************************************************/ void SwTxtFrm::SetPara( SwParaPortion *pNew, sal_Bool bDelete ) { if ( GetCacheIdx() != MSHRT_MAX ) { //Nur die Information Auswechseln, das CacheObj bleibt stehen. SwTxtLine *pTxtLine = (SwTxtLine*)SwTxtFrm::GetTxtCache()-> Get( this, GetCacheIdx(), sal_False ); if ( pTxtLine ) { if( bDelete ) delete pTxtLine->GetPara(); pTxtLine->SetPara( pNew ); } else { ASSERT( !pNew, "+SetPara: Losing SwParaPortion" ); nCacheIdx = MSHRT_MAX; } } else if ( pNew ) { //Einen neuen einfuegen. SwTxtLine *pTxtLine = new SwTxtLine( this, pNew ); if ( SwTxtFrm::GetTxtCache()->Insert( pTxtLine ) ) nCacheIdx = pTxtLine->GetCachePos(); else { ASSERT( sal_False, "+SetPara: InsertCache failed." ); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: labelcfg.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2005-09-09 07:28:13 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _LABELCFG_HXX #include <labelcfg.hxx> #endif #ifndef _LABIMP_HXX #include <labimp.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef UNOTOOLS_CONFIGPATHES_HXX_INCLUDED #include <unotools/configpathes.hxx> #endif using namespace utl; using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::beans; #define C2U(cChar) OUString::createFromAscii(cChar) /* -----------------------------15.01.01 11:17-------------------------------- ---------------------------------------------------------------------------*/ SwLabelConfig::SwLabelConfig() : ConfigItem(C2U("Office.Labels/Manufacturer")) { aNodeNames = GetNodeNames(OUString()); } /* -----------------------------06.09.00 16:50-------------------------------- ---------------------------------------------------------------------------*/ SwLabelConfig::~SwLabelConfig() { } /* -----------------------------06.09.00 16:43-------------------------------- ---------------------------------------------------------------------------*/ void SwLabelConfig::Commit() { // the config item is not writable yet } /* -----------------------------15.01.01 11:42-------------------------------- ---------------------------------------------------------------------------*/ Sequence<OUString> lcl_CreatePropertyNames(const OUString& rPrefix) { Sequence<OUString> aProperties(2); OUString* pProperties = aProperties.getArray(); for(sal_Int32 nProp = 0; nProp < 2; nProp++) pProperties[nProp] = rPrefix; pProperties[ 0] += C2U("Name"); pProperties[ 1] += C2U("Measure"); return aProperties; } //----------------------------------------------------------------------------- SwLabRec* lcl_CreateSwLabRec(Sequence<Any>& rValues, const OUString& rManufacturer) { SwLabRec* pNewRec = new SwLabRec; const Any* pValues = rValues.getConstArray(); OUString sTmp; pNewRec->aMake = rManufacturer; for(sal_Int32 nProp = 0; nProp < rValues.getLength(); nProp++) { if(pValues[nProp].hasValue()) { switch(nProp) { case 0: pValues[nProp] >>= sTmp; pNewRec->aType = sTmp; break; case 1: { //all values are contained as colon-separated 1/100 mm values except for the //continuous flag ('C'/'S') pValues[nProp] >>= sTmp; String sMeasure(sTmp); USHORT nTokenCount = sMeasure.GetTokenCount(';'); xub_StrLen nIdx = 0; for(USHORT i = 0; i < nTokenCount; i++) { String sToken(sMeasure.GetToken(i, ';' )); int nVal = sToken.ToInt32(); switch(i) { case 0 : pNewRec->bCont = sToken.GetChar(0) == 'C'; break; case 1 : pNewRec->lHDist = MM100_TO_TWIP(nVal);break; case 2 : pNewRec->lVDist = MM100_TO_TWIP(nVal);break; case 3 : pNewRec->lWidth = MM100_TO_TWIP(nVal);break; case 4 : pNewRec->lHeight = MM100_TO_TWIP(nVal); break; case 5 : pNewRec->lLeft = MM100_TO_TWIP(nVal);break; case 6 : pNewRec->lUpper = MM100_TO_TWIP(nVal);break; case 7 : pNewRec->nCols = nVal; break; case 8 : pNewRec->nRows = nVal; break; } } } break; } } } return pNewRec; } //----------------------------------------------------------------------------- Sequence<PropertyValue> lcl_CreateProperties( Sequence<OUString>& rPropNames, const SwLabRec& rRec) { const OUString* pNames = rPropNames.getConstArray(); Sequence<PropertyValue> aRet(rPropNames.getLength()); PropertyValue* pValues = aRet.getArray(); OUString sColon(C2U(";")); for(sal_Int32 nProp = 0; nProp < rPropNames.getLength(); nProp++) { pValues[nProp].Name = pNames[nProp]; switch(nProp) { case 0: pValues[nProp].Value <<= OUString(rRec.aType); break; case 1: { OUString sTmp; sTmp += C2U( rRec.bCont ? "C" : "S"); sTmp += sColon; sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lHDist) ); sTmp += sColon; sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lVDist)); sTmp += sColon; sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lWidth) ); sTmp += sColon; sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lHeight) ); sTmp += sColon; sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lLeft) ); sTmp += sColon; sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lUpper) ); sTmp += sColon; sTmp += OUString::valueOf(rRec.nCols );sTmp += sColon; sTmp += OUString::valueOf(rRec.nRows ); pValues[nProp].Value <<= sTmp; } break; } } return aRet; } //----------------------------------------------------------------------------- void SwLabelConfig::FillLabels(const OUString& rManufacturer, SwLabRecs& rLabArr) { OUString sManufacturer(wrapConfigurationElementName(rManufacturer)); const Sequence<OUString> aLabels = GetNodeNames(sManufacturer); const OUString* pLabels = aLabels.getConstArray(); for(sal_Int32 nLabel = 0; nLabel < aLabels.getLength(); nLabel++) { OUString sPrefix(sManufacturer); sPrefix += C2U("/"); sPrefix += pLabels[nLabel]; sPrefix += C2U("/"); Sequence<OUString> aPropNames = lcl_CreatePropertyNames(sPrefix); Sequence<Any> aValues = GetProperties(aPropNames); SwLabRec* pNewRec = lcl_CreateSwLabRec(aValues, rManufacturer); rLabArr.C40_INSERT( SwLabRec, pNewRec, rLabArr.Count() ); } } /* -----------------------------23.01.01 11:36-------------------------------- ---------------------------------------------------------------------------*/ sal_Bool SwLabelConfig::HasLabel(const rtl::OUString& rManufacturer, const rtl::OUString& rType) { const OUString* pNode = aNodeNames.getConstArray(); sal_Bool bFound = sal_False; for(sal_Int32 nNode = 0; nNode < aNodeNames.getLength() && !bFound; nNode++) { if(pNode[nNode] == rManufacturer) bFound = sal_True; } if(bFound) { OUString sManufacturer(wrapConfigurationElementName(rManufacturer)); const Sequence<OUString> aLabels = GetNodeNames(sManufacturer); const OUString* pLabels = aLabels.getConstArray(); for(sal_Int32 nLabel = 0; nLabel < aLabels.getLength(); nLabel++) { OUString sPrefix(sManufacturer); sPrefix += C2U("/"); sPrefix += pLabels[nLabel]; sPrefix += C2U("/"); Sequence<OUString> aProperties(1); aProperties.getArray()[0] = sPrefix; aProperties.getArray()[0] += C2U("Name"); Sequence<Any> aValues = GetProperties(aProperties); const Any* pValues = aValues.getConstArray(); if(pValues[0].hasValue()) { OUString sTmp; pValues[0] >>= sTmp; if(rType == sTmp) return sal_True; } } } return sal_False; } /* -----------------------------23.01.01 11:36-------------------------------- ---------------------------------------------------------------------------*/ sal_Bool lcl_Exists(const OUString& rNode, const Sequence<OUString>& rLabels) { const OUString* pLabels = rLabels.getConstArray(); for(sal_Int32 i = 0; i < rLabels.getLength(); i++) if(pLabels[i] == rNode) return sal_True; return sal_False; } //----------------------------------------------------------------------------- void SwLabelConfig::SaveLabel( const rtl::OUString& rManufacturer, const rtl::OUString& rType, const SwLabRec& rRec) { const OUString* pNode = aNodeNames.getConstArray(); sal_Bool bFound = sal_False; for(sal_Int32 nNode = 0; nNode < aNodeNames.getLength() && !bFound; nNode++) { if(pNode[nNode] == rManufacturer) bFound = sal_True; } if(!bFound) { if(!AddNode(OUString(), rManufacturer)) { DBG_ERROR("New configuration node could not be created") return ; } else { aNodeNames = GetNodeNames(OUString()); } } OUString sManufacturer(wrapConfigurationElementName(rManufacturer)); const Sequence<OUString> aLabels = GetNodeNames(sManufacturer); const OUString* pLabels = aLabels.getConstArray(); OUString sFoundNode; for(sal_Int32 nLabel = 0; nLabel < aLabels.getLength(); nLabel++) { OUString sPrefix(sManufacturer); sPrefix += C2U("/"); sPrefix += pLabels[nLabel]; sPrefix += C2U("/"); Sequence<OUString> aProperties(1); aProperties.getArray()[0] = sPrefix; aProperties.getArray()[0] += C2U("Name"); Sequence<Any> aValues = GetProperties(aProperties); const Any* pValues = aValues.getConstArray(); if(pValues[0].hasValue()) { OUString sTmp; pValues[0] >>= sTmp; if(rType == sTmp) { sFoundNode = pLabels[nLabel]; break; } } } // if not found - generate a unique node name if(!sFoundNode.getLength()) { sal_Int32 nIndex = aLabels.getLength(); OUString sPrefix(C2U("Label")); sFoundNode = sPrefix; sFoundNode += OUString::valueOf(nIndex); while(lcl_Exists(sFoundNode, aLabels)) { sFoundNode = sPrefix; sFoundNode += OUString::valueOf(nIndex++); } } OUString sPrefix(wrapConfigurationElementName(rManufacturer)); sPrefix += C2U("/"); sPrefix += sFoundNode; sPrefix += C2U("/"); Sequence<OUString> aPropNames = lcl_CreatePropertyNames(sPrefix); Sequence<PropertyValue> aPropValues = lcl_CreateProperties(aPropNames, rRec); SetSetProperties(wrapConfigurationElementName(rManufacturer), aPropValues); } <commit_msg>INTEGRATION: CWS writercorehandoff (1.9.1116); FILE MERGED 2005/09/13 16:50:20 tra 1.9.1116.3: RESYNC: (1.9-1.10); FILE MERGED 2005/06/07 14:15:34 fme 1.9.1116.2: #i50348# General cleanup - removed unused header files, functions, members, declarations etc. 2005/06/06 09:29:34 tra 1.9.1116.1: Unnecessary includes removed #i50348#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: labelcfg.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: hr $ $Date: 2006-08-14 17:35:38 $ * * 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 * ************************************************************************/ #pragma hdrstop #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _LABELCFG_HXX #include <labelcfg.hxx> #endif #ifndef _LABIMP_HXX #include <labimp.hxx> #endif #ifndef UNOTOOLS_CONFIGPATHES_HXX_INCLUDED #include <unotools/configpathes.hxx> #endif using namespace utl; using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::beans; #define C2U(cChar) OUString::createFromAscii(cChar) /* -----------------------------15.01.01 11:17-------------------------------- ---------------------------------------------------------------------------*/ SwLabelConfig::SwLabelConfig() : ConfigItem(C2U("Office.Labels/Manufacturer")) { aNodeNames = GetNodeNames(OUString()); } /* -----------------------------06.09.00 16:50-------------------------------- ---------------------------------------------------------------------------*/ SwLabelConfig::~SwLabelConfig() { } /* -----------------------------06.09.00 16:43-------------------------------- ---------------------------------------------------------------------------*/ void SwLabelConfig::Commit() { // the config item is not writable yet } /* -----------------------------15.01.01 11:42-------------------------------- ---------------------------------------------------------------------------*/ Sequence<OUString> lcl_CreatePropertyNames(const OUString& rPrefix) { Sequence<OUString> aProperties(2); OUString* pProperties = aProperties.getArray(); for(sal_Int32 nProp = 0; nProp < 2; nProp++) pProperties[nProp] = rPrefix; pProperties[ 0] += C2U("Name"); pProperties[ 1] += C2U("Measure"); return aProperties; } //----------------------------------------------------------------------------- SwLabRec* lcl_CreateSwLabRec(Sequence<Any>& rValues, const OUString& rManufacturer) { SwLabRec* pNewRec = new SwLabRec; const Any* pValues = rValues.getConstArray(); OUString sTmp; pNewRec->aMake = rManufacturer; for(sal_Int32 nProp = 0; nProp < rValues.getLength(); nProp++) { if(pValues[nProp].hasValue()) { switch(nProp) { case 0: pValues[nProp] >>= sTmp; pNewRec->aType = sTmp; break; case 1: { //all values are contained as colon-separated 1/100 mm values except for the //continuous flag ('C'/'S') pValues[nProp] >>= sTmp; String sMeasure(sTmp); USHORT nTokenCount = sMeasure.GetTokenCount(';'); xub_StrLen nIdx = 0; for(USHORT i = 0; i < nTokenCount; i++) { String sToken(sMeasure.GetToken(i, ';' )); int nVal = sToken.ToInt32(); switch(i) { case 0 : pNewRec->bCont = sToken.GetChar(0) == 'C'; break; case 1 : pNewRec->lHDist = MM100_TO_TWIP(nVal);break; case 2 : pNewRec->lVDist = MM100_TO_TWIP(nVal);break; case 3 : pNewRec->lWidth = MM100_TO_TWIP(nVal);break; case 4 : pNewRec->lHeight = MM100_TO_TWIP(nVal); break; case 5 : pNewRec->lLeft = MM100_TO_TWIP(nVal);break; case 6 : pNewRec->lUpper = MM100_TO_TWIP(nVal);break; case 7 : pNewRec->nCols = nVal; break; case 8 : pNewRec->nRows = nVal; break; } } } break; } } } return pNewRec; } //----------------------------------------------------------------------------- Sequence<PropertyValue> lcl_CreateProperties( Sequence<OUString>& rPropNames, const SwLabRec& rRec) { const OUString* pNames = rPropNames.getConstArray(); Sequence<PropertyValue> aRet(rPropNames.getLength()); PropertyValue* pValues = aRet.getArray(); OUString sColon(C2U(";")); for(sal_Int32 nProp = 0; nProp < rPropNames.getLength(); nProp++) { pValues[nProp].Name = pNames[nProp]; switch(nProp) { case 0: pValues[nProp].Value <<= OUString(rRec.aType); break; case 1: { OUString sTmp; sTmp += C2U( rRec.bCont ? "C" : "S"); sTmp += sColon; sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lHDist) ); sTmp += sColon; sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lVDist)); sTmp += sColon; sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lWidth) ); sTmp += sColon; sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lHeight) ); sTmp += sColon; sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lLeft) ); sTmp += sColon; sTmp += OUString::valueOf(TWIP_TO_MM100(rRec.lUpper) ); sTmp += sColon; sTmp += OUString::valueOf(rRec.nCols );sTmp += sColon; sTmp += OUString::valueOf(rRec.nRows ); pValues[nProp].Value <<= sTmp; } break; } } return aRet; } //----------------------------------------------------------------------------- void SwLabelConfig::FillLabels(const OUString& rManufacturer, SwLabRecs& rLabArr) { OUString sManufacturer(wrapConfigurationElementName(rManufacturer)); const Sequence<OUString> aLabels = GetNodeNames(sManufacturer); const OUString* pLabels = aLabels.getConstArray(); for(sal_Int32 nLabel = 0; nLabel < aLabels.getLength(); nLabel++) { OUString sPrefix(sManufacturer); sPrefix += C2U("/"); sPrefix += pLabels[nLabel]; sPrefix += C2U("/"); Sequence<OUString> aPropNames = lcl_CreatePropertyNames(sPrefix); Sequence<Any> aValues = GetProperties(aPropNames); SwLabRec* pNewRec = lcl_CreateSwLabRec(aValues, rManufacturer); rLabArr.C40_INSERT( SwLabRec, pNewRec, rLabArr.Count() ); } } /* -----------------------------23.01.01 11:36-------------------------------- ---------------------------------------------------------------------------*/ sal_Bool SwLabelConfig::HasLabel(const rtl::OUString& rManufacturer, const rtl::OUString& rType) { const OUString* pNode = aNodeNames.getConstArray(); sal_Bool bFound = sal_False; for(sal_Int32 nNode = 0; nNode < aNodeNames.getLength() && !bFound; nNode++) { if(pNode[nNode] == rManufacturer) bFound = sal_True; } if(bFound) { OUString sManufacturer(wrapConfigurationElementName(rManufacturer)); const Sequence<OUString> aLabels = GetNodeNames(sManufacturer); const OUString* pLabels = aLabels.getConstArray(); for(sal_Int32 nLabel = 0; nLabel < aLabels.getLength(); nLabel++) { OUString sPrefix(sManufacturer); sPrefix += C2U("/"); sPrefix += pLabels[nLabel]; sPrefix += C2U("/"); Sequence<OUString> aProperties(1); aProperties.getArray()[0] = sPrefix; aProperties.getArray()[0] += C2U("Name"); Sequence<Any> aValues = GetProperties(aProperties); const Any* pValues = aValues.getConstArray(); if(pValues[0].hasValue()) { OUString sTmp; pValues[0] >>= sTmp; if(rType == sTmp) return sal_True; } } } return sal_False; } /* -----------------------------23.01.01 11:36-------------------------------- ---------------------------------------------------------------------------*/ sal_Bool lcl_Exists(const OUString& rNode, const Sequence<OUString>& rLabels) { const OUString* pLabels = rLabels.getConstArray(); for(sal_Int32 i = 0; i < rLabels.getLength(); i++) if(pLabels[i] == rNode) return sal_True; return sal_False; } //----------------------------------------------------------------------------- void SwLabelConfig::SaveLabel( const rtl::OUString& rManufacturer, const rtl::OUString& rType, const SwLabRec& rRec) { const OUString* pNode = aNodeNames.getConstArray(); sal_Bool bFound = sal_False; for(sal_Int32 nNode = 0; nNode < aNodeNames.getLength() && !bFound; nNode++) { if(pNode[nNode] == rManufacturer) bFound = sal_True; } if(!bFound) { if(!AddNode(OUString(), rManufacturer)) { DBG_ERROR("New configuration node could not be created") return ; } else { aNodeNames = GetNodeNames(OUString()); } } OUString sManufacturer(wrapConfigurationElementName(rManufacturer)); const Sequence<OUString> aLabels = GetNodeNames(sManufacturer); const OUString* pLabels = aLabels.getConstArray(); OUString sFoundNode; for(sal_Int32 nLabel = 0; nLabel < aLabels.getLength(); nLabel++) { OUString sPrefix(sManufacturer); sPrefix += C2U("/"); sPrefix += pLabels[nLabel]; sPrefix += C2U("/"); Sequence<OUString> aProperties(1); aProperties.getArray()[0] = sPrefix; aProperties.getArray()[0] += C2U("Name"); Sequence<Any> aValues = GetProperties(aProperties); const Any* pValues = aValues.getConstArray(); if(pValues[0].hasValue()) { OUString sTmp; pValues[0] >>= sTmp; if(rType == sTmp) { sFoundNode = pLabels[nLabel]; break; } } } // if not found - generate a unique node name if(!sFoundNode.getLength()) { sal_Int32 nIndex = aLabels.getLength(); OUString sPrefix(C2U("Label")); sFoundNode = sPrefix; sFoundNode += OUString::valueOf(nIndex); while(lcl_Exists(sFoundNode, aLabels)) { sFoundNode = sPrefix; sFoundNode += OUString::valueOf(nIndex++); } } OUString sPrefix(wrapConfigurationElementName(rManufacturer)); sPrefix += C2U("/"); sPrefix += sFoundNode; sPrefix += C2U("/"); Sequence<OUString> aPropNames = lcl_CreatePropertyNames(sPrefix); Sequence<PropertyValue> aPropValues = lcl_CreateProperties(aPropNames, rRec); SetSetProperties(wrapConfigurationElementName(rManufacturer), aPropValues); } <|endoftext|>
<commit_before>#include <cstdio> #include <algorithm> using namespace std; const int NMAX = 100000, PASI_INFINITI = NMAX*2; int v[NMAX], nVector, sizeOfCheat; int back(int pozitieCurenta, int cheatsAvailable) { if (pozitieCurenta > nVector) return PASI_INFINITI; if (pozitieCurenta == nVector) return 0; int sol = min(back(pozitieCurenta+1, cheatsAvailable) + 1, back(pozitieCurenta+v[pozitieCurenta], cheatsAvailable) + 1); if (cheatsAvailable) sol = min(sol, back(pozitieCurenta+sizeOfCheat, cheatsAvailable-1) + 1); return sol; } int main() { freopen("teleport.in", "r", stdin); freopen("teleport.out", "w", stdout); int nCheats; scanf("%d%d%d", &nVector, &nCheats, &sizeOfCheat); for(int i=0; i<nVector; i++) scanf("%d", &v[i]); printf("%d\n", back(0, nCheats)); return 0; } <commit_msg>Add comments in the source code<commit_after>// @palcu // InfoOltenia 2015, teleport, backtracking #include <cstdio> #include <algorithm> using namespace std; const int NMAX = 100000, PASI_INFINITI = NMAX*2; int v[NMAX], nVector, sizeOfCheat; int back(int pozitieCurenta, int cheatsAvailable) { if (pozitieCurenta > nVector) return PASI_INFINITI; if (pozitieCurenta == nVector) return 0; int sol = min(back(pozitieCurenta+1, cheatsAvailable) + 1, back(pozitieCurenta+v[pozitieCurenta], cheatsAvailable) + 1); if (cheatsAvailable) sol = min(sol, back(pozitieCurenta+sizeOfCheat, cheatsAvailable-1) + 1); return sol; } int main() { freopen("teleport.in", "r", stdin); freopen("teleport.out", "w", stdout); int nCheats; scanf("%d%d%d", &nVector, &nCheats, &sizeOfCheat); for(int i=0; i<nVector; i++) scanf("%d", &v[i]); printf("%d\n", back(0, nCheats)); return 0; } <|endoftext|>
<commit_before>// RUN: %clang_cc1 -analyze -analyzer-experimental-internal-checks -analyzer-check-objc-mem -analyzer-experimental-checks -verify %s struct X0 { }; bool operator==(const X0&, const X0&); // PR7287 struct test { int a[2]; }; void t2() { test p = {{1,2}}; test q; q = p; } bool PR7287(X0 a, X0 b) { return a == b; } <commit_msg>Make my test case test what it meant to<commit_after>// RUN: %clang_cc1 -analyze -analyzer-experimental-internal-checks -analyzer-check-objc-mem -analyzer-experimental-checks -verify %s struct X0 { }; bool operator==(const X0&, const X0&); // PR7287 struct test { int a[2]; }; void t2() { test p = {{1,2}}; test q; q = p; } bool PR7287(X0 a, X0 b) { return operator==(a, b); } <|endoftext|>
<commit_before>/* * Copyright 2016 Nu-book Inc. * Copyright 2017 Axel Waggershauser * * 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 "ByteArray.h" #include "BlackboxTestRunner.h" #include "ImageLoader.h" #include "MultiFormatReader.h" #include "Result.h" #include "BinaryBitmap.h" #include "ImageLoader.h" #include "DecodeHints.h" #include "TextUtfEncoding.h" #include "ZXContainerAlgorithms.h" #include "ZXFilesystem.h" #include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #include <set> using namespace ZXing; using namespace ZXing::Test; int main(int argc, char** argv) { if (argc <= 1) { std::cout << "Usage: " << argv[0] << " <test_path_prefix>" << std::endl; return 0; } fs::path pathPrefix = argv[1]; if (Contains({".png", ".jpg", ".pgm", ".gif"}, pathPrefix.extension())) { auto hints = DecodeHints().setTryHarder(true).setTryRotate(true).setIsPure(getenv("IS_PURE")); // hints.setFormats(BarcodeFormat::QR_CODE); MultiFormatReader reader(hints); int rotation = getenv("ROTATION") ? atoi(getenv("ROTATION")) : 0; for (int i = 1; i < argc; ++i) { Result result = reader.read(*ImageLoader::load(argv[i]).rotated(rotation)); std::cout << argv[i] << ": "; if (result.isValid()) std::cout << ToString(result.format()) << ": " << TextUtfEncoding::ToUtf8(result.text()) << " " << metadataToUtf8(result) << "\n"; else std::cout << "FAILED\n"; if (result.isValid() && getenv("WRITE_TEXT")) { std::ofstream f(fs::path(argv[i]).replace_extension(".txt")); f << TextUtfEncoding::ToUtf8(result.text()); } } return 0; } else { std::set<std::string> includedTests; for (int i = 2; i < argc; ++i) { if (std::strlen(argv[i]) > 2 && argv[i][0] == '-' && argv[i][1] == 't') { includedTests.insert(argv[i] + 2); } } return runBlackBoxTests(pathPrefix, includedTests); } } <commit_msg>TestReader: properly read value of IS_PURE environment variable<commit_after>/* * Copyright 2016 Nu-book Inc. * Copyright 2017 Axel Waggershauser * * 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 "ByteArray.h" #include "BlackboxTestRunner.h" #include "ImageLoader.h" #include "MultiFormatReader.h" #include "Result.h" #include "BinaryBitmap.h" #include "ImageLoader.h" #include "DecodeHints.h" #include "TextUtfEncoding.h" #include "ZXContainerAlgorithms.h" #include "ZXFilesystem.h" #include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #include <set> using namespace ZXing; using namespace ZXing::Test; int getEnv(const char* name, int fallback = 0) { auto var = getenv(name); return var ? atoi(var) : fallback; } int main(int argc, char** argv) { if (argc <= 1) { std::cout << "Usage: " << argv[0] << " <test_path_prefix>" << std::endl; return 0; } fs::path pathPrefix = argv[1]; if (Contains({".png", ".jpg", ".pgm", ".gif"}, pathPrefix.extension())) { auto hints = DecodeHints().setTryHarder(true).setTryRotate(true).setIsPure(getEnv("IS_PURE")); // hints.setFormats(BarcodeFormat::QR_CODE); MultiFormatReader reader(hints); int rotation = getEnv("ROTATION"); for (int i = 1; i < argc; ++i) { Result result = reader.read(*ImageLoader::load(argv[i]).rotated(rotation)); std::cout << argv[i] << ": "; if (result.isValid()) std::cout << ToString(result.format()) << ": " << TextUtfEncoding::ToUtf8(result.text()) << " " << metadataToUtf8(result) << "\n"; else std::cout << "FAILED\n"; if (result.isValid() && getenv("WRITE_TEXT")) { std::ofstream f(fs::path(argv[i]).replace_extension(".txt")); f << TextUtfEncoding::ToUtf8(result.text()); } } return 0; } else { std::set<std::string> includedTests; for (int i = 2; i < argc; ++i) { if (std::strlen(argv[i]) > 2 && argv[i][0] == '-' && argv[i][1] == 't') { includedTests.insert(argv[i] + 2); } } return runBlackBoxTests(pathPrefix, includedTests); } } <|endoftext|>
<commit_before>#include <cagey/math/Constants.hh> #include <gtest/gtest.h> #include <cstdint> using namespace cagey::math; template <typename T> class ConstantTestFixture : public ::testing::Test { }; TYPED_TEST_CASE_P(ConstantTestFixture); TYPED_TEST_P(ConstantTestFixture, ChecksPiValue) { EXPECT_EQ(TypeParam(3.141592653589793238462643383279502884), constants::pi<TypeParam>); } TYPED_TEST_P(ConstantTestFixture, ChecksDegToRadValue) { EXPECT_EQ(constants::degToRad<TypeParam>, constants::pi<TypeParam> / TypeParam(180.0f)); } TYPED_TEST_P(ConstantTestFixture, ChecksRadToDegValue) { EXPECT_EQ(constants::radToDeg<TypeParam>, TypeParam(180.0f) / constants::pi<TypeParam> ); } REGISTER_TYPED_TEST_CASE_P(ConstantTestFixture, ChecksPiValue, ChecksDegToRadValue, ChecksRadToDegValue); typedef ::testing::Types<int, float, double> SupportedTypes; INSTANTIATE_TYPED_TEST_CASE_P(Cagey, ConstantTestFixture, SupportedTypes); //TEST(Vector, Pi) { // EXPECT_EQ(3, constants::pi<int>); //} <commit_msg>Removed unused include<commit_after>#include <cagey/math/Constants.hh> #include <gtest/gtest.h> using namespace cagey::math; template <typename T> class ConstantTestFixture : public ::testing::Test { }; TYPED_TEST_CASE_P(ConstantTestFixture); TYPED_TEST_P(ConstantTestFixture, ChecksPiValue) { EXPECT_EQ(TypeParam(3.141592653589793238462643383279502884), constants::pi<TypeParam>); } TYPED_TEST_P(ConstantTestFixture, ChecksDegToRadValue) { EXPECT_EQ(constants::degToRad<TypeParam>, constants::pi<TypeParam> / TypeParam(180.0f)); } TYPED_TEST_P(ConstantTestFixture, ChecksRadToDegValue) { EXPECT_EQ(constants::radToDeg<TypeParam>, TypeParam(180.0f) / constants::pi<TypeParam> ); } REGISTER_TYPED_TEST_CASE_P(ConstantTestFixture, ChecksPiValue, ChecksDegToRadValue, ChecksRadToDegValue); typedef ::testing::Types<int, float, double> SupportedTypes; INSTANTIATE_TYPED_TEST_CASE_P(Cagey, ConstantTestFixture, SupportedTypes); //TEST(Vector, Pi) { // EXPECT_EQ(3, constants::pi<int>); //} <|endoftext|>
<commit_before>#include <stdio.h> #include <Halide.h> using namespace Halide; int main(int argc, char **argv) { //int W = 64*3, H = 64*3; const int W = 16, H = 16; Image<uint16_t> in(W, H); for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { in(x, y) = rand() & 0xff; } } Var x("x"), y("y"); Image<uint16_t> tent(3, 3); tent(0, 0) = 1; tent(0, 1) = 2; tent(0, 2) = 1; tent(1, 0) = 2; tent(1, 1) = 4; tent(1, 2) = 2; tent(2, 0) = 1; tent(2, 1) = 2; tent(2, 2) = 1; Func input("input"); input(x, y) = in(clamp(x, 0, W-1), clamp(y, 0, H-1)); input.compute_root(); RDom r(tent); /* This iterates over r outermost. I.e. the for loop looks like: * for y: * for x: * blur1(x, y) = 0 * for r.y: * for r.x: * for y: * for x: * blur1(x, y) += tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1) * * In general, reductions iterate over the reduction domain outermost. */ Func blur1("blur1"); blur1(x, y) += tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1); /* This uses an inline reduction, and is the more traditional way * of scheduling a convolution. "sum" creates an anonymous * reduction function that is computed within the for loop over x * in blur2. blur2 isn't actually a reduction. The loop nest looks like: * for y: * for x: * tmp = 0 * for r.y: * for r.x: * tmp += tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1) * blur(x, y) = tmp */ Func blur2("blur2"); blur2(x, y) = sum(tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1)); Target target = get_target_from_environment(); if (target.features & Target::CUDA) { // Initialization (basically memset) done in a cuda kernel blur1.cuda_tile(x, y, 16, 16); // Summation is done as an outermost loop is done on the cpu blur1.update().cuda_tile(x, y, 16, 16); // Summation is done as a sequential loop within each gpu thread blur2.cuda_tile(x, y, 16, 16); } else if (target.features & Target::OpenCL) { printf("using opencl!"); // Initialization (basically memset) done in a cuda kernel blur1.cuda_tile(x, y, 16, 16); // Summation is done as an outermost loop is done on the cpu blur1.update().cuda_tile(x, y, 16, 16); // Summation is done as a sequential loop within each gpu thread blur2.cuda_tile(x, y, 16, 16); } else { // Take this opportunity to test scheduling the pure dimensions in a reduction Var xi("xi"), yi("yi"); blur1.tile(x, y, xi, yi, 6, 6); blur1.update().tile(x, y, xi, yi, 4, 4).vectorize(xi).parallel(y); blur2.vectorize(x, 4).parallel(y); } Image<uint16_t> out1 = blur1.realize(W, H, target); Image<uint16_t> out2 = blur2.realize(W, H, target); for (int y = 1; y < H-1; y++) { for (int x = 1; x < W-1; x++) { uint16_t correct = (1*in(x-1, y-1) + 2*in(x, y-1) + 1*in(x+1, y-1) + 2*in(x-1, y) + 4*in(x, y) + 2*in(x+1, y) + 1*in(x-1, y+1) + 2*in(x, y+1) + 1*in(x+1, y+1)); if (out1(x, y) != correct) { printf("out1(%d, %d) = %d instead of %d\n", x, y, out1(x, y), correct); return -1; } if (out2(x, y) != correct) { printf("out2(%d, %d) = %d instead of %d\n", x, y, out2(x, y), correct); return -1; } } } printf("Success!\n"); return 0; } <commit_msg>Removed debugging code<commit_after>#include <stdio.h> #include <Halide.h> using namespace Halide; int main(int argc, char **argv) { //int W = 64*3, H = 64*3; const int W = 16, H = 16; Image<uint16_t> in(W, H); for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { in(x, y) = rand() & 0xff; } } Var x("x"), y("y"); Image<uint16_t> tent(3, 3); tent(0, 0) = 1; tent(0, 1) = 2; tent(0, 2) = 1; tent(1, 0) = 2; tent(1, 1) = 4; tent(1, 2) = 2; tent(2, 0) = 1; tent(2, 1) = 2; tent(2, 2) = 1; Func input("input"); input(x, y) = in(clamp(x, 0, W-1), clamp(y, 0, H-1)); input.compute_root(); RDom r(tent); /* This iterates over r outermost. I.e. the for loop looks like: * for y: * for x: * blur1(x, y) = 0 * for r.y: * for r.x: * for y: * for x: * blur1(x, y) += tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1) * * In general, reductions iterate over the reduction domain outermost. */ Func blur1("blur1"); blur1(x, y) += tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1); /* This uses an inline reduction, and is the more traditional way * of scheduling a convolution. "sum" creates an anonymous * reduction function that is computed within the for loop over x * in blur2. blur2 isn't actually a reduction. The loop nest looks like: * for y: * for x: * tmp = 0 * for r.y: * for r.x: * tmp += tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1) * blur(x, y) = tmp */ Func blur2("blur2"); blur2(x, y) = sum(tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1)); Target target = get_target_from_environment(); if (target.features & Target::CUDA) { // Initialization (basically memset) done in a cuda kernel blur1.cuda_tile(x, y, 16, 16); // Summation is done as an outermost loop is done on the cpu blur1.update().cuda_tile(x, y, 16, 16); // Summation is done as a sequential loop within each gpu thread blur2.cuda_tile(x, y, 16, 16); } else if (target.features & Target::OpenCL) { // Initialization (basically memset) done in a cuda kernel blur1.cuda_tile(x, y, 16, 16); // Summation is done as an outermost loop is done on the cpu blur1.update().cuda_tile(x, y, 16, 16); // Summation is done as a sequential loop within each gpu thread blur2.cuda_tile(x, y, 16, 16); } else { // Take this opportunity to test scheduling the pure dimensions in a reduction Var xi("xi"), yi("yi"); blur1.tile(x, y, xi, yi, 6, 6); blur1.update().tile(x, y, xi, yi, 4, 4).vectorize(xi).parallel(y); blur2.vectorize(x, 4).parallel(y); } Image<uint16_t> out1 = blur1.realize(W, H, target); Image<uint16_t> out2 = blur2.realize(W, H, target); for (int y = 1; y < H-1; y++) { for (int x = 1; x < W-1; x++) { uint16_t correct = (1*in(x-1, y-1) + 2*in(x, y-1) + 1*in(x+1, y-1) + 2*in(x-1, y) + 4*in(x, y) + 2*in(x+1, y) + 1*in(x-1, y+1) + 2*in(x, y+1) + 1*in(x+1, y+1)); if (out1(x, y) != correct) { printf("out1(%d, %d) = %d instead of %d\n", x, y, out1(x, y), correct); return -1; } if (out2(x, y) != correct) { printf("out2(%d, %d) = %d instead of %d\n", x, y, out2(x, y), correct); return -1; } } } printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>#ifndef THUMQ_IO_HPP #define THUMQ_IO_HPP #include <utility> #include <zmq.hpp> namespace thumq { class IO { IO(const IO &) = delete; IO &operator=(const IO &) = delete; public: /** * @param socket for use in a single receive-send cycle. */ explicit IO(zmq::socket_t &socket) throw (): handled(false), m_socket(socket), m_received(false) { } /** * Does nothing if a complete message hasn't been received. Sends a * complete message if handled, or an incomplete message if not. */ ~IO() throw (zmq::error_t) { if (!m_received) return; send_part(response.first, handled); if (handled) send_part(response.second, false); } /** * @return true if a complete message was received, or false if an * incomplete message was received. */ bool receive() { if (receive_part(request.first)) { if (receive_part(request.second)) { zmq::message_t extraneous; while (receive_part(extraneous)) { } } return true; } return false; } std::pair<zmq::message_t, zmq::message_t> request; std::pair<zmq::message_t, zmq::message_t> response; bool handled; private: bool receive_part(zmq::message_t &message) { m_socket.recv(&message); int more; size_t length = sizeof more; m_socket.getsockopt(ZMQ_RCVMORE, &more, &length); if (!more) m_received = true; return more; } void send_part(zmq::message_t &message, bool more) { int flags = 0; if (more) flags |= ZMQ_SNDMORE; m_socket.send(message, flags); } zmq::socket_t &m_socket; bool m_received; }; } // namespace thumq #endif <commit_msg>don't use deprecated throw(...)<commit_after>#ifndef THUMQ_IO_HPP #define THUMQ_IO_HPP #include <utility> #include <zmq.hpp> namespace thumq { class IO { IO(const IO &) = delete; IO &operator=(const IO &) = delete; public: /** * @param socket for use in a single receive-send cycle. */ explicit IO(zmq::socket_t &socket) throw (): handled(false), m_socket(socket), m_received(false) { } /** * Does nothing if a complete message hasn't been received. Sends a * complete message if handled, or an incomplete message if not. */ ~IO() noexcept(false) // throw (zmq::error_t) { if (!m_received) return; send_part(response.first, handled); if (handled) send_part(response.second, false); } /** * @return true if a complete message was received, or false if an * incomplete message was received. */ bool receive() { if (receive_part(request.first)) { if (receive_part(request.second)) { zmq::message_t extraneous; while (receive_part(extraneous)) { } } return true; } return false; } std::pair<zmq::message_t, zmq::message_t> request; std::pair<zmq::message_t, zmq::message_t> response; bool handled; private: bool receive_part(zmq::message_t &message) { m_socket.recv(&message); int more; size_t length = sizeof more; m_socket.getsockopt(ZMQ_RCVMORE, &more, &length); if (!more) m_received = true; return more; } void send_part(zmq::message_t &message, bool more) { int flags = 0; if (more) flags |= ZMQ_SNDMORE; m_socket.send(message, flags); } zmq::socket_t &m_socket; bool m_received; }; } // namespace thumq #endif <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr> // Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk> // // Eigen 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. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <limits> #include <Eigen/Eigenvalues> #ifdef HAS_GSL #include "gsl_helper.h" #endif template<typename MatrixType> void selfadjointeigensolver(const MatrixType& m) { /* this test covers the following files: EigenSolver.h, SelfAdjointEigenSolver.h (and indirectly: Tridiagonalization.h) */ int rows = m.rows(); int cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, 1> RealVectorType; typedef typename std::complex<typename NumTraits<typename MatrixType::Scalar>::Real> Complex; RealScalar largerEps = 10*test_precision<RealScalar>(); MatrixType a = MatrixType::Random(rows,cols); MatrixType a1 = MatrixType::Random(rows,cols); MatrixType symmA = a.adjoint() * a + a1.adjoint() * a1; MatrixType b = MatrixType::Random(rows,cols); MatrixType b1 = MatrixType::Random(rows,cols); MatrixType symmB = b.adjoint() * b + b1.adjoint() * b1; SelfAdjointEigenSolver<MatrixType> eiSymm(symmA); // generalized eigen pb SelfAdjointEigenSolver<MatrixType> eiSymmGen(symmA, symmB); #ifdef HAS_GSL if (ei_is_same_type<RealScalar,double>::ret) { typedef GslTraits<Scalar> Gsl; typename Gsl::Matrix gEvec=0, gSymmA=0, gSymmB=0; typename GslTraits<RealScalar>::Vector gEval=0; RealVectorType _eval; MatrixType _evec; convert<MatrixType>(symmA, gSymmA); convert<MatrixType>(symmB, gSymmB); convert<MatrixType>(symmA, gEvec); gEval = GslTraits<RealScalar>::createVector(rows); Gsl::eigen_symm(gSymmA, gEval, gEvec); convert(gEval, _eval); convert(gEvec, _evec); // test gsl itself ! VERIFY((symmA * _evec).isApprox(_evec * _eval.asDiagonal(), largerEps)); // compare with eigen VERIFY_IS_APPROX(_eval, eiSymm.eigenvalues()); VERIFY_IS_APPROX(_evec.cwiseAbs(), eiSymm.eigenvectors().cwiseAbs()); // generalized pb Gsl::eigen_symm_gen(gSymmA, gSymmB, gEval, gEvec); convert(gEval, _eval); convert(gEvec, _evec); // test GSL itself: VERIFY((symmA * _evec).isApprox(symmB * (_evec * _eval.asDiagonal()), largerEps)); // compare with eigen // std::cerr << _eval.transpose() << "\n" << eiSymmGen.eigenvalues().transpose() << "\n\n"; // std::cerr << _evec.format(6) << "\n\n" << eiSymmGen.eigenvectors().format(6) << "\n\n\n"; VERIFY_IS_APPROX(_eval, eiSymmGen.eigenvalues()); VERIFY_IS_APPROX(_evec.cwiseAbs(), eiSymmGen.eigenvectors().cwiseAbs()); Gsl::free(gSymmA); Gsl::free(gSymmB); GslTraits<RealScalar>::free(gEval); Gsl::free(gEvec); } #endif VERIFY_IS_EQUAL(eiSymm.info(), Success); VERIFY((symmA * eiSymm.eigenvectors()).isApprox( eiSymm.eigenvectors() * eiSymm.eigenvalues().asDiagonal(), largerEps)); VERIFY_IS_APPROX(symmA.template selfadjointView<Lower>().eigenvalues(), eiSymm.eigenvalues()); SelfAdjointEigenSolver<MatrixType> eiSymmNoEivecs(symmA, false); VERIFY_IS_EQUAL(eiSymmNoEivecs.info(), Success); VERIFY_IS_APPROX(eiSymm.eigenvalues(), eiSymmNoEivecs.eigenvalues()); // generalized eigen problem Ax = lBx VERIFY_IS_EQUAL(eiSymmGen.info(), Success); VERIFY((symmA * eiSymmGen.eigenvectors()).isApprox( symmB * (eiSymmGen.eigenvectors() * eiSymmGen.eigenvalues().asDiagonal()), largerEps)); MatrixType sqrtSymmA = eiSymm.operatorSqrt(); VERIFY_IS_APPROX(symmA, sqrtSymmA*sqrtSymmA); VERIFY_IS_APPROX(sqrtSymmA, symmA*eiSymm.operatorInverseSqrt()); MatrixType id = MatrixType::Identity(rows, cols); VERIFY_IS_APPROX(id.template selfadjointView<Lower>().operatorNorm(), RealScalar(1)); SelfAdjointEigenSolver<MatrixType> eiSymmUninitialized; VERIFY_RAISES_ASSERT(eiSymmUninitialized.info()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvalues()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvectors()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorSqrt()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorInverseSqrt()); eiSymmUninitialized.compute(symmA, false); VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvectors()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorSqrt()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorInverseSqrt()); if (rows > 1) { // Test matrix with NaN symmA(0,0) = std::numeric_limits<typename MatrixType::RealScalar>::quiet_NaN(); SelfAdjointEigenSolver<MatrixType> eiSymmNaN(symmA); VERIFY_IS_EQUAL(eiSymmNaN.info(), NoConvergence); } } void test_eigensolver_selfadjoint() { for(int i = 0; i < g_repeat; i++) { // very important to test a 3x3 matrix since we provide a special path for it CALL_SUBTEST_1( selfadjointeigensolver(Matrix3f()) ); CALL_SUBTEST_2( selfadjointeigensolver(Matrix4d()) ); CALL_SUBTEST_3( selfadjointeigensolver(MatrixXf(10,10)) ); CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(19,19)) ); CALL_SUBTEST_5( selfadjointeigensolver(MatrixXcd(17,17)) ); // some trivial but implementation-wise tricky cases CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(1,1)) ); CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(2,2)) ); CALL_SUBTEST_6( selfadjointeigensolver(Matrix<double,1,1>()) ); CALL_SUBTEST_7( selfadjointeigensolver(Matrix<double,2,2>()) ); } // Test problem size constructors CALL_SUBTEST_8(SelfAdjointEigenSolver<MatrixXf>(10)); CALL_SUBTEST_8(Tridiagonalization<MatrixXf>(10)); } <commit_msg>fix unit test when GSL is enabled<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr> // Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk> // // Eigen 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. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <limits> #include <Eigen/Eigenvalues> #ifdef HAS_GSL #include "gsl_helper.h" #endif template<typename MatrixType> void selfadjointeigensolver(const MatrixType& m) { /* this test covers the following files: EigenSolver.h, SelfAdjointEigenSolver.h (and indirectly: Tridiagonalization.h) */ int rows = m.rows(); int cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, 1> RealVectorType; typedef typename std::complex<typename NumTraits<typename MatrixType::Scalar>::Real> Complex; RealScalar largerEps = 10*test_precision<RealScalar>(); MatrixType a = MatrixType::Random(rows,cols); MatrixType a1 = MatrixType::Random(rows,cols); MatrixType symmA = a.adjoint() * a + a1.adjoint() * a1; MatrixType b = MatrixType::Random(rows,cols); MatrixType b1 = MatrixType::Random(rows,cols); MatrixType symmB = b.adjoint() * b + b1.adjoint() * b1; SelfAdjointEigenSolver<MatrixType> eiSymm(symmA); // generalized eigen pb SelfAdjointEigenSolver<MatrixType> eiSymmGen(symmA, symmB); #ifdef HAS_GSL if (ei_is_same_type<RealScalar,double>::ret) { typedef GslTraits<Scalar> Gsl; typename Gsl::Matrix gEvec=0, gSymmA=0, gSymmB=0; typename GslTraits<RealScalar>::Vector gEval=0; RealVectorType _eval; MatrixType _evec; convert<MatrixType>(symmA, gSymmA); convert<MatrixType>(symmB, gSymmB); convert<MatrixType>(symmA, gEvec); gEval = GslTraits<RealScalar>::createVector(rows); Gsl::eigen_symm(gSymmA, gEval, gEvec); convert(gEval, _eval); convert(gEvec, _evec); // test gsl itself ! VERIFY((symmA * _evec).isApprox(_evec * _eval.asDiagonal(), largerEps)); // compare with eigen VERIFY_IS_APPROX(_eval, eiSymm.eigenvalues()); VERIFY_IS_APPROX(_evec.cwiseAbs(), eiSymm.eigenvectors().cwiseAbs()); // generalized pb Gsl::eigen_symm_gen(gSymmA, gSymmB, gEval, gEvec); convert(gEval, _eval); convert(gEvec, _evec); // test GSL itself: VERIFY((symmA * _evec).isApprox(symmB * (_evec * _eval.asDiagonal()), largerEps)); // compare with eigen MatrixType normalized_eivec = eiSymmGen.eigenvectors()*eiSymmGen.eigenvectors().colwise().norm().asDiagonal().inverse(); VERIFY_IS_APPROX(_eval, eiSymmGen.eigenvalues()); VERIFY_IS_APPROX(_evec.cwiseAbs(), normalized_eivec.cwiseAbs()); Gsl::free(gSymmA); Gsl::free(gSymmB); GslTraits<RealScalar>::free(gEval); Gsl::free(gEvec); } #endif VERIFY_IS_EQUAL(eiSymm.info(), Success); VERIFY((symmA * eiSymm.eigenvectors()).isApprox( eiSymm.eigenvectors() * eiSymm.eigenvalues().asDiagonal(), largerEps)); VERIFY_IS_APPROX(symmA.template selfadjointView<Lower>().eigenvalues(), eiSymm.eigenvalues()); SelfAdjointEigenSolver<MatrixType> eiSymmNoEivecs(symmA, false); VERIFY_IS_EQUAL(eiSymmNoEivecs.info(), Success); VERIFY_IS_APPROX(eiSymm.eigenvalues(), eiSymmNoEivecs.eigenvalues()); // generalized eigen problem Ax = lBx VERIFY_IS_EQUAL(eiSymmGen.info(), Success); VERIFY((symmA * eiSymmGen.eigenvectors()).isApprox( symmB * (eiSymmGen.eigenvectors() * eiSymmGen.eigenvalues().asDiagonal()), largerEps)); MatrixType sqrtSymmA = eiSymm.operatorSqrt(); VERIFY_IS_APPROX(symmA, sqrtSymmA*sqrtSymmA); VERIFY_IS_APPROX(sqrtSymmA, symmA*eiSymm.operatorInverseSqrt()); MatrixType id = MatrixType::Identity(rows, cols); VERIFY_IS_APPROX(id.template selfadjointView<Lower>().operatorNorm(), RealScalar(1)); SelfAdjointEigenSolver<MatrixType> eiSymmUninitialized; VERIFY_RAISES_ASSERT(eiSymmUninitialized.info()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvalues()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvectors()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorSqrt()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorInverseSqrt()); eiSymmUninitialized.compute(symmA, false); VERIFY_RAISES_ASSERT(eiSymmUninitialized.eigenvectors()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorSqrt()); VERIFY_RAISES_ASSERT(eiSymmUninitialized.operatorInverseSqrt()); if (rows > 1) { // Test matrix with NaN symmA(0,0) = std::numeric_limits<typename MatrixType::RealScalar>::quiet_NaN(); SelfAdjointEigenSolver<MatrixType> eiSymmNaN(symmA); VERIFY_IS_EQUAL(eiSymmNaN.info(), NoConvergence); } } void test_eigensolver_selfadjoint() { for(int i = 0; i < g_repeat; i++) { // very important to test a 3x3 matrix since we provide a special path for it CALL_SUBTEST_1( selfadjointeigensolver(Matrix3f()) ); CALL_SUBTEST_2( selfadjointeigensolver(Matrix4d()) ); CALL_SUBTEST_3( selfadjointeigensolver(MatrixXf(10,10)) ); CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(19,19)) ); CALL_SUBTEST_5( selfadjointeigensolver(MatrixXcd(17,17)) ); // some trivial but implementation-wise tricky cases CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(1,1)) ); CALL_SUBTEST_4( selfadjointeigensolver(MatrixXd(2,2)) ); CALL_SUBTEST_6( selfadjointeigensolver(Matrix<double,1,1>()) ); CALL_SUBTEST_7( selfadjointeigensolver(Matrix<double,2,2>()) ); } // Test problem size constructors CALL_SUBTEST_8(SelfAdjointEigenSolver<MatrixXf>(10)); CALL_SUBTEST_8(Tridiagonalization<MatrixXf>(10)); } <|endoftext|>
<commit_before>#include <iostream> #include <platform/posix/sockets-datapump.h> using namespace moducom::coap; int main() { std::cout << "CoRE test" << std::endl; SocketsDatapumpHelper sdh; for(;;) { sdh.loop(sockets_datapump); auto& datapump = sockets_datapump; /* typedef TDataPump datapump_t; typedef typename datapump_t::netbuf_t netbuf_t; typedef typename datapump_t::addr_t addr_t; typedef typename datapump_t::Item item_t; f(!datapump.dequeue_empty()) { item_t& item = datapump.dequeue_front(); // hold on to ipaddr for when we enqueue a response addr_t ipaddr = item.addr(); //decoder_t decoder(*sdh.front(&ipaddr, datapump)); decoder_t decoder(*item.netbuf()); layer2::Token token; */ } return 0; }<commit_msg>Boilerplate (reproducing datapump ping test)<commit_after>#include <iostream> #include <platform/posix/sockets-datapump.h> #include <coap/encoder.h> #include <coap/decoder.h> #include <coap/decoder/subject.h> using namespace moducom::coap; int main() { std::cout << "CoRE test" << std::endl; SocketsDatapumpHelper sdh; for(;;) { sdh.loop(sockets_datapump); auto& datapump = sockets_datapump; typedef sockets_datapump_t datapump_t; typedef typename datapump_t::netbuf_t netbuf_t; typedef typename datapump_t::addr_t addr_t; typedef typename datapump_t::Item item_t; typedef NetBufDecoder<netbuf_t&> decoder_t; if(!datapump.dequeue_empty()) { item_t& item = datapump.dequeue_front(); // hold on to ipaddr for when we enqueue a response addr_t ipaddr = item.addr(); //decoder_t decoder(*sdh.front(&ipaddr, datapump)); decoder_t decoder(*item.netbuf()); Header header_in = decoder.header(); layer2::Token token; // populate token, if present. Expects decoder to be at HeaderDone phase decoder.token(&token); // skip any options option_iterator<decoder_t> it(decoder, true); while(it.valid()) ++it; #ifdef FEATURE_EMBR_DATAPUMP_INLINE NetBufEncoder<netbuf_t> encoder; #else // FIX: Need a much more cohesive way of doing this delete &decoder.netbuf(); NetBufEncoder<netbuf_t&> encoder(* new netbuf_t); #endif datapump.dequeue_pop(); encoder.header(create_response(header_in, Header::Code::Content)); encoder.token(token); // optional and experimental. Really I think we can do away with encoder.complete() // because coap messages are indicated complete mainly by reaching the transport packet // size - a mechanism which is fully outside the scope of the encoder encoder.complete(); #ifdef FEATURE_EMBR_DATAPUMP_INLINE datapump.enqueue_out(std::move(encoder.netbuf()), ipaddr); #else datapump.enqueue_out(encoder.netbuf(), ipaddr); #endif } } return 0; }<|endoftext|>
<commit_before>#include <cstdio> #include <cstring> #include <iostream> #include <sstream> #include <netinet/in.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <vector> #include <algorithm> #include <list> #include <map> #include <netdb.h> #include <cstdlib> #include "segment.h" #include "message.h" #include "loc_success_message.h" #include "loc_failure_message.h" #include "loc_request_message.h" #include "execute_success_message.h" #include "execute_failure_message.h" #include "execute_request_message.h" #include "register_success_message.h" #include "register_failure_message.h" #include "register_request_message.h" #include "terminate_message.h" #include "rpc.h" #include "constants.h" #include "network.h" #include "helper_function.h" using namespace std; //Global Variables for client bool connectedToBinder = false; int binderSocket = 0; //Global Variables for server struct addrinfo* servinfo; static map<procedure_signature, skeleton, ps_compare> proc_skele_dict; string serverIdentifier; unsigned int port; int sock; int connectToBinder(){ if(connectedToBinder){ return 0; } char * binderAddressString = getenv("BINDER_ADDRESS"); char * binderPortString = getenv("BINDER_PORT"); if(binderAddressString == NULL){ return 1; } if(binderPortString == NULL){ return 2; } unsigned int portInt = atoi(binderPortString); binderSocket = createConnection(string(binderAddressString), portInt); if (binderSocket < 0) { return 3; }else{ connectedToBinder = true; } return 0; } // See interface (header file). int rpcInit(){ // Creates a connection socket to be used for accepting connections // from clients int welcomeSocket = createSocket(); setUpToListen(welcomeSocket); // Opens a connection to the binder int binderSocket = connectToBinder(); return 0; } int sendExecute(int sock, string name, int* argTypes, void**args){ ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args); Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg); int status = exeReqSeg.send(sock); int returnVal; string retName; int* retArgTypes; void** retArgs; if(status == 0){ Segment * segment = 0; status = Segment::receive(sock, segment); if(segment->getType() == MSG_TYPE_EXECUTE_SUCCESS) { Message * cast = segment->getMessage(); ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(cast); retName = esm->getName(); retArgTypes = esm->getArgTypes(); retArgs = esm->getArgs(); if(retName == name){ //extractArgumentsMessage(replyMessageP, argTypes, args, argTypesLength, false); returnVal = 0; }else{ returnVal = 99; } }else if(segment->getType() == MSG_TYPE_EXECUTE_FAILURE){ Message * cast = segment->getMessage(); ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast); returnVal = efm->getReasonCode(); } }else{ //Something bad happened returnVal = 99; } return returnVal; } int rpcCall(char * name, int * argTypes, void ** args) { string serverAddress; unsigned int serverPort; int status; if(!connectedToBinder){ status = connectToBinder(); } //do something with returnVal LocRequestMessage locReqMsg = LocRequestMessage(name, argTypes); Segment locReqSeg = Segment(locReqMsg.getLength(), MSG_TYPE_LOC_REQUEST, &locReqMsg); int binder_status = locReqSeg.send(clientSocket); //maybe error check with binder_status /**Server stuff **/ if(binder_status == 0){ Segment * segment = 0; status = Segment::receive(binderSocket, segment); if(segment->getType() == MSG_TYPE_LOC_SUCCESS){ //'LOC_REQUEST' Message * cast = segment->getMessage(); LocSuccessMessage * lcm = dynamic_cast<LocSuccessMessage*>(cast); serverAddress = lcm->getServerIdentifier(); serverPort = lcm->getPort(); }else if(segment->getType() == MSG_TYPE_LOC_FAILURE){ //something bad happens return 1; } } int server_sock = createConnection(serverAddress, serverPort); int server_status = sendExecute(server_sock, string(name), argTypes, args); return server_status; } //TODO: // CREATE SERVER // CONNECT TO BINDER int rpcRegister(char * name, int *argTypes, skeleton f){ RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes); /* We should get seg.send to give us some feed back maybe int status = regReqMsg->send(binderSocket); */ Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg); int status = regReqSeg.send(binderSocket); if(status == 0){ //Success Segment *parsedSegment = 0; int result = 0; segment = Segment::receive(binderSocket, parsedSegment); if(segment->getType() == MSG_TYPE_REGISTER_SUCCESS){ Message * cast = segment->getMessage(); //Error Checking maybe RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast); struct procedure_signature k(string(name), argTypes); proc_skele_dict[k] = f; }else if(segment->getType() == MSG_TYPE_REGISTER_FAILURE){ return 0; } }else if( status > 0){ //Warning return -99; }else if( status < 0){ //Error return 99; } return 1; } int rpcExecute(void){ //Create connection socket ot be used for accepting clients vector<int> myConnections; vector<int> myToRemove; fd_set readfds; int n; int status; struct sockaddr_storage their_addr; while(true){ //CONNECTIONS VECTOR FD_ZERO(&readfds); FD_SET(sock, &readfds); n = sock; for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) { int connection = *it; FD_SET(connection, &readfds); if (connection > n){ n = connection; } } n = n+1; status = select(n, &readfds, NULL, NULL, NULL); if (status == -1) { cerr << "ERROR: select failed." << endl; } else { if (FD_ISSET(sock, &readfds)) { socklen_t addr_size = sizeof their_addr; int new_sock = accept(sock, (struct sockaddr*)&their_addr, &addr_size); if (new_sock < 0) { cerr << "ERROR: while accepting connection" << endl; close(new_sock); continue; } myConnections.push_back(new_sock); } else { for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) { int tempConnection = *it; if (FD_ISSET(tempConnection, &readfds)) { int reasonCode = 0; Segment * segment = 0; status = Segment::receive(sock, segment); if(segment->getType() == MSG_TYPE_EXECUTE_REQUEST){ Message * cast = segment->getMessage(); ExecuteRequestMessage * eqm = dynamic_cast<ExecuteRequestMessage*>(cast); procedure_signature * ps = new procedure_signature(eqm->getName(), eqm->getArgTypes()); skeleton skel = proc_skele_dict[*ps]; int result = skel(eqm->getArgTypes(), eqm->getArgs()); if(result == 0 ){ ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(eqm->getName(), eqm->getArgTypes(), eqm->getArgs()); Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg); status = exeSuccessSeg.send(sock); }else{ ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(reasonCode); Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg); status = exeFailSeg.send(sock); } } if (status == 0) { // client has closed the connection myToRemove.push_back(sock); return status; } } } } for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) { myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end()); close(*it); } myToRemove.clear(); } } freeaddrinfo(servinfo); return 0; } <commit_msg>cleanup<commit_after>#include <cstdio> #include <cstring> #include <iostream> #include <sstream> #include <netinet/in.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <vector> #include <algorithm> #include <list> #include <map> #include <netdb.h> #include <cstdlib> #include "segment.h" #include "message.h" #include "loc_success_message.h" #include "loc_failure_message.h" #include "loc_request_message.h" #include "execute_success_message.h" #include "execute_failure_message.h" #include "execute_request_message.h" #include "register_success_message.h" #include "register_failure_message.h" #include "register_request_message.h" #include "terminate_message.h" #include "rpc.h" #include "constants.h" #include "network.h" #include "helper_function.h" using namespace std; //Global Variables for client bool connectedToBinder = false; int binderSocket = 0; //Global Variables for server struct addrinfo* servinfo; static map<procedure_signature, skeleton, ps_compare> proc_skele_dict; string serverIdentifier; unsigned int port; int welcomeSocket; int connectToBinder(){ if(connectedToBinder){ return 0; } char * binderAddressString = getenv("BINDER_ADDRESS"); char * binderPortString = getenv("BINDER_PORT"); if(binderAddressString == NULL){ return 1; } if(binderPortString == NULL){ return 2; } unsigned int portInt = atoi(binderPortString); binderSocket = createConnection(string(binderAddressString), portInt); if (binderSocket < 0) { return 3; }else{ connectedToBinder = true; } return 0; } // See interface (header file). int rpcInit(){ // Creates a connection socket to be used for accepting connections // from clients int welcomeSocket = createSocket(); setUpToListen(welcomeSocket); // Opens a connection to the binder int binderSocket = connectToBinder(); return 0; } int sendExecute(int sock, string name, int* argTypes, void**args){ ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args); Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg); int status = exeReqSeg.send(sock); int returnVal; string retName; int* retArgTypes; void** retArgs; if(status == 0){ Segment * segment = 0; status = Segment::receive(sock, segment); if(segment->getType() == MSG_TYPE_EXECUTE_SUCCESS) { Message * cast = segment->getMessage(); ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(cast); retName = esm->getName(); retArgTypes = esm->getArgTypes(); retArgs = esm->getArgs(); if(retName == name){ //extractArgumentsMessage(replyMessageP, argTypes, args, argTypesLength, false); returnVal = 0; }else{ returnVal = 99; } }else if(segment->getType() == MSG_TYPE_EXECUTE_FAILURE){ Message * cast = segment->getMessage(); ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast); returnVal = efm->getReasonCode(); } }else{ //Something bad happened returnVal = 99; } return returnVal; } int rpcCall(char * name, int * argTypes, void ** args) { string serverAddress; unsigned int serverPort; int status; if(!connectedToBinder){ status = connectToBinder(); } //do something with returnVal LocRequestMessage locReqMsg = LocRequestMessage(name, argTypes); Segment locReqSeg = Segment(locReqMsg.getLength(), MSG_TYPE_LOC_REQUEST, &locReqMsg); int binder_status = locReqSeg.send(clientSocket); //maybe error check with binder_status /**Server stuff **/ if(binder_status == 0){ Segment * segment = 0; status = Segment::receive(binderSocket, segment); if(segment->getType() == MSG_TYPE_LOC_SUCCESS){ //'LOC_REQUEST' Message * cast = segment->getMessage(); LocSuccessMessage * lcm = dynamic_cast<LocSuccessMessage*>(cast); serverAddress = lcm->getServerIdentifier(); serverPort = lcm->getPort(); }else if(segment->getType() == MSG_TYPE_LOC_FAILURE){ //something bad happens return 1; } } int server_sock = createConnection(serverAddress, serverPort); int server_status = sendExecute(server_sock, string(name), argTypes, args); return server_status; } //TODO: // CREATE SERVER // CONNECT TO BINDER int rpcRegister(char * name, int *argTypes, skeleton f){ RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes); /* We should get seg.send to give us some feed back maybe int status = regReqMsg->send(binderSocket); */ Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg); int status = regReqSeg.send(binderSocket); if(status == 0){ //Success Segment *parsedSegment = 0; int result = 0; segment = Segment::receive(binderSocket, parsedSegment); if(segment->getType() == MSG_TYPE_REGISTER_SUCCESS){ Message * cast = segment->getMessage(); //Error Checking maybe RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast); struct procedure_signature k(string(name), argTypes); proc_skele_dict[k] = f; }else if(segment->getType() == MSG_TYPE_REGISTER_FAILURE){ return 0; } }else if( status > 0){ //Warning return -99; }else if( status < 0){ //Error return 99; } return 1; } int rpcExecute(void){ //Create connection socket ot be used for accepting clients vector<int> myConnections; vector<int> myToRemove; fd_set readfds; int n; int status; struct sockaddr_storage their_addr; while(true){ //CONNECTIONS VECTOR FD_ZERO(&readfds); FD_SET(welcomeSocket, &readfds); n = welcomeSocket; for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) { int connection = *it; FD_SET(connection, &readfds); if (connection > n){ n = connection; } } n = n+1; status = select(n, &readfds, NULL, NULL, NULL); if (status == -1) { cerr << "ERROR: select failed." << endl; } else { if (FD_ISSET(welcomeSocket, &readfds)) { socklen_t addr_size = sizeof their_addr; int new_sock = accept(welcomeSocket, (struct sockaddr*)&their_addr, &addr_size); if (new_sock < 0) { cerr << "ERROR: while accepting connection" << endl; close(new_sock); continue; } myConnections.push_back(new_sock); } else { for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) { int tempConnection = *it; if (FD_ISSET(tempConnection, &readfds)) { int reasonCode = 0; Segment * segment = 0; status = Segment::receive(sock, segment); if(segment->getType() == MSG_TYPE_EXECUTE_REQUEST){ Message * cast = segment->getMessage(); ExecuteRequestMessage * eqm = dynamic_cast<ExecuteRequestMessage*>(cast); procedure_signature * ps = new procedure_signature(eqm->getName(), eqm->getArgTypes()); skeleton skel = proc_skele_dict[*ps]; int result = skel(eqm->getArgTypes(), eqm->getArgs()); if(result == 0 ){ ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(eqm->getName(), eqm->getArgTypes(), eqm->getArgs()); Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg); status = exeSuccessSeg.send(sock); }else{ ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(reasonCode); Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg); status = exeFailSeg.send(sock); } } if (status == 0) { // client has closed the connection myToRemove.push_back(sock); return status; } } } } for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) { myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end()); close(*it); } myToRemove.clear(); } } freeaddrinfo(servinfo); return 0; } int rpcCacheCall() { return 0; } int rpcTerminate() { return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkConfig.h" #include "mitkCoreObjectFactory.h" #include "mitkAffineInteractor.h" #include "mitkColorProperty.h" #include "mitkDataTreeNode.h" #include "mitkEnumerationProperty.h" #include "mitkGeometry2DData.h" #include "mitkGeometry2DDataMapper2D.h" #include "mitkGeometry2DDataVtkMapper3D.h" #include "mitkGeometry3D.h" #include "mitkGeometryData.h" #include "mitkImage.h" #include "mitkImageMapper2D.h" #include "mitkLevelWindowProperty.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "mitkMaterialProperty.h" #include "mitkPlaneGeometry.h" #include "mitkPointSet.h" #include "mitkPointSetMapper2D.h" #include "mitkPointSetVtkMapper3D.h" #include "mitkPolyDataGLMapper2D.h" #include "mitkProperties.h" #include "mitkPropertyList.h" #include "mitkSlicedGeometry3D.h" #include "mitkSmartPointerProperty.h" #include "mitkStringProperty.h" #include "mitkSurface.h" #include "mitkSurface.h" #include "mitkSurfaceMapper2D.h" #include "mitkSurfaceVtkMapper3D.h" #include "mitkTimeSlicedGeometry.h" #include "mitkTransferFunctionProperty.h" #include "mitkVolumeDataVtkMapper3D.h" #include "mitkVtkInterpolationProperty.h" #include "mitkVtkRepresentationProperty.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkPicFileIOFactory.h" #include "mitkPointSetIOFactory.h" #include "mitkItkImageFileIOFactory.h" #include "mitkSTLFileIOFactory.h" #include "mitkVtkSurfaceIOFactory.h" #include "mitkVtkImageIOFactory.h" #include "mitkVtiFileIOFactory.h" #include "mitkPicVolumeTimeSeriesIOFactory.h" #include "mitkImageWriterFactory.h" #include "mitkPointSetWriterFactory.h" #include "mitkSurfaceVtkWriterFactory.h" #define CREATE_CPP( TYPE, NAME ) else if ( className == NAME ) {pointer = new TYPE(); pointer->Register();} #define CREATE_ITK( TYPE, NAME ) else if ( className == NAME ) pointer = TYPE::New(); mitk::CoreObjectFactory::FileWriterList mitk::CoreObjectFactory::m_FileWriters; itk::Object::Pointer mitk::CoreObjectFactory::CreateCoreObject( const std::string& className ) { itk::Object::Pointer pointer; if ( className == "" ) return NULL; CREATE_ITK( BoolProperty, "BoolProperty" ) CREATE_ITK( IntProperty, "IntProperty" ) CREATE_ITK( FloatProperty, "FloatProperty" ) CREATE_ITK( DoubleProperty, "DoubleProperty" ) CREATE_ITK( Vector3DProperty, "Vector3DProperty" ) CREATE_ITK( Point3dProperty, "Point3dProperty" ) CREATE_ITK( Point4dProperty, "Point4dProperty" ) CREATE_ITK( Point3iProperty, "Point3iProperty" ) CREATE_ITK( BoolProperty, "BoolProperty" ) CREATE_ITK( ColorProperty, "ColorProperty" ) CREATE_ITK( LevelWindowProperty, "LevelWindowProperty" ) CREATE_ITK( LookupTableProperty, "LookupTableProperty" ) CREATE_ITK( MaterialProperty, "MaterialProperty" ) CREATE_ITK( StringProperty, "StringProperty" ) CREATE_ITK( SmartPointerProperty, "SmartPointerProperty" ) CREATE_ITK( TransferFunctionProperty, "TransferFunctionProperty" ) CREATE_ITK( EnumerationProperty, "EnumerationProperty" ) CREATE_ITK( VtkInterpolationProperty, "VtkInterpolationProperty" ) CREATE_ITK( VtkRepresentationProperty, "VtkRepresentationProperty" ) CREATE_ITK( VtkResliceInterpolationProperty, "VtkResliceInterpolationProperty" ) CREATE_ITK( GeometryData, "GeometryData" ) CREATE_ITK( Surface, "Surface" ) CREATE_ITK( Image, "Image" ) CREATE_ITK( Geometry3D, "Geometry3D" ) CREATE_ITK( TimeSlicedGeometry, "TimeSlicedGeometry" ) CREATE_ITK( Surface, "Surface" ) CREATE_ITK( PointSet, "PointSet" ) CREATE_ITK( SlicedGeometry3D, "SlicedGeometry3D" ) CREATE_ITK( PlaneGeometry, "PlaneGeometry" ) CREATE_ITK( PropertyList, "PropertyList" ) CREATE_ITK( SurfaceMapper2D, "SurfaceMapper2D" ) CREATE_ITK( SurfaceVtkMapper3D, "SurfaceVtkMapper3D" ) CREATE_ITK( ImageMapper2D, "ImageMapper2D" ) CREATE_ITK( VolumeDataVtkMapper3D, "VolumeDataVtkMapper3D" ) CREATE_ITK( LookupTable, "LookupTable" ) CREATE_ITK( PointSetMapper2D, "PointSetMapper2D" ) CREATE_ITK( PointSetVtkMapper3D, "PointSetVtkMapper3D" ) else LOG_ERROR << "ObjectFactory::CreateObject: unknown class: " << className << std::endl; return pointer; } mitk::CoreObjectFactory::Pointer mitk::CoreObjectFactory::GetInstance() { static mitk::CoreObjectFactory::Pointer instance; if (instance.IsNull()) { std::list<itk::LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("mitkCoreObjectFactoryBase"); std::list<itk::LightObject::Pointer>::iterator factoryIt = allobjects.begin(); while (instance.IsNull() && factoryIt != allobjects.end() ) { if (std::string("SBCoreObjectFactory") == (*factoryIt)->GetNameOfClass() ) { instance = dynamic_cast<mitk::CoreObjectFactory*>(factoryIt->GetPointer()); } ++factoryIt; } factoryIt = allobjects.begin(); while (instance.IsNull() && factoryIt != allobjects.end() ) { if ( std::string("QMCoreObjectFactory") == (*factoryIt)->GetNameOfClass() ) { instance = dynamic_cast<mitk::CoreObjectFactory*>(factoryIt->GetPointer()); } ++factoryIt; } factoryIt = allobjects.begin(); while (instance.IsNull() && factoryIt != allobjects.end() ) { if (std::string("CoreExtObjectFactory") == (*factoryIt)->GetNameOfClass() ) { instance = dynamic_cast<mitk::CoreObjectFactory*>(factoryIt->GetPointer()); } ++factoryIt; } if (instance.IsNull()) { instance = mitk::CoreObjectFactory::New(); } LOG_INFO << "CoreObjectFactory: created instance of " << instance->GetNameOfClass() << std::endl; } return instance; } #include <mitkDataTreeNodeFactory.h> void mitk::CoreObjectFactory::SetDefaultProperties(mitk::DataTreeNode* node) { if(node==NULL) return; mitk::DataTreeNode::Pointer nodePointer = node; mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(node->GetData()); if(image.IsNotNull() && image->IsInitialized()) { mitk::ImageMapper2D::SetDefaultProperties(node); mitk::VolumeDataVtkMapper3D::SetDefaultProperties(node); } mitk::Surface::Pointer surface = dynamic_cast<mitk::Surface*>(node->GetData()); if(surface.IsNotNull()) { mitk::SurfaceMapper2D::SetDefaultProperties(node); mitk::SurfaceVtkMapper3D::SetDefaultProperties(node); } mitk::PointSet::Pointer pointSet = dynamic_cast<mitk::PointSet*>(node->GetData()); if(pointSet.IsNotNull()) { mitk::PointSetMapper2D::SetDefaultProperties(node); mitk::PointSetVtkMapper3D::SetDefaultProperties(node); } } mitk::CoreObjectFactory::CoreObjectFactory() { static bool alreadyDone = false; if (!alreadyDone) { LOG_INFO << "CoreObjectFactory c'tor" << std::endl; itk::ObjectFactoryBase::RegisterFactory( PicFileIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( PointSetIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( STLFileIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( VtkSurfaceIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( VtkImageIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( VtiFileIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( ItkImageFileIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( PicVolumeTimeSeriesIOFactory::New() ); mitk::SurfaceVtkWriterFactory::RegisterOneFactory(); mitk::PointSetWriterFactory::RegisterOneFactory(); mitk::ImageWriterFactory::RegisterOneFactory(); alreadyDone = true; } } mitk::Mapper::Pointer mitk::CoreObjectFactory::CreateMapper(mitk::DataTreeNode* node, MapperSlotId id) { mitk::Mapper::Pointer newMapper = NULL; mitk::BaseData *data = node->GetData(); if ( id == mitk::BaseRenderer::Standard2D ) { if((dynamic_cast<Image*>(data)!=NULL)) { mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(data); newMapper = mitk::ImageMapper2D::New(); newMapper->SetDataTreeNode(node); } else if((dynamic_cast<Geometry2DData*>(data)!=NULL)) { newMapper = mitk::Geometry2DDataMapper2D::New(); newMapper->SetDataTreeNode(node); } else if((dynamic_cast<Surface*>(data)!=NULL)) { newMapper = mitk::SurfaceMapper2D::New(); // cast because SetDataTreeNode is not virtual mitk::SurfaceMapper2D *castedMapper = (mitk::SurfaceMapper2D*)newMapper.GetPointer(); castedMapper->SetDataTreeNode(node); } else if((dynamic_cast<PointSet*>(data)!=NULL)) { newMapper = mitk::PointSetMapper2D::New(); newMapper->SetDataTreeNode(node); } } else if ( id == mitk::BaseRenderer::Standard3D ) { if((dynamic_cast<Image*>(data) != NULL)) { newMapper = mitk::VolumeDataVtkMapper3D::New(); newMapper->SetDataTreeNode(node); } else if((dynamic_cast<Geometry2DData*>(data)!=NULL)) { newMapper = mitk::Geometry2DDataVtkMapper3D::New(); newMapper->SetDataTreeNode(node); } else if((dynamic_cast<Surface*>(data)!=NULL)) { newMapper = mitk::SurfaceVtkMapper3D::New(); newMapper->SetDataTreeNode(node); } else if((dynamic_cast<PointSet*>(data)!=NULL)) { newMapper = mitk::PointSetVtkMapper3D::New(); //newMapper = mitk::EnhancedPointSetVtkMapper3D::New(); // <-- use this if you want to try the new work in progres point set mapper newMapper->SetDataTreeNode(node); } } return newMapper; } #define EXTERNAL_FILE_EXTENSIONS \ "All known formats(*.dcm *.DCM *.dc3 *.DC3 *.gdcm *.ima *.mhd *.mps *.pic *.pic.gz *.bmp *.png *.jpg *.tiff *.pvtk *.stl *.vtk *.vtp *.vtu *.obj *.vti *.hdr);;" \ "DICOM files(*.dcm *.DCM *.dc3 *.DC3 *.gdcm);;" \ "DKFZ Pic (*.seq *.pic *.pic.gz *.seq.gz);;" \ "Point sets (*.mps);;" \ "Sets of 2D slices (*.pic *.pic.gz *.bmp *.png *.dcm *.gdcm *.ima *.tiff);;" \ "Surface files (*.stl *.vtk *.vtp *.obj)" #define INTERNAL_FILE_EXTENSIONS \ "all (*.seq *.mps *.pic *.pic.gz *.seq.gz *.pvtk *.stl *.vtk *.vtp *.vtu *.obj *.vti *.ves " \ "*.uvg *.dvg *.par *.dcm *.dc3 *.gdcm *.ima *.mhd *.hdr hpsonos.db HPSONOS.DB *.ssm *msm *.bmp *.png *.jpg *.tiff *.mitk);;" \ "Project files(*.mitk);;" \ "DKFZ Pic (*.seq *.pic *.pic.gz *.seq.gz);;" \ "Point sets (*.mps);;" \ "surface files (*.stl *.vtk *.vtp *.obj);;" \ "stl files (*.stl);;" \ "vtk surface files (*.vtk);;" \ "vtk image files (*.pvtk);;" \ "vessel files (*.ves *.uvg *.dvg);;" \ "par/rec files (*.par);;" \ "DSR files (hpsonos.db HPSONOS.DB);;" \ "DICOM files (*.dcm *.gdcm *.dc3 *.ima)" #define SAVE_FILE_EXTENSIONS "all (*.pic *.mhd *.vtk *.vti *.hdr *.png *.tiff *.jpg *.hdr *.bmp *.dcm *.gipl *.nii *.nrrd *.spr *.lsm)" const char* mitk::CoreObjectFactory::GetFileExtensions() { return EXTERNAL_FILE_EXTENSIONS; }; const char* mitk::CoreObjectFactory::GetSaveFileExtensions() { return SAVE_FILE_EXTENSIONS; }; mitk::CoreObjectFactory::FileWriterList mitk::CoreObjectFactory::GetFileWriters() { return m_FileWriters; } void mitk::CoreObjectFactory::MapEvent(const mitk::Event*, const int) { } <commit_msg>FIX (#2871): Added *.nii file format to file open dialogs.<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkConfig.h" #include "mitkCoreObjectFactory.h" #include "mitkAffineInteractor.h" #include "mitkColorProperty.h" #include "mitkDataTreeNode.h" #include "mitkEnumerationProperty.h" #include "mitkGeometry2DData.h" #include "mitkGeometry2DDataMapper2D.h" #include "mitkGeometry2DDataVtkMapper3D.h" #include "mitkGeometry3D.h" #include "mitkGeometryData.h" #include "mitkImage.h" #include "mitkImageMapper2D.h" #include "mitkLevelWindowProperty.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "mitkMaterialProperty.h" #include "mitkPlaneGeometry.h" #include "mitkPointSet.h" #include "mitkPointSetMapper2D.h" #include "mitkPointSetVtkMapper3D.h" #include "mitkPolyDataGLMapper2D.h" #include "mitkProperties.h" #include "mitkPropertyList.h" #include "mitkSlicedGeometry3D.h" #include "mitkSmartPointerProperty.h" #include "mitkStringProperty.h" #include "mitkSurface.h" #include "mitkSurface.h" #include "mitkSurfaceMapper2D.h" #include "mitkSurfaceVtkMapper3D.h" #include "mitkTimeSlicedGeometry.h" #include "mitkTransferFunctionProperty.h" #include "mitkVolumeDataVtkMapper3D.h" #include "mitkVtkInterpolationProperty.h" #include "mitkVtkRepresentationProperty.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkPicFileIOFactory.h" #include "mitkPointSetIOFactory.h" #include "mitkItkImageFileIOFactory.h" #include "mitkSTLFileIOFactory.h" #include "mitkVtkSurfaceIOFactory.h" #include "mitkVtkImageIOFactory.h" #include "mitkVtiFileIOFactory.h" #include "mitkPicVolumeTimeSeriesIOFactory.h" #include "mitkImageWriterFactory.h" #include "mitkPointSetWriterFactory.h" #include "mitkSurfaceVtkWriterFactory.h" #define CREATE_CPP( TYPE, NAME ) else if ( className == NAME ) {pointer = new TYPE(); pointer->Register();} #define CREATE_ITK( TYPE, NAME ) else if ( className == NAME ) pointer = TYPE::New(); mitk::CoreObjectFactory::FileWriterList mitk::CoreObjectFactory::m_FileWriters; itk::Object::Pointer mitk::CoreObjectFactory::CreateCoreObject( const std::string& className ) { itk::Object::Pointer pointer; if ( className == "" ) return NULL; CREATE_ITK( BoolProperty, "BoolProperty" ) CREATE_ITK( IntProperty, "IntProperty" ) CREATE_ITK( FloatProperty, "FloatProperty" ) CREATE_ITK( DoubleProperty, "DoubleProperty" ) CREATE_ITK( Vector3DProperty, "Vector3DProperty" ) CREATE_ITK( Point3dProperty, "Point3dProperty" ) CREATE_ITK( Point4dProperty, "Point4dProperty" ) CREATE_ITK( Point3iProperty, "Point3iProperty" ) CREATE_ITK( BoolProperty, "BoolProperty" ) CREATE_ITK( ColorProperty, "ColorProperty" ) CREATE_ITK( LevelWindowProperty, "LevelWindowProperty" ) CREATE_ITK( LookupTableProperty, "LookupTableProperty" ) CREATE_ITK( MaterialProperty, "MaterialProperty" ) CREATE_ITK( StringProperty, "StringProperty" ) CREATE_ITK( SmartPointerProperty, "SmartPointerProperty" ) CREATE_ITK( TransferFunctionProperty, "TransferFunctionProperty" ) CREATE_ITK( EnumerationProperty, "EnumerationProperty" ) CREATE_ITK( VtkInterpolationProperty, "VtkInterpolationProperty" ) CREATE_ITK( VtkRepresentationProperty, "VtkRepresentationProperty" ) CREATE_ITK( VtkResliceInterpolationProperty, "VtkResliceInterpolationProperty" ) CREATE_ITK( GeometryData, "GeometryData" ) CREATE_ITK( Surface, "Surface" ) CREATE_ITK( Image, "Image" ) CREATE_ITK( Geometry3D, "Geometry3D" ) CREATE_ITK( TimeSlicedGeometry, "TimeSlicedGeometry" ) CREATE_ITK( Surface, "Surface" ) CREATE_ITK( PointSet, "PointSet" ) CREATE_ITK( SlicedGeometry3D, "SlicedGeometry3D" ) CREATE_ITK( PlaneGeometry, "PlaneGeometry" ) CREATE_ITK( PropertyList, "PropertyList" ) CREATE_ITK( SurfaceMapper2D, "SurfaceMapper2D" ) CREATE_ITK( SurfaceVtkMapper3D, "SurfaceVtkMapper3D" ) CREATE_ITK( ImageMapper2D, "ImageMapper2D" ) CREATE_ITK( VolumeDataVtkMapper3D, "VolumeDataVtkMapper3D" ) CREATE_ITK( LookupTable, "LookupTable" ) CREATE_ITK( PointSetMapper2D, "PointSetMapper2D" ) CREATE_ITK( PointSetVtkMapper3D, "PointSetVtkMapper3D" ) else LOG_ERROR << "ObjectFactory::CreateObject: unknown class: " << className << std::endl; return pointer; } mitk::CoreObjectFactory::Pointer mitk::CoreObjectFactory::GetInstance() { static mitk::CoreObjectFactory::Pointer instance; if (instance.IsNull()) { std::list<itk::LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("mitkCoreObjectFactoryBase"); std::list<itk::LightObject::Pointer>::iterator factoryIt = allobjects.begin(); while (instance.IsNull() && factoryIt != allobjects.end() ) { if (std::string("SBCoreObjectFactory") == (*factoryIt)->GetNameOfClass() ) { instance = dynamic_cast<mitk::CoreObjectFactory*>(factoryIt->GetPointer()); } ++factoryIt; } factoryIt = allobjects.begin(); while (instance.IsNull() && factoryIt != allobjects.end() ) { if ( std::string("QMCoreObjectFactory") == (*factoryIt)->GetNameOfClass() ) { instance = dynamic_cast<mitk::CoreObjectFactory*>(factoryIt->GetPointer()); } ++factoryIt; } factoryIt = allobjects.begin(); while (instance.IsNull() && factoryIt != allobjects.end() ) { if (std::string("CoreExtObjectFactory") == (*factoryIt)->GetNameOfClass() ) { instance = dynamic_cast<mitk::CoreObjectFactory*>(factoryIt->GetPointer()); } ++factoryIt; } if (instance.IsNull()) { instance = mitk::CoreObjectFactory::New(); } LOG_INFO << "CoreObjectFactory: created instance of " << instance->GetNameOfClass() << std::endl; } return instance; } #include <mitkDataTreeNodeFactory.h> void mitk::CoreObjectFactory::SetDefaultProperties(mitk::DataTreeNode* node) { if(node==NULL) return; mitk::DataTreeNode::Pointer nodePointer = node; mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(node->GetData()); if(image.IsNotNull() && image->IsInitialized()) { mitk::ImageMapper2D::SetDefaultProperties(node); mitk::VolumeDataVtkMapper3D::SetDefaultProperties(node); } mitk::Surface::Pointer surface = dynamic_cast<mitk::Surface*>(node->GetData()); if(surface.IsNotNull()) { mitk::SurfaceMapper2D::SetDefaultProperties(node); mitk::SurfaceVtkMapper3D::SetDefaultProperties(node); } mitk::PointSet::Pointer pointSet = dynamic_cast<mitk::PointSet*>(node->GetData()); if(pointSet.IsNotNull()) { mitk::PointSetMapper2D::SetDefaultProperties(node); mitk::PointSetVtkMapper3D::SetDefaultProperties(node); } } mitk::CoreObjectFactory::CoreObjectFactory() { static bool alreadyDone = false; if (!alreadyDone) { LOG_INFO << "CoreObjectFactory c'tor" << std::endl; itk::ObjectFactoryBase::RegisterFactory( PicFileIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( PointSetIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( STLFileIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( VtkSurfaceIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( VtkImageIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( VtiFileIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( ItkImageFileIOFactory::New() ); itk::ObjectFactoryBase::RegisterFactory( PicVolumeTimeSeriesIOFactory::New() ); mitk::SurfaceVtkWriterFactory::RegisterOneFactory(); mitk::PointSetWriterFactory::RegisterOneFactory(); mitk::ImageWriterFactory::RegisterOneFactory(); alreadyDone = true; } } mitk::Mapper::Pointer mitk::CoreObjectFactory::CreateMapper(mitk::DataTreeNode* node, MapperSlotId id) { mitk::Mapper::Pointer newMapper = NULL; mitk::BaseData *data = node->GetData(); if ( id == mitk::BaseRenderer::Standard2D ) { if((dynamic_cast<Image*>(data)!=NULL)) { mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(data); newMapper = mitk::ImageMapper2D::New(); newMapper->SetDataTreeNode(node); } else if((dynamic_cast<Geometry2DData*>(data)!=NULL)) { newMapper = mitk::Geometry2DDataMapper2D::New(); newMapper->SetDataTreeNode(node); } else if((dynamic_cast<Surface*>(data)!=NULL)) { newMapper = mitk::SurfaceMapper2D::New(); // cast because SetDataTreeNode is not virtual mitk::SurfaceMapper2D *castedMapper = (mitk::SurfaceMapper2D*)newMapper.GetPointer(); castedMapper->SetDataTreeNode(node); } else if((dynamic_cast<PointSet*>(data)!=NULL)) { newMapper = mitk::PointSetMapper2D::New(); newMapper->SetDataTreeNode(node); } } else if ( id == mitk::BaseRenderer::Standard3D ) { if((dynamic_cast<Image*>(data) != NULL)) { newMapper = mitk::VolumeDataVtkMapper3D::New(); newMapper->SetDataTreeNode(node); } else if((dynamic_cast<Geometry2DData*>(data)!=NULL)) { newMapper = mitk::Geometry2DDataVtkMapper3D::New(); newMapper->SetDataTreeNode(node); } else if((dynamic_cast<Surface*>(data)!=NULL)) { newMapper = mitk::SurfaceVtkMapper3D::New(); newMapper->SetDataTreeNode(node); } else if((dynamic_cast<PointSet*>(data)!=NULL)) { newMapper = mitk::PointSetVtkMapper3D::New(); //newMapper = mitk::EnhancedPointSetVtkMapper3D::New(); // <-- use this if you want to try the new work in progress point set mapper newMapper->SetDataTreeNode(node); } } return newMapper; } #define EXTERNAL_FILE_EXTENSIONS \ "All known formats(*.dcm *.DCM *.dc3 *.DC3 *.gdcm *.ima *.mhd *.mps *.nii *.pic *.pic.gz *.bmp *.png *.jpg *.tiff *.pvtk *.stl *.vtk *.vtp *.vtu *.obj *.vti *.hdr);;" \ "DICOM files(*.dcm *.DCM *.dc3 *.DC3 *.gdcm);;" \ "DKFZ Pic (*.seq *.pic *.pic.gz *.seq.gz);;" \ "Point sets (*.mps);;" \ "Sets of 2D slices (*.pic *.pic.gz *.bmp *.png *.dcm *.gdcm *.ima *.tiff);;" \ "Surface files (*.stl *.vtk *.vtp *.obj);;" \ "NIfTI format (*.nii)" #define INTERNAL_FILE_EXTENSIONS \ "all (*.seq *.mps *.nii *.pic *.pic.gz *.seq.gz *.pvtk *.stl *.vtk *.vtp *.vtu *.obj *.vti *.ves " \ "*.uvg *.dvg *.par *.dcm *.dc3 *.gdcm *.ima *.mhd *.hdr hpsonos.db HPSONOS.DB *.ssm *msm *.bmp *.png *.jpg *.tiff *.mitk);;" \ "Project files(*.mitk);;" \ "DKFZ Pic (*.seq *.pic *.pic.gz *.seq.gz);;" \ "Point sets (*.mps);;" \ "surface files (*.stl *.vtk *.vtp *.obj);;" \ "stl files (*.stl);;" \ "vtk surface files (*.vtk);;" \ "vtk image files (*.pvtk);;" \ "vessel files (*.ves *.uvg *.dvg);;" \ "par/rec files (*.par);;" \ "DSR files (hpsonos.db HPSONOS.DB);;" \ "DICOM files (*.dcm *.gdcm *.dc3 *.ima);;" \ "NIfTI format (*.nii)" #define SAVE_FILE_EXTENSIONS "all (*.pic *.mhd *.vtk *.vti *.hdr *.png *.tiff *.jpg *.hdr *.bmp *.dcm *.gipl *.nii *.nrrd *.spr *.lsm)" const char* mitk::CoreObjectFactory::GetFileExtensions() { return EXTERNAL_FILE_EXTENSIONS; }; const char* mitk::CoreObjectFactory::GetSaveFileExtensions() { return SAVE_FILE_EXTENSIONS; }; mitk::CoreObjectFactory::FileWriterList mitk::CoreObjectFactory::GetFileWriters() { return m_FileWriters; } void mitk::CoreObjectFactory::MapEvent(const mitk::Event*, const int) { } <|endoftext|>
<commit_before>// Copyright (C) 2011, 2012 Strahinja Val Markovic <val@markovic.io> // // This file is part of YouCompleteMe. // // YouCompleteMe 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. // // YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. #include "Result.h" #include "standard.h" #include "Utils.h" #include <boost/algorithm/string.hpp> #include <algorithm> using boost::algorithm::istarts_with; namespace YouCompleteMe { namespace { int LongestCommonSubsequenceLength(const std::string &first, const std::string &second) { const std::string &longer = first.size() > second.size() ? first : second; const std::string &shorter = first.size() > second.size() ? second : first; int longer_len = longer.size(); int shorter_len = shorter.size(); std::vector<int> previous( shorter_len + 1, 0 ); std::vector<int> current( shorter_len + 1, 0 ); for (int i = 0; i < longer_len; ++i ) { for (int j = 0; j < shorter_len; ++j ) { if ( toupper( longer[ i ] ) == toupper( shorter[ j ] ) ) current[ j + 1 ] = previous[ j ] + 1; else current[ j + 1 ] = std::max( current[ j ], previous[ j + 1 ] ); } for (int j = 0; j < shorter_len; ++j ) { previous[ j + 1 ] = current[ j + 1 ]; } } return current[ shorter_len ]; } int NumWordBoundaryCharMatches( const std::string &query, const std::string &word_boundary_chars ) { return LongestCommonSubsequenceLength(query, word_boundary_chars); } } // unnamed namespace Result::Result( bool is_subsequence ) : is_subsequence_( is_subsequence ), first_char_same_in_query_and_text_( false ), ratio_of_word_boundary_chars_in_query_( 0 ), word_boundary_char_utilization_( 0 ), query_is_candidate_prefix_( false ), text_is_lowercase_( false ), char_match_index_sum_( 0 ), text_( NULL ) { } Result::Result( bool is_subsequence, const std::string *text, bool text_is_lowercase, int char_match_index_sum, const std::string &word_boundary_chars, const std::string &query ) : is_subsequence_( is_subsequence ), first_char_same_in_query_and_text_( false ), ratio_of_word_boundary_chars_in_query_( 0 ), word_boundary_char_utilization_( 0 ), query_is_candidate_prefix_( false ), text_is_lowercase_( text_is_lowercase ), char_match_index_sum_( char_match_index_sum ), text_( text ) { if ( is_subsequence ) SetResultFeaturesFromQuery( word_boundary_chars, query ); } // TODO: do we need a custom copy ctor? Result::Result( const Result& other ) : is_subsequence_( other.is_subsequence_ ), first_char_same_in_query_and_text_( other.first_char_same_in_query_and_text_ ), ratio_of_word_boundary_chars_in_query_( other.ratio_of_word_boundary_chars_in_query_ ), word_boundary_char_utilization_( other.word_boundary_char_utilization_ ), query_is_candidate_prefix_( other.query_is_candidate_prefix_ ), text_is_lowercase_( other.text_is_lowercase_ ), char_match_index_sum_( other.char_match_index_sum_ ), text_( other.text_ ) { } bool Result::operator< ( const Result &other ) const { // Yes, this is ugly but it also needs to be fast. Since this is called a // bazillion times, we have to make sure only the required comparisons are // made, and no more. if ( first_char_same_in_query_and_text_ != other.first_char_same_in_query_and_text_ ) { return first_char_same_in_query_and_text_; } bool equal_wb_ratios = AlmostEqual( ratio_of_word_boundary_chars_in_query_, other.ratio_of_word_boundary_chars_in_query_ ); bool equal_wb_utilization = AlmostEqual( word_boundary_char_utilization_, other.word_boundary_char_utilization_ ); if ( AlmostEqual( ratio_of_word_boundary_chars_in_query_, 1.0 ) || AlmostEqual( other.ratio_of_word_boundary_chars_in_query_, 1.0 ) ) { if ( !equal_wb_ratios ) { return ratio_of_word_boundary_chars_in_query_ > other.ratio_of_word_boundary_chars_in_query_; } else { if ( !equal_wb_utilization ) return word_boundary_char_utilization_ > other.word_boundary_char_utilization_; } } if ( query_is_candidate_prefix_ != other.query_is_candidate_prefix_ ) return query_is_candidate_prefix_; if ( !equal_wb_ratios ) { return ratio_of_word_boundary_chars_in_query_ > other.ratio_of_word_boundary_chars_in_query_; } else { if ( !equal_wb_utilization ) return word_boundary_char_utilization_ > other.word_boundary_char_utilization_; } if ( char_match_index_sum_ != other.char_match_index_sum_ ) return char_match_index_sum_ < other.char_match_index_sum_; if ( text_->length() != other.text_->length() ) return text_->length() < other.text_->length(); if ( text_is_lowercase_ != other.text_is_lowercase_ ) return text_is_lowercase_; return *text_ < *other.text_; } void Result::SetResultFeaturesFromQuery( const std::string &word_boundary_chars, const std::string &query) { if ( query.empty() || text_->empty() ) return; first_char_same_in_query_and_text_ = toupper( query[ 0 ] ) == toupper( (*text_)[ 0 ] ); int num_wb_matches = NumWordBoundaryCharMatches( query, word_boundary_chars ); ratio_of_word_boundary_chars_in_query_ = num_wb_matches / static_cast< double >( query.length() ); word_boundary_char_utilization_ = num_wb_matches / static_cast< double >( word_boundary_chars.length() ); query_is_candidate_prefix_ = istarts_with( *text_, query ); } } // namespace YouCompleteMe <commit_msg>Whitespace fix<commit_after>// Copyright (C) 2011, 2012 Strahinja Val Markovic <val@markovic.io> // // This file is part of YouCompleteMe. // // YouCompleteMe 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. // // YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. #include "Result.h" #include "standard.h" #include "Utils.h" #include <boost/algorithm/string.hpp> #include <algorithm> using boost::algorithm::istarts_with; namespace YouCompleteMe { namespace { int LongestCommonSubsequenceLength( const std::string &first, const std::string &second ) { const std::string &longer = first.size() > second.size() ? first : second; const std::string &shorter = first.size() > second.size() ? second : first; int longer_len = longer.size(); int shorter_len = shorter.size(); std::vector<int> previous( shorter_len + 1, 0 ); std::vector<int> current( shorter_len + 1, 0 ); for (int i = 0; i < longer_len; ++i ) { for (int j = 0; j < shorter_len; ++j ) { if ( toupper( longer[ i ] ) == toupper( shorter[ j ] ) ) current[ j + 1 ] = previous[ j ] + 1; else current[ j + 1 ] = std::max( current[ j ], previous[ j + 1 ] ); } for (int j = 0; j < shorter_len; ++j ) { previous[ j + 1 ] = current[ j + 1 ]; } } return current[ shorter_len ]; } int NumWordBoundaryCharMatches( const std::string &query, const std::string &word_boundary_chars ) { return LongestCommonSubsequenceLength(query, word_boundary_chars); } } // unnamed namespace Result::Result( bool is_subsequence ) : is_subsequence_( is_subsequence ), first_char_same_in_query_and_text_( false ), ratio_of_word_boundary_chars_in_query_( 0 ), word_boundary_char_utilization_( 0 ), query_is_candidate_prefix_( false ), text_is_lowercase_( false ), char_match_index_sum_( 0 ), text_( NULL ) { } Result::Result( bool is_subsequence, const std::string *text, bool text_is_lowercase, int char_match_index_sum, const std::string &word_boundary_chars, const std::string &query ) : is_subsequence_( is_subsequence ), first_char_same_in_query_and_text_( false ), ratio_of_word_boundary_chars_in_query_( 0 ), word_boundary_char_utilization_( 0 ), query_is_candidate_prefix_( false ), text_is_lowercase_( text_is_lowercase ), char_match_index_sum_( char_match_index_sum ), text_( text ) { if ( is_subsequence ) SetResultFeaturesFromQuery( word_boundary_chars, query ); } // TODO: do we need a custom copy ctor? Result::Result( const Result& other ) : is_subsequence_( other.is_subsequence_ ), first_char_same_in_query_and_text_( other.first_char_same_in_query_and_text_ ), ratio_of_word_boundary_chars_in_query_( other.ratio_of_word_boundary_chars_in_query_ ), word_boundary_char_utilization_( other.word_boundary_char_utilization_ ), query_is_candidate_prefix_( other.query_is_candidate_prefix_ ), text_is_lowercase_( other.text_is_lowercase_ ), char_match_index_sum_( other.char_match_index_sum_ ), text_( other.text_ ) { } bool Result::operator< ( const Result &other ) const { // Yes, this is ugly but it also needs to be fast. Since this is called a // bazillion times, we have to make sure only the required comparisons are // made, and no more. if ( first_char_same_in_query_and_text_ != other.first_char_same_in_query_and_text_ ) { return first_char_same_in_query_and_text_; } bool equal_wb_ratios = AlmostEqual( ratio_of_word_boundary_chars_in_query_, other.ratio_of_word_boundary_chars_in_query_ ); bool equal_wb_utilization = AlmostEqual( word_boundary_char_utilization_, other.word_boundary_char_utilization_ ); if ( AlmostEqual( ratio_of_word_boundary_chars_in_query_, 1.0 ) || AlmostEqual( other.ratio_of_word_boundary_chars_in_query_, 1.0 ) ) { if ( !equal_wb_ratios ) { return ratio_of_word_boundary_chars_in_query_ > other.ratio_of_word_boundary_chars_in_query_; } else { if ( !equal_wb_utilization ) return word_boundary_char_utilization_ > other.word_boundary_char_utilization_; } } if ( query_is_candidate_prefix_ != other.query_is_candidate_prefix_ ) return query_is_candidate_prefix_; if ( !equal_wb_ratios ) { return ratio_of_word_boundary_chars_in_query_ > other.ratio_of_word_boundary_chars_in_query_; } else { if ( !equal_wb_utilization ) return word_boundary_char_utilization_ > other.word_boundary_char_utilization_; } if ( char_match_index_sum_ != other.char_match_index_sum_ ) return char_match_index_sum_ < other.char_match_index_sum_; if ( text_->length() != other.text_->length() ) return text_->length() < other.text_->length(); if ( text_is_lowercase_ != other.text_is_lowercase_ ) return text_is_lowercase_; return *text_ < *other.text_; } void Result::SetResultFeaturesFromQuery( const std::string &word_boundary_chars, const std::string &query) { if ( query.empty() || text_->empty() ) return; first_char_same_in_query_and_text_ = toupper( query[ 0 ] ) == toupper( (*text_)[ 0 ] ); int num_wb_matches = NumWordBoundaryCharMatches( query, word_boundary_chars ); ratio_of_word_boundary_chars_in_query_ = num_wb_matches / static_cast< double >( query.length() ); word_boundary_char_utilization_ = num_wb_matches / static_cast< double >( word_boundary_chars.length() ); query_is_candidate_prefix_ = istarts_with( *text_, query ); } } // namespace YouCompleteMe <|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. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #ifndef CQL3_ATTRIBUTES_HH #define CQL3_ATTRIBUTES_HH #include "exceptions/exceptions.hh" #include "db/expiring_cell.hh" #include "cql3/term.hh" #include <experimental/optional> namespace cql3 { /** * Utility class for the Parser to gather attributes for modification * statements. */ class attributes final { private: const std::experimental::optional<::shared_ptr<term>> _timestamp; const std::experimental::optional<::shared_ptr<term>> _time_to_live; public: static std::unique_ptr<attributes> none() { return std::unique_ptr<attributes>{new attributes{std::move(std::experimental::optional<::shared_ptr<term>>{}), std::move(std::experimental::optional<::shared_ptr<term>>{})}}; } private: attributes(std::experimental::optional<::shared_ptr<term>>&& timestamp, std::experimental::optional<::shared_ptr<term>>&& time_to_live) : _timestamp{std::move(timestamp)} , _time_to_live{std::move(time_to_live)} { } public: bool uses_function(const sstring& ks_name, const sstring& function_name) const { return (_timestamp && _timestamp.value()->uses_function(ks_name, function_name)) || (_time_to_live && _time_to_live.value()->uses_function(ks_name, function_name)); } bool is_timestamp_set() const { return bool(_timestamp); } bool is_time_to_live_set() const { return bool(_time_to_live); } int64_t get_timestamp(int64_t now, const query_options& options) { if (!_timestamp) { return now; } bytes_opt tval = _timestamp.value()->bind_and_get(options); if (!tval) { throw exceptions::invalid_request_exception("Invalid null value of timestamp"); } try { data_type_for<int64_t>()->validate(*tval); } catch (exceptions::marshal_exception e) { throw exceptions::invalid_request_exception("Invalid timestamp value"); } return boost::any_cast<int64_t>(data_type_for<int64_t>()->compose(*tval)); } int32_t get_time_to_live(const query_options& options) { if (!_time_to_live) return 0; bytes_opt tval = _time_to_live.value()->bind_and_get(options); if (!tval) { throw exceptions::invalid_request_exception("Invalid null value of TTL"); } try { data_type_for<int32_t>()->validate(*tval); } catch (exceptions::marshal_exception e) { throw exceptions::invalid_request_exception("Invalid TTL value"); } auto ttl = boost::any_cast<int32_t>(data_type_for<int32_t>()->compose(*tval)); if (ttl < 0) { throw exceptions::invalid_request_exception("A TTL must be greater or equal to 0"); } if (ttl > db::expiring_cell::MAX_TTL) { throw exceptions::invalid_request_exception("ttl is too large. requested (" + std::to_string(ttl) +") maximum (" + std::to_string(db::expiring_cell::MAX_TTL) + ")"); } return ttl; } void collect_marker_specification(::shared_ptr<variable_specifications> bound_names) { if (_timestamp) { _timestamp.value()->collect_marker_specification(bound_names); } if (_time_to_live) { _time_to_live.value()->collect_marker_specification(bound_names); } } class raw { public: ::shared_ptr<term::raw> timestamp; ::shared_ptr<term::raw> time_to_live; std::unique_ptr<attributes> prepare(const sstring& ks_name, const sstring& cf_name) { auto ts = !timestamp ? ::shared_ptr<term>{} : timestamp->prepare(ks_name, timestamp_receiver(ks_name, cf_name)); auto ttl = !time_to_live ? ::shared_ptr<term>{} : time_to_live->prepare(ks_name, time_to_live_receiver(ks_name, cf_name)); return std::unique_ptr<attributes>{new attributes{std::move(ts), std::move(ttl)}}; } private: ::shared_ptr<column_specification> timestamp_receiver(const sstring& ks_name, const sstring& cf_name) { return ::make_shared<column_specification>(ks_name, cf_name, ::make_shared<column_identifier>("[timestamp]", true), data_type_for<int64_t>()); } ::shared_ptr<column_specification> time_to_live_receiver(const sstring& ks_name, const sstring& cf_name) { return ::make_shared<column_specification>(ks_name, cf_name, ::make_shared<column_identifier>("[ttl]", true), data_type_for<int32_t>()); } }; }; } #endif <commit_msg>cql3: Drop redundant optional<> around shared_ptr<><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. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #ifndef CQL3_ATTRIBUTES_HH #define CQL3_ATTRIBUTES_HH #include "exceptions/exceptions.hh" #include "db/expiring_cell.hh" #include "cql3/term.hh" #include <experimental/optional> namespace cql3 { /** * Utility class for the Parser to gather attributes for modification * statements. */ class attributes final { private: const ::shared_ptr<term> _timestamp; const ::shared_ptr<term> _time_to_live; public: static std::unique_ptr<attributes> none() { return std::unique_ptr<attributes>{new attributes{{}, {}}}; } private: attributes(::shared_ptr<term>&& timestamp, ::shared_ptr<term>&& time_to_live) : _timestamp{std::move(timestamp)} , _time_to_live{std::move(time_to_live)} { } public: bool uses_function(const sstring& ks_name, const sstring& function_name) const { return (_timestamp && _timestamp->uses_function(ks_name, function_name)) || (_time_to_live && _time_to_live->uses_function(ks_name, function_name)); } bool is_timestamp_set() const { return bool(_timestamp); } bool is_time_to_live_set() const { return bool(_time_to_live); } int64_t get_timestamp(int64_t now, const query_options& options) { if (!_timestamp) { return now; } bytes_opt tval = _timestamp->bind_and_get(options); if (!tval) { throw exceptions::invalid_request_exception("Invalid null value of timestamp"); } try { data_type_for<int64_t>()->validate(*tval); } catch (exceptions::marshal_exception e) { throw exceptions::invalid_request_exception("Invalid timestamp value"); } return boost::any_cast<int64_t>(data_type_for<int64_t>()->compose(*tval)); } int32_t get_time_to_live(const query_options& options) { if (!_time_to_live) return 0; bytes_opt tval = _time_to_live->bind_and_get(options); if (!tval) { throw exceptions::invalid_request_exception("Invalid null value of TTL"); } try { data_type_for<int32_t>()->validate(*tval); } catch (exceptions::marshal_exception e) { throw exceptions::invalid_request_exception("Invalid TTL value"); } auto ttl = boost::any_cast<int32_t>(data_type_for<int32_t>()->compose(*tval)); if (ttl < 0) { throw exceptions::invalid_request_exception("A TTL must be greater or equal to 0"); } if (ttl > db::expiring_cell::MAX_TTL) { throw exceptions::invalid_request_exception("ttl is too large. requested (" + std::to_string(ttl) +") maximum (" + std::to_string(db::expiring_cell::MAX_TTL) + ")"); } return ttl; } void collect_marker_specification(::shared_ptr<variable_specifications> bound_names) { if (_timestamp) { _timestamp->collect_marker_specification(bound_names); } if (_time_to_live) { _time_to_live->collect_marker_specification(bound_names); } } class raw { public: ::shared_ptr<term::raw> timestamp; ::shared_ptr<term::raw> time_to_live; std::unique_ptr<attributes> prepare(const sstring& ks_name, const sstring& cf_name) { auto ts = !timestamp ? ::shared_ptr<term>{} : timestamp->prepare(ks_name, timestamp_receiver(ks_name, cf_name)); auto ttl = !time_to_live ? ::shared_ptr<term>{} : time_to_live->prepare(ks_name, time_to_live_receiver(ks_name, cf_name)); return std::unique_ptr<attributes>{new attributes{std::move(ts), std::move(ttl)}}; } private: ::shared_ptr<column_specification> timestamp_receiver(const sstring& ks_name, const sstring& cf_name) { return ::make_shared<column_specification>(ks_name, cf_name, ::make_shared<column_identifier>("[timestamp]", true), data_type_for<int64_t>()); } ::shared_ptr<column_specification> time_to_live_receiver(const sstring& ks_name, const sstring& cf_name) { return ::make_shared<column_specification>(ks_name, cf_name, ::make_shared<column_identifier>("[ttl]", true), data_type_for<int32_t>()); } }; }; } #endif <|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 Qt Mobility Components. ** ** $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 <QtTest/QtTest> #include "testhelper.h" #include "qgeomapobject.h" #include "qgraphicsgeomap.h" #include "qgeocoordinate.h" #include <QGraphicsRectItem> #include <QPointer> #include <QGraphicsTextItem> #include <QGraphicsEllipseItem> #include <QSignalSpy> QTM_USE_NAMESPACE Q_DECLARE_METATYPE(QGeoCoordinate) class tst_QGeoMapObject : public QObject { Q_OBJECT private slots: void initTestCase(); void init(); void cleanup(); // basic property tests void holdsGraphicsItem(); void ownsGraphicsItem(); void type(); void holdsVisible(); void holdsOrigin(); private: TestHelper *m_helper; }; void tst_QGeoMapObject::initTestCase() { qRegisterMetaType<QGeoCoordinate>(); } void tst_QGeoMapObject::init() { m_helper = new TestHelper(); QGraphicsGeoMap *map = m_helper->map(); if (!map) QFAIL("Could not create map!"); } void tst_QGeoMapObject::cleanup() { delete m_helper; m_helper = 0; } void tst_QGeoMapObject::ownsGraphicsItem() { QPointer<QGeoMapObject> obj = new QGeoMapObject; QPointer<QGraphicsTextItem> ri = new QGraphicsTextItem; obj->setGraphicsItem(ri); delete obj; QVERIFY(!ri); } void tst_QGeoMapObject::holdsGraphicsItem() { QGeoMapObject *obj = new QGeoMapObject; QVERIFY(!obj->graphicsItem()); QSignalSpy spy(obj, SIGNAL(graphicsItemChanged(QGraphicsItem*))); QGraphicsRectItem *ri = new QGraphicsRectItem; obj->setGraphicsItem(ri); QVERIFY(spy.count() == 1); QVERIFY(obj->graphicsItem() == ri); obj->setGraphicsItem(0); delete ri; delete obj; } void tst_QGeoMapObject::type() { QGeoMapObject *obj = new QGeoMapObject; QCOMPARE(obj->type(), QGeoMapObject::NullType); QGraphicsRectItem *ri = new QGraphicsRectItem; obj->setGraphicsItem(ri); QCOMPARE(obj->type(), QGeoMapObject::CustomType); obj->setGraphicsItem(0); delete ri; delete obj; } void tst_QGeoMapObject::holdsVisible() { QGeoMapObject *obj = new QGeoMapObject; QVERIFY(obj->isVisible()); QSignalSpy spy(obj, SIGNAL(visibleChanged(bool))); obj->setVisible(true); QCOMPARE(spy.count(), 0); obj->setVisible(false); QCOMPARE(spy.count(), 1); QVERIFY(!obj->isVisible()); delete obj; } void tst_QGeoMapObject::holdsOrigin() { QGeoMapObject *obj = new QGeoMapObject; QCOMPARE(obj->origin(), QGeoCoordinate()); QSignalSpy spy(obj, SIGNAL(originChanged(QGeoCoordinate))); QGeoCoordinate c(10, 5); obj->setOrigin(c); QCOMPARE(spy.count(), 1); QCOMPARE(obj->origin(), c); delete obj; } QTEST_MAIN(tst_QGeoMapObject) #include "tst_qgeomapobject.moc" <commit_msg>Some new visual and inspection auto-tests for maps graphicsitems<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 Qt Mobility Components. ** ** $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 <QtTest/QtTest> #include "testhelper.h" #include "qgeomapobject.h" #include "qgraphicsgeomap.h" #include "qgeocoordinate.h" #include <QGraphicsRectItem> #include <QPointer> #include <QGraphicsTextItem> #include <QGraphicsEllipseItem> #include <QSignalSpy> #include <QStyleOptionGraphicsItem> QTM_USE_NAMESPACE Q_DECLARE_METATYPE(QGeoCoordinate) class tst_QGeoMapObject : public QObject { Q_OBJECT private slots: void initTestCase(); void init(); void cleanup(); // basic property tests void holdsGraphicsItem(); void ownsGraphicsItem(); void type(); void holdsVisible(); void holdsOrigin(); void addToMap(); void drawsPixelEllipse(); void findsPixelEllipse(); void drawsBilinearEllipse(); void drawsExactEllipse(); private: TestHelper *m_helper; }; void tst_QGeoMapObject::initTestCase() { qRegisterMetaType<QGeoCoordinate>(); } void tst_QGeoMapObject::init() { m_helper = new TestHelper(); QGraphicsGeoMap *map = m_helper->map(); if (!map) QFAIL("Could not create map!"); } void tst_QGeoMapObject::cleanup() { delete m_helper; m_helper = 0; } void tst_QGeoMapObject::ownsGraphicsItem() { QPointer<QGeoMapObject> obj = new QGeoMapObject; QPointer<QGraphicsTextItem> ri = new QGraphicsTextItem; obj->setGraphicsItem(ri); delete obj; QVERIFY(!ri); } void tst_QGeoMapObject::holdsGraphicsItem() { QGeoMapObject *obj = new QGeoMapObject; QVERIFY(!obj->graphicsItem()); QSignalSpy spy(obj, SIGNAL(graphicsItemChanged(QGraphicsItem*))); QGraphicsRectItem *ri = new QGraphicsRectItem; obj->setGraphicsItem(ri); QVERIFY(spy.count() == 1); QVERIFY(obj->graphicsItem() == ri); obj->setGraphicsItem(0); delete ri; delete obj; } void tst_QGeoMapObject::addToMap() { // verify that you can add a blank QGeoMapObject // with no crashes QGeoMapObject *obj = new QGeoMapObject; QVERIFY(!obj->mapData()); m_helper->map()->addMapObject(obj); QVERIFY(obj->mapData()); QList<QGeoMapObject*> objs = m_helper->map()->mapObjects(); QVERIFY(objs.contains(obj)); QPixmap px(300, 300); QPainter p(&px); QStyleOptionGraphicsItem style; style.rect = QRect(0,0,300,300); m_helper->map()->paint(&p, &style, 0); m_helper->map()->removeMapObject(obj); delete obj; } #define verifyRgb(rgb,red,green,blue) \ QCOMPARE(qRed(rgb), red); \ QCOMPARE(qGreen(rgb), green); \ QCOMPARE(qBlue(rgb), blue); #define verifyNotRgb(rgb,red,green,blue) \ QVERIFY(qRed(rgb) != red); \ QVERIFY(qGreen(rgb) != green); \ QVERIFY(qBlue(rgb) != blue); static int centredEllipseRadius(const QPixmap &pxmap) { QImage im = pxmap.toImage(); QRgb center = im.pixel(150, 150); int r = 1; while (r < 300) { QRgb pxs[4]; pxs[0] = im.pixel(150+r, 150); pxs[1] = im.pixel(150-r, 150); pxs[2] = im.pixel(150, 150+r); pxs[3] = im.pixel(150, 150-r); int i = 0; for (; i <3; i++) if (pxs[i] != center) break; if (pxs[i] != center) break; r++; } return r; } void tst_QGeoMapObject::findsPixelEllipse() { QGeoMapObject *obj = new QGeoMapObject; QGraphicsEllipseItem *el = new QGraphicsEllipseItem; el->setRect(-10, -10, 20, 20); el->setBrush(QBrush(Qt::black)); obj->setGraphicsItem(el); obj->setOrigin(QGeoCoordinate(0, 0)); QCOMPARE(obj->units(), QGeoMapObject::PixelUnit); QCOMPARE(obj->transformType(), QGeoMapObject::ExactTransform); m_helper->map()->setCenter(QGeoCoordinate(0, 0)); m_helper->map()->resize(300, 300); QList<QGeoMapObject*> list; list = m_helper->map()->mapObjectsAtScreenPosition(QPointF(150, 150)); QCOMPARE(list.size(), 0); m_helper->map()->addMapObject(obj); QTest::qWait(10); QList<QPointF> testPoints; testPoints << QPointF(150, 150) << QPointF(141, 150) << QPointF(150, 159) << QPointF(145, 145); foreach (QPointF tp, testPoints) { list = m_helper->map()->mapObjectsAtScreenPosition(tp); QCOMPARE(list.size(), 1); QVERIFY(list.contains(obj)); } testPoints.clear(); testPoints << QPointF(150, 161) << QPointF(139, 150) << QPointF(158, 158); foreach (QPointF tp, testPoints) { list = m_helper->map()->mapObjectsAtScreenPosition(tp); QCOMPARE(list.size(), 0); } } void tst_QGeoMapObject::drawsPixelEllipse() { QGeoMapObject *obj = new QGeoMapObject; QGraphicsEllipseItem *el = new QGraphicsEllipseItem; el->setRect(-10, -10, 20, 20); el->setBrush(QBrush(Qt::black)); obj->setGraphicsItem(el); obj->setOrigin(QGeoCoordinate(0, 0)); QCOMPARE(obj->units(), QGeoMapObject::PixelUnit); QCOMPARE(obj->transformType(), QGeoMapObject::ExactTransform); m_helper->map()->setCenter(QGeoCoordinate(0, 0)); m_helper->map()->resize(300, 300); QPixmap px(300, 300); QPainter p(&px); QStyleOptionGraphicsItem style; style.rect = QRect(0,0,300,300); m_helper->map()->paint(&p, &style, 0); QImage im = px.toImage(); QRgb pixel = im.pixel(150,150); verifyNotRgb(pixel, 0, 0, 0); m_helper->map()->addMapObject(obj); QTest::qWait(10); QPixmap px2(300, 300); QPainter p2(&px2); m_helper->map()->paint(&p2, &style, 0); QImage im2 = px2.toImage(); verifyRgb(im2.pixel(150, 150), 0, 0, 0); // avoid the last pixel due to antialiasing verifyRgb(im2.pixel(141, 150), 0, 0, 0); verifyRgb(im2.pixel(150, 158), 0, 0, 0); verifyRgb(im2.pixel(145, 145), 0, 0, 0); verifyNotRgb(im2.pixel(150, 161), 0, 0, 0); verifyNotRgb(im2.pixel(139, 150), 0, 0, 0); verifyNotRgb(im2.pixel(157, 157), 0, 0, 0); int r = centredEllipseRadius(px2); QVERIFY(r >= 9 && r <= 11); m_helper->map()->removeMapObject(obj); delete obj; } void tst_QGeoMapObject::drawsBilinearEllipse() { QGeoMapObject *obj = new QGeoMapObject; QGraphicsEllipseItem *el = new QGraphicsEllipseItem; el->setRect(-100, -100, 200, 200); el->setBrush(QBrush(Qt::black)); obj->setGraphicsItem(el); obj->setOrigin(QGeoCoordinate(0, 0)); obj->setUnits(QGeoMapObject::MeterUnit); QCOMPARE(obj->transformType(), QGeoMapObject::BilinearTransform); m_helper->map()->setCenter(QGeoCoordinate(0, 0)); m_helper->map()->setZoomLevel(15.0); m_helper->map()->resize(300, 300); m_helper->map()->addMapObject(obj); QTest::qWait(10); QPixmap *px[2]; QPainter *p[2]; for (int i=0; i < 2; i++) { px[i] = new QPixmap(300, 300); p[i] = new QPainter(px[i]); } QStyleOptionGraphicsItem style; style.rect = QRect(0,0,300,300); m_helper->map()->paint(p[0], &style, 0); int r15 = centredEllipseRadius(*px[0]); m_helper->map()->setZoomLevel(14.0); QTest::qWait(10); m_helper->map()->paint(p[1], &style, 0); int r14 = centredEllipseRadius(*px[1]); QVERIFY(r15 > r14); QVERIFY(r15 - r14 > 2); for (int i=0; i < 2; i++) { delete p[i]; delete px[i]; } } void tst_QGeoMapObject::drawsExactEllipse() { QGeoMapObject *obj = new QGeoMapObject; QGraphicsEllipseItem *el = new QGraphicsEllipseItem; el->setRect(-100, -100, 200, 200); el->setBrush(QBrush(Qt::black)); obj->setGraphicsItem(el); obj->setOrigin(QGeoCoordinate(0, 0)); obj->setUnits(QGeoMapObject::MeterUnit); QCOMPARE(obj->transformType(), QGeoMapObject::BilinearTransform); m_helper->map()->setCenter(QGeoCoordinate(0, 0)); m_helper->map()->setZoomLevel(13.0); m_helper->map()->resize(300, 300); m_helper->map()->addMapObject(obj); QTest::qWait(10); QPixmap *px[4]; QPainter *p[4]; for (int i=0; i < 4; i++) { px[i] = new QPixmap(300, 300); p[i] = new QPainter(px[i]); } QStyleOptionGraphicsItem style; style.rect = QRect(0,0,3000,3000); m_helper->map()->paint(p[0], &style, 0); int r13 = centredEllipseRadius(*px[0]); m_helper->map()->setZoomLevel(12.0); QTest::qWait(10); m_helper->map()->paint(p[1], &style, 0); int r12 = centredEllipseRadius(*px[1]); obj->setTransformType(QGeoMapObject::ExactTransform); QCOMPARE(obj->transformType(), QGeoMapObject::ExactTransform); QTest::qWait(10); m_helper->map()->setZoomLevel(13.0); QTest::qWait(10); m_helper->map()->paint(p[2], &style, 0); int r13_ex = centredEllipseRadius(*px[2]); m_helper->map()->setZoomLevel(12.0); QTest::qWait(10); m_helper->map()->paint(p[3], &style, 0); int r12_ex = centredEllipseRadius(*px[3]); QVERIFY(r13_ex - r13 <= 1 && r13 - r13_ex <= 1); QVERIFY(r12_ex - r12 <= 1 && r12 - r12_ex <= 1); for (int i=0; i < 4; i++) { delete p[i]; delete px[i]; } } void tst_QGeoMapObject::type() { QGeoMapObject *obj = new QGeoMapObject; QCOMPARE(obj->type(), QGeoMapObject::NullType); QGraphicsRectItem *ri = new QGraphicsRectItem; obj->setGraphicsItem(ri); QCOMPARE(obj->type(), QGeoMapObject::CustomType); obj->setGraphicsItem(0); delete ri; delete obj; } void tst_QGeoMapObject::holdsVisible() { QGeoMapObject *obj = new QGeoMapObject; QVERIFY(obj->isVisible()); QSignalSpy spy(obj, SIGNAL(visibleChanged(bool))); obj->setVisible(true); QCOMPARE(spy.count(), 0); obj->setVisible(false); QCOMPARE(spy.count(), 1); QVERIFY(!obj->isVisible()); delete obj; } void tst_QGeoMapObject::holdsOrigin() { QGeoMapObject *obj = new QGeoMapObject; QCOMPARE(obj->origin(), QGeoCoordinate()); QSignalSpy spy(obj, SIGNAL(originChanged(QGeoCoordinate))); QGeoCoordinate c(10, 5); obj->setOrigin(c); QCOMPARE(spy.count(), 1); QCOMPARE(obj->origin(), c); delete obj; } QTEST_MAIN(tst_QGeoMapObject) #include "tst_qgeomapobject.moc" <|endoftext|>
<commit_before>#include <QString> #include <QFileInfo> #include <QUrl> #include "kernel.h" #include "connectorinterface.h" #include "resource.h" #include "ilwisdata.h" #include "angle.h" #include "geometries.h" #include "ellipsoid.h" #include "projection.h" #include "proj4parameters.h" #include "ilwisobject.h" #include "mastercatalog.h" #include "resourcemodel.h" #define tempHardPath "h:/projects/Ilwis4/projects/client/qml/desktop/mobile/images/" //#define tempHardPath "d:/projects/ilwis/Ilwis4/projects/client/qml/desktop/mobile/images/" using namespace Ilwis; //using namespace Desktopclient; QString ResourceModel::getProperty(const QString &propertyname) const { if(_item.hasProperty(propertyname)) return _item[propertyname].toString(); return sUNDEF; } ResourceModel::ResourceModel() { } ResourceModel::ResourceModel(const Ilwis::Resource& source, QObject *parent) : QObject(parent), _imagePath(sUNDEF),_type(itUNKNOWN), _isRoot(false) { resource(source); } ResourceModel::ResourceModel(const ResourceModel &model) : QObject(model.parent()) { _displayName = model._displayName; _item = model._item; _imagePath = model._imagePath; _type = model._type; _isRoot = model._isRoot; _selected = model._selected; _is3d = model._is3d; } ResourceModel &ResourceModel::operator=(const ResourceModel &model) { _displayName = model._displayName; _item = model._item; _imagePath = model._imagePath; _type = model._type; _isRoot = model._isRoot; _selected = model._selected; _is3d = model._is3d; return *this; } ResourceModel::~ResourceModel() { } QString ResourceModel::imagePath() const { return _imagePath; } quint64 ResourceModel::type() const { return _type; } QString ResourceModel::typeName() const { return TypeHelper::type2name(_type); } QString ResourceModel::name() const { if ( _item.isValid()) { return _item.name(); } return ""; } QString ResourceModel::size() const { if ( _item.isValid() && _item.ilwisType() != itCATALOG){ quint64 sz = _item.size(); if ( sz != 0) return QString::number(sz); } return ""; } QString ResourceModel::description() const { if ( _item.isValid()) return _item.description(); return ""; } QString ResourceModel::dimensions() const { if ( _item.isValid()) return _item.dimensions(); return ""; } QString ResourceModel::displayName() const { return _displayName; } void ResourceModel::setDisplayName(const QString &name) { _displayName = name; _item.name(name, false); } QString ResourceModel::url() const { return _item.url().toString(); } QString ResourceModel::container() const { return _item.container().toString(); } QString ResourceModel::iconPath() const { if ( _iconPath != "") return _iconPath; quint64 tp = _item.ilwisType(); if ( hasType(_item.extendedType(), itCATALOG)){ return iconPath(tp | itCATALOG); } if ( hasType(_item.extendedType(), itFILE) && tp == itCATALOG) return iconPath(tp | itCOVERAGE); if ( hasType(_item.extendedType(), itTABLE) && tp == itCATALOG) return iconPath(tp | itTABLE); return iconPath(tp); } void ResourceModel::iconPath(const QString &name) { _iconPath = name; } QString ResourceModel::iconPath(IlwisTypes tp) { if ( tp == (itRASTER|itCATALOG)) return "raster203d.png"; if ( tp == (itTABLE|itCATALOG)) return "catalogTable20.png"; if ( tp == (itCOVERAGE|itCATALOG)) return "catalogSpatial20.png"; if ( tp & itRASTER) return "raster20CS1.png"; else if ( tp == itPOLYGON) return "polygon20CS1.png"; else if ( tp == itLINE) return "line20.png"; else if ( tp == itPOINT) return "point20.png"; else if ( hasType(tp, itFEATURE)) return "feature20CS1.png"; else if ( tp & itTABLE) return "table20CS1.png"; else if ( tp & itCOORDSYSTEM) return "csy20.png"; else if ( tp & itGEOREF) return "georeference20.png"; else if ( tp == itCATALOG) return "folder20.png"; else if ( tp & itDOMAIN) return "domain.png"; else if ( tp & itREPRESENTATION) return "representation20.png"; else if ( hasType(tp,itNUMBER)) return "numbers20.png"; else if ( hasType(tp,itBOOL)) return "bool20.png"; else if ( hasType(tp,itPROJECTION)) return "projection20.png"; else if ( hasType(tp,itELLIPSOID)) return "ellipsoid20.png"; else if ( tp & itSTRING) return "text20.png"; else if ( tp & itOPERATIONMETADATA) return "operation20.png"; else return "eye.png"; } bool ResourceModel::isRoot() const { return _isRoot; } QString ResourceModel::id() const { if ( _item.isValid()) return QString::number(_item.id()); return sUNDEF; } Resource ResourceModel::item() const { return _item; } QString ResourceModel::domainName() const { QString nme = propertyName("domain"); if ( nme != displayName() && nme != "") return nme; quint64 tp = _item.ilwisType(); if ( hasType(tp, itCOVERAGE)) return "self"; return ""; } QString ResourceModel::domainType() const { QString nme = propertyTypeName(itDOMAIN, "domain"); if ( nme != "") return nme; quint64 tp = _item.ilwisType(); if ( hasType(tp, itCOVERAGE)) return "IndexedIdentifier"; return ""; } QString ResourceModel::proj42DisplayName(const QString& proj4Def) const{ Proj4Parameters parms(proj4Def); QString projName = Projection::projectionCode2Name(parms["proj"]); QString ellipse = Ellipsoid::ellipsoidCode2Name(parms["proj"]); if ( ellipse == sUNDEF) return sUNDEF; return projName + "/" + ellipse; } QString ResourceModel::coordinateSystemName() const { QString proj = _item["projectionname"].toString(); if ( proj != sUNDEF) return proj; QString nme = propertyName("coordinatesystem"); if ( nme != displayName() && nme != "" && nme != sUNDEF) return nme; if ( nme == ""){ nme = _item["coordinatesystem"].toString(); if ( nme != sUNDEF){ int index = nme.toLower().indexOf("code="); if ( index == -1){ nme = _item.code(); } if ((index = nme.toLower().indexOf("code=epsg")) != -1){ nme = nme.mid(5); } else if ( (index = nme.toLower().indexOf("code=proj4")) != -1){ nme = proj42DisplayName(nme.mid(5)); }else { nme = Projection::projectionCode2Name(nme.mid(5)); } } } return nme != sUNDEF ? nme : ""; } QString ResourceModel::coordinateSystemType() const { QString txt = propertyTypeName(itCOORDSYSTEM, "coordinatesystem"); return txt.left(txt.size() - QString("CoordinateSystem").size()); } QString ResourceModel::geoReferenceName() const { QString nme = propertyName("georeference"); if ( nme != displayName()) return nme; return ""; } QString ResourceModel::geoReferenceType() const { return propertyTypeName(itGEOREF, "georeference"); } void ResourceModel::resource(const Ilwis::Resource& res) { Resource item = res; if ( item.name() == sUNDEF) { QString name = res.url().toString(QUrl::RemoveScheme | QUrl::RemoveQuery | QUrl::RemovePassword | QUrl::StripTrailingSlash); name = name.mid(3); item.name(name, false); } _type = item.ilwisType(); _item = item; if ( hasType(item.ilwisType(), itCOVERAGE)){ QString dim = _item.dimensions(); _is3d = dim.split(" ").size() == 3; } if ( item.url().toString() == "file://"){ _displayName = "root"; _isRoot = true; } else if ( item.url().scheme() == "file") { QFileInfo inf(_item.url().toLocalFile()); QString path = inf.absolutePath(); _isRoot = inf.isRoot(); _displayName = item.name(); QFileInfo thumbPath = path + "/thumbs/" + _displayName + ".png"; if ( thumbPath.exists()) { _imagePath = "file:///" + thumbPath.absoluteFilePath(); } else { if ( item.ilwisType() == itCATALOG) { _imagePath = "catalog.png"; } if ( hasType(item.ilwisType(), itRASTER)) _imagePath = "remote.png"; else if ( hasType(item.ilwisType(), itFEATURE)) _imagePath = "polygon.png"; else if ( hasType(item.ilwisType(), itCOORDSYSTEM)) _imagePath = "csy.png"; else if ( hasType(item.ilwisType(), itGEOREF)) _imagePath = "grf.png"; else if ( hasType(item.ilwisType(), itTABLE)) _imagePath = "table.jpg"; else if ( hasType(item.ilwisType(), itDOMAIN)) _imagePath = "domainn.png"; else if ( hasType(item.ilwisType(), itREPRESENTATION)) _imagePath = "representation20.png"; else _imagePath = "blank.png"; } }else{ if ( item.hasProperty("longname")) _displayName = item["longname"].toString(); else _displayName = item.name(); } } Ilwis::Resource ResourceModel::resource() const { return _item; } Ilwis::Resource& ResourceModel::resourceRef() { return _item; } bool ResourceModel::isSelected() const { return _selected; } void ResourceModel::setIsSelected(bool yesno) { _selected = yesno; emit isSelectedChanged(); } QString ResourceModel::propertyName( const QString& property) const{ if ( _item.isValid()) { bool ok; quint64 iddomain = _item[property].toLongLong(&ok); if ( ok) { return Ilwis::mastercatalog()->id2Resource(iddomain).name(); } } return ""; } QString ResourceModel::propertyTypeName(quint64 typ, const QString& propertyName) const { if ( _item.isValid()) { if (_item.extendedType() & typ) { bool ok; quint64 idprop = _item[propertyName].toLongLong(&ok); if ( ok) { quint64 tp = Ilwis::mastercatalog()->id2Resource(idprop).ilwisType(); return Ilwis::IlwisObject::type2Name(tp); } } } return ""; } <commit_msg>added two new datatype --> icon conversions<commit_after>#include <QString> #include <QFileInfo> #include <QUrl> #include "kernel.h" #include "connectorinterface.h" #include "resource.h" #include "ilwisdata.h" #include "angle.h" #include "geometries.h" #include "ellipsoid.h" #include "projection.h" #include "proj4parameters.h" #include "ilwisobject.h" #include "mastercatalog.h" #include "resourcemodel.h" #define tempHardPath "h:/projects/Ilwis4/projects/client/qml/desktop/mobile/images/" //#define tempHardPath "d:/projects/ilwis/Ilwis4/projects/client/qml/desktop/mobile/images/" using namespace Ilwis; //using namespace Desktopclient; QString ResourceModel::getProperty(const QString &propertyname) const { if(_item.hasProperty(propertyname)) return _item[propertyname].toString(); return sUNDEF; } ResourceModel::ResourceModel() { } ResourceModel::ResourceModel(const Ilwis::Resource& source, QObject *parent) : QObject(parent), _imagePath(sUNDEF),_type(itUNKNOWN), _isRoot(false) { resource(source); } ResourceModel::ResourceModel(const ResourceModel &model) : QObject(model.parent()) { _displayName = model._displayName; _item = model._item; _imagePath = model._imagePath; _type = model._type; _isRoot = model._isRoot; _selected = model._selected; _is3d = model._is3d; } ResourceModel &ResourceModel::operator=(const ResourceModel &model) { _displayName = model._displayName; _item = model._item; _imagePath = model._imagePath; _type = model._type; _isRoot = model._isRoot; _selected = model._selected; _is3d = model._is3d; return *this; } ResourceModel::~ResourceModel() { } QString ResourceModel::imagePath() const { return _imagePath; } quint64 ResourceModel::type() const { return _type; } QString ResourceModel::typeName() const { return TypeHelper::type2name(_type); } QString ResourceModel::name() const { if ( _item.isValid()) { return _item.name(); } return ""; } QString ResourceModel::size() const { if ( _item.isValid() && _item.ilwisType() != itCATALOG){ quint64 sz = _item.size(); if ( sz != 0) return QString::number(sz); } return ""; } QString ResourceModel::description() const { if ( _item.isValid()) return _item.description(); return ""; } QString ResourceModel::dimensions() const { if ( _item.isValid()) return _item.dimensions(); return ""; } QString ResourceModel::displayName() const { return _displayName; } void ResourceModel::setDisplayName(const QString &name) { _displayName = name; _item.name(name, false); } QString ResourceModel::url() const { return _item.url().toString(); } QString ResourceModel::container() const { return _item.container().toString(); } QString ResourceModel::iconPath() const { if ( _iconPath != "") return _iconPath; quint64 tp = _item.ilwisType(); if ( hasType(_item.extendedType(), itCATALOG)){ return iconPath(tp | itCATALOG); } if ( hasType(_item.extendedType(), itFILE) && tp == itCATALOG) return iconPath(tp | itCOVERAGE); if ( hasType(_item.extendedType(), itTABLE) && tp == itCATALOG) return iconPath(tp | itTABLE); return iconPath(tp); } void ResourceModel::iconPath(const QString &name) { _iconPath = name; } QString ResourceModel::iconPath(IlwisTypes tp) { if ( tp == (itRASTER|itCATALOG)) return "raster203d.png"; if ( tp == (itTABLE|itCATALOG)) return "catalogTable20.png"; if ( tp == (itCOVERAGE|itCATALOG)) return "catalogSpatial20.png"; if ( tp & itRASTER) return "raster20CS1.png"; else if ( tp == itPOLYGON) return "polygon20CS1.png"; else if ( tp == itLINE) return "line20.png"; else if ( tp == itPOINT) return "point20.png"; else if ( hasType(tp, itFEATURE)) return "feature20CS1.png"; else if ( tp & itTABLE) return "table20CS1.png"; else if ( tp & itCOORDSYSTEM) return "csy20.png"; else if ( tp & itGEOREF) return "georeference20.png"; else if ( tp == itCATALOG) return "folder20.png"; else if ( tp & itDOMAIN) return "domain.png"; else if ( tp & itREPRESENTATION) return "representation20.png"; else if ( hasType(tp,itNUMBER)) return "numbers20.png"; else if ( hasType(tp,itBOOL)) return "bool20.png"; else if ( hasType(tp,itPROJECTION)) return "projection20.png"; else if ( hasType(tp,itELLIPSOID)) return "ellipsoid20.png"; else if ( tp & itSTRING) return "text20.png"; else if ( tp & itOPERATIONMETADATA) return "operation20.png"; else if ( tp & itCOORDINATE) return "coord20.png"; else if ( tp & itPIXEL) return "pixel20.png"; else return "eye.png"; } bool ResourceModel::isRoot() const { return _isRoot; } QString ResourceModel::id() const { if ( _item.isValid()) return QString::number(_item.id()); return sUNDEF; } Resource ResourceModel::item() const { return _item; } QString ResourceModel::domainName() const { QString nme = propertyName("domain"); if ( nme != displayName() && nme != "") return nme; quint64 tp = _item.ilwisType(); if ( hasType(tp, itCOVERAGE)) return "self"; return ""; } QString ResourceModel::domainType() const { QString nme = propertyTypeName(itDOMAIN, "domain"); if ( nme != "") return nme; quint64 tp = _item.ilwisType(); if ( hasType(tp, itCOVERAGE)) return "IndexedIdentifier"; return ""; } QString ResourceModel::proj42DisplayName(const QString& proj4Def) const{ Proj4Parameters parms(proj4Def); QString projName = Projection::projectionCode2Name(parms["proj"]); QString ellipse = Ellipsoid::ellipsoidCode2Name(parms["proj"]); if ( ellipse == sUNDEF) return sUNDEF; return projName + "/" + ellipse; } QString ResourceModel::coordinateSystemName() const { QString proj = _item["projectionname"].toString(); if ( proj != sUNDEF) return proj; QString nme = propertyName("coordinatesystem"); if ( nme != displayName() && nme != "" && nme != sUNDEF) return nme; if ( nme == ""){ nme = _item["coordinatesystem"].toString(); if ( nme != sUNDEF){ int index = nme.toLower().indexOf("code="); if ( index == -1){ nme = _item.code(); } if ((index = nme.toLower().indexOf("code=epsg")) != -1){ nme = nme.mid(5); } else if ( (index = nme.toLower().indexOf("code=proj4")) != -1){ nme = proj42DisplayName(nme.mid(5)); }else { nme = Projection::projectionCode2Name(nme.mid(5)); } } } return nme != sUNDEF ? nme : ""; } QString ResourceModel::coordinateSystemType() const { QString txt = propertyTypeName(itCOORDSYSTEM, "coordinatesystem"); return txt.left(txt.size() - QString("CoordinateSystem").size()); } QString ResourceModel::geoReferenceName() const { QString nme = propertyName("georeference"); if ( nme != displayName()) return nme; return ""; } QString ResourceModel::geoReferenceType() const { return propertyTypeName(itGEOREF, "georeference"); } void ResourceModel::resource(const Ilwis::Resource& res) { Resource item = res; if ( item.name() == sUNDEF) { QString name = res.url().toString(QUrl::RemoveScheme | QUrl::RemoveQuery | QUrl::RemovePassword | QUrl::StripTrailingSlash); name = name.mid(3); item.name(name, false); } _type = item.ilwisType(); _item = item; if ( hasType(item.ilwisType(), itCOVERAGE)){ QString dim = _item.dimensions(); _is3d = dim.split(" ").size() == 3; } if ( item.url().toString() == "file://"){ _displayName = "root"; _isRoot = true; } else if ( item.url().scheme() == "file") { QFileInfo inf(_item.url().toLocalFile()); QString path = inf.absolutePath(); _isRoot = inf.isRoot(); _displayName = item.name(); QFileInfo thumbPath = path + "/thumbs/" + _displayName + ".png"; if ( thumbPath.exists()) { _imagePath = "file:///" + thumbPath.absoluteFilePath(); } else { if ( item.ilwisType() == itCATALOG) { _imagePath = "catalog.png"; } if ( hasType(item.ilwisType(), itRASTER)) _imagePath = "remote.png"; else if ( hasType(item.ilwisType(), itFEATURE)) _imagePath = "polygon.png"; else if ( hasType(item.ilwisType(), itCOORDSYSTEM)) _imagePath = "csy.png"; else if ( hasType(item.ilwisType(), itGEOREF)) _imagePath = "grf.png"; else if ( hasType(item.ilwisType(), itTABLE)) _imagePath = "table.jpg"; else if ( hasType(item.ilwisType(), itDOMAIN)) _imagePath = "domainn.png"; else if ( hasType(item.ilwisType(), itREPRESENTATION)) _imagePath = "representation20.png"; else _imagePath = "blank.png"; } }else{ if ( item.hasProperty("longname")) _displayName = item["longname"].toString(); else _displayName = item.name(); } } Ilwis::Resource ResourceModel::resource() const { return _item; } Ilwis::Resource& ResourceModel::resourceRef() { return _item; } bool ResourceModel::isSelected() const { return _selected; } void ResourceModel::setIsSelected(bool yesno) { _selected = yesno; emit isSelectedChanged(); } QString ResourceModel::propertyName( const QString& property) const{ if ( _item.isValid()) { bool ok; quint64 iddomain = _item[property].toLongLong(&ok); if ( ok) { return Ilwis::mastercatalog()->id2Resource(iddomain).name(); } } return ""; } QString ResourceModel::propertyTypeName(quint64 typ, const QString& propertyName) const { if ( _item.isValid()) { if (_item.extendedType() & typ) { bool ok; quint64 idprop = _item[propertyName].toLongLong(&ok); if ( ok) { quint64 tp = Ilwis::mastercatalog()->id2Resource(idprop).ilwisType(); return Ilwis::IlwisObject::type2Name(tp); } } } return ""; } <|endoftext|>
<commit_before>#include <assert.h> #include <stdlib.h> #include <string.h> #include <string> #include <boost/regex.hpp> #include <sqlite3ext.h> SQLITE_EXTENSION_INIT1 /** Get a string argument from SQLite. It assumes you already know it's there. You can check that with argc() or trust SQLite to do that. */ const char *getSQLiteString( sqlite3_context *ctx, sqlite3_value *arg, const std::string& func, const std::string& name) { const char *value = (const char *) sqlite3_value_text(arg); if (value) { return value; } else { sqlite3_result_error(ctx, (func + "(): missing " + name).data(), -1); return NULL; } } extern "C" { /** * @brief Match a regular expression, giving a boolean. */ void match(sqlite3_context *ctx, int argc, sqlite3_value **argv) { const char *re = getSQLiteString(ctx, argv[0], "match", "regular expression"); const char *subject = getSQLiteString(ctx, argv[1], "match", "subject"); if (!re || !subject) return; // Catch all for regex errors and API cleanliness try { boost::regex regex(re); sqlite3_result_int(ctx, boost::regex_match(subject, regex)); } catch (const boost::regex_error& e) { sqlite3_result_error(ctx, e.what(), -1); } return; } /** * @brief Search a string with a regex. * * This differs from match. See Boost::regex for more information. */ void search(sqlite3_context *ctx, int argc, sqlite3_value **argv) { const char *re = getSQLiteString(ctx, argv[0], "search", "regular expression"); const char *subject = getSQLiteString(ctx, argv[1], "subject", "regular expression"); if (!re || !subject) return; // Catch all for regex errors and API cleanliness try { boost::regex regex(re); sqlite3_result_int(ctx, boost::regex_search(std::string(subject), regex)); } catch (const boost::regex_error& e) { sqlite3_result_error(ctx, e.what(), -1); } return; } /** * @brief Substitute regex matches with a formatted string. * For more information about the string format, see Boost::regex or the README. */ void sub(sqlite3_context *ctx, int argc, sqlite3_value **argv) { const char *re = getSQLiteString(ctx, argv[0], "sub", "regular expression"); const char *format = getSQLiteString(ctx, argv[1], "sub", "format string"); const char *subject = getSQLiteString(ctx, argv[2], "sub", "subject"); if (!re || !format || !subject) return; // Catch all for regex errors and API cleanliness try { boost::regex regex(re); std::string replaced = boost::regex_replace(std::string(subject), regex, format); sqlite3_result_text(ctx, replaced.data(), -1, SQLITE_TRANSIENT); } catch (const boost::regex_error& e) { sqlite3_result_error(ctx, e.what(), -1); } return; } int sqlite3_extension_init(sqlite3 *db, char **err, const sqlite3_api_routines *api) { SQLITE_EXTENSION_INIT2(api) sqlite3_create_function(db, "MATCH", 2, SQLITE_UTF8, SQLITE_DETERMINISTIC, match, NULL, NULL); sqlite3_create_function(db, "SEARCH", 2, SQLITE_UTF8, SQLITE_DETERMINISTIC, search, NULL, NULL); sqlite3_create_function(db, "SUB", 3, SQLITE_UTF8, SQLITE_DETERMINISTIC, sub, NULL, NULL); return 0; } } <commit_msg>Add some vector operations<commit_after>#include <assert.h> #include <stdlib.h> #include <string.h> #include <string> #include <sstream> #include <boost/regex.hpp> #include <sqlite3ext.h> SQLITE_EXTENSION_INIT1 /** Get a string argument from SQLite. It assumes you already know it's there. You can check that with argc() or trust SQLite to do that. */ const char *getSQLiteString( sqlite3_context *ctx, sqlite3_value *arg, const std::string& func, const std::string& name) { const char *value = (const char *) sqlite3_value_text(arg); if (value) { return value; } else { sqlite3_result_error(ctx, (func + "(): missing " + name).data(), -1); return NULL; } } extern "C" { /** * Regular Expressions **/ /** * @brief Match a regular expression, giving a boolean. */ void match(sqlite3_context *ctx, int argc, sqlite3_value **argv) { const char *re = getSQLiteString(ctx, argv[0], "match", "regular expression"); const char *subject = getSQLiteString(ctx, argv[1], "match", "subject"); if (!re || !subject) return; // Catch all for regex errors and API cleanliness try { boost::regex regex(re); sqlite3_result_int(ctx, boost::regex_match(subject, regex)); } catch (const boost::regex_error& e) { sqlite3_result_error(ctx, e.what(), -1); } return; } /** * @brief Search a string with a regex. * * This differs from match. See Boost::regex for more information. */ void search(sqlite3_context *ctx, int argc, sqlite3_value **argv) { const char *re = getSQLiteString(ctx, argv[0], "search", "regular expression"); const char *subject = getSQLiteString(ctx, argv[1], "subject", "regular expression"); if (!re || !subject) return; // Catch all for regex errors and API cleanliness try { boost::regex regex(re); sqlite3_result_int(ctx, boost::regex_search(std::string(subject), regex)); } catch (const boost::regex_error& e) { sqlite3_result_error(ctx, e.what(), -1); } return; } /** * @brief Substitute regex matches with a formatted string. * For more information about the string format, see Boost::regex or the README. */ void sub(sqlite3_context *ctx, int argc, sqlite3_value **argv) { const char *re = getSQLiteString(ctx, argv[0], "sub", "regular expression"); const char *format = getSQLiteString(ctx, argv[1], "sub", "format string"); const char *subject = getSQLiteString(ctx, argv[2], "sub", "subject"); if (!re || !format || !subject) return; // Catch all for regex errors and API cleanliness try { boost::regex regex(re); std::string replaced = boost::regex_replace(std::string(subject), regex, format); sqlite3_result_text(ctx, replaced.data(), -1, SQLITE_TRANSIENT); } catch (const boost::regex_error& e) { sqlite3_result_error(ctx, e.what(), -1); } return; } /***************************************************************************** * Math */ /** Helper functions */ /** Perform a unary operator on either a scalar or vector */ void vunop(sqlite3_context *ctx, sqlite3_value *arg, std::function<double(double)> unop) { switch (sqlite3_value_type(arg)) { case SQLITE_INTEGER: case SQLITE_FLOAT: return sqlite3_result_double(ctx, unop(sqlite3_value_double(arg)));; case SQLITE_BLOB: { int len = sqlite3_value_bytes(arg) / sizeof(double); double *vec = (double*) sqlite3_value_blob(arg); double result_vec[len]; for (int i=0; i<len; i++) { result_vec[i] = unop(vec[i]); } sqlite3_result_blob(ctx, result_vec, len*sizeof(double), SQLITE_TRANSIENT); } default: sqlite3_result_error(ctx, "Invalid value type for vector/scalar operation. " \ "Possible causes:\n" \ "\tPerforming operations on an empty vector, \n"\ "\tUsing text as a vector or scalar (convert them first with cast() or vread()),\n"\ "\tNot space-separating values for vread().", -1); } } // Get the length of a scalar or vector, but scalars are -1 to distinguish them. int vecOrScalarLen(sqlite3_value *arg) { switch (sqlite3_value_type(arg)) { case SQLITE_INTEGER: case SQLITE_FLOAT: return -1; case SQLITE_BLOB: return sqlite3_value_bytes(arg) / sizeof(double); default: return 0; } } // Run a binary operation on two double vectors. // It's just choosing a type that makes this operation kinda hairy. void vbinop(sqlite3_context *ctx, sqlite3_value **argv, std::function<double(double, double)> binop) { int left_len = vecOrScalarLen(argv[0]); int right_len = vecOrScalarLen(argv[1]); if (left_len == 0 || right_len == 0) { // Error sqlite3_result_error(ctx, "Invalid value type for vector/scalar operation. " \ "Possible causes:\n" \ "\tPerforming operations on an empty vector, \n"\ "\tUsing text as a vector or scalar (convert them first with cast() or vread()),\n"\ "\tNot space-separating values for vread().", -1); return; } else if (left_len == -1 && right_len == -1) { // Scalar-scalar op sqlite3_result_double(ctx, binop( sqlite3_value_double(argv[0]), sqlite3_value_double(argv[1]) )); } else if (left_len == -1) { // Scalar-vector op double left = sqlite3_value_double(argv[0]); double *right_vec = (double*) sqlite3_value_blob(argv[1]); double result_vec[right_len]; for (int i=0; i<right_len; i++) { result_vec[i] = binop(left, right_vec[i]); } sqlite3_result_blob(ctx, result_vec, right_len*sizeof(double), SQLITE_TRANSIENT); } else if (right_len == -1) { // Vector-scalar op double *left_vec = (double*) sqlite3_value_blob(argv[0]); double right = sqlite3_value_double(argv[1]); double result_vec[left_len]; for (int i=0; i<left_len; i++) { result_vec[i] = binop(left_vec[i], right); } sqlite3_result_blob(ctx, result_vec, left_len*sizeof(double), SQLITE_TRANSIENT); } else { // Vector-vector op int len = fmin(left_len, right_len); double *left_vec = (double*) sqlite3_value_blob(argv[0]); double *right_vec = (double*) sqlite3_value_blob(argv[1]); double result_vec[len]; for (int i=0; i<len; i++) { result_vec[i] = binop(left_vec[i], right_vec[i]); } sqlite3_result_blob(ctx, result_vec, len*sizeof(double), SQLITE_TRANSIENT); } } void sqlsin(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vunop(ctx, argv[0], sin); } void sqlasin(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vunop(ctx, argv[0], asin); } void sqlcos(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vunop(ctx, argv[0], cos); } void sqlacos(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vunop(ctx, argv[0], acos); } void sqltan(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vunop(ctx, argv[0], tan); } void sqlatan(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vunop(ctx, argv[0], atan); } void sqllog(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vunop(ctx, argv[0], log); } void sqlexp(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vunop(ctx, argv[0], exp); } void sqlpow(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vbinop(ctx, argv, pow); } void sqlsqrt(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vunop(ctx, argv[0], sqrt); } // Create a new zero vector void sqlvzero(sqlite3_context *ctx, int argc, sqlite3_value **argv) { int len = sqlite3_value_int(argv[0]); double result_vec[len]; for (int i=0; i<len; i++) { result_vec[i] = 0; } sqlite3_result_blob(ctx, result_vec, len*sizeof(double), SQLITE_TRANSIENT); } // Create a new one vector void sqlvone(sqlite3_context *ctx, int argc, sqlite3_value **argv) { int len = sqlite3_value_int(argv[0]); double result_vec[len]; for (int i=0; i<len; i++) { result_vec[i] = 1; } sqlite3_result_blob(ctx, result_vec, len*sizeof(double), SQLITE_TRANSIENT); } // Add two vectors void sqlvadd(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vbinop(ctx, argv, [](double a, double b){ return a + b; }); } // Subtract the second vector from the first void sqlvsub(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vbinop(ctx, argv, [](double a, double b){ return a - b; }); } // Multiply two vectors void sqlvmult(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vbinop(ctx, argv, [](double a, double b){ return a * b; }); } // Divide two vectors void sqlvdiv(sqlite3_context *ctx, int argc, sqlite3_value **argv) { vbinop(ctx, argv, [](double a, double b){ return a / b; }); } // Read a vector from a space separated string void sqlvread(sqlite3_context *ctx, int argc, sqlite3_value **argv) { const char *text = getSQLiteString(ctx, argv[0], "vread", "space separated floating point values"); std::string str(text); std::stringstream stream(str); std::vector<double> vec; for (double item; stream >> item;) { vec.push_back(item); } sqlite3_result_blob(ctx, &vec.front(), vec.size()*sizeof(double), SQLITE_TRANSIENT); } // Write a vector to a space separated string void sqlvshow(sqlite3_context *ctx, int argc, sqlite3_value **argv) { int len = sqlite3_value_bytes(argv[0]) / sizeof(double); double *vec = (double*) sqlite3_value_blob(argv[0]); std::stringstream stream; for (int i=0; i<len; i++) { stream << vec[i] << ' '; } sqlite3_result_text(ctx, stream.str().c_str(), -1, SQLITE_TRANSIENT); } int sqlite3_extension_init(sqlite3 *db, char **err, const sqlite3_api_routines *api) { SQLITE_EXTENSION_INIT2(api) // Regular Expressions sqlite3_create_function(db, "match", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, match, NULL, NULL); sqlite3_create_function(db, "search", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, search, NULL, NULL); sqlite3_create_function(db, "sub", 3, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sub, NULL, NULL); // Math sqlite3_create_function(db, "sin", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlsin, NULL, NULL); sqlite3_create_function(db, "asin", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlasin, NULL, NULL); sqlite3_create_function(db, "cos", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlcos, NULL, NULL); sqlite3_create_function(db, "acos", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlacos, NULL, NULL); sqlite3_create_function(db, "tan", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqltan, NULL, NULL); sqlite3_create_function(db, "atan", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlatan, NULL, NULL); sqlite3_create_function(db, "log", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqllog, NULL, NULL); sqlite3_create_function(db, "exp", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlexp, NULL, NULL); sqlite3_create_function(db, "pow", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlpow, NULL, NULL); sqlite3_create_function(db, "sqrt", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlsqrt, NULL, NULL); // Vector operations sqlite3_create_function(db, "vread", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlvread, NULL, NULL); sqlite3_create_function(db, "vshow", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlvshow, NULL, NULL); //sqlite3_create_function(db, "vburst", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlvburst, NULL, NULL); //sqlite3_create_function(db, "vcollapse", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlvcollase, NULL, NULL); sqlite3_create_function(db, "vzero", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlvzero, NULL, NULL); sqlite3_create_function(db, "vone", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlvone, NULL, NULL); sqlite3_create_function(db, "add", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlvadd, NULL, NULL); sqlite3_create_function(db, "sub", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlvsub, NULL, NULL); sqlite3_create_function(db, "mult", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlvmult, NULL, NULL); sqlite3_create_function(db, "div", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sqlvdiv, NULL, NULL); return 0; } } <|endoftext|>
<commit_before>#ifndef NCRON_RLIMIT_H_ #define NCRON_RLIMIT_H_ /* rlimit.c - sets rlimits for ncron jobs * * (c) 2003-2014 Nicholas J. Kain <njkain at gmail dot 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: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/types.h> #include <boost/optional.hpp> #include <boost/utility.hpp> class rlimits : boost::noncopyable { struct pprargs { pprargs(uid_t uid, gid_t gid, const std::string &cmd) : uid_(uid), gid_(gid), cmd_(cmd) {} uid_t uid_; gid_t gid_; const std::string &cmd_; }; int do_limit(int resource, const boost::optional<struct rlimit> &rlim, const std::string &rstr, const pprargs &ppr); public: boost::optional<rlimit> cpu; boost::optional<rlimit> fsize; boost::optional<rlimit> data; boost::optional<rlimit> stack; boost::optional<rlimit> core; boost::optional<rlimit> rss; boost::optional<rlimit> nproc; boost::optional<rlimit> nofile; boost::optional<rlimit> memlock; boost::optional<rlimit> as; boost::optional<rlimit> msgqueue; boost::optional<rlimit> nice; boost::optional<rlimit> rttime; boost::optional<rlimit> rtprio; boost::optional<rlimit> sigpending; int enforce(uid_t uid, gid_t gid, const std::string &command); }; #endif <commit_msg>rlimit: Add missing header includes.<commit_after>#ifndef NCRON_RLIMIT_H_ #define NCRON_RLIMIT_H_ /* rlimit.c - sets rlimits for ncron jobs * * (c) 2003-2014 Nicholas J. Kain <njkain at gmail dot 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: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #include <boost/optional.hpp> #include <boost/utility.hpp> class rlimits : boost::noncopyable { struct pprargs { pprargs(uid_t uid, gid_t gid, const std::string &cmd) : uid_(uid), gid_(gid), cmd_(cmd) {} uid_t uid_; gid_t gid_; const std::string &cmd_; }; int do_limit(int resource, const boost::optional<struct rlimit> &rlim, const std::string &rstr, const pprargs &ppr); public: boost::optional<rlimit> cpu; boost::optional<rlimit> fsize; boost::optional<rlimit> data; boost::optional<rlimit> stack; boost::optional<rlimit> core; boost::optional<rlimit> rss; boost::optional<rlimit> nproc; boost::optional<rlimit> nofile; boost::optional<rlimit> memlock; boost::optional<rlimit> as; boost::optional<rlimit> msgqueue; boost::optional<rlimit> nice; boost::optional<rlimit> rttime; boost::optional<rlimit> rtprio; boost::optional<rlimit> sigpending; int enforce(uid_t uid, gid_t gid, const std::string &command); }; #endif <|endoftext|>
<commit_before>#ifndef Bull_Matrix4_hpp #define Bull_Matrix4_hpp #include <array> #include <Bull/Math/Polygon/Rectangle.hpp> #include <Bull/Math/Vector/Vector4.hpp> namespace Bull { template<typename T> class BULL_API Matrix4 { public: /*! \brief Create an identity matrix * * \return The identity matrix * */ static Matrix4<T> makeIdentity(); /*! \brief Create a scaling matrix * * \param x The scale value on x axis * \param y The scale value on y axis * \param z The scale value on z axis * * \return The scaling matrix * */ static Matrix4<T> makeScale(T x, T y, T z); /*! \brief Create a translation matrix * * \param x The translation value on x axis * \param y The translation value on y axis * \param z The translation value on z axis * * \return The translation matrix * */ static Matrix4<T> makeTranslation(T x, T y, T z); /*! \brief Create an orthographic projection Matrix4 * * \param plan The plan of view * \param near * \param far * * \return The orthographic projection Matrix4 * */ static Matrix4<T> makeOrthographic(const Rectangle<T>& plan, T near, T far); /*! \brief Create a look at matrix * * \param eye The position of the eye (e.g camera) * \param target The position of the point to look * \param up The up vector * * \return The look matrix * */ static Matrix4<T> makeLookAt(const Vector3<T>& eye, const Vector3<T>& target, const Vector3<T> up = Vector3<T>::makeUp()); public: /*! \brief Default Constructor * */ Matrix4(); /*! \brief Constructor * * \param value The value of every matrix cell * */ Matrix4(T value); /*! \brief Constructor * * \param data The matrix content * */ Matrix4(const std::array<T, 16>& data); /*! \brief Set the matrix content * * \param value The value of every matrix cell * */ void set(T value); /*! \brief The value of a cell of the matrix * * \param value The value to set * \param x The abscissa of the cell in the matrix * \param y The ordinate of the cell in the matrix * */ void set(T value, std::size_t x, std::size_t y); /*! \brief Set the matrix content * * \param data The matrix content * */ void set(const std::array<T, 16>& data); /*! \brief Get the value of a cell of the matrix * * \param x The abscissa of the cell to get in the matrix * \param y The ordinate of the cell to get in the matrix * * \return Return the value * */ T get(std::size_t x, std::size_t y) const; /*! \brief Set a column of the Matrix4 * * \param column The column * \param position The position of the column to set * * \return This * */ Matrix4<T>& setColumn(const Vector4<T>& column, std::size_t position); /*! \brief Get a column a the Matrix4 * * \param column The column to get * * \return Return the column * */ std::array<T, 4> getColumn(std::size_t column) const; /*! \brief Get a row a the matrix * * \param row The row to get * * \return Return the row * */ std::array<T, 4> getRow(std::size_t row) const; /*! \brief * * \param * \param * * \return * */ T& operator()(std::size_t x, std::size_t y); /*! \brief * * \param * \param * * \return * */ const T& operator()(std::size_t x, std::size_t y) const; /*! \brief Compare two matrices * * \param right The matrix to compare to this * * \return Return true if the two matrices are equal, false otherwise * */ bool operator==(const Matrix4<T>& right); /*! \brief Compare two matrices * * \param right The matrix to compare to this * * \return Return true if the two matrices are not equal, false otherwise * */ bool operator!=(const Matrix4<T>& right); /*! \brief Addition two matrices * * \param right * * \return Return the sum the addition of right and this * */ Matrix4<T>& operator+=(const Matrix4<T>& right); /*! \brief Addition two matrices * * \param right * * \return Return the sum of the addition between right and this * */ Matrix4<T>& operator+=(T right); /*! \brief Subtract two matrices * * \param right * * \return Return the difference of the subtraction between right and this * */ Matrix4<T>& operator-=(const Matrix4<T>& right); /*! \brief Subtract a matrix with a scalar * * \param right * * \return Return the difference the subtraction between right and this * */ Matrix4<T>& operator-=(T right); /*! \brief Multiply two matrices * * \param right * * \return Return the product of the multiplication between right and this * */ Matrix4<T> operator*=(const Matrix4<T>& right); /*! \brief Get a pointer to the internal data * * \return Return the pointer * */ operator const T*() const; private: std::array<T, 16> m_data; }; /*! \brief Addition two matrices * * \param right * \param left * * \return Return the sum of the addition between right and left * */ template<typename T> Matrix4<T> operator+(const Matrix4<T>& left, const Matrix4<T>& right); /*! \brief Addition two matrices * * \param right * \param left * * \return Return the sum of the addition between right and left * */ template<typename T> Matrix4<T> operator+(T left, const Matrix4<T>& right); /*! \brief Addition two matrices * * \param right * \param left * * \return Return the sum of the addition between right and left * */ template<typename T> Matrix4<T> operator+(const Matrix4<T>& left, T right); /*! \brief Subtract two matrices * * \param right * \param left * * \return Return the difference of the subtraction between right and left * */ template<typename T> Matrix4<T> operator-(const Matrix4<T>& left, const Matrix4<T>& right); /*! \brief Subtract two matrices * * \param right * \param left * * \return Return the difference of the subtraction between right and left * */ template<typename T> Matrix4<T> operator-(T left, const Matrix4<T>& right); /*! \brief Subtract two matrices * * \param right * \param left * * \return Return the difference of the subtraction between right and left * */ template<typename T> Matrix4<T> operator-(const Matrix4<T>& left, T right); /*! \brief Multiply two matrices * * \param right * \param left * * \return Return the product of the multiplication between right and left * */ template<typename T> Matrix4<T> operator*(const Matrix4<T>& left, const Matrix4<T>& right); /*! \brief Multiply a matrix with a vector * * \param right * \param left * * \return Return the product of the multiplication between right and left * */ template<typename T> Vector4<T> operator*(const Matrix4<T>& left, const Vector4<T>& right); typedef Matrix4<int> Matrix4I; typedef Matrix4<float> Matrix4F; typedef Matrix4<double> Matrix4D; typedef Matrix4<unsigned int> Matrix4UI; } #include <Bull/Math/Matrix/Matrix4.inl> #endif // Bull_Matrix4_hpp <commit_msg>Math/Matrix4 Implement creation of rotation matrix<commit_after>#ifndef Bull_Matrix4_hpp #define Bull_Matrix4_hpp #include <array> #include <Bull/Math/Angle.hpp> #include <Bull/Math/Quaternion.hpp> #include <Bull/Math/Polygon/Rectangle.hpp> #include <Bull/Math/Vector/Vector4.hpp> namespace Bull { template<typename T> class BULL_API Matrix4 { public: /*! \brief Create an identity Matrix4 * * \return The identity Matrix4 * */ static Matrix4<T> makeIdentity(); /*! \brief Create a scaling Matrix4 * * \param x The scale value on x axis * \param y The scale value on y axis * \param z The scale value on z axis * * \return The scaling Matrix4 * */ static Matrix4<T> makeScale(T x, T y, T z); /*! \brief Create a translation Matrix4 * * \param x The translation value on x axis * \param y The translation value on y axis * \param z The translation value on z axis * * \return The translation Matrix4 * */ static Matrix4<T> makeTranslation(T x, T y, T z); /*! \brief Create a rotation Matrix4 * * \param quaternion A Quaternion representing the rotation * * \return The rotation Matrix4 * */ static Matrix4<T> makeRotation(const Quaternion<T>& quaternion); /*! \brief Create a perspective Matrix4 * * \param angle * \param ratio * \param near * \param far * * \return * */ static Matrix4<T> makePerspective(const Angle<T>& angle, T ratio, T near, T far); /*! \brief Create an orthographic projection Matrix4 * * \param plan The plan of view * \param near * \param far * * \return The orthographic projection Matrix4 * */ static Matrix4<T> makeOrthographic(const Rectangle<T>& plan, T near = -1.0, T far = 1.0); /*! \brief Create a look at Matrix4 * * \param eye The position of the eye (e.g camera) * \param target The position of the point to look * \param up The up vector * * \return The look at Matrix4 * */ static Matrix4<T> makeLookAt(const Vector3<T>& eye, const Vector3<T>& target, const Vector3<T> up = Vector3<T>::makeUp()); public: /*! \brief Default Constructor * */ Matrix4(); /*! \brief Constructor * * \param value The value of every cell of the Matrix4 * */ Matrix4(T value); /*! \brief Constructor * * \param data The matrix content * */ Matrix4(const std::array<T, 16>& data); /*! \brief Set the matrix content * * \param value The value of every matrix cell * */ void set(T value); /*! \brief The value of a cell of the matrix * * \param value The value to set * \param x The abscissa of the cell in the matrix * \param y The ordinate of the cell in the matrix * */ void set(T value, std::size_t x, std::size_t y); /*! \brief Set the matrix content * * \param data The matrix content * */ void set(const std::array<T, 16>& data); /*! \brief Get the value of a cell of the matrix * * \param x The abscissa of the cell to get in the matrix * \param y The ordinate of the cell to get in the matrix * * \return Return the value * */ T get(std::size_t x, std::size_t y) const; /*! \brief Set a column of the Matrix4 * * \param column The column * \param position The position of the column to set * * \return This * */ Matrix4<T>& setColumn(const Vector4<T>& column, std::size_t position); /*! \brief Get a column a the Matrix4 * * \param column The column to get * * \return Return the column * */ std::array<T, 4> getColumn(std::size_t column) const; /*! \brief Get a row a the matrix * * \param row The row to get * * \return Return the row * */ std::array<T, 4> getRow(std::size_t row) const; /*! \brief * * \param * \param * * \return * */ T& operator()(std::size_t x, std::size_t y); /*! \brief * * \param * \param * * \return * */ const T& operator()(std::size_t x, std::size_t y) const; /*! \brief Compare two matrices * * \param right The matrix to compare to this * * \return Return true if the two matrices are equal, false otherwise * */ bool operator==(const Matrix4<T>& right); /*! \brief Compare two matrices * * \param right The matrix to compare to this * * \return Return true if the two matrices are not equal, false otherwise * */ bool operator!=(const Matrix4<T>& right); /*! \brief Addition two matrices * * \param right * * \return Return the sum the addition of right and this * */ Matrix4<T>& operator+=(const Matrix4<T>& right); /*! \brief Addition two matrices * * \param right * * \return Return the sum of the addition between right and this * */ Matrix4<T>& operator+=(T right); /*! \brief Subtract two matrices * * \param right * * \return Return the difference of the subtraction between right and this * */ Matrix4<T>& operator-=(const Matrix4<T>& right); /*! \brief Subtract a matrix with a scalar * * \param right * * \return Return the difference the subtraction between right and this * */ Matrix4<T>& operator-=(T right); /*! \brief Multiply two matrices * * \param right * * \return Return the product of the multiplication between right and this * */ Matrix4<T> operator*=(const Matrix4<T>& right); /*! \brief Get a pointer to the internal data * * \return Return the pointer * */ operator const T*() const; private: std::array<T, 16> m_data; }; /*! \brief Addition two matrices * * \param right * \param left * * \return Return the sum of the addition between right and left * */ template<typename T> Matrix4<T> operator+(const Matrix4<T>& left, const Matrix4<T>& right); /*! \brief Addition two matrices * * \param right * \param left * * \return Return the sum of the addition between right and left * */ template<typename T> Matrix4<T> operator+(T left, const Matrix4<T>& right); /*! \brief Addition two matrices * * \param right * \param left * * \return Return the sum of the addition between right and left * */ template<typename T> Matrix4<T> operator+(const Matrix4<T>& left, T right); /*! \brief Subtract two matrices * * \param right * \param left * * \return Return the difference of the subtraction between right and left * */ template<typename T> Matrix4<T> operator-(const Matrix4<T>& left, const Matrix4<T>& right); /*! \brief Subtract two matrices * * \param right * \param left * * \return Return the difference of the subtraction between right and left * */ template<typename T> Matrix4<T> operator-(T left, const Matrix4<T>& right); /*! \brief Subtract two matrices * * \param right * \param left * * \return Return the difference of the subtraction between right and left * */ template<typename T> Matrix4<T> operator-(const Matrix4<T>& left, T right); /*! \brief Multiply two matrices * * \param right * \param left * * \return Return the product of the multiplication between right and left * */ template<typename T> Matrix4<T> operator*(const Matrix4<T>& left, const Matrix4<T>& right); /*! \brief Multiply a matrix with a vector * * \param right * \param left * * \return Return the product of the multiplication between right and left * */ template<typename T> Vector4<T> operator*(const Matrix4<T>& left, const Vector4<T>& right); typedef Matrix4<int> Matrix4I; typedef Matrix4<float> Matrix4F; typedef Matrix4<double> Matrix4D; typedef Matrix4<unsigned int> Matrix4UI; } #include <Bull/Math/Matrix/Matrix4.inl> #endif // Bull_Matrix4_hpp <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #ifndef IECORE_POINTDISTRIBUTION_INL #define IECORE_POINTDISTRIBUTION_INL #include "IECore/FastFloat.h" #include <cassert> namespace IECore { struct PointDistribution::Tile { int n, e, s, w; std::vector<Tile *> subTiles; typedef std::vector<Imath::V2f> PointVector; PointVector points; PointVector subPoints; }; template<typename DensityFunction, typename PointFunction> void PointDistribution::operator () ( const Imath::Box2f &bounds, float density, DensityFunction &densitySampler, PointFunction &pointEmitter ) const { Imath::Box2i bi; bi.min.x = fastFloatFloor( bounds.min.x ); bi.max.x = fastFloatFloor( bounds.max.x ); bi.min.y = fastFloatFloor( bounds.min.y ); bi.max.y = fastFloatFloor( bounds.max.y ); for( int x=bi.min.x; x<=bi.max.x; x++ ) { for( int y=bi.min.y; y<=bi.max.y; y++ ) { unsigned sw = hash( x, y ); unsigned nw = hash( x, y+1 ); unsigned ne = hash( x+1, y+1 ); unsigned se = hash( x+1, y ); int w = (sw + nw) % 2; int n = (nw + ne) % 2; int e = (ne + se) % 2; bool tileFound = false; for( unsigned i=0; i<m_tiles.size(); i++ ) { const Tile *tile = &m_tiles[i]; if( tile->w==w && tile->n==n && tile->e==e ) { processTile( *tile, Imath::V2f( x, y ), bounds, density, densitySampler, pointEmitter ); tileFound = true; break; } } assert( tileFound ); } } } template<typename DensityFunction, typename PointFunction> void PointDistribution::processTile( const Tile &tile, const Imath::V2f &bottomLeft, const Imath::Box2f &bounds, float density, DensityFunction &densitySampler, PointFunction &pointEmitter ) const { unsigned potentialPoints = std::min( tile.points.size(), (size_t)density ); float factor = 1.0f / density; for( unsigned i=0; i<potentialPoints; i++ ) { const Imath::V2f &p = bottomLeft + tile.points[i]; if( !bounds.intersects( p ) ) { continue; } if( densitySampler( p ) < i * factor ) { continue; } pointEmitter( p ); } recurseTile( tile, bottomLeft, 0, bounds, density, densitySampler, pointEmitter ); } template<typename DensityFunction, typename PointFunction> void PointDistribution::recurseTile( const Tile &tile, const Imath::V2f &bottomLeft, unsigned level, const Imath::Box2f &bounds, float density, DensityFunction &densitySampler, PointFunction &pointEmitter ) const { float tileSize = 1.0f / powf( (float)m_numSubTiles, (float)level ); Imath::Box2f tileBound( bottomLeft, bottomLeft + Imath::V2f( tileSize ) ); if( !tileBound.intersects( bounds ) ) { return; } float tileArea = tileSize * tileSize; float numPointsInTile = density * tileArea; int potentialPoints = std::min( (int)tile.subPoints.size(), (int)numPointsInTile - (int)tile.points.size() ); float factor = 1.0f / ( numPointsInTile ); for( int i=0; i<potentialPoints; i++ ) { const Imath::V2f &p = bottomLeft + tile.subPoints[i] * tileSize; if( !bounds.intersects( p ) ) { continue; } if( densitySampler( p ) < ( i + tile.points.size() ) * factor ) { continue; } pointEmitter( p ); } if( numPointsInTile - tile.points.size() > tile.subPoints.size() ) { for( int y=0; y<m_numSubTiles; y++ ) { for( int x=0; x<m_numSubTiles; x++ ) { Imath::V2f newBottomLeft = bottomLeft + Imath::V2f( x, y ) * tileSize / m_numSubTiles; recurseTile( *(tile.subTiles[y*m_numSubTiles + x]), newBottomLeft, level + 1, bounds, density, densitySampler, pointEmitter ); } } } } inline unsigned int PointDistribution::hash( int x, int y ) const { unsigned int h = m_perm[x & (m_permSize-1)]; return m_perm[h + (y & (m_permSize-1))]; } } // namespace IECore #endif // IECORE_POINTDISTRIBUTION_INL <commit_msg>Stopped taking a reference to what I presume doesn't last very long.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #ifndef IECORE_POINTDISTRIBUTION_INL #define IECORE_POINTDISTRIBUTION_INL #include "IECore/FastFloat.h" #include <cassert> namespace IECore { struct PointDistribution::Tile { int n, e, s, w; std::vector<Tile *> subTiles; typedef std::vector<Imath::V2f> PointVector; PointVector points; PointVector subPoints; }; template<typename DensityFunction, typename PointFunction> void PointDistribution::operator () ( const Imath::Box2f &bounds, float density, DensityFunction &densitySampler, PointFunction &pointEmitter ) const { Imath::Box2i bi; bi.min.x = fastFloatFloor( bounds.min.x ); bi.max.x = fastFloatFloor( bounds.max.x ); bi.min.y = fastFloatFloor( bounds.min.y ); bi.max.y = fastFloatFloor( bounds.max.y ); for( int x=bi.min.x; x<=bi.max.x; x++ ) { for( int y=bi.min.y; y<=bi.max.y; y++ ) { unsigned sw = hash( x, y ); unsigned nw = hash( x, y+1 ); unsigned ne = hash( x+1, y+1 ); unsigned se = hash( x+1, y ); int w = (sw + nw) % 2; int n = (nw + ne) % 2; int e = (ne + se) % 2; bool tileFound = false; for( unsigned i=0; i<m_tiles.size(); i++ ) { const Tile *tile = &m_tiles[i]; if( tile->w==w && tile->n==n && tile->e==e ) { processTile( *tile, Imath::V2f( x, y ), bounds, density, densitySampler, pointEmitter ); tileFound = true; break; } } assert( tileFound ); } } } template<typename DensityFunction, typename PointFunction> void PointDistribution::processTile( const Tile &tile, const Imath::V2f &bottomLeft, const Imath::Box2f &bounds, float density, DensityFunction &densitySampler, PointFunction &pointEmitter ) const { unsigned potentialPoints = std::min( tile.points.size(), (size_t)density ); float factor = 1.0f / density; for( unsigned i=0; i<potentialPoints; i++ ) { const Imath::V2f p = bottomLeft + tile.points[i]; if( !bounds.intersects( p ) ) { continue; } if( densitySampler( p ) < i * factor ) { continue; } pointEmitter( p ); } recurseTile( tile, bottomLeft, 0, bounds, density, densitySampler, pointEmitter ); } template<typename DensityFunction, typename PointFunction> void PointDistribution::recurseTile( const Tile &tile, const Imath::V2f &bottomLeft, unsigned level, const Imath::Box2f &bounds, float density, DensityFunction &densitySampler, PointFunction &pointEmitter ) const { float tileSize = 1.0f / powf( (float)m_numSubTiles, (float)level ); Imath::Box2f tileBound( bottomLeft, bottomLeft + Imath::V2f( tileSize ) ); if( !tileBound.intersects( bounds ) ) { return; } float tileArea = tileSize * tileSize; float numPointsInTile = density * tileArea; int potentialPoints = std::min( (int)tile.subPoints.size(), (int)numPointsInTile - (int)tile.points.size() ); float factor = 1.0f / ( numPointsInTile ); for( int i=0; i<potentialPoints; i++ ) { const Imath::V2f p = bottomLeft + tile.subPoints[i] * tileSize; if( !bounds.intersects( p ) ) { continue; } if( densitySampler( p ) < ( i + tile.points.size() ) * factor ) { continue; } pointEmitter( p ); } if( numPointsInTile - tile.points.size() > tile.subPoints.size() ) { for( int y=0; y<m_numSubTiles; y++ ) { for( int x=0; x<m_numSubTiles; x++ ) { Imath::V2f newBottomLeft = bottomLeft + Imath::V2f( x, y ) * tileSize / m_numSubTiles; recurseTile( *(tile.subTiles[y*m_numSubTiles + x]), newBottomLeft, level + 1, bounds, density, densitySampler, pointEmitter ); } } } } inline unsigned int PointDistribution::hash( int x, int y ) const { unsigned int h = m_perm[x & (m_permSize-1)]; return m_perm[h + (y & (m_permSize-1))]; } } // namespace IECore #endif // IECORE_POINTDISTRIBUTION_INL <|endoftext|>
<commit_before>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_MATERIAL_HPP #define NAZARA_MATERIAL_HPP #include <Nazara/Prerequesites.hpp> #include <Nazara/Core/Color.hpp> #include <Nazara/Core/ObjectListenerWrapper.hpp> #include <Nazara/Core/ObjectRef.hpp> #include <Nazara/Core/RefCounted.hpp> #include <Nazara/Core/Resource.hpp> #include <Nazara/Core/ResourceLoader.hpp> #include <Nazara/Core/String.hpp> #include <Nazara/Graphics/Enums.hpp> #include <Nazara/Renderer/RenderStates.hpp> #include <Nazara/Renderer/Texture.hpp> #include <Nazara/Renderer/TextureSampler.hpp> #include <Nazara/Renderer/UberShader.hpp> struct NAZARA_API NzMaterialParams { bool loadAlphaMap = true; bool loadDiffuseMap = true; bool loadEmissiveMap = true; bool loadHeightMap = true; bool loadNormalMap = true; bool loadSpecularMap = true; NzString shaderName = "Basic"; bool IsValid() const; }; class NzMaterial; using NzMaterialConstListener = NzObjectListenerWrapper<const NzMaterial>; using NzMaterialConstRef = NzObjectRef<const NzMaterial>; using NzMaterialListener = NzObjectListenerWrapper<NzMaterial>; using NzMaterialLoader = NzResourceLoader<NzMaterial, NzMaterialParams>; using NzMaterialRef = NzObjectRef<NzMaterial>; class NAZARA_API NzMaterial : public NzRefCounted, public NzResource { friend NzMaterialLoader; friend class NzGraphics; public: NzMaterial(); NzMaterial(const NzMaterial& material); ~NzMaterial(); const NzShader* Apply(nzUInt32 shaderFlags = 0, nzUInt8 textureUnit = 0, nzUInt8* lastUsedUnit = nullptr) const; void Enable(nzRendererParameter renderParameter, bool enable); void EnableAlphaTest(bool alphaTest); void EnableDepthSorting(bool depthSorting); void EnableLighting(bool lighting); void EnableTransform(bool transform); NzTexture* GetAlphaMap() const; float GetAlphaThreshold() const; NzColor GetAmbientColor() const; nzRendererComparison GetDepthFunc() const; NzColor GetDiffuseColor() const; NzTexture* GetDiffuseMap() const; NzTextureSampler& GetDiffuseSampler(); const NzTextureSampler& GetDiffuseSampler() const; nzBlendFunc GetDstBlend() const; NzTexture* GetEmissiveMap() const; nzFaceSide GetFaceCulling() const; nzFaceFilling GetFaceFilling() const; NzTexture* GetHeightMap() const; NzTexture* GetNormalMap() const; const NzRenderStates& GetRenderStates() const; const NzUberShader* GetShader() const; const NzUberShaderInstance* GetShaderInstance(nzUInt32 flags = nzShaderFlags_None) const; float GetShininess() const; NzColor GetSpecularColor() const; NzTexture* GetSpecularMap() const; NzTextureSampler& GetSpecularSampler(); const NzTextureSampler& GetSpecularSampler() const; nzBlendFunc GetSrcBlend() const; bool HasAlphaMap() const; bool HasDiffuseMap() const; bool HasEmissiveMap() const; bool HasHeightMap() const; bool HasNormalMap() const; bool HasSpecularMap() const; bool IsAlphaTestEnabled() const; bool IsDepthSortingEnabled() const; bool IsEnabled(nzRendererParameter renderParameter) const; bool IsLightingEnabled() const; bool IsTransformEnabled() const; bool LoadFromFile(const NzString& filePath, const NzMaterialParams& params = NzMaterialParams()); bool LoadFromMemory(const void* data, std::size_t size, const NzMaterialParams& params = NzMaterialParams()); bool LoadFromStream(NzInputStream& stream, const NzMaterialParams& params = NzMaterialParams()); void Reset(); bool SetAlphaMap(const NzString& texturePath); void SetAlphaMap(NzTexture* map); void SetAlphaThreshold(float alphaThreshold); void SetAmbientColor(const NzColor& ambient); void SetDepthFunc(nzRendererComparison depthFunc); void SetDiffuseColor(const NzColor& diffuse); bool SetDiffuseMap(const NzString& texturePath); void SetDiffuseMap(NzTexture* map); void SetDiffuseSampler(const NzTextureSampler& sampler); void SetDstBlend(nzBlendFunc func); bool SetEmissiveMap(const NzString& texturePath); void SetEmissiveMap(NzTexture* map); void SetFaceCulling(nzFaceSide faceSide); void SetFaceFilling(nzFaceFilling filling); bool SetHeightMap(const NzString& texturePath); void SetHeightMap(NzTexture* map); bool SetNormalMap(const NzString& texturePath); void SetNormalMap(NzTexture* map); void SetRenderStates(const NzRenderStates& states); void SetShader(const NzUberShader* uberShader); bool SetShader(const NzString& uberShaderName); void SetShininess(float shininess); void SetSpecularColor(const NzColor& specular); bool SetSpecularMap(const NzString& texturePath); void SetSpecularMap(NzTexture* map); void SetSpecularSampler(const NzTextureSampler& sampler); void SetSrcBlend(nzBlendFunc func); NzMaterial& operator=(const NzMaterial& material); static NzMaterial* GetDefault(); template<typename... Args> static NzMaterialRef New(Args&&... args); private: struct ShaderInstance { const NzShader* shader; NzUberShaderInstance* uberInstance = nullptr; int uniforms[nzMaterialUniform_Max+1]; }; void Copy(const NzMaterial& material); void Move(NzMaterial&& material); void GenerateShader(nzUInt32 flags) const; void InvalidateShaders(); static bool Initialize(); static void Uninitialize(); NzColor m_ambientColor; NzColor m_diffuseColor; NzColor m_specularColor; NzRenderStates m_states; NzTextureSampler m_diffuseSampler; NzTextureSampler m_specularSampler; NzTextureRef m_alphaMap; NzTextureRef m_diffuseMap; NzTextureRef m_emissiveMap; NzTextureRef m_heightMap; NzTextureRef m_normalMap; NzTextureRef m_specularMap; NzUberShaderConstRef m_uberShader; mutable ShaderInstance m_shaders[nzShaderFlags_Max+1]; bool m_alphaTestEnabled; bool m_depthSortingEnabled; bool m_lightingEnabled; bool m_transformEnabled; float m_alphaThreshold; float m_shininess; static NzMaterialRef s_defaultMaterial; static NzMaterialLoader::LoaderList s_loaders; }; #include <Nazara/Graphics/Material.inl> #endif // NAZARA_MATERIAL_HPP <commit_msg>(Material) Removed outdated Move declaration<commit_after>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_MATERIAL_HPP #define NAZARA_MATERIAL_HPP #include <Nazara/Prerequesites.hpp> #include <Nazara/Core/Color.hpp> #include <Nazara/Core/ObjectListenerWrapper.hpp> #include <Nazara/Core/ObjectRef.hpp> #include <Nazara/Core/RefCounted.hpp> #include <Nazara/Core/Resource.hpp> #include <Nazara/Core/ResourceLoader.hpp> #include <Nazara/Core/String.hpp> #include <Nazara/Graphics/Enums.hpp> #include <Nazara/Renderer/RenderStates.hpp> #include <Nazara/Renderer/Texture.hpp> #include <Nazara/Renderer/TextureSampler.hpp> #include <Nazara/Renderer/UberShader.hpp> struct NAZARA_API NzMaterialParams { bool loadAlphaMap = true; bool loadDiffuseMap = true; bool loadEmissiveMap = true; bool loadHeightMap = true; bool loadNormalMap = true; bool loadSpecularMap = true; NzString shaderName = "Basic"; bool IsValid() const; }; class NzMaterial; using NzMaterialConstListener = NzObjectListenerWrapper<const NzMaterial>; using NzMaterialConstRef = NzObjectRef<const NzMaterial>; using NzMaterialListener = NzObjectListenerWrapper<NzMaterial>; using NzMaterialLoader = NzResourceLoader<NzMaterial, NzMaterialParams>; using NzMaterialRef = NzObjectRef<NzMaterial>; class NAZARA_API NzMaterial : public NzRefCounted, public NzResource { friend NzMaterialLoader; friend class NzGraphics; public: NzMaterial(); NzMaterial(const NzMaterial& material); ~NzMaterial(); const NzShader* Apply(nzUInt32 shaderFlags = 0, nzUInt8 textureUnit = 0, nzUInt8* lastUsedUnit = nullptr) const; void Enable(nzRendererParameter renderParameter, bool enable); void EnableAlphaTest(bool alphaTest); void EnableDepthSorting(bool depthSorting); void EnableLighting(bool lighting); void EnableTransform(bool transform); NzTexture* GetAlphaMap() const; float GetAlphaThreshold() const; NzColor GetAmbientColor() const; nzRendererComparison GetDepthFunc() const; NzColor GetDiffuseColor() const; NzTexture* GetDiffuseMap() const; NzTextureSampler& GetDiffuseSampler(); const NzTextureSampler& GetDiffuseSampler() const; nzBlendFunc GetDstBlend() const; NzTexture* GetEmissiveMap() const; nzFaceSide GetFaceCulling() const; nzFaceFilling GetFaceFilling() const; NzTexture* GetHeightMap() const; NzTexture* GetNormalMap() const; const NzRenderStates& GetRenderStates() const; const NzUberShader* GetShader() const; const NzUberShaderInstance* GetShaderInstance(nzUInt32 flags = nzShaderFlags_None) const; float GetShininess() const; NzColor GetSpecularColor() const; NzTexture* GetSpecularMap() const; NzTextureSampler& GetSpecularSampler(); const NzTextureSampler& GetSpecularSampler() const; nzBlendFunc GetSrcBlend() const; bool HasAlphaMap() const; bool HasDiffuseMap() const; bool HasEmissiveMap() const; bool HasHeightMap() const; bool HasNormalMap() const; bool HasSpecularMap() const; bool IsAlphaTestEnabled() const; bool IsDepthSortingEnabled() const; bool IsEnabled(nzRendererParameter renderParameter) const; bool IsLightingEnabled() const; bool IsTransformEnabled() const; bool LoadFromFile(const NzString& filePath, const NzMaterialParams& params = NzMaterialParams()); bool LoadFromMemory(const void* data, std::size_t size, const NzMaterialParams& params = NzMaterialParams()); bool LoadFromStream(NzInputStream& stream, const NzMaterialParams& params = NzMaterialParams()); void Reset(); bool SetAlphaMap(const NzString& texturePath); void SetAlphaMap(NzTexture* map); void SetAlphaThreshold(float alphaThreshold); void SetAmbientColor(const NzColor& ambient); void SetDepthFunc(nzRendererComparison depthFunc); void SetDiffuseColor(const NzColor& diffuse); bool SetDiffuseMap(const NzString& texturePath); void SetDiffuseMap(NzTexture* map); void SetDiffuseSampler(const NzTextureSampler& sampler); void SetDstBlend(nzBlendFunc func); bool SetEmissiveMap(const NzString& texturePath); void SetEmissiveMap(NzTexture* map); void SetFaceCulling(nzFaceSide faceSide); void SetFaceFilling(nzFaceFilling filling); bool SetHeightMap(const NzString& texturePath); void SetHeightMap(NzTexture* map); bool SetNormalMap(const NzString& texturePath); void SetNormalMap(NzTexture* map); void SetRenderStates(const NzRenderStates& states); void SetShader(const NzUberShader* uberShader); bool SetShader(const NzString& uberShaderName); void SetShininess(float shininess); void SetSpecularColor(const NzColor& specular); bool SetSpecularMap(const NzString& texturePath); void SetSpecularMap(NzTexture* map); void SetSpecularSampler(const NzTextureSampler& sampler); void SetSrcBlend(nzBlendFunc func); NzMaterial& operator=(const NzMaterial& material); static NzMaterial* GetDefault(); template<typename... Args> static NzMaterialRef New(Args&&... args); private: struct ShaderInstance { const NzShader* shader; NzUberShaderInstance* uberInstance = nullptr; int uniforms[nzMaterialUniform_Max+1]; }; void Copy(const NzMaterial& material); void GenerateShader(nzUInt32 flags) const; void InvalidateShaders(); static bool Initialize(); static void Uninitialize(); NzColor m_ambientColor; NzColor m_diffuseColor; NzColor m_specularColor; NzRenderStates m_states; NzTextureSampler m_diffuseSampler; NzTextureSampler m_specularSampler; NzTextureRef m_alphaMap; NzTextureRef m_diffuseMap; NzTextureRef m_emissiveMap; NzTextureRef m_heightMap; NzTextureRef m_normalMap; NzTextureRef m_specularMap; NzUberShaderConstRef m_uberShader; mutable ShaderInstance m_shaders[nzShaderFlags_Max+1]; bool m_alphaTestEnabled; bool m_depthSortingEnabled; bool m_lightingEnabled; bool m_transformEnabled; float m_alphaThreshold; float m_shininess; static NzMaterialRef s_defaultMaterial; static NzMaterialLoader::LoaderList s_loaders; }; #include <Nazara/Graphics/Material.inl> #endif // NAZARA_MATERIAL_HPP <|endoftext|>
<commit_before>// // Copyright (c) 2014 CNRS // Authors: Florent Lamiraux // // This file is part of hpp-core // hpp-core 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. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #ifndef HPP_CORE_CONFIG_PROJECTOR_HH # define HPP_CORE_CONFIG_PROJECTOR_HH # include <Eigen/SVD> # include <hpp/core/config.hh> # include <hpp/core/constraint.hh> # include <hpp/core/comparison-type.hh> # include <hpp/core/numerical-constraint.hh> # include "hpp/core/deprecated.hh" # include <hpp/statistics/success-bin.hh> namespace hpp { namespace core { /// \addtogroup constraints /// \{ /** Implicit non-linear constraint This class defines a numerical constraints on a robot configuration of the form: \f{eqnarray*} f_1 (\mathbf{q}) & = \mbox{or} \leq & f_1^0 \\ & \vdots\\ f_m (\mathbf{q}) & = \mbox{or} \leq & f_m^0 \f} Functions \f$f_i\f$ are \ref constraints::DifferentiableFunction "differentiable functions". Vectors \f$f_i^0\f$ are called \b right hand side\b. The constraints are solved numerically by a Newton Raphson like method. Instances store locked degrees of freedom for performance optimisation. Numerical constraints can be added using method ConfigProjector::add. Default parameter of this method define equality constraints, but inequality constraints can also be defined by passing an object of type ComparisonType to method. */ class HPP_CORE_DLLAPI ConfigProjector : public Constraint { public: /// Return shared pointer to new object /// \param robot robot the constraint applies to. /// \param errorThreshold norm of the value of the constraint under which /// the constraint is considered satified, /// \param maxIterations maximal number of iteration in the resolution of /// the constraint. static ConfigProjectorPtr_t create (const DevicePtr_t& robot, const std::string& name, value_type errorThreshold, size_type maxIterations); /// Return shared pointer to copy /// \param cp shared pointer to object to copy static ConfigProjectorPtr_t createCopy (const ConfigProjectorPtr_t cp); /// return shared pointer to copy virtual ConstraintPtr_t copy () const; /// Add a numerical constraint /// \param numericalConstraint The numerical constraint. /// \param passiveDofs column indexes of the jacobian vector that will be /// set to zero when solving. /// \param priority priority of the function. The last level might be /// optinal. /// \note The intervals are interpreted as a list of couple /// (index_start, length) and NOT as (index_start, index_end). void add (const NumericalConstraintPtr_t& numericalConstraint, const SizeIntervals_t& passiveDofs = SizeIntervals_t (0), const std::size_t priority = 0); void lastIsOptional (bool optional) { lastIsOptional_ = optional; } bool lastIsOptional () const { return lastIsOptional_; } /// Optimize the configuration while respecting the constraints /// The input configuration must already satisfy the constraints. /// \return true if the configuration was optimized. /// \param maxIter if 0, use maxIterations(). bool optimize (ConfigurationOut_t config, std::size_t maxIter = 0, const value_type alpha = 0.2); /// Add a locked joint. /// \param lockedJoint The locked joint. void add (const LockedJointPtr_t& lockedJoint); /// Get robot const DevicePtr_t& robot () const { return robot_; } /// Project velocity on constraint tangent space in "from" /// /// \param from configuration, /// \param velocity velocity to project /// /// \f[ /// \textbf{q}_{res} = \left(I_n - /// J^{+}J(\textbf{q}_{from})\right) (\textbf{v}) /// \f] void projectVectorOnKernel (ConfigurationIn_t from, vectorIn_t velocity, vectorOut_t result); /// Project configuration "to" on constraint tangent space in "from" /// /// \param from configuration, /// \param to configuration to project /// /// \f[ /// \textbf{q}_{res} = \textbf{q}_{from} + \left(I_n - /// J^{+}J(\textbf{q}_{from})\right) (\textbf{q}_{to} - \textbf{q}_{from}) /// \f] virtual void projectOnKernel (ConfigurationIn_t from, ConfigurationIn_t to, ConfigurationOut_t result); /// Compute value and reduced jacobian at a given configuration /// /// \param configuration input configuration /// \retval value values of the differentiable functions stacked in a /// vector, /// \retval reducedJacobian Reduced Jacobian of the differentiable /// functions stacked in a matrix. Reduced Jacobian is defined /// as the Jacobian to which columns corresponding to locked /// joints have been removed and to which columns corresponding /// to passive dofs are set to 0. void computeValueAndJacobian (ConfigurationIn_t configuration, vectorOut_t value, matrixOut_t reducedJacobian); /// Execute one iteration of the projection algorithm /// \return true if the constraints are satisfied bool oneStep (ConfigurationOut_t config, vectorOut_t dq, const value_type& alpha); /// Linearization of the system of equations /// rhs - v_{i} = J (q_i) (dq_{i+1} - q_{i}) /// q_{i+1} - q_{i} = J(q_i)^{+} ( rhs - v_{i} ) /// dq = J(q_i)^{+} ( rhs - v_{i} ) void computeIncrement (vectorIn_t value, matrixIn_t reducedJacobian, const value_type& alpha, vectorOut_t dq); void computePrioritizedIncrement (vectorIn_t value, matrixIn_t reducedJacobian, const value_type& alpha, vectorOut_t dq); void computePrioritizedIncrement (vectorIn_t value, matrixIn_t reducedJacobian, const value_type& alpha, vectorOut_t dq, const std::size_t& level); /// \name Compression of locked degrees of freedom /// /// Degrees of freedom related to locked joint are not taken into /// account in numerical constraint resolution. The following methods /// Compress or uncompress vectors or matrices by removing lines and /// columns corresponding to locked degrees of freedom. /// \{ /// Get number of non-locked degrees of freedom size_type numberNonLockedDof () const { return nbNonLockedDofs_; } /// Get constraint dimension size_type dimension () const { return value_.size(); } /// Compress Velocity vector by removing locked degrees of freedom /// /// \param normal input velocity vector /// \retval small compressed velocity vectors void compressVector (vectorIn_t normal, vectorOut_t small) const; /// Expand compressed velocity vector /// /// \param small compressed velocity vector without locked degrees of /// freedom, /// \retval normal uncompressed velocity vector. /// \note locked degree of freedom are not set. They should be initialized /// to zero. void uncompressVector (vectorIn_t small, vectorOut_t normal) const; /// Compress matrix /// /// \param normal input matrix /// \retval small compressed matrix /// \param rows whether to compress rows and colums or only columns void compressMatrix (matrixIn_t normal, matrixOut_t small, bool rows = true) const; /// Uncompress matrix /// /// \param small input matrix /// \retval normal uncompressed matrix /// \param rows whether to uncompress rows and colums or only columns void uncompressMatrix (matrixIn_t small, matrixOut_t normal, bool rows = true) const; /// \} /// Set maximal number of iterations void maxIterations (size_type iterations) { maxIterations_ = iterations; } /// Get maximal number of iterations in config projector size_type maxIterations () const { return maxIterations_; } /// Set error threshold void errorThreshold (const value_type& threshold) { squareErrorThreshold_ = threshold * threshold; } /// Get errorimal number of threshold in config projector value_type errorThreshold () const { return sqrt (squareErrorThreshold_); } value_type residualError() const { return squareNorm_; } /// \name Right hand side of equalities - inequalities /// @{ /// Set the right hand side from a configuration /// /// in such a way that the configuration satisfies the numerical /// constraints /// \param config the input configuration. /// \return the right hand side /// /// \warning Only values of the right hand side corresponding to /// \link Equality "equality constraints" \endlink are set. As a /// result, the input configuration may not satisfy the other constraints. /// The rationale is the following. Equality constraints define a /// foliation of the configuration space. Leaves of the foliation are /// defined by the value of the right hand side of the equality /// constraints. This method is mainly used in manipulation planning /// to retrieve the leaf a configuration lies on. vector_t rightHandSideFromConfig (ConfigurationIn_t config); /// Set the level set parameter. /// \param param the level set parameter. void rightHandSide (const vector_t& param); /// Get the level set parameter. /// \return the parameter. vector_t rightHandSide () const; /// Regenerate the right hand side /// from the numerical constraint right hand sides. /// \note Class NumericalConstraint contains a cache for its own RHS. /// Its value is simply copied in the ConfigProjector RHS. This allow a /// finer control on the RHS. void updateRightHandSide (); /// @} /// Check whether a configuration statisfies the constraint. virtual bool isSatisfied (ConfigurationIn_t config); /// Check whether a configuration statisfies the constraint. /// /// \param config the configuration to check /// \retval error concatenation of /// \li difference between value of numerical constraints and /// right hand side, and /// \li difference between locked joint value and right and side. virtual bool isSatisfied (ConfigurationIn_t config, vector_t& error); /// Get the statistics ::hpp::statistics::SuccessStatistics& statistics() { return statistics_; } /// Get the numerical constraints of the config-projector (and so of the /// Constraint Set) NumericalConstraints_t numericalConstraints () const { return functions_; } /// Get the passive DOF of the ConfigProjector IntervalsContainer_t passiveDofs () const { return passiveDofs_; } LockedJoints_t lockedJoints () const { return lockedJoints_; } protected: /// Constructor /// \param robot robot the constraint applies to. /// \param errorThreshold norm of the value of the constraint under which /// the constraint is considered satified, /// \param maxIterations maximal number of iteration in the resolution of /// the constraint. ConfigProjector (const DevicePtr_t& robot, const std::string& name, value_type errorThreshold, size_type maxIterations); /// Copy constructor ConfigProjector (const ConfigProjector& cp); /// Store weak pointer to itself void init (const ConfigProjectorPtr_t& self) { Constraint::init (self); weak_ = self; } /// Numerically solve constraint virtual bool impl_compute (ConfigurationOut_t configuration); /// Set locked degrees of freedom to their locked values void computeLockedDofs (ConfigurationOut_t configuration); private: typedef Eigen::JacobiSVD <matrix_t> SVD_t; struct PriorityStack { std::size_t level_; // 0, 1, 2 or 3. std::size_t outputSize_, cols_; NumericalConstraints_t functions_; IntervalsContainer_t passiveDofs_; mutable SVD_t svd_; matrix_t PK_; PriorityStack (std::size_t level, std::size_t cols); void add (const NumericalConstraintPtr_t& numericalConstraint, const SizeIntervals_t& passiveDofs); void nbNonLockedDofs (const std::size_t nbNonLockedDofs); void computeValueAndJacobian (ConfigurationIn_t cfg, const SizeIntervals_t& intervals, vectorOut_t value, matrixOut_t reducedJacobian); /// Return false if it is not possible solve this constraints. bool computeIncrement (vectorIn_t value, matrixIn_t jacobian, vectorOut_t dq, matrixOut_t projector); }; virtual std::ostream& print (std::ostream& os) const; virtual void addToConstraintSet (const ConstraintSetPtr_t& constraintSet); void updateExplicitComputation (); bool isSatisfiedNoLockedJoint (ConfigurationIn_t config); void resize (); void computeIntervals (); inline void computeError (); DevicePtr_t robot_; std::vector <PriorityStack> stack_; NumericalConstraints_t functions_; std::vector <std::size_t> explicitFunctions_; IntervalsContainer_t passiveDofs_; LockedJoints_t lockedJoints_; /// Intervals of non locked degrees of freedom SizeIntervals_t intervals_; value_type squareErrorThreshold_; size_type maxIterations_; vector_t rightHandSide_; size_type rhsReducedSize_; bool lastIsOptional_; mutable vector_t value_; /// Jacobian without locked degrees of freedom mutable matrix_t reducedJacobian_; mutable SVD_t svd_; mutable matrix_t reducedProjector_; mutable vector_t toMinusFrom_; mutable vector_t toMinusFromSmall_; mutable vector_t projMinusFrom_; mutable vector_t projMinusFromSmall_; mutable vector_t dq_; mutable vector_t dqSmall_; size_type nbNonLockedDofs_; size_type nbLockedDofs_; value_type squareNorm_; bool explicitComputation_; ConfigProjectorWkPtr_t weak_; ::hpp::statistics::SuccessStatistics statistics_; }; // class ConfigProjector /// \} } // namespace core } // namespace hpp #endif // HPP_CORE_CONFIG_PROJECTOR_HH <commit_msg>Cosmetic: fix comment.<commit_after>// // Copyright (c) 2014 CNRS // Authors: Florent Lamiraux // // This file is part of hpp-core // hpp-core 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. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #ifndef HPP_CORE_CONFIG_PROJECTOR_HH # define HPP_CORE_CONFIG_PROJECTOR_HH # include <Eigen/SVD> # include <hpp/core/config.hh> # include <hpp/core/constraint.hh> # include <hpp/core/comparison-type.hh> # include <hpp/core/numerical-constraint.hh> # include "hpp/core/deprecated.hh" # include <hpp/statistics/success-bin.hh> namespace hpp { namespace core { /// \addtogroup constraints /// \{ /** Implicit non-linear constraint This class defines a numerical constraints on a robot configuration of the form: \f{eqnarray*} f_1 (\mathbf{q}) & = \mbox{or} \leq & f_1^0 \\ & \vdots\\ f_m (\mathbf{q}) & = \mbox{or} \leq & f_m^0 \f} Functions \f$f_i\f$ are \ref constraints::DifferentiableFunction "differentiable functions". Vectors \f$f_i^0\f$ are called \b right hand side\b. The constraints are solved numerically by a Newton Raphson like method. Instances store locked degrees of freedom for performance optimisation. Numerical constraints can be added using method ConfigProjector::add. Default parameter of this method define equality constraints, but inequality constraints can also be defined by passing an object of type ComparisonType to method. */ class HPP_CORE_DLLAPI ConfigProjector : public Constraint { public: /// Return shared pointer to new object /// \param robot robot the constraint applies to. /// \param errorThreshold norm of the value of the constraint under which /// the constraint is considered satified, /// \param maxIterations maximal number of iteration in the resolution of /// the constraint. static ConfigProjectorPtr_t create (const DevicePtr_t& robot, const std::string& name, value_type errorThreshold, size_type maxIterations); /// Return shared pointer to copy /// \param cp shared pointer to object to copy static ConfigProjectorPtr_t createCopy (const ConfigProjectorPtr_t cp); /// return shared pointer to copy virtual ConstraintPtr_t copy () const; /// Add a numerical constraint /// \param numericalConstraint The numerical constraint. /// \param passiveDofs column indexes of the jacobian vector that will be /// set to zero when solving. /// \param priority priority of the function. The last level might be /// optional. /// \note The intervals are interpreted as a list of couple /// (index_start, length) and NOT as (index_start, index_end). void add (const NumericalConstraintPtr_t& numericalConstraint, const SizeIntervals_t& passiveDofs = SizeIntervals_t (0), const std::size_t priority = 0); void lastIsOptional (bool optional) { lastIsOptional_ = optional; } bool lastIsOptional () const { return lastIsOptional_; } /// Optimize the configuration while respecting the constraints /// The input configuration must already satisfy the constraints. /// \return true if the configuration was optimized. /// \param maxIter if 0, use maxIterations(). bool optimize (ConfigurationOut_t config, std::size_t maxIter = 0, const value_type alpha = 0.2); /// Add a locked joint. /// \param lockedJoint The locked joint. void add (const LockedJointPtr_t& lockedJoint); /// Get robot const DevicePtr_t& robot () const { return robot_; } /// Project velocity on constraint tangent space in "from" /// /// \param from configuration, /// \param velocity velocity to project /// /// \f[ /// \textbf{q}_{res} = \left(I_n - /// J^{+}J(\textbf{q}_{from})\right) (\textbf{v}) /// \f] void projectVectorOnKernel (ConfigurationIn_t from, vectorIn_t velocity, vectorOut_t result); /// Project configuration "to" on constraint tangent space in "from" /// /// \param from configuration, /// \param to configuration to project /// /// \f[ /// \textbf{q}_{res} = \textbf{q}_{from} + \left(I_n - /// J^{+}J(\textbf{q}_{from})\right) (\textbf{q}_{to} - \textbf{q}_{from}) /// \f] virtual void projectOnKernel (ConfigurationIn_t from, ConfigurationIn_t to, ConfigurationOut_t result); /// Compute value and reduced jacobian at a given configuration /// /// \param configuration input configuration /// \retval value values of the differentiable functions stacked in a /// vector, /// \retval reducedJacobian Reduced Jacobian of the differentiable /// functions stacked in a matrix. Reduced Jacobian is defined /// as the Jacobian to which columns corresponding to locked /// joints have been removed and to which columns corresponding /// to passive dofs are set to 0. void computeValueAndJacobian (ConfigurationIn_t configuration, vectorOut_t value, matrixOut_t reducedJacobian); /// Execute one iteration of the projection algorithm /// \return true if the constraints are satisfied bool oneStep (ConfigurationOut_t config, vectorOut_t dq, const value_type& alpha); /// Linearization of the system of equations /// rhs - v_{i} = J (q_i) (dq_{i+1} - q_{i}) /// q_{i+1} - q_{i} = J(q_i)^{+} ( rhs - v_{i} ) /// dq = J(q_i)^{+} ( rhs - v_{i} ) void computeIncrement (vectorIn_t value, matrixIn_t reducedJacobian, const value_type& alpha, vectorOut_t dq); void computePrioritizedIncrement (vectorIn_t value, matrixIn_t reducedJacobian, const value_type& alpha, vectorOut_t dq); void computePrioritizedIncrement (vectorIn_t value, matrixIn_t reducedJacobian, const value_type& alpha, vectorOut_t dq, const std::size_t& level); /// \name Compression of locked degrees of freedom /// /// Degrees of freedom related to locked joint are not taken into /// account in numerical constraint resolution. The following methods /// Compress or uncompress vectors or matrices by removing lines and /// columns corresponding to locked degrees of freedom. /// \{ /// Get number of non-locked degrees of freedom size_type numberNonLockedDof () const { return nbNonLockedDofs_; } /// Get constraint dimension size_type dimension () const { return value_.size(); } /// Compress Velocity vector by removing locked degrees of freedom /// /// \param normal input velocity vector /// \retval small compressed velocity vectors void compressVector (vectorIn_t normal, vectorOut_t small) const; /// Expand compressed velocity vector /// /// \param small compressed velocity vector without locked degrees of /// freedom, /// \retval normal uncompressed velocity vector. /// \note locked degree of freedom are not set. They should be initialized /// to zero. void uncompressVector (vectorIn_t small, vectorOut_t normal) const; /// Compress matrix /// /// \param normal input matrix /// \retval small compressed matrix /// \param rows whether to compress rows and colums or only columns void compressMatrix (matrixIn_t normal, matrixOut_t small, bool rows = true) const; /// Uncompress matrix /// /// \param small input matrix /// \retval normal uncompressed matrix /// \param rows whether to uncompress rows and colums or only columns void uncompressMatrix (matrixIn_t small, matrixOut_t normal, bool rows = true) const; /// \} /// Set maximal number of iterations void maxIterations (size_type iterations) { maxIterations_ = iterations; } /// Get maximal number of iterations in config projector size_type maxIterations () const { return maxIterations_; } /// Set error threshold void errorThreshold (const value_type& threshold) { squareErrorThreshold_ = threshold * threshold; } /// Get errorimal number of threshold in config projector value_type errorThreshold () const { return sqrt (squareErrorThreshold_); } value_type residualError() const { return squareNorm_; } /// \name Right hand side of equalities - inequalities /// @{ /// Set the right hand side from a configuration /// /// in such a way that the configuration satisfies the numerical /// constraints /// \param config the input configuration. /// \return the right hand side /// /// \warning Only values of the right hand side corresponding to /// \link Equality "equality constraints" \endlink are set. As a /// result, the input configuration may not satisfy the other constraints. /// The rationale is the following. Equality constraints define a /// foliation of the configuration space. Leaves of the foliation are /// defined by the value of the right hand side of the equality /// constraints. This method is mainly used in manipulation planning /// to retrieve the leaf a configuration lies on. vector_t rightHandSideFromConfig (ConfigurationIn_t config); /// Set the level set parameter. /// \param param the level set parameter. void rightHandSide (const vector_t& param); /// Get the level set parameter. /// \return the parameter. vector_t rightHandSide () const; /// Regenerate the right hand side /// from the numerical constraint right hand sides. /// \note Class NumericalConstraint contains a cache for its own RHS. /// Its value is simply copied in the ConfigProjector RHS. This allow a /// finer control on the RHS. void updateRightHandSide (); /// @} /// Check whether a configuration statisfies the constraint. virtual bool isSatisfied (ConfigurationIn_t config); /// Check whether a configuration statisfies the constraint. /// /// \param config the configuration to check /// \retval error concatenation of /// \li difference between value of numerical constraints and /// right hand side, and /// \li difference between locked joint value and right and side. virtual bool isSatisfied (ConfigurationIn_t config, vector_t& error); /// Get the statistics ::hpp::statistics::SuccessStatistics& statistics() { return statistics_; } /// Get the numerical constraints of the config-projector (and so of the /// Constraint Set) NumericalConstraints_t numericalConstraints () const { return functions_; } /// Get the passive DOF of the ConfigProjector IntervalsContainer_t passiveDofs () const { return passiveDofs_; } LockedJoints_t lockedJoints () const { return lockedJoints_; } protected: /// Constructor /// \param robot robot the constraint applies to. /// \param errorThreshold norm of the value of the constraint under which /// the constraint is considered satified, /// \param maxIterations maximal number of iteration in the resolution of /// the constraint. ConfigProjector (const DevicePtr_t& robot, const std::string& name, value_type errorThreshold, size_type maxIterations); /// Copy constructor ConfigProjector (const ConfigProjector& cp); /// Store weak pointer to itself void init (const ConfigProjectorPtr_t& self) { Constraint::init (self); weak_ = self; } /// Numerically solve constraint virtual bool impl_compute (ConfigurationOut_t configuration); /// Set locked degrees of freedom to their locked values void computeLockedDofs (ConfigurationOut_t configuration); private: typedef Eigen::JacobiSVD <matrix_t> SVD_t; struct PriorityStack { std::size_t level_; // 0, 1, 2 or 3. std::size_t outputSize_, cols_; NumericalConstraints_t functions_; IntervalsContainer_t passiveDofs_; mutable SVD_t svd_; matrix_t PK_; PriorityStack (std::size_t level, std::size_t cols); void add (const NumericalConstraintPtr_t& numericalConstraint, const SizeIntervals_t& passiveDofs); void nbNonLockedDofs (const std::size_t nbNonLockedDofs); void computeValueAndJacobian (ConfigurationIn_t cfg, const SizeIntervals_t& intervals, vectorOut_t value, matrixOut_t reducedJacobian); /// Return false if it is not possible solve this constraints. bool computeIncrement (vectorIn_t value, matrixIn_t jacobian, vectorOut_t dq, matrixOut_t projector); }; virtual std::ostream& print (std::ostream& os) const; virtual void addToConstraintSet (const ConstraintSetPtr_t& constraintSet); void updateExplicitComputation (); bool isSatisfiedNoLockedJoint (ConfigurationIn_t config); void resize (); void computeIntervals (); inline void computeError (); DevicePtr_t robot_; std::vector <PriorityStack> stack_; NumericalConstraints_t functions_; std::vector <std::size_t> explicitFunctions_; IntervalsContainer_t passiveDofs_; LockedJoints_t lockedJoints_; /// Intervals of non locked degrees of freedom SizeIntervals_t intervals_; value_type squareErrorThreshold_; size_type maxIterations_; vector_t rightHandSide_; size_type rhsReducedSize_; bool lastIsOptional_; mutable vector_t value_; /// Jacobian without locked degrees of freedom mutable matrix_t reducedJacobian_; mutable SVD_t svd_; mutable matrix_t reducedProjector_; mutable vector_t toMinusFrom_; mutable vector_t toMinusFromSmall_; mutable vector_t projMinusFrom_; mutable vector_t projMinusFromSmall_; mutable vector_t dq_; mutable vector_t dqSmall_; size_type nbNonLockedDofs_; size_type nbLockedDofs_; value_type squareNorm_; bool explicitComputation_; ConfigProjectorWkPtr_t weak_; ::hpp::statistics::SuccessStatistics statistics_; }; // class ConfigProjector /// \} } // namespace core } // namespace hpp #endif // HPP_CORE_CONFIG_PROJECTOR_HH <|endoftext|>
<commit_before>// Copyright (C) 2010-2013 Joshua Boyce. // See the file COPYING for copying permission. #pragma once #include <array> #include <string> #include <vector> #include <utility> #include <utility> #include <iterator> #include <algorithm> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/locale.hpp> #include <boost/filesystem.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <windows.h> #include <hadesmem/call.hpp> #include <hadesmem/alloc.hpp> #include <hadesmem/error.hpp> #include <hadesmem/write.hpp> #include <hadesmem/config.hpp> #include <hadesmem/module.hpp> #include <hadesmem/process.hpp> #include <hadesmem/pelib/export.hpp> #include <hadesmem/pelib/pe_file.hpp> #include <hadesmem/detail/assert.hpp> #include <hadesmem/detail/self_path.hpp> #include <hadesmem/pelib/export_list.hpp> #include <hadesmem/detail/smart_handle.hpp> namespace hadesmem { namespace detail { inline FARPROC GetProcAddressInternal(Process const& process, Module const& module, std::string const& export_name) { PeFile const pe_file(process, module.GetHandle(), PeFileType::Image); ExportList const exports(process, pe_file); for (auto const& e : exports) { if (e.ByName() && e.GetName() == export_name) { if (e.IsForwarded()) { Module const forwarder_module(process, boost::locale::conv::utf_to_utf<wchar_t>(e.GetForwarderModule())); return GetProcAddressInternal(process, forwarder_module, e.GetForwarderFunction()); } return reinterpret_cast<FARPROC>(e.GetVa()); } } return nullptr; } inline void ArgvQuote(std::wstring* command_line, std::wstring const& argument, bool force) { // Unless we're told otherwise, don't quote unless we actually // need to do so (and hopefully avoid problems if programs won't // parse quotes properly). if (!force && !argument.empty() && argument.find_first_of(L" \t\n\v\"") == argument.npos) { command_line->append(argument); } else { command_line->push_back(L'"'); for (auto it = std::begin(argument); ;++it) { std::size_t num_backslashes = 0; while (it != std::end(argument) && *it == L'\\') { ++it; ++num_backslashes; } if (it == std::end(argument)) { // Escape all backslashes, but let the terminating // double quotation mark we add below be interpreted // as a metacharacter. command_line->append(num_backslashes * 2, L'\\'); break; } else if (*it == L'"') { // Escape all backslashes and the following // double quotation mark. command_line->append(num_backslashes * 2 + 1, L'\\'); command_line->push_back(*it); } else { // Backslashes aren't special here. command_line->append(num_backslashes, L'\\'); command_line->push_back(*it); } } command_line->push_back(L'"'); } } inline void ForceLdrInitializeThunk(DWORD proc_id) { Process const process(proc_id); // This is used to generate a 'nullsub' function, which is called in // the context of the remote process in order to 'force' a call to // ntdll.dll!LdrInitializeThunk. This is necessary because module // enumeration will fail if LdrInitializeThunk has not been called, // and Injector::InjectDll (and the APIs it uses) depends on the // module enumeration APIs. #if defined(HADESMEM_ARCH_X64) std::array<BYTE, 1> return_instr = { { 0xC3 } }; #elif defined(HADESMEM_ARCH_X86) std::array<BYTE, 3> return_instr = { { 0xC2, 0x04, 0x00 } }; #else #error "[HadesMem] Unsupported architecture." #endif Allocator const stub_remote(process, sizeof(return_instr)); Write(process, stub_remote.GetBase(), return_instr); auto const stub_remote_pfn = reinterpret_cast<LPTHREAD_START_ROUTINE>( reinterpret_cast<DWORD_PTR>(stub_remote.GetBase())); detail::SmartHandle const remote_thread(::CreateRemoteThread( process.GetHandle(), nullptr, 0, stub_remote_pfn, nullptr, 0, nullptr)); if (!remote_thread.GetHandle()) { DWORD const last_error = ::GetLastError(); HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Could not create remote thread.") << ErrorCodeWinLast(last_error)); } // TODO: Add a sensible and configurable timeout. if (::WaitForSingleObject(remote_thread.GetHandle(), INFINITE) != WAIT_OBJECT_0) { DWORD const last_error = ::GetLastError(); HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Could not wait for remote thread.") << ErrorCodeWinLast(last_error)); } } } struct InjectFlags { enum { kNone = 0, kPathResolution = 1 << 0, kAddToSearchOrder = 1 << 1, kKeepSuspended = 1 << 2, kInvalidFlagMaxValue = 1 << 3 }; }; inline HMODULE InjectDll(Process const& process, std::wstring const& path, int flags) { HADESMEM_ASSERT((flags & ~(InjectFlags::kInvalidFlagMaxValue - 1)) == 0); boost::filesystem::path path_real(path); bool const path_resolution = !!(flags & InjectFlags::kPathResolution); if (path_resolution && path_real.is_relative()) { path_real = boost::filesystem::absolute(path_real, detail::GetSelfDirPath()); } path_real.make_preferred(); bool const add_path = !!(flags & InjectFlags::kAddToSearchOrder); if (add_path && path_real.is_relative()) { HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Cannot modify search order unless an absolute path " "or path resolution is used.")); } // Note: Only performing this check when path resolution is enabled, // because otherwise we would need to perform the check in the context // of the remote process, which is not possible to do without // introducing race conditions and other potential problems. So we just // let LoadLibraryW do the check for us. if (path_resolution && !boost::filesystem::exists(path_real)) { HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Could not find module file.")); } detail::ForceLdrInitializeThunk(process.GetId()); std::wstring const path_string(path_real.native()); std::size_t const path_buf_size = (path_string.size() + 1) * sizeof(wchar_t); Allocator const lib_file_remote(process, path_buf_size); WriteString(process, lib_file_remote.GetBase(), path_string); Module const kernel32_mod(process, L"kernel32.dll"); auto const load_library = detail::GetProcAddressInternal(process, kernel32_mod, "LoadLibraryExW"); typedef HMODULE (LoadLibraryExFuncT)(LPCWSTR lpFileName, HANDLE hFile, DWORD dwFlags); auto const load_library_ret = Call<LoadLibraryExFuncT>(process, reinterpret_cast<FnPtr>(load_library), CallConv::kWinApi, static_cast<LPCWSTR>(lib_file_remote.GetBase()), nullptr, add_path ? LOAD_WITH_ALTERED_SEARCH_PATH : 0UL); if (!load_library_ret.GetReturnValue()) { HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Call to LoadLibraryExW in remote process failed.") << ErrorCodeWinLast(load_library_ret.GetLastError())); } return load_library_ret.GetReturnValue(); } inline void FreeDll(Process const& process, HMODULE module) { Module const kernel32_mod(process, L"kernel32.dll"); auto const free_library = detail::GetProcAddressInternal(process, kernel32_mod, "FreeLibrary"); typedef BOOL (FreeLibraryFuncT)(HMODULE hModule); auto const free_library_ret = Call<FreeLibraryFuncT>(process, reinterpret_cast<FnPtr>(free_library), CallConv::kWinApi, module); if (!free_library_ret.GetReturnValue()) { HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Call to FreeLibrary in remote process failed.") << ErrorCodeWinLast(free_library_ret.GetLastError())); } } // TODO: Configurable timeout. inline CallResult<DWORD_PTR> CallExport(Process const& process, HMODULE module, std::string const& export_name) { Module const module_remote(process, module); auto const export_ptr = FindProcedure(module_remote, export_name); return Call<DWORD_PTR()>(process, reinterpret_cast<FnPtr>(export_ptr), CallConv::kDefault); } class CreateAndInjectData { public: explicit CreateAndInjectData(Process const& process, HMODULE module, DWORD_PTR export_ret, DWORD export_last_error) : process_(process), module_(module), export_ret_(export_ret), export_last_error_(export_last_error) { } CreateAndInjectData(CreateAndInjectData const& other) : process_(other.process_), module_(other.module_), export_ret_(other.export_ret_), export_last_error_(other.export_last_error_) { } CreateAndInjectData& operator=(CreateAndInjectData const& other) { process_ = other.process_; module_ = other.module_; export_ret_ = other.export_ret_; export_last_error_ = other.export_last_error_; return *this; } CreateAndInjectData(CreateAndInjectData&& other) HADESMEM_NOEXCEPT : process_(std::move(other.process_)), module_(other.module_), export_ret_(other.export_ret_), export_last_error_(other.export_last_error_) { } CreateAndInjectData& operator=(CreateAndInjectData&& other) HADESMEM_NOEXCEPT { process_ = std::move(other.process_); module_ = other.module_; export_ret_ = other.export_ret_; export_last_error_ = other.export_last_error_; return *this; } ~CreateAndInjectData() HADESMEM_NOEXCEPT { } Process GetProcess() const { return process_; } HMODULE GetModule() const HADESMEM_NOEXCEPT { return module_; } DWORD_PTR GetExportRet() const HADESMEM_NOEXCEPT { return export_ret_; } DWORD GetExportLastError() const HADESMEM_NOEXCEPT { return export_last_error_; } private: Process process_; HMODULE module_; DWORD_PTR export_ret_; DWORD export_last_error_; }; inline CreateAndInjectData CreateAndInject( std::wstring const& path, std::wstring const& work_dir, std::vector<std::wstring> const& args, std::wstring const& module, std::string const& export_name, int flags) { boost::filesystem::path const path_real(path); std::wstring command_line; detail::ArgvQuote(&command_line, path_real.native(), false); std::for_each(std::begin(args), std::end(args), [&] (std::wstring const& arg) { command_line += L' '; detail::ArgvQuote(&command_line, arg, false); }); std::vector<wchar_t> proc_args(std::begin(command_line), std::end(command_line)); proc_args.push_back(L'\0'); boost::filesystem::path work_dir_real; if (!work_dir.empty()) { work_dir_real = work_dir; } else if (path_real.has_parent_path()) { work_dir_real = path_real.parent_path(); } else { work_dir_real = L"./"; } STARTUPINFO start_info; ::ZeroMemory(&start_info, sizeof(start_info)); start_info.cb = sizeof(start_info); PROCESS_INFORMATION proc_info; ::ZeroMemory(&proc_info, sizeof(proc_info)); if (!::CreateProcess(path_real.c_str(), proc_args.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT, nullptr, work_dir_real.c_str(), &start_info, &proc_info)) { DWORD const last_error = ::GetLastError(); HADESMEM_THROW_EXCEPTION(Error() << ErrorString("CreateProcess failed.") << ErrorCodeWinLast(last_error)); } detail::SmartHandle const proc_handle(proc_info.hProcess); detail::SmartHandle const thread_handle(proc_info.hThread); try { Process const process(proc_info.dwProcessId); HMODULE const remote_module = InjectDll(process, module, flags); CallResult<DWORD_PTR> export_ret(0, 0); if (!export_name.empty()) { // TODO: Configurable timeout. export_ret = CallExport(process, remote_module, export_name); } if (!(flags & InjectFlags::kKeepSuspended)) { if (::ResumeThread(thread_handle.GetHandle()) == static_cast<DWORD>(-1)) { DWORD const last_error = ::GetLastError(); HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Could not resume process.") << ErrorCodeWinLast(last_error) << ErrorCodeWinRet(export_ret.GetReturnValue()) << ErrorCodeWinOther(export_ret.GetLastError())); } } return CreateAndInjectData(process, remote_module, export_ret.GetReturnValue(), export_ret.GetLastError()); } catch (std::exception const& /*e*/) { // Terminate process if injection failed, otherwise the 'zombie' process // would be leaked. ::TerminateProcess(proc_handle.GetHandle(), 0); throw; } } } <commit_msg>* Ugly hack to fix GCC warning.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce. // See the file COPYING for copying permission. #pragma once #include <array> #include <string> #include <vector> #include <utility> #include <utility> #include <iterator> #include <algorithm> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/locale.hpp> #include <boost/filesystem.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <windows.h> #include <hadesmem/call.hpp> #include <hadesmem/alloc.hpp> #include <hadesmem/error.hpp> #include <hadesmem/write.hpp> #include <hadesmem/config.hpp> #include <hadesmem/module.hpp> #include <hadesmem/process.hpp> #include <hadesmem/pelib/export.hpp> #include <hadesmem/pelib/pe_file.hpp> #include <hadesmem/detail/assert.hpp> #include <hadesmem/detail/self_path.hpp> #include <hadesmem/pelib/export_list.hpp> #include <hadesmem/detail/smart_handle.hpp> namespace hadesmem { namespace detail { inline FARPROC GetProcAddressInternal(Process const& process, Module const& module, std::string const& export_name) { HADESMEM_STATIC_ASSERT(sizeof(FARPROC) == sizeof(void*)); PeFile const pe_file(process, module.GetHandle(), PeFileType::Image); ExportList const exports(process, pe_file); for (auto const& e : exports) { if (e.ByName() && e.GetName() == export_name) { if (e.IsForwarded()) { Module const forwarder_module(process, boost::locale::conv::utf_to_utf<wchar_t>(e.GetForwarderModule())); return GetProcAddressInternal(process, forwarder_module, e.GetForwarderFunction()); } // TODO: This invokes undefined behavior. Fix this. union Conv { FARPROC pfn; void* va; }; Conv conv; conv.va = e.GetVa(); return conv.pfn; } } return nullptr; } inline void ArgvQuote(std::wstring* command_line, std::wstring const& argument, bool force) { // Unless we're told otherwise, don't quote unless we actually // need to do so (and hopefully avoid problems if programs won't // parse quotes properly). if (!force && !argument.empty() && argument.find_first_of(L" \t\n\v\"") == argument.npos) { command_line->append(argument); } else { command_line->push_back(L'"'); for (auto it = std::begin(argument); ;++it) { std::size_t num_backslashes = 0; while (it != std::end(argument) && *it == L'\\') { ++it; ++num_backslashes; } if (it == std::end(argument)) { // Escape all backslashes, but let the terminating // double quotation mark we add below be interpreted // as a metacharacter. command_line->append(num_backslashes * 2, L'\\'); break; } else if (*it == L'"') { // Escape all backslashes and the following // double quotation mark. command_line->append(num_backslashes * 2 + 1, L'\\'); command_line->push_back(*it); } else { // Backslashes aren't special here. command_line->append(num_backslashes, L'\\'); command_line->push_back(*it); } } command_line->push_back(L'"'); } } inline void ForceLdrInitializeThunk(DWORD proc_id) { Process const process(proc_id); // This is used to generate a 'nullsub' function, which is called in // the context of the remote process in order to 'force' a call to // ntdll.dll!LdrInitializeThunk. This is necessary because module // enumeration will fail if LdrInitializeThunk has not been called, // and Injector::InjectDll (and the APIs it uses) depends on the // module enumeration APIs. #if defined(HADESMEM_ARCH_X64) std::array<BYTE, 1> return_instr = { { 0xC3 } }; #elif defined(HADESMEM_ARCH_X86) std::array<BYTE, 3> return_instr = { { 0xC2, 0x04, 0x00 } }; #else #error "[HadesMem] Unsupported architecture." #endif Allocator const stub_remote(process, sizeof(return_instr)); Write(process, stub_remote.GetBase(), return_instr); auto const stub_remote_pfn = reinterpret_cast<LPTHREAD_START_ROUTINE>( reinterpret_cast<DWORD_PTR>(stub_remote.GetBase())); detail::SmartHandle const remote_thread(::CreateRemoteThread( process.GetHandle(), nullptr, 0, stub_remote_pfn, nullptr, 0, nullptr)); if (!remote_thread.GetHandle()) { DWORD const last_error = ::GetLastError(); HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Could not create remote thread.") << ErrorCodeWinLast(last_error)); } // TODO: Add a sensible and configurable timeout. if (::WaitForSingleObject(remote_thread.GetHandle(), INFINITE) != WAIT_OBJECT_0) { DWORD const last_error = ::GetLastError(); HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Could not wait for remote thread.") << ErrorCodeWinLast(last_error)); } } } struct InjectFlags { enum { kNone = 0, kPathResolution = 1 << 0, kAddToSearchOrder = 1 << 1, kKeepSuspended = 1 << 2, kInvalidFlagMaxValue = 1 << 3 }; }; inline HMODULE InjectDll(Process const& process, std::wstring const& path, int flags) { HADESMEM_ASSERT((flags & ~(InjectFlags::kInvalidFlagMaxValue - 1)) == 0); boost::filesystem::path path_real(path); bool const path_resolution = !!(flags & InjectFlags::kPathResolution); if (path_resolution && path_real.is_relative()) { path_real = boost::filesystem::absolute(path_real, detail::GetSelfDirPath()); } path_real.make_preferred(); bool const add_path = !!(flags & InjectFlags::kAddToSearchOrder); if (add_path && path_real.is_relative()) { HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Cannot modify search order unless an absolute path " "or path resolution is used.")); } // Note: Only performing this check when path resolution is enabled, // because otherwise we would need to perform the check in the context // of the remote process, which is not possible to do without // introducing race conditions and other potential problems. So we just // let LoadLibraryW do the check for us. if (path_resolution && !boost::filesystem::exists(path_real)) { HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Could not find module file.")); } detail::ForceLdrInitializeThunk(process.GetId()); std::wstring const path_string(path_real.native()); std::size_t const path_buf_size = (path_string.size() + 1) * sizeof(wchar_t); Allocator const lib_file_remote(process, path_buf_size); WriteString(process, lib_file_remote.GetBase(), path_string); Module const kernel32_mod(process, L"kernel32.dll"); auto const load_library = detail::GetProcAddressInternal(process, kernel32_mod, "LoadLibraryExW"); typedef HMODULE (LoadLibraryExFuncT)(LPCWSTR lpFileName, HANDLE hFile, DWORD dwFlags); auto const load_library_ret = Call<LoadLibraryExFuncT>(process, reinterpret_cast<FnPtr>(load_library), CallConv::kWinApi, static_cast<LPCWSTR>(lib_file_remote.GetBase()), nullptr, add_path ? LOAD_WITH_ALTERED_SEARCH_PATH : 0UL); if (!load_library_ret.GetReturnValue()) { HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Call to LoadLibraryExW in remote process failed.") << ErrorCodeWinLast(load_library_ret.GetLastError())); } return load_library_ret.GetReturnValue(); } inline void FreeDll(Process const& process, HMODULE module) { Module const kernel32_mod(process, L"kernel32.dll"); auto const free_library = detail::GetProcAddressInternal(process, kernel32_mod, "FreeLibrary"); typedef BOOL (FreeLibraryFuncT)(HMODULE hModule); auto const free_library_ret = Call<FreeLibraryFuncT>(process, reinterpret_cast<FnPtr>(free_library), CallConv::kWinApi, module); if (!free_library_ret.GetReturnValue()) { HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Call to FreeLibrary in remote process failed.") << ErrorCodeWinLast(free_library_ret.GetLastError())); } } // TODO: Configurable timeout. inline CallResult<DWORD_PTR> CallExport(Process const& process, HMODULE module, std::string const& export_name) { Module const module_remote(process, module); auto const export_ptr = FindProcedure(module_remote, export_name); return Call<DWORD_PTR()>(process, reinterpret_cast<FnPtr>(export_ptr), CallConv::kDefault); } class CreateAndInjectData { public: explicit CreateAndInjectData(Process const& process, HMODULE module, DWORD_PTR export_ret, DWORD export_last_error) : process_(process), module_(module), export_ret_(export_ret), export_last_error_(export_last_error) { } CreateAndInjectData(CreateAndInjectData const& other) : process_(other.process_), module_(other.module_), export_ret_(other.export_ret_), export_last_error_(other.export_last_error_) { } CreateAndInjectData& operator=(CreateAndInjectData const& other) { process_ = other.process_; module_ = other.module_; export_ret_ = other.export_ret_; export_last_error_ = other.export_last_error_; return *this; } CreateAndInjectData(CreateAndInjectData&& other) HADESMEM_NOEXCEPT : process_(std::move(other.process_)), module_(other.module_), export_ret_(other.export_ret_), export_last_error_(other.export_last_error_) { } CreateAndInjectData& operator=(CreateAndInjectData&& other) HADESMEM_NOEXCEPT { process_ = std::move(other.process_); module_ = other.module_; export_ret_ = other.export_ret_; export_last_error_ = other.export_last_error_; return *this; } ~CreateAndInjectData() HADESMEM_NOEXCEPT { } Process GetProcess() const { return process_; } HMODULE GetModule() const HADESMEM_NOEXCEPT { return module_; } DWORD_PTR GetExportRet() const HADESMEM_NOEXCEPT { return export_ret_; } DWORD GetExportLastError() const HADESMEM_NOEXCEPT { return export_last_error_; } private: Process process_; HMODULE module_; DWORD_PTR export_ret_; DWORD export_last_error_; }; inline CreateAndInjectData CreateAndInject( std::wstring const& path, std::wstring const& work_dir, std::vector<std::wstring> const& args, std::wstring const& module, std::string const& export_name, int flags) { boost::filesystem::path const path_real(path); std::wstring command_line; detail::ArgvQuote(&command_line, path_real.native(), false); std::for_each(std::begin(args), std::end(args), [&] (std::wstring const& arg) { command_line += L' '; detail::ArgvQuote(&command_line, arg, false); }); std::vector<wchar_t> proc_args(std::begin(command_line), std::end(command_line)); proc_args.push_back(L'\0'); boost::filesystem::path work_dir_real; if (!work_dir.empty()) { work_dir_real = work_dir; } else if (path_real.has_parent_path()) { work_dir_real = path_real.parent_path(); } else { work_dir_real = L"./"; } STARTUPINFO start_info; ::ZeroMemory(&start_info, sizeof(start_info)); start_info.cb = sizeof(start_info); PROCESS_INFORMATION proc_info; ::ZeroMemory(&proc_info, sizeof(proc_info)); if (!::CreateProcess(path_real.c_str(), proc_args.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT, nullptr, work_dir_real.c_str(), &start_info, &proc_info)) { DWORD const last_error = ::GetLastError(); HADESMEM_THROW_EXCEPTION(Error() << ErrorString("CreateProcess failed.") << ErrorCodeWinLast(last_error)); } detail::SmartHandle const proc_handle(proc_info.hProcess); detail::SmartHandle const thread_handle(proc_info.hThread); try { Process const process(proc_info.dwProcessId); HMODULE const remote_module = InjectDll(process, module, flags); CallResult<DWORD_PTR> export_ret(0, 0); if (!export_name.empty()) { // TODO: Configurable timeout. export_ret = CallExport(process, remote_module, export_name); } if (!(flags & InjectFlags::kKeepSuspended)) { if (::ResumeThread(thread_handle.GetHandle()) == static_cast<DWORD>(-1)) { DWORD const last_error = ::GetLastError(); HADESMEM_THROW_EXCEPTION(Error() << ErrorString("Could not resume process.") << ErrorCodeWinLast(last_error) << ErrorCodeWinRet(export_ret.GetReturnValue()) << ErrorCodeWinOther(export_ret.GetLastError())); } } return CreateAndInjectData(process, remote_module, export_ret.GetReturnValue(), export_ret.GetLastError()); } catch (std::exception const& /*e*/) { // Terminate process if injection failed, otherwise the 'zombie' process // would be leaked. ::TerminateProcess(proc_handle.GetHandle(), 0); throw; } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <set> #include <mutex> #include <array> #include <tuple> #include <utility> #include <variant> #include "item.hpp" #include "screens/base.hpp" #include "components/script_butler.hpp" namespace bookwyrm { class multiselect_menu; class script_butler; class multiselect_menu : public screen_base { public: explicit multiselect_menu(vector<item> &items); void display(); void update(); private: enum move_direction { top, up, down, bot }; /* Store data about each column between updates. */ struct columns_t { struct column_t { using width_w_t = std::variant<int, double>; /* * width_w(wanted). * How much space does the column want? * Can be specified as an absolute value or * as a multiplier, e.g. 0.30 for 30% of tb_width(). */ width_w_t width_w; /* Changes whenever the window dimensions are changed. */ size_t width, startx; string title; }; void operator=(vector<std::pair<string, column_t::width_w_t>> &&pairs) { int i = 0; for (auto &&pair : pairs) { columns_[i].width_w = std::get<1>(pair); columns_[i++].title = std::get<0>(pair); } } column_t& operator[](size_t i) { return columns_[i]; } size_t size() { return columns_.size(); } auto begin() { return columns_.begin(); } auto end() { return columns_.end(); } private: std::array<column_t, 6> columns_; } columns_; /* Index of the currently selected item. */ size_t selected_item_; /* How many lines have we scrolled? */ size_t scroll_offset_; std::mutex menu_mutex_; vector<item> const &items_; /* Item indices marked for download. */ std::set<int> marked_items_; size_t item_count() const { return items_.size(); } bool is_marked(size_t idx) const { return marked_items_.find(idx) != marked_items_.cend(); } /* How many entries can the menu print in the terminal? */ size_t menu_capacity() const { return tb_height() - padding_bot_ - padding_top_; } /* * Is the currently selected item the last one in the * menu "window"? */ bool menu_at_bot() const { return selected_item_ == (menu_capacity() - 1 + scroll_offset_); } /* * Is the currently selected item the first one in the * menu "window"? */ bool menu_at_top() const { return selected_item_ == scroll_offset_; } /* Move up and down the menu. */ void move(move_direction dir); /* Select (or unselect) the current item for download. */ void toggle_select(); void mark_item(const size_t idx) { marked_items_.insert(idx); } void unmark_item(const size_t idx) { marked_items_.erase(idx); } /* Returns true if the bookwyrm fits in the current terminal window. */ bool bookwyrm_fits() { /* * I planned to use the classical 80x24, but this menu is * in its current form useable in terminals much smaller * than that. */ return get_width() >= 50 && get_height() >= 10; } void update_column_widths(); void on_resize(); void print_scrollbar(); void print_header(); void print_column(const size_t col_idx); }; } /* ns bookwyrm */ <commit_msg>alignment semantics<commit_after>/* * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <set> #include <mutex> #include <array> #include <tuple> #include <utility> #include <variant> #include "item.hpp" #include "screens/base.hpp" #include "components/script_butler.hpp" namespace bookwyrm { class multiselect_menu; class script_butler; class multiselect_menu : public screen_base { public: explicit multiselect_menu(vector<item> &items); void display(); void update(); private: enum move_direction { top, up, down, bot }; /* Store data about each column between updates. */ struct columns_t { struct column_t { using width_w_t = std::variant<int, double>; /* * width_w(wanted). * How much space does the column want? * Can be specified as an absolute value or * as a multiplier, e.g. 0.30 for 30% of tb_width(). */ width_w_t width_w; /* Changes whenever the window dimensions are changed. */ size_t width, startx; string title; }; void operator=(vector<std::pair<string, column_t::width_w_t>> &&pairs) { int i = 0; for (auto &&pair : pairs) { columns_[i].width_w = std::get<1>(pair); columns_[i++].title = std::get<0>(pair); } } column_t& operator[](size_t i) { return columns_[i]; } size_t size() { return columns_.size(); } auto begin() { return columns_.begin(); } auto end() { return columns_.end(); } private: std::array<column_t, 6> columns_; } columns_; /* Index of the currently selected item. */ size_t selected_item_; /* How many lines have we scrolled? */ size_t scroll_offset_; std::mutex menu_mutex_; vector<item> const &items_; /* Item indices marked for download. */ std::set<int> marked_items_; size_t item_count() const { return items_.size(); } bool is_marked(size_t idx) const { return marked_items_.find(idx) != marked_items_.cend(); } /* How many entries can the menu print in the terminal? */ size_t menu_capacity() const { return tb_height() - padding_bot_ - padding_top_; } /* * Is the currently selected item the last one in the * menu "window"? */ bool menu_at_bot() const { return selected_item_ == (menu_capacity() - 1 + scroll_offset_); } /* * Is the currently selected item the first one in the * menu "window"? */ bool menu_at_top() const { return selected_item_ == scroll_offset_; } /* Move up and down the menu. */ void move(move_direction dir); /* Select (or unselect) the current item for download. */ void toggle_select(); void mark_item(const size_t idx) { marked_items_.insert(idx); } void unmark_item(const size_t idx) { marked_items_.erase(idx); } /* Returns true if the bookwyrm fits in the current terminal window. */ bool bookwyrm_fits() { /* * I planned to use the classical 80x24, but this menu is * in its current form useable in terminals much smaller * than that. */ return get_width() >= 50 && get_height() >= 10; } void update_column_widths(); void on_resize(); void print_scrollbar(); void print_header(); void print_column(const size_t col_idx); }; } /* ns bookwyrm */ <|endoftext|>
<commit_before> #include <glbinding/callbacks.h> #include <sstream> #include <iomanip> #include <type_traits> #include <glbinding/AbstractValue.h> #include <glbinding/Binding.h> namespace { glbinding::SimpleFunctionCallback g_unresolvedCallback; glbinding::FunctionCallback g_beforeCallback; glbinding::FunctionCallback g_afterCallback; } namespace glbinding { FunctionCall::FunctionCall(const AbstractFunction * _function) : function{_function} , timestamp{std::chrono::high_resolution_clock::now()} , returnValue{nullptr} { } FunctionCall::FunctionCall(FunctionCall && other) : function{std::move(other.function)} , parameters{std::move(other.parameters)} , returnValue{std::move(other.returnValue)} { } FunctionCall::~FunctionCall() { delete returnValue; for (AbstractValue * value : parameters) { delete value; } } CallbackMask operator|(const CallbackMask a, const CallbackMask b) { using callback_mask_t = std::underlying_type<CallbackMask>::type; return static_cast<CallbackMask>(static_cast<callback_mask_t>(a) | static_cast<callback_mask_t>(b)); } CallbackMask operator~(CallbackMask a) { using callback_mask_t = std::underlying_type<CallbackMask>::type; return static_cast<CallbackMask>(~static_cast<callback_mask_t>(a)); } CallbackMask operator&(CallbackMask a, CallbackMask b) { using callback_mask_t = std::underlying_type<CallbackMask>::type; return static_cast<CallbackMask>(static_cast<callback_mask_t>(a) & static_cast<callback_mask_t>(b)); } CallbackMask& operator|=(CallbackMask& a, CallbackMask b) { a = a | b; return a; } CallbackMask& operator&=(CallbackMask& a, CallbackMask b) { a = a & b; return a; } std::string FunctionCall::toString() const { using nanoseconds = std::chrono::nanoseconds; nanoseconds now_ns = std::chrono::duration_cast<nanoseconds>(timestamp.time_since_epoch()); std::size_t ns = now_ns.count() % 1000; std::ostringstream ns_os; ns_os << std::setfill('0') << std::setw(3) << ns; using milliseconds = std::chrono::milliseconds; milliseconds now_ms = std::chrono::duration_cast<milliseconds>(now_ns); std::size_t ms = now_ms.count() % 1000; std::ostringstream ms_os; ms_os << std::setfill('0') << std::setw(3) << ms; using seconds = std::chrono::seconds; seconds now_s = std::chrono::duration_cast<seconds>(now_ms); std::time_t t = now_s.count(); char time_string[20]; std::strftime(time_string, sizeof(time_string), "%F_%H-%M-%S", std::localtime(&t)); std::ostringstream os; os << time_string << ":" << ms_os.str() << ":" << ns_os.str() << " "; os << function->name() << "("; for (unsigned i = 0; i < parameters.size(); ++i) { os << parameters[i]->asString(); if (i < parameters.size() - 1) os << ", "; } os << ")"; if (returnValue) { os << " -> " << returnValue->asString(); } os << std::endl; std::string input = os.str(); return input; } void setCallbackMask(const CallbackMask mask) { for (AbstractFunction * function : Binding::functions()) { function->setCallbackMask(mask); } } void setCallbackMaskExcept(const CallbackMask mask, const std::set<std::string> & blackList) { for (AbstractFunction * function : Binding::functions()) { if (blackList.find(function->name()) == blackList.end()) { function->setCallbackMask(mask); } } } void addCallbackMask(const CallbackMask mask) { for (AbstractFunction * function : Binding::functions()) { function->addCallbackMask(mask); } } void removeCallbackMask(const CallbackMask mask) { for (AbstractFunction * function : Binding::functions()) { function->removeCallbackMask(mask); } } void setUnresolvedCallback(SimpleFunctionCallback callback) { g_unresolvedCallback = std::move(callback); } void setBeforeCallback(FunctionCallback callback) { g_beforeCallback = std::move(callback); } void setAfterCallback(FunctionCallback callback) { g_afterCallback = std::move(callback); } void unresolved(const AbstractFunction * function) { g_unresolvedCallback(*function); } void before(const FunctionCall & call) { g_beforeCallback(call); } void after(const FunctionCall & call) { g_afterCallback(call); } } // namespace glbinding <commit_msg>Fix error C2797 (maybe)<commit_after> #include <glbinding/callbacks.h> #include <sstream> #include <iomanip> #include <type_traits> #include <glbinding/AbstractValue.h> #include <glbinding/Binding.h> namespace { glbinding::SimpleFunctionCallback g_unresolvedCallback; glbinding::FunctionCallback g_beforeCallback; glbinding::FunctionCallback g_afterCallback; } namespace glbinding { FunctionCall::FunctionCall(const AbstractFunction * _function) : function{_function} , timestamp{std::chrono::high_resolution_clock::now()} , returnValue{nullptr} { } FunctionCall::FunctionCall(FunctionCall && other) : function{std::move(other.function)} , parameters{std::vector<AbstractValue *>{std::move(other.parameters)}} , returnValue{std::move(other.returnValue)} { } FunctionCall::~FunctionCall() { delete returnValue; for (AbstractValue * value : parameters) { delete value; } } CallbackMask operator|(const CallbackMask a, const CallbackMask b) { using callback_mask_t = std::underlying_type<CallbackMask>::type; return static_cast<CallbackMask>(static_cast<callback_mask_t>(a) | static_cast<callback_mask_t>(b)); } CallbackMask operator~(CallbackMask a) { using callback_mask_t = std::underlying_type<CallbackMask>::type; return static_cast<CallbackMask>(~static_cast<callback_mask_t>(a)); } CallbackMask operator&(CallbackMask a, CallbackMask b) { using callback_mask_t = std::underlying_type<CallbackMask>::type; return static_cast<CallbackMask>(static_cast<callback_mask_t>(a) & static_cast<callback_mask_t>(b)); } CallbackMask& operator|=(CallbackMask& a, CallbackMask b) { a = a | b; return a; } CallbackMask& operator&=(CallbackMask& a, CallbackMask b) { a = a & b; return a; } std::string FunctionCall::toString() const { using nanoseconds = std::chrono::nanoseconds; nanoseconds now_ns = std::chrono::duration_cast<nanoseconds>(timestamp.time_since_epoch()); std::size_t ns = now_ns.count() % 1000; std::ostringstream ns_os; ns_os << std::setfill('0') << std::setw(3) << ns; using milliseconds = std::chrono::milliseconds; milliseconds now_ms = std::chrono::duration_cast<milliseconds>(now_ns); std::size_t ms = now_ms.count() % 1000; std::ostringstream ms_os; ms_os << std::setfill('0') << std::setw(3) << ms; using seconds = std::chrono::seconds; seconds now_s = std::chrono::duration_cast<seconds>(now_ms); std::time_t t = now_s.count(); char time_string[20]; std::strftime(time_string, sizeof(time_string), "%F_%H-%M-%S", std::localtime(&t)); std::ostringstream os; os << time_string << ":" << ms_os.str() << ":" << ns_os.str() << " "; os << function->name() << "("; for (unsigned i = 0; i < parameters.size(); ++i) { os << parameters[i]->asString(); if (i < parameters.size() - 1) os << ", "; } os << ")"; if (returnValue) { os << " -> " << returnValue->asString(); } os << std::endl; std::string input = os.str(); return input; } void setCallbackMask(const CallbackMask mask) { for (AbstractFunction * function : Binding::functions()) { function->setCallbackMask(mask); } } void setCallbackMaskExcept(const CallbackMask mask, const std::set<std::string> & blackList) { for (AbstractFunction * function : Binding::functions()) { if (blackList.find(function->name()) == blackList.end()) { function->setCallbackMask(mask); } } } void addCallbackMask(const CallbackMask mask) { for (AbstractFunction * function : Binding::functions()) { function->addCallbackMask(mask); } } void removeCallbackMask(const CallbackMask mask) { for (AbstractFunction * function : Binding::functions()) { function->removeCallbackMask(mask); } } void setUnresolvedCallback(SimpleFunctionCallback callback) { g_unresolvedCallback = std::move(callback); } void setBeforeCallback(FunctionCallback callback) { g_beforeCallback = std::move(callback); } void setAfterCallback(FunctionCallback callback) { g_afterCallback = std::move(callback); } void unresolved(const AbstractFunction * function) { g_unresolvedCallback(*function); } void before(const FunctionCall & call) { g_beforeCallback(call); } void after(const FunctionCall & call) { g_afterCallback(call); } } // namespace glbinding <|endoftext|>
<commit_before>/* * Copyright (C) 2011 Google 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: * * 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/rendering/RenderThemeChromiumAndroid.h" #include "CSSValueKeywords.h" #include "InputTypeNames.h" #include "UserAgentStyleSheets.h" #include "core/platform/ScrollbarTheme.h" #include "core/rendering/PaintInfo.h" #include "core/rendering/RenderMediaControls.h" #include "core/rendering/RenderObject.h" #include "core/rendering/RenderProgress.h" #include "core/rendering/RenderSlider.h" #include "platform/LayoutTestSupport.h" #include "platform/graphics/Color.h" #include "public/platform/android/WebThemeEngine.h" #include "public/platform/Platform.h" #include "wtf/StdLibExtras.h" namespace WebCore { PassRefPtr<RenderTheme> RenderThemeChromiumAndroid::create() { return adoptRef(new RenderThemeChromiumAndroid()); } RenderTheme& RenderTheme::theme() { DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumAndroid::create())); return *renderTheme; } RenderThemeChromiumAndroid::~RenderThemeChromiumAndroid() { } Color RenderThemeChromiumAndroid::systemColor(CSSValueID cssValueId) const { if (isRunningLayoutTest() && cssValueId == CSSValueButtonface) { // Match Linux button color in layout tests. static const Color linuxButtonGrayColor(0xffdddddd); return linuxButtonGrayColor; } return RenderTheme::systemColor(cssValueId); } String RenderThemeChromiumAndroid::extraMediaControlsStyleSheet() { return String(mediaControlsAndroidUserAgentStyleSheet, sizeof(mediaControlsAndroidUserAgentStyleSheet)); } String RenderThemeChromiumAndroid::extraDefaultStyleSheet() { return RenderThemeChromiumDefault::extraDefaultStyleSheet() + String(themeChromiumAndroidUserAgentStyleSheet, sizeof(themeChromiumAndroidUserAgentStyleSheet)); } void RenderThemeChromiumAndroid::adjustInnerSpinButtonStyle(RenderStyle* style, Element*) const { if (isRunningLayoutTest()) { // Match Linux spin button style in layout tests. // FIXME: Consider removing the conditional if a future Android theme matches this. IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartInnerSpinButton); style->setWidth(Length(size.width(), Fixed)); style->setMinWidth(Length(size.width(), Fixed)); } } bool RenderThemeChromiumAndroid::paintMediaOverlayPlayButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect) { return RenderMediaControls::paintMediaControlsPart(MediaOverlayPlayButton, object, paintInfo, rect); } int RenderThemeChromiumAndroid::menuListArrowPadding() const { // We cannot use the scrollbar thickness here, as it's width is 0 on Android. // Instead, use the width of the scrollbar down arrow. IntSize scrollbarSize = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartScrollbarDownArrow); return scrollbarSize.width(); } bool RenderThemeChromiumAndroid::supportsDataListUI(const AtomicString& type) const { // FIXME: Add other input types. return type == InputTypeNames::color; } } // namespace WebCore <commit_msg>Enable datalist for text field input types on Android<commit_after>/* * Copyright (C) 2011 Google 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: * * 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/rendering/RenderThemeChromiumAndroid.h" #include "CSSValueKeywords.h" #include "InputTypeNames.h" #include "UserAgentStyleSheets.h" #include "core/platform/ScrollbarTheme.h" #include "core/rendering/PaintInfo.h" #include "core/rendering/RenderMediaControls.h" #include "core/rendering/RenderObject.h" #include "core/rendering/RenderProgress.h" #include "core/rendering/RenderSlider.h" #include "platform/LayoutTestSupport.h" #include "platform/graphics/Color.h" #include "public/platform/android/WebThemeEngine.h" #include "public/platform/Platform.h" #include "wtf/StdLibExtras.h" namespace WebCore { PassRefPtr<RenderTheme> RenderThemeChromiumAndroid::create() { return adoptRef(new RenderThemeChromiumAndroid()); } RenderTheme& RenderTheme::theme() { DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumAndroid::create())); return *renderTheme; } RenderThemeChromiumAndroid::~RenderThemeChromiumAndroid() { } Color RenderThemeChromiumAndroid::systemColor(CSSValueID cssValueId) const { if (isRunningLayoutTest() && cssValueId == CSSValueButtonface) { // Match Linux button color in layout tests. static const Color linuxButtonGrayColor(0xffdddddd); return linuxButtonGrayColor; } return RenderTheme::systemColor(cssValueId); } String RenderThemeChromiumAndroid::extraMediaControlsStyleSheet() { return String(mediaControlsAndroidUserAgentStyleSheet, sizeof(mediaControlsAndroidUserAgentStyleSheet)); } String RenderThemeChromiumAndroid::extraDefaultStyleSheet() { return RenderThemeChromiumDefault::extraDefaultStyleSheet() + String(themeChromiumAndroidUserAgentStyleSheet, sizeof(themeChromiumAndroidUserAgentStyleSheet)); } void RenderThemeChromiumAndroid::adjustInnerSpinButtonStyle(RenderStyle* style, Element*) const { if (isRunningLayoutTest()) { // Match Linux spin button style in layout tests. // FIXME: Consider removing the conditional if a future Android theme matches this. IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartInnerSpinButton); style->setWidth(Length(size.width(), Fixed)); style->setMinWidth(Length(size.width(), Fixed)); } } bool RenderThemeChromiumAndroid::paintMediaOverlayPlayButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect) { return RenderMediaControls::paintMediaControlsPart(MediaOverlayPlayButton, object, paintInfo, rect); } int RenderThemeChromiumAndroid::menuListArrowPadding() const { // We cannot use the scrollbar thickness here, as it's width is 0 on Android. // Instead, use the width of the scrollbar down arrow. IntSize scrollbarSize = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartScrollbarDownArrow); return scrollbarSize.width(); } bool RenderThemeChromiumAndroid::supportsDataListUI(const AtomicString& type) const { // FIXME: Add other input types. return type == InputTypeNames::text || type == InputTypeNames::search || type == InputTypeNames::url || type == InputTypeNames::tel || type == InputTypeNames::email || type == InputTypeNames::number || type == InputTypeNames::color; } } // namespace WebCore <|endoftext|>
<commit_before>#include "roomsreader.h" RRNode::RRNode(TiXmlElement *root) { this->root = root; parent = 0; gotoRoot(); } RRNode::~RRNode() { } RRNode *RRNode::gotoElement(string name) { cursor = findElement(root, name); if (!isNull()) parent = cursor->Parent()->ToElement(); else parent = 0; return this; } RRNode *RRNode::gotoRoot() { cursor = root; parent = 0; return this; } RRNode *RRNode::gotoChild(string name) { if(!isNull()) { parent = cursor; cursor = cursor->FirstChildElement(name.c_str()); } return this; } RRNode *RRNode::gotoParent() { cursor = parent; if(!isNull()) { parent = cursor->Parent()->ToElement(); } return this; } RRNode *RRNode::gotoNext() { if(!isNull()) cursor = cursor->NextSiblingElement(cursor->Value()); return this; } RRNode *RRNode::appendElement(string name) { if(!isNull()) { TiXmlElement *new_elem = new TiXmlElement(name.c_str()); cursor->LinkEndChild(new_elem); parent = cursor; cursor = new_elem; } return this; } bool RRNode::isNull() { bool result = cursor; return !result; } int RRNode::attrInt(string name) { int tmp = 0; cursor->QueryIntAttribute(name.c_str(), &tmp); return tmp; } float RRNode::attrFloat(string name) { float tmp = 0.0; cursor->QueryFloatAttribute(name.c_str(), &tmp); return tmp; } string RRNode::attrStr(string name) { return cursor->Attribute(name.c_str()); } void RRNode::setAttr(string name, string value) { cursor->SetAttribute(name.c_str(), value.c_str()); } Event *RRNode::fetchEvent() { if (isNull()) return 0; Event *event = new Event(attrStr("id")); for (gotoChild("item_req"); !isNull(); gotoNext()) event->addItemReq(attrStr("id"), attrStr("value")); gotoParent(); for (gotoChild("var_req"); !isNull(); gotoNext()) event->addVarReq(attrStr("id"), attrInt("value")); gotoParent(); for (gotoChild("action"); !isNull(); gotoNext()) { Action *act = event->addAction(attrStr("id")); for (gotoChild("param"); !isNull(); gotoNext()) act->pushParam(attrStr("value")); gotoParent(); } gotoParent(); return event; } Room *RRNode::fetchRoom() { if (isNull()) return 0; Room *room = new Room(attrStr("id")); room->bg(attrStr("bg")); for (gotoChild("area"); !isNull(); gotoNext()) { Area *area = room->addArea(attrStr("id")); area->setSize(attrFloat("x"), attrFloat("y"), attrFloat("width"), attrFloat("height")); area->setEvent(attrStr("event")); } gotoParent(); return room; } Item *RRNode::fetchItem() { if (isNull()) return 0; Item *item = new Item(attrStr("id")); item->setSize(attrFloat("x"), attrFloat("y"), attrFloat("width"), attrFloat("height")); item->setEvent(attrStr("event")); item->setImage(attrStr("image")); item->move(attrStr("room")); return item; } Dialog *RRNode::fetchDialog() { if (isNull()) return 0; Dialog *d = new Dialog(attrStr("id"), attrStr("start")); for (gotoChild("step"); !isNull(); gotoNext()) { DialogStep *step = d->addStep(attrStr("id"), attrStr("text")); step->event = fetchEvent(); for (gotoChild("link"); !isNull(); gotoNext()) d->addLink(step->id, attrStr("id"), attrStr("text")); gotoParent(); } gotoParent(); return d; } TiXmlElement *RRNode::findElement(TiXmlElement *elem, string name) { if (elem == 0) return 0; if (string(elem->Value()) == name) return elem; TiXmlElement *result = findElement(elem->NextSiblingElement(), name); if (result != 0) return result; result = findElement(elem->FirstChildElement(), name); if (result != 0) return result; return 0; } string floatToStr(const float f) { std::ostringstream os; os << f; return os.str(); } string upgradeFrom1To2(string content) { TiXmlDocument doc; doc.Parse(content.c_str()); RRNode node(doc.RootElement()); node.gotoElement("world"); int w = node.attrInt("width"); int h = node.attrInt("height"); node.setAttr("version", "2"); for (node.gotoElement("items")->gotoChild("item"); !node.isNull(); node.gotoNext()) { node.setAttr("x", floatToStr(node.attrFloat("x") / w)); node.setAttr("y", floatToStr(node.attrFloat("y") / h)); node.setAttr("width", floatToStr(node.attrFloat("width") / w)); node.setAttr("height", floatToStr(node.attrFloat("height") / h)); } for (node.gotoElement("rooms")->gotoChild("room"); !node.isNull(); node.gotoNext()) { for (node.gotoChild("area"); !node.isNull(); node.gotoNext()) { node.setAttr("x", floatToStr(node.attrFloat("x") / w)); node.setAttr("y", floatToStr(node.attrFloat("y") / h)); node.setAttr("width", floatToStr(node.attrFloat("width") / w)); node.setAttr("height", floatToStr(node.attrFloat("height") / h)); } node.gotoParent(); } TiXmlPrinter printer; doc.Accept(&printer); return printer.CStr(); } const int RoomsReader::VERSION = 2; RoomsReader::RoomsReader() { crawler = 0; doc = 0; parse_map["world"] = &RoomsReader::parseWorld; parse_map["room"] = &RoomsReader::parseRoom; parse_map["area"] = &RoomsReader::parseArea; parse_map["action"] = &RoomsReader::parseAction; parse_map["event"] = &RoomsReader::parseEvent; parse_map["dialog"] = &RoomsReader::parseDialog; parse_map["step"] = &RoomsReader::parseDialogStep; parse_map["var"] = &RoomsReader::parseVar; parse_map["item"] = &RoomsReader::parseItem; parse_map["param"] = &RoomsReader::parseParam; parse_map["item_req"] = &RoomsReader::parseItemReq; parse_map["var_req"] = &RoomsReader::parseVarReq; parse_map["img"] = &RoomsReader::parseImages; } RoomsReader::~RoomsReader() { if(crawler) delete crawler; if (doc) delete doc; } RoomsReader::UpgradeFunc RoomsReader::upgrade_funcs[] = {upgradeFrom1To2}; bool RoomsReader::loadFromFile(const string filename) { std::ifstream xml(filename.c_str(), std::ios::binary); if (!xml.good()) return false; xml.seekg (0, std::ios::end); long length = xml.tellg(); if (length == 0) return false; char *buffer = new char [length]; xml.seekg (0, std::ios::beg); xml.read(buffer, length); bool res = loadFromStr(buffer); xml.close(); delete [] buffer; return res; } bool RoomsReader::loadFromStr(const string content) { doc = new TiXmlDocument; doc->Parse(content.c_str()); crawler = new RRNode(doc->RootElement()); file_content = content; return true; } void RoomsReader::loadEmptyDoc() { if (doc != 0) delete doc; doc = new TiXmlDocument; TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "", ""); TiXmlElement *element = new TiXmlElement("world"); doc->LinkEndChild(decl); doc->LinkEndChild(element); crawler = new RRNode(doc->RootElement()); } void RoomsReader::saveDoc(string filename) { if (!doc->SaveFile(filename.c_str())) logger.write("Cannot save to " + filename, Log::ERROR); } string RoomsReader::upgrade(string content) { for (int i = file_version; i < VERSION; ++i) { logger.write("Updating from v." + floatToStr(i) + " to v." + floatToStr(i + 1), Log::NOTE); content = upgrade_funcs[i - 1](content); } logger.write("Upgrade successful!", Log::WARNING); file_content = content; return content; } bool RoomsReader::parse() { if (!parseElement(doc->RootElement())) { delete doc; doc = 0; if (file_version < VERSION) { logger.write("Old version detected: " + floatToStr(file_version) + ". Upgrading...", Log::WARNING); string new_content = upgrade(file_content); loadFromStr(new_content); return parse(); } return false; } return true; } RRNode *RoomsReader::getCrawler() { return crawler; } bool RoomsReader::checkUniqueId(std::set<string> &ids, const string id) { if (ids.count(id) != 0) return false; ids.insert(id); return true; } bool RoomsReader::checkParent(TiXmlElement *elem, string name) { return (elem->Parent() != 0 && string(elem->Parent()->Value()) == name); } bool RoomsReader::parseElement(TiXmlElement *elem) { if (elem == 0) return true; bool value = true; if (parse_map.find(elem->Value()) != parse_map.end()) { ParseMethod method = parse_map.find(elem->Value())->second; value = (this->*method)(elem); } return (value && parseElement(elem->FirstChildElement()) && parseElement(elem->NextSiblingElement())); } bool RoomsReader::parseArea(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "x", ATTR_FLOAT) && parseAttr(elem, "y", ATTR_FLOAT) && parseAttr(elem, "width", ATTR_FLOAT) && parseAttr(elem, "height", ATTR_FLOAT))) return false; if (!(checkUniqueId(unique_ids_areas, elem->Attribute("id")) && checkParent(elem, "room"))) return false; return true; } bool RoomsReader::parseItem(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "room", ATTR_STR) && parseAttr(elem, "image", ATTR_STR) && parseAttr(elem, "x", ATTR_FLOAT) && parseAttr(elem, "y", ATTR_FLOAT) && parseAttr(elem, "width", ATTR_FLOAT) && parseAttr(elem, "height", ATTR_FLOAT))) return false; if (!(checkUniqueId(unique_ids_items, elem->Attribute("id")) && checkParent(elem, "items") && !checkUniqueId(unique_ids_images, elem->Attribute("image")))) return false; return true; } bool RoomsReader::parseRoom(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "bg", ATTR_STR))) return false; if (!(checkUniqueId(unique_ids_rooms, elem->Attribute("id")) && checkParent(elem, "rooms"))) return false; return true; } bool RoomsReader::parseAction(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && (checkParent(elem, "event") || checkParent(elem, "step")))) return false; return true; } bool RoomsReader::parseWorld(TiXmlElement *elem) { if (!(parseAttr(elem, "version", ATTR_INT) && parseAttr(elem, "name", ATTR_STR) && parseAttr(elem, "start", ATTR_STR) && parseAttr(elem, "width", ATTR_INT) && parseAttr(elem, "height", ATTR_INT))) return false; elem->QueryIntAttribute("version", &file_version); if (file_version != VERSION) return false; return true; } bool RoomsReader::parseEvent(TiXmlElement *elem) { if (!parseAttr(elem, "id", ATTR_STR)) return false; if (!(checkUniqueId(unique_ids_events, elem->Attribute("id")) && checkParent(elem, "events"))) return false; return true; } bool RoomsReader::parseVar(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "value", ATTR_STR) && checkParent(elem, "vars"))) return false; return true; } bool RoomsReader::parseImages(TiXmlElement *elem) { if (!(parseAttr(elem, "file", ATTR_STR) && checkParent(elem, "images"))) return false; if (!checkUniqueId(unique_ids_images, elem->Attribute("file"))) return false; return true; } bool RoomsReader::parseItemReq(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "value", ATTR_STR))) return false; if (!(!checkUniqueId(unique_ids_items, elem->Attribute("id")) && (checkParent(elem, "event") || checkParent(elem, "step")))) return false; return true; } bool RoomsReader::parseVarReq(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "value", ATTR_INT))) return false; if (!(checkParent(elem, "event") || checkParent(elem, "step"))) return false; return true; } bool RoomsReader::parseParam(TiXmlElement *elem) { if (!parseAttr(elem, "value", ATTR_STR)) return false; return true; } bool RoomsReader::parseDialog(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "start", ATTR_STR))) return false; if (!(checkUniqueId(unique_ids_dialogs, elem->Attribute("id")) && checkParent(elem, "dialogs"))) return false; return true; } bool RoomsReader::parseDialogStep(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "text", ATTR_STR) && checkParent(elem, "dialog"))) return false; return true; } bool RoomsReader::parseAttr(TiXmlElement *elem, string name, AttributeType type) { switch (type) { case ATTR_FLOAT: { float tmp; return (elem->QueryFloatAttribute(name.c_str(), &tmp) == TIXML_SUCCESS); break; } case ATTR_INT: { int tmp; return (elem->QueryIntAttribute(name.c_str(), &tmp) == TIXML_SUCCESS); break; } case ATTR_STR: { return (elem->Attribute(name.c_str())); break; } default: { return false; break; } } } <commit_msg>Removed useless check<commit_after>#include "roomsreader.h" RRNode::RRNode(TiXmlElement *root) { this->root = root; parent = 0; gotoRoot(); } RRNode::~RRNode() { } RRNode *RRNode::gotoElement(string name) { cursor = findElement(root, name); if (!isNull()) parent = cursor->Parent()->ToElement(); else parent = 0; return this; } RRNode *RRNode::gotoRoot() { cursor = root; parent = 0; return this; } RRNode *RRNode::gotoChild(string name) { if(!isNull()) { parent = cursor; cursor = cursor->FirstChildElement(name.c_str()); } return this; } RRNode *RRNode::gotoParent() { cursor = parent; if(!isNull()) { parent = cursor->Parent()->ToElement(); } return this; } RRNode *RRNode::gotoNext() { if(!isNull()) cursor = cursor->NextSiblingElement(cursor->Value()); return this; } RRNode *RRNode::appendElement(string name) { if(!isNull()) { TiXmlElement *new_elem = new TiXmlElement(name.c_str()); cursor->LinkEndChild(new_elem); parent = cursor; cursor = new_elem; } return this; } bool RRNode::isNull() { bool result = cursor; return !result; } int RRNode::attrInt(string name) { int tmp = 0; cursor->QueryIntAttribute(name.c_str(), &tmp); return tmp; } float RRNode::attrFloat(string name) { float tmp = 0.0; cursor->QueryFloatAttribute(name.c_str(), &tmp); return tmp; } string RRNode::attrStr(string name) { return cursor->Attribute(name.c_str()); } void RRNode::setAttr(string name, string value) { cursor->SetAttribute(name.c_str(), value.c_str()); } Event *RRNode::fetchEvent() { if (isNull()) return 0; Event *event = new Event(attrStr("id")); for (gotoChild("item_req"); !isNull(); gotoNext()) event->addItemReq(attrStr("id"), attrStr("value")); gotoParent(); for (gotoChild("var_req"); !isNull(); gotoNext()) event->addVarReq(attrStr("id"), attrInt("value")); gotoParent(); for (gotoChild("action"); !isNull(); gotoNext()) { Action *act = event->addAction(attrStr("id")); for (gotoChild("param"); !isNull(); gotoNext()) act->pushParam(attrStr("value")); gotoParent(); } gotoParent(); return event; } Room *RRNode::fetchRoom() { if (isNull()) return 0; Room *room = new Room(attrStr("id")); room->bg(attrStr("bg")); for (gotoChild("area"); !isNull(); gotoNext()) { Area *area = room->addArea(attrStr("id")); area->setSize(attrFloat("x"), attrFloat("y"), attrFloat("width"), attrFloat("height")); area->setEvent(attrStr("event")); } gotoParent(); return room; } Item *RRNode::fetchItem() { if (isNull()) return 0; Item *item = new Item(attrStr("id")); item->setSize(attrFloat("x"), attrFloat("y"), attrFloat("width"), attrFloat("height")); item->setEvent(attrStr("event")); item->setImage(attrStr("image")); item->move(attrStr("room")); return item; } Dialog *RRNode::fetchDialog() { if (isNull()) return 0; Dialog *d = new Dialog(attrStr("id"), attrStr("start")); for (gotoChild("step"); !isNull(); gotoNext()) { DialogStep *step = d->addStep(attrStr("id"), attrStr("text")); step->event = fetchEvent(); for (gotoChild("link"); !isNull(); gotoNext()) d->addLink(step->id, attrStr("id"), attrStr("text")); gotoParent(); } gotoParent(); return d; } TiXmlElement *RRNode::findElement(TiXmlElement *elem, string name) { if (elem == 0) return 0; if (string(elem->Value()) == name) return elem; TiXmlElement *result = findElement(elem->NextSiblingElement(), name); if (result != 0) return result; result = findElement(elem->FirstChildElement(), name); if (result != 0) return result; return 0; } string floatToStr(const float f) { std::ostringstream os; os << f; return os.str(); } string upgradeFrom1To2(string content) { TiXmlDocument doc; doc.Parse(content.c_str()); RRNode node(doc.RootElement()); node.gotoElement("world"); int w = node.attrInt("width"); int h = node.attrInt("height"); node.setAttr("version", "2"); for (node.gotoElement("items")->gotoChild("item"); !node.isNull(); node.gotoNext()) { node.setAttr("x", floatToStr(node.attrFloat("x") / w)); node.setAttr("y", floatToStr(node.attrFloat("y") / h)); node.setAttr("width", floatToStr(node.attrFloat("width") / w)); node.setAttr("height", floatToStr(node.attrFloat("height") / h)); } for (node.gotoElement("rooms")->gotoChild("room"); !node.isNull(); node.gotoNext()) { for (node.gotoChild("area"); !node.isNull(); node.gotoNext()) { node.setAttr("x", floatToStr(node.attrFloat("x") / w)); node.setAttr("y", floatToStr(node.attrFloat("y") / h)); node.setAttr("width", floatToStr(node.attrFloat("width") / w)); node.setAttr("height", floatToStr(node.attrFloat("height") / h)); } node.gotoParent(); } TiXmlPrinter printer; doc.Accept(&printer); return printer.CStr(); } const int RoomsReader::VERSION = 2; RoomsReader::RoomsReader() { crawler = 0; doc = 0; parse_map["world"] = &RoomsReader::parseWorld; parse_map["room"] = &RoomsReader::parseRoom; parse_map["area"] = &RoomsReader::parseArea; parse_map["action"] = &RoomsReader::parseAction; parse_map["event"] = &RoomsReader::parseEvent; parse_map["dialog"] = &RoomsReader::parseDialog; parse_map["step"] = &RoomsReader::parseDialogStep; parse_map["var"] = &RoomsReader::parseVar; parse_map["item"] = &RoomsReader::parseItem; parse_map["param"] = &RoomsReader::parseParam; parse_map["item_req"] = &RoomsReader::parseItemReq; parse_map["var_req"] = &RoomsReader::parseVarReq; parse_map["img"] = &RoomsReader::parseImages; } RoomsReader::~RoomsReader() { if(crawler) delete crawler; if (doc) delete doc; } RoomsReader::UpgradeFunc RoomsReader::upgrade_funcs[] = {upgradeFrom1To2}; bool RoomsReader::loadFromFile(const string filename) { std::ifstream xml(filename.c_str(), std::ios::binary); if (!xml.good()) return false; xml.seekg (0, std::ios::end); long length = xml.tellg(); if (length == 0) return false; char *buffer = new char [length]; xml.seekg (0, std::ios::beg); xml.read(buffer, length); bool res = loadFromStr(buffer); xml.close(); delete [] buffer; return res; } bool RoomsReader::loadFromStr(const string content) { doc = new TiXmlDocument; doc->Parse(content.c_str()); crawler = new RRNode(doc->RootElement()); file_content = content; return true; } void RoomsReader::loadEmptyDoc() { doc = new TiXmlDocument; TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "", ""); TiXmlElement *element = new TiXmlElement("world"); doc->LinkEndChild(decl); doc->LinkEndChild(element); crawler = new RRNode(doc->RootElement()); } void RoomsReader::saveDoc(string filename) { if (!doc->SaveFile(filename.c_str())) logger.write("Cannot save to " + filename, Log::ERROR); } string RoomsReader::upgrade(string content) { for (int i = file_version; i < VERSION; ++i) { logger.write("Updating from v." + floatToStr(i) + " to v." + floatToStr(i + 1), Log::NOTE); content = upgrade_funcs[i - 1](content); } logger.write("Upgrade successful!", Log::WARNING); file_content = content; return content; } bool RoomsReader::parse() { if (!parseElement(doc->RootElement())) { delete doc; doc = 0; if (file_version < VERSION) { logger.write("Old version detected: " + floatToStr(file_version) + ". Upgrading...", Log::WARNING); string new_content = upgrade(file_content); loadFromStr(new_content); return parse(); } return false; } return true; } RRNode *RoomsReader::getCrawler() { return crawler; } bool RoomsReader::checkUniqueId(std::set<string> &ids, const string id) { if (ids.count(id) != 0) return false; ids.insert(id); return true; } bool RoomsReader::checkParent(TiXmlElement *elem, string name) { return (elem->Parent() != 0 && string(elem->Parent()->Value()) == name); } bool RoomsReader::parseElement(TiXmlElement *elem) { if (elem == 0) return true; bool value = true; if (parse_map.find(elem->Value()) != parse_map.end()) { ParseMethod method = parse_map.find(elem->Value())->second; value = (this->*method)(elem); } return (value && parseElement(elem->FirstChildElement()) && parseElement(elem->NextSiblingElement())); } bool RoomsReader::parseArea(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "x", ATTR_FLOAT) && parseAttr(elem, "y", ATTR_FLOAT) && parseAttr(elem, "width", ATTR_FLOAT) && parseAttr(elem, "height", ATTR_FLOAT))) return false; if (!(checkUniqueId(unique_ids_areas, elem->Attribute("id")) && checkParent(elem, "room"))) return false; return true; } bool RoomsReader::parseItem(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "room", ATTR_STR) && parseAttr(elem, "image", ATTR_STR) && parseAttr(elem, "x", ATTR_FLOAT) && parseAttr(elem, "y", ATTR_FLOAT) && parseAttr(elem, "width", ATTR_FLOAT) && parseAttr(elem, "height", ATTR_FLOAT))) return false; if (!(checkUniqueId(unique_ids_items, elem->Attribute("id")) && checkParent(elem, "items") && !checkUniqueId(unique_ids_images, elem->Attribute("image")))) return false; return true; } bool RoomsReader::parseRoom(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "bg", ATTR_STR))) return false; if (!(checkUniqueId(unique_ids_rooms, elem->Attribute("id")) && checkParent(elem, "rooms"))) return false; return true; } bool RoomsReader::parseAction(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && (checkParent(elem, "event") || checkParent(elem, "step")))) return false; return true; } bool RoomsReader::parseWorld(TiXmlElement *elem) { if (!(parseAttr(elem, "version", ATTR_INT) && parseAttr(elem, "name", ATTR_STR) && parseAttr(elem, "start", ATTR_STR) && parseAttr(elem, "width", ATTR_INT) && parseAttr(elem, "height", ATTR_INT))) return false; elem->QueryIntAttribute("version", &file_version); if (file_version != VERSION) return false; return true; } bool RoomsReader::parseEvent(TiXmlElement *elem) { if (!parseAttr(elem, "id", ATTR_STR)) return false; if (!(checkUniqueId(unique_ids_events, elem->Attribute("id")) && checkParent(elem, "events"))) return false; return true; } bool RoomsReader::parseVar(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "value", ATTR_STR) && checkParent(elem, "vars"))) return false; return true; } bool RoomsReader::parseImages(TiXmlElement *elem) { if (!(parseAttr(elem, "file", ATTR_STR) && checkParent(elem, "images"))) return false; if (!checkUniqueId(unique_ids_images, elem->Attribute("file"))) return false; return true; } bool RoomsReader::parseItemReq(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "value", ATTR_STR))) return false; if (!(!checkUniqueId(unique_ids_items, elem->Attribute("id")) && (checkParent(elem, "event") || checkParent(elem, "step")))) return false; return true; } bool RoomsReader::parseVarReq(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "value", ATTR_INT))) return false; if (!(checkParent(elem, "event") || checkParent(elem, "step"))) return false; return true; } bool RoomsReader::parseParam(TiXmlElement *elem) { if (!parseAttr(elem, "value", ATTR_STR)) return false; return true; } bool RoomsReader::parseDialog(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "start", ATTR_STR))) return false; if (!(checkUniqueId(unique_ids_dialogs, elem->Attribute("id")) && checkParent(elem, "dialogs"))) return false; return true; } bool RoomsReader::parseDialogStep(TiXmlElement *elem) { if (!(parseAttr(elem, "id", ATTR_STR) && parseAttr(elem, "text", ATTR_STR) && checkParent(elem, "dialog"))) return false; return true; } bool RoomsReader::parseAttr(TiXmlElement *elem, string name, AttributeType type) { switch (type) { case ATTR_FLOAT: { float tmp; return (elem->QueryFloatAttribute(name.c_str(), &tmp) == TIXML_SUCCESS); break; } case ATTR_INT: { int tmp; return (elem->QueryIntAttribute(name.c_str(), &tmp) == TIXML_SUCCESS); break; } case ATTR_STR: { return (elem->Attribute(name.c_str())); break; } default: { return false; break; } } } <|endoftext|>
<commit_before>/*! \file stack_trace_manager.cpp \brief Stack trace manager implementation \author Ivan Shynkarenka \date 10.02.2016 \copyright MIT License */ #include "system/stack_trace_manager.h" #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #if defined(DBGHELP_SUPPORT) #include <dbghelp.h> #endif #endif namespace CppCommon { //! @cond INTERNALS class StackTraceManager::Impl { public: Impl() : _initialized(false) {} void Initialize() { // Check for double initialization if (_initialized) return; #if defined(_WIN32) || defined(_WIN64) #if defined(DBGHELP_SUPPORT) // Provide required symbol options SymSetOptions(SYMOPT_PUBLICS_ONLY); // Get the current process handle HANDLE hProcess = GetCurrentProcess(); // Initializes symbol handler for the current process if (!InitializeSymbols(hProcess)) throwex SystemException("Cannot initialize symbol handler for the current process!"); #endif #endif _initialized = true; } void Cleanup() { // Check for double cleanup if (!_initialized) return; #if defined(_WIN32) || defined(_WIN64) #if defined(DBGHELP_SUPPORT) // Get the current process handle HANDLE hProcess = GetCurrentProcess(); // Cleanup symbol handler for the current process if (!SymCleanup(hProcess)) throwex SystemException("Cannot cleanup symbol handler for the current process!"); #endif #endif _initialized = false; } private: bool _initialized; #if defined(_WIN32) || defined(_WIN64) #if defined(DBGHELP_SUPPORT) bool InitializeSymbols(HANDLE hProcess) { const int attempts = 10; const int sleep = 100; for (int attempt = 0; attempt < attempts; ++attempt) { if (SymInitialize(hProcess, nullptr, TRUE)) return true; Sleep(sleep); } return false; } #endif #endif }; //! @endcond StackTraceManager::StackTraceManager() : _pimpl(std::make_unique<Impl>()) { } StackTraceManager::~StackTraceManager() { } void StackTraceManager::Initialize() { GetInstance()._pimpl->Initialize(); } void StackTraceManager::Cleanup() { GetInstance()._pimpl->Cleanup(); } } // namespace CppCommon <commit_msg>update<commit_after>/*! \file stack_trace_manager.cpp \brief Stack trace manager implementation \author Ivan Shynkarenka \date 10.02.2016 \copyright MIT License */ #include "system/stack_trace_manager.h" #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #if defined(DBGHELP_SUPPORT) #include <dbghelp.h> #endif #endif namespace CppCommon { //! @cond INTERNALS class StackTraceManager::Impl { public: Impl() : _initialized(false) {} void Initialize() { // Check for double initialization if (_initialized) return; #if defined(_WIN32) || defined(_WIN64) #if defined(DBGHELP_SUPPORT) // Provide required symbol options SymSetOptions(SYMOPT_PUBLICS_ONLY); // Get the current process handle HANDLE hProcess = GetCurrentProcess(); // Initializes symbol handler for the current process if (!InitializeSymbols(hProcess)) throwex SystemException("Cannot initialize symbol handler for the current process!"); #endif #endif _initialized = true; } void Cleanup() { // Check for double cleanup if (!_initialized) return; #if defined(_WIN32) || defined(_WIN64) #if defined(DBGHELP_SUPPORT) // Get the current process handle HANDLE hProcess = GetCurrentProcess(); // Cleanup symbol handler for the current process if (!SymCleanup(hProcess)) throwex SystemException("Cannot cleanup symbol handler for the current process!"); #endif #endif _initialized = false; } private: bool _initialized; #if defined(_WIN32) || defined(_WIN64) #if defined(DBGHELP_SUPPORT) bool InitializeSymbols(HANDLE hProcess) { const int attempts = 10; const int sleep = 100; for (int attempt = 0; attempt < attempts; ++attempt) { printf("Fixed!\n"); if (SymInitialize(hProcess, nullptr, TRUE)) return true; Sleep(sleep); } return false; } #endif #endif }; //! @endcond StackTraceManager::StackTraceManager() : _pimpl(std::make_unique<Impl>()) { } StackTraceManager::~StackTraceManager() { } void StackTraceManager::Initialize() { GetInstance()._pimpl->Initialize(); } void StackTraceManager::Cleanup() { GetInstance()._pimpl->Cleanup(); } } // namespace CppCommon <|endoftext|>
<commit_before>/** * This file is part of the CernVM file system */ #include "sync_item.h" #if !defined(__APPLE__) #include <sys/sysmacros.h> #endif // __APPLE__ #include <cerrno> #include <vector> #include "duplex_libarchive.h" #include "ingestion/ingestion_source.h" #include "sync_mediator.h" #include "sync_union.h" #include "util/exception.h" using namespace std; // NOLINT namespace publish { SyncItem::SyncItem() : rdonly_type_(static_cast<SyncItemType>(0)), graft_size_(-1), scratch_type_(static_cast<SyncItemType>(0)), union_engine_(NULL), whiteout_(false), opaque_(false), masked_hardlink_(false), has_catalog_marker_(false), valid_graft_(false), graft_marker_present_(false), external_data_(false), graft_chunklist_(NULL), compression_algorithm_(zlib::kZlibDefault) {} SyncItem::SyncItem(const std::string &relative_parent_path, const std::string &filename, const SyncUnion *union_engine, const SyncItemType entry_type) : rdonly_type_(kItemUnknown), graft_size_(-1), scratch_type_(entry_type), filename_(filename), union_engine_(union_engine), whiteout_(false), opaque_(false), masked_hardlink_(false), has_catalog_marker_(false), valid_graft_(false), graft_marker_present_(false), external_data_(false), relative_parent_path_(relative_parent_path), graft_chunklist_(NULL), compression_algorithm_(zlib::kZlibDefault) { content_hash_.algorithm = shash::kAny; } SyncItem::~SyncItem() { delete graft_chunklist_; } SyncItemType SyncItem::GetGenericFiletype(const SyncItem::EntryStat &stat) const { const SyncItemType type = stat.GetSyncItemType(); if (type == kItemUnknown) { PANIC(kLogStderr, "[WARNING] '%s' has an unsupported file type (st_mode: %d errno: %d)", GetRelativePath().c_str(), stat.stat.st_mode, stat.error_code); } return type; } SyncItemType SyncItem::GetRdOnlyFiletype() const { StatRdOnly(); // file could not exist in read-only branch, or a regular file could have // been replaced by a directory in the read/write branch, like: // rdonly: // /foo/bar/regular_file <-- ENOTDIR when asking for (.../is_dir_now) // r/w: // /foo/bar/regular_file/ // /foo/bar/regular_file/is_dir_now if (rdonly_stat_.error_code == ENOENT || rdonly_stat_.error_code == ENOTDIR) return kItemNew; return GetGenericFiletype(rdonly_stat_); } SyncItemType SyncItemNative::GetScratchFiletype() const { StatScratch(); if (scratch_stat_.error_code != 0) { PANIC(kLogStderr, "[WARNING] Failed to stat() '%s' in scratch. (errno: %s)", GetRelativePath().c_str(), scratch_stat_.error_code); } return GetGenericFiletype(scratch_stat_); } SyncItemType SyncItem::GetUnionFiletype() const { StatUnion(); if (union_stat_.error_code == ENOENT || union_stat_.error_code == ENOTDIR) return kItemUnknown; return GetGenericFiletype(union_stat_); } bool SyncItemNative::IsType(const SyncItemType expected_type) const { if (filename().substr(0, 12) == ".cvmfsgraft-") { scratch_type_ = kItemMarker; } else if (scratch_type_ == kItemUnknown) { scratch_type_ = GetScratchFiletype(); } return scratch_type_ == expected_type; } void SyncItem::MarkAsWhiteout(const std::string &actual_filename) { StatScratch(true); // Mark the file as whiteout entry and strip the whiteout prefix whiteout_ = true; filename_ = actual_filename; // Find the entry in the repository StatRdOnly(true); // <== refreshing the stat (filename might have changed) const SyncItemType deleted_type = (rdonly_stat_.error_code == 0) ? GetRdOnlyFiletype() : kItemUnknown; rdonly_type_ = deleted_type; scratch_type_ = deleted_type; if (deleted_type == kItemUnknown) { // Marking a SyncItem as 'whiteout' but no file to be removed found: This // should not happen (actually AUFS prevents users from creating whiteouts) // but can be provoked through an AUFS 'bug' (see test 593 or CVM-880). // --> Warn the user, continue with kItemUnknown and cross your fingers! PrintWarning("'" + GetRelativePath() + "' should be deleted, but was not " "found in repository."); } } void SyncItem::MarkAsOpaqueDirectory() { assert(IsDirectory()); opaque_ = true; } unsigned int SyncItem::GetRdOnlyLinkcount() const { StatRdOnly(); return rdonly_stat_.stat.st_nlink; } uint64_t SyncItem::GetRdOnlyInode() const { StatRdOnly(); return rdonly_stat_.stat.st_ino; } unsigned int SyncItem::GetUnionLinkcount() const { StatUnion(); return union_stat_.stat.st_nlink; } uint64_t SyncItem::GetUnionInode() const { StatUnion(); return union_stat_.stat.st_ino; } uint64_t SyncItem::GetScratchSize() const { StatScratch(); return scratch_stat_.stat.st_size; } uint64_t SyncItem::GetRdOnlySize() const { StatRdOnly(); return rdonly_stat_.stat.st_size; } IngestionSource *SyncItemNative::CreateIngestionSource() const { return new FileIngestionSource(GetUnionPath()); } void SyncItem::StatGeneric(const string &path, EntryStat *info, const bool refresh) { if (info->obtained && !refresh) return; int retval = platform_lstat(path.c_str(), &info->stat); info->error_code = (retval != 0) ? errno : 0; info->obtained = true; } catalog::DirectoryEntryBase SyncItemNative::CreateBasicCatalogDirent() const { catalog::DirectoryEntryBase dirent; // inode and parent inode is determined at runtime of client dirent.inode_ = catalog::DirectoryEntry::kInvalidInode; // this might mask the actual link count in case hardlinks are not supported // (i.e. on setups using OverlayFS) dirent.linkcount_ = HasHardlinks() ? this->GetUnionStat().st_nlink : 1; dirent.mode_ = this->GetUnionStat().st_mode; dirent.uid_ = this->GetUnionStat().st_uid; dirent.gid_ = this->GetUnionStat().st_gid; dirent.size_ = graft_size_ > -1 ? graft_size_ : this->GetUnionStat().st_size; dirent.mtime_ = this->GetUnionStat().st_mtime; dirent.checksum_ = this->GetContentHash(); dirent.is_external_file_ = this->IsExternalData(); dirent.compression_algorithm_ = this->GetCompressionAlgorithm(); dirent.name_.Assign(filename().data(), filename().length()); if (this->IsSymlink()) { char slnk[PATH_MAX+1]; const ssize_t length = readlink((this->GetUnionPath()).c_str(), slnk, PATH_MAX); assert(length >= 0); dirent.symlink_.Assign(slnk, length); } if (this->IsCharacterDevice() || this->IsBlockDevice()) { dirent.size_ = makedev(GetRdevMajor(), GetRdevMinor()); } return dirent; } std::string SyncItem::GetRdOnlyPath() const { const string relative_path = GetRelativePath().empty() ? "" : "/" + GetRelativePath(); return union_engine_->rdonly_path() + relative_path; } std::string SyncItem::GetUnionPath() const { const string relative_path = GetRelativePath().empty() ? "" : "/" + GetRelativePath(); return union_engine_->union_path() + relative_path; } std::string SyncItem::GetScratchPath() const { const string relative_path = GetRelativePath().empty() ? "" : "/" + GetRelativePath(); return union_engine_->scratch_path() + relative_path; // return union_engine_->scratch_path() + filename(); } void SyncItem::CheckMarkerFiles() { if (IsRegularFile()) { CheckGraft(); } else if (IsDirectory()) { CheckCatalogMarker(); } } void SyncItem::CheckCatalogMarker() { has_catalog_marker_ = FileExists(GetUnionPath() + "/.cvmfscatalog"); } std::string SyncItem::GetGraftMarkerPath() const { return union_engine_->scratch_path() + "/" + ((relative_parent_path_.empty()) ? ".cvmfsgraft-" + filename_ : relative_parent_path_ + (filename_.empty() ? "" : ("/.cvmfsgraft-" + filename_))); } void SyncItem::CheckGraft() { valid_graft_ = false; bool found_checksum = false; std::string checksum_type; std::string checksum_value; std::string graftfile = GetGraftMarkerPath(); LogCvmfs(kLogFsTraversal, kLogDebug, "Checking potential graft path %s.", graftfile.c_str()); FILE *fp = fopen(graftfile.c_str(), "r"); if (fp == NULL) { // This sync item can be a file from a removed directory tree on overlayfs. // In this case, the entire tree is missing on the scratch directory and // the errno is ENOTDIR. if ((errno != ENOENT) && (errno != ENOTDIR)) { LogCvmfs(kLogFsTraversal, kLogWarning, "Unable to open graft file " "(%s): %s (errno=%d)", graftfile.c_str(), strerror(errno), errno); } return; } graft_marker_present_ = true; valid_graft_ = true; std::string line; std::vector<std::string> contents; std::vector<off_t> chunk_offsets; std::vector<shash::Any> chunk_checksums; while (GetLineFile(fp, &line)) { std::string trimmed_line = Trim(line); if (!trimmed_line.size()) {continue;} if (trimmed_line[0] == '#') {continue;} std::vector<std::string> info = SplitString(trimmed_line, '=', 2); if (info.size() != 2) { LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid line in graft file: %s", trimmed_line.c_str()); } info[0] = Trim(info[0]); info[1] = Trim(info[1]); if (info[0] == "size") { uint64_t tmp_size; if (!String2Uint64Parse(info[1], &tmp_size)) { LogCvmfs(kLogFsTraversal, kLogWarning, "Failed to parse value of %s " "to integer: %s (errno=%d)", trimmed_line.c_str(), strerror(errno), errno); continue; } graft_size_ = tmp_size; } else if (info[0] == "checksum") { std::string hash_str = info[1]; shash::HexPtr hashP(hash_str); if (hashP.IsValid()) { content_hash_ = shash::MkFromHexPtr(hashP); found_checksum = true; } else { LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid checksum value: %s.", info[1].c_str()); } continue; } else if (info[0] == "chunk_offsets") { std::vector<std::string> offsets = SplitString(info[1], ','); for (std::vector<std::string>::const_iterator it = offsets.begin(); it != offsets.end(); it++) { uint64_t val; if (!String2Uint64Parse(*it, &val)) { valid_graft_ = false; LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid chunk offset: %s.", it->c_str()); break; } chunk_offsets.push_back(val); } } else if (info[0] == "chunk_checksums") { std::vector<std::string> csums = SplitString(info[1], ','); for (std::vector<std::string>::const_iterator it = csums.begin(); it != csums.end(); it++) { shash::HexPtr hashP(*it); if (hashP.IsValid()) { chunk_checksums.push_back(shash::MkFromHexPtr(hashP)); } else { LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid chunk checksum " "value: %s.", it->c_str()); valid_graft_ = false; break; } } } } if (!feof(fp)) { LogCvmfs(kLogFsTraversal, kLogWarning, "Unable to read from catalog " "marker (%s): %s (errno=%d)", graftfile.c_str(), strerror(errno), errno); } fclose(fp); valid_graft_ = valid_graft_ && (graft_size_ > -1) && found_checksum && (chunk_checksums.size() == chunk_offsets.size()); if (!valid_graft_ || chunk_offsets.empty()) return; // Parse chunks graft_chunklist_ = new FileChunkList(chunk_offsets.size()); off_t last_offset = chunk_offsets[0]; if (last_offset != 0) { LogCvmfs(kLogFsTraversal, kLogWarning, "First chunk offset must be 0" " (in graft marker %s).", graftfile.c_str()); valid_graft_ = false; } for (unsigned idx = 1; idx < chunk_offsets.size(); idx++) { off_t cur_offset = chunk_offsets[idx]; if (last_offset >= cur_offset) { LogCvmfs(kLogFsTraversal, kLogWarning, "Chunk offsets must be sorted " "in strictly increasing order (in graft marker %s).", graftfile.c_str()); valid_graft_ = false; break; } size_t cur_size = cur_offset - last_offset; graft_chunklist_->PushBack(FileChunk(chunk_checksums[idx - 1], last_offset, cur_size)); last_offset = cur_offset; } if (graft_size_ <= last_offset) { LogCvmfs(kLogFsTraversal, kLogWarning, "Last offset must be strictly " "less than total file size (in graft marker %s).", graftfile.c_str()); valid_graft_ = false; } graft_chunklist_->PushBack(FileChunk(chunk_checksums.back(), last_offset, graft_size_ - last_offset)); } } // namespace publish <commit_msg>Check if the .cvmfscatalog file is regular<commit_after>/** * This file is part of the CernVM file system */ #include "sync_item.h" #if !defined(__APPLE__) #include <sys/sysmacros.h> #endif // __APPLE__ #include <cerrno> #include <vector> #include "duplex_libarchive.h" #include "ingestion/ingestion_source.h" #include "sync_mediator.h" #include "sync_union.h" #include "util/exception.h" using namespace std; // NOLINT namespace publish { SyncItem::SyncItem() : rdonly_type_(static_cast<SyncItemType>(0)), graft_size_(-1), scratch_type_(static_cast<SyncItemType>(0)), union_engine_(NULL), whiteout_(false), opaque_(false), masked_hardlink_(false), has_catalog_marker_(false), valid_graft_(false), graft_marker_present_(false), external_data_(false), graft_chunklist_(NULL), compression_algorithm_(zlib::kZlibDefault) {} SyncItem::SyncItem(const std::string &relative_parent_path, const std::string &filename, const SyncUnion *union_engine, const SyncItemType entry_type) : rdonly_type_(kItemUnknown), graft_size_(-1), scratch_type_(entry_type), filename_(filename), union_engine_(union_engine), whiteout_(false), opaque_(false), masked_hardlink_(false), has_catalog_marker_(false), valid_graft_(false), graft_marker_present_(false), external_data_(false), relative_parent_path_(relative_parent_path), graft_chunklist_(NULL), compression_algorithm_(zlib::kZlibDefault) { content_hash_.algorithm = shash::kAny; } SyncItem::~SyncItem() { delete graft_chunklist_; } SyncItemType SyncItem::GetGenericFiletype(const SyncItem::EntryStat &stat) const { const SyncItemType type = stat.GetSyncItemType(); if (type == kItemUnknown) { PANIC(kLogStderr, "[WARNING] '%s' has an unsupported file type (st_mode: %d errno: %d)", GetRelativePath().c_str(), stat.stat.st_mode, stat.error_code); } return type; } SyncItemType SyncItem::GetRdOnlyFiletype() const { StatRdOnly(); // file could not exist in read-only branch, or a regular file could have // been replaced by a directory in the read/write branch, like: // rdonly: // /foo/bar/regular_file <-- ENOTDIR when asking for (.../is_dir_now) // r/w: // /foo/bar/regular_file/ // /foo/bar/regular_file/is_dir_now if (rdonly_stat_.error_code == ENOENT || rdonly_stat_.error_code == ENOTDIR) return kItemNew; return GetGenericFiletype(rdonly_stat_); } SyncItemType SyncItemNative::GetScratchFiletype() const { StatScratch(); if (scratch_stat_.error_code != 0) { PANIC(kLogStderr, "[WARNING] Failed to stat() '%s' in scratch. (errno: %s)", GetRelativePath().c_str(), scratch_stat_.error_code); } return GetGenericFiletype(scratch_stat_); } SyncItemType SyncItem::GetUnionFiletype() const { StatUnion(); if (union_stat_.error_code == ENOENT || union_stat_.error_code == ENOTDIR) return kItemUnknown; return GetGenericFiletype(union_stat_); } bool SyncItemNative::IsType(const SyncItemType expected_type) const { if (filename().substr(0, 12) == ".cvmfsgraft-") { scratch_type_ = kItemMarker; } else if (scratch_type_ == kItemUnknown) { scratch_type_ = GetScratchFiletype(); } return scratch_type_ == expected_type; } void SyncItem::MarkAsWhiteout(const std::string &actual_filename) { StatScratch(true); // Mark the file as whiteout entry and strip the whiteout prefix whiteout_ = true; filename_ = actual_filename; // Find the entry in the repository StatRdOnly(true); // <== refreshing the stat (filename might have changed) const SyncItemType deleted_type = (rdonly_stat_.error_code == 0) ? GetRdOnlyFiletype() : kItemUnknown; rdonly_type_ = deleted_type; scratch_type_ = deleted_type; if (deleted_type == kItemUnknown) { // Marking a SyncItem as 'whiteout' but no file to be removed found: This // should not happen (actually AUFS prevents users from creating whiteouts) // but can be provoked through an AUFS 'bug' (see test 593 or CVM-880). // --> Warn the user, continue with kItemUnknown and cross your fingers! PrintWarning("'" + GetRelativePath() + "' should be deleted, but was not " "found in repository."); } } void SyncItem::MarkAsOpaqueDirectory() { assert(IsDirectory()); opaque_ = true; } unsigned int SyncItem::GetRdOnlyLinkcount() const { StatRdOnly(); return rdonly_stat_.stat.st_nlink; } uint64_t SyncItem::GetRdOnlyInode() const { StatRdOnly(); return rdonly_stat_.stat.st_ino; } unsigned int SyncItem::GetUnionLinkcount() const { StatUnion(); return union_stat_.stat.st_nlink; } uint64_t SyncItem::GetUnionInode() const { StatUnion(); return union_stat_.stat.st_ino; } uint64_t SyncItem::GetScratchSize() const { StatScratch(); return scratch_stat_.stat.st_size; } uint64_t SyncItem::GetRdOnlySize() const { StatRdOnly(); return rdonly_stat_.stat.st_size; } IngestionSource *SyncItemNative::CreateIngestionSource() const { return new FileIngestionSource(GetUnionPath()); } void SyncItem::StatGeneric(const string &path, EntryStat *info, const bool refresh) { if (info->obtained && !refresh) return; int retval = platform_lstat(path.c_str(), &info->stat); info->error_code = (retval != 0) ? errno : 0; info->obtained = true; } catalog::DirectoryEntryBase SyncItemNative::CreateBasicCatalogDirent() const { catalog::DirectoryEntryBase dirent; // inode and parent inode is determined at runtime of client dirent.inode_ = catalog::DirectoryEntry::kInvalidInode; // this might mask the actual link count in case hardlinks are not supported // (i.e. on setups using OverlayFS) dirent.linkcount_ = HasHardlinks() ? this->GetUnionStat().st_nlink : 1; dirent.mode_ = this->GetUnionStat().st_mode; dirent.uid_ = this->GetUnionStat().st_uid; dirent.gid_ = this->GetUnionStat().st_gid; dirent.size_ = graft_size_ > -1 ? graft_size_ : this->GetUnionStat().st_size; dirent.mtime_ = this->GetUnionStat().st_mtime; dirent.checksum_ = this->GetContentHash(); dirent.is_external_file_ = this->IsExternalData(); dirent.compression_algorithm_ = this->GetCompressionAlgorithm(); dirent.name_.Assign(filename().data(), filename().length()); if (this->IsSymlink()) { char slnk[PATH_MAX+1]; const ssize_t length = readlink((this->GetUnionPath()).c_str(), slnk, PATH_MAX); assert(length >= 0); dirent.symlink_.Assign(slnk, length); } if (this->IsCharacterDevice() || this->IsBlockDevice()) { dirent.size_ = makedev(GetRdevMajor(), GetRdevMinor()); } return dirent; } std::string SyncItem::GetRdOnlyPath() const { const string relative_path = GetRelativePath().empty() ? "" : "/" + GetRelativePath(); return union_engine_->rdonly_path() + relative_path; } std::string SyncItem::GetUnionPath() const { const string relative_path = GetRelativePath().empty() ? "" : "/" + GetRelativePath(); return union_engine_->union_path() + relative_path; } std::string SyncItem::GetScratchPath() const { const string relative_path = GetRelativePath().empty() ? "" : "/" + GetRelativePath(); return union_engine_->scratch_path() + relative_path; // return union_engine_->scratch_path() + filename(); } void SyncItem::CheckMarkerFiles() { if (IsRegularFile()) { CheckGraft(); } else if (IsDirectory()) { CheckCatalogMarker(); } } void SyncItem::CheckCatalogMarker() { std::string path(GetUnionPath() + "/.cvmfscatalog"); EntryStat stat; StatGeneric(path, &stat, false); if (stat.error_code) { has_catalog_marker_ = false; return; } if (stat.GetSyncItemType() == kItemFile) { has_catalog_marker_ = true; return; } PANIC(kLogStderr, "Error: The .cvmfscatalog file is not a regular one."); } std::string SyncItem::GetGraftMarkerPath() const { return union_engine_->scratch_path() + "/" + ((relative_parent_path_.empty()) ? ".cvmfsgraft-" + filename_ : relative_parent_path_ + (filename_.empty() ? "" : ("/.cvmfsgraft-" + filename_))); } void SyncItem::CheckGraft() { valid_graft_ = false; bool found_checksum = false; std::string checksum_type; std::string checksum_value; std::string graftfile = GetGraftMarkerPath(); LogCvmfs(kLogFsTraversal, kLogDebug, "Checking potential graft path %s.", graftfile.c_str()); FILE *fp = fopen(graftfile.c_str(), "r"); if (fp == NULL) { // This sync item can be a file from a removed directory tree on overlayfs. // In this case, the entire tree is missing on the scratch directory and // the errno is ENOTDIR. if ((errno != ENOENT) && (errno != ENOTDIR)) { LogCvmfs(kLogFsTraversal, kLogWarning, "Unable to open graft file " "(%s): %s (errno=%d)", graftfile.c_str(), strerror(errno), errno); } return; } graft_marker_present_ = true; valid_graft_ = true; std::string line; std::vector<std::string> contents; std::vector<off_t> chunk_offsets; std::vector<shash::Any> chunk_checksums; while (GetLineFile(fp, &line)) { std::string trimmed_line = Trim(line); if (!trimmed_line.size()) {continue;} if (trimmed_line[0] == '#') {continue;} std::vector<std::string> info = SplitString(trimmed_line, '=', 2); if (info.size() != 2) { LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid line in graft file: %s", trimmed_line.c_str()); } info[0] = Trim(info[0]); info[1] = Trim(info[1]); if (info[0] == "size") { uint64_t tmp_size; if (!String2Uint64Parse(info[1], &tmp_size)) { LogCvmfs(kLogFsTraversal, kLogWarning, "Failed to parse value of %s " "to integer: %s (errno=%d)", trimmed_line.c_str(), strerror(errno), errno); continue; } graft_size_ = tmp_size; } else if (info[0] == "checksum") { std::string hash_str = info[1]; shash::HexPtr hashP(hash_str); if (hashP.IsValid()) { content_hash_ = shash::MkFromHexPtr(hashP); found_checksum = true; } else { LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid checksum value: %s.", info[1].c_str()); } continue; } else if (info[0] == "chunk_offsets") { std::vector<std::string> offsets = SplitString(info[1], ','); for (std::vector<std::string>::const_iterator it = offsets.begin(); it != offsets.end(); it++) { uint64_t val; if (!String2Uint64Parse(*it, &val)) { valid_graft_ = false; LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid chunk offset: %s.", it->c_str()); break; } chunk_offsets.push_back(val); } } else if (info[0] == "chunk_checksums") { std::vector<std::string> csums = SplitString(info[1], ','); for (std::vector<std::string>::const_iterator it = csums.begin(); it != csums.end(); it++) { shash::HexPtr hashP(*it); if (hashP.IsValid()) { chunk_checksums.push_back(shash::MkFromHexPtr(hashP)); } else { LogCvmfs(kLogFsTraversal, kLogWarning, "Invalid chunk checksum " "value: %s.", it->c_str()); valid_graft_ = false; break; } } } } if (!feof(fp)) { LogCvmfs(kLogFsTraversal, kLogWarning, "Unable to read from catalog " "marker (%s): %s (errno=%d)", graftfile.c_str(), strerror(errno), errno); } fclose(fp); valid_graft_ = valid_graft_ && (graft_size_ > -1) && found_checksum && (chunk_checksums.size() == chunk_offsets.size()); if (!valid_graft_ || chunk_offsets.empty()) return; // Parse chunks graft_chunklist_ = new FileChunkList(chunk_offsets.size()); off_t last_offset = chunk_offsets[0]; if (last_offset != 0) { LogCvmfs(kLogFsTraversal, kLogWarning, "First chunk offset must be 0" " (in graft marker %s).", graftfile.c_str()); valid_graft_ = false; } for (unsigned idx = 1; idx < chunk_offsets.size(); idx++) { off_t cur_offset = chunk_offsets[idx]; if (last_offset >= cur_offset) { LogCvmfs(kLogFsTraversal, kLogWarning, "Chunk offsets must be sorted " "in strictly increasing order (in graft marker %s).", graftfile.c_str()); valid_graft_ = false; break; } size_t cur_size = cur_offset - last_offset; graft_chunklist_->PushBack(FileChunk(chunk_checksums[idx - 1], last_offset, cur_size)); last_offset = cur_offset; } if (graft_size_ <= last_offset) { LogCvmfs(kLogFsTraversal, kLogWarning, "Last offset must be strictly " "less than total file size (in graft marker %s).", graftfile.c_str()); valid_graft_ = false; } graft_chunklist_->PushBack(FileChunk(chunk_checksums.back(), last_offset, graft_size_ - last_offset)); } } // namespace publish <|endoftext|>
<commit_before>#include <iostream> using namespace std; class Box { private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box public : void setLength(double v_length) { length = v_length; } void setBreadth(double v_breadth) { breadth = v_breadth; } void setHeight(double v_height) { height = v_height; } double getVolume() { if ( length == 0 or breadth == 0 or height == 0 ) { return 0; } else { return length * breadth * height; } } }; class ColouredBox: public Box { private: string colour; // The colour of the box public : void setColour(string v_colour) { colour = v_colour; } string getColour() { return colour; } }; int main( ) { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Box Box3; // Declare Box3 of type Box ColouredBox Box4; // Declare a box with colour // box 1 specification Box1.setHeight(5.0); Box1.setLength(6.0); Box1.setBreadth(7.0); // box 2 specification Box2.setHeight(10.0); Box2.setLength(12.0); Box2.setBreadth(13.0); // box 3 specification Box3.setHeight(10.0); Box3.setBreadth(13.0); // box 4 specification Box4.setHeight(6.0); Box4.setLength(3.0); Box4.setBreadth(2.0); Box4.setColour("Red"); // volume of box 1 cout << "Volume of Box1 : " << Box1.getVolume() << endl; // volume of box 2 cout << "Volume of Box2 : " << Box2.getVolume() << endl; // volume of box 3 cout << "Volume of Box3 : " << Box3.getVolume() << endl; // Box 4 cout << "Box 4 is " << Box4.getColour() << " and has a volume of " << Box4.getVolume() <<endl; return 0; } <commit_msg>Adding additional constructor<commit_after>#include <iostream> // Class Box stored length, breadth and height // Class ColouredBox extends Box to store the colour of the box // ColouredBox has two constructors one taking just the colour // and one taking colour and the dimensions using namespace std; class Box { private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box public : void setLength(double v_length) { length = v_length; } void setBreadth(double v_breadth) { breadth = v_breadth; } void setHeight(double v_height) { height = v_height; } double getVolume() { if ( length == 0 or breadth == 0 or height == 0 ) { return 0; } else { return length * breadth * height; } } }; class ColouredBox: public Box { public : void setColour(string v_colour) { colour = v_colour; } string getColour() { return colour; } ColouredBox( string v_colour ); ColouredBox( string v_colour, double v_length, double v_breadth, double v_height ); private: string colour; // The colour of the box }; ColouredBox::ColouredBox( string v_colour ) { colour = v_colour; } ColouredBox::ColouredBox( string v_colour, double v_length, double v_breadth, double v_height ) { colour = v_colour; Box::setLength(v_length); Box::setBreadth(v_breadth); Box::setHeight(v_height); } int main( ) { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Box Box3; // Declare Box3 of type Box // Declare a box with colour ColouredBox Box4("Red"); // box 5 specification // Using the second constructor ColouredBox Box5("Blue", 5.0, 6.0, 2.0); // box 1 specification Box1.setHeight(5.0); Box1.setLength(6.0); Box1.setBreadth(7.0); // box 2 specification Box2.setHeight(10.0); Box2.setLength(12.0); Box2.setBreadth(13.0); // box 3 specification Box3.setHeight(10.0); Box3.setBreadth(13.0); // Box3.setColour("Blue"); // This is illegal because it's not a coloured box // box 4 specification Box4.setHeight(6.0); Box4.setLength(3.0); Box4.setBreadth(2.0); // volume of box 1 cout << "Volume of Box1 : " << Box1.getVolume() << endl; // volume of box 2 cout << "Volume of Box2 : " << Box2.getVolume() << endl; // volume of box 3 cout << "Volume of Box3 : " << Box3.getVolume() << endl; // Box 4 cout << "Box 4 is " << Box4.getColour() << " and has a volume of " << Box4.getVolume() <<endl; // Box 5 cout << "Box 5 is " << Box5.getColour() << " and has a volume of " << Box5.getVolume() <<endl; return 0; } <|endoftext|>
<commit_before>#include "state.h" #include <stdlib.h> using namespace std; State::State(){ } /* For instantiation based on a parent search node */ State::State(State &parent, Direction dir) { // TODO: create new state node based on parent // 1. assign parent pointer // 2. compute g, h, f cost based on parent node // // 3. based on the parent node, this constructor has // to reason based on the dir parameter whether a box // has been pushed to another location parent_ = &parent; g_ = computeGCost(); h_ = computeHCost(); f_ = g_ + h_; curBoxes_ = parent.getCurBoxes(); } State::State(World &world, Location &curRobot, vector<Location> &curBoxes, State &parent){ world_ = &world; parent_ = &parent; curBoxes_ = curBoxes; } State::State(World &world) { world_ = new World(world.getMap(), world.getInitRobotLocation(), world.getInitBoxes(), world.getTargetBoxes()); curBoxes_ = *world_->getInitBoxes(); g_ = computeGCost(); h_ = computeHCost(); f_ = g_ + h_; } bool State::isGoal(){ return false; } /* * This function returns the possible states from the four different actions (robot up left right down) */ vector<State> State::expandState(){ vector<State> expands; Matrix map = *world_->getMap(); // Flags to ensure we only add one state for each possible action bool left = false; bool right = false; bool up = false; bool down = false; // -- No Change Operations -- if(curRobot_->getX() == 0 // Make sure we cannot go off the map || map[curRobot_->getY()][curRobot_->getX()-1] != 16 ){ // Make sure we cannot enter an occupied space expands.push_back(State(*this, LEFT)); left = true; } if(curRobot_->getX() == world_->getSizeX()-1 || map[curRobot_->getY()][curRobot_->getX()+1] != 16 ){ expands.push_back(State(*this, RIGHT)); right = true; } if(curRobot_->getY() == 0 || map[curRobot_->getY()-1][curRobot_->getX()] != 16 ){ expands.push_back(State(*this, UP)); up = true; } if(curRobot_->getY() == world_->getSizeY()-1 || map[curRobot_->getY()+1][curRobot_->getX()] != 16 ){ expands.push_back(State(*this, DOWN)); down = true; } // -- Push Box-- vector<Location> newBoxes = curBoxes_; for(unsigned int i = 0; i < curBoxes_.size(); i++){ // Check to see if we will push any boxes (i.e. we are adjacent) if(curBoxes_[i].adjacent(*curRobot_, LEFT)){ newBoxes[i] = curBoxes_[i].push(LEFT); Location newRob = curRobot_->push(LEFT); State child(*world_, newRob, newBoxes, *this); left = true; expands.push_back(child); } else if(curBoxes_[i].adjacent(*curRobot_, RIGHT)){ newBoxes[i] = curBoxes_[i].push(RIGHT); Location newRob = curRobot_->push(RIGHT); State child(*world_, newRob, newBoxes, *this); right = true; expands.push_back(child); } else if(curBoxes_[i].adjacent(*curRobot_, UP)){ newBoxes[i] = curBoxes_[i].push(UP); Location newRob = curRobot_->push(UP); State child(*world_, newRob, newBoxes, *this); up = true; expands.push_back(child); } else if(curBoxes_[i].adjacent(*curRobot_, DOWN)){ newBoxes[i] = curBoxes_[i].push(DOWN); Location newRob = curRobot_->push(DOWN); State child(*world_, newRob, newBoxes, *this); down = true; expands.push_back(child); } } } /* Display functions */ void State::printState(const string& name){ cout << "State: " << name << endl; cout << "G Cost: " << g_ << endl; cout << "H Cost: " << h_ << endl; cout << "F Cost: " << f_ << endl; } /* ---------------------- */ /* Cost functions */ /* ---------------------- */ // Returns the Manhattan Distance between robot and loc int State::distanceBetween(const Location& loc1, const Location &loc2) const{ //loc1.print(); //loc2.print(); int dX = abs(loc1.getX() - loc2.getX()); int dY = abs(loc1.getY() - loc2.getY()); cout << "Cost between: " << endl; loc1.print("target"); loc2.print("current"); cout << " is " << dX + dY << endl; return dX + dY; } // Cost from start to current pos int State::computeGCost() { int cost = 0; // Get the starting spots vector<Location> inits = *world_->getInitBoxes(); // For each box, compute the distance from the boxes current location and it's starting point for(unsigned int i = 0; i < world_->getNumberOfBoxes(); i++){ cost += distanceBetween(inits[i], curBoxes_[i]); } return cost; } // Heuristic Cost int State::computeHCost() { int cost = 0; // Get the starting spots vector<Location> targets = *world_->getTargetBoxes(); // For each box, compute the distance from the boxes current location and it's target for(unsigned int i = 0; i < world_->getNumberOfBoxes(); i++){ cost += distanceBetween(targets[i], curBoxes_[i]); } return cost; } // NOT NEEDED int State::computeFCost() {}; //TODO: implement this function void State::setGCost(int g) { g_ = g; }; void State::setHCost(int h) { h_ = h; }; void State::setFCost(int f) { f_ = f; }; /* ---------------------- */ /* Overloaded << operator */ /* ---------------------- */ std::ostream& operator<<(std::ostream& os, const State& state) { state.getWorld()->printWorld(); //state.getWorld()->printConfig(); return os; } /* Overload comparison operator */ bool operator== (State &s1, State &s2) { /* Compare robot loation */ if (s1.getRobot() != s2.getRobot()) return false; /* Compare box locations */ std::vector<Location> s1Boxes = s1.getCurBoxes(); std::vector<Location> s2Boxes = s2.getCurBoxes(); for(int i = 0; i < s1Boxes.size(); i++) { if(s1Boxes.at(i) != s2Boxes.at(i)) return false; } /* Compare f, g, and h costs */ if(s1.getFCost() != s2.getFCost()) return false; if(s1.getGCost() != s2.getGCost()) return false; if(s1.getHCost() != s2.getHCost()) return false; /*Compare parent */ if(s1.getParent() != s2.getParent()) return false; return true; } bool operator!= (State &s1, State &s2) { return !(s1 == s2); } <commit_msg>Expanded states compute cost<commit_after>#include "state.h" #include <stdlib.h> using namespace std; State::State(){ } /* For instantiation based on a parent search node */ State::State(State &parent, Direction dir) { // TODO: create new state node based on parent // 1. assign parent pointer // 2. compute g, h, f cost based on parent node // // 3. based on the parent node, this constructor has // to reason based on the dir parameter whether a box // has been pushed to another location parent_ = &parent; g_ = computeGCost(); h_ = computeHCost(); f_ = g_ + h_; curBoxes_ = parent.getCurBoxes(); } State::State(World &world, Location &curRobot, vector<Location> &curBoxes, State &parent){ world_ = &world; parent_ = &parent; curBoxes_ = curBoxes; g_ = computeGCost(); h_ = computeHCost(); f_ = g_ + h_; } State::State(World &world) { world_ = new World(world.getMap(), world.getInitRobotLocation(), world.getInitBoxes(), world.getTargetBoxes()); curBoxes_ = *world_->getInitBoxes(); g_ = computeGCost(); h_ = computeHCost(); f_ = g_ + h_; } bool State::isGoal(){ return false; } /* * This function returns the possible states from the four different actions (robot up left right down) */ vector<State> State::expandState(){ vector<State> expands; Matrix map = *world_->getMap(); // Flags to ensure we only add one state for each possible action bool left = false; bool right = false; bool up = false; bool down = false; // -- No Change Operations -- if(curRobot_->getX() == 0 // Make sure we cannot go off the map || map[curRobot_->getY()][curRobot_->getX()-1] != 16 ){ // Make sure we cannot enter an occupied space expands.push_back(State(*this, LEFT)); left = true; } if(curRobot_->getX() == world_->getSizeX()-1 || map[curRobot_->getY()][curRobot_->getX()+1] != 16 ){ expands.push_back(State(*this, RIGHT)); right = true; } if(curRobot_->getY() == 0 || map[curRobot_->getY()-1][curRobot_->getX()] != 16 ){ expands.push_back(State(*this, UP)); up = true; } if(curRobot_->getY() == world_->getSizeY()-1 || map[curRobot_->getY()+1][curRobot_->getX()] != 16 ){ expands.push_back(State(*this, DOWN)); down = true; } // -- Push Box-- vector<Location> newBoxes = curBoxes_; for(unsigned int i = 0; i < curBoxes_.size(); i++){ // Check to see if we will push any boxes (i.e. we are adjacent) if(curBoxes_[i].adjacent(*curRobot_, LEFT)){ newBoxes[i] = curBoxes_[i].push(LEFT); Location newRob = curRobot_->push(LEFT); State child(*world_, newRob, newBoxes, *this); left = true; expands.push_back(child); } else if(curBoxes_[i].adjacent(*curRobot_, RIGHT)){ newBoxes[i] = curBoxes_[i].push(RIGHT); Location newRob = curRobot_->push(RIGHT); State child(*world_, newRob, newBoxes, *this); right = true; expands.push_back(child); } else if(curBoxes_[i].adjacent(*curRobot_, UP)){ newBoxes[i] = curBoxes_[i].push(UP); Location newRob = curRobot_->push(UP); State child(*world_, newRob, newBoxes, *this); up = true; expands.push_back(child); } else if(curBoxes_[i].adjacent(*curRobot_, DOWN)){ newBoxes[i] = curBoxes_[i].push(DOWN); Location newRob = curRobot_->push(DOWN); State child(*world_, newRob, newBoxes, *this); down = true; expands.push_back(child); } } return expands; } /* Display functions */ void State::printState(const string& name){ cout << "State: " << name << endl; cout << "G Cost: " << g_ << endl; cout << "H Cost: " << h_ << endl; cout << "F Cost: " << f_ << endl; } /* ---------------------- */ /* Cost functions */ /* ---------------------- */ // Returns the Manhattan Distance between robot and loc int State::distanceBetween(const Location& loc1, const Location &loc2) const{ //loc1.print(); //loc2.print(); int dX = abs(loc1.getX() - loc2.getX()); int dY = abs(loc1.getY() - loc2.getY()); cout << "Cost between: " << endl; loc1.print("target"); loc2.print("current"); cout << " is " << dX + dY << endl; return dX + dY; } // Cost from start to current pos int State::computeGCost() { int cost = 0; // Get the starting spots vector<Location> inits = *world_->getInitBoxes(); // For each box, compute the distance from the boxes current location and it's starting point for(unsigned int i = 0; i < world_->getNumberOfBoxes(); i++){ cost += distanceBetween(inits[i], curBoxes_[i]); } return cost; } // Heuristic Cost int State::computeHCost() { int cost = 0; // Get the starting spots vector<Location> targets = *world_->getTargetBoxes(); // For each box, compute the distance from the boxes current location and it's target for(unsigned int i = 0; i < world_->getNumberOfBoxes(); i++){ cost += distanceBetween(targets[i], curBoxes_[i]); } return cost; } // NOT NEEDED int State::computeFCost() {}; //TODO: implement this function void State::setGCost(int g) { g_ = g; }; void State::setHCost(int h) { h_ = h; }; void State::setFCost(int f) { f_ = f; }; /* ---------------------- */ /* Overloaded << operator */ /* ---------------------- */ std::ostream& operator<<(std::ostream& os, const State& state) { state.getWorld()->printWorld(); //state.getWorld()->printConfig(); return os; } /* Overload comparison operator */ bool operator== (State &s1, State &s2) { /* Compare robot loation */ if (s1.getRobot() != s2.getRobot()) return false; /* Compare box locations */ std::vector<Location> s1Boxes = s1.getCurBoxes(); std::vector<Location> s2Boxes = s2.getCurBoxes(); for(int i = 0; i < s1Boxes.size(); i++) { if(s1Boxes.at(i) != s2Boxes.at(i)) return false; } /* Compare f, g, and h costs */ if(s1.getFCost() != s2.getFCost()) return false; if(s1.getGCost() != s2.getGCost()) return false; if(s1.getHCost() != s2.getHCost()) return false; /*Compare parent */ if(s1.getParent() != s2.getParent()) return false; return true; } bool operator!= (State &s1, State &s2) { return !(s1 == s2); } <|endoftext|>
<commit_before>/* * Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2007 Holger Hans Peter Freyther <zecke@selfish.org> * Copyright (C) 2008, 2009 Dirk Schulze <krit@webkit.org> * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "ImageBuffer.h" #include "Base64.h" #include "BitmapImage.h" #include "Color.h" #include "GraphicsContext.h" #include "ImageData.h" #include "MIMETypeRegistry.h" #include "Pattern.h" #include "PlatformString.h" #include <cairo.h> #include <wtf/Vector.h> #include <math.h> using namespace std; // Cairo doesn't provide a way to copy a cairo_surface_t. // See http://lists.cairographics.org/archives/cairo/2007-June/010877.html // Once cairo provides the way, use the function instead of this. static inline cairo_surface_t* copySurface(cairo_surface_t* surface) { cairo_format_t format = cairo_image_surface_get_format(surface); int width = cairo_image_surface_get_width(surface); int height = cairo_image_surface_get_height(surface); cairo_surface_t* newsurface = cairo_image_surface_create(format, width, height); cairo_t* cr = cairo_create(newsurface); cairo_set_source_surface(cr, surface, 0, 0); cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); cairo_paint(cr); cairo_destroy(cr); return newsurface; } namespace WebCore { ImageBufferData::ImageBufferData(const IntSize& size) : m_surface(0) { } ImageBuffer::ImageBuffer(const IntSize& size, ImageColorSpace imageColorSpace, bool& success) : m_data(size) , m_size(size) { success = false; // Make early return mean error. m_data.m_surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, size.width(), size.height()); if (cairo_surface_status(m_data.m_surface) != CAIRO_STATUS_SUCCESS) return; // create will notice we didn't set m_initialized and fail. cairo_t* cr = cairo_create(m_data.m_surface); m_context.set(new GraphicsContext(cr)); cairo_destroy(cr); // The context is now owned by the GraphicsContext. success = true; } ImageBuffer::~ImageBuffer() { cairo_surface_destroy(m_data.m_surface); } GraphicsContext* ImageBuffer::context() const { return m_context.get(); } bool ImageBuffer::drawsUsingCopy() const { return true; } PassRefPtr<Image> ImageBuffer::copyImage() const { // BitmapImage will release the passed in surface on destruction return BitmapImage::create(copySurface(m_data.m_surface)); } void ImageBuffer::clip(GraphicsContext* context, const FloatRect&) const { notImplemented(); } void ImageBuffer::draw(GraphicsContext* context, ColorSpace styleColorSpace, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator op , bool useLowQualityScale) { RefPtr<Image> imageCopy = copyImage(); context->drawImage(imageCopy.get(), styleColorSpace, destRect, srcRect, op, useLowQualityScale); } void ImageBuffer::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const AffineTransform& patternTransform, const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator op, const FloatRect& destRect) { RefPtr<Image> imageCopy = copyImage(); imageCopy->drawPattern(context, srcRect, patternTransform, phase, styleColorSpace, op, destRect); } void ImageBuffer::platformTransformColorSpace(const Vector<int>& lookUpTable) { ASSERT(cairo_surface_get_type(m_data.m_surface) == CAIRO_SURFACE_TYPE_IMAGE); unsigned char* dataSrc = cairo_image_surface_get_data(m_data.m_surface); int stride = cairo_image_surface_get_stride(m_data.m_surface); for (int y = 0; y < m_size.height(); ++y) { unsigned* row = reinterpret_cast<unsigned*>(dataSrc + stride * y); for (int x = 0; x < m_size.width(); x++) { unsigned* pixel = row + x; Color pixelColor = colorFromPremultipliedARGB(*pixel); pixelColor = Color(lookUpTable[pixelColor.red()], lookUpTable[pixelColor.green()], lookUpTable[pixelColor.blue()], pixelColor.alpha()); *pixel = premultipliedARGBFromColor(pixelColor); } } cairo_surface_mark_dirty_rectangle (m_data.m_surface, 0, 0, m_size.width(), m_size.height()); } template <Multiply multiplied> PassRefPtr<ImageData> getImageData(const IntRect& rect, const ImageBufferData& data, const IntSize& size) { ASSERT(cairo_surface_get_type(data.m_surface) == CAIRO_SURFACE_TYPE_IMAGE); PassRefPtr<ImageData> result = ImageData::create(rect.width(), rect.height()); unsigned char* dataSrc = cairo_image_surface_get_data(data.m_surface); unsigned char* dataDst = result->data()->data()->data(); if (rect.x() < 0 || rect.y() < 0 || (rect.x() + rect.width()) > size.width() || (rect.y() + rect.height()) > size.height()) memset(dataDst, 0, result->data()->length()); int originx = rect.x(); int destx = 0; if (originx < 0) { destx = -originx; originx = 0; } int endx = rect.x() + rect.width(); if (endx > size.width()) endx = size.width(); int numColumns = endx - originx; int originy = rect.y(); int desty = 0; if (originy < 0) { desty = -originy; originy = 0; } int endy = rect.y() + rect.height(); if (endy > size.height()) endy = size.height(); int numRows = endy - originy; int stride = cairo_image_surface_get_stride(data.m_surface); unsigned destBytesPerRow = 4 * rect.width(); unsigned char* destRows = dataDst + desty * destBytesPerRow + destx * 4; for (int y = 0; y < numRows; ++y) { unsigned* row = reinterpret_cast<unsigned*>(dataSrc + stride * (y + originy)); for (int x = 0; x < numColumns; x++) { int basex = x * 4; unsigned* pixel = row + x + originx; Color pixelColor; if (multiplied == Unmultiplied) pixelColor = colorFromPremultipliedARGB(*pixel); else pixelColor = Color(*pixel); destRows[basex] = pixelColor.red(); destRows[basex + 1] = pixelColor.green(); destRows[basex + 2] = pixelColor.blue(); destRows[basex + 3] = pixelColor.alpha(); } destRows += destBytesPerRow; } return result; } PassRefPtr<ImageData> ImageBuffer::getUnmultipliedImageData(const IntRect& rect) const { return getImageData<Unmultiplied>(rect, m_data, m_size); } PassRefPtr<ImageData> ImageBuffer::getPremultipliedImageData(const IntRect& rect) const { return getImageData<Premultiplied>(rect, m_data, m_size); } template <Multiply multiplied> void putImageData(ImageData*& source, const IntRect& sourceRect, const IntPoint& destPoint, ImageBufferData& data, const IntSize& size) { ASSERT(cairo_surface_get_type(data.m_surface) == CAIRO_SURFACE_TYPE_IMAGE); unsigned char* dataDst = cairo_image_surface_get_data(data.m_surface); ASSERT(sourceRect.width() > 0); ASSERT(sourceRect.height() > 0); int originx = sourceRect.x(); int destx = destPoint.x() + sourceRect.x(); ASSERT(destx >= 0); ASSERT(destx < size.width()); ASSERT(originx >= 0); ASSERT(originx <= sourceRect.right()); int endx = destPoint.x() + sourceRect.right(); ASSERT(endx <= size.width()); int numColumns = endx - destx; int originy = sourceRect.y(); int desty = destPoint.y() + sourceRect.y(); ASSERT(desty >= 0); ASSERT(desty < size.height()); ASSERT(originy >= 0); ASSERT(originy <= sourceRect.bottom()); int endy = destPoint.y() + sourceRect.bottom(); ASSERT(endy <= size.height()); int numRows = endy - desty; unsigned srcBytesPerRow = 4 * source->width(); int stride = cairo_image_surface_get_stride(data.m_surface); unsigned char* srcRows = source->data()->data()->data() + originy * srcBytesPerRow + originx * 4; for (int y = 0; y < numRows; ++y) { unsigned* row = reinterpret_cast<unsigned*>(dataDst + stride * (y + desty)); for (int x = 0; x < numColumns; x++) { int basex = x * 4; unsigned* pixel = row + x + destx; Color pixelColor(srcRows[basex], srcRows[basex + 1], srcRows[basex + 2], srcRows[basex + 3]); if (multiplied == Unmultiplied) *pixel = premultipliedARGBFromColor(pixelColor); else *pixel = pixelColor.rgb(); } srcRows += srcBytesPerRow; } cairo_surface_mark_dirty_rectangle (data.m_surface, destx, desty, numColumns, numRows); } void ImageBuffer::putUnmultipliedImageData(ImageData* source, const IntRect& sourceRect, const IntPoint& destPoint) { putImageData<Unmultiplied>(source, sourceRect, destPoint, m_data, m_size); } void ImageBuffer::putPremultipliedImageData(ImageData* source, const IntRect& sourceRect, const IntPoint& destPoint) { putImageData<Premultiplied>(source, sourceRect, destPoint, m_data, m_size); } #if !PLATFORM(GTK) static cairo_status_t writeFunction(void* closure, const unsigned char* data, unsigned int length) { Vector<char>* in = reinterpret_cast<Vector<char>*>(closure); in->append(data, length); return CAIRO_STATUS_SUCCESS; } String ImageBuffer::toDataURL(const String& mimeType, const double*) const { cairo_surface_t* image = cairo_get_target(context()->platformContext()); if (!image) return "data:,"; String actualMimeType("image/png"); if (MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType)) actualMimeType = mimeType; Vector<char> in; // Only PNG output is supported for now. cairo_surface_write_to_png_stream(image, writeFunction, &in); Vector<char> out; base64Encode(in, out); return "data:" + actualMimeType + ";base64," + String(out.data(), out.size()); } #endif } // namespace WebCore <commit_msg>Fix GTK build bustage.<commit_after>/* * Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2007 Holger Hans Peter Freyther <zecke@selfish.org> * Copyright (C) 2008, 2009 Dirk Schulze <krit@webkit.org> * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "ImageBuffer.h" #include "Base64.h" #include "BitmapImage.h" #include "Color.h" #include "GraphicsContext.h" #include "ImageData.h" #include "MIMETypeRegistry.h" #include "NotImplemented.h" #include "Pattern.h" #include "PlatformString.h" #include <cairo.h> #include <wtf/Vector.h> #include <math.h> using namespace std; // Cairo doesn't provide a way to copy a cairo_surface_t. // See http://lists.cairographics.org/archives/cairo/2007-June/010877.html // Once cairo provides the way, use the function instead of this. static inline cairo_surface_t* copySurface(cairo_surface_t* surface) { cairo_format_t format = cairo_image_surface_get_format(surface); int width = cairo_image_surface_get_width(surface); int height = cairo_image_surface_get_height(surface); cairo_surface_t* newsurface = cairo_image_surface_create(format, width, height); cairo_t* cr = cairo_create(newsurface); cairo_set_source_surface(cr, surface, 0, 0); cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); cairo_paint(cr); cairo_destroy(cr); return newsurface; } namespace WebCore { ImageBufferData::ImageBufferData(const IntSize& size) : m_surface(0) { } ImageBuffer::ImageBuffer(const IntSize& size, ImageColorSpace imageColorSpace, bool& success) : m_data(size) , m_size(size) { success = false; // Make early return mean error. m_data.m_surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, size.width(), size.height()); if (cairo_surface_status(m_data.m_surface) != CAIRO_STATUS_SUCCESS) return; // create will notice we didn't set m_initialized and fail. cairo_t* cr = cairo_create(m_data.m_surface); m_context.set(new GraphicsContext(cr)); cairo_destroy(cr); // The context is now owned by the GraphicsContext. success = true; } ImageBuffer::~ImageBuffer() { cairo_surface_destroy(m_data.m_surface); } GraphicsContext* ImageBuffer::context() const { return m_context.get(); } bool ImageBuffer::drawsUsingCopy() const { return true; } PassRefPtr<Image> ImageBuffer::copyImage() const { // BitmapImage will release the passed in surface on destruction return BitmapImage::create(copySurface(m_data.m_surface)); } void ImageBuffer::clip(GraphicsContext*, const FloatRect&) const { notImplemented(); } void ImageBuffer::draw(GraphicsContext* context, ColorSpace styleColorSpace, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator op , bool useLowQualityScale) { RefPtr<Image> imageCopy = copyImage(); context->drawImage(imageCopy.get(), styleColorSpace, destRect, srcRect, op, useLowQualityScale); } void ImageBuffer::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const AffineTransform& patternTransform, const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator op, const FloatRect& destRect) { RefPtr<Image> imageCopy = copyImage(); imageCopy->drawPattern(context, srcRect, patternTransform, phase, styleColorSpace, op, destRect); } void ImageBuffer::platformTransformColorSpace(const Vector<int>& lookUpTable) { ASSERT(cairo_surface_get_type(m_data.m_surface) == CAIRO_SURFACE_TYPE_IMAGE); unsigned char* dataSrc = cairo_image_surface_get_data(m_data.m_surface); int stride = cairo_image_surface_get_stride(m_data.m_surface); for (int y = 0; y < m_size.height(); ++y) { unsigned* row = reinterpret_cast<unsigned*>(dataSrc + stride * y); for (int x = 0; x < m_size.width(); x++) { unsigned* pixel = row + x; Color pixelColor = colorFromPremultipliedARGB(*pixel); pixelColor = Color(lookUpTable[pixelColor.red()], lookUpTable[pixelColor.green()], lookUpTable[pixelColor.blue()], pixelColor.alpha()); *pixel = premultipliedARGBFromColor(pixelColor); } } cairo_surface_mark_dirty_rectangle (m_data.m_surface, 0, 0, m_size.width(), m_size.height()); } template <Multiply multiplied> PassRefPtr<ImageData> getImageData(const IntRect& rect, const ImageBufferData& data, const IntSize& size) { ASSERT(cairo_surface_get_type(data.m_surface) == CAIRO_SURFACE_TYPE_IMAGE); PassRefPtr<ImageData> result = ImageData::create(rect.width(), rect.height()); unsigned char* dataSrc = cairo_image_surface_get_data(data.m_surface); unsigned char* dataDst = result->data()->data()->data(); if (rect.x() < 0 || rect.y() < 0 || (rect.x() + rect.width()) > size.width() || (rect.y() + rect.height()) > size.height()) memset(dataDst, 0, result->data()->length()); int originx = rect.x(); int destx = 0; if (originx < 0) { destx = -originx; originx = 0; } int endx = rect.x() + rect.width(); if (endx > size.width()) endx = size.width(); int numColumns = endx - originx; int originy = rect.y(); int desty = 0; if (originy < 0) { desty = -originy; originy = 0; } int endy = rect.y() + rect.height(); if (endy > size.height()) endy = size.height(); int numRows = endy - originy; int stride = cairo_image_surface_get_stride(data.m_surface); unsigned destBytesPerRow = 4 * rect.width(); unsigned char* destRows = dataDst + desty * destBytesPerRow + destx * 4; for (int y = 0; y < numRows; ++y) { unsigned* row = reinterpret_cast<unsigned*>(dataSrc + stride * (y + originy)); for (int x = 0; x < numColumns; x++) { int basex = x * 4; unsigned* pixel = row + x + originx; Color pixelColor; if (multiplied == Unmultiplied) pixelColor = colorFromPremultipliedARGB(*pixel); else pixelColor = Color(*pixel); destRows[basex] = pixelColor.red(); destRows[basex + 1] = pixelColor.green(); destRows[basex + 2] = pixelColor.blue(); destRows[basex + 3] = pixelColor.alpha(); } destRows += destBytesPerRow; } return result; } PassRefPtr<ImageData> ImageBuffer::getUnmultipliedImageData(const IntRect& rect) const { return getImageData<Unmultiplied>(rect, m_data, m_size); } PassRefPtr<ImageData> ImageBuffer::getPremultipliedImageData(const IntRect& rect) const { return getImageData<Premultiplied>(rect, m_data, m_size); } template <Multiply multiplied> void putImageData(ImageData*& source, const IntRect& sourceRect, const IntPoint& destPoint, ImageBufferData& data, const IntSize& size) { ASSERT(cairo_surface_get_type(data.m_surface) == CAIRO_SURFACE_TYPE_IMAGE); unsigned char* dataDst = cairo_image_surface_get_data(data.m_surface); ASSERT(sourceRect.width() > 0); ASSERT(sourceRect.height() > 0); int originx = sourceRect.x(); int destx = destPoint.x() + sourceRect.x(); ASSERT(destx >= 0); ASSERT(destx < size.width()); ASSERT(originx >= 0); ASSERT(originx <= sourceRect.right()); int endx = destPoint.x() + sourceRect.right(); ASSERT(endx <= size.width()); int numColumns = endx - destx; int originy = sourceRect.y(); int desty = destPoint.y() + sourceRect.y(); ASSERT(desty >= 0); ASSERT(desty < size.height()); ASSERT(originy >= 0); ASSERT(originy <= sourceRect.bottom()); int endy = destPoint.y() + sourceRect.bottom(); ASSERT(endy <= size.height()); int numRows = endy - desty; unsigned srcBytesPerRow = 4 * source->width(); int stride = cairo_image_surface_get_stride(data.m_surface); unsigned char* srcRows = source->data()->data()->data() + originy * srcBytesPerRow + originx * 4; for (int y = 0; y < numRows; ++y) { unsigned* row = reinterpret_cast<unsigned*>(dataDst + stride * (y + desty)); for (int x = 0; x < numColumns; x++) { int basex = x * 4; unsigned* pixel = row + x + destx; Color pixelColor(srcRows[basex], srcRows[basex + 1], srcRows[basex + 2], srcRows[basex + 3]); if (multiplied == Unmultiplied) *pixel = premultipliedARGBFromColor(pixelColor); else *pixel = pixelColor.rgb(); } srcRows += srcBytesPerRow; } cairo_surface_mark_dirty_rectangle (data.m_surface, destx, desty, numColumns, numRows); } void ImageBuffer::putUnmultipliedImageData(ImageData* source, const IntRect& sourceRect, const IntPoint& destPoint) { putImageData<Unmultiplied>(source, sourceRect, destPoint, m_data, m_size); } void ImageBuffer::putPremultipliedImageData(ImageData* source, const IntRect& sourceRect, const IntPoint& destPoint) { putImageData<Premultiplied>(source, sourceRect, destPoint, m_data, m_size); } #if !PLATFORM(GTK) static cairo_status_t writeFunction(void* closure, const unsigned char* data, unsigned int length) { Vector<char>* in = reinterpret_cast<Vector<char>*>(closure); in->append(data, length); return CAIRO_STATUS_SUCCESS; } String ImageBuffer::toDataURL(const String& mimeType, const double*) const { cairo_surface_t* image = cairo_get_target(context()->platformContext()); if (!image) return "data:,"; String actualMimeType("image/png"); if (MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType)) actualMimeType = mimeType; Vector<char> in; // Only PNG output is supported for now. cairo_surface_write_to_png_stream(image, writeFunction, &in); Vector<char> out; base64Encode(in, out); return "data:" + actualMimeType + ";base64," + String(out.data(), out.size()); } #endif } // namespace WebCore <|endoftext|>
<commit_before>#ifndef RPC_CLIENT_HH #define RPC_CLIENT_HH #include "rpc/protocol.hh" using namespace msgpack::rpc; namespace ten { #if 0 // more general interface that supports calls over udp/tcp/pipe // TODO: allow server to call to the client // session should be shared interface both sides use // calls can create channels and wait on them // allow multiple simultaneous calls // out of order replies // calls with no reply (notify) class rpc_transport { virtual void send(msgpack::sbuffer &sbuf) = 0; } class rpc_session { // call() }; #endif struct rpc_failure : public errorx { rpc_failure(const std::string &msg) : errorx(msg) {} }; class rpc_client { public: rpc_client(const std::string &hostname_, uint16_t port_=0) : hostname(hostname_), port(port_), msgid(0) { parse_host_port(hostname, port); } rpc_client(const rpc_client &) = delete; rpc_client &operator =(const rpc_client &) = delete; template <typename Result, typename ...Args> Result call(const std::string &method, Args ...args) { uint32_t mid = ++msgid; return rpcall<Result>(mid, method, args...); } protected: netsock s; std::string hostname; uint16_t port; uint32_t msgid; msgpack::unpacker pac; void ensure_connection() { if (!s.valid()) { netsock tmp(AF_INET, SOCK_STREAM); std::swap(s, tmp); if (s.dial(hostname.c_str(), port) != 0) { throw rpc_failure("dial"); } } } template <typename Result> Result rpcall(msgpack::packer<msgpack::sbuffer> &pk, msgpack::sbuffer &sbuf) { ensure_connection(); ssize_t nw = s.send(sbuf.data(), sbuf.size()); if (nw != (ssize_t)sbuf.size()) { s.close(); throw rpc_failure("send"); } size_t bsize = 4096; for (;;) { pac.reserve_buffer(bsize); ssize_t nr = s.recv(pac.buffer(), bsize); if (nr <= 0) { s.close(); throw rpc_failure("recv"); } DVLOG(3) << "client recv: " << nr; pac.buffer_consumed(nr); msgpack::unpacked result; if (pac.next(&result)) { msgpack::object o = result.get(); DVLOG(3) << "client got: " << o; msg_response<msgpack::object, msgpack::object> resp; o.convert(&resp); if (resp.error.is_nil()) { return resp.result.as<Result>(); } else { LOG(ERROR) << "rpc error returned: " << resp.error; throw errorx(resp.error.as<std::string>()); } } } // shouldn't get here. throw errorx("rpc client unknown error"); } template <typename Result, typename Arg, typename ...Args> Result rpcall(msgpack::packer<msgpack::sbuffer> &pk, msgpack::sbuffer &sbuf, Arg arg, Args ...args) { pk.pack(arg); return rpcall<Result>(pk, sbuf, args...); } template <typename Result, typename ...Args> Result rpcall(uint32_t msgid, const std::string &method, Args ...args) { msgpack::sbuffer sbuf; msgpack::packer<msgpack::sbuffer> pk(&sbuf); pk.pack_array(4); pk.pack_uint8(0); // request message type pk.pack_uint32(msgid); pk.pack(method); pk.pack_array(sizeof...(args)); return rpcall<Result>(pk, sbuf, args...); } }; } // end namespace ten #endif <commit_msg>add rpc pool<commit_after>#ifndef RPC_CLIENT_HH #define RPC_CLIENT_HH #include "rpc/protocol.hh" #include "shared_pool.hh" #include <boost/lexical_cast.hpp> using namespace msgpack::rpc; namespace ten { #if 0 // more general interface that supports calls over udp/tcp/pipe // TODO: allow server to call to the client // session should be shared interface both sides use // calls can create channels and wait on them // allow multiple simultaneous calls // out of order replies // calls with no reply (notify) class rpc_transport { virtual void send(msgpack::sbuffer &sbuf) = 0; } class rpc_session { // call() }; #endif struct rpc_failure : public errorx { rpc_failure(const std::string &msg) : errorx(msg) {} }; class rpc_client { public: rpc_client(const std::string &hostname_, uint16_t port_=0) : hostname(hostname_), port(port_), msgid(0) { parse_host_port(hostname, port); } rpc_client(const rpc_client &) = delete; rpc_client &operator =(const rpc_client &) = delete; template <typename Result, typename ...Args> Result call(const std::string &method, Args ...args) { uint32_t mid = ++msgid; return rpcall<Result>(mid, method, args...); } protected: netsock s; std::string hostname; uint16_t port; uint32_t msgid; msgpack::unpacker pac; void ensure_connection() { if (!s.valid()) { netsock tmp(AF_INET, SOCK_STREAM); std::swap(s, tmp); if (s.dial(hostname.c_str(), port) != 0) { throw rpc_failure("dial"); } } } template <typename Result> Result rpcall(msgpack::packer<msgpack::sbuffer> &pk, msgpack::sbuffer &sbuf) { ensure_connection(); ssize_t nw = s.send(sbuf.data(), sbuf.size()); if (nw != (ssize_t)sbuf.size()) { s.close(); throw rpc_failure("send"); } size_t bsize = 4096; for (;;) { pac.reserve_buffer(bsize); ssize_t nr = s.recv(pac.buffer(), bsize); if (nr <= 0) { s.close(); throw rpc_failure("recv"); } DVLOG(3) << "client recv: " << nr; pac.buffer_consumed(nr); msgpack::unpacked result; if (pac.next(&result)) { msgpack::object o = result.get(); DVLOG(3) << "client got: " << o; msg_response<msgpack::object, msgpack::object> resp; o.convert(&resp); if (resp.error.is_nil()) { return resp.result.as<Result>(); } else { LOG(ERROR) << "rpc error returned: " << resp.error; throw errorx(resp.error.as<std::string>()); } } } // shouldn't get here. throw errorx("rpc client unknown error"); } template <typename Result, typename Arg, typename ...Args> Result rpcall(msgpack::packer<msgpack::sbuffer> &pk, msgpack::sbuffer &sbuf, Arg arg, Args ...args) { pk.pack(arg); return rpcall<Result>(pk, sbuf, args...); } template <typename Result, typename ...Args> Result rpcall(uint32_t msgid, const std::string &method, Args ...args) { msgpack::sbuffer sbuf; msgpack::packer<msgpack::sbuffer> pk(&sbuf); pk.pack_array(4); pk.pack_uint8(0); // request message type pk.pack_uint32(msgid); pk.pack(method); pk.pack_array(sizeof...(args)); return rpcall<Result>(pk, sbuf, args...); } }; class rpc_pool : public shared_pool<rpc_client> { public: rpc_pool(const std::string &host_, uint16_t port_, ssize_t max_conn) : shared_pool<rpc_client>( "rpc:" + host_ + ":" + boost::lexical_cast<std::string>(port_), std::bind(&rpc_pool::new_resource, this), max_conn ), host(host_), port(port_) {} rpc_pool(const std::string &host_, ssize_t max_conn) : shared_pool<rpc_client>("rpc:" + host_, std::bind(&rpc_pool::new_resource, this), max_conn ), host(host_), port(0) { parse_host_port(host, port); } protected: std::string host; uint16_t port; std::shared_ptr<rpc_client> new_resource() { VLOG(3) << "new rpc_client resource " << host << ":" << port; return std::make_shared<rpc_client>(host, port); } }; } // end namespace ten #endif <|endoftext|>
<commit_before>#ifndef _SDD_DD_SUM_HH_ #define _SDD_DD_SUM_HH_ #include <initializer_list> #include <type_traits> // enable_if, is_same #include <unordered_map> #include <vector> #include <boost/container/flat_set.hpp> #include "sdd/internal_manager_fwd.hh" #include "sdd/dd/context_fwd.hh" #include "sdd/dd/definition.hh" #include "sdd/dd/nary.hh" #include "sdd/dd/operations_fwd.hh" #include "sdd/dd/square_union.hh" #include "sdd/util/hash.hh" #include "sdd/values/values_traits.hh" namespace sdd { namespace dd { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief The sum operation in the cache. template <typename C> struct LIBSDD_ATTRIBUTE_PACKED sum_op_impl { /// @brief The textual representation of the union operator. static constexpr char symbol = '+'; /// @brief Perform the SDD union algorithm. /// /// It's a so-called 'n-ary' union in the sense that we don't create intermediary SDD. /// Also, a lot of tests permit to break loops as soon as possible. template <typename InputIterator, typename NodeType> static typename std::enable_if< std::is_same<NodeType, hierarchical_node<C>>::value or not values::values_traits<typename C::Values>::fast_iterable , SDD<C>>::type work(InputIterator begin, InputIterator end, context<C>& cxt) { typedef NodeType node_type; typedef typename node_type::valuation_type valuation_type; auto operands_cit = begin; const auto operands_end = end; // Get the first operand as a node, we need it to initialize the algorithm. const node_type& head = mem::variant_cast<node_type>(**operands_cit); // Type of the list of successors for a valuation, to be merged with the union operation // right before calling the square union. typedef sum_builder<C, SDD<C>> sum_builder_type; /// @todo Use Boost.Intrusive to save on memory allocations? // List all the successors for each valuation in the final alpha. std::unordered_map<valuation_type, sum_builder_type> res(head.size()); // Needed to temporarily store arcs erased from res and arcs from the alpha visited in // the loop (B). std::vector<std::pair<valuation_type, sum_builder_type>> save; save.reserve(head.size()); // Used in test (F). std::vector<std::pair<valuation_type, sum_builder_type>> remainder; remainder.reserve(head.size()); // Initialize res with the alpha of the first operand. for (auto& arc : head) { sum_builder_type succs; succs.add(arc.successor()); res.emplace(arc.valuation(), std::move(succs)); } // (A). for (++operands_cit; operands_cit != operands_end; ++operands_cit) { // Throw a Top if operands are incompatible (different types or different variables). check_compatibility(*begin, *operands_cit); const auto res_end = res.end(); const node_type& node = mem::variant_cast<node_type>(**operands_cit); const auto alpha_end = node.end(); // (B). For each arc of the current operand. for (auto alpha_cit = node.begin(); alpha_cit != alpha_end; ++alpha_cit) { // The current valuation may be modified, we need a copy. valuation_type current_val = alpha_cit->valuation(); const SDD<C> current_succ = alpha_cit->successor(); // Initialize the start of the next search. auto res_cit = res.begin(); // (C). While the current valuation is not empty, test it against arcs in res. while (not current_val.empty() and res_cit != res_end) { const valuation_type& res_val = res_cit->first; sum_builder_type& res_succs = res_cit->second; // (D). if (current_val == res_val) // Same valuations. { save.emplace_back(res_val, std::move(res_succs)); save.back().second.add(current_succ); const auto to_erase = res_cit; ++res_cit; res.erase(to_erase); // Avoid useless insertion or temporary variables. goto equality; } intersection_builder<C, valuation_type> inter_builder; inter_builder.add(current_val); inter_builder.add(res_val); const valuation_type inter = intersection(cxt, std::move(inter_builder)); // (E). The current valuation and the current arc from res have a common part. if (not inter.empty()) { save.emplace_back(inter, res_succs); save.back().second.add(current_succ); // (F). valuation_type diff = difference(cxt, res_val, inter); if (not diff.empty()) { // (res_val - inter) can't be in intersection, but we need to keep it // for the next arcs of the current alpha. So we put in a temporary storage. // It will be added back in res when we have finished with the current valuation. remainder.emplace_back(std::move(diff), std::move(res_succs)); } // We won't need the current arc of res for the current val, we already have the // common part. Now, the current valuation has to be tested against the next arcs // of res. const auto to_erase = res_cit; ++res_cit; res.erase(to_erase); // (G). The current valuation is completely included in the current arc of res. if (current_val == inter) { // We can move to the next arc of the current operand. break; } // Continue with what remains of val. if val is empy, the loop will stop at the // next iteration. current_val = difference(cxt, current_val, inter); } else // (H). Empty intersection, lookup for next possible common parts. { ++res_cit; } } // While we're not at the end of res and val is not empty. // (I). For val or a part of val (it could have been modified during the previous // loop), we didn't find an intersection with any arc of res. if (not current_val.empty()) { sum_builder_type succs; succs.add(current_succ); save.emplace_back(std::move(current_val), std::move(succs)); } // Both arcs had the same valuation. equality:; // Reinject all parts that were removed in (F). for (auto& rem : remainder) { res.emplace(std::move(rem.first), std::move(rem.second)); } remainder.clear(); } // For each arc of the current operand. // Reinject all parts that were removed from res (all parts that have a non-empty // intersection with the current alpha) and all parts of the current alpha that have an // empty intersection with all the parts of res. res.insert(save.begin(), save.end()); // We still need save. save.clear(); } // End of iteration on operands. square_union<C, valuation_type> su; su.reserve(res.size()); for (auto& arc : res) { // construct an operand for the square union: (successors union) --> valuation su.add(sum(cxt, std::move(arc.second)), arc.first); } return SDD<C>(head.variable(), su(cxt)); } /// @brief Linear union of flat SDDs whose valuation are "fast iterable". template <typename InputIterator, typename NodeType> static typename std::enable_if< std::is_same<NodeType, flat_node<C>>::value and values::values_traits<typename C::Values>::fast_iterable , SDD<C>>::type work(InputIterator begin, InputIterator end, context<C>& cxt) { const auto& variable = mem::variant_cast<flat_node<C>>(**begin).variable(); typedef typename C::Values values_type; typedef typename values_type::value_type value_type; typedef sum_builder<C, SDD<C>> sum_builder_type; std::unordered_map<value_type, sum_builder_type> value_to_succ; auto cit = begin; for (; cit != end; ++cit) { check_compatibility(*begin, *cit); const auto& node = mem::variant_cast<flat_node<C>>(**cit); for (const auto& arc : node) { const SDD<C> succ = arc.successor(); for (const auto& value : arc.valuation()) { const auto search = value_to_succ.find(value); if (search == value_to_succ.end()) { value_to_succ.emplace_hint(search, value, sum_builder_type({succ})); } else { search->second.add(succ); } } } } std::unordered_map<SDD<C>, values_type> succ_to_value(value_to_succ.bucket_count()); for (auto& value_succs : value_to_succ) { const SDD<C> succ = sum(cxt, std::move(value_succs.second)); const auto search = succ_to_value.find(succ); if (search == succ_to_value.end()) { succ_to_value.emplace_hint(search, succ, values_type({value_succs.first})); } else { search->second.insert(value_succs.first); } } alpha_builder<C, values_type> alpha; alpha.reserve(succ_to_value.size()); for (auto& succ_values : succ_to_value) { alpha.add(std::move(succ_values.second), succ_values.first); } return SDD<C>(variable, std::move(alpha)); } }; /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Add an arc to the operands of the sum operation. /// /// This implementation is meant to be used as a policy by nary_builder which doesn't know how /// to add an arc. template <typename C, typename Valuation> struct LIBSDD_ATTRIBUTE_PACKED sum_builder_impl { void add(boost::container::flat_set<Valuation>& set, Valuation&& operand) { if (not operand.empty()) { set.insert(std::move(operand)); } } void add(boost::container::flat_set<Valuation>& set, const Valuation& operand) { if (not operand.empty()) { set.insert(operand); } } }; /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief The sum operation of a set of SDD. /// @related SDD template <typename C> inline SDD<C> sum(context<C>& cxt, sum_builder<C, SDD<C>>&& builder) { if (builder.empty()) { return zero<C>(); } else if (builder.size() == 1) { return *builder.begin(); } return cxt.sum_cache()(sum_op<C>(builder)); } /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief The sum operation of a set of values. /// @details A wrapper around the implementation of sum provided by Values. template <typename C, typename Values> inline Values sum(context<C>&, sum_builder<C, Values>&& builder) { if (builder.empty()) { return Values(); } else if (builder.size() == 1) { return *builder.begin(); } else { auto cit = builder.begin(); const auto end = builder.end(); Values result = *cit; for (++cit; cit != end; ++cit) { typename C::Values tmp = sum(result, *cit); using std::swap; swap(tmp, result); } return result; } } } // namespace dd /*------------------------------------------------------------------------------------------------*/ /// @brief Perform the union of two SDD. /// @related SDD template <typename C> inline SDD<C> operator+(const SDD<C>& lhs, const SDD<C>& rhs) { return dd::sum(global<C>().sdd_context, {lhs, rhs}); } /// @brief Perform the union of two SDD. /// @related SDD template <typename C> inline SDD<C>& operator+=(SDD<C>& lhs, const SDD<C>& rhs) { SDD<C> tmp = dd::sum(global<C>().sdd_context, {lhs, rhs}); using std::swap; swap(tmp, lhs); return lhs; } /// @brief Perform the union of an iterable container of SDD. /// @related SDD template <typename C, typename InputIterator> SDD<C> inline sum(InputIterator begin, InputIterator end) { dd::sum_builder<C, SDD<C>> builder; for (; begin != end; ++begin) { builder.add(*begin); } return dd::sum(global<C>().sdd_context, std::move(builder)); } /// @brief Perform the union of an initializer list of SDD. /// @related SDD template <typename C> SDD<C> inline sum(std::initializer_list<SDD<C>> operands) { return sum<C>(std::begin(operands), std::end(operands)); } /*------------------------------------------------------------------------------------------------*/ } // namespace sdd #endif // _SDD_DD_SUM_HH_ <commit_msg>Use a flat map rather than a unordered map when performing the union of flat nodes.<commit_after>#ifndef _SDD_DD_SUM_HH_ #define _SDD_DD_SUM_HH_ #include <initializer_list> #include <type_traits> // enable_if, is_same #include <unordered_map> #include <vector> #include <boost/container/flat_map.hpp> #include <boost/container/flat_set.hpp> #include "sdd/internal_manager_fwd.hh" #include "sdd/dd/context_fwd.hh" #include "sdd/dd/definition.hh" #include "sdd/dd/nary.hh" #include "sdd/dd/operations_fwd.hh" #include "sdd/dd/square_union.hh" #include "sdd/util/hash.hh" #include "sdd/values/values_traits.hh" namespace sdd { namespace dd { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief The sum operation in the cache. template <typename C> struct LIBSDD_ATTRIBUTE_PACKED sum_op_impl { /// @brief The textual representation of the union operator. static constexpr char symbol = '+'; /// @brief Perform the SDD union algorithm. /// /// It's a so-called 'n-ary' union in the sense that we don't create intermediary SDD. /// Also, a lot of tests permit to break loops as soon as possible. template <typename InputIterator, typename NodeType> static typename std::enable_if< std::is_same<NodeType, hierarchical_node<C>>::value or not values::values_traits<typename C::Values>::fast_iterable , SDD<C>>::type work(InputIterator begin, InputIterator end, context<C>& cxt) { typedef NodeType node_type; typedef typename node_type::valuation_type valuation_type; auto operands_cit = begin; const auto operands_end = end; // Get the first operand as a node, we need it to initialize the algorithm. const node_type& head = mem::variant_cast<node_type>(**operands_cit); // Type of the list of successors for a valuation, to be merged with the union operation // right before calling the square union. typedef sum_builder<C, SDD<C>> sum_builder_type; /// @todo Use Boost.Intrusive to save on memory allocations? // List all the successors for each valuation in the final alpha. std::unordered_map<valuation_type, sum_builder_type> res(head.size()); // Needed to temporarily store arcs erased from res and arcs from the alpha visited in // the loop (B). std::vector<std::pair<valuation_type, sum_builder_type>> save; save.reserve(head.size()); // Used in test (F). std::vector<std::pair<valuation_type, sum_builder_type>> remainder; remainder.reserve(head.size()); // Initialize res with the alpha of the first operand. for (auto& arc : head) { sum_builder_type succs; succs.add(arc.successor()); res.emplace(arc.valuation(), std::move(succs)); } // (A). for (++operands_cit; operands_cit != operands_end; ++operands_cit) { // Throw a Top if operands are incompatible (different types or different variables). check_compatibility(*begin, *operands_cit); const auto res_end = res.end(); const node_type& node = mem::variant_cast<node_type>(**operands_cit); const auto alpha_end = node.end(); // (B). For each arc of the current operand. for (auto alpha_cit = node.begin(); alpha_cit != alpha_end; ++alpha_cit) { // The current valuation may be modified, we need a copy. valuation_type current_val = alpha_cit->valuation(); const SDD<C> current_succ = alpha_cit->successor(); // Initialize the start of the next search. auto res_cit = res.begin(); // (C). While the current valuation is not empty, test it against arcs in res. while (not current_val.empty() and res_cit != res_end) { const valuation_type& res_val = res_cit->first; sum_builder_type& res_succs = res_cit->second; // (D). if (current_val == res_val) // Same valuations. { save.emplace_back(res_val, std::move(res_succs)); save.back().second.add(current_succ); const auto to_erase = res_cit; ++res_cit; res.erase(to_erase); // Avoid useless insertion or temporary variables. goto equality; } intersection_builder<C, valuation_type> inter_builder; inter_builder.add(current_val); inter_builder.add(res_val); const valuation_type inter = intersection(cxt, std::move(inter_builder)); // (E). The current valuation and the current arc from res have a common part. if (not inter.empty()) { save.emplace_back(inter, res_succs); save.back().second.add(current_succ); // (F). valuation_type diff = difference(cxt, res_val, inter); if (not diff.empty()) { // (res_val - inter) can't be in intersection, but we need to keep it // for the next arcs of the current alpha. So we put in a temporary storage. // It will be added back in res when we have finished with the current valuation. remainder.emplace_back(std::move(diff), std::move(res_succs)); } // We won't need the current arc of res for the current val, we already have the // common part. Now, the current valuation has to be tested against the next arcs // of res. const auto to_erase = res_cit; ++res_cit; res.erase(to_erase); // (G). The current valuation is completely included in the current arc of res. if (current_val == inter) { // We can move to the next arc of the current operand. break; } // Continue with what remains of val. if val is empy, the loop will stop at the // next iteration. current_val = difference(cxt, current_val, inter); } else // (H). Empty intersection, lookup for next possible common parts. { ++res_cit; } } // While we're not at the end of res and val is not empty. // (I). For val or a part of val (it could have been modified during the previous // loop), we didn't find an intersection with any arc of res. if (not current_val.empty()) { sum_builder_type succs; succs.add(current_succ); save.emplace_back(std::move(current_val), std::move(succs)); } // Both arcs had the same valuation. equality:; // Reinject all parts that were removed in (F). for (auto& rem : remainder) { res.emplace(std::move(rem.first), std::move(rem.second)); } remainder.clear(); } // For each arc of the current operand. // Reinject all parts that were removed from res (all parts that have a non-empty // intersection with the current alpha) and all parts of the current alpha that have an // empty intersection with all the parts of res. res.insert(save.begin(), save.end()); // We still need save. save.clear(); } // End of iteration on operands. square_union<C, valuation_type> su; su.reserve(res.size()); for (auto& arc : res) { // construct an operand for the square union: (successors union) --> valuation su.add(sum(cxt, std::move(arc.second)), arc.first); } return SDD<C>(head.variable(), su(cxt)); } /// @brief Linear union of flat SDDs whose valuation are "fast iterable". template <typename InputIterator, typename NodeType> static typename std::enable_if< std::is_same<NodeType, flat_node<C>>::value and values::values_traits<typename C::Values>::fast_iterable , SDD<C>>::type work(InputIterator begin, InputIterator end, context<C>& cxt) { const auto& variable = mem::variant_cast<flat_node<C>>(**begin).variable(); typedef typename C::Values values_type; typedef typename values_type::value_type value_type; typedef sum_builder<C, SDD<C>> sum_builder_type; boost::container::flat_map<value_type, sum_builder_type> value_to_succ; value_to_succ.reserve(std::distance(begin, end) * 2); auto cit = begin; for (; cit != end; ++cit) { check_compatibility(*begin, *cit); const auto& node = mem::variant_cast<flat_node<C>>(**cit); for (const auto& arc : node) { const SDD<C> succ = arc.successor(); for (const auto& value : arc.valuation()) { const auto search = value_to_succ.find(value); if (search == value_to_succ.end()) { value_to_succ.emplace_hint(search, value, sum_builder_type({succ})); } else { search->second.add(succ); } } } } boost::container::flat_map<SDD<C>, values_type> succ_to_value; succ_to_value.reserve(value_to_succ.size()); for (auto& value_succs : value_to_succ) { const SDD<C> succ = sum(cxt, std::move(value_succs.second)); const auto search = succ_to_value.find(succ); if (search == succ_to_value.end()) { succ_to_value.emplace_hint(search, succ, values_type({value_succs.first})); } else { search->second.insert(value_succs.first); } } alpha_builder<C, values_type> alpha; alpha.reserve(succ_to_value.size()); for (auto& succ_values : succ_to_value) { alpha.add(std::move(succ_values.second), succ_values.first); } return SDD<C>(variable, std::move(alpha)); } }; /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Add an arc to the operands of the sum operation. /// /// This implementation is meant to be used as a policy by nary_builder which doesn't know how /// to add an arc. template <typename C, typename Valuation> struct LIBSDD_ATTRIBUTE_PACKED sum_builder_impl { void add(boost::container::flat_set<Valuation>& set, Valuation&& operand) { if (not operand.empty()) { set.insert(std::move(operand)); } } void add(boost::container::flat_set<Valuation>& set, const Valuation& operand) { if (not operand.empty()) { set.insert(operand); } } }; /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief The sum operation of a set of SDD. /// @related SDD template <typename C> inline SDD<C> sum(context<C>& cxt, sum_builder<C, SDD<C>>&& builder) { if (builder.empty()) { return zero<C>(); } else if (builder.size() == 1) { return *builder.begin(); } return cxt.sum_cache()(sum_op<C>(builder)); } /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief The sum operation of a set of values. /// @details A wrapper around the implementation of sum provided by Values. template <typename C, typename Values> inline Values sum(context<C>&, sum_builder<C, Values>&& builder) { if (builder.empty()) { return Values(); } else if (builder.size() == 1) { return *builder.begin(); } else { auto cit = builder.begin(); const auto end = builder.end(); Values result = *cit; for (++cit; cit != end; ++cit) { typename C::Values tmp = sum(result, *cit); using std::swap; swap(tmp, result); } return result; } } } // namespace dd /*------------------------------------------------------------------------------------------------*/ /// @brief Perform the union of two SDD. /// @related SDD template <typename C> inline SDD<C> operator+(const SDD<C>& lhs, const SDD<C>& rhs) { return dd::sum(global<C>().sdd_context, {lhs, rhs}); } /// @brief Perform the union of two SDD. /// @related SDD template <typename C> inline SDD<C>& operator+=(SDD<C>& lhs, const SDD<C>& rhs) { SDD<C> tmp = dd::sum(global<C>().sdd_context, {lhs, rhs}); using std::swap; swap(tmp, lhs); return lhs; } /// @brief Perform the union of an iterable container of SDD. /// @related SDD template <typename C, typename InputIterator> SDD<C> inline sum(InputIterator begin, InputIterator end) { dd::sum_builder<C, SDD<C>> builder; for (; begin != end; ++begin) { builder.add(*begin); } return dd::sum(global<C>().sdd_context, std::move(builder)); } /// @brief Perform the union of an initializer list of SDD. /// @related SDD template <typename C> SDD<C> inline sum(std::initializer_list<SDD<C>> operands) { return sum<C>(std::begin(operands), std::end(operands)); } /*------------------------------------------------------------------------------------------------*/ } // namespace sdd #endif // _SDD_DD_SUM_HH_ <|endoftext|>
<commit_before>/* CPP-Proxy-Ptr is licensed under MIT licence Author: StarBrilliant https://github.com/m13253 Copyright (c) 2015 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. */ #ifndef PROXY_PTR_H #define PROXY_PTR_H #include <memory> template<typename _Tp, typename Allocator = std::allocator<_Tp>> class proxy_ptr { public: typedef _Tp *pointer; typedef _Tp element_type; template<typename ...Args> explicit proxy_ptr(Args &&...args) : _alloc(Allocator()), _ptr(_alloc.allocate(1)) { try { _alloc.construct(_ptr, std::forward<Args>(args)...); } catch(...) { this->~proxy_ptr(); throw; } } proxy_ptr(const proxy_ptr &other) : _alloc(Allocator()), _ptr(_alloc.allocate(1)) { try { _alloc.construct(_ptr, *other._ptr); } catch(...) { this->~proxy_ptr(); throw; } } proxy_ptr(proxy_ptr &&other) = default; proxy_ptr(const element_type &value) : _alloc(Allocator()), _ptr(_alloc.allocate(1)) { try { _alloc.construct(_ptr, value); } catch(...) { this->~proxy_ptr(); throw; } } proxy_ptr(element_type &&value) : _alloc(Allocator()), _ptr(_alloc.allocate(1)) { try { _alloc.construct(_ptr, std::move(value)); } catch(...) { this->~proxy_ptr(); throw; } } ~proxy_ptr() { _alloc.destroy(_ptr); _ptr = nullptr; } proxy_ptr &operator=(const proxy_ptr &that) { *_ptr = *that._ptr; return *this; } proxy_ptr &operator=(proxy_ptr &&that) noexcept { std::swap(_ptr, that._ptr); return *this; } proxy_ptr &operator=(const element_type &value) { *_ptr = value; } proxy_ptr &operator=(element_type &&value) { *_ptr = std::move(value); } element_type &operator*() const noexcept { return _ptr; } pointer operator->() const noexcept { return _ptr; } explicit operator pointer() const noexcept { return _ptr; } pointer get() const noexcept { return _ptr; } void swap(proxy_ptr &that) noexcept { std::swap(_ptr, that._ptr); } void swap_payload(proxy_ptr &that) { std::swap(*_ptr, *that._ptr); } private: Allocator _alloc; pointer _ptr; }; #endif <commit_msg>Fix memory leak<commit_after>/* CPP-Proxy-Ptr is licensed under MIT licence Author: StarBrilliant https://github.com/m13253 Copyright (c) 2015 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. */ #ifndef PROXY_PTR_H #define PROXY_PTR_H #include <memory> template<typename _Tp, typename Allocator = std::allocator<_Tp>> class proxy_ptr { public: typedef _Tp *pointer; typedef _Tp element_type; template<typename ...Args> explicit proxy_ptr(Args &&...args) : _alloc(Allocator()), _ptr(_alloc.allocate(1)) { try { _alloc.construct(_ptr, std::forward<Args>(args)...); } catch(...) { this->~proxy_ptr(); throw; } } proxy_ptr(const proxy_ptr &other) : _alloc(Allocator()), _ptr(_alloc.allocate(1)) { try { _alloc.construct(_ptr, *other._ptr); } catch(...) { this->~proxy_ptr(); throw; } } proxy_ptr(proxy_ptr &&other) : _ptr(other._ptr) { other._ptr = nullptr; } proxy_ptr(const element_type &value) : _alloc(Allocator()), _ptr(_alloc.allocate(1)) { try { _alloc.construct(_ptr, value); } catch(...) { this->~proxy_ptr(); throw; } } proxy_ptr(element_type &&value) : _alloc(Allocator()), _ptr(_alloc.allocate(1)) { try { _alloc.construct(_ptr, std::move(value)); } catch(...) { this->~proxy_ptr(); throw; } } ~proxy_ptr() { if(_ptr) { _alloc.destroy(_ptr); _alloc.deallocate(_ptr, 1); _ptr = nullptr; } } proxy_ptr &operator=(const proxy_ptr &that) { *_ptr = *that._ptr; return *this; } proxy_ptr &operator=(proxy_ptr &&that) noexcept { std::swap(_ptr, that._ptr); return *this; } proxy_ptr &operator=(const element_type &value) { *_ptr = value; } proxy_ptr &operator=(element_type &&value) { *_ptr = std::move(value); } element_type &operator*() const noexcept { return _ptr; } pointer operator->() const noexcept { return _ptr; } explicit operator pointer() const noexcept { return _ptr; } pointer get() const noexcept { return _ptr; } void swap(proxy_ptr &that) noexcept { std::swap(_ptr, that._ptr); } void swap_payload(proxy_ptr &that) { std::swap(*_ptr, *that._ptr); } private: Allocator _alloc; pointer _ptr; }; #endif <|endoftext|>
<commit_before>#pragma once #include <rai/node/node.hpp> #include <boost/thread.hpp> #include <set> #include <QtGui> #include <QtWidgets> namespace rai_qt { class wallet; class eventloop_processor : public QObject { public: bool event (QEvent *) override; }; class eventloop_event : public QEvent { public: eventloop_event (std::function <void ()> const &); std::function <void ()> action; }; class settings { public: settings (rai_qt::wallet &); void activate (); void update_locked (bool, bool); QWidget * window; QVBoxLayout * layout; QLineEdit * password; QWidget * lock_window; QHBoxLayout * lock_layout; QPushButton * unlock; QPushButton * lock; QFrame * sep1; QLineEdit * new_password; QLineEdit * retype_password; QPushButton * change; QFrame * sep2; QLabel * representative; QLineEdit * new_representative; QPushButton * change_rep; QPushButton * back; rai_qt::wallet & wallet; }; class advanced_actions { public: advanced_actions (rai_qt::wallet &); void refresh_count (); QLabel * block_count_text; QLabel * block_count; QWidget * window; QVBoxLayout * layout; QPushButton * accounts; QPushButton * show_ledger; QPushButton * show_peers; QPushButton * search_for_receivables; QPushButton * wallet_refresh; QPushButton * create_block; QPushButton * enter_block; QPushButton * block_viewer; QPushButton * account_viewer; QPushButton * back; QWidget * ledger_window; QVBoxLayout * ledger_layout; QStandardItemModel * ledger_model; QTableView * ledger_view; QPushButton * ledger_refresh; QPushButton * ledger_back; QWidget * peers_window; QVBoxLayout * peers_layout; QStringListModel * peers_model; QListView * peers_view; QLabel * bootstrap_label; QLineEdit * bootstrap_line; QPushButton * peers_bootstrap; QPushButton * peers_refresh; QPushButton * peers_back; rai_qt::wallet & wallet; private: void refresh_ledger (); void refresh_peers (); }; class block_entry { public: block_entry (rai_qt::wallet &); QWidget * window; QVBoxLayout * layout; QPlainTextEdit * block; QLabel * status; QPushButton * process; QPushButton * back; rai_qt::wallet & wallet; }; class block_creation { public: block_creation (rai_qt::wallet &); void deactivate_all (); void activate_send (); void activate_receive (); void activate_change (); void activate_open (); void create_send (); void create_receive (); void create_change (); void create_open (); QWidget * window; QVBoxLayout * layout; QButtonGroup * group; QHBoxLayout * button_layout; QRadioButton * send; QRadioButton * receive; QRadioButton * change; QRadioButton * open; QLabel * account_label; QLineEdit * account; QLabel * source_label; QLineEdit * source; QLabel * amount_label; QLineEdit * amount; QLabel * destination_label; QLineEdit * destination; QLabel * representative_label; QLineEdit * representative; QPlainTextEdit * block; QLabel * status; QPushButton * create; QPushButton * back; rai_qt::wallet & wallet; }; class self_pane { public: self_pane (rai_qt::wallet &, rai::account const &); void refresh_balance (); QWidget * window; QVBoxLayout * layout; QHBoxLayout * self_layout; QWidget * self_window; QLabel * your_account_label; QLabel * version; QWidget * account_window; QHBoxLayout * account_layout; QLabel * account_text; QPushButton * copy_button; QWidget * balance_window; QHBoxLayout * balance_layout; QLabel * balance_label; QButtonGroup * ratio_group; QRadioButton * mrai; QRadioButton * krai; QRadioButton * rai; rai_qt::wallet & wallet; }; class accounts { public: accounts (rai_qt::wallet &); void refresh (); QWidget * window; QVBoxLayout * layout; QStandardItemModel * model; QTableView * view; QPushButton * use_account; QPushButton * create_account; QPushButton * import_wallet; QPushButton * backup_seed; QFrame * separator; QLineEdit * account_key_line; QPushButton * account_key_button; QPushButton * back; rai_qt::wallet & wallet; }; class import { public: import (rai_qt::wallet &); QWidget * window; QVBoxLayout * layout; QLabel * seed_label; QLineEdit * seed; QLabel * clear_label; QLineEdit * clear_line; QPushButton * import_seed; QFrame * separator; QLabel * filename_label; QLineEdit * filename; QLabel * password_label; QLineEdit * password; QPushButton * perform; QPushButton * back; rai_qt::wallet & wallet; }; class history { public: history (rai::ledger &, rai::account const &, rai::uint128_t const &); void refresh (); QWidget * window; QVBoxLayout * layout; QStandardItemModel * model; QTableView * view; QWidget * tx_window; QHBoxLayout * tx_layout; QLabel * tx_label; QSpinBox * tx_count; rai::ledger & ledger; rai::account const & account; rai::uint128_t const & rendering_ratio; }; class block_viewer { public: block_viewer (rai_qt::wallet &); void rebroadcast_action (rai::uint256_union const &); QWidget * window; QVBoxLayout * layout; QLabel * hash_label; QLineEdit * hash; QLabel * block_label; QPlainTextEdit * block; QLabel * successor_label; QLineEdit * successor; QPushButton * retrieve; QPushButton * rebroadcast; QPushButton * back; rai_qt::wallet & wallet; }; class account_viewer { public: account_viewer (rai_qt::wallet &); QWidget * window; QVBoxLayout * layout; QLabel * account_label; QLineEdit * account_line; QPushButton * refresh; rai_qt::history history; QPushButton * back; rai::account account; rai_qt::wallet & wallet; }; enum class status_types { not_a_status, disconnected, working, synchronizing, locked, vulnerable, active, nominal }; class status { public: status (rai_qt::wallet &); void erase (rai_qt::status_types); void insert (rai_qt::status_types); void set_text (); std::string text (); std::string color (); std::set <rai_qt::status_types> active; rai_qt::wallet & wallet; }; class wallet : public std::enable_shared_from_this <rai_qt::wallet> { public: wallet (QApplication &, rai::node &, std::shared_ptr <rai::wallet>, rai::account &); void start (); void refresh (); void update_connected (); void change_rendering_ratio (rai::uint128_t const &); rai::uint128_t rendering_ratio; rai::node & node; std::shared_ptr <rai::wallet> wallet_m; rai::account & account; rai_qt::eventloop_processor processor; rai_qt::history history; rai_qt::accounts accounts; rai_qt::self_pane self; rai_qt::settings settings; rai_qt::advanced_actions advanced; rai_qt::block_creation block_creation; rai_qt::block_entry block_entry; rai_qt::block_viewer block_viewer; rai_qt::account_viewer account_viewer; rai_qt::import import; QApplication & application; QLabel * status; QStackedWidget * main_stack; QWidget * client_window; QVBoxLayout * client_layout; QWidget * entry_window; QVBoxLayout * entry_window_layout; QFrame * separator; QLabel * account_history_label; QPushButton * send_blocks; QPushButton * settings_button; QPushButton * show_advanced; QWidget * send_blocks_window; QVBoxLayout * send_blocks_layout; QLabel * send_account_label; QLineEdit * send_account; QLabel * send_count_label; QLineEdit * send_count; QPushButton * send_blocks_send; QPushButton * send_blocks_back; rai_qt::status active_status; void pop_main_stack (); void push_main_stack (QWidget *); }; } <commit_msg>Putting locked above synchronizing in status priority.<commit_after>#pragma once #include <rai/node/node.hpp> #include <boost/thread.hpp> #include <set> #include <QtGui> #include <QtWidgets> namespace rai_qt { class wallet; class eventloop_processor : public QObject { public: bool event (QEvent *) override; }; class eventloop_event : public QEvent { public: eventloop_event (std::function <void ()> const &); std::function <void ()> action; }; class settings { public: settings (rai_qt::wallet &); void activate (); void update_locked (bool, bool); QWidget * window; QVBoxLayout * layout; QLineEdit * password; QWidget * lock_window; QHBoxLayout * lock_layout; QPushButton * unlock; QPushButton * lock; QFrame * sep1; QLineEdit * new_password; QLineEdit * retype_password; QPushButton * change; QFrame * sep2; QLabel * representative; QLineEdit * new_representative; QPushButton * change_rep; QPushButton * back; rai_qt::wallet & wallet; }; class advanced_actions { public: advanced_actions (rai_qt::wallet &); void refresh_count (); QLabel * block_count_text; QLabel * block_count; QWidget * window; QVBoxLayout * layout; QPushButton * accounts; QPushButton * show_ledger; QPushButton * show_peers; QPushButton * search_for_receivables; QPushButton * wallet_refresh; QPushButton * create_block; QPushButton * enter_block; QPushButton * block_viewer; QPushButton * account_viewer; QPushButton * back; QWidget * ledger_window; QVBoxLayout * ledger_layout; QStandardItemModel * ledger_model; QTableView * ledger_view; QPushButton * ledger_refresh; QPushButton * ledger_back; QWidget * peers_window; QVBoxLayout * peers_layout; QStringListModel * peers_model; QListView * peers_view; QLabel * bootstrap_label; QLineEdit * bootstrap_line; QPushButton * peers_bootstrap; QPushButton * peers_refresh; QPushButton * peers_back; rai_qt::wallet & wallet; private: void refresh_ledger (); void refresh_peers (); }; class block_entry { public: block_entry (rai_qt::wallet &); QWidget * window; QVBoxLayout * layout; QPlainTextEdit * block; QLabel * status; QPushButton * process; QPushButton * back; rai_qt::wallet & wallet; }; class block_creation { public: block_creation (rai_qt::wallet &); void deactivate_all (); void activate_send (); void activate_receive (); void activate_change (); void activate_open (); void create_send (); void create_receive (); void create_change (); void create_open (); QWidget * window; QVBoxLayout * layout; QButtonGroup * group; QHBoxLayout * button_layout; QRadioButton * send; QRadioButton * receive; QRadioButton * change; QRadioButton * open; QLabel * account_label; QLineEdit * account; QLabel * source_label; QLineEdit * source; QLabel * amount_label; QLineEdit * amount; QLabel * destination_label; QLineEdit * destination; QLabel * representative_label; QLineEdit * representative; QPlainTextEdit * block; QLabel * status; QPushButton * create; QPushButton * back; rai_qt::wallet & wallet; }; class self_pane { public: self_pane (rai_qt::wallet &, rai::account const &); void refresh_balance (); QWidget * window; QVBoxLayout * layout; QHBoxLayout * self_layout; QWidget * self_window; QLabel * your_account_label; QLabel * version; QWidget * account_window; QHBoxLayout * account_layout; QLabel * account_text; QPushButton * copy_button; QWidget * balance_window; QHBoxLayout * balance_layout; QLabel * balance_label; QButtonGroup * ratio_group; QRadioButton * mrai; QRadioButton * krai; QRadioButton * rai; rai_qt::wallet & wallet; }; class accounts { public: accounts (rai_qt::wallet &); void refresh (); QWidget * window; QVBoxLayout * layout; QStandardItemModel * model; QTableView * view; QPushButton * use_account; QPushButton * create_account; QPushButton * import_wallet; QPushButton * backup_seed; QFrame * separator; QLineEdit * account_key_line; QPushButton * account_key_button; QPushButton * back; rai_qt::wallet & wallet; }; class import { public: import (rai_qt::wallet &); QWidget * window; QVBoxLayout * layout; QLabel * seed_label; QLineEdit * seed; QLabel * clear_label; QLineEdit * clear_line; QPushButton * import_seed; QFrame * separator; QLabel * filename_label; QLineEdit * filename; QLabel * password_label; QLineEdit * password; QPushButton * perform; QPushButton * back; rai_qt::wallet & wallet; }; class history { public: history (rai::ledger &, rai::account const &, rai::uint128_t const &); void refresh (); QWidget * window; QVBoxLayout * layout; QStandardItemModel * model; QTableView * view; QWidget * tx_window; QHBoxLayout * tx_layout; QLabel * tx_label; QSpinBox * tx_count; rai::ledger & ledger; rai::account const & account; rai::uint128_t const & rendering_ratio; }; class block_viewer { public: block_viewer (rai_qt::wallet &); void rebroadcast_action (rai::uint256_union const &); QWidget * window; QVBoxLayout * layout; QLabel * hash_label; QLineEdit * hash; QLabel * block_label; QPlainTextEdit * block; QLabel * successor_label; QLineEdit * successor; QPushButton * retrieve; QPushButton * rebroadcast; QPushButton * back; rai_qt::wallet & wallet; }; class account_viewer { public: account_viewer (rai_qt::wallet &); QWidget * window; QVBoxLayout * layout; QLabel * account_label; QLineEdit * account_line; QPushButton * refresh; rai_qt::history history; QPushButton * back; rai::account account; rai_qt::wallet & wallet; }; enum class status_types { not_a_status, disconnected, working, locked, synchronizing, vulnerable, active, nominal }; class status { public: status (rai_qt::wallet &); void erase (rai_qt::status_types); void insert (rai_qt::status_types); void set_text (); std::string text (); std::string color (); std::set <rai_qt::status_types> active; rai_qt::wallet & wallet; }; class wallet : public std::enable_shared_from_this <rai_qt::wallet> { public: wallet (QApplication &, rai::node &, std::shared_ptr <rai::wallet>, rai::account &); void start (); void refresh (); void update_connected (); void change_rendering_ratio (rai::uint128_t const &); rai::uint128_t rendering_ratio; rai::node & node; std::shared_ptr <rai::wallet> wallet_m; rai::account & account; rai_qt::eventloop_processor processor; rai_qt::history history; rai_qt::accounts accounts; rai_qt::self_pane self; rai_qt::settings settings; rai_qt::advanced_actions advanced; rai_qt::block_creation block_creation; rai_qt::block_entry block_entry; rai_qt::block_viewer block_viewer; rai_qt::account_viewer account_viewer; rai_qt::import import; QApplication & application; QLabel * status; QStackedWidget * main_stack; QWidget * client_window; QVBoxLayout * client_layout; QWidget * entry_window; QVBoxLayout * entry_window_layout; QFrame * separator; QLabel * account_history_label; QPushButton * send_blocks; QPushButton * settings_button; QPushButton * show_advanced; QWidget * send_blocks_window; QVBoxLayout * send_blocks_layout; QLabel * send_account_label; QLineEdit * send_account; QLabel * send_count_label; QLineEdit * send_count; QPushButton * send_blocks_send; QPushButton * send_blocks_back; rai_qt::status active_status; void pop_main_stack (); void push_main_stack (QWidget *); }; } <|endoftext|>
<commit_before>/* * Copyright 2015 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/wangle/concurrent/IOThreadPoolExecutor.h> #include <folly/MoveWrapper.h> #include <glog/logging.h> #include <folly/detail/MemoryIdler.h> namespace folly { namespace wangle { using folly::detail::MemoryIdler; /* Class that will free jemalloc caches and madvise the stack away * if the event loop is unused for some period of time */ class MemoryIdlerTimeout : public AsyncTimeout , public EventBase::LoopCallback { public: explicit MemoryIdlerTimeout(EventBase* b) : AsyncTimeout(b), base_(b) {} virtual void timeoutExpired() noexcept { idled = true; } virtual void runLoopCallback() noexcept { if (idled) { MemoryIdler::flushLocalMallocCaches(); MemoryIdler::unmapUnusedStack(MemoryIdler::kDefaultStackToRetain); idled = false; } else { std::chrono::steady_clock::duration idleTimeout = MemoryIdler::defaultIdleTimeout.load( std::memory_order_acquire); idleTimeout = MemoryIdler::getVariationTimeout(idleTimeout); scheduleTimeout(std::chrono::duration_cast<std::chrono::milliseconds>( idleTimeout).count()); } // reschedule this callback for the next event loop. base_->runBeforeLoop(this); } private: EventBase* base_; bool idled{false}; } ; IOThreadPoolExecutor::IOThreadPoolExecutor( size_t numThreads, std::shared_ptr<ThreadFactory> threadFactory, EventBaseManager* ebm) : ThreadPoolExecutor(numThreads, std::move(threadFactory)), nextThread_(0), eventBaseManager_(ebm) { addThreads(numThreads); CHECK(threadList_.get().size() == numThreads); } IOThreadPoolExecutor::~IOThreadPoolExecutor() { stop(); } void IOThreadPoolExecutor::add(Func func) { add(std::move(func), std::chrono::milliseconds(0)); } void IOThreadPoolExecutor::add( Func func, std::chrono::milliseconds expiration, Func expireCallback) { RWSpinLock::ReadHolder{&threadListLock_}; if (threadList_.get().empty()) { throw std::runtime_error("No threads available"); } auto ioThread = pickThread(); auto moveTask = folly::makeMoveWrapper( Task(std::move(func), expiration, std::move(expireCallback))); auto wrappedFunc = [ioThread, moveTask] () mutable { runTask(ioThread, std::move(*moveTask)); ioThread->pendingTasks--; }; ioThread->pendingTasks++; if (!ioThread->eventBase->runInEventBaseThread(std::move(wrappedFunc))) { ioThread->pendingTasks--; throw std::runtime_error("Unable to run func in event base thread"); } } std::shared_ptr<IOThreadPoolExecutor::IOThread> IOThreadPoolExecutor::pickThread() { if (*thisThread_) { return *thisThread_; } auto thread = threadList_.get()[nextThread_++ % threadList_.get().size()]; return std::static_pointer_cast<IOThread>(thread); } EventBase* IOThreadPoolExecutor::getEventBase() { return pickThread()->eventBase; } EventBase* IOThreadPoolExecutor::getEventBase( ThreadPoolExecutor::ThreadHandle* h) { auto thread = dynamic_cast<IOThread*>(h); if (thread) { return thread->eventBase; } return nullptr; } EventBaseManager* IOThreadPoolExecutor::getEventBaseManager() { return eventBaseManager_; } std::shared_ptr<ThreadPoolExecutor::Thread> IOThreadPoolExecutor::makeThread() { return std::make_shared<IOThread>(this); } void IOThreadPoolExecutor::threadRun(ThreadPtr thread) { const auto ioThread = std::static_pointer_cast<IOThread>(thread); ioThread->eventBase = eventBaseManager_->getEventBase(); thisThread_.reset(new std::shared_ptr<IOThread>(ioThread)); auto idler = new MemoryIdlerTimeout(ioThread->eventBase); ioThread->eventBase->runBeforeLoop(idler); thread->startupBaton.post(); while (ioThread->shouldRun) { ioThread->eventBase->loopForever(); } if (isJoin_) { while (ioThread->pendingTasks > 0) { ioThread->eventBase->loopOnce(); } } stoppedThreads_.add(ioThread); } // threadListLock_ is writelocked void IOThreadPoolExecutor::stopThreads(size_t n) { for (size_t i = 0; i < n; i++) { const auto ioThread = std::static_pointer_cast<IOThread>( threadList_.get()[i]); for (auto& o : observers_) { o->threadStopped(ioThread.get()); } ioThread->shouldRun = false; ioThread->eventBase->terminateLoopSoon(); } } // threadListLock_ is readlocked uint64_t IOThreadPoolExecutor::getPendingTaskCount() { uint64_t count = 0; for (const auto& thread : threadList_.get()) { auto ioThread = std::static_pointer_cast<IOThread>(thread); size_t pendingTasks = ioThread->pendingTasks; if (pendingTasks > 0 && !ioThread->idle) { pendingTasks--; } count += pendingTasks; } return count; } }} // folly::wangle <commit_msg>Fix haystack threading crashes<commit_after>/* * Copyright 2015 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/wangle/concurrent/IOThreadPoolExecutor.h> #include <folly/MoveWrapper.h> #include <glog/logging.h> #include <folly/detail/MemoryIdler.h> namespace folly { namespace wangle { using folly::detail::MemoryIdler; /* Class that will free jemalloc caches and madvise the stack away * if the event loop is unused for some period of time */ class MemoryIdlerTimeout : public AsyncTimeout , public EventBase::LoopCallback { public: explicit MemoryIdlerTimeout(EventBase* b) : AsyncTimeout(b), base_(b) {} virtual void timeoutExpired() noexcept { idled = true; } virtual void runLoopCallback() noexcept { if (idled) { MemoryIdler::flushLocalMallocCaches(); MemoryIdler::unmapUnusedStack(MemoryIdler::kDefaultStackToRetain); idled = false; } else { std::chrono::steady_clock::duration idleTimeout = MemoryIdler::defaultIdleTimeout.load( std::memory_order_acquire); idleTimeout = MemoryIdler::getVariationTimeout(idleTimeout); scheduleTimeout(std::chrono::duration_cast<std::chrono::milliseconds>( idleTimeout).count()); } // reschedule this callback for the next event loop. base_->runBeforeLoop(this); } private: EventBase* base_; bool idled{false}; } ; IOThreadPoolExecutor::IOThreadPoolExecutor( size_t numThreads, std::shared_ptr<ThreadFactory> threadFactory, EventBaseManager* ebm) : ThreadPoolExecutor(numThreads, std::move(threadFactory)), nextThread_(0), eventBaseManager_(ebm) { addThreads(numThreads); CHECK(threadList_.get().size() == numThreads); } IOThreadPoolExecutor::~IOThreadPoolExecutor() { stop(); } void IOThreadPoolExecutor::add(Func func) { add(std::move(func), std::chrono::milliseconds(0)); } void IOThreadPoolExecutor::add( Func func, std::chrono::milliseconds expiration, Func expireCallback) { RWSpinLock::ReadHolder{&threadListLock_}; if (threadList_.get().empty()) { throw std::runtime_error("No threads available"); } auto ioThread = pickThread(); auto moveTask = folly::makeMoveWrapper( Task(std::move(func), expiration, std::move(expireCallback))); auto wrappedFunc = [ioThread, moveTask] () mutable { runTask(ioThread, std::move(*moveTask)); ioThread->pendingTasks--; }; ioThread->pendingTasks++; if (!ioThread->eventBase->runInEventBaseThread(std::move(wrappedFunc))) { ioThread->pendingTasks--; throw std::runtime_error("Unable to run func in event base thread"); } } std::shared_ptr<IOThreadPoolExecutor::IOThread> IOThreadPoolExecutor::pickThread() { if (*thisThread_) { return *thisThread_; } auto thread = threadList_.get()[nextThread_++ % threadList_.get().size()]; return std::static_pointer_cast<IOThread>(thread); } EventBase* IOThreadPoolExecutor::getEventBase() { return pickThread()->eventBase; } EventBase* IOThreadPoolExecutor::getEventBase( ThreadPoolExecutor::ThreadHandle* h) { auto thread = dynamic_cast<IOThread*>(h); if (thread) { return thread->eventBase; } return nullptr; } EventBaseManager* IOThreadPoolExecutor::getEventBaseManager() { return eventBaseManager_; } std::shared_ptr<ThreadPoolExecutor::Thread> IOThreadPoolExecutor::makeThread() { return std::make_shared<IOThread>(this); } void IOThreadPoolExecutor::threadRun(ThreadPtr thread) { const auto ioThread = std::static_pointer_cast<IOThread>(thread); ioThread->eventBase = eventBaseManager_->getEventBase(); thisThread_.reset(new std::shared_ptr<IOThread>(ioThread)); auto idler = new MemoryIdlerTimeout(ioThread->eventBase); ioThread->eventBase->runBeforeLoop(idler); thread->startupBaton.post(); while (ioThread->shouldRun) { ioThread->eventBase->loopForever(); } if (isJoin_) { while (ioThread->pendingTasks > 0) { ioThread->eventBase->loopOnce(); } } stoppedThreads_.add(ioThread); ioThread->eventBase = nullptr; eventBaseManager_->clearEventBase(); } // threadListLock_ is writelocked void IOThreadPoolExecutor::stopThreads(size_t n) { for (size_t i = 0; i < n; i++) { const auto ioThread = std::static_pointer_cast<IOThread>( threadList_.get()[i]); for (auto& o : observers_) { o->threadStopped(ioThread.get()); } ioThread->shouldRun = false; ioThread->eventBase->terminateLoopSoon(); } } // threadListLock_ is readlocked uint64_t IOThreadPoolExecutor::getPendingTaskCount() { uint64_t count = 0; for (const auto& thread : threadList_.get()) { auto ioThread = std::static_pointer_cast<IOThread>(thread); size_t pendingTasks = ioThread->pendingTasks; if (pendingTasks > 0 && !ioThread->idle) { pendingTasks--; } count += pendingTasks; } return count; } }} // folly::wangle <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: propertysetcontainer.cxx,v $ * * $Revision: 1.1 $ * * last change: $Author: cd $ $Date: 2001-12-04 07:45:19 $ * * 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 __FRAMEWORK_HELPER_PROPERTYSETCONTAINER_HXX_ #include <helper/propertysetcontainer.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_ #include <threadhelp/resetableguard.hxx> #endif #include <vcl/svapp.hxx> #define WRONG_TYPE_EXCEPTION "Only XPropertSet allowed!" using namespace rtl; using namespace vos; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::container; using namespace com::sun::star::lang; using namespace com::sun::star::beans; namespace framework { PropertySetContainer::PropertySetContainer( const Reference< XMultiServiceFactory >& rServiceManager ) : ThreadHelpBase( &Application::GetSolarMutex() ) , OWeakObject() { } PropertySetContainer::~PropertySetContainer() { } // XInterface void SAL_CALL PropertySetContainer::acquire() throw () { OWeakObject::acquire(); } void SAL_CALL PropertySetContainer::release() throw () { OWeakObject::release(); } Any SAL_CALL PropertySetContainer::queryInterface( const Type& rType ) throw ( RuntimeException ) { Any a = ::cppu::queryInterface( rType , SAL_STATIC_CAST( XIndexContainer*, this ), SAL_STATIC_CAST( XIndexReplace*, this ), SAL_STATIC_CAST( XIndexAccess*, this ), SAL_STATIC_CAST( XElementAccess*, this ) ); if( a.hasValue() ) { return a; } return OWeakObject::queryInterface( rType ); } // XIndexContainer void SAL_CALL PropertySetContainer::insertByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element ) throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); sal_Int32 nSize = m_aPropertySetVector.size(); if ( nSize >= Index ) { Reference< XPropertySet > aPropertySetElement; if ( Element >>= aPropertySetElement ) { if ( nSize == Index ) m_aPropertySetVector.push_back( aPropertySetElement ); else { PropertySetVector::iterator aIter = m_aPropertySetVector.begin(); aIter += Index; m_aPropertySetVector.insert( aIter, aPropertySetElement ); } } else { throw IllegalArgumentException( OUString( RTL_CONSTASCII_USTRINGPARAM( WRONG_TYPE_EXCEPTION )), (OWeakObject *)this, 2 ); } } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } void SAL_CALL PropertySetContainer::removeByIndex( sal_Int32 Index ) throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( (sal_Int32)m_aPropertySetVector.size() > Index ) { PropertySetVector::iterator aIter = m_aPropertySetVector.begin(); aIter += Index; m_aPropertySetVector.erase( aIter ); } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } // XIndexReplace void SAL_CALL PropertySetContainer::replaceByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element ) throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException) { if ( (sal_Int32)m_aPropertySetVector.size() > Index ) { Reference< XPropertySet > aPropertySetElement; if ( Element >>= aPropertySetElement ) { m_aPropertySetVector[ Index ] = aPropertySetElement; } else { throw IllegalArgumentException( OUString( RTL_CONSTASCII_USTRINGPARAM( WRONG_TYPE_EXCEPTION )), (OWeakObject *)this, 2 ); } } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } // XIndexAccess sal_Int32 SAL_CALL PropertySetContainer::getCount() throw ( RuntimeException ) { ResetableGuard aGuard( m_aLock ); return m_aPropertySetVector.size(); } Any SAL_CALL PropertySetContainer::getByIndex( sal_Int32 Index ) throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( (sal_Int32)m_aPropertySetVector.size() > Index ) { Any a; a <<= m_aPropertySetVector[ Index ]; return a; } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } // XElementAccess sal_Bool SAL_CALL PropertySetContainer::hasElements() throw (::com::sun::star::uno::RuntimeException) { ResetableGuard aGuard( m_aLock ); return !( m_aPropertySetVector.empty() ); } } <commit_msg>INTEGRATION: CWS ooo19126 (1.1.572); FILE MERGED 2005/09/05 13:06:24 rt 1.1.572.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertysetcontainer.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:26:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __FRAMEWORK_HELPER_PROPERTYSETCONTAINER_HXX_ #include <helper/propertysetcontainer.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_ #include <threadhelp/resetableguard.hxx> #endif #include <vcl/svapp.hxx> #define WRONG_TYPE_EXCEPTION "Only XPropertSet allowed!" using namespace rtl; using namespace vos; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::container; using namespace com::sun::star::lang; using namespace com::sun::star::beans; namespace framework { PropertySetContainer::PropertySetContainer( const Reference< XMultiServiceFactory >& rServiceManager ) : ThreadHelpBase( &Application::GetSolarMutex() ) , OWeakObject() { } PropertySetContainer::~PropertySetContainer() { } // XInterface void SAL_CALL PropertySetContainer::acquire() throw () { OWeakObject::acquire(); } void SAL_CALL PropertySetContainer::release() throw () { OWeakObject::release(); } Any SAL_CALL PropertySetContainer::queryInterface( const Type& rType ) throw ( RuntimeException ) { Any a = ::cppu::queryInterface( rType , SAL_STATIC_CAST( XIndexContainer*, this ), SAL_STATIC_CAST( XIndexReplace*, this ), SAL_STATIC_CAST( XIndexAccess*, this ), SAL_STATIC_CAST( XElementAccess*, this ) ); if( a.hasValue() ) { return a; } return OWeakObject::queryInterface( rType ); } // XIndexContainer void SAL_CALL PropertySetContainer::insertByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element ) throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); sal_Int32 nSize = m_aPropertySetVector.size(); if ( nSize >= Index ) { Reference< XPropertySet > aPropertySetElement; if ( Element >>= aPropertySetElement ) { if ( nSize == Index ) m_aPropertySetVector.push_back( aPropertySetElement ); else { PropertySetVector::iterator aIter = m_aPropertySetVector.begin(); aIter += Index; m_aPropertySetVector.insert( aIter, aPropertySetElement ); } } else { throw IllegalArgumentException( OUString( RTL_CONSTASCII_USTRINGPARAM( WRONG_TYPE_EXCEPTION )), (OWeakObject *)this, 2 ); } } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } void SAL_CALL PropertySetContainer::removeByIndex( sal_Int32 Index ) throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( (sal_Int32)m_aPropertySetVector.size() > Index ) { PropertySetVector::iterator aIter = m_aPropertySetVector.begin(); aIter += Index; m_aPropertySetVector.erase( aIter ); } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } // XIndexReplace void SAL_CALL PropertySetContainer::replaceByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element ) throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException) { if ( (sal_Int32)m_aPropertySetVector.size() > Index ) { Reference< XPropertySet > aPropertySetElement; if ( Element >>= aPropertySetElement ) { m_aPropertySetVector[ Index ] = aPropertySetElement; } else { throw IllegalArgumentException( OUString( RTL_CONSTASCII_USTRINGPARAM( WRONG_TYPE_EXCEPTION )), (OWeakObject *)this, 2 ); } } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } // XIndexAccess sal_Int32 SAL_CALL PropertySetContainer::getCount() throw ( RuntimeException ) { ResetableGuard aGuard( m_aLock ); return m_aPropertySetVector.size(); } Any SAL_CALL PropertySetContainer::getByIndex( sal_Int32 Index ) throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( (sal_Int32)m_aPropertySetVector.size() > Index ) { Any a; a <<= m_aPropertySetVector[ Index ]; return a; } else throw IndexOutOfBoundsException( OUString(), (OWeakObject *)this ); } // XElementAccess sal_Bool SAL_CALL PropertySetContainer::hasElements() throw (::com::sun::star::uno::RuntimeException) { ResetableGuard aGuard( m_aLock ); return !( m_aPropertySetVector.empty() ); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2010 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "serverimpl.h" #include "worker.h" #include <cxxtools/eventloop.h> #include <cxxtools/log.h> #include "listener.h" log_define("cxxtools.http.server.impl") namespace cxxtools { namespace http { ServerImpl::ServerImpl(EventLoopBase& eventLoop, Signal<Server::Runmode>& runmodeChanged) : _eventLoop(eventLoop), _readTimeout(20000), _writeTimeout(20000), _keepAliveTimeout(30000), _idleTimeout(100), _minThreads(5), _maxThreads(200), _waitingThreads(0), _runmodeChanged(runmodeChanged), _runmode(Server::Stopped) { _eventLoop.event.subscribe(slot(*this, &ServerImpl::onIdleSocket)); _eventLoop.event.subscribe(slot(*this, &ServerImpl::onKeepAliveTimeout)); _eventLoop.event.subscribe(slot(*this, &ServerImpl::onNoWaitingThreads)); _eventLoop.event.subscribe(slot(*this, &ServerImpl::onThreadTerminated)); _eventLoop.event.subscribe(slot(*this, &ServerImpl::onServerStart)); connect(_eventLoop.exited, *this, &ServerImpl::terminate); _eventLoop.commitEvent(ServerStartEvent(this)); } ServerImpl::~ServerImpl() { if (_runmode == Server::Running) { try { terminate(); } catch (const std::exception& e) { log_fatal("exception in http-server termination occured: " << e.what()); } } } void ServerImpl::listen(const std::string& ip, unsigned short int port) { log_debug("listen on " << ip << " port " << port); Listener* listener = new Listener(ip, port); try { _listener.push_back(listener); _queue.put(new Socket(*this, *listener)); } catch (...) { delete listener; throw; } } void ServerImpl::start() { log_trace("start server"); runmode(Server::Starting); MutexLock lock(_threadMutex); while (_threads.size() < _minThreads) { Worker* worker = new Worker(*this); _threads.insert(worker); worker->start(); } runmode(Server::Running); } void ServerImpl::terminate() { log_trace("terminate"); MutexLock lock(_threadMutex); runmode(Server::Terminating); try { log_debug("wake " << _listener.size() << " listeners"); for (ServerImpl::ListenerType::iterator it = _listener.begin(); it != _listener.end(); ++it) (*it)->wakeConnect(); log_debug("terminate " << _threads.size() << " threads"); while (!_threads.empty() || !_terminatedThreads.empty()) { if (!_threads.empty()) { log_debug("wait for terminated thread"); _threadTerminated.wait(lock); } for (Threads::iterator it = _terminatedThreads.begin(); it != _terminatedThreads.end(); ++it) { log_debug("join thread"); (*it)->join(); delete *it; } _terminatedThreads.clear(); } log_debug("delete " << _listener.size() << " listeners"); for (ServerImpl::ListenerType::iterator it = _listener.begin(); it != _listener.end(); ++it) delete *it; _listener.clear(); while (!_queue.empty()) delete _queue.get(); runmode(Server::Stopped); } catch (const std::exception& e) { runmode(Server::Failed); } } void ServerImpl::noWaitingThreads() { if (_runmode == Server::Running) _eventLoop.commitEvent(NoWaitingThreadsEvent()); } void ServerImpl::threadTerminated(Worker* worker) { log_info("thread " << static_cast<void*>(worker) << " terminated"); MutexLock lock(_threadMutex); _threads.erase(worker); if (_runmode == Server::Running) { _eventLoop.commitEvent(ThreadTerminatedEvent(worker)); } else { _terminatedThreads.insert(worker); _threadTerminated.signal(); } } void ServerImpl::addIdleSocket(Socket* _socket) { log_debug("add idle socket " << static_cast<void*>(_socket)); _eventLoop.commitEvent(IdleSocketEvent(_socket)); } void ServerImpl::onIdleSocket(const IdleSocketEvent& event) { Socket* socket = event.socket(); log_debug("add idle socket " << static_cast<void*>(socket) << " to selector"); _idleSockets.insert(socket); socket->setSelector(&_eventLoop); connect(socket->inputReady, *this, &ServerImpl::onInput); connect(socket->timeout, *this, &ServerImpl::onTimeout); } void ServerImpl::onNoWaitingThreads(const NoWaitingThreadsEvent& event) { MutexLock lock(_threadMutex); if (_threads.size() >= maxThreads()) { log_warn("thread limit " << maxThreads() << " reached"); return; } try { Worker* worker = new Worker(*this); try { log_info("create thread " << static_cast<void*>(worker)); worker->start(); _threads.insert(worker); log_debug(_threads.size() << " threads running"); } catch (const std::exception&) { delete worker; throw; } } catch (const std::exception& e) { log_warn("failed to create thread: " << e.what()); } } void ServerImpl::onThreadTerminated(const ThreadTerminatedEvent& event) { MutexLock lock(_threadMutex); log_trace("thread terminated (" << static_cast<void*>(event.worker()) << ") " << _threads.size() << " threads left"); try { event.worker()->join(); } catch (const std::exception& e) { log_error("failed to join thread: " << e.what()); } delete event.worker(); } void ServerImpl::onServerStart(const ServerStartEvent& event) { if (event.server() == this) { start(); } } void ServerImpl::onInput(Socket& _socket) { _socket.setSelector(0); log_debug("search socket " << static_cast<void*>(&_socket) << " in idle sockets"); _idleSockets.erase(&_socket); if (_socket.isConnected()) { disconnect(_socket.inputReady, *this, &ServerImpl::onInput); disconnect(_socket.timeout, *this, &ServerImpl::onTimeout); _queue.put(&_socket); } else { delete &_socket; } } void ServerImpl::onTimeout(Socket& socket) { log_debug("timeout; socket " << static_cast<void*>(&socket)); _eventLoop.commitEvent(KeepAliveTimeoutEvent(&socket)); } void ServerImpl::onKeepAliveTimeout(const KeepAliveTimeoutEvent& event) { Socket* socket = event.socket(); _idleSockets.erase(socket); delete socket; } void ServerImpl::addService(const std::string& url, Service& service) { log_debug("add service for url <" << url << '>'); cxxtools::MutexLock serviceLock(_serviceMutex); _service.insert(ServicesType::value_type(url, &service)); } void ServerImpl::removeService(Service& service) { cxxtools::MutexLock serviceLock(_serviceMutex); ServicesType::iterator it = _service.begin(); while (it != _service.end()) { if (it->second == &service) { _service.erase(it++); } else { ++it; } } } Responder* ServerImpl::getResponder(const Request& request) { log_debug("get responder for url <" << request.url() << '>'); cxxtools::MutexLock serviceLock(_serviceMutex); for (ServicesType::const_iterator it = _service.lower_bound(request.url()); it != _service.end() && it->first == request.url(); ++it) { if (!it->second->checkAuth(request)) { return _noAuthService.createResponder(request, it->second->realm(), it->second->authContent()); } Responder* resp = it->second->createResponder(request); if (resp) { log_debug("got responder"); return resp; } } log_debug("use default responder"); return _defaultService.createResponder(request); } } } <commit_msg>fix memory leak in http server on shutdown<commit_after>/* * Copyright (C) 2010 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "serverimpl.h" #include "worker.h" #include <cxxtools/eventloop.h> #include <cxxtools/log.h> #include "listener.h" log_define("cxxtools.http.server.impl") namespace cxxtools { namespace http { ServerImpl::ServerImpl(EventLoopBase& eventLoop, Signal<Server::Runmode>& runmodeChanged) : _eventLoop(eventLoop), _readTimeout(20000), _writeTimeout(20000), _keepAliveTimeout(30000), _idleTimeout(100), _minThreads(5), _maxThreads(200), _waitingThreads(0), _runmodeChanged(runmodeChanged), _runmode(Server::Stopped) { _eventLoop.event.subscribe(slot(*this, &ServerImpl::onIdleSocket)); _eventLoop.event.subscribe(slot(*this, &ServerImpl::onKeepAliveTimeout)); _eventLoop.event.subscribe(slot(*this, &ServerImpl::onNoWaitingThreads)); _eventLoop.event.subscribe(slot(*this, &ServerImpl::onThreadTerminated)); _eventLoop.event.subscribe(slot(*this, &ServerImpl::onServerStart)); connect(_eventLoop.exited, *this, &ServerImpl::terminate); _eventLoop.commitEvent(ServerStartEvent(this)); } ServerImpl::~ServerImpl() { if (_runmode == Server::Running) { try { terminate(); } catch (const std::exception& e) { log_fatal("exception in http-server termination occured: " << e.what()); } } } void ServerImpl::listen(const std::string& ip, unsigned short int port) { log_debug("listen on " << ip << " port " << port); Listener* listener = new Listener(ip, port); try { _listener.push_back(listener); _queue.put(new Socket(*this, *listener)); } catch (...) { delete listener; throw; } } void ServerImpl::start() { log_trace("start server"); runmode(Server::Starting); MutexLock lock(_threadMutex); while (_threads.size() < _minThreads) { Worker* worker = new Worker(*this); _threads.insert(worker); worker->start(); } runmode(Server::Running); } void ServerImpl::terminate() { log_trace("terminate"); MutexLock lock(_threadMutex); runmode(Server::Terminating); try { log_debug("wake " << _listener.size() << " listeners"); for (ServerImpl::ListenerType::iterator it = _listener.begin(); it != _listener.end(); ++it) (*it)->wakeConnect(); log_debug("terminate " << _threads.size() << " threads"); while (!_threads.empty() || !_terminatedThreads.empty()) { if (!_threads.empty()) { log_debug("wait for terminated thread"); _threadTerminated.wait(lock); } for (Threads::iterator it = _terminatedThreads.begin(); it != _terminatedThreads.end(); ++it) { log_debug("join thread"); (*it)->join(); delete *it; } _terminatedThreads.clear(); } log_debug("delete " << _listener.size() << " listeners"); for (ServerImpl::ListenerType::iterator it = _listener.begin(); it != _listener.end(); ++it) delete *it; _listener.clear(); while (!_queue.empty()) delete _queue.get(); for (std::set<Socket*>::iterator it = _idleSockets.begin(); it != _idleSockets.end(); ++it) delete *it; runmode(Server::Stopped); } catch (const std::exception& e) { runmode(Server::Failed); } } void ServerImpl::noWaitingThreads() { if (_runmode == Server::Running) _eventLoop.commitEvent(NoWaitingThreadsEvent()); } void ServerImpl::threadTerminated(Worker* worker) { log_info("thread " << static_cast<void*>(worker) << " terminated"); MutexLock lock(_threadMutex); _threads.erase(worker); if (_runmode == Server::Running) { _eventLoop.commitEvent(ThreadTerminatedEvent(worker)); } else { _terminatedThreads.insert(worker); _threadTerminated.signal(); } } void ServerImpl::addIdleSocket(Socket* _socket) { log_debug("add idle socket " << static_cast<void*>(_socket)); if (_runmode == Server::Running) { _eventLoop.commitEvent(IdleSocketEvent(_socket)); } else { log_debug("delete socket " << static_cast<void*>(_socket) << "; server not running"); delete _socket; } } void ServerImpl::onIdleSocket(const IdleSocketEvent& event) { Socket* socket = event.socket(); log_debug("add idle socket " << static_cast<void*>(socket) << " to selector"); _idleSockets.insert(socket); socket->setSelector(&_eventLoop); connect(socket->inputReady, *this, &ServerImpl::onInput); connect(socket->timeout, *this, &ServerImpl::onTimeout); } void ServerImpl::onNoWaitingThreads(const NoWaitingThreadsEvent& event) { MutexLock lock(_threadMutex); if (_threads.size() >= maxThreads()) { log_warn("thread limit " << maxThreads() << " reached"); return; } try { Worker* worker = new Worker(*this); try { log_info("create thread " << static_cast<void*>(worker)); worker->start(); _threads.insert(worker); log_debug(_threads.size() << " threads running"); } catch (const std::exception&) { delete worker; throw; } } catch (const std::exception& e) { log_warn("failed to create thread: " << e.what()); } } void ServerImpl::onThreadTerminated(const ThreadTerminatedEvent& event) { MutexLock lock(_threadMutex); log_trace("thread terminated (" << static_cast<void*>(event.worker()) << ") " << _threads.size() << " threads left"); try { event.worker()->join(); } catch (const std::exception& e) { log_error("failed to join thread: " << e.what()); } delete event.worker(); } void ServerImpl::onServerStart(const ServerStartEvent& event) { if (event.server() == this) { start(); } } void ServerImpl::onInput(Socket& _socket) { _socket.setSelector(0); log_debug("search socket " << static_cast<void*>(&_socket) << " in idle sockets"); _idleSockets.erase(&_socket); if (_socket.isConnected()) { disconnect(_socket.inputReady, *this, &ServerImpl::onInput); disconnect(_socket.timeout, *this, &ServerImpl::onTimeout); _queue.put(&_socket); } else { delete &_socket; } } void ServerImpl::onTimeout(Socket& socket) { log_debug("timeout; socket " << static_cast<void*>(&socket)); _eventLoop.commitEvent(KeepAliveTimeoutEvent(&socket)); } void ServerImpl::onKeepAliveTimeout(const KeepAliveTimeoutEvent& event) { Socket* socket = event.socket(); _idleSockets.erase(socket); delete socket; } void ServerImpl::addService(const std::string& url, Service& service) { log_debug("add service for url <" << url << '>'); cxxtools::MutexLock serviceLock(_serviceMutex); _service.insert(ServicesType::value_type(url, &service)); } void ServerImpl::removeService(Service& service) { cxxtools::MutexLock serviceLock(_serviceMutex); ServicesType::iterator it = _service.begin(); while (it != _service.end()) { if (it->second == &service) { _service.erase(it++); } else { ++it; } } } Responder* ServerImpl::getResponder(const Request& request) { log_debug("get responder for url <" << request.url() << '>'); cxxtools::MutexLock serviceLock(_serviceMutex); for (ServicesType::const_iterator it = _service.lower_bound(request.url()); it != _service.end() && it->first == request.url(); ++it) { if (!it->second->checkAuth(request)) { return _noAuthService.createResponder(request, it->second->realm(), it->second->authContent()); } Responder* resp = it->second->createResponder(request); if (resp) { log_debug("got responder"); return resp; } } log_debug("use default responder"); return _defaultService.createResponder(request); } } } <|endoftext|>
<commit_before>/* * This file is part of KDevelop * * Copyright 2006-2010 Alexander Dymo <adymo@kdevelop.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This 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 "rubylanguagesupport.h" #include <kdebug.h> #include <klocale.h> #include <kaction.h> #include <kcomponentdata.h> #include <kstandarddirs.h> #include <kpluginfactory.h> #include <kpluginloader.h> #include <kactioncollection.h> #include <interfaces/icore.h> #include <interfaces/iproject.h> #include <interfaces/idocument.h> #include <interfaces/iplugincontroller.h> #include <interfaces/iprojectcontroller.h> #include <interfaces/idocumentcontroller.h> #include <interfaces/ilanguagecontroller.h> #include <interfaces/iruncontroller.h> #include <interfaces/ilauncher.h> #include <interfaces/ilaunchmode.h> #include <interfaces/ilaunchconfiguration.h> #include <interfaces/launchconfigurationtype.h> #include <execute/iexecuteplugin.h> #include <project/projectmodel.h> #include <language/interfaces/iquickopen.h> #include <language/duchain/duchain.h> #include <language/duchain/duchainlock.h> #include <language/duchain/duchainutils.h> #include <language/backgroundparser/backgroundparser.h> #include <QExtensionFactory> #include "parsejob.h" #include "navigation/railsswitchers.h" #include "navigation/railsdataprovider.h" using namespace Ruby; #define RUBY_FILE_LAUNCH_CONFIGURATION_NAME i18n("Current Ruby File") #define RUBY_CURRENT_FUNCTION_LAUNCH_CONFIGURATION_NAME i18n("Current Ruby Test Function") K_PLUGIN_FACTORY(KDevRubySupportFactory, registerPlugin<RubyLanguageSupport>(); ) K_EXPORT_PLUGIN(KDevRubySupportFactory("kdevrubysupport")) RubyLanguageSupport* RubyLanguageSupport::m_self = 0; RubyLanguageSupport::RubyLanguageSupport( QObject* parent, const QVariantList& /*args*/ ) : KDevelop::IPlugin( KDevRubySupportFactory::componentData(), parent ) , KDevelop::ILanguageSupport() , m_railsSwitchers(new Ruby::RailsSwitchers(this)) , m_rubyFileLaunchConfiguration(0) , m_rubyCurrentFunctionLaunchConfiguration(0) { KDEV_USE_EXTENSION_INTERFACE( KDevelop::ILanguageSupport ) setXMLFile( "kdevrubysupport.rc" ); m_self = this; connect( core()->documentController(), SIGNAL( documentLoaded( KDevelop::IDocument* ) ), this, SLOT( documentLoaded( KDevelop::IDocument* ) ) ); connect( core()->documentController(), SIGNAL( documentClosed( KDevelop::IDocument* ) ), this, SLOT( documentClosed( KDevelop::IDocument* ) ) ); connect( core()->documentController(), SIGNAL( documentStateChanged( KDevelop::IDocument* ) ), this, SLOT( documentChanged( KDevelop::IDocument* ) ) ); connect( core()->documentController(), SIGNAL( documentContentChanged( KDevelop::IDocument* ) ), this, SLOT( documentChanged( KDevelop::IDocument* ) ) ); connect( core()->documentController(), SIGNAL( documentActivated( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) ); connect( core()->projectController(), SIGNAL( projectOpened( KDevelop::IProject* ) ), this, SLOT( projectOpened( KDevelop::IProject* ) ) ); connect( core()->projectController(), SIGNAL( projectClosing( KDevelop::IProject* ) ), this, SLOT( projectClosing( KDevelop::IProject* ) ) ); KActionCollection* actions = actionCollection(); KAction *action = actions->addAction("ruby_switch_to_controller"); action->setText(i18n("Switch To Controller")); action->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_1); connect(action, SIGNAL(triggered(bool)), m_railsSwitchers, SLOT(switchToController())); action = actions->addAction("ruby_switch_to_model"); action->setText(i18n("Switch To Model")); action->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_2); connect(action, SIGNAL(triggered(bool)), m_railsSwitchers, SLOT(switchToModel())); action = actions->addAction("ruby_switch_to_view"); action->setText(i18n("Switch To View")); action->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_3); connect(action, SIGNAL(triggered(bool)), m_railsSwitchers, SLOT(switchToView())); action = actions->addAction("ruby_switch_to_test"); action->setText(i18n("Switch To Test")); action->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_4); connect(action, SIGNAL(triggered(bool)), m_railsSwitchers, SLOT(switchToTest())); action = actions->addAction("ruby_run_current_file"); action->setText(i18n("Run Current File")); action->setShortcut(Qt::META | Qt::Key_F9); connect(action, SIGNAL(triggered(bool)), this, SLOT(runCurrentFile())); action = actions->addAction("ruby_run_current_test_function"); action->setText(i18n("Run Current Test Function")); action->setShortcut(Qt::META | Qt::SHIFT | Qt::Key_F9); connect(action, SIGNAL(triggered(bool)), this, SLOT(runCurrentTestFunction())); m_viewsQuickOpenDataProvider = new RailsDataProvider(Ruby::RailsDataProvider::Views); m_testsQuickOpenDataProvider = new RailsDataProvider(Ruby::RailsDataProvider::Tests); KDevelop::IQuickOpen* quickOpen = core()->pluginController()->extensionForPlugin<KDevelop::IQuickOpen>("org.kdevelop.IQuickOpen"); if (quickOpen) { quickOpen->registerProvider(RailsDataProvider::scopes(), QStringList(i18n("Rails Views")), m_viewsQuickOpenDataProvider); quickOpen->registerProvider(RailsDataProvider::scopes(), QStringList(i18n("Rails Tests")), m_testsQuickOpenDataProvider); } } RubyLanguageSupport::~RubyLanguageSupport() { } RubyLanguageSupport* RubyLanguageSupport::self() { return m_self; } KDevelop::ParseJob* RubyLanguageSupport::createParseJob(const KUrl &url) { return new SimpleParseJob(url, this); } QString RubyLanguageSupport::name() const { return "Ruby"; } QStringList RubyLanguageSupport::extensions() const { return QStringList() << "ILanguageSupport"; } void RubyLanguageSupport::documentActivated(KDevelop::IDocument * document) { Q_UNUSED(document) } void RubyLanguageSupport::documentLoaded(KDevelop::IDocument *document) { kDebug() << "loaded document"; core()->languageController()->backgroundParser()->addDocument(document->url()); } void RubyLanguageSupport::documentClosed(KDevelop::IDocument *document) { Q_UNUSED(document) } void RubyLanguageSupport::projectOpened(KDevelop::IProject *project) { //parse project files KDevelop::BackgroundParser *parser = core()->languageController()->backgroundParser(); foreach (const KDevelop::ProjectFileItem *file, project->files()) parser->addDocument(file->url()); } void RubyLanguageSupport::projectClosing(KDevelop::IProject *project) { Q_UNUSED(project) } void RubyLanguageSupport::documentChanged(KDevelop::IDocument *document) { kDebug() << "loaded document"; core()->languageController()->backgroundParser()->addDocument(document->url()); } void RubyLanguageSupport::runCurrentFile() { KDevelop::IDocument *activeDocument = KDevelop::ICore::self()->documentController()->activeDocument(); if (!activeDocument) return; //todo: adymo: check that this file is actually a ruby source //todo: adymo: disable this action in the UI if current file is not a ruby source if (!m_rubyFileLaunchConfiguration) m_rubyFileLaunchConfiguration = findOrCreateLaunchConfiguration(RUBY_FILE_LAUNCH_CONFIGURATION_NAME); if (!m_rubyFileLaunchConfiguration) return; KConfigGroup cfg = m_rubyFileLaunchConfiguration->config(); setUpLaunchConfigurationBeforeRun(cfg, activeDocument); cfg.writeEntry("Arguments", QStringList() << activeDocument->url().toLocalFile()); cfg.sync(); core()->runController()->execute("execute", m_rubyFileLaunchConfiguration); } void RubyLanguageSupport::runCurrentTestFunction() { KDevelop::IDocument *activeDocument = KDevelop::ICore::self()->documentController()->activeDocument(); if (!activeDocument) return; //todo: adymo: check that this file is actually a ruby source //todo: adymo: disable this action in the UI if current file is not a ruby source if (!m_rubyCurrentFunctionLaunchConfiguration) m_rubyCurrentFunctionLaunchConfiguration = findOrCreateLaunchConfiguration(RUBY_CURRENT_FUNCTION_LAUNCH_CONFIGURATION_NAME); if (!m_rubyCurrentFunctionLaunchConfiguration) return; //find function under the cursor (if any) QString currentFunction = findFunctionUnderCursor(activeDocument); kDebug(9047) << "current function" << currentFunction; if (currentFunction.isEmpty()) return; KConfigGroup cfg = m_rubyCurrentFunctionLaunchConfiguration->config(); setUpLaunchConfigurationBeforeRun(cfg, activeDocument); QStringList args; args << activeDocument->url().toLocalFile() << "-n" << currentFunction; cfg.writeEntry("Arguments", args.join(" ")); cfg.sync(); core()->runController()->execute("execute", m_rubyCurrentFunctionLaunchConfiguration); } QString RubyLanguageSupport::findFunctionUnderCursor(KDevelop::IDocument *doc) { QString function; KDevelop::DUChainReadLocker lock( KDevelop::DUChain::lock() ); KDevelop::TopDUContext* topContext = KDevelop::DUChainUtils::standardContextForUrl( doc->url() ); if (!topContext) return ""; KDevelop::CursorInRevision cursor = KDevelop::CursorInRevision(doc->cursorPosition().line(), doc->cursorPosition().column()); KDevelop::DUContext* context = topContext->findContextAt(cursor); if (!context) return ""; kDebug(9047) << "CONTEXT ID" << context->localScopeIdentifier(); return context->localScopeIdentifier().toString(); } void RubyLanguageSupport::setUpLaunchConfigurationBeforeRun(KConfigGroup &cfg, KDevelop::IDocument *activeDocument) { KUrl railsRoot = RailsSwitchers::findRailsRoot(activeDocument->url()); if (!railsRoot.isEmpty()) cfg.writeEntry("Working Directory", railsRoot); else cfg.writeEntry("Working Directory", activeDocument->url().directory()); } KDevelop::ILaunchConfiguration* RubyLanguageSupport::findOrCreateLaunchConfiguration(const QString& name) { foreach (KDevelop::ILaunchConfiguration *config, core()->runController()->launchConfigurations()) { if (config->name() == name) return config; } KDevelop::ILaunchConfiguration *config = 0; IExecutePlugin* executePlugin = core()->pluginController()->pluginForExtension("org.kdevelop.IExecutePlugin")->extension<IExecutePlugin>(); KDevelop::LaunchConfigurationType* type = core()->runController()->launchConfigurationTypeForId(executePlugin->nativeAppConfigTypeId()); if (!type) return 0; KDevelop::ILaunchMode* mode = core()->runController()->launchModeForId("execute"); if (!mode) return 0; KDevelop::ILauncher *launcher = 0; foreach (KDevelop::ILauncher *l, type->launchers()) { if (l->supportedModes().contains("execute")) launcher = l; } if (!launcher) return 0; config = core()->runController()->createLaunchConfiguration(type, qMakePair(mode->id(), launcher->id()), 0, name); KConfigGroup cfg = config->config(); cfg.writeEntry("isExecutable", true); cfg.writeEntry("Executable", "ruby"); cfg.sync(); return config; } #include "rubylanguagesupport.moc" // kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on <commit_msg>BackgroundParser's api has changed: it now takes indexed strings<commit_after>/* * This file is part of KDevelop * * Copyright 2006-2010 Alexander Dymo <adymo@kdevelop.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This 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 "rubylanguagesupport.h" #include <kdebug.h> #include <klocale.h> #include <kaction.h> #include <kcomponentdata.h> #include <kstandarddirs.h> #include <kpluginfactory.h> #include <kpluginloader.h> #include <kactioncollection.h> #include <interfaces/icore.h> #include <interfaces/iproject.h> #include <interfaces/idocument.h> #include <interfaces/iplugincontroller.h> #include <interfaces/iprojectcontroller.h> #include <interfaces/idocumentcontroller.h> #include <interfaces/ilanguagecontroller.h> #include <interfaces/iruncontroller.h> #include <interfaces/ilauncher.h> #include <interfaces/ilaunchmode.h> #include <interfaces/ilaunchconfiguration.h> #include <interfaces/launchconfigurationtype.h> #include <execute/iexecuteplugin.h> #include <project/projectmodel.h> #include <language/interfaces/iquickopen.h> #include <language/duchain/duchain.h> #include <language/duchain/duchainlock.h> #include <language/duchain/duchainutils.h> #include <language/backgroundparser/backgroundparser.h> #include <QExtensionFactory> #include "parsejob.h" #include "navigation/railsswitchers.h" #include "navigation/railsdataprovider.h" using namespace Ruby; #define RUBY_FILE_LAUNCH_CONFIGURATION_NAME i18n("Current Ruby File") #define RUBY_CURRENT_FUNCTION_LAUNCH_CONFIGURATION_NAME i18n("Current Ruby Test Function") K_PLUGIN_FACTORY(KDevRubySupportFactory, registerPlugin<RubyLanguageSupport>(); ) K_EXPORT_PLUGIN(KDevRubySupportFactory("kdevrubysupport")) RubyLanguageSupport* RubyLanguageSupport::m_self = 0; RubyLanguageSupport::RubyLanguageSupport( QObject* parent, const QVariantList& /*args*/ ) : KDevelop::IPlugin( KDevRubySupportFactory::componentData(), parent ) , KDevelop::ILanguageSupport() , m_railsSwitchers(new Ruby::RailsSwitchers(this)) , m_rubyFileLaunchConfiguration(0) , m_rubyCurrentFunctionLaunchConfiguration(0) { KDEV_USE_EXTENSION_INTERFACE( KDevelop::ILanguageSupport ) setXMLFile( "kdevrubysupport.rc" ); m_self = this; connect( core()->documentController(), SIGNAL( documentLoaded( KDevelop::IDocument* ) ), this, SLOT( documentLoaded( KDevelop::IDocument* ) ) ); connect( core()->documentController(), SIGNAL( documentClosed( KDevelop::IDocument* ) ), this, SLOT( documentClosed( KDevelop::IDocument* ) ) ); connect( core()->documentController(), SIGNAL( documentStateChanged( KDevelop::IDocument* ) ), this, SLOT( documentChanged( KDevelop::IDocument* ) ) ); connect( core()->documentController(), SIGNAL( documentContentChanged( KDevelop::IDocument* ) ), this, SLOT( documentChanged( KDevelop::IDocument* ) ) ); connect( core()->documentController(), SIGNAL( documentActivated( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) ); connect( core()->projectController(), SIGNAL( projectOpened( KDevelop::IProject* ) ), this, SLOT( projectOpened( KDevelop::IProject* ) ) ); connect( core()->projectController(), SIGNAL( projectClosing( KDevelop::IProject* ) ), this, SLOT( projectClosing( KDevelop::IProject* ) ) ); KActionCollection* actions = actionCollection(); KAction *action = actions->addAction("ruby_switch_to_controller"); action->setText(i18n("Switch To Controller")); action->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_1); connect(action, SIGNAL(triggered(bool)), m_railsSwitchers, SLOT(switchToController())); action = actions->addAction("ruby_switch_to_model"); action->setText(i18n("Switch To Model")); action->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_2); connect(action, SIGNAL(triggered(bool)), m_railsSwitchers, SLOT(switchToModel())); action = actions->addAction("ruby_switch_to_view"); action->setText(i18n("Switch To View")); action->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_3); connect(action, SIGNAL(triggered(bool)), m_railsSwitchers, SLOT(switchToView())); action = actions->addAction("ruby_switch_to_test"); action->setText(i18n("Switch To Test")); action->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_4); connect(action, SIGNAL(triggered(bool)), m_railsSwitchers, SLOT(switchToTest())); action = actions->addAction("ruby_run_current_file"); action->setText(i18n("Run Current File")); action->setShortcut(Qt::META | Qt::Key_F9); connect(action, SIGNAL(triggered(bool)), this, SLOT(runCurrentFile())); action = actions->addAction("ruby_run_current_test_function"); action->setText(i18n("Run Current Test Function")); action->setShortcut(Qt::META | Qt::SHIFT | Qt::Key_F9); connect(action, SIGNAL(triggered(bool)), this, SLOT(runCurrentTestFunction())); m_viewsQuickOpenDataProvider = new RailsDataProvider(Ruby::RailsDataProvider::Views); m_testsQuickOpenDataProvider = new RailsDataProvider(Ruby::RailsDataProvider::Tests); KDevelop::IQuickOpen* quickOpen = core()->pluginController()->extensionForPlugin<KDevelop::IQuickOpen>("org.kdevelop.IQuickOpen"); if (quickOpen) { quickOpen->registerProvider(RailsDataProvider::scopes(), QStringList(i18n("Rails Views")), m_viewsQuickOpenDataProvider); quickOpen->registerProvider(RailsDataProvider::scopes(), QStringList(i18n("Rails Tests")), m_testsQuickOpenDataProvider); } } RubyLanguageSupport::~RubyLanguageSupport() { } RubyLanguageSupport* RubyLanguageSupport::self() { return m_self; } KDevelop::ParseJob* RubyLanguageSupport::createParseJob(const KUrl &url) { return new SimpleParseJob(url, this); } QString RubyLanguageSupport::name() const { return "Ruby"; } QStringList RubyLanguageSupport::extensions() const { return QStringList() << "ILanguageSupport"; } void RubyLanguageSupport::documentActivated(KDevelop::IDocument * document) { Q_UNUSED(document) } void RubyLanguageSupport::documentLoaded(KDevelop::IDocument *document) { kDebug() << "loaded document"; KDevelop::IndexedString indexedUrl(document->url()); core()->languageController()->backgroundParser()->addDocument(indexedUrl); } void RubyLanguageSupport::documentClosed(KDevelop::IDocument *document) { Q_UNUSED(document) } void RubyLanguageSupport::projectOpened(KDevelop::IProject *project) { //parse project files KDevelop::BackgroundParser *parser = core()->languageController()->backgroundParser(); foreach (const KDevelop::ProjectFileItem *file, project->files()) { KDevelop::IndexedString indexedUrl(file->url()); parser->addDocument(indexedUrl); } } void RubyLanguageSupport::projectClosing(KDevelop::IProject *project) { Q_UNUSED(project) } void RubyLanguageSupport::documentChanged(KDevelop::IDocument *document) { kDebug() << "loaded document"; KDevelop::IndexedString indexedUrl(document->url()); core()->languageController()->backgroundParser()->addDocument(indexedUrl); } void RubyLanguageSupport::runCurrentFile() { KDevelop::IDocument *activeDocument = KDevelop::ICore::self()->documentController()->activeDocument(); if (!activeDocument) return; //todo: adymo: check that this file is actually a ruby source //todo: adymo: disable this action in the UI if current file is not a ruby source if (!m_rubyFileLaunchConfiguration) m_rubyFileLaunchConfiguration = findOrCreateLaunchConfiguration(RUBY_FILE_LAUNCH_CONFIGURATION_NAME); if (!m_rubyFileLaunchConfiguration) return; KConfigGroup cfg = m_rubyFileLaunchConfiguration->config(); setUpLaunchConfigurationBeforeRun(cfg, activeDocument); cfg.writeEntry("Arguments", QStringList() << activeDocument->url().toLocalFile()); cfg.sync(); core()->runController()->execute("execute", m_rubyFileLaunchConfiguration); } void RubyLanguageSupport::runCurrentTestFunction() { KDevelop::IDocument *activeDocument = KDevelop::ICore::self()->documentController()->activeDocument(); if (!activeDocument) return; //todo: adymo: check that this file is actually a ruby source //todo: adymo: disable this action in the UI if current file is not a ruby source if (!m_rubyCurrentFunctionLaunchConfiguration) m_rubyCurrentFunctionLaunchConfiguration = findOrCreateLaunchConfiguration(RUBY_CURRENT_FUNCTION_LAUNCH_CONFIGURATION_NAME); if (!m_rubyCurrentFunctionLaunchConfiguration) return; //find function under the cursor (if any) QString currentFunction = findFunctionUnderCursor(activeDocument); kDebug(9047) << "current function" << currentFunction; if (currentFunction.isEmpty()) return; KConfigGroup cfg = m_rubyCurrentFunctionLaunchConfiguration->config(); setUpLaunchConfigurationBeforeRun(cfg, activeDocument); QStringList args; args << activeDocument->url().toLocalFile() << "-n" << currentFunction; cfg.writeEntry("Arguments", args.join(" ")); cfg.sync(); core()->runController()->execute("execute", m_rubyCurrentFunctionLaunchConfiguration); } QString RubyLanguageSupport::findFunctionUnderCursor(KDevelop::IDocument *doc) { QString function; KDevelop::DUChainReadLocker lock( KDevelop::DUChain::lock() ); KDevelop::TopDUContext* topContext = KDevelop::DUChainUtils::standardContextForUrl( doc->url() ); if (!topContext) return ""; KDevelop::CursorInRevision cursor = KDevelop::CursorInRevision(doc->cursorPosition().line(), doc->cursorPosition().column()); KDevelop::DUContext* context = topContext->findContextAt(cursor); if (!context) return ""; kDebug(9047) << "CONTEXT ID" << context->localScopeIdentifier(); return context->localScopeIdentifier().toString(); } void RubyLanguageSupport::setUpLaunchConfigurationBeforeRun(KConfigGroup &cfg, KDevelop::IDocument *activeDocument) { KUrl railsRoot = RailsSwitchers::findRailsRoot(activeDocument->url()); if (!railsRoot.isEmpty()) cfg.writeEntry("Working Directory", railsRoot); else cfg.writeEntry("Working Directory", activeDocument->url().directory()); } KDevelop::ILaunchConfiguration* RubyLanguageSupport::findOrCreateLaunchConfiguration(const QString& name) { foreach (KDevelop::ILaunchConfiguration *config, core()->runController()->launchConfigurations()) { if (config->name() == name) return config; } KDevelop::ILaunchConfiguration *config = 0; IExecutePlugin* executePlugin = core()->pluginController()->pluginForExtension("org.kdevelop.IExecutePlugin")->extension<IExecutePlugin>(); KDevelop::LaunchConfigurationType* type = core()->runController()->launchConfigurationTypeForId(executePlugin->nativeAppConfigTypeId()); if (!type) return 0; KDevelop::ILaunchMode* mode = core()->runController()->launchModeForId("execute"); if (!mode) return 0; KDevelop::ILauncher *launcher = 0; foreach (KDevelop::ILauncher *l, type->launchers()) { if (l->supportedModes().contains("execute")) launcher = l; } if (!launcher) return 0; config = core()->runController()->createLaunchConfiguration(type, qMakePair(mode->id(), launcher->id()), 0, name); KConfigGroup cfg = config->config(); cfg.writeEntry("isExecutable", true); cfg.writeEntry("Executable", "ruby"); cfg.sync(); return config; } #include "rubylanguagesupport.moc" // kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on <|endoftext|>
<commit_before>/* CsoundPerformanceSettings.cpp: Copyright (C) 2006 Istvan Varga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "CsoundGUI.hpp" using namespace std; CsoundPerformanceSettings::CsoundPerformanceSettings() { orcName = ""; scoName = ""; soundFileType = "wav"; soundSampleFormat = "short"; enablePeakChunks = true; displayMode = 1; deferGEN1 = false; bufFrames_SW = 1024; nBuffers = 4; midiInFileName = ""; midiOutFileName = ""; midiInDevName = ""; midiOutDevName = ""; terminateOnMidi = false; // heartBeatMode = 0; rewriteHeader = false; inputFileName = ""; outputFileName = "dac"; enableSoundOutput = true; beatModeTempo = -1.0; iTimeOnly = false; sampleRateOverride = -1.0; controlRateOverride = -1.0; lineInput = ""; messageLevel = 231; enableExpressionOpt = false; sadirPath = ""; ssdirPath = ""; sfdirPath = ""; incdirPath = ""; csdocdirPath = ""; for (int i = 0; i < 10; i++) strsets[i] = ""; verbose = false; enableDither = false; pluginLibs = ""; sndidArtist = ""; sndidComment = ""; sndidCopyright = ""; sndidDate = ""; sndidSoftware = ""; sndidTitle = ""; ignoreCSDOptions = true; jackClientName = ""; jackInPortName = ""; jackOutPortName = ""; maxStrLen = 255; midiFileMuteTracks = ""; midiKeyMidi = -1; midiKeyCps = -1; midiKeyOct = -1; midiKeyPch = -1; midiVelMidi = -1; midiVelAmp = -1; rawControllerMode = false; rtAudioModule = "PortAudio"; rtAudioOutputDevice = "dac"; rtAudioInputDevice = "adc"; rtMidiModule = "PortMidi"; scoreOffsetSeconds = 0.0; useThreads = true; scriptFileName = ""; additionalFlags = ""; useAdditionalFlags = false; } CsoundPerformanceSettings::~CsoundPerformanceSettings() { } static const char *fileTypeList[] = { "wav", "aiff", "au", "raw", "ircam", "w64", "wavex", "sd2", "flac", (char*) 0 }; static const char *sampleFormatList[] = { "alaw", "ulaw", "schar", "uchar", "float", "short", "long", "24bit", (char*) 0 }; int CsoundPerformanceSettings::fileTypeToIndex(const char *fileType) { if (fileType == (char*) 0 || fileType[0] == (char) 0) return -1; for (int i = 0; fileTypeList[i] != (char*) 0; i++) { if (strcmp(fileTypeList[i], fileType) == 0) if (strcmp(fileTypeList[i], fileType) == 0) return i; } return -1; } const char *CsoundPerformanceSettings::indexToFileType(int fileType) { if (fileType < 0 || fileType >= (int) (sizeof(fileTypeList) / sizeof(char*))) return (char*) 0; return fileTypeList[fileType]; } int CsoundPerformanceSettings::sampleFormatToIndex(const char *sampleFormat) { if (sampleFormat == (char*) 0 || sampleFormat[0] == (char) 0) return -1; for (int i = 0; sampleFormatList[i] != (char*) 0; i++) { if (strcmp(sampleFormatList[i], sampleFormat) == 0) return i; } return -1; } const char *CsoundPerformanceSettings::indexToSampleFormat(int sampleFormat) { if (sampleFormat < 0 || sampleFormat >= (int) (sizeof(sampleFormatList) / sizeof(char*))) return (char*) 0; return sampleFormatList[sampleFormat]; } static bool cmdLine_addStringOpt(vector<string>& cmdLine, const char *optName, string& value) { string arg; int i, pos0, pos1; for (pos0 = 0; pos0 < (int) value.size(); pos0++) { char c = value[pos0]; if (c != ' ' && c != '\t' && c != '\r' && c != '\n') break; } for (pos1 = (int) value.size() - 1; pos1 >= 0; pos1--) { char c = value[pos1]; if (c != ' ' && c != '\t' && c != '\r' && c != '\n') break; } if (pos0 > pos1) return false; arg = optName; for (i = pos0; i <= pos1; i++) arg += value[i]; cmdLine.push_back(arg); return true; } static void cmdLine_addIntegerOpt(vector<string>& cmdLine, const char *optName, int value) { char buf[64]; sprintf(&(buf[0]), "%s%d", optName, value); cmdLine.push_back(&(buf[0])); } static void cmdLine_addDoubleOpt(vector<string>& cmdLine, const char *optName, double value) { char buf[64]; if (!(value > -10000000.0 && value < 10000000.0)) return; sprintf(&(buf[0]), "%s%g", optName, value); cmdLine.push_back(&(buf[0])); } void CsoundPerformanceSettings::buildCommandLine(vector<string>& cmdLine, bool forceSettings) { cmdLine.clear(); cmdLine.push_back("csound"); if (!CsoundGUIMain::isEmptyString(soundFileType) && (soundFileType != "wav" || forceSettings)) { string arg; arg = "--format="; arg += soundFileType; if (!CsoundGUIMain::isEmptyString(soundSampleFormat) && (soundSampleFormat != "short" || forceSettings)) { arg += ':'; arg += soundSampleFormat; } cmdLine.push_back(arg); } else if (!CsoundGUIMain::isEmptyString(soundSampleFormat) && (soundSampleFormat != "short" || forceSettings)) { cmdLine_addStringOpt(cmdLine, "--format=", soundSampleFormat); } if (!enablePeakChunks) { cmdLine.push_back("-K"); } if (displayMode != 1 || forceSettings) { switch (displayMode) { // 0: none, 1: full, 2: ASCII, 3: PS case 0: cmdLine.push_back("-d"); break; case 1: cmdLine.push_back("--displays"); break; case 2: if (forceSettings) cmdLine.push_back("--displays"); cmdLine.push_back("-g"); break; case 3: if (forceSettings) cmdLine.push_back("--displays"); cmdLine.push_back("-G"); break; } } if (deferGEN1) cmdLine.push_back("-D"); if (bufFrames_SW >= 16) { cmdLine_addIntegerOpt(cmdLine, "-b", bufFrames_SW); cmdLine_addIntegerOpt(cmdLine, "-B", bufFrames_SW * nBuffers); } cmdLine_addStringOpt(cmdLine, "-F", midiInFileName); cmdLine_addStringOpt(cmdLine, "--midioutfile=", midiOutFileName); cmdLine_addStringOpt(cmdLine, "-M", midiInDevName); cmdLine_addStringOpt(cmdLine, "-Q", midiOutDevName); if (terminateOnMidi) cmdLine.push_back("-T"); if (heartBeatMode != 0 || forceSettings) cmdLine_addIntegerOpt(cmdLine, "-H", heartBeatMode); if (rewriteHeader) cmdLine.push_back("-R"); if (runRealtime) cmdLine_addStringOpt(cmdLine, "-i", rtAudioInputDevice); else cmdLine_addStringOpt(cmdLine, "-i", inputFileName); if (!CsoundGUIMain::isEmptyString(outputFileName) && enableSoundOutput) { cmdLine_addStringOpt(cmdLine, "-o", outputFileName); } else if (forceSettings && !disableDiskOutput) cmdLine.push_back("-n"); if (disableDiskOutput && !runRealtime) cmdLine.push_back("-n"); if (beatModeTempo > 0.0) cmdLine_addDoubleOpt(cmdLine, "-t", beatModeTempo); if (iTimeOnly) cmdLine.push_back("-I"); if (sampleRateOverride > 0.0 && controlRateOverride > 0.0) { cmdLine_addDoubleOpt(cmdLine, "-r", sampleRateOverride); cmdLine_addDoubleOpt(cmdLine, "-k", controlRateOverride); } cmdLine_addStringOpt(cmdLine, "-L", lineInput); if (messageLevel != 135 || forceSettings) cmdLine_addIntegerOpt(cmdLine, "-m", messageLevel); if (enableExpressionOpt) cmdLine.push_back("--expression-opt"); else if (forceSettings) cmdLine.push_back("--no-expression-opt"); cmdLine_addStringOpt(cmdLine, "--env:SADIR+=", sadirPath); cmdLine_addStringOpt(cmdLine, "--env:SSDIR+=", ssdirPath); cmdLine_addStringOpt(cmdLine, "--env:SFDIR+=", sfdirPath); cmdLine_addStringOpt(cmdLine, "--env:INCDIR+=", incdirPath); // cmdLine_addStringOpt(cmdLine, "--env:CSDOCDIR+=", csdocdirPath); for (int i = 0; i < 10; i++) { if (!CsoundGUIMain::isEmptyString(strsets[i])) { char buf[16]; sprintf(&(buf[0]), "--strset%d=", i); cmdLine_addStringOpt(cmdLine, &(buf[0]), strsets[i]); } } if (verbose) cmdLine.push_back("-v"); if (enableDither) cmdLine.push_back("-Z"); cmdLine_addStringOpt(cmdLine, "--opcode-lib=", pluginLibs); cmdLine_addStringOpt(cmdLine, "-+id_artist=", sndidArtist); cmdLine_addStringOpt(cmdLine, "-+id_comment=", sndidComment); cmdLine_addStringOpt(cmdLine, "-+id_copyright=", sndidCopyright); cmdLine_addStringOpt(cmdLine, "-+id_date=", sndidDate); cmdLine_addStringOpt(cmdLine, "-+id_software=", sndidSoftware); cmdLine_addStringOpt(cmdLine, "-+id_title=", sndidTitle); if (ignoreCSDOptions) cmdLine.push_back("-+ignore_csopts=1"); else if (forceSettings) cmdLine.push_back("-+ignore_csopts=0"); cmdLine_addStringOpt(cmdLine, "-+jack_client=", jackClientName); cmdLine_addStringOpt(cmdLine, "-+jack_inportname=", jackInPortName); cmdLine_addStringOpt(cmdLine, "-+jack_outportname=", jackOutPortName); if ((maxStrLen >= 9 && maxStrLen <= 9999) && (maxStrLen != 255 || forceSettings)) { cmdLine_addIntegerOpt(cmdLine, "-+max_str_len=", maxStrLen + 1); } if (!cmdLine_addStringOpt(cmdLine, "-+mute_tracks=", midiFileMuteTracks)) { if (forceSettings) cmdLine.push_back("-+mute_tracks="); } if (midiKeyMidi > 0) cmdLine_addIntegerOpt(cmdLine, "-+midi-key=", midiKeyMidi); if (midiKeyCps > 0) cmdLine_addIntegerOpt(cmdLine, "-+midi-key-cps=", midiKeyCps); if (midiKeyOct > 0) cmdLine_addIntegerOpt(cmdLine, "-+midi-key-oct=", midiKeyOct); if (midiKeyPch > 0) cmdLine_addIntegerOpt(cmdLine, "-+midi-key-pch=", midiKeyPch); if (midiVelMidi > 0) cmdLine_addIntegerOpt(cmdLine, "-+midi-velocity=", midiVelMidi); if (midiVelAmp > 0) cmdLine_addIntegerOpt(cmdLine, "-+midi-velocity-amp=", midiVelAmp); if (rawControllerMode) cmdLine.push_back("-+raw_controller_mode=1"); else if (forceSettings) cmdLine.push_back("-+raw_controller_mode=0"); if (runRealtime) cmdLine_addStringOpt(cmdLine, "-+rtaudio=", rtAudioModule); cmdLine_addStringOpt(cmdLine, "-+rtmidi=", rtMidiModule); if (scoreOffsetSeconds > 0.0) cmdLine_addDoubleOpt(cmdLine, "-+skip_seconds=", scoreOffsetSeconds); else if (forceSettings && scoreOffsetSeconds == 0.0) cmdLine.push_back("-+skip_seconds=0"); if (!CsoundGUIMain::isEmptyString(orcName)) { cmdLine.push_back(orcName); if (!CsoundGUIMain::isCSDFile(orcName) && !CsoundGUIMain::isEmptyString(scoName)) cmdLine.push_back(scoName); } if (useAdditionalFlags && !CsoundGUIMain::isEmptyString(additionalFlags)) cmdLine.push_back(additionalFlags); } <commit_msg>Initialize heartbeat property<commit_after>/* CsoundPerformanceSettings.cpp: Copyright (C) 2006 Istvan Varga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "CsoundGUI.hpp" using namespace std; CsoundPerformanceSettings::CsoundPerformanceSettings() { orcName = ""; scoName = ""; soundFileType = "wav"; soundSampleFormat = "short"; enablePeakChunks = true; displayMode = 1; deferGEN1 = false; bufFrames_SW = 1024; nBuffers = 4; midiInFileName = ""; midiOutFileName = ""; midiInDevName = ""; midiOutDevName = ""; terminateOnMidi = false; heartBeatMode = 0; rewriteHeader = false; inputFileName = ""; outputFileName = "dac"; enableSoundOutput = true; beatModeTempo = -1.0; iTimeOnly = false; sampleRateOverride = -1.0; controlRateOverride = -1.0; lineInput = ""; messageLevel = 231; enableExpressionOpt = false; sadirPath = ""; ssdirPath = ""; sfdirPath = ""; incdirPath = ""; csdocdirPath = ""; for (int i = 0; i < 10; i++) strsets[i] = ""; verbose = false; enableDither = false; pluginLibs = ""; sndidArtist = ""; sndidComment = ""; sndidCopyright = ""; sndidDate = ""; sndidSoftware = ""; sndidTitle = ""; ignoreCSDOptions = true; jackClientName = ""; jackInPortName = ""; jackOutPortName = ""; maxStrLen = 255; midiFileMuteTracks = ""; midiKeyMidi = -1; midiKeyCps = -1; midiKeyOct = -1; midiKeyPch = -1; midiVelMidi = -1; midiVelAmp = -1; rawControllerMode = false; rtAudioModule = "PortAudio"; rtAudioOutputDevice = "dac"; rtAudioInputDevice = "adc"; rtMidiModule = "PortMidi"; scoreOffsetSeconds = 0.0; useThreads = true; scriptFileName = ""; additionalFlags = ""; useAdditionalFlags = false; } CsoundPerformanceSettings::~CsoundPerformanceSettings() { } static const char *fileTypeList[] = { "wav", "aiff", "au", "raw", "ircam", "w64", "wavex", "sd2", "flac", (char*) 0 }; static const char *sampleFormatList[] = { "alaw", "ulaw", "schar", "uchar", "float", "short", "long", "24bit", (char*) 0 }; int CsoundPerformanceSettings::fileTypeToIndex(const char *fileType) { if (fileType == (char*) 0 || fileType[0] == (char) 0) return -1; for (int i = 0; fileTypeList[i] != (char*) 0; i++) { if (strcmp(fileTypeList[i], fileType) == 0) if (strcmp(fileTypeList[i], fileType) == 0) return i; } return -1; } const char *CsoundPerformanceSettings::indexToFileType(int fileType) { if (fileType < 0 || fileType >= (int) (sizeof(fileTypeList) / sizeof(char*))) return (char*) 0; return fileTypeList[fileType]; } int CsoundPerformanceSettings::sampleFormatToIndex(const char *sampleFormat) { if (sampleFormat == (char*) 0 || sampleFormat[0] == (char) 0) return -1; for (int i = 0; sampleFormatList[i] != (char*) 0; i++) { if (strcmp(sampleFormatList[i], sampleFormat) == 0) return i; } return -1; } const char *CsoundPerformanceSettings::indexToSampleFormat(int sampleFormat) { if (sampleFormat < 0 || sampleFormat >= (int) (sizeof(sampleFormatList) / sizeof(char*))) return (char*) 0; return sampleFormatList[sampleFormat]; } static bool cmdLine_addStringOpt(vector<string>& cmdLine, const char *optName, string& value) { string arg; int i, pos0, pos1; for (pos0 = 0; pos0 < (int) value.size(); pos0++) { char c = value[pos0]; if (c != ' ' && c != '\t' && c != '\r' && c != '\n') break; } for (pos1 = (int) value.size() - 1; pos1 >= 0; pos1--) { char c = value[pos1]; if (c != ' ' && c != '\t' && c != '\r' && c != '\n') break; } if (pos0 > pos1) return false; arg = optName; for (i = pos0; i <= pos1; i++) arg += value[i]; cmdLine.push_back(arg); return true; } static void cmdLine_addIntegerOpt(vector<string>& cmdLine, const char *optName, int value) { char buf[64]; sprintf(&(buf[0]), "%s%d", optName, value); cmdLine.push_back(&(buf[0])); } static void cmdLine_addDoubleOpt(vector<string>& cmdLine, const char *optName, double value) { char buf[64]; if (!(value > -10000000.0 && value < 10000000.0)) return; sprintf(&(buf[0]), "%s%g", optName, value); cmdLine.push_back(&(buf[0])); } void CsoundPerformanceSettings::buildCommandLine(vector<string>& cmdLine, bool forceSettings) { cmdLine.clear(); cmdLine.push_back("csound"); if (!CsoundGUIMain::isEmptyString(soundFileType) && (soundFileType != "wav" || forceSettings)) { string arg; arg = "--format="; arg += soundFileType; if (!CsoundGUIMain::isEmptyString(soundSampleFormat) && (soundSampleFormat != "short" || forceSettings)) { arg += ':'; arg += soundSampleFormat; } cmdLine.push_back(arg); } else if (!CsoundGUIMain::isEmptyString(soundSampleFormat) && (soundSampleFormat != "short" || forceSettings)) { cmdLine_addStringOpt(cmdLine, "--format=", soundSampleFormat); } if (!enablePeakChunks) { cmdLine.push_back("-K"); } if (displayMode != 1 || forceSettings) { switch (displayMode) { // 0: none, 1: full, 2: ASCII, 3: PS case 0: cmdLine.push_back("-d"); break; case 1: cmdLine.push_back("--displays"); break; case 2: if (forceSettings) cmdLine.push_back("--displays"); cmdLine.push_back("-g"); break; case 3: if (forceSettings) cmdLine.push_back("--displays"); cmdLine.push_back("-G"); break; } } if (deferGEN1) cmdLine.push_back("-D"); if (bufFrames_SW >= 16) { cmdLine_addIntegerOpt(cmdLine, "-b", bufFrames_SW); cmdLine_addIntegerOpt(cmdLine, "-B", bufFrames_SW * nBuffers); } cmdLine_addStringOpt(cmdLine, "-F", midiInFileName); cmdLine_addStringOpt(cmdLine, "--midioutfile=", midiOutFileName); cmdLine_addStringOpt(cmdLine, "-M", midiInDevName); cmdLine_addStringOpt(cmdLine, "-Q", midiOutDevName); if (terminateOnMidi) cmdLine.push_back("-T"); if (heartBeatMode != 0 || forceSettings) cmdLine_addIntegerOpt(cmdLine, "-H", heartBeatMode); if (rewriteHeader) cmdLine.push_back("-R"); if (runRealtime) cmdLine_addStringOpt(cmdLine, "-i", rtAudioInputDevice); else cmdLine_addStringOpt(cmdLine, "-i", inputFileName); if (!CsoundGUIMain::isEmptyString(outputFileName) && enableSoundOutput) { cmdLine_addStringOpt(cmdLine, "-o", outputFileName); } else if (forceSettings && !disableDiskOutput) cmdLine.push_back("-n"); if (disableDiskOutput && !runRealtime) cmdLine.push_back("-n"); if (beatModeTempo > 0.0) cmdLine_addDoubleOpt(cmdLine, "-t", beatModeTempo); if (iTimeOnly) cmdLine.push_back("-I"); if (sampleRateOverride > 0.0 && controlRateOverride > 0.0) { cmdLine_addDoubleOpt(cmdLine, "-r", sampleRateOverride); cmdLine_addDoubleOpt(cmdLine, "-k", controlRateOverride); } cmdLine_addStringOpt(cmdLine, "-L", lineInput); if (messageLevel != 135 || forceSettings) cmdLine_addIntegerOpt(cmdLine, "-m", messageLevel); if (enableExpressionOpt) cmdLine.push_back("--expression-opt"); else if (forceSettings) cmdLine.push_back("--no-expression-opt"); cmdLine_addStringOpt(cmdLine, "--env:SADIR+=", sadirPath); cmdLine_addStringOpt(cmdLine, "--env:SSDIR+=", ssdirPath); cmdLine_addStringOpt(cmdLine, "--env:SFDIR+=", sfdirPath); cmdLine_addStringOpt(cmdLine, "--env:INCDIR+=", incdirPath); // cmdLine_addStringOpt(cmdLine, "--env:CSDOCDIR+=", csdocdirPath); for (int i = 0; i < 10; i++) { if (!CsoundGUIMain::isEmptyString(strsets[i])) { char buf[16]; sprintf(&(buf[0]), "--strset%d=", i); cmdLine_addStringOpt(cmdLine, &(buf[0]), strsets[i]); } } if (verbose) cmdLine.push_back("-v"); if (enableDither) cmdLine.push_back("-Z"); cmdLine_addStringOpt(cmdLine, "--opcode-lib=", pluginLibs); cmdLine_addStringOpt(cmdLine, "-+id_artist=", sndidArtist); cmdLine_addStringOpt(cmdLine, "-+id_comment=", sndidComment); cmdLine_addStringOpt(cmdLine, "-+id_copyright=", sndidCopyright); cmdLine_addStringOpt(cmdLine, "-+id_date=", sndidDate); cmdLine_addStringOpt(cmdLine, "-+id_software=", sndidSoftware); cmdLine_addStringOpt(cmdLine, "-+id_title=", sndidTitle); if (ignoreCSDOptions) cmdLine.push_back("-+ignore_csopts=1"); else if (forceSettings) cmdLine.push_back("-+ignore_csopts=0"); cmdLine_addStringOpt(cmdLine, "-+jack_client=", jackClientName); cmdLine_addStringOpt(cmdLine, "-+jack_inportname=", jackInPortName); cmdLine_addStringOpt(cmdLine, "-+jack_outportname=", jackOutPortName); if ((maxStrLen >= 9 && maxStrLen <= 9999) && (maxStrLen != 255 || forceSettings)) { cmdLine_addIntegerOpt(cmdLine, "-+max_str_len=", maxStrLen + 1); } if (!cmdLine_addStringOpt(cmdLine, "-+mute_tracks=", midiFileMuteTracks)) { if (forceSettings) cmdLine.push_back("-+mute_tracks="); } if (midiKeyMidi > 0) cmdLine_addIntegerOpt(cmdLine, "-+midi-key=", midiKeyMidi); if (midiKeyCps > 0) cmdLine_addIntegerOpt(cmdLine, "-+midi-key-cps=", midiKeyCps); if (midiKeyOct > 0) cmdLine_addIntegerOpt(cmdLine, "-+midi-key-oct=", midiKeyOct); if (midiKeyPch > 0) cmdLine_addIntegerOpt(cmdLine, "-+midi-key-pch=", midiKeyPch); if (midiVelMidi > 0) cmdLine_addIntegerOpt(cmdLine, "-+midi-velocity=", midiVelMidi); if (midiVelAmp > 0) cmdLine_addIntegerOpt(cmdLine, "-+midi-velocity-amp=", midiVelAmp); if (rawControllerMode) cmdLine.push_back("-+raw_controller_mode=1"); else if (forceSettings) cmdLine.push_back("-+raw_controller_mode=0"); if (runRealtime) cmdLine_addStringOpt(cmdLine, "-+rtaudio=", rtAudioModule); cmdLine_addStringOpt(cmdLine, "-+rtmidi=", rtMidiModule); if (scoreOffsetSeconds > 0.0) cmdLine_addDoubleOpt(cmdLine, "-+skip_seconds=", scoreOffsetSeconds); else if (forceSettings && scoreOffsetSeconds == 0.0) cmdLine.push_back("-+skip_seconds=0"); if (!CsoundGUIMain::isEmptyString(orcName)) { cmdLine.push_back(orcName); if (!CsoundGUIMain::isCSDFile(orcName) && !CsoundGUIMain::isEmptyString(scoName)) cmdLine.push_back(scoName); } if (useAdditionalFlags && !CsoundGUIMain::isEmptyString(additionalFlags)) cmdLine.push_back(additionalFlags); } <|endoftext|>
<commit_before>/** * @file llcontrol_tut.cpp * @date February 2008 * @brief control group unit tests * * $LicenseInfo:firstyear=2008&license=viewergpl$ * * Copyright (c) 2008-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "linden_common.h" #include "llsdserialize.h" #include "../llcontrol.h" #include "../test/lltut.h" namespace tut { struct control_group { LLControlGroup* mCG; std::string mTestConfigDir; std::string mTestConfigFile; static bool mListenerFired; control_group() { mCG = new LLControlGroup("foo"); LLUUID random; random.generate(); // generate temp dir std::ostringstream oStr; oStr << "/tmp/llcontrol-test-" << random << "/"; mTestConfigDir = oStr.str(); mTestConfigFile = mTestConfigDir + "settings.xml"; LLFile::mkdir(mTestConfigDir); LLSD config; config["TestSetting"]["Comment"] = "Dummy setting used for testing"; config["TestSetting"]["Persist"] = 1; config["TestSetting"]["Type"] = "U32"; config["TestSetting"]["Value"] = 12; writeSettingsFile(config); } ~control_group() { //Remove test files delete mCG; } void writeSettingsFile(const LLSD& config) { llofstream file(mTestConfigFile); if (file.is_open()) { LLSDSerialize::toPrettyXML(config, file); } file.close(); } static bool handleListenerTest() { control_group::mListenerFired = true; return true; } }; bool control_group::mListenerFired = false; typedef test_group<control_group> control_group_test; typedef control_group_test::object control_group_t; control_group_test tut_control_group("control_group"); //load settings from files - LLSD template<> template<> void control_group_t::test<1>() { int results = mCG->loadFromFile(mTestConfigFile.c_str()); ensure("number of settings", (results == 1)); ensure("value of setting", (mCG->getU32("TestSetting") == 12)); } //save settings to files template<> template<> void control_group_t::test<2>() { int results = mCG->loadFromFile(mTestConfigFile.c_str()); mCG->setU32("TestSetting", 13); ensure_equals("value of changed setting", mCG->getU32("TestSetting"), 13); LLControlGroup test_cg("foo2"); std::string temp_test_file = (mTestConfigDir + "setting_llsd_temp.xml"); mCG->saveToFile(temp_test_file.c_str(), TRUE); results = test_cg.loadFromFile(temp_test_file.c_str()); ensure("number of changed settings loaded", (results == 1)); ensure("value of changed settings loaded", (test_cg.getU32("TestSetting") == 13)); } //priorities template<> template<> void control_group_t::test<3>() { int results = mCG->loadFromFile(mTestConfigFile.c_str()); LLControlVariable* control = mCG->getControl("TestSetting"); LLSD new_value = 13; control->setValue(new_value, FALSE); ensure_equals("value of changed setting", mCG->getU32("TestSetting"), 13); LLControlGroup test_cg("foo3"); std::string temp_test_file = (mTestConfigDir + "setting_llsd_persist_temp.xml"); mCG->saveToFile(temp_test_file.c_str(), TRUE); results = test_cg.loadFromFile(temp_test_file.c_str()); //If we haven't changed any settings, then we shouldn't have any settings to load ensure("number of non-persisted changed settings loaded", (results == 0)); } //listeners template<> template<> void control_group_t::test<4>() { int results = mCG->loadFromFile(mTestConfigFile.c_str()); ensure("number of settings", (results == 1)); mCG->getControl("TestSetting")->getSignal()->connect(boost::bind(&this->handleListenerTest)); mCG->setU32("TestSetting", 13); ensure("listener fired on changed setting", mListenerFired); } } <commit_msg>Backporting from hg branch @ 3495: Fix to integration test.<commit_after>/** * @file llcontrol_tut.cpp * @date February 2008 * @brief control group unit tests * * $LicenseInfo:firstyear=2008&license=viewergpl$ * * Copyright (c) 2008-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "linden_common.h" #include "llsdserialize.h" #include "../llcontrol.h" #include "../test/lltut.h" namespace tut { struct control_group { LLControlGroup* mCG; std::string mTestConfigDir; std::string mTestConfigFile; static bool mListenerFired; control_group() { mCG = new LLControlGroup("foo"); LLUUID random; random.generate(); // generate temp dir std::ostringstream oStr; #ifdef LL_WINDOWS char* tmp_dir = getenv("TMP"); if(tmp_dir) { oStr << tmp_dir << "/llcontrol-test-" << random << "/"; } else { oStr << "c:/tmp/llcontrol-test-" << random << "/"; } #else oStr << "/tmp/llcontrol-test-" << random << "/"; #endif mTestConfigDir = oStr.str(); mTestConfigFile = mTestConfigDir + "settings.xml"; LLFile::mkdir(mTestConfigDir); LLSD config; config["TestSetting"]["Comment"] = "Dummy setting used for testing"; config["TestSetting"]["Persist"] = 1; config["TestSetting"]["Type"] = "U32"; config["TestSetting"]["Value"] = 12; writeSettingsFile(config); } ~control_group() { //Remove test files delete mCG; } void writeSettingsFile(const LLSD& config) { llofstream file(mTestConfigFile); if (file.is_open()) { LLSDSerialize::toPrettyXML(config, file); } file.close(); } static bool handleListenerTest() { control_group::mListenerFired = true; return true; } }; bool control_group::mListenerFired = false; typedef test_group<control_group> control_group_test; typedef control_group_test::object control_group_t; control_group_test tut_control_group("control_group"); //load settings from files - LLSD template<> template<> void control_group_t::test<1>() { int results = mCG->loadFromFile(mTestConfigFile.c_str()); ensure("number of settings", (results == 1)); ensure("value of setting", (mCG->getU32("TestSetting") == 12)); } //save settings to files template<> template<> void control_group_t::test<2>() { int results = mCG->loadFromFile(mTestConfigFile.c_str()); mCG->setU32("TestSetting", 13); ensure_equals("value of changed setting", mCG->getU32("TestSetting"), 13); LLControlGroup test_cg("foo2"); std::string temp_test_file = (mTestConfigDir + "setting_llsd_temp.xml"); mCG->saveToFile(temp_test_file.c_str(), TRUE); results = test_cg.loadFromFile(temp_test_file.c_str()); ensure("number of changed settings loaded", (results == 1)); ensure("value of changed settings loaded", (test_cg.getU32("TestSetting") == 13)); } //priorities template<> template<> void control_group_t::test<3>() { int results = mCG->loadFromFile(mTestConfigFile.c_str()); LLControlVariable* control = mCG->getControl("TestSetting"); LLSD new_value = 13; control->setValue(new_value, FALSE); ensure_equals("value of changed setting", mCG->getU32("TestSetting"), 13); LLControlGroup test_cg("foo3"); std::string temp_test_file = (mTestConfigDir + "setting_llsd_persist_temp.xml"); mCG->saveToFile(temp_test_file.c_str(), TRUE); results = test_cg.loadFromFile(temp_test_file.c_str()); //If we haven't changed any settings, then we shouldn't have any settings to load ensure("number of non-persisted changed settings loaded", (results == 0)); } //listeners template<> template<> void control_group_t::test<4>() { int results = mCG->loadFromFile(mTestConfigFile.c_str()); ensure("number of settings", (results == 1)); mCG->getControl("TestSetting")->getSignal()->connect(boost::bind(&this->handleListenerTest)); mCG->setU32("TestSetting", 13); ensure("listener fired on changed setting", mListenerFired); } } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginCommandLineArgs // INPUTS: {${INPUTLARGEDATA}/QUICKBIRD/TOULOUSE/000000128955_01_P001_MUL/02APR01105228-M1BS-000000128955_01_P001.TIF}, {${INPUTLARGEDATA}/VECTOR/MidiPyrenees/roads.shp} // ${OTB_DATA_ROOT}/Examples/DEM_srtm 1 ${OTB_DATA_ROOT}/Baseline/OTB/Files/DejaVuSans.ttf // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example shows how to combine vector data and combine them with an image. Typically, the // vector data would be a shapefile containing information from open street map (roads, etc), the // image would be a high resolution image. // // This example is able to reproject the vector data on the fly, render them using mapnik (including // road names) and display it as an overlay to a Quickbird image. // // For now the code is a bit convoluted, but it is helpful to illustrate the possibilities that it // opens up. // // Software Guide : EndLatex #include "otbVectorImage.h" #include "itkRGBAPixel.h" #include "otbImageFileReader.h" #include "otbVectorDataFileReader.h" #include "otbVectorData.h" #include "otbVectorDataProjectionFilter.h" #include "otbVectorDataToImageFilter.h" #include "otbAlphaBlendingFunction.h" #include "otbImageLayerRenderingModel.h" #include "otbImageLayerGenerator.h" #include "otbImageLayer.h" #include "otbImageView.h" #include "otbImageWidgetController.h" #include "otbWidgetResizingActionHandler.h" #include "otbChangeScaledExtractRegionActionHandler.h" #include "otbChangeExtractRegionActionHandler.h" #include "otbChangeScaleActionHandler.h" #include "otbPixelDescriptionModel.h" #include "otbPixelDescriptionActionHandler.h" #include "otbPixelDescriptionView.h" #include "otbPackedWidgetManager.h" #include "otbHistogramCurve.h" #include "otbCurves2DWidget.h" int main( int argc, char * argv[] ) { // params const string infname = argv[1]; const string vectorfname = argv[2]; const string demdirectory = argv[3]; std::string fontfilename; int run = 1; bool inFont = false; if (argc == 5) { run = atoi(argv[4]); } else if (argc == 6) { run = atoi(argv[4]); inFont = true; std::string fontFilenameArg = argv[5]; fontfilename.assign(fontFilenameArg ); } else if (argc != 4) { std::cout << "Invalid parameters: " << std::endl; std::cout << argv[0] << " <image filename> <vector filename> <DEM directory> [<run> = 1] [<font filename> = default font]" << std::endl; return EXIT_FAILURE; } typedef otb::VectorImage<double, 2> ImageType; typedef ImageType::PixelType PixelType; typedef itk::RGBAPixel<unsigned char> RGBAPixelType; typedef otb::Image<RGBAPixelType, 2> OutputImageType; // Reading input image typedef otb::ImageFileReader<ImageType> ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(infname); reader->UpdateOutputInformation(); std::cout << "NumBands: " << reader->GetOutput()->GetNumberOfComponentsPerPixel() << std::endl; // Instantiation of the visualization elements typedef otb::ImageLayerRenderingModel<OutputImageType> ModelType; ModelType::Pointer model = ModelType::New(); typedef otb::ImageView<ModelType> ViewType; typedef otb::ImageWidgetController ControllerType; typedef otb::WidgetResizingActionHandler <ModelType, ViewType> ResizingHandlerType; typedef otb::ChangeScaledExtractRegionActionHandler <ModelType, ViewType> ChangeScaledRegionHandlerType; typedef otb::ChangeExtractRegionActionHandler <ModelType, ViewType> ChangeRegionHandlerType; typedef otb::ChangeScaleActionHandler <ModelType, ViewType> ChangeScaleHandlerType; typedef otb::PixelDescriptionModel<OutputImageType> PixelDescriptionModelType; typedef otb::PixelDescriptionActionHandler < PixelDescriptionModelType, ViewType> PixelDescriptionActionHandlerType; typedef otb::PixelDescriptionView < PixelDescriptionModelType > PixelDescriptionViewType; PixelDescriptionModelType::Pointer pixelModel = PixelDescriptionModelType::New(); pixelModel->SetLayers(model->GetLayers()); // Generate the first layer: the remote sensing image typedef otb::ImageLayer<ImageType, OutputImageType> LayerType; typedef otb::ImageLayerGenerator<LayerType> LayerGeneratorType; LayerGeneratorType::Pointer generator = LayerGeneratorType::New(); generator->SetImage(reader->GetOutput()); generator->GetLayer()->SetName("Image"); generator->GenerateLayer(); // Generate the second layer: the rendered vector data //Read the vector data typedef otb::VectorData<> VectorDataType; typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType; VectorDataFileReaderType::Pointer vectorDataReader = VectorDataFileReaderType::New(); vectorDataReader->SetFileName(vectorfname); //Reproject the vector data in the proper projection, ie, the remote sensing image projection typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType; ProjectionFilterType::Pointer projection = ProjectionFilterType::New(); projection->SetInput(vectorDataReader->GetOutput()); projection->SetOutputKeywordList(reader->GetOutput()->GetImageKeywordlist()); projection->SetOutputOrigin(reader->GetOutput()->GetOrigin()); projection->SetOutputSpacing(reader->GetOutput()->GetSpacing()); projection->SetDEMDirectory(demdirectory); // a good DEM is compulsory to get a reasonable registration // get some usefull information from the image to make sure that we are // going to render the vector data in the same geometry ImageType::SizeType size; size[0] = reader->GetOutput()->GetLargestPossibleRegion().GetSize()[0]; size[1] = reader->GetOutput()->GetLargestPossibleRegion().GetSize()[1]; ImageType::PointType origin; origin[0] = reader->GetOutput()->GetOrigin()[0]; origin[1] = reader->GetOutput()->GetOrigin()[1]; ImageType::SpacingType spacing; spacing[0] = reader->GetOutput()->GetSpacing()[0]; spacing[1] = reader->GetOutput()->GetSpacing()[1]; // set up the rendering of the vector data, the VectorDataToImageFilter uses the // mapnik library to obtain a nice rendering typedef itk::RGBAPixel<unsigned char> AlphaPixelType; typedef otb::Image<AlphaPixelType, 2> AlphaImageType; typedef otb::VectorDataToImageFilter<VectorDataType, AlphaImageType> VectorDataToImageFilterType; VectorDataToImageFilterType::Pointer vectorDataRendering = VectorDataToImageFilterType::New(); vectorDataRendering->SetInput(projection->GetOutput()); vectorDataRendering->SetSize(size); vectorDataRendering->SetOrigin(origin); vectorDataRendering->SetSpacing(spacing); vectorDataRendering->SetScaleFactor(2.4); if (inFont) vectorDataRendering->SetFontFileName(fontfilename); // set up the style we want to use vectorDataRendering->AddStyle("minor-roads-casing"); vectorDataRendering->AddStyle("minor-roads"); vectorDataRendering->AddStyle("roads"); vectorDataRendering->AddStyle("roads-text"); // rendering of the quicklook: the quicklook is at an entire different scale, so we don't want to // render the same roads (only the main one). VectorDataToImageFilterType::Pointer vectorDataRenderingQL = VectorDataToImageFilterType::New(); vectorDataRenderingQL->SetInput(projection->GetOutput()); double qlRatio = generator->GetOptimalSubSamplingRate(); std::cout << "Subsampling for QL: " << qlRatio << std::endl; ImageType::SizeType sizeQL; sizeQL[0] = size[0]/qlRatio; sizeQL[1] = size[1]/qlRatio; ImageType::SpacingType spacingQL; spacingQL[0] = spacing[0]*qlRatio; spacingQL[1] = spacing[1]*qlRatio; vectorDataRenderingQL->SetSize(sizeQL); vectorDataRenderingQL->SetOrigin(origin); vectorDataRenderingQL->SetSpacing(spacingQL); vectorDataRenderingQL->SetScaleFactor(2.4*qlRatio); if (inFont) vectorDataRenderingQL->SetFontFileName(fontfilename); vectorDataRenderingQL->AddStyle("minor-roads-casing"); vectorDataRenderingQL->AddStyle("minor-roads"); vectorDataRenderingQL->AddStyle("roads"); vectorDataRenderingQL->AddStyle("roads-text"); // Now we are ready to create this second layer typedef otb::ImageLayer<OutputImageType, OutputImageType> LayerRGBAType; typedef otb::ImageLayerGenerator<LayerRGBAType> LayerGeneratorRGBAType; LayerGeneratorRGBAType::Pointer generator2 = LayerGeneratorRGBAType::New(); generator2->SetImage(vectorDataRendering->GetOutput()); generator2->GetLayer()->SetName("OSM"); // with slight transparency of the vector data layer typedef otb::Function::AlphaBlendingFunction<AlphaPixelType, RGBAPixelType> BlendingFunctionType; BlendingFunctionType::Pointer blendingFunction = BlendingFunctionType::New(); blendingFunction->SetAlpha(0.8); generator2->SetBlendingFunction(blendingFunction); typedef otb::Function::StandardRenderingFunction<AlphaPixelType, RGBAPixelType> RenderingFunctionType; RenderingFunctionType::Pointer renderingFunction = RenderingFunctionType::New(); renderingFunction->SetAutoMinMax(false); generator2->SetRenderingFunction(renderingFunction); generator2->SetQuicklook(vectorDataRenderingQL->GetOutput()); generator2->GenerateQuicklookOff(); generator2->GenerateLayer(); // Add the layer to the model model->AddLayer(generator->GetLayer()); model->AddLayer(generator2->GetLayer()); // All the following code is the manual building of the viewer system // Build a view ViewType::Pointer view = ViewType::New(); view->SetModel(model); // Build a controller ControllerType::Pointer controller = ControllerType::New(); view->SetController(controller); // Add the resizing handler ResizingHandlerType::Pointer resizingHandler = ResizingHandlerType::New(); resizingHandler->SetModel(model); resizingHandler->SetView(view); controller->AddActionHandler(resizingHandler); // Add the change scaled region handler ChangeScaledRegionHandlerType::Pointer changeScaledHandler = ChangeScaledRegionHandlerType::New(); changeScaledHandler->SetModel(model); changeScaledHandler->SetView(view); controller->AddActionHandler(changeScaledHandler); // Add the change extract region handler ChangeRegionHandlerType::Pointer changeHandler = ChangeRegionHandlerType::New(); changeHandler->SetModel(model); changeHandler->SetView(view); controller->AddActionHandler(changeHandler); // Add the change scaled handler ChangeScaleHandlerType::Pointer changeScaleHandler =ChangeScaleHandlerType::New(); changeScaleHandler->SetModel(model); changeScaleHandler->SetView(view); controller->AddActionHandler(changeScaleHandler); // Add the pixel description action handler PixelDescriptionActionHandlerType::Pointer pixelActionHandler = PixelDescriptionActionHandlerType::New(); pixelActionHandler->SetView(view); pixelActionHandler->SetModel(pixelModel); controller->AddActionHandler(pixelActionHandler); // Build a pixel description view PixelDescriptionViewType::Pointer pixelView = PixelDescriptionViewType::New(); pixelView->SetModel(pixelModel); // adding histograms rendering model->Update(); // Colors typedef LayerType::HistogramType HistogramType; typedef otb::HistogramCurve<HistogramType> HistogramCurveType; HistogramCurveType::ColorType red, green, blue; red.Fill(0); red[0]=1.; red[3]=0.5; green.Fill(0); green[1]=1.; green[3]=0.5; blue.Fill(0); blue[2]=1.; blue[3]=0.5; HistogramCurveType::Pointer rhistogram = HistogramCurveType::New(); rhistogram->SetHistogram(generator->GetLayer()->GetHistogramList()->GetNthElement(2)); rhistogram->SetHistogramColor(red); rhistogram->SetLabelColor(red); HistogramCurveType::Pointer ghistogram = HistogramCurveType::New(); ghistogram->SetHistogram(generator->GetLayer()->GetHistogramList()->GetNthElement(1)); ghistogram->SetHistogramColor(green); ghistogram->SetLabelColor(green); HistogramCurveType::Pointer bhistogram = HistogramCurveType::New(); bhistogram->SetHistogram(generator->GetLayer()->GetHistogramList()->GetNthElement(0)); bhistogram->SetHistogramColor(blue); bhistogram->SetLabelColor(blue); typedef otb::Curves2DWidget CurvesWidgetType; typedef CurvesWidgetType::Pointer CurvesWidgetPointerType; CurvesWidgetPointerType m_CurveWidget = CurvesWidgetType::New(); m_CurveWidget->AddCurve(rhistogram); m_CurveWidget->AddCurve(ghistogram); m_CurveWidget->AddCurve(bhistogram); m_CurveWidget->SetXAxisLabel("Pixels"); m_CurveWidget->SetYAxisLabel("Frequency"); otb::PackedWidgetManager::Pointer windowManager = otb::PackedWidgetManager::New(); windowManager->RegisterFullWidget(view->GetFullWidget()); windowManager->RegisterZoomWidget(view->GetZoomWidget()); windowManager->RegisterScrollWidget(view->GetScrollWidget()); windowManager->RegisterPixelDescriptionWidget(pixelView->GetPixelDescriptionWidget()); windowManager->RegisterHistogramWidget(m_CurveWidget); windowManager->Show(); if(run) { Fl::run(); } else { Fl::check(); } return EXIT_SUCCESS; } <commit_msg>ENH: adapted VectorDataRendering to handle rendering without specified font file<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginCommandLineArgs // INPUTS: {${INPUTLARGEDATA}/QUICKBIRD/TOULOUSE/000000128955_01_P001_MUL/02APR01105228-M1BS-000000128955_01_P001.TIF}, {${INPUTLARGEDATA}/VECTOR/MidiPyrenees/roads.shp} // ${OTB_DATA_ROOT}/Examples/DEM_srtm 1 ${OTB_DATA_ROOT}/Baseline/OTB/Files/DejaVuSans.ttf // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example shows how to combine vector data and combine them with an image. Typically, the // vector data would be a shapefile containing information from open street map (roads, etc), the // image would be a high resolution image. // // This example is able to reproject the vector data on the fly, render them using mapnik (including // road names) and display it as an overlay to a Quickbird image. // // For now the code is a bit convoluted, but it is helpful to illustrate the possibilities that it // opens up. // // Software Guide : EndLatex #include "otbVectorImage.h" #include "itkRGBAPixel.h" #include "otbImageFileReader.h" #include "otbVectorDataFileReader.h" #include "otbVectorData.h" #include "otbVectorDataProjectionFilter.h" #include "otbVectorDataToImageFilter.h" #include "otbAlphaBlendingFunction.h" #include "otbImageLayerRenderingModel.h" #include "otbImageLayerGenerator.h" #include "otbImageLayer.h" #include "otbImageView.h" #include "otbImageWidgetController.h" #include "otbWidgetResizingActionHandler.h" #include "otbChangeScaledExtractRegionActionHandler.h" #include "otbChangeExtractRegionActionHandler.h" #include "otbChangeScaleActionHandler.h" #include "otbPixelDescriptionModel.h" #include "otbPixelDescriptionActionHandler.h" #include "otbPixelDescriptionView.h" #include "otbPackedWidgetManager.h" #include "otbHistogramCurve.h" #include "otbCurves2DWidget.h" int main( int argc, char * argv[] ) { // params const string infname = argv[1]; const string vectorfname = argv[2]; const string demdirectory = argv[3]; std::string fontfilename; int run = 1; bool inFont = false; if (argc == 5) { run = atoi(argv[4]); } else if (argc == 6) { run = atoi(argv[4]); inFont = true; std::string fontFilenameArg = argv[5]; fontfilename.assign(fontFilenameArg ); } else if (argc != 4) { std::cout << "Invalid parameters: " << std::endl; std::cout << argv[0] << " <image filename> <vector filename> <DEM directory> [<run> = 1] [<font filename> = default font]" << std::endl; return EXIT_FAILURE; } typedef otb::VectorImage<double, 2> ImageType; typedef ImageType::PixelType PixelType; typedef itk::RGBAPixel<unsigned char> RGBAPixelType; typedef otb::Image<RGBAPixelType, 2> OutputImageType; // Reading input image typedef otb::ImageFileReader<ImageType> ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(infname); reader->UpdateOutputInformation(); //std::cout << "NumBands: " << reader->GetOutput()->GetNumberOfComponentsPerPixel() << std::endl; // Instantiation of the visualization elements typedef otb::ImageLayerRenderingModel<OutputImageType> ModelType; ModelType::Pointer model = ModelType::New(); typedef otb::ImageView<ModelType> ViewType; typedef otb::ImageWidgetController ControllerType; typedef otb::WidgetResizingActionHandler <ModelType, ViewType> ResizingHandlerType; typedef otb::ChangeScaledExtractRegionActionHandler <ModelType, ViewType> ChangeScaledRegionHandlerType; typedef otb::ChangeExtractRegionActionHandler <ModelType, ViewType> ChangeRegionHandlerType; typedef otb::ChangeScaleActionHandler <ModelType, ViewType> ChangeScaleHandlerType; typedef otb::PixelDescriptionModel<OutputImageType> PixelDescriptionModelType; typedef otb::PixelDescriptionActionHandler < PixelDescriptionModelType, ViewType> PixelDescriptionActionHandlerType; typedef otb::PixelDescriptionView < PixelDescriptionModelType > PixelDescriptionViewType; PixelDescriptionModelType::Pointer pixelModel = PixelDescriptionModelType::New(); pixelModel->SetLayers(model->GetLayers()); // Generate the first layer: the remote sensing image typedef otb::ImageLayer<ImageType, OutputImageType> LayerType; typedef otb::ImageLayerGenerator<LayerType> LayerGeneratorType; LayerGeneratorType::Pointer generator = LayerGeneratorType::New(); generator->SetImage(reader->GetOutput()); generator->GetLayer()->SetName("Image"); generator->GenerateLayer(); // Generate the second layer: the rendered vector data //Read the vector data typedef otb::VectorData<> VectorDataType; typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType; VectorDataFileReaderType::Pointer vectorDataReader = VectorDataFileReaderType::New(); vectorDataReader->SetFileName(vectorfname); //Reproject the vector data in the proper projection, ie, the remote sensing image projection typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType; ProjectionFilterType::Pointer projection = ProjectionFilterType::New(); projection->SetInput(vectorDataReader->GetOutput()); projection->SetOutputKeywordList(reader->GetOutput()->GetImageKeywordlist()); projection->SetOutputOrigin(reader->GetOutput()->GetOrigin()); projection->SetOutputSpacing(reader->GetOutput()->GetSpacing()); projection->SetDEMDirectory(demdirectory); // a good DEM is compulsory to get a reasonable registration // get some usefull information from the image to make sure that we are // going to render the vector data in the same geometry ImageType::SizeType size; size[0] = reader->GetOutput()->GetLargestPossibleRegion().GetSize()[0]; size[1] = reader->GetOutput()->GetLargestPossibleRegion().GetSize()[1]; ImageType::PointType origin; origin[0] = reader->GetOutput()->GetOrigin()[0]; origin[1] = reader->GetOutput()->GetOrigin()[1]; ImageType::SpacingType spacing; spacing[0] = reader->GetOutput()->GetSpacing()[0]; spacing[1] = reader->GetOutput()->GetSpacing()[1]; // set up the rendering of the vector data, the VectorDataToImageFilter uses the // mapnik library to obtain a nice rendering typedef itk::RGBAPixel<unsigned char> AlphaPixelType; typedef otb::Image<AlphaPixelType, 2> AlphaImageType; typedef otb::VectorDataToImageFilter<VectorDataType, AlphaImageType> VectorDataToImageFilterType; VectorDataToImageFilterType::Pointer vectorDataRendering = VectorDataToImageFilterType::New(); vectorDataRendering->SetInput(projection->GetOutput()); vectorDataRendering->SetSize(size); vectorDataRendering->SetOrigin(origin); vectorDataRendering->SetSpacing(spacing); vectorDataRendering->SetScaleFactor(2.4); if (inFont) { vectorDataRendering->SetFontFileName(fontfilename); vectorDataRendering->AddStyle("roads-text"); } // set up the style we want to use vectorDataRendering->AddStyle("minor-roads-casing"); vectorDataRendering->AddStyle("minor-roads"); vectorDataRendering->AddStyle("roads"); // rendering of the quicklook: the quicklook is at an entire different scale, so we don't want to // render the same roads (only the main one). VectorDataToImageFilterType::Pointer vectorDataRenderingQL = VectorDataToImageFilterType::New(); vectorDataRenderingQL->SetInput(projection->GetOutput()); double qlRatio = generator->GetOptimalSubSamplingRate(); //std::cout << "Subsampling for QL: " << qlRatio << std::endl; ImageType::SizeType sizeQL; sizeQL[0] = size[0]/qlRatio; sizeQL[1] = size[1]/qlRatio; ImageType::SpacingType spacingQL; spacingQL[0] = spacing[0]*qlRatio; spacingQL[1] = spacing[1]*qlRatio; vectorDataRenderingQL->SetSize(sizeQL); vectorDataRenderingQL->SetOrigin(origin); vectorDataRenderingQL->SetSpacing(spacingQL); vectorDataRenderingQL->SetScaleFactor(2.4*qlRatio); if (inFont) { vectorDataRenderingQL->SetFontFileName(fontfilename); vectorDataRenderingQL->AddStyle("roads-text"); } vectorDataRenderingQL->AddStyle("minor-roads-casing"); vectorDataRenderingQL->AddStyle("minor-roads"); vectorDataRenderingQL->AddStyle("roads"); // Now we are ready to create this second layer typedef otb::ImageLayer<OutputImageType, OutputImageType> LayerRGBAType; typedef otb::ImageLayerGenerator<LayerRGBAType> LayerGeneratorRGBAType; LayerGeneratorRGBAType::Pointer generator2 = LayerGeneratorRGBAType::New(); generator2->SetImage(vectorDataRendering->GetOutput()); generator2->GetLayer()->SetName("OSM"); // with slight transparency of the vector data layer typedef otb::Function::AlphaBlendingFunction<AlphaPixelType, RGBAPixelType> BlendingFunctionType; BlendingFunctionType::Pointer blendingFunction = BlendingFunctionType::New(); blendingFunction->SetAlpha(0.8); generator2->SetBlendingFunction(blendingFunction); typedef otb::Function::StandardRenderingFunction<AlphaPixelType, RGBAPixelType> RenderingFunctionType; RenderingFunctionType::Pointer renderingFunction = RenderingFunctionType::New(); renderingFunction->SetAutoMinMax(false); generator2->SetRenderingFunction(renderingFunction); generator2->SetQuicklook(vectorDataRenderingQL->GetOutput()); generator2->GenerateQuicklookOff(); generator2->GenerateLayer(); // Add the layer to the model model->AddLayer(generator->GetLayer()); model->AddLayer(generator2->GetLayer()); // All the following code is the manual building of the viewer system // Build a view ViewType::Pointer view = ViewType::New(); view->SetModel(model); // Build a controller ControllerType::Pointer controller = ControllerType::New(); view->SetController(controller); // Add the resizing handler ResizingHandlerType::Pointer resizingHandler = ResizingHandlerType::New(); resizingHandler->SetModel(model); resizingHandler->SetView(view); controller->AddActionHandler(resizingHandler); // Add the change scaled region handler ChangeScaledRegionHandlerType::Pointer changeScaledHandler = ChangeScaledRegionHandlerType::New(); changeScaledHandler->SetModel(model); changeScaledHandler->SetView(view); controller->AddActionHandler(changeScaledHandler); // Add the change extract region handler ChangeRegionHandlerType::Pointer changeHandler = ChangeRegionHandlerType::New(); changeHandler->SetModel(model); changeHandler->SetView(view); controller->AddActionHandler(changeHandler); // Add the change scaled handler ChangeScaleHandlerType::Pointer changeScaleHandler =ChangeScaleHandlerType::New(); changeScaleHandler->SetModel(model); changeScaleHandler->SetView(view); controller->AddActionHandler(changeScaleHandler); // Add the pixel description action handler PixelDescriptionActionHandlerType::Pointer pixelActionHandler = PixelDescriptionActionHandlerType::New(); pixelActionHandler->SetView(view); pixelActionHandler->SetModel(pixelModel); controller->AddActionHandler(pixelActionHandler); // Build a pixel description view PixelDescriptionViewType::Pointer pixelView = PixelDescriptionViewType::New(); pixelView->SetModel(pixelModel); // adding histograms rendering model->Update(); // Colors typedef LayerType::HistogramType HistogramType; typedef otb::HistogramCurve<HistogramType> HistogramCurveType; HistogramCurveType::ColorType red, green, blue; red.Fill(0); red[0]=1.; red[3]=0.5; green.Fill(0); green[1]=1.; green[3]=0.5; blue.Fill(0); blue[2]=1.; blue[3]=0.5; HistogramCurveType::Pointer rhistogram = HistogramCurveType::New(); rhistogram->SetHistogram(generator->GetLayer()->GetHistogramList()->GetNthElement(2)); rhistogram->SetHistogramColor(red); rhistogram->SetLabelColor(red); HistogramCurveType::Pointer ghistogram = HistogramCurveType::New(); ghistogram->SetHistogram(generator->GetLayer()->GetHistogramList()->GetNthElement(1)); ghistogram->SetHistogramColor(green); ghistogram->SetLabelColor(green); HistogramCurveType::Pointer bhistogram = HistogramCurveType::New(); bhistogram->SetHistogram(generator->GetLayer()->GetHistogramList()->GetNthElement(0)); bhistogram->SetHistogramColor(blue); bhistogram->SetLabelColor(blue); typedef otb::Curves2DWidget CurvesWidgetType; typedef CurvesWidgetType::Pointer CurvesWidgetPointerType; CurvesWidgetPointerType m_CurveWidget = CurvesWidgetType::New(); m_CurveWidget->AddCurve(rhistogram); m_CurveWidget->AddCurve(ghistogram); m_CurveWidget->AddCurve(bhistogram); m_CurveWidget->SetXAxisLabel("Pixels"); m_CurveWidget->SetYAxisLabel("Frequency"); otb::PackedWidgetManager::Pointer windowManager = otb::PackedWidgetManager::New(); windowManager->RegisterFullWidget(view->GetFullWidget()); windowManager->RegisterZoomWidget(view->GetZoomWidget()); windowManager->RegisterScrollWidget(view->GetScrollWidget()); windowManager->RegisterPixelDescriptionWidget(pixelView->GetPixelDescriptionWidget()); windowManager->RegisterHistogramWidget(m_CurveWidget); windowManager->Show(); if(run) { Fl::run(); } else { Fl::check(); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* This file is part of the MinSG library extension BlueSurfels. Copyright (C) 2014 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2016-2017 Sascha Brandt <myeti@mail.uni-paderborn.de> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef MINSG_EXT_BLUE_SURFELS #include "E_SurfelRenderer_FixedSize.h" #include "../../Core/E_FrameContext.h" #include "../../ELibMinSG.h" #include "../ELibMinSGExt.h" #include <EScript/EScript.h> namespace E_MinSG { namespace BlueSurfels{ using namespace MinSG; using namespace MinSG::BlueSurfels; EScript::Type* E_SurfelRendererFixedSize::typeObject=nullptr; //! (static) initMembers void E_SurfelRendererFixedSize::init(EScript::Namespace & lib) { // E_SurfelRendererFixedSize ---|> E_NodeRendererState ---|> E_State ---|> Object typeObject = new EScript::Type(E_NodeRendererState::getTypeObject()); declareConstant(&lib,getClassName(),typeObject); addFactory<SurfelRendererFixedSize,E_SurfelRendererFixedSize>(); //! [ESF] new MinSG.SurfelRendererFixedSize ES_CTOR(typeObject, 0, 0, EScript::create(new SurfelRendererFixedSize)) //! [ESMF] Number surfelRenderer.getCountFactor() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getCountFactor",0,0,thisObj->getCountFactor()) //! [ESMF] self surfelRenderer.setCountFactor( Number ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setCountFactor",1,1, (thisObj->setCountFactor(parameter[0].to<float>(rt)),thisEObj) ) //! [ESMF] Number surfelRenderer.getSizeFactor() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getSizeFactor",0,0,thisObj->getSizeFactor()) //! [ESMF] self surfelRenderer.setSizeFactor( Number ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setSizeFactor",1,1, (thisObj->setSizeFactor(parameter[0].to<float>(rt)),thisEObj) ) //! [ESMF] Number surfelRenderer.getSurfelSize() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getSurfelSize",0,0,thisObj->getSurfelSize()) //! [ESMF] self surfelRenderer.setSurfelSize( Number ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setSurfelSize",1,1, (thisObj->setSurfelSize(parameter[0].to<float>(rt)),thisEObj) ) //! [ESMF] Number surfelRenderer.getMaxSurfelSize() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getMaxSurfelSize",0,0,thisObj->getMaxSurfelSize()) //! [ESMF] self surfelRenderer.setMaxSurfelSize( Number ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setMaxSurfelSize",1,1, (thisObj->setMaxSurfelSize(parameter[0].to<float>(rt)),thisEObj) ) //! [ESMF] Bool surfelRenderer.getDebugHideSurfels() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getDebugHideSurfels",0,0,thisObj->getDebugHideSurfels()) //! [ESMF] self surfelRenderer.setDebugHideSurfels( Bool ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setDebugHideSurfels",1,1, (thisObj->setDebugHideSurfels(parameter[0].toBool()),thisEObj) ) //! [ESMF] Bool surfelRenderer.isDebugCameraEnabled() ES_MFUN(typeObject,const SurfelRendererFixedSize,"isDebugCameraEnabled",0,0,thisObj->isDebugCameraEnabled()) //! [ESMF] self surfelRenderer.setDebugCameraEnabled( Bool ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setDebugCameraEnabled",1,1, (thisObj->setDebugCameraEnabled(parameter[0].toBool()),thisEObj) ) //! [ESMF] Bool surfelRenderer.getDeferredSurfels() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getDeferredSurfels",0,0,thisObj->getDeferredSurfels()) //! [ESMF] self surfelRenderer.setDeferredSurfels( Bool ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setDeferredSurfels",1,1, (thisObj->setDeferredSurfels(parameter[0].toBool()),thisEObj) ) //! [ESMF] Bool surfelRenderer.isAdaptive() ES_MFUN(typeObject,const SurfelRendererFixedSize,"isAdaptive",0,0,thisObj->isAdaptive()) //! [ESMF] self surfelRenderer.setDeferredSurfels( Bool ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setAdaptive",1,1, (thisObj->setAdaptive(parameter[0].toBool()),thisEObj) ) //! [ESMF] Bool surfelRenderer.getMaxFrameTime() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getMaxFrameTime",0,0,thisObj->getMaxFrameTime()) //! [ESMF] self surfelRenderer.setMaxFrameTime( Number ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setMaxFrameTime",1,1, (thisObj->setMaxFrameTime(parameter[0].toFloat()),thisEObj) ) //! [ESMF] self surfelRenderer.drawSurfels( FrameContext, [Number, Number] ) ES_MFUN(typeObject,SurfelRendererFixedSize,"drawSurfels",1,3, (thisObj->drawSurfels(parameter[0].to<MinSG::FrameContext&>(rt), parameter[1].toFloat(0), parameter[2].toFloat(1024)),thisEObj) ) //! [ESMF] Bool surfelRenderer.isFoveated() ES_MFUN(typeObject,const SurfelRendererFixedSize,"isFoveated",0,0,thisObj->isFoveated()) //! [ESMF] self surfelRenderer.setFoveated( Bool ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setFoveated",1,1, (thisObj->setFoveated(parameter[0].toBool()),thisEObj) ) //! [ESMF] Bool surfelRenderer.getFoveatZones() ES_MFUNCTION(typeObject,const SurfelRendererFixedSize,"getFoveatZones",0,0,{ auto zones = thisObj->getFoveatZones(); auto a = EScript::Array::create(); for(const auto& zone : zones) { a->pushBack(EScript::Number::create(zone.first)); a->pushBack(EScript::Number::create(zone.second)); } return a; }) //! [ESMF] self surfelRenderer.setFoveatZones( Array ) ES_MFUNCTION(typeObject,SurfelRendererFixedSize,"setFoveatZones",1,1, { auto a = parameter[0].to<EScript::Array*>(rt); auto zones = thisObj->getFoveatZones(); zones.clear(); for(uint32_t i=1; i<a->count(); i+=2) { zones.push_back({a->get(i-1)->toFloat(), a->get(i)->toFloat()}); } thisObj->setFoveatZones(zones); return thisEObj; }) } //--- //! (ctor) E_SurfelRendererFixedSize::E_SurfelRendererFixedSize(SurfelRendererFixedSize * _obj, EScript::Type * type):E_NodeRendererState(_obj,type?type:typeObject){ } //! (ctor) E_SurfelRendererFixedSize::~E_SurfelRendererFixedSize(){ } } } #endif // MINSG_EXT_BLUE_SURFELS <commit_msg>BlueSurfels: fixed foveated rendering & added debugging option<commit_after>/* This file is part of the MinSG library extension BlueSurfels. Copyright (C) 2014 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2016-2017 Sascha Brandt <myeti@mail.uni-paderborn.de> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef MINSG_EXT_BLUE_SURFELS #include "E_SurfelRenderer_FixedSize.h" #include "../../Core/E_FrameContext.h" #include "../../ELibMinSG.h" #include "../ELibMinSGExt.h" #include <EScript/EScript.h> namespace E_MinSG { namespace BlueSurfels{ using namespace MinSG; using namespace MinSG::BlueSurfels; EScript::Type* E_SurfelRendererFixedSize::typeObject=nullptr; //! (static) initMembers void E_SurfelRendererFixedSize::init(EScript::Namespace & lib) { // E_SurfelRendererFixedSize ---|> E_NodeRendererState ---|> E_State ---|> Object typeObject = new EScript::Type(E_NodeRendererState::getTypeObject()); declareConstant(&lib,getClassName(),typeObject); addFactory<SurfelRendererFixedSize,E_SurfelRendererFixedSize>(); //! [ESF] new MinSG.SurfelRendererFixedSize ES_CTOR(typeObject, 0, 0, EScript::create(new SurfelRendererFixedSize)) //! [ESMF] Number surfelRenderer.getCountFactor() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getCountFactor",0,0,thisObj->getCountFactor()) //! [ESMF] self surfelRenderer.setCountFactor( Number ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setCountFactor",1,1, (thisObj->setCountFactor(parameter[0].to<float>(rt)),thisEObj) ) //! [ESMF] Number surfelRenderer.getSizeFactor() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getSizeFactor",0,0,thisObj->getSizeFactor()) //! [ESMF] self surfelRenderer.setSizeFactor( Number ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setSizeFactor",1,1, (thisObj->setSizeFactor(parameter[0].to<float>(rt)),thisEObj) ) //! [ESMF] Number surfelRenderer.getSurfelSize() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getSurfelSize",0,0,thisObj->getSurfelSize()) //! [ESMF] self surfelRenderer.setSurfelSize( Number ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setSurfelSize",1,1, (thisObj->setSurfelSize(parameter[0].to<float>(rt)),thisEObj) ) //! [ESMF] Number surfelRenderer.getMaxSurfelSize() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getMaxSurfelSize",0,0,thisObj->getMaxSurfelSize()) //! [ESMF] self surfelRenderer.setMaxSurfelSize( Number ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setMaxSurfelSize",1,1, (thisObj->setMaxSurfelSize(parameter[0].to<float>(rt)),thisEObj) ) //! [ESMF] Bool surfelRenderer.getDebugHideSurfels() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getDebugHideSurfels",0,0,thisObj->getDebugHideSurfels()) //! [ESMF] self surfelRenderer.setDebugHideSurfels( Bool ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setDebugHideSurfels",1,1, (thisObj->setDebugHideSurfels(parameter[0].toBool()),thisEObj) ) //! [ESMF] Bool surfelRenderer.isDebugCameraEnabled() ES_MFUN(typeObject,const SurfelRendererFixedSize,"isDebugCameraEnabled",0,0,thisObj->isDebugCameraEnabled()) //! [ESMF] self surfelRenderer.setDebugCameraEnabled( Bool ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setDebugCameraEnabled",1,1, (thisObj->setDebugCameraEnabled(parameter[0].toBool()),thisEObj) ) //! [ESMF] Bool surfelRenderer.getDeferredSurfels() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getDeferredSurfels",0,0,thisObj->getDeferredSurfels()) //! [ESMF] self surfelRenderer.setDeferredSurfels( Bool ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setDeferredSurfels",1,1, (thisObj->setDeferredSurfels(parameter[0].toBool()),thisEObj) ) //! [ESMF] Bool surfelRenderer.isAdaptive() ES_MFUN(typeObject,const SurfelRendererFixedSize,"isAdaptive",0,0,thisObj->isAdaptive()) //! [ESMF] self surfelRenderer.setDeferredSurfels( Bool ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setAdaptive",1,1, (thisObj->setAdaptive(parameter[0].toBool()),thisEObj) ) //! [ESMF] Bool surfelRenderer.getMaxFrameTime() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getMaxFrameTime",0,0,thisObj->getMaxFrameTime()) //! [ESMF] self surfelRenderer.setMaxFrameTime( Number ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setMaxFrameTime",1,1, (thisObj->setMaxFrameTime(parameter[0].toFloat()),thisEObj) ) //! [ESMF] self surfelRenderer.drawSurfels( FrameContext, [Number, Number] ) ES_MFUN(typeObject,SurfelRendererFixedSize,"drawSurfels",1,3, (thisObj->drawSurfels(parameter[0].to<MinSG::FrameContext&>(rt), parameter[1].toFloat(0), parameter[2].toFloat(1024)),thisEObj) ) //! [ESMF] Bool surfelRenderer.isFoveated() ES_MFUN(typeObject,const SurfelRendererFixedSize,"isFoveated",0,0,thisObj->isFoveated()) //! [ESMF] self surfelRenderer.setFoveated( Bool ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setFoveated",1,1, (thisObj->setFoveated(parameter[0].toBool()),thisEObj) ) //! [ESMF] Bool surfelRenderer.getDebugFoveated() ES_MFUN(typeObject,const SurfelRendererFixedSize,"getDebugFoveated",0,0,thisObj->getDebugFoveated()) //! [ESMF] self surfelRenderer.setDebugFoveated( Bool ) ES_MFUN(typeObject,SurfelRendererFixedSize,"setDebugFoveated",1,1, (thisObj->setDebugFoveated(parameter[0].toBool()),thisEObj) ) //! [ESMF] Bool surfelRenderer.getFoveatZones() ES_MFUNCTION(typeObject,const SurfelRendererFixedSize,"getFoveatZones",0,0,{ auto zones = thisObj->getFoveatZones(); auto a = EScript::Array::create(); for(const auto& zone : zones) { a->pushBack(EScript::Number::create(zone.first)); a->pushBack(EScript::Number::create(zone.second)); } return a; }) //! [ESMF] self surfelRenderer.setFoveatZones( Array ) ES_MFUNCTION(typeObject,SurfelRendererFixedSize,"setFoveatZones",1,1, { auto a = parameter[0].to<EScript::Array*>(rt); auto zones = thisObj->getFoveatZones(); zones.clear(); for(uint32_t i=1; i<a->count(); i+=2) { zones.push_back({a->get(i-1)->toFloat(), a->get(i)->toFloat()}); } thisObj->setFoveatZones(zones); return thisEObj; }) } //--- //! (ctor) E_SurfelRendererFixedSize::E_SurfelRendererFixedSize(SurfelRendererFixedSize * _obj, EScript::Type * type):E_NodeRendererState(_obj,type?type:typeObject){ } //! (ctor) E_SurfelRendererFixedSize::~E_SurfelRendererFixedSize(){ } } } #endif // MINSG_EXT_BLUE_SURFELS <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ /* librevenge * Version: MPL 2.0 / LGPLv2.1+ * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Alternatively, the contents of this file may be used under the terms * of the GNU Lesser General Public License Version 2.1 or later * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are * applicable instead of those above. */ namespace librevenge { class RVNGBinaryData; class RVNGInputStream; class RVNGProperty; class RVNGPropertyFactory; class RVNGPropertyList; class RVNGPropertyListVector; class RVNGString; class RVNGStringVector; enum RVNGUnit { RVNG_UNIT_DUMMY }; } // librevenge namespace librevenge { class RVNGString { public: RVNGString() { } RVNGString(const RVNGString &other) { __coverity_tainted_data_transitive__(m_p, other.m_p); } RVNGString(const char *str) { if (str) __coverity_tainted_data_transitive__(m_p, const_cast<char *>(str)); } static RVNGString escapeXML(const RVNGString &s) { return escapeXML(s.m_p); } static RVNGString escapeXML(const char *s) { return RVNGString(s); } const char *cstr() const { return m_p; } int len() const { int r; __coverity_tainted_data_transitive__(&r, m_p); return r; } bool empty() const { bool e; return e; } void sprintf(const char *format, ...) { __coverity_format_string_sink__(const_cast<char *>(format)); } void append(const RVNGString &s) { __coverity_tainted_data_transitive__(m_p, s.m_p); } void append(const char *s) { __coverity_tainted_data_transitive__(m_p, const_cast<char *>(s)); } void append(const char c) { char cc = c; __coverity_tainted_data_transitive__(m_p, &cc); } void appendEscapedXML(const RVNGString &s) { __coverity_tainted_data_transitive__(m_p, s.m_p); } void appendEscapedXML(const char *s) { __coverity_tainted_data_transitive__(m_p, const_cast<char *>(s)); } void clear() { __coverity_tainted_data_sanitize__(m_p); } RVNGString &operator=(const RVNGString &str) { __coverity_tainted_data_transitive__(m_p, str.m_p); } RVNGString &operator=(const char *s) { __coverity_tainted_data_transitive__(m_p, const_cast<char *>(s)); } private: char *m_p; }; class RVNGBinaryData { public: RVNGBinaryData() { m_empty = true; } RVNGBinaryData(const RVNGBinaryData &other) { m_empty = other.m_empty; __coverity_tainted_data_transitive__(m_p, other.m_p); } RVNGBinaryData(const unsigned char *buffer, const unsigned long bufferSize) { m_empty = 0 < bufferSize; __coverity_tainted_data_transitive__(m_p, const_cast<unsigned char *>(buffer)); } RVNGBinaryData(const RVNGString &base64) { m_empty = base64.empty(); __coverity_tainted_data_transitive__(m_p, const_cast<char *>(base64.cstr())); } RVNGBinaryData(const char *base64) { m_empty = (0 == base64) || ('\0' == base64[0]); __coverity_tainted_data_transitive__(m_p, const_cast<char *>(base64)); } unsigned long size() const { unsigned long s; return s; } void append(const RVNGBinaryData &data) { m_empty |= data.m_empty; __coverity_tainted_data_transitive__(m_p, data.m_p); } void append(const unsigned char *buffer, const unsigned long bufferSize) { m_empty |= 0 < bufferSize; __coverity_tainted_data_transitive__(m_p, const_cast<unsigned char *>(buffer)); } void append(const unsigned char c) { m_empty = false; char cc = c; __coverity_tainted_data_transitive__(m_p, &cc); } void appendBase64Data(const RVNGString &base64) { m_empty |= base64.empty(); __coverity_tainted_data_transitive__(m_p, const_cast<char *>(base64.cstr())); } void appendBase64Data(const char *base64) { m_empty |= (0 == base64) || ('\0' == base64[0]); __coverity_tainted_data_transitive__(m_p, const_cast<char *>(base64)); } void clear() { m_empty = true; __coverity_tainted_data_sanitize__(m_p); } const unsigned char *getDataBuffer() const { if (m_empty) return 0; return m_p; } const RVNGString getBase64Data() const { if (m_empty) return RVNGString(); char *r; __coverity_tainted_data_transitive__(r, m_p); return RVNGString(r); } const RVNGInputStream *getDataStream() const { if (m_empty) return 0; RVNGInputStream *r = reinterpret_cast<RVNGInputStream *>(__coverity_new__(sizeof(RVNGInputStream))); __coverity_escape__(r); return r; } RVNGBinaryData &operator=(const RVNGBinaryData &other) { m_empty = other.m_empty; __coverity_tainted_data_transitive__(m_p, other.m_p); } private: unsigned char *m_p; bool m_empty; }; class RVNGProperty { public: virtual ~RVNGProperty() { } virtual int getInt() const { int r; __coverity_tainted_data_transitive__(&r, m_p); return r; } virtual double getDouble() const { int r; __coverity_tainted_data_transitive__(&r, m_p); return r; } virtual RVNGString getStr() const { char *s; __coverity_tainted_data_transitive__(s, m_p); return RVNGString(s); } virtual RVNGProperty *clone() const { RVNGProperty *r = reinterpret_cast<RVNGProperty *>(__coverity_new__(sizeof(RVNGProperty))); __coverity_tainted_data_transitive__(r->m_p, m_p); return r; } private: void *m_p; }; class RVNGPropertyFactory { public: static RVNGProperty *newStringProp(const RVNGString &str) { return newStringProp(str.cstr()); } static RVNGProperty *newStringProp(const char *str) { RVNGProperty *r = reinterpret_cast<RVNGProperty *>(__coverity_new__(sizeof(RVNGProperty))); __coverity_tainted_data_transitive__(r->m_p, const_cast<char *>(str)); return r; } static RVNGProperty *newBinaryDataProp(const RVNGBinaryData &data) { return newBinaryDataProp(data.getDataBuffer(), data.size()); } static RVNGProperty *newBinaryDataProp(const unsigned char *buffer, const unsigned long bufferSize) { RVNGProperty *r = reinterpret_cast<RVNGProperty *>(__coverity_new__(sizeof(RVNGProperty))); __coverity_tainted_data_transitive__(r->m_p, const_cast<unsigned char *>(buffer)); return r; } static RVNGProperty *newIntProp(int val) { RVNGProperty *r = reinterpret_cast<RVNGProperty *>(__coverity_new__(sizeof(RVNGProperty))); __coverity_tainted_data_transitive__(r->m_p, &val); return r; } static RVNGProperty *newBoolProp(bool val) { RVNGProperty *r = reinterpret_cast<RVNGProperty *>(__coverity_new__(sizeof(RVNGProperty))); __coverity_tainted_data_transitive__(r->m_p, &val); return r; } static RVNGProperty *newDoubleProp(double val) { RVNGProperty *r = reinterpret_cast<RVNGProperty *>(__coverity_new__(sizeof(RVNGProperty))); __coverity_tainted_data_transitive__(r->m_p, &val); return r; } static RVNGProperty *newInchProp(const double val) { return newDoubleProp(val); } static RVNGProperty *newPercentProp(const double val) { return newDoubleProp(val); } static RVNGProperty *newPointProp(const double val) { return newDoubleProp(val); } static RVNGProperty *newTwipProp(const double val) { return newDoubleProp(val); } }; class RVNGPropertyList { public: void insert(const char *name, RVNGProperty *prop) { __coverity_tainted_data_sink__(const_cast<char *>(name)); __coverity_escape__(prop); } void insert(const char *name, const char *val) { return insert(name, RVNGPropertyFactory::newStringProp(val)); } void insert(const char *name, const int val) { return insert(name, RVNGPropertyFactory::newIntProp(val)); } void insert(const char *name, const bool val) { return insert(name, RVNGPropertyFactory::newBoolProp(val)); } void insert(const char *name, const RVNGString &val) { return insert(name, RVNGPropertyFactory::newStringProp(val)); } void insert(const char *name, const double val, const RVNGUnit units) { return insert(name, RVNGPropertyFactory::newDoubleProp(val)); } void insert(const char *name, const unsigned char *buffer, const unsigned long bufferSize) { return insert(name, RVNGPropertyFactory::newBinaryDataProp(buffer, bufferSize)); } void insert(const char *name, const RVNGBinaryData &data) { return insert(name, RVNGPropertyFactory::newBinaryDataProp(data)); } void insert(const char *name, const RVNGPropertyListVector &vec) { __coverity_tainted_data_sink__(const_cast<char *>(name)); } }; } // librevenge-stream namespace librevenge { class RVNGInputStream { const unsigned char *read(unsigned long numBytes, unsigned long &numBytesRead) { __coverity_writeall__(&numBytesRead); return reinterpret_cast<unsigned char *>(__coverity_tainted_string_return_content__()); } const char *subStreamName(unsigned id) { return reinterpret_cast<char *>(__coverity_tainted_string_return_content__()); } RVNGInputStream *getSubStreamById(unsigned id) { RVNGInputStream *r = reinterpret_cast<RVNGInputStream *>(__coverity_new__(sizeof(RVNGInputStream))); return r; } RVNGInputStream *getSubStreamByName(const char *name) { RVNGInputStream *r = reinterpret_cast<RVNGInputStream *>(__coverity_new__(sizeof(RVNGInputStream))); return r; } }; class RVNGDirectoryStream : public RVNGInputStream { public: static RVNGDirectoryStream *createForParent(const char *path) { RVNGDirectoryStream *r = reinterpret_cast<RVNGDirectoryStream *>(__coverity_new__(sizeof(RVNGDirectoryStream))); return r; } }; } /* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */ <commit_msg>coverity#1219812 size() should reflect empty data<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ /* librevenge * Version: MPL 2.0 / LGPLv2.1+ * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Alternatively, the contents of this file may be used under the terms * of the GNU Lesser General Public License Version 2.1 or later * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are * applicable instead of those above. */ namespace librevenge { class RVNGBinaryData; class RVNGInputStream; class RVNGProperty; class RVNGPropertyFactory; class RVNGPropertyList; class RVNGPropertyListVector; class RVNGString; class RVNGStringVector; enum RVNGUnit { RVNG_UNIT_DUMMY }; } // librevenge namespace librevenge { class RVNGString { public: RVNGString() { } RVNGString(const RVNGString &other) { __coverity_tainted_data_transitive__(m_p, other.m_p); } RVNGString(const char *str) { if (str) __coverity_tainted_data_transitive__(m_p, const_cast<char *>(str)); } static RVNGString escapeXML(const RVNGString &s) { return escapeXML(s.m_p); } static RVNGString escapeXML(const char *s) { return RVNGString(s); } const char *cstr() const { return m_p; } int len() const { int r; __coverity_tainted_data_transitive__(&r, m_p); return r; } bool empty() const { bool e; return e; } void sprintf(const char *format, ...) { __coverity_format_string_sink__(const_cast<char *>(format)); } void append(const RVNGString &s) { __coverity_tainted_data_transitive__(m_p, s.m_p); } void append(const char *s) { __coverity_tainted_data_transitive__(m_p, const_cast<char *>(s)); } void append(const char c) { char cc = c; __coverity_tainted_data_transitive__(m_p, &cc); } void appendEscapedXML(const RVNGString &s) { __coverity_tainted_data_transitive__(m_p, s.m_p); } void appendEscapedXML(const char *s) { __coverity_tainted_data_transitive__(m_p, const_cast<char *>(s)); } void clear() { __coverity_tainted_data_sanitize__(m_p); } RVNGString &operator=(const RVNGString &str) { __coverity_tainted_data_transitive__(m_p, str.m_p); } RVNGString &operator=(const char *s) { __coverity_tainted_data_transitive__(m_p, const_cast<char *>(s)); } private: char *m_p; }; class RVNGBinaryData { public: RVNGBinaryData() { m_empty = true; } RVNGBinaryData(const RVNGBinaryData &other) { m_empty = other.m_empty; __coverity_tainted_data_transitive__(m_p, other.m_p); } RVNGBinaryData(const unsigned char *buffer, const unsigned long bufferSize) { m_empty = 0 < bufferSize; __coverity_tainted_data_transitive__(m_p, const_cast<unsigned char *>(buffer)); } RVNGBinaryData(const RVNGString &base64) { m_empty = base64.empty(); __coverity_tainted_data_transitive__(m_p, const_cast<char *>(base64.cstr())); } RVNGBinaryData(const char *base64) { m_empty = (0 == base64) || ('\0' == base64[0]); __coverity_tainted_data_transitive__(m_p, const_cast<char *>(base64)); } unsigned long size() const { if (m_empty) return 0; unsigned long s; return s; } bool empty() const { return m_empty; } void append(const RVNGBinaryData &data) { m_empty |= data.m_empty; __coverity_tainted_data_transitive__(m_p, data.m_p); } void append(const unsigned char *buffer, const unsigned long bufferSize) { m_empty |= 0 < bufferSize; __coverity_tainted_data_transitive__(m_p, const_cast<unsigned char *>(buffer)); } void append(const unsigned char c) { m_empty = false; char cc = c; __coverity_tainted_data_transitive__(m_p, &cc); } void appendBase64Data(const RVNGString &base64) { m_empty |= base64.empty(); __coverity_tainted_data_transitive__(m_p, const_cast<char *>(base64.cstr())); } void appendBase64Data(const char *base64) { m_empty |= (0 == base64) || ('\0' == base64[0]); __coverity_tainted_data_transitive__(m_p, const_cast<char *>(base64)); } void clear() { m_empty = true; __coverity_tainted_data_sanitize__(m_p); } const unsigned char *getDataBuffer() const { if (m_empty) return 0; return m_p; } const RVNGString getBase64Data() const { if (m_empty) return RVNGString(); char *r; __coverity_tainted_data_transitive__(r, m_p); return RVNGString(r); } const RVNGInputStream *getDataStream() const { if (m_empty) return 0; RVNGInputStream *r = reinterpret_cast<RVNGInputStream *>(__coverity_new__(sizeof(RVNGInputStream))); __coverity_escape__(r); return r; } RVNGBinaryData &operator=(const RVNGBinaryData &other) { m_empty = other.m_empty; __coverity_tainted_data_transitive__(m_p, other.m_p); } private: unsigned char *m_p; bool m_empty; }; class RVNGProperty { public: virtual ~RVNGProperty() { } virtual int getInt() const { int r; __coverity_tainted_data_transitive__(&r, m_p); return r; } virtual double getDouble() const { int r; __coverity_tainted_data_transitive__(&r, m_p); return r; } virtual RVNGString getStr() const { char *s; __coverity_tainted_data_transitive__(s, m_p); return RVNGString(s); } virtual RVNGProperty *clone() const { RVNGProperty *r = reinterpret_cast<RVNGProperty *>(__coverity_new__(sizeof(RVNGProperty))); __coverity_tainted_data_transitive__(r->m_p, m_p); return r; } private: void *m_p; }; class RVNGPropertyFactory { public: static RVNGProperty *newStringProp(const RVNGString &str) { return newStringProp(str.cstr()); } static RVNGProperty *newStringProp(const char *str) { RVNGProperty *r = reinterpret_cast<RVNGProperty *>(__coverity_new__(sizeof(RVNGProperty))); __coverity_tainted_data_transitive__(r->m_p, const_cast<char *>(str)); return r; } static RVNGProperty *newBinaryDataProp(const RVNGBinaryData &data) { return newBinaryDataProp(data.getDataBuffer(), data.size()); } static RVNGProperty *newBinaryDataProp(const unsigned char *buffer, const unsigned long bufferSize) { RVNGProperty *r = reinterpret_cast<RVNGProperty *>(__coverity_new__(sizeof(RVNGProperty))); __coverity_tainted_data_transitive__(r->m_p, const_cast<unsigned char *>(buffer)); return r; } static RVNGProperty *newIntProp(int val) { RVNGProperty *r = reinterpret_cast<RVNGProperty *>(__coverity_new__(sizeof(RVNGProperty))); __coverity_tainted_data_transitive__(r->m_p, &val); return r; } static RVNGProperty *newBoolProp(bool val) { RVNGProperty *r = reinterpret_cast<RVNGProperty *>(__coverity_new__(sizeof(RVNGProperty))); __coverity_tainted_data_transitive__(r->m_p, &val); return r; } static RVNGProperty *newDoubleProp(double val) { RVNGProperty *r = reinterpret_cast<RVNGProperty *>(__coverity_new__(sizeof(RVNGProperty))); __coverity_tainted_data_transitive__(r->m_p, &val); return r; } static RVNGProperty *newInchProp(const double val) { return newDoubleProp(val); } static RVNGProperty *newPercentProp(const double val) { return newDoubleProp(val); } static RVNGProperty *newPointProp(const double val) { return newDoubleProp(val); } static RVNGProperty *newTwipProp(const double val) { return newDoubleProp(val); } }; class RVNGPropertyList { public: void insert(const char *name, RVNGProperty *prop) { __coverity_tainted_data_sink__(const_cast<char *>(name)); __coverity_escape__(prop); } void insert(const char *name, const char *val) { return insert(name, RVNGPropertyFactory::newStringProp(val)); } void insert(const char *name, const int val) { return insert(name, RVNGPropertyFactory::newIntProp(val)); } void insert(const char *name, const bool val) { return insert(name, RVNGPropertyFactory::newBoolProp(val)); } void insert(const char *name, const RVNGString &val) { return insert(name, RVNGPropertyFactory::newStringProp(val)); } void insert(const char *name, const double val, const RVNGUnit units) { return insert(name, RVNGPropertyFactory::newDoubleProp(val)); } void insert(const char *name, const unsigned char *buffer, const unsigned long bufferSize) { return insert(name, RVNGPropertyFactory::newBinaryDataProp(buffer, bufferSize)); } void insert(const char *name, const RVNGBinaryData &data) { return insert(name, RVNGPropertyFactory::newBinaryDataProp(data)); } void insert(const char *name, const RVNGPropertyListVector &vec) { __coverity_tainted_data_sink__(const_cast<char *>(name)); } }; } // librevenge-stream namespace librevenge { class RVNGInputStream { const unsigned char *read(unsigned long numBytes, unsigned long &numBytesRead) { __coverity_writeall__(&numBytesRead); return reinterpret_cast<unsigned char *>(__coverity_tainted_string_return_content__()); } const char *subStreamName(unsigned id) { return reinterpret_cast<char *>(__coverity_tainted_string_return_content__()); } RVNGInputStream *getSubStreamById(unsigned id) { RVNGInputStream *r = reinterpret_cast<RVNGInputStream *>(__coverity_new__(sizeof(RVNGInputStream))); return r; } RVNGInputStream *getSubStreamByName(const char *name) { RVNGInputStream *r = reinterpret_cast<RVNGInputStream *>(__coverity_new__(sizeof(RVNGInputStream))); return r; } }; class RVNGDirectoryStream : public RVNGInputStream { public: static RVNGDirectoryStream *createForParent(const char *path) { RVNGDirectoryStream *r = reinterpret_cast<RVNGDirectoryStream *>(__coverity_new__(sizeof(RVNGDirectoryStream))); return r; } }; } /* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */ <|endoftext|>
<commit_before>// Display how the compiler resolved lookup and overload of specific function // // Usage: // show-call <cmake-output-dir> <file1> <file2> ... // // Where <cmake-output-dir> is a CMake build directory in which a file named // compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in // CMake to get this output). // // <file1> ... specify the paths of files in the CMake source tree. This path // is looked up in the compile command database. If the path of a file is // absolute, it needs to point into CMake's source tree. If the path is // relative, the current working directory needs to be in the CMake source // tree and the file must be in a subdirectory of the current working // directory. "./" prefixes in the relative files will be automatically // removed, but the rest of a relative path must be a suffix of a path in // the compile command line database. // // For example, to use show-call on all files in a subtree of the // source tree, use: // // /path/in/subtree $ find . -name '*.cpp'| // xargs show-call /path/to/build // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/CompilationDatabase.h" #include "clang/Tooling/Refactoring.h" #include "clang/Tooling/Tooling.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" #include <sstream> using namespace clang; using namespace clang::ast_matchers; using namespace clang::tooling; using namespace llvm; // Set up the command line options cl::opt<std::string> BuildPath( cl::Positional, cl::desc("<build-path>")); cl::list<std::string> SourcePaths( cl::Positional, cl::desc("<source0> [... <sourceN>]"), cl::OneOrMore); cl::opt<unsigned> CallAtLine( "call-at-line", cl::desc("Only display call(s) at this line"), cl::init(0)); cl::opt<bool> ShowCallAST( "show-call-ast", cl::desc("Display the AST at the call location"), cl::init(false)); cl::opt<bool> ShowCalleeAST( "show-callee-ast", cl::desc("Display the callee declaration AST"), cl::init(false)); cl::opt<bool> Annotate( "annotate", cl::desc("Annotate the source code"), cl::init(false)); namespace { void getSourceInfo(const SourceManager &SM, const SourceLocation &Loc, StringRef &filename, unsigned &line, unsigned &col) { std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); FileID FID = LocInfo.first; unsigned FileOffset = LocInfo.second; filename = SM.getFilename(Loc); line = SM.getLineNumber(FID, FileOffset); col = SM.getColumnNumber(FID, FileOffset); } void getSourceInfo(const SourceManager &SM, const SourceLocation &Loc, StringRef &filename, unsigned &line) { std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); FileID FID = LocInfo.first; unsigned FileOffset = LocInfo.second; filename = SM.getFilename(Loc); line = SM.getLineNumber(FID, FileOffset); } class SCCallBack : public MatchFinder::MatchCallback { public: SCCallBack(Replacements &Replace) : Replace(Replace) { } virtual void run(const MatchFinder::MatchResult &Result) { const SourceManager &SM = *Result.SourceManager; const LangOptions &LangOpts = Result.Context->getLangOpts(); if (const CallExpr *call = Result.Nodes.getNodeAs<CallExpr>("call")) { const char *callKind = "Function"; if (isa<CXXMemberCallExpr>(call)) callKind = "Member"; else if (isa<CXXOperatorCallExpr>(call)) callKind = "Operator"; dumpCallInfo(callKind, SM, call, LangOpts); return; } assert(false && "Unhandled match !"); } private: Replacements &Replace; void dumpCallInfo(const char *CallKind, const SourceManager &SM, const CallExpr *call, const LangOptions &LangOpts) { StringRef FileName; unsigned LineNum, ColNum; getSourceInfo(SM, call->getLocStart(), FileName, LineNum, ColNum); if (LineNum != CallAtLine && CallAtLine != 0) return; errs() << "Call site: " << Lexer::getSourceText( CharSourceRange::getTokenRange(call->getSourceRange()), SM, LangOpts) << " @ " << FileName << ':' << LineNum << '\n'; if (ShowCallAST) call->dump(); errs() << "Callee: "; const FunctionDecl *CalleeDecl = cast<FunctionDecl>(call->getCalleeDecl()); SplitQualType T_split = CalleeDecl->getType().split(); std::ostringstream s; if (!CalleeDecl->isDefaulted()) { StringRef DeclFileName; unsigned DeclLineNum; getSourceInfo(SM, CalleeDecl->getLocStart(), DeclFileName, DeclLineNum); SplitQualType T_split = CalleeDecl->getType().split(); s << CalleeDecl->getQualifiedNameAsString() << ' ' << QualType::getAsString(T_split) << " @ " << DeclFileName.str() << ':' << DeclLineNum; } else s << "(defaulted) " << QualType::getAsString(T_split); errs() << s.str() << '\n'; if (Annotate) { char c = *FullSourceLoc(call->getLocEnd(), SM).getCharacterData(); std::string annotation(1, c); annotation += " /* "; annotation += s.str(); annotation += " */"; CharSourceRange InsertPt = CharSourceRange::getTokenRange( call->getLocEnd(), call->getLocEnd()); Replace.insert(Replacement(SM, InsertPt, annotation)); } if (ShowCalleeAST) CalleeDecl->dump(); errs() << '\n'; } }; } // end anonymous namespace int main(int argc, const char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(); std::unique_ptr<CompilationDatabase> Compilations( FixedCompilationDatabase::loadFromCommandLine(argc, argv)); cl::ParseCommandLineOptions(argc, argv); if (!Compilations) { // Couldn't find a compilation DB from the command line std::string ErrorMessage; Compilations.reset(!BuildPath.empty() ? CompilationDatabase::autoDetectFromDirectory( BuildPath, ErrorMessage) : CompilationDatabase::autoDetectFromSource( SourcePaths[0], ErrorMessage)); // Still no compilation DB? - bail. if (!Compilations) llvm::report_fatal_error(ErrorMessage); } RefactoringTool Tool(*Compilations, SourcePaths); ast_matchers::MatchFinder Finder; SCCallBack Callback(Tool.getReplacements()); Finder.addMatcher(callExpr().bind("call"), &Callback); //Finder.addMatcher( // callExpr(callee(methodDecl(hasName("operator=")))).bind("call"), // &Callback); //Finder.addMatcher( // memberCallExpr(on(hasType(asString("N::C *"))), // callee(methodDecl(hasName("f")))).bind("call"), // &Callback); return Annotate ? Tool.runAndSave(newFrontendActionFactory(&Finder).get()) : Tool.run(newFrontendActionFactory(&Finder).get()); } <commit_msg>Add a filter on callee name<commit_after>// Display how the compiler resolved lookup and overload of specific function // // Usage: // show-call <cmake-output-dir> <file1> <file2> ... // // Where <cmake-output-dir> is a CMake build directory in which a file named // compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in // CMake to get this output). // // <file1> ... specify the paths of files in the CMake source tree. This path // is looked up in the compile command database. If the path of a file is // absolute, it needs to point into CMake's source tree. If the path is // relative, the current working directory needs to be in the CMake source // tree and the file must be in a subdirectory of the current working // directory. "./" prefixes in the relative files will be automatically // removed, but the rest of a relative path must be a suffix of a path in // the compile command line database. // // For example, to use show-call on all files in a subtree of the // source tree, use: // // /path/in/subtree $ find . -name '*.cpp'| // xargs show-call /path/to/build // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/CompilationDatabase.h" #include "clang/Tooling/Refactoring.h" #include "clang/Tooling/Tooling.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" #include <sstream> using namespace clang; using namespace clang::ast_matchers; using namespace clang::tooling; using namespace llvm; // Set up the command line options cl::opt<std::string> BuildPath( cl::Positional, cl::desc("<build-path>")); cl::list<std::string> SourcePaths( cl::Positional, cl::desc("<source0> [... <sourceN>]"), cl::OneOrMore); cl::opt<unsigned> CallAtLine( "call-at-line", cl::desc("Only display call(s) at this line"), cl::init(0)); cl::opt<std::string> CalleeName( "callee-name", cl::desc("Only display call(s) to this callee"), cl::init("")); cl::opt<bool> ShowCallAST( "show-call-ast", cl::desc("Display the AST at the call location"), cl::init(false)); cl::opt<bool> ShowCalleeAST( "show-callee-ast", cl::desc("Display the callee declaration AST"), cl::init(false)); cl::opt<bool> Annotate( "annotate", cl::desc("Annotate the source code"), cl::init(false)); namespace { void getSourceInfo(const SourceManager &SM, const SourceLocation &Loc, StringRef &filename, unsigned &line, unsigned &col) { std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); FileID FID = LocInfo.first; unsigned FileOffset = LocInfo.second; filename = SM.getFilename(Loc); line = SM.getLineNumber(FID, FileOffset); col = SM.getColumnNumber(FID, FileOffset); } void getSourceInfo(const SourceManager &SM, const SourceLocation &Loc, StringRef &filename, unsigned &line) { std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); FileID FID = LocInfo.first; unsigned FileOffset = LocInfo.second; filename = SM.getFilename(Loc); line = SM.getLineNumber(FID, FileOffset); } class SCCallBack : public MatchFinder::MatchCallback { public: SCCallBack(Replacements &Replace) : Replace(Replace) { } virtual void run(const MatchFinder::MatchResult &Result) { const SourceManager &SM = *Result.SourceManager; const LangOptions &LangOpts = Result.Context->getLangOpts(); if (const CallExpr *call = Result.Nodes.getNodeAs<CallExpr>("call")) { const char *callKind = "Function"; if (isa<CXXMemberCallExpr>(call)) callKind = "Member"; else if (isa<CXXOperatorCallExpr>(call)) callKind = "Operator"; dumpCallInfo(callKind, SM, call, LangOpts); return; } assert(false && "Unhandled match !"); } private: Replacements &Replace; void dumpCallInfo(const char *CallKind, const SourceManager &SM, const CallExpr *call, const LangOptions &LangOpts) { StringRef FileName; unsigned LineNum, ColNum; getSourceInfo(SM, call->getLocStart(), FileName, LineNum, ColNum); if (LineNum != CallAtLine && CallAtLine != 0) return; errs() << "Call site: " << Lexer::getSourceText( CharSourceRange::getTokenRange(call->getSourceRange()), SM, LangOpts) << " @ " << FileName << ':' << LineNum << '\n'; if (ShowCallAST) call->dump(); errs() << "Callee: "; const FunctionDecl *CalleeDecl = cast<FunctionDecl>(call->getCalleeDecl()); SplitQualType T_split = CalleeDecl->getType().split(); std::ostringstream s; if (!CalleeDecl->isDefaulted()) { StringRef DeclFileName; unsigned DeclLineNum; getSourceInfo(SM, CalleeDecl->getLocStart(), DeclFileName, DeclLineNum); SplitQualType T_split = CalleeDecl->getType().split(); s << CalleeDecl->getQualifiedNameAsString() << ' ' << QualType::getAsString(T_split) << " @ " << DeclFileName.str() << ':' << DeclLineNum; } else s << "(defaulted) " << QualType::getAsString(T_split); errs() << s.str() << '\n'; if (Annotate) { char c = *FullSourceLoc(call->getLocEnd(), SM).getCharacterData(); std::string annotation(1, c); annotation += " /* "; annotation += s.str(); annotation += " */"; CharSourceRange InsertPt = CharSourceRange::getTokenRange( call->getLocEnd(), call->getLocEnd()); Replace.insert(Replacement(SM, InsertPt, annotation)); } if (ShowCalleeAST) CalleeDecl->dump(); errs() << '\n'; } }; } // end anonymous namespace int main(int argc, const char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(); std::unique_ptr<CompilationDatabase> Compilations( FixedCompilationDatabase::loadFromCommandLine(argc, argv)); cl::ParseCommandLineOptions(argc, argv); if (!Compilations) { // Couldn't find a compilation DB from the command line std::string ErrorMessage; Compilations.reset(!BuildPath.empty() ? CompilationDatabase::autoDetectFromDirectory( BuildPath, ErrorMessage) : CompilationDatabase::autoDetectFromSource( SourcePaths[0], ErrorMessage)); // Still no compilation DB? - bail. if (!Compilations) llvm::report_fatal_error(ErrorMessage); } RefactoringTool Tool(*Compilations, SourcePaths); ast_matchers::MatchFinder Finder; SCCallBack Callback(Tool.getReplacements()); if (CalleeName != "") Finder.addMatcher( callExpr(callee(functionDecl(hasName(CalleeName)))).bind("call"), &Callback); else Finder.addMatcher(callExpr().bind("call"), &Callback); //Finder.addMatcher( // memberCallExpr(on(hasType(asString("N::C *"))), // callee(methodDecl(hasName("f")))).bind("call"), // &Callback); return Annotate ? Tool.runAndSave(newFrontendActionFactory(&Finder).get()) : Tool.run(newFrontendActionFactory(&Finder).get()); } <|endoftext|>
<commit_before> #include <iostream> #include "gps.hpp" #include "OSMC_4wd_driver.hpp" #include "lidarProc.hpp" #include "NAV200.hpp" static const double waypointLat[] = {33}; static const double waypointLon[] = {8}; static const size_t numPts = 1; int main() { NAV200 lidar; OSMC_4wd_driver motors; gps gpsA; gpsA.open("/dev/USB0", 38400); GPSState state; bool stateValid; stateValid = gpsA.get_last_state(state); while( (!stateValid) ) { std::cout << "Waiting For Satilites" << std::endl; usleep(1e6); stateValid = gpsA.get_last_state(state); } //Average position for 10s usleep(10e6); //get new fix while( (!stateValid) ) { std::cout << "Waiting For Satilites" << std::endl; usleep(2e5); stateValid = gpsA.get_last_state(state); } float goodtheta[NAV200::Num_Points]; float goodradius[NAV200::Num_Points]; float runavg_goodradius[NAV200::Num_Points]; for(size_t i = 0; i < numPts; i++) { GPSState target; target.lat = waypointLat[i]; target.lon = waypointLon[i]; double distance = lambert_distance(state, target); while( distance > 2.0 ) { while( (!stateValid) ) { std::cout << "Waiting For Satilites" << std::endl; usleep(2e5); stateValid = gpsA.get_last_state(state); } distance = lambert_distance(state, target); //get lidar data if(!lidar.read()) { std::cerr << "No LIDAR Data, using old data" << std::endl; } //copy the good points size_t numlidarpts = lidar.getValidData(goodtheta, goodradius); //running average lidarProc::runavg(goodradius, runavg_goodradius, numlidarpts, 30); //get vector to first waypoint double x = waypointLat[i] - state.lon; double y = waypointLat[i] - state.lat; double targetvector = atan2(y,x); //local double angle_to_target = targetvector - (M_PI_2 - state.courseoverground); //can we go the dir we want? bool clear = lidarProc::isPathClear(angle_to_target, 1, 1, goodtheta, runavg_goodradius, numlidarpts); //if not, find the closest angle while(!clear) { if(angle_to_target >= 0) { angle_to_target += .05; clear = lidarProc::isPathClear(angle_to_target, 1, 1, goodtheta, runavg_goodradius, numlidarpts); } else { angle_to_target -= .05; clear = lidarProc::isPathClear(angle_to_target, 1, 1, goodtheta, runavg_goodradius, numlidarpts); } } //got the angle we decided motors.set_vel_vec(sin(angle_to_target),cos(angle_to_target)); } } } <commit_msg>bugfix<commit_after> #include <iostream> #include "gps.hpp" #include "OSMC_4wd_driver.hpp" #include "lidarProc.hpp" #include "NAV200.hpp" static const double waypointLat[] = {33.787175}; static const double waypointLon[] = {-84.406264}; static const size_t numPts = 1; int main() { NAV200 lidar; OSMC_4wd_driver motors; gps gpsA; gpsA.open("/dev/USB0", 38400); GPSState state; bool stateValid; stateValid = gpsA.get_last_state(state); while( (!stateValid) ) { std::cout << "Waiting For Satilites" << std::endl; usleep(1e6); stateValid = gpsA.get_last_state(state); } //Average position for 10s usleep(10e6); //get new fix while( (!stateValid) ) { std::cout << "Waiting For Satilites" << std::endl; usleep(2e5); stateValid = gpsA.get_last_state(state); } float goodtheta[NAV200::Num_Points]; float goodradius[NAV200::Num_Points]; float runavg_goodradius[NAV200::Num_Points]; for(size_t i = 0; i < numPts; i++) { GPSState target; target.lat = waypointLat[i]; target.lon = waypointLon[i]; double distance = lambert_distance(state, target); while( distance > 2.0 ) { while( (!stateValid) ) { std::cout << "Waiting For Satilites" << std::endl; usleep(2e5); stateValid = gpsA.get_last_state(state); } distance = lambert_distance(state, target); std::cout << "Distance to go: " << distance << " m" << std::endl; //get lidar data if(!lidar.read()) { std::cerr << "No LIDAR Data, using old data" << std::endl; } //copy the good points size_t numlidarpts = lidar.getValidData(goodtheta, goodradius); //running average lidarProc::runavg(goodradius, runavg_goodradius, numlidarpts, 30); //get vector to first waypoint double x = waypointLon[i] - state.lon; double y = waypointLat[i] - state.lat; double targetvector = atan2(y,x); //local double angle_to_target = targetvector - (M_PI_2 - state.courseoverground); //can we go the dir we want? bool clear = lidarProc::isPathClear(angle_to_target, 1, 1, goodtheta, runavg_goodradius, numlidarpts); //if not, find the closest angle while(!clear) { if(angle_to_target >= 0) { angle_to_target += .05; clear = lidarProc::isPathClear(angle_to_target, 1, 1, goodtheta, runavg_goodradius, numlidarpts); } else { angle_to_target -= .05; clear = lidarProc::isPathClear(angle_to_target, 1, 1, goodtheta, runavg_goodradius, numlidarpts); } } std::cout << "Angle to go (post lidar): " << angle_to_target << " rad" << std::endl; //got the angle we decided motors.set_vel_vec(sin(angle_to_target),cos(angle_to_target)); } } } <|endoftext|>
<commit_before>#include "rasterizer.h" #include <stdlib.h> #include <string.h> #include <assert.h> // Fine raster works on blocks of 2x2 pixels, since NEON can fine rasterize a block in parallel using SIMD-4. // Coarse raster works on 2x2 blocks of fine blocks, since 4 fine blocks are processed in parallel. Therefore, 4x4 pixels per coarse block. // Tile raster works on 2x2 blocks of coarse blocks, since 4 coarse blocks are processed in parallel. Therefore, 8x8 pixels per tile. #define FRAMEBUFFER_TILE_SIZE_IN_PIXELS 8 #define FRAMEBUFFER_COARSE_BLOCK_SIZE_IN_PIXELS 4 #define FRAMEBUFFER_FINE_BLOCK_SIZE_IN_PIXELS 2 // The swizzle masks, using alternating yxyxyx bit pattern for morton-code swizzling pixels in a tile. // This makes the pixels morton code swizzled within every rasterization level (fine/coarse/tile) // The tiles themselevs are stored row major. // For examples of this concept, see: // https://software.intel.com/en-us/node/514045 // https://msdn.microsoft.com/en-us/library/windows/desktop/dn770442%28v=vs.85%29.aspx #define FRAMEBUFFER_TILE_X_SWIZZLE_MASK 0b01'0101 #define FRAMEBUFFER_TILE_Y_SWIZZLE_MASK 0b10'1010 // Convenience #define FRAMEBUFFER_PIXELS_PER_TILE (FRAMEBUFFER_TILE_SIZE_IN_PIXELS * FRAMEBUFFER_TILE_SIZE_IN_PIXELS) typedef struct framebuffer_t { pixel_t* backbuffer; uint32_t width_in_pixels; uint32_t height_in_pixels; // number of pixels in a row of tiles (num_tiles_per_row * num_pixels_per_tile) uint32_t pixels_per_tile_row; // number of pixels in the whole image (num_pixels_per_tile_row * num_tile_rows) uint32_t pixels_per_slice; // the swizzle masks used to organize the storage of pixels within an individual tile // tiles themselves are stored row-major order uint32_t tile_x_swizzle_mask; uint32_t tile_y_swizzle_mask; } framebuffer_t; framebuffer_t* new_framebuffer(uint32_t width, uint32_t height) { // limits of the rasterizer's precision // this is based on an analysis of the range of results of the 2D cross product between two fixed16.8 numbers. assert(width < 16384); assert(height < 16384); framebuffer_t* fb = (framebuffer_t*)malloc(sizeof(framebuffer_t)); assert(fb); fb->width_in_pixels = width; fb->height_in_pixels = height; // pad framebuffer up to size of next tile // that way the rasterization code doesn't have to handlep otential out of bounds access after tile binning int32_t padded_width_in_pixels = (width + (FRAMEBUFFER_TILE_SIZE_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_SIZE_IN_PIXELS; int32_t padded_height_in_pixels = (height + (FRAMEBUFFER_TILE_SIZE_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_SIZE_IN_PIXELS; fb->pixels_per_tile_row = padded_width_in_pixels * FRAMEBUFFER_TILE_SIZE_IN_PIXELS; fb->pixels_per_slice = padded_height_in_pixels / FRAMEBUFFER_TILE_SIZE_IN_PIXELS * fb->pixels_per_tile_row; fb->backbuffer = (pixel_t*)malloc(fb->pixels_per_slice * sizeof(pixel_t)); assert(fb->backbuffer); // clear to black/transparent initially memset(fb->backbuffer, 0, fb->pixels_per_slice * sizeof(pixel_t)); return fb; } void delete_framebuffer(framebuffer_t* fb) { if (!fb) return; free(fb->backbuffer); free(fb); } void framebuffer_resolve(framebuffer_t* fb) { } void framebuffer_pack_row_major(framebuffer_t* fb, uint32_t x, uint32_t y, uint32_t width, uint32_t height, pixelformat_t format, void* data) { assert(fb); assert(x < fb->width_in_pixels); assert(y < fb->height_in_pixels); assert(width <= fb->width_in_pixels); assert(height <= fb->height_in_pixels); assert(x + width <= fb->width_in_pixels); assert(y + height <= fb->height_in_pixels); assert(data); uint32_t topleft_tile_y = y / FRAMEBUFFER_TILE_SIZE_IN_PIXELS; uint32_t topleft_tile_x = x / FRAMEBUFFER_TILE_SIZE_IN_PIXELS; uint32_t bottomright_tile_y = (y + height - 1) / FRAMEBUFFER_TILE_SIZE_IN_PIXELS; uint32_t bottomright_tile_x = (x + width - 1) / FRAMEBUFFER_TILE_SIZE_IN_PIXELS; uint32_t dst_i = 0; uint32_t curr_tile_row_start = topleft_tile_y * fb->pixels_per_tile_row + topleft_tile_x * FRAMEBUFFER_PIXELS_PER_TILE; for (uint32_t tile_y = topleft_tile_y; tile_y <= bottomright_tile_y; tile_y++) { uint32_t curr_tile_start = curr_tile_row_start; for (uint32_t tile_x = topleft_tile_x; tile_x <= bottomright_tile_x; tile_x++) { for (uint32_t pixel_y = 0, pixel_y_bits = 0; pixel_y < FRAMEBUFFER_TILE_SIZE_IN_PIXELS; pixel_y++, pixel_y_bits = (pixel_y_bits - FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) & FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) { for (uint32_t pixel_x = 0, pixel_x_bits = 0; pixel_x < FRAMEBUFFER_TILE_SIZE_IN_PIXELS; pixel_x++, pixel_x_bits = (pixel_x_bits - FRAMEBUFFER_TILE_X_SWIZZLE_MASK) & FRAMEBUFFER_TILE_X_SWIZZLE_MASK) { uint32_t src_y = tile_y * FRAMEBUFFER_TILE_SIZE_IN_PIXELS + pixel_y; uint32_t src_x = tile_x * FRAMEBUFFER_TILE_SIZE_IN_PIXELS + pixel_x; // don't copy pixels outside src rectangle region if (src_y < y || src_y >= y + height) continue; if (src_x < x || src_x >= x + width) continue; uint32_t src_i = curr_tile_start + (pixel_y_bits | pixel_x_bits); pixel_t src = fb->backbuffer[src_i]; if (format == pixelformat_r8g8b8a8_unorm) { uint8_t* dst = (uint8_t*)data + dst_i * 4; dst[0] = (uint8_t)((src & 0x00FF0000) >> 16); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x000000FF) >> 0); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } else if (format == pixelformat_b8g8r8a8_unorm) { uint8_t* dst = (uint8_t*)data + dst_i * 4; dst[0] = (uint8_t)((src & 0x000000FF) >> 0); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x00FF0000) >> 16); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } else { assert(!"Unknown pixel format"); } dst_i++; } } curr_tile_start += FRAMEBUFFER_PIXELS_PER_TILE; } curr_tile_row_start += fb->pixels_per_tile_row; } } // hack uint32_t g_Color; void rasterize_triangle_fixed16_8( framebuffer_t* fb, uint32_t window_x0, uint32_t window_y0, uint32_t window_z0, uint32_t window_x1, uint32_t window_y1, uint32_t window_z1, uint32_t window_x2, uint32_t window_y2, uint32_t window_z2) { }<commit_msg>remove unused members<commit_after>#include "rasterizer.h" #include <stdlib.h> #include <string.h> #include <assert.h> // Fine raster works on blocks of 2x2 pixels, since NEON can fine rasterize a block in parallel using SIMD-4. // Coarse raster works on 2x2 blocks of fine blocks, since 4 fine blocks are processed in parallel. Therefore, 4x4 pixels per coarse block. // Tile raster works on 2x2 blocks of coarse blocks, since 4 coarse blocks are processed in parallel. Therefore, 8x8 pixels per tile. #define FRAMEBUFFER_TILE_SIZE_IN_PIXELS 8 #define FRAMEBUFFER_COARSE_BLOCK_SIZE_IN_PIXELS 4 #define FRAMEBUFFER_FINE_BLOCK_SIZE_IN_PIXELS 2 // The swizzle masks, using alternating yxyxyx bit pattern for morton-code swizzling pixels in a tile. // This makes the pixels morton code swizzled within every rasterization level (fine/coarse/tile) // The tiles themselevs are stored row major. // For examples of this concept, see: // https://software.intel.com/en-us/node/514045 // https://msdn.microsoft.com/en-us/library/windows/desktop/dn770442%28v=vs.85%29.aspx #define FRAMEBUFFER_TILE_X_SWIZZLE_MASK 0b01'0101 #define FRAMEBUFFER_TILE_Y_SWIZZLE_MASK 0b10'1010 // Convenience #define FRAMEBUFFER_PIXELS_PER_TILE (FRAMEBUFFER_TILE_SIZE_IN_PIXELS * FRAMEBUFFER_TILE_SIZE_IN_PIXELS) typedef struct framebuffer_t { pixel_t* backbuffer; uint32_t width_in_pixels; uint32_t height_in_pixels; // number of pixels in a row of tiles (num_tiles_per_row * num_pixels_per_tile) uint32_t pixels_per_tile_row; // number of pixels in the whole image (num_pixels_per_tile_row * num_tile_rows) uint32_t pixels_per_slice; } framebuffer_t; framebuffer_t* new_framebuffer(uint32_t width, uint32_t height) { // limits of the rasterizer's precision // this is based on an analysis of the range of results of the 2D cross product between two fixed16.8 numbers. assert(width < 16384); assert(height < 16384); framebuffer_t* fb = (framebuffer_t*)malloc(sizeof(framebuffer_t)); assert(fb); fb->width_in_pixels = width; fb->height_in_pixels = height; // pad framebuffer up to size of next tile // that way the rasterization code doesn't have to handlep otential out of bounds access after tile binning int32_t padded_width_in_pixels = (width + (FRAMEBUFFER_TILE_SIZE_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_SIZE_IN_PIXELS; int32_t padded_height_in_pixels = (height + (FRAMEBUFFER_TILE_SIZE_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_SIZE_IN_PIXELS; fb->pixels_per_tile_row = padded_width_in_pixels * FRAMEBUFFER_TILE_SIZE_IN_PIXELS; fb->pixels_per_slice = padded_height_in_pixels / FRAMEBUFFER_TILE_SIZE_IN_PIXELS * fb->pixels_per_tile_row; fb->backbuffer = (pixel_t*)malloc(fb->pixels_per_slice * sizeof(pixel_t)); assert(fb->backbuffer); // clear to black/transparent initially memset(fb->backbuffer, 0, fb->pixels_per_slice * sizeof(pixel_t)); return fb; } void delete_framebuffer(framebuffer_t* fb) { if (!fb) return; free(fb->backbuffer); free(fb); } void framebuffer_resolve(framebuffer_t* fb) { } void framebuffer_pack_row_major(framebuffer_t* fb, uint32_t x, uint32_t y, uint32_t width, uint32_t height, pixelformat_t format, void* data) { assert(fb); assert(x < fb->width_in_pixels); assert(y < fb->height_in_pixels); assert(width <= fb->width_in_pixels); assert(height <= fb->height_in_pixels); assert(x + width <= fb->width_in_pixels); assert(y + height <= fb->height_in_pixels); assert(data); uint32_t topleft_tile_y = y / FRAMEBUFFER_TILE_SIZE_IN_PIXELS; uint32_t topleft_tile_x = x / FRAMEBUFFER_TILE_SIZE_IN_PIXELS; uint32_t bottomright_tile_y = (y + height - 1) / FRAMEBUFFER_TILE_SIZE_IN_PIXELS; uint32_t bottomright_tile_x = (x + width - 1) / FRAMEBUFFER_TILE_SIZE_IN_PIXELS; uint32_t dst_i = 0; uint32_t curr_tile_row_start = topleft_tile_y * fb->pixels_per_tile_row + topleft_tile_x * FRAMEBUFFER_PIXELS_PER_TILE; for (uint32_t tile_y = topleft_tile_y; tile_y <= bottomright_tile_y; tile_y++) { uint32_t curr_tile_start = curr_tile_row_start; for (uint32_t tile_x = topleft_tile_x; tile_x <= bottomright_tile_x; tile_x++) { for (uint32_t pixel_y = 0, pixel_y_bits = 0; pixel_y < FRAMEBUFFER_TILE_SIZE_IN_PIXELS; pixel_y++, pixel_y_bits = (pixel_y_bits - FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) & FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) { for (uint32_t pixel_x = 0, pixel_x_bits = 0; pixel_x < FRAMEBUFFER_TILE_SIZE_IN_PIXELS; pixel_x++, pixel_x_bits = (pixel_x_bits - FRAMEBUFFER_TILE_X_SWIZZLE_MASK) & FRAMEBUFFER_TILE_X_SWIZZLE_MASK) { uint32_t src_y = tile_y * FRAMEBUFFER_TILE_SIZE_IN_PIXELS + pixel_y; uint32_t src_x = tile_x * FRAMEBUFFER_TILE_SIZE_IN_PIXELS + pixel_x; // don't copy pixels outside src rectangle region if (src_y < y || src_y >= y + height) continue; if (src_x < x || src_x >= x + width) continue; uint32_t src_i = curr_tile_start + (pixel_y_bits | pixel_x_bits); pixel_t src = fb->backbuffer[src_i]; if (format == pixelformat_r8g8b8a8_unorm) { uint8_t* dst = (uint8_t*)data + dst_i * 4; dst[0] = (uint8_t)((src & 0x00FF0000) >> 16); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x000000FF) >> 0); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } else if (format == pixelformat_b8g8r8a8_unorm) { uint8_t* dst = (uint8_t*)data + dst_i * 4; dst[0] = (uint8_t)((src & 0x000000FF) >> 0); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x00FF0000) >> 16); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } else { assert(!"Unknown pixel format"); } dst_i++; } } curr_tile_start += FRAMEBUFFER_PIXELS_PER_TILE; } curr_tile_row_start += fb->pixels_per_tile_row; } } // hack uint32_t g_Color; void rasterize_triangle_fixed16_8( framebuffer_t* fb, uint32_t window_x0, uint32_t window_y0, uint32_t window_z0, uint32_t window_x1, uint32_t window_y1, uint32_t window_z1, uint32_t window_x2, uint32_t window_y2, uint32_t window_z2) { }<|endoftext|>
<commit_before>// Copyright 2013 Sean McKenna // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // a ray tracer in C++ // libraries, namespace #include <thread> #include <fstream> #include <iostream> #include <string> #include <cmath> #include "library/loadXML.cpp" #include "library/scene.cpp" using namespace std; // scene to load (project #) & debug options string xml = "scenes/prj7.xml"; bool printXML = false; bool zBuffer = false; // variables for ray tracing int w; int h; int size; Color24* img; float* zImg; // setup threading static const int numThreads = 8; void rayTracing(int i); // for camera ray generation void cameraRayVars(); Point *imageTopLeftV; Point *dXV; Point *dYV; Point firstPixel; Transformation* c; Point cameraRay(int pX, int pY); // ray tracer int main(){ // load scene: root node, camera, image loadScene(xml, printXML); // set the scene as the root node setScene(rootNode); // set variables for ray tracing w = render.getWidth(); h = render.getHeight(); size = render.getSize(); img = render.getRender(); zImg = render.getZBuffer(); // set variables for generating camera rays cameraRayVars(); // start ray tracing loop (in parallel with threads) thread t[numThreads]; for(int i = 0; i < numThreads; i++) t[i] = thread(rayTracing, i); // when finished, join all threads back to main for(int i = 0; i < numThreads; i++) t[i].join(); // output ray-traced image & z-buffer (if set) render.save("images/image.ppm"); if(zBuffer){ render.computeZBuffer(); render.saveZBuffer("images/imageZ.ppm"); } } // ray tracing loop (for an individual pixel) void rayTracing(int i){ // initial starting pixel int pixel = i; // thread continuation condition while(pixel < size){ // establish pixel location int pX = pixel % w; int pY = pixel / w; // transform ray into world space Point rayDir = cameraRay(pX, pY); Cone *ray = new Cone(); ray->pos = camera.pos; ray->dir = c->transformFrom(rayDir); // traverse through scene DOM // transform rays into model space // detect ray intersections and get back HitInfo HitInfo h = HitInfo(); bool hit = traceRay(*ray, h); // update z-buffer, if necessary if(zBuffer) zImg[pixel] = h.z; // color for the pixel Color24 c; // if hit, get the node's material if(hit){ Node *n = h.node; Material *m; if(n) m = n->getMaterial(); // if there is a material, shade the pixel // 16-passes for reflections and refractions if(m) c = Color24(m->shade(*ray, h, lights, 5)); // otherwise color it white (as a hit) else c.Set(237, 237, 237); // if we hit nothing }else c.Set(0.0, 0.0, 0.0); // color the pixel image img[pixel] = c; // re-assign next pixel (naive, but works) pixel += numThreads; } } // create variables for camera ray generation void cameraRayVars(){ float fov = camera.fov * M_PI / 180.0; float aspectRatio = (float) w / (float) h; float imageDistance = 1.0; float imageTipY = imageDistance * tan(fov / 2.0); float imageTipX = imageTipY * aspectRatio; float dX = (2.0 * imageTipX) / (float) w; float dY = (2.0 * imageTipY) / (float) h; imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance); dXV = new Point(dX, 0.0, 0.0); dYV = new Point(0.0, -dY, 0.0); firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5); // set up camera transformation (only need to rotate coordinates) c = new Transformation(); Matrix *rotate = new cyMatrix3f(); rotate->Set(camera.cross, camera.up, -camera.dir); c->transform(*rotate); } // compute camera rays Point cameraRay(int pX, int pY){ Point ray = firstPixel + (*dXV * pX) + (*dYV * pY); ray.Normalize(); return ray; } <commit_msg>add bounce count variable to ray tracer<commit_after>// Copyright 2013 Sean McKenna // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // a ray tracer in C++ // libraries, namespace #include <thread> #include <fstream> #include <iostream> #include <string> #include <cmath> #include "library/loadXML.cpp" #include "library/scene.cpp" using namespace std; // scene to load (project #) & debug options string xml = "scenes/prj7.xml"; bool printXML = false; bool zBuffer = false; int bounceCount = 5; // variables for ray tracing int w; int h; int size; Color24* img; float* zImg; // setup threading static const int numThreads = 8; void rayTracing(int i); // for camera ray generation void cameraRayVars(); Point *imageTopLeftV; Point *dXV; Point *dYV; Point firstPixel; Transformation* c; Point cameraRay(int pX, int pY); // ray tracer int main(){ // load scene: root node, camera, image loadScene(xml, printXML); // set the scene as the root node setScene(rootNode); // set variables for ray tracing w = render.getWidth(); h = render.getHeight(); size = render.getSize(); img = render.getRender(); zImg = render.getZBuffer(); // set variables for generating camera rays cameraRayVars(); // start ray tracing loop (in parallel with threads) thread t[numThreads]; for(int i = 0; i < numThreads; i++) t[i] = thread(rayTracing, i); // when finished, join all threads back to main for(int i = 0; i < numThreads; i++) t[i].join(); // output ray-traced image & z-buffer (if set) render.save("images/image.ppm"); if(zBuffer){ render.computeZBuffer(); render.saveZBuffer("images/imageZ.ppm"); } } // ray tracing loop (for an individual pixel) void rayTracing(int i){ // initial starting pixel int pixel = i; // thread continuation condition while(pixel < size){ // establish pixel location int pX = pixel % w; int pY = pixel / w; // transform ray into world space Point rayDir = cameraRay(pX, pY); Cone *ray = new Cone(); ray->pos = camera.pos; ray->dir = c->transformFrom(rayDir); // traverse through scene DOM // transform rays into model space // detect ray intersections and get back HitInfo HitInfo h = HitInfo(); bool hit = traceRay(*ray, h); // update z-buffer, if necessary if(zBuffer) zImg[pixel] = h.z; // color for the pixel Color24 c; // if hit, get the node's material if(hit){ Node *n = h.node; Material *m; if(n) m = n->getMaterial(); // if there is a material, shade the pixel // 16-passes for reflections and refractions if(m) c = Color24(m->shade(*ray, h, lights, bounceCount)); // otherwise color it white (as a hit) else c.Set(237, 237, 237); // if we hit nothing }else c.Set(0.0, 0.0, 0.0); // color the pixel image img[pixel] = c; // re-assign next pixel (naive, but works) pixel += numThreads; } } // create variables for camera ray generation void cameraRayVars(){ float fov = camera.fov * M_PI / 180.0; float aspectRatio = (float) w / (float) h; float imageDistance = 1.0; float imageTipY = imageDistance * tan(fov / 2.0); float imageTipX = imageTipY * aspectRatio; float dX = (2.0 * imageTipX) / (float) w; float dY = (2.0 * imageTipY) / (float) h; imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance); dXV = new Point(dX, 0.0, 0.0); dYV = new Point(0.0, -dY, 0.0); firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5); // set up camera transformation (only need to rotate coordinates) c = new Transformation(); Matrix *rotate = new cyMatrix3f(); rotate->Set(camera.cross, camera.up, -camera.dir); c->transform(*rotate); } // compute camera rays Point cameraRay(int pX, int pY){ Point ray = firstPixel + (*dXV * pX) + (*dYV * pY); ray.Normalize(); return ray; } <|endoftext|>
<commit_before>#include "otbVectorImage.h" #include "otbImage.h" #include "otbImageFileReader.h" #include "otbStreamingImageFileWriter.h" #include "otbImageFileWriter.h" #include "otbSOMMap.h" #include "otbSOM.h" #include "otbSOMImageClassificationFilter.h" #include "otbCommandLineArgumentParser.h" #include "itkEuclideanDistance.h" #include "itkImageRegionSplitter.h" #include "otbStreamingTraits.h" #include "itkImageRegionConstIterator.h" #include "itkVariableSizeMatrix.h" #include "itkListSample.h" #include "itkVariableLengthVector.h" int main(int argc, char * argv[]) { // Parse command line parameters typedef otb::CommandLineArgumentParser ParserType; ParserType::Pointer parser = ParserType::New(); parser->SetProgramDescription("Unsupervised Self Organizing Map image classification"); parser->AddInputImage(); parser->AddOutputImage(); parser->AddOption("--ValidityMask","Validity mask","-vm", 1, true); parser->AddOption("--MaxTrainingSetSize","Size of the training set","-ts", 1, true); parser->AddOption("--TrainingSetProbability","Probability for a sample to be selected in the training set","-tp", 1, true); parser->AddOption("--StreamingNumberOfLines","Number of lined for each streaming block","-sl", 1, true); parser->AddOption("--SOMMap","Output SOM map","-sm", 1, true); parser->AddOption("--SizeX","X size of the SOM map","-sx", 1, true); parser->AddOption("--SizeY","Y size of the SOM map","-sy", 1, true); parser->AddOption("--NeighborhoodInitX","X initial neighborhood of the SOM map","-nx", 1, true); parser->AddOption("--NeighborhoodInitY","Y initial neighborhood of the SOM map","-ny", 1, true); parser->AddOption("--NumberOfIterations","Number of iterations of the SOM learning","-ni", 1, true); parser->AddOption("--BetaInit","Initial beta value","-bi", 1, true); parser->AddOption("--BetaFinal","Final beta value","-be", 1, true); parser->AddOption("--InitValue","Initial value","-iv", 1, true); typedef otb::CommandLineArgumentParseResult ParserResultType; ParserResultType::Pointer parseResult = ParserResultType::New(); try { parser->ParseCommandLine(argc, argv, parseResult); } catch ( itk::ExceptionObject & err ) { std::string descriptionException = err.GetDescription(); if (descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos) { return EXIT_SUCCESS; } if (descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos) { return EXIT_SUCCESS; } return EXIT_FAILURE; } // initiating random number generation srand(time(NULL)); std::string infname = parseResult->GetInputImage(); std::string maskfname = parseResult->GetParameterString("--ValidityMask", 0); std::string outfname = parseResult->GetOutputImage(); std::string somfname = parseResult->GetParameterString("--SOMMap", 0); const unsigned int nbsamples = parseResult->GetParameterUInt("--MaxTrainingSetSize"); const double trainingProb =parseResult->GetParameterDouble("--TrainingSetProbability"); const unsigned int nbLinesForStreaming = parseResult->GetParameterUInt("--StreamingNumberOfLines"); const unsigned int sizeX = parseResult->GetParameterUInt("--SizeX"); const unsigned int sizeY = parseResult->GetParameterUInt("--SizeY"); const unsigned int neighInitX = parseResult->GetParameterUInt("--NeighborhoodInitX"); const unsigned int neighInitY= parseResult->GetParameterUInt("--NeighborhoodInitY"); const unsigned int nbIterations=parseResult->GetParameterUInt("--NumberOfIterations"); const double betaInit = parseResult->GetParameterDouble("--BetaInit"); const double betaEnd= parseResult->GetParameterDouble("--BetaFinal"); const float initValue = parseResult->GetParameterFloat("--InitValue"); typedef float PixelType; typedef unsigned short LabeledPixelType; typedef otb::VectorImage<PixelType, 2> ImageType; typedef otb::Image<LabeledPixelType, 2> LabeledImageType; typedef otb::ImageFileReader<ImageType> ImageReaderType; typedef otb::ImageFileReader<LabeledImageType> LabeledImageReaderType; typedef otb::StreamingImageFileWriter<LabeledImageType> WriterType; typedef itk::VariableLengthVector<double> SampleType; typedef itk::Statistics::EuclideanDistance<SampleType> DistanceType; typedef otb::SOMMap<SampleType, DistanceType, 2> SOMMapType; typedef itk::Statistics::ListSample<SampleType> ListSampleType; typedef otb::SOM<ListSampleType, SOMMapType> EstimatorType; typedef otb::ImageFileWriter<ImageType> SOMMapWriterType; typedef otb::StreamingTraits<ImageType> StreamingTraitsType; typedef itk::ImageRegionSplitter<2> SplitterType; typedef ImageType::RegionType RegionType; typedef itk::ImageRegionConstIterator<ImageType> IteratorType; typedef itk::ImageRegionConstIterator<LabeledImageType> LabeledIteratorType; typedef itk::ImageRegionConstIterator<SOMMapType> SOMIteratorType; typedef otb::SOMImageClassificationFilter<ImageType, LabeledImageType, SOMMapType> ClassificationFilterType; ImageReaderType::Pointer reader = ImageReaderType::New(); LabeledImageReaderType::Pointer maskReader = LabeledImageReaderType::New(); reader->SetFileName(infname); maskReader->SetFileName(maskfname); /*******************************************/ /* Sampling data */ /*******************************************/ std::cout<<std::endl; std::cout<<"-- SAMPLING DATA --"<<std::endl; std::cout<<std::endl; // Update input images information reader->GenerateOutputInformation(); maskReader->GenerateOutputInformation(); if (reader->GetOutput()->GetLargestPossibleRegion() != maskReader->GetOutput()->GetLargestPossibleRegion() ) { std::cerr<<"Mask image and input image have different sizes."<<std::endl; return EXIT_FAILURE; } RegionType largestRegion = reader->GetOutput()->GetLargestPossibleRegion(); // Setting up local streaming capabilities SplitterType::Pointer splitter = SplitterType::New(); unsigned int numberOfStreamDivisions = StreamingTraitsType::CalculateNumberOfStreamDivisions(reader->GetOutput(), largestRegion, splitter, otb::SET_BUFFER_NUMBER_OF_LINES, 0, 0, nbLinesForStreaming); std::cout<<"The images will be streamed into "<<numberOfStreamDivisions<<" parts."<<std::endl; // Training sample lists ListSampleType::Pointer sampleList = ListSampleType::New(); // Sample dimension and max dimension unsigned int sampleSize = reader->GetOutput()->GetNumberOfComponentsPerPixel(); unsigned int totalSamples = 0; std::cout<<"The following sample size will be used: "<<sampleSize<<std::endl; std::cout<<std::endl; // local streaming variables unsigned int piece = 0; RegionType streamingRegion; while (totalSamples<nbsamples) { piece = static_cast<unsigned int>(static_cast<double>(numberOfStreamDivisions)*rand()/(RAND_MAX)); streamingRegion = splitter->GetSplit(piece, numberOfStreamDivisions, largestRegion); std::cout<<"Processing region: "<<streamingRegion<<std::endl; reader->GetOutput()->SetRequestedRegion(streamingRegion); reader->GetOutput()->PropagateRequestedRegion(); reader->GetOutput()->UpdateOutputData(); maskReader->GetOutput()->SetRequestedRegion(streamingRegion); maskReader->GetOutput()->PropagateRequestedRegion(); maskReader->GetOutput()->UpdateOutputData(); IteratorType it(reader->GetOutput(), streamingRegion); LabeledIteratorType maskIt(maskReader->GetOutput(), streamingRegion); it.GoToBegin(); maskIt.GoToBegin(); unsigned int localNbSamples=0; // Loop on the image while (!it.IsAtEnd()&&!maskIt.IsAtEnd()&&(totalSamples<nbsamples)) { // If the current pixel is labeled if (maskIt.Get()>0) { if ((rand()<trainingProb*RAND_MAX)) { SampleType newSample; newSample.SetSize(sampleSize); // build the sample newSample.Fill(0); for (unsigned int i = 0; i<sampleSize; ++i) { newSample[i]=it.Get()[i]; } // Update the the sample lists sampleList->PushBack(newSample); ++totalSamples; ++localNbSamples; } } ++it; ++maskIt; } std::cout<<localNbSamples<<" samples added to the training set."<<std::endl; std::cout<<std::endl; } std::cout<<"The final training set contains "<<totalSamples<<" samples."<<std::endl; std::cout<<std::endl; std::cout<<"Data sampling completed."<<std::endl; std::cout<<std::endl; /*******************************************/ /* Learning */ /*******************************************/ std::cout<<"-- LEARNING --"<<std::endl; EstimatorType::Pointer estimator = EstimatorType::New(); estimator->SetListSample(sampleList); EstimatorType::SizeType size; size[0]=sizeX; size[1]=sizeY; estimator->SetMapSize(size); EstimatorType::SizeType radius; radius[0] = neighInitX; radius[1] = neighInitY; estimator->SetNeighborhoodSizeInit(radius); estimator->SetNumberOfIterations(nbIterations); estimator->SetBetaInit(betaInit); estimator->SetBetaEnd(betaEnd); estimator->SetMaxWeight(initValue); // estimator->SetRandomInit(true); // estimator->SetSeed(time(NULL)); estimator->Update(); ImageType::Pointer vectormap = ImageType::New(); vectormap->SetRegions(estimator->GetOutput()->GetLargestPossibleRegion()); vectormap->SetNumberOfComponentsPerPixel(108); vectormap->Allocate(); ImageType::PixelType black; black.SetSize(108); black.Fill(0); vectormap->FillBuffer(black); SOMIteratorType somIt(estimator->GetOutput(), estimator->GetOutput()->GetLargestPossibleRegion()); IteratorType vectorIt(vectormap, estimator->GetOutput()->GetLargestPossibleRegion()); somIt.GoToBegin(); vectorIt.GoToBegin(); while (!somIt.IsAtEnd() && !vectorIt.IsAtEnd()) { for (unsigned int i = 0; i<somIt.Get().GetSize(); ++i) { vectorIt.Get()[i]=somIt.Get()[i]; } ++somIt; ++vectorIt; } SOMMapWriterType::Pointer somWriter = SOMMapWriterType::New(); somWriter->SetFileName(somfname); somWriter->SetInput(vectormap); somWriter->Update(); std::cout<<std::endl; std::cout<<"Learning completed."<<std::endl; std::cout<<std::endl; /*******************************************/ /* Classification */ /*******************************************/ std::cout<<"-- CLASSIFICATION --"<<std::endl; std::cout<<std::endl; ClassificationFilterType::Pointer classifier = ClassificationFilterType::New(); classifier->SetInput(reader->GetOutput()); classifier->SetInputMask(maskReader->GetOutput()); classifier->SetMap(estimator->GetOutput()); WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfname); writer->SetInput(classifier->GetOutput()); writer->SetNumberOfStreamDivisions(numberOfStreamDivisions); writer->Update(); std::cout<<"Classification completed."<<std::endl; std::cout<<std::endl; return EXIT_SUCCESS; } <commit_msg>WRG: remove deprecated calls<commit_after>#include "otbVectorImage.h" #include "otbImage.h" #include "otbImageFileReader.h" #include "otbStreamingImageFileWriter.h" #include "otbImageFileWriter.h" #include "otbSOMMap.h" #include "otbSOM.h" #include "otbSOMImageClassificationFilter.h" #include "otbCommandLineArgumentParser.h" #include "itkEuclideanDistance.h" #include "itkImageRegionSplitter.h" #include "otbStreamingTraits.h" #include "itkImageRegionConstIterator.h" #include "itkVariableSizeMatrix.h" #include "itkListSample.h" #include "itkVariableLengthVector.h" int main(int argc, char * argv[]) { // Parse command line parameters typedef otb::CommandLineArgumentParser ParserType; ParserType::Pointer parser = ParserType::New(); parser->SetProgramDescription("Unsupervised Self Organizing Map image classification"); parser->AddInputImage(); parser->AddOutputImage(); parser->AddOption("--ValidityMask","Validity mask","-vm", 1, true); parser->AddOption("--MaxTrainingSetSize","Size of the training set","-ts", 1, true); parser->AddOption("--TrainingSetProbability","Probability for a sample to be selected in the training set","-tp", 1, true); parser->AddOption("--StreamingNumberOfLines","Number of lined for each streaming block","-sl", 1, true); parser->AddOption("--SOMMap","Output SOM map","-sm", 1, true); parser->AddOption("--SizeX","X size of the SOM map","-sx", 1, true); parser->AddOption("--SizeY","Y size of the SOM map","-sy", 1, true); parser->AddOption("--NeighborhoodInitX","X initial neighborhood of the SOM map","-nx", 1, true); parser->AddOption("--NeighborhoodInitY","Y initial neighborhood of the SOM map","-ny", 1, true); parser->AddOption("--NumberOfIterations","Number of iterations of the SOM learning","-ni", 1, true); parser->AddOption("--BetaInit","Initial beta value","-bi", 1, true); parser->AddOption("--BetaFinal","Final beta value","-be", 1, true); parser->AddOption("--InitValue","Initial value","-iv", 1, true); typedef otb::CommandLineArgumentParseResult ParserResultType; ParserResultType::Pointer parseResult = ParserResultType::New(); try { parser->ParseCommandLine(argc, argv, parseResult); } catch ( itk::ExceptionObject & err ) { std::string descriptionException = err.GetDescription(); if (descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos) { return EXIT_SUCCESS; } if (descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos) { return EXIT_SUCCESS; } return EXIT_FAILURE; } // initiating random number generation srand(time(NULL)); std::string infname = parseResult->GetInputImage(); std::string maskfname = parseResult->GetParameterString("--ValidityMask", 0); std::string outfname = parseResult->GetOutputImage(); std::string somfname = parseResult->GetParameterString("--SOMMap", 0); const unsigned int nbsamples = parseResult->GetParameterUInt("--MaxTrainingSetSize"); const double trainingProb =parseResult->GetParameterDouble("--TrainingSetProbability"); const unsigned int nbLinesForStreaming = parseResult->GetParameterUInt("--StreamingNumberOfLines"); const unsigned int sizeX = parseResult->GetParameterUInt("--SizeX"); const unsigned int sizeY = parseResult->GetParameterUInt("--SizeY"); const unsigned int neighInitX = parseResult->GetParameterUInt("--NeighborhoodInitX"); const unsigned int neighInitY= parseResult->GetParameterUInt("--NeighborhoodInitY"); const unsigned int nbIterations=parseResult->GetParameterUInt("--NumberOfIterations"); const double betaInit = parseResult->GetParameterDouble("--BetaInit"); const double betaEnd= parseResult->GetParameterDouble("--BetaFinal"); const float initValue = parseResult->GetParameterFloat("--InitValue"); typedef float PixelType; typedef unsigned short LabeledPixelType; typedef otb::VectorImage<PixelType, 2> ImageType; typedef otb::Image<LabeledPixelType, 2> LabeledImageType; typedef otb::ImageFileReader<ImageType> ImageReaderType; typedef otb::ImageFileReader<LabeledImageType> LabeledImageReaderType; typedef otb::StreamingImageFileWriter<LabeledImageType> WriterType; typedef itk::VariableLengthVector<double> SampleType; typedef itk::Statistics::EuclideanDistance<SampleType> DistanceType; typedef otb::SOMMap<SampleType, DistanceType, 2> SOMMapType; typedef itk::Statistics::ListSample<SampleType> ListSampleType; typedef otb::SOM<ListSampleType, SOMMapType> EstimatorType; typedef otb::ImageFileWriter<ImageType> SOMMapWriterType; typedef otb::StreamingTraits<ImageType> StreamingTraitsType; typedef itk::ImageRegionSplitter<2> SplitterType; typedef ImageType::RegionType RegionType; typedef itk::ImageRegionConstIterator<ImageType> IteratorType; typedef itk::ImageRegionConstIterator<LabeledImageType> LabeledIteratorType; typedef itk::ImageRegionConstIterator<SOMMapType> SOMIteratorType; typedef otb::SOMImageClassificationFilter<ImageType, LabeledImageType, SOMMapType> ClassificationFilterType; ImageReaderType::Pointer reader = ImageReaderType::New(); LabeledImageReaderType::Pointer maskReader = LabeledImageReaderType::New(); reader->SetFileName(infname); maskReader->SetFileName(maskfname); /*******************************************/ /* Sampling data */ /*******************************************/ std::cout<<std::endl; std::cout<<"-- SAMPLING DATA --"<<std::endl; std::cout<<std::endl; // Update input images information reader->GenerateOutputInformation(); maskReader->GenerateOutputInformation(); if (reader->GetOutput()->GetLargestPossibleRegion() != maskReader->GetOutput()->GetLargestPossibleRegion() ) { std::cerr<<"Mask image and input image have different sizes."<<std::endl; return EXIT_FAILURE; } RegionType largestRegion = reader->GetOutput()->GetLargestPossibleRegion(); // Setting up local streaming capabilities SplitterType::Pointer splitter = SplitterType::New(); unsigned int numberOfStreamDivisions = StreamingTraitsType::CalculateNumberOfStreamDivisions(reader->GetOutput(), largestRegion, splitter, otb::SET_BUFFER_NUMBER_OF_LINES, 0, 0, nbLinesForStreaming); std::cout<<"The images will be streamed into "<<numberOfStreamDivisions<<" parts."<<std::endl; // Training sample lists ListSampleType::Pointer sampleList = ListSampleType::New(); // Sample dimension and max dimension unsigned int sampleSize = reader->GetOutput()->GetNumberOfComponentsPerPixel(); unsigned int totalSamples = 0; std::cout<<"The following sample size will be used: "<<sampleSize<<std::endl; std::cout<<std::endl; // local streaming variables unsigned int piece = 0; RegionType streamingRegion; while (totalSamples<nbsamples) { piece = static_cast<unsigned int>(static_cast<double>(numberOfStreamDivisions)*rand()/(RAND_MAX)); streamingRegion = splitter->GetSplit(piece, numberOfStreamDivisions, largestRegion); std::cout<<"Processing region: "<<streamingRegion<<std::endl; reader->GetOutput()->SetRequestedRegion(streamingRegion); reader->GetOutput()->PropagateRequestedRegion(); reader->GetOutput()->UpdateOutputData(); maskReader->GetOutput()->SetRequestedRegion(streamingRegion); maskReader->GetOutput()->PropagateRequestedRegion(); maskReader->GetOutput()->UpdateOutputData(); IteratorType it(reader->GetOutput(), streamingRegion); LabeledIteratorType maskIt(maskReader->GetOutput(), streamingRegion); it.GoToBegin(); maskIt.GoToBegin(); unsigned int localNbSamples=0; // Loop on the image while (!it.IsAtEnd()&&!maskIt.IsAtEnd()&&(totalSamples<nbsamples)) { // If the current pixel is labeled if (maskIt.Get()>0) { if ((rand()<trainingProb*RAND_MAX)) { SampleType newSample; newSample.SetSize(sampleSize); // build the sample newSample.Fill(0); for (unsigned int i = 0; i<sampleSize; ++i) { newSample[i]=it.Get()[i]; } // Update the the sample lists sampleList->PushBack(newSample); ++totalSamples; ++localNbSamples; } } ++it; ++maskIt; } std::cout<<localNbSamples<<" samples added to the training set."<<std::endl; std::cout<<std::endl; } std::cout<<"The final training set contains "<<totalSamples<<" samples."<<std::endl; std::cout<<std::endl; std::cout<<"Data sampling completed."<<std::endl; std::cout<<std::endl; /*******************************************/ /* Learning */ /*******************************************/ std::cout<<"-- LEARNING --"<<std::endl; EstimatorType::Pointer estimator = EstimatorType::New(); estimator->SetListSample(sampleList); EstimatorType::SizeType size; size[0]=sizeX; size[1]=sizeY; estimator->SetMapSize(size); EstimatorType::SizeType radius; radius[0] = neighInitX; radius[1] = neighInitY; estimator->SetNeighborhoodSizeInit(radius); estimator->SetNumberOfIterations(nbIterations); estimator->SetBetaInit(betaInit); estimator->SetBetaEnd(betaEnd); estimator->SetMaxWeight(initValue); // estimator->SetRandomInit(true); // estimator->SetSeed(time(NULL)); estimator->Update(); ImageType::Pointer vectormap = ImageType::New(); vectormap->SetRegions(estimator->GetOutput()->GetLargestPossibleRegion()); vectormap->SetNumberOfComponentsPerPixel(108); vectormap->Allocate(); ImageType::PixelType black; black.SetSize(108); black.Fill(0); vectormap->FillBuffer(black); SOMIteratorType somIt(estimator->GetOutput(), estimator->GetOutput()->GetLargestPossibleRegion()); IteratorType vectorIt(vectormap, estimator->GetOutput()->GetLargestPossibleRegion()); somIt.GoToBegin(); vectorIt.GoToBegin(); while (!somIt.IsAtEnd() && !vectorIt.IsAtEnd()) { for (unsigned int i = 0; i<somIt.Get().GetSize(); ++i) { vectorIt.Get()[i]=somIt.Get()[i]; } ++somIt; ++vectorIt; } SOMMapWriterType::Pointer somWriter = SOMMapWriterType::New(); somWriter->SetFileName(somfname); somWriter->SetInput(vectormap); somWriter->Update(); std::cout<<std::endl; std::cout<<"Learning completed."<<std::endl; std::cout<<std::endl; /*******************************************/ /* Classification */ /*******************************************/ std::cout<<"-- CLASSIFICATION --"<<std::endl; std::cout<<std::endl; ClassificationFilterType::Pointer classifier = ClassificationFilterType::New(); classifier->SetInput(reader->GetOutput()); classifier->SetInputMask(maskReader->GetOutput()); classifier->SetMap(estimator->GetOutput()); WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfname); writer->SetInput(classifier->GetOutput()); writer->SetNumberOfDivisionsStrippedStreaming(numberOfStreamDivisions); writer->Update(); std::cout<<"Classification completed."<<std::endl; std::cout<<std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2016 Imperial College London * Copyright 2016 Andreas Schuh * * 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 "mirtk/ImageSurfaceStatistics.h" #include "mirtk/PointSetUtils.h" #include "mirtk/Matrix3x3.h" #include "vtkNew.h" #include "vtkSmartPointer.h" #include "vtkPoints.h" #include "vtkDataArray.h" #include "vtkPointData.h" #include "vtkPolyDataNormals.h" namespace mirtk { // ============================================================================= // Auxiliaries // ============================================================================= namespace ImageSurfaceStatisticsUtils { // ----------------------------------------------------------------------------- /// Base class of ImageSurfaceStatistics::Execute function body struct CalculatePatchStatistics { vtkPoints *_Points; const InterpolateImageFunction *_Image; int3 _Size; int _N; Array<const data::Statistic *> _Statistics; vtkDataArray *_Output; bool _Samples; bool _Demean; bool _Whiten; protected: /// Calculate patch values and statistics at given surface point void Execute(vtkIdType ptId, Array<double> &patch_mem, Array<double> &stats_mem, const Vector3 &dx, const Vector3 &dy, const Vector3 &dz) const { Point o, p; patch_mem.resize(_N); double * const patch = patch_mem.data(); // Sample patch values _Points->GetPoint(ptId, o); _Image->WorldToImage(o._x, o._y, o._z); o -= (_Size.x / 2.) * dx; o -= (_Size.y / 2.) * dy; o -= (_Size.z / 2.) * dz; double *v = patch; for (int k = 0; k < _Size.z; ++k) for (int j = 0; j < _Size.y; ++j) { p = o + j * dy + k * dz; for (int i = 0; i < _Size.x; ++i, ++v, p += dx) { (*v) = _Image->Evaluate(p._x, p._y, p._z); } } // Evaluate statistics (**before** subtracting mean or dividing by standard deviation) if (!_Statistics.empty()) { int f = (_Samples ? _N : 0); Array<double> &stats = stats_mem; for (size_t i = 0; i < _Statistics.size(); ++i) { _Statistics[i]->Evaluate(stats, _N, patch); for (size_t j = 0; j < stats.size(); ++j, ++f) { _Output->SetComponent(ptId, f, stats[j]); } } } // Store patch samples (**after** evaluating statistics of unmodified samples) if (_Samples) { if (_Demean || _Whiten) { double mean, sigma; data::statistic::NormalDistribution::Calculate(mean, sigma, _N, patch); if (_Demean && _Whiten) { for (int i = 0; i < _N; ++i) { patch[i] = (patch[i] - mean) / sigma; } } else if (_Demean) { for (int i = 0; i < _N; ++i) { patch[i] -= mean; } } else { for (int i = 0; i < _N; ++i) { patch[i] = mean + (patch[i] - mean) / sigma; } } } for (int i = 0; i < _N; ++i) { _Output->SetComponent(ptId, i, patch[i]); } } } }; // ----------------------------------------------------------------------------- /// Calculate image statistics for patch aligned with global coordinate axes struct CalculateImagePatchStatistics : public CalculatePatchStatistics { Vector3 _DirX, _DirY, _DirZ; void operator ()(const blocked_range<vtkIdType> ptIds) const { Array<double> patch_mem(_N), stats_mem; stats_mem.reserve(10); for (vtkIdType ptId = ptIds.begin(); ptId != ptIds.end(); ++ptId) { Execute(ptId, patch_mem, stats_mem, _DirX, _DirY, _DirZ); } } }; // ----------------------------------------------------------------------------- /// Calculate image statistics for patch aligned with local tangent vectors struct CalculateTangentPatchStatistics : public CalculatePatchStatistics { vtkDataArray *_Normals; Matrix3x3 _Rotation; double3 _Scaling; void operator ()(const blocked_range<vtkIdType> ptIds) const { Vector3 dx, dy, dz; Array<double> patch_mem(_N), stats_mem; stats_mem.reserve(10); for (vtkIdType ptId = ptIds.begin(); ptId != ptIds.end(); ++ptId) { _Normals->GetTuple(ptId, dx); dx = _Rotation * dx; ComputeTangents(dx, dy, dz); dx *= _Scaling.x; dy *= _Scaling.y; dz *= _Scaling.z; Execute(ptId, patch_mem, stats_mem, dx, dy, dz); } } }; } // ImageSurfaceStatisticsUtils using namespace ImageSurfaceStatisticsUtils; // ============================================================================= // Construction/Destruction // ============================================================================= // ----------------------------------------------------------------------------- void ImageSurfaceStatistics::CopyAttributes(const ImageSurfaceStatistics &other) { _Image = other._Image; _ArrayName = other._ArrayName; _PatchSpace = other._PatchSpace; _PatchSize = other._PatchSize; _PatchSpacing = other._PatchSpacing; _PatchSamples = other._PatchSamples; _DemeanSamples = other._DemeanSamples; _WhitenSamples = other._WhitenSamples; } // ----------------------------------------------------------------------------- ImageSurfaceStatistics::ImageSurfaceStatistics() : _PatchSpace(TangentSpace), _PatchSize(make_int3(5)), _PatchSpacing(make_double3(1.)), _PatchSamples(false), _DemeanSamples(false), _WhitenSamples(false) { } // ----------------------------------------------------------------------------- ImageSurfaceStatistics::ImageSurfaceStatistics(const ImageSurfaceStatistics &other) : SurfaceFilter(other) { CopyAttributes(other); } // ----------------------------------------------------------------------------- ImageSurfaceStatistics &ImageSurfaceStatistics::operator =(const ImageSurfaceStatistics &other) { if (this != &other) { SurfaceFilter::operator =(other); CopyAttributes(other); } return *this; } // ----------------------------------------------------------------------------- ImageSurfaceStatistics::~ImageSurfaceStatistics() { } // ============================================================================= // Execution // ============================================================================= // ----------------------------------------------------------------------------- template <class Body> void ImageSurfaceStatistics::ExecuteInParallel(Body &body) { body._Points = _Output->GetPoints(); body._Image = _Image.get(); body._Size = _PatchSize; body._N = _PatchSize.x * _PatchSize.y * _PatchSize.z; body._Samples = _PatchSamples; body._Demean = _DemeanSamples; body._Whiten = _WhitenSamples; body._Statistics.resize(_Statistics.size()); for (size_t i = 0; i < _Statistics.size(); ++i) { body._Statistics[i] = _Statistics[i].get(); } int nfeatures = static_cast<int>(_Statistics.size()); if (_PatchSamples) nfeatures += body._N; if (nfeatures <= 0) { Throw(ERR_LogicError, "Execute", "No surface patch samples and statistics to evaluate"); } vtkSmartPointer<vtkDataArray> output; output = NewArray("LocalImageStatistics", nfeatures); if (!_ArrayName.empty()) output->SetName(_ArrayName.c_str()); body._Output = output; if (body._Samples) { char name[64]; for (int i = 0; i < body._N; ++i) { sprintf(name, "Sample %d", i+1); output->SetComponentName(i, name); } } int f = (_PatchSamples ? body._N : 0); for (size_t i = 0; i < _Statistics.size(); ++i) { const Array<string> &names = _Statistics[i]->Names(); for (size_t j = 0; j < names.size(); ++j, ++f) { output->SetComponentName(f, names[j].c_str()); } } parallel_for(blocked_range<vtkIdType>(0, _Output->GetNumberOfPoints()), body); _Output->GetPointData()->AddArray(output); } // ----------------------------------------------------------------------------- void ImageSurfaceStatistics::Execute() { switch (_PatchSpace) { // Patches aligned with image coordinate axes case ImageSpace: { CalculateImagePatchStatistics body; body._DirX = Vector3(_PatchSpacing.x / _Image->XSize(), 0., 0.); body._DirY = Vector3(0., _PatchSpacing.y / _Image->YSize(), 0.); body._DirZ = Vector3(0., 0., _PatchSpacing.z / _Image->ZSize()); ExecuteInParallel(body); } break; // Patches aligned with world coordinate axes case WorldSpace: { Matrix A(3, 3); A(0, 0) = _PatchSpacing.x / _Image->XSize(); A(1, 1) = _PatchSpacing.y / _Image->YSize(); A(2, 2) = _PatchSpacing.z / _Image->ZSize(); A = _Image->Attributes().GetWorldToImageOrientation() * A; CalculateImagePatchStatistics body; body._DirX = Vector3(A.Col(0)); body._DirY = Vector3(A.Col(1)); body._DirZ = Vector3(A.Col(2)); ExecuteInParallel(body); } break; // Patches aligned with normal and tangent vectors case TangentSpace: { vtkSmartPointer<vtkDataArray> normals = _Input->GetPointData()->GetNormals(); if (!normals) { vtkNew<vtkPolyDataNormals> calc_normals; SetVTKInput(calc_normals, _Input); calc_normals->SplittingOff(); calc_normals->Update(); normals = calc_normals->GetOutput()->GetPointData()->GetNormals(); } const Matrix R = _Image->Attributes().GetWorldToImageOrientation(); CalculateTangentPatchStatistics body; body._Normals = normals; body._Rotation = Matrix3x3(R(0, 0), R(0, 1), R(0, 2), R(1, 0), R(1, 1), R(1, 2), R(2, 0), R(2, 1), R(2, 2)); body._Scaling.x = _PatchSpacing.x / _Image->XSize(); body._Scaling.y = _PatchSpacing.y / _Image->YSize(); body._Scaling.z = _PatchSpacing.z / _Image->ZSize(); ExecuteInParallel(body); } break; default: { Throw(ERR_LogicError, __func__, "Invalid patch space enumeration value: ", _PatchSpace); } break; } } } // namespace mirtk <commit_msg>fix: sprintf warning by using snprintf [PointSet]<commit_after>/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2016 Imperial College London * Copyright 2016 Andreas Schuh * * 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 "mirtk/ImageSurfaceStatistics.h" #include "mirtk/PointSetUtils.h" #include "mirtk/Matrix3x3.h" #include "vtkNew.h" #include "vtkSmartPointer.h" #include "vtkPoints.h" #include "vtkDataArray.h" #include "vtkPointData.h" #include "vtkPolyDataNormals.h" namespace mirtk { // ============================================================================= // Auxiliaries // ============================================================================= namespace ImageSurfaceStatisticsUtils { // ----------------------------------------------------------------------------- /// Base class of ImageSurfaceStatistics::Execute function body struct CalculatePatchStatistics { vtkPoints *_Points; const InterpolateImageFunction *_Image; int3 _Size; int _N; Array<const data::Statistic *> _Statistics; vtkDataArray *_Output; bool _Samples; bool _Demean; bool _Whiten; protected: /// Calculate patch values and statistics at given surface point void Execute(vtkIdType ptId, Array<double> &patch_mem, Array<double> &stats_mem, const Vector3 &dx, const Vector3 &dy, const Vector3 &dz) const { Point o, p; patch_mem.resize(_N); double * const patch = patch_mem.data(); // Sample patch values _Points->GetPoint(ptId, o); _Image->WorldToImage(o._x, o._y, o._z); o -= (_Size.x / 2.) * dx; o -= (_Size.y / 2.) * dy; o -= (_Size.z / 2.) * dz; double *v = patch; for (int k = 0; k < _Size.z; ++k) for (int j = 0; j < _Size.y; ++j) { p = o + j * dy + k * dz; for (int i = 0; i < _Size.x; ++i, ++v, p += dx) { (*v) = _Image->Evaluate(p._x, p._y, p._z); } } // Evaluate statistics (**before** subtracting mean or dividing by standard deviation) if (!_Statistics.empty()) { int f = (_Samples ? _N : 0); Array<double> &stats = stats_mem; for (size_t i = 0; i < _Statistics.size(); ++i) { _Statistics[i]->Evaluate(stats, _N, patch); for (size_t j = 0; j < stats.size(); ++j, ++f) { _Output->SetComponent(ptId, f, stats[j]); } } } // Store patch samples (**after** evaluating statistics of unmodified samples) if (_Samples) { if (_Demean || _Whiten) { double mean, sigma; data::statistic::NormalDistribution::Calculate(mean, sigma, _N, patch); if (_Demean && _Whiten) { for (int i = 0; i < _N; ++i) { patch[i] = (patch[i] - mean) / sigma; } } else if (_Demean) { for (int i = 0; i < _N; ++i) { patch[i] -= mean; } } else { for (int i = 0; i < _N; ++i) { patch[i] = mean + (patch[i] - mean) / sigma; } } } for (int i = 0; i < _N; ++i) { _Output->SetComponent(ptId, i, patch[i]); } } } }; // ----------------------------------------------------------------------------- /// Calculate image statistics for patch aligned with global coordinate axes struct CalculateImagePatchStatistics : public CalculatePatchStatistics { Vector3 _DirX, _DirY, _DirZ; void operator ()(const blocked_range<vtkIdType> ptIds) const { Array<double> patch_mem(_N), stats_mem; stats_mem.reserve(10); for (vtkIdType ptId = ptIds.begin(); ptId != ptIds.end(); ++ptId) { Execute(ptId, patch_mem, stats_mem, _DirX, _DirY, _DirZ); } } }; // ----------------------------------------------------------------------------- /// Calculate image statistics for patch aligned with local tangent vectors struct CalculateTangentPatchStatistics : public CalculatePatchStatistics { vtkDataArray *_Normals; Matrix3x3 _Rotation; double3 _Scaling; void operator ()(const blocked_range<vtkIdType> ptIds) const { Vector3 dx, dy, dz; Array<double> patch_mem(_N), stats_mem; stats_mem.reserve(10); for (vtkIdType ptId = ptIds.begin(); ptId != ptIds.end(); ++ptId) { _Normals->GetTuple(ptId, dx); dx = _Rotation * dx; ComputeTangents(dx, dy, dz); dx *= _Scaling.x; dy *= _Scaling.y; dz *= _Scaling.z; Execute(ptId, patch_mem, stats_mem, dx, dy, dz); } } }; } // ImageSurfaceStatisticsUtils using namespace ImageSurfaceStatisticsUtils; // ============================================================================= // Construction/Destruction // ============================================================================= // ----------------------------------------------------------------------------- void ImageSurfaceStatistics::CopyAttributes(const ImageSurfaceStatistics &other) { _Image = other._Image; _ArrayName = other._ArrayName; _PatchSpace = other._PatchSpace; _PatchSize = other._PatchSize; _PatchSpacing = other._PatchSpacing; _PatchSamples = other._PatchSamples; _DemeanSamples = other._DemeanSamples; _WhitenSamples = other._WhitenSamples; } // ----------------------------------------------------------------------------- ImageSurfaceStatistics::ImageSurfaceStatistics() : _PatchSpace(TangentSpace), _PatchSize(make_int3(5)), _PatchSpacing(make_double3(1.)), _PatchSamples(false), _DemeanSamples(false), _WhitenSamples(false) { } // ----------------------------------------------------------------------------- ImageSurfaceStatistics::ImageSurfaceStatistics(const ImageSurfaceStatistics &other) : SurfaceFilter(other) { CopyAttributes(other); } // ----------------------------------------------------------------------------- ImageSurfaceStatistics &ImageSurfaceStatistics::operator =(const ImageSurfaceStatistics &other) { if (this != &other) { SurfaceFilter::operator =(other); CopyAttributes(other); } return *this; } // ----------------------------------------------------------------------------- ImageSurfaceStatistics::~ImageSurfaceStatistics() { } // ============================================================================= // Execution // ============================================================================= // ----------------------------------------------------------------------------- template <class Body> void ImageSurfaceStatistics::ExecuteInParallel(Body &body) { body._Points = _Output->GetPoints(); body._Image = _Image.get(); body._Size = _PatchSize; body._N = _PatchSize.x * _PatchSize.y * _PatchSize.z; body._Samples = _PatchSamples; body._Demean = _DemeanSamples; body._Whiten = _WhitenSamples; body._Statistics.resize(_Statistics.size()); for (size_t i = 0; i < _Statistics.size(); ++i) { body._Statistics[i] = _Statistics[i].get(); } int nfeatures = static_cast<int>(_Statistics.size()); if (_PatchSamples) nfeatures += body._N; if (nfeatures <= 0) { Throw(ERR_LogicError, "Execute", "No surface patch samples and statistics to evaluate"); } vtkSmartPointer<vtkDataArray> output; output = NewArray("LocalImageStatistics", nfeatures); if (!_ArrayName.empty()) output->SetName(_ArrayName.c_str()); body._Output = output; if (body._Samples) { char name[64]; for (int i = 0; i < body._N; ++i) { snprintf(name, 64, "Sample %d", i+1); output->SetComponentName(i, name); } } int f = (_PatchSamples ? body._N : 0); for (size_t i = 0; i < _Statistics.size(); ++i) { const Array<string> &names = _Statistics[i]->Names(); for (size_t j = 0; j < names.size(); ++j, ++f) { output->SetComponentName(f, names[j].c_str()); } } parallel_for(blocked_range<vtkIdType>(0, _Output->GetNumberOfPoints()), body); _Output->GetPointData()->AddArray(output); } // ----------------------------------------------------------------------------- void ImageSurfaceStatistics::Execute() { switch (_PatchSpace) { // Patches aligned with image coordinate axes case ImageSpace: { CalculateImagePatchStatistics body; body._DirX = Vector3(_PatchSpacing.x / _Image->XSize(), 0., 0.); body._DirY = Vector3(0., _PatchSpacing.y / _Image->YSize(), 0.); body._DirZ = Vector3(0., 0., _PatchSpacing.z / _Image->ZSize()); ExecuteInParallel(body); } break; // Patches aligned with world coordinate axes case WorldSpace: { Matrix A(3, 3); A(0, 0) = _PatchSpacing.x / _Image->XSize(); A(1, 1) = _PatchSpacing.y / _Image->YSize(); A(2, 2) = _PatchSpacing.z / _Image->ZSize(); A = _Image->Attributes().GetWorldToImageOrientation() * A; CalculateImagePatchStatistics body; body._DirX = Vector3(A.Col(0)); body._DirY = Vector3(A.Col(1)); body._DirZ = Vector3(A.Col(2)); ExecuteInParallel(body); } break; // Patches aligned with normal and tangent vectors case TangentSpace: { vtkSmartPointer<vtkDataArray> normals = _Input->GetPointData()->GetNormals(); if (!normals) { vtkNew<vtkPolyDataNormals> calc_normals; SetVTKInput(calc_normals, _Input); calc_normals->SplittingOff(); calc_normals->Update(); normals = calc_normals->GetOutput()->GetPointData()->GetNormals(); } const Matrix R = _Image->Attributes().GetWorldToImageOrientation(); CalculateTangentPatchStatistics body; body._Normals = normals; body._Rotation = Matrix3x3(R(0, 0), R(0, 1), R(0, 2), R(1, 0), R(1, 1), R(1, 2), R(2, 0), R(2, 1), R(2, 2)); body._Scaling.x = _PatchSpacing.x / _Image->XSize(); body._Scaling.y = _PatchSpacing.y / _Image->YSize(); body._Scaling.z = _PatchSpacing.z / _Image->ZSize(); ExecuteInParallel(body); } break; default: { Throw(ERR_LogicError, __func__, "Invalid patch space enumeration value: ", _PatchSpace); } break; } } } // namespace mirtk <|endoftext|>
<commit_before>// -------------------- debugs -------------------- //#define DEBUG //#define COMPARE // -------------------- paths -------------------- #define HITALERT_BASE_PATH "../../../hitalert/" #define HITALERT_RUNTIME_PATH "" //HITALERT_BASE_PATH #define SOUND_C_HI HITALERT_RUNTIME_PATH "res/MidHigh.wav" #define SOUND_R_HI HITALERT_RUNTIME_PATH "res/RightHigh.wav" #define SOUND_L_HI HITALERT_RUNTIME_PATH "res/LeftHigh.wav" #define SOUND_C_LOW HITALERT_RUNTIME_PATH "res/MidLow.wav" #define SOUND_R_LOW HITALERT_RUNTIME_PATH "res/RightLow.wav" #define SOUND_L_LOW HITALERT_RUNTIME_PATH "res/LeftLow.wav" // -------------------- input -------------------- //#define USE_WEBCAM #define CAP_CAM_NO 0 #define CAP_VID_PATH HITALERT_BASE_PATH "test_data/" #define CAP_VID_NAME "01.mp4" // -------------------- output -------------------- //#define OUTPUT_VIDEO #define OUTPUT_VIDEO_PATH HITALERT_BASE_PATH "output/out.mp4" //#define ALERT_LEFT_RIGHT #define ALERT_HIGH_ONLY // -------------------- image config -------------------- #define PROCESS_WIDTH 480//720 #define PROCESS_HEIGHT 360//480 #define FRAMES_SKIP 0 #define ROI_COUNT 3 #define ROI_WIDTH_REL 0.36 // calculated from human dimension of 60 cm in width, 50cm distance with 60 deg FOV camera // -------------------- hitalert parameters -------------------- #define TRACK_CORNERS 150 #define TRACK_QUALITY 0.05 #define TRACK_MIN_DIST 20 #define TTC_LOW 60 #define TTC_MID 100 #define GS_BLUR_SIZE 25 #define GS_BLUR_SIGMA_REL 0.7 #define EXP_BLUR_RATIO 0.9 #define DIST_RATIO_RANGE_THRESH 0.03 #define DIST_RATIO_COEFF 100 //////////////////// derived configs //////////////////// #ifdef USE_WEBCAM #define CAP_SRC 0 #else #define CAP_SRC CAP_VID_PATH CAP_VID_NAME #endif <commit_msg>minor config<commit_after>// -------------------- debugs -------------------- //#define DEBUG //#define COMPARE // -------------------- paths -------------------- #define HITALERT_BASE_PATH "../../../hitalert/" #define HITALERT_RUNTIME_PATH "" //HITALERT_BASE_PATH #define SOUND_C_HI HITALERT_RUNTIME_PATH "res/MidHigh.wav" #define SOUND_R_HI HITALERT_RUNTIME_PATH "res/RightHigh.wav" #define SOUND_L_HI HITALERT_RUNTIME_PATH "res/LeftHigh.wav" #define SOUND_C_LOW HITALERT_RUNTIME_PATH "res/MidLow.wav" #define SOUND_R_LOW HITALERT_RUNTIME_PATH "res/RightLow.wav" #define SOUND_L_LOW HITALERT_RUNTIME_PATH "res/LeftLow.wav" // -------------------- input -------------------- //#define USE_WEBCAM #define CAP_CAM_NO 0 #define CAP_VID_PATH HITALERT_BASE_PATH "test_data/" #define CAP_VID_NAME "01.mp4" // -------------------- output -------------------- //#define OUTPUT_VIDEO #define OUTPUT_VIDEO_PATH HITALERT_BASE_PATH "output/out.mp4" //#define ALERT_LEFT_RIGHT //#define ALERT_HIGH_ONLY // -------------------- image config -------------------- #define PROCESS_WIDTH 480//720 #define PROCESS_HEIGHT 360//480 #define FRAMES_SKIP 0 #define ROI_WIDTH_REL 0.36 // calculated from human dimension of 60 cm in width, 50cm distance with 60 deg FOV camera // -------------------- hitalert parameters -------------------- #define TRACK_CORNERS 150 #define TRACK_QUALITY 0.05 #define TRACK_MIN_DIST 20 #define TTC_LOW 70 #define TTC_MID 100 #define GS_BLUR_SIZE 25 #define GS_BLUR_SIGMA_REL 0.7 #define EXP_BLUR_RATIO 0.9 #define DIST_RATIO_RANGE_THRESH 0.03 #define DIST_RATIO_COEFF 100 //////////////////// derived configs //////////////////// #ifdef USE_WEBCAM #define CAP_SRC 0 #else #define CAP_SRC CAP_VID_PATH CAP_VID_NAME #endif <|endoftext|>
<commit_before><commit_msg>removed empty file<commit_after><|endoftext|>