text
stringlengths
54
60.6k
<commit_before>#ifndef DUNE_STUFF_GRID_PROVIDER_CUBE_HH #define DUNE_STUFF_GRID_PROVIDER_CUBE_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG #if HAVE_DUNE_GRID #include <sstream> #include <type_traits> #include <boost/assign/list_of.hpp> #include <dune/common/parametertree.hh> #include <dune/common/shared_ptr.hh> #include <dune/common/exceptions.hh> #include <dune/common/fvector.hh> #include <dune/common/static_assert.hh> #include <dune/grid/utility/structuredgridfactory.hh> #include <dune/grid/yaspgrid.hh> #ifdef HAVE_ALUGRID #include <dune/grid/alugrid.hh> #endif #include <dune/grid/sgrid.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/color.hh> #include "interface.hh" namespace Dune { namespace Stuff { namespace Grid { namespace Provider { /** * \brief Creates a grid of a cube in various dimensions. * * Default implementation using the Dune::StructuredGridFactory to create a grid of a cube in 1, 2 or 3 * dimensions. Tested with * <ul><li> \c YASPGRID, \c variant 1, dim = 1, 2, 3, * <li> \c SGRID, \c variant 1, dim = 1, 2, 3, * <li> \c ALUGRID_SIMPLEX, \c variant 2, dim = 2, 3, * <li> \c ALUGRID_CONFORM, \c variant 2, dim = 2, 2 and * <li> \c ALUGRID_CUBE, \c variant 1, dim = 2, 3.</ul> * \tparam GridImp * Type of the underlying grid. * \tparam variant * Type of the codim 0 elements: * <ul><li>\c 1: cubes * <li>2: simplices</ul> **/ template< typename GridImp, int variant > class GenericCube : public Interface< GridImp > { public: //! Type of the provided grid. typedef GridImp GridType; typedef Interface< GridType > BaseType; typedef GenericCube< GridType, variant > ThisType; private: typedef typename GridType::LeafGridView GridViewType; public: static const unsigned int dim = BaseType::dim; //! Type of the grids coordinates. typedef typename GridType::ctype ctype; typedef Dune::FieldVector< ctype, dim > CoordinateType; //! Unique identifier: \c stuff.grid.provider.cube static const std::string id() { return BaseType::id() + ".cube"; } /** * \brief Creates a cube. * \param[in] lowerLeft * A double that is used as a lower left corner in each dimension. * \param[in] upperRight * A double that is used as a upper right corner in each dimension. * \param[in] numElements (optional) * number of elements. **/ GenericCube(const double _lowerLeft = 0.0, const double _upperRight = 1.0, const unsigned int numElements = 1u) : lowerLeft_(_lowerLeft), upperRight_(_upperRight) { Dune::array< unsigned int, dim > tmpNumElements; std::fill(tmpNumElements.begin(), tmpNumElements.end(), numElements); buildGrid(tmpNumElements); } /** * \brief Creates a cube. * \param[in] lowerLeft * A vector that is used as a lower left corner. * \param[in] upperRight * A vector that is used as a upper right corner. * \param[in] numElements (optional) * number of elements. **/ GenericCube(const CoordinateType& _lowerLeft, const CoordinateType& _upperRight, const unsigned int numElements = 1u) : lowerLeft_(_lowerLeft), upperRight_(_upperRight) { Dune::array< unsigned int, dim > tmpNumElements; std::fill(tmpNumElements.begin(), tmpNumElements.end(), numElements); buildGrid(tmpNumElements); } /** \brief Creates a cube. This signature allows to prescribe anisotopic refinement \param[in] lowerLeft A double that is used as a lower left corner in each dimension. \param[in] upperRight A double that is used as a upper right corner in each dimension. \param[in] numElements number of elements in each dimension. can contain 0 to dim elements (missing dimension are initialized to 1) \tparam Coord anything that CoordinateType allows to copy construct from \tparam ContainerType some sequence type that functions with std::begin/end \tparam T an unsigned integral Type **/ template< class ContainerType > GenericCube(const CoordinateType& _lowerLeft, const CoordinateType& _upperRight, const ContainerType numElements = boost::assign::list_of< typename ContainerType::value_type>().repeat(dim, typename ContainerType::value_type(1u))) : lowerLeft_(_lowerLeft), upperRight_(_upperRight) { Dune::array< unsigned int, dim > tmpNumElements; static_assert(std::is_unsigned< typename ContainerType::value_type >::value && std::is_integral< typename ContainerType::value_type >::value, "only unsigned integral number of elements per dimension allowed"); //base init in case input is shorter std::fill(tmpNumElements.begin(), tmpNumElements.end(), 1u); std::copy(numElements.begin(), numElements.end(), tmpNumElements.begin()); buildGrid(tmpNumElements); } GenericCube(ThisType& other) : lowerLeft_(other.lowerLeft_) , upperRight_(other.upperRight_) , grid_(other.grid_) {} GenericCube(const ThisType& other) : lowerLeft_(other.lowerLeft_) , upperRight_(other.upperRight_) , grid_(other.grid_) {} /** * \brief Creates a cube. * \param[in] paramTree * A Dune::ParameterTree containing * <ul><li> the following keys directly or * <li> a subtree named Cube::id, containing the following keys. If a subtree is present, it is always selected. Also it is solely selceted, so that all keys in the supertree are ignored.</ul> * The actual keys are: * <ul><li> \c lowerLeft: \a double or a vector that is used as lower left corners. * <li> \c upperRight: \a double or a vector that is used as upper right corners. * <li> \c numElements: \a int or vector to denote the number of elements. * </ul> **/ static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id()) { // get correct paramTree Dune::Stuff::Common::ParameterTreeX extendedParamTree; if (paramTree.hasSub(subName)) extendedParamTree = paramTree.sub(subName); else extendedParamTree = paramTree; // get lower left std::vector< ctype > lowerLefts; if (extendedParamTree.hasVector("lowerLeft")) { lowerLefts = extendedParamTree.getVector("lowerLeft", ctype(0), dim); assert(lowerLefts.size() >= dim && "Given vector too short!"); } else if (extendedParamTree.hasKey("lowerLeft")) { const ctype lowerLeft = extendedParamTree.get("lowerLeft", ctype(0)); lowerLefts = std::vector< ctype >(dim, lowerLeft); } else { std::cout << "\n" << Dune::Stuff::Common::highlightString("WARNING in " + id() + ":", Dune::Stuff::Common::Colors::brown) << " neither vector nor key 'lowerLeft' given, defaulting to 0.0!" << std::flush; lowerLefts = std::vector< ctype >(dim, ctype(0)); } // get upper right std::vector< ctype > upperRights; if (extendedParamTree.hasVector("upperRight")) { upperRights = extendedParamTree.getVector("upperRight", ctype(1), dim); assert(upperRights.size() >= dim && "Given vector too short!"); } else if (extendedParamTree.hasKey("upperRight")) { const ctype upperRight = extendedParamTree.get("upperRight", ctype(1)); upperRights = std::vector< ctype >(dim, upperRight); } else { std::cout << "\n" << Dune::Stuff::Common::highlightString("WARNING in " + id() + ":", Dune::Stuff::Common::Colors::brown) << " neither vector nor key 'upperRight' given, defaulting to 1.0!" << std::flush; upperRights = std::vector< ctype >(dim, ctype(1)); } // get number of elements std::vector< unsigned int > tmpNumElements; if (extendedParamTree.hasVector("numElements")) { tmpNumElements = extendedParamTree.getVector("numElements", 1u, dim); assert(tmpNumElements.size() >= dim && "Given vector too short!"); } else if (extendedParamTree.hasKey("numElements")) { const unsigned int numElement = extendedParamTree.get("numElements", 1u); tmpNumElements = std::vector< unsigned int >(dim, numElement); } else { std::cout << "\n" << Dune::Stuff::Common::highlightString("WARNING in " + id() + ":", Dune::Stuff::Common::Colors::brown) << " neither vector nor key 'numElements' given, defaulting to 1!" << std::flush; tmpNumElements = std::vector< unsigned int >(dim, 1u); } // check and save CoordinateType lowerLeft; CoordinateType upperRight; Dune::array< unsigned int, dim > numElements; for (unsigned int d = 0; d < dim; ++d) { assert(lowerLefts[d] < upperRights[d] && "Given 'upperRight' hast to be elementwise larger than given 'lowerLeft'!"); lowerLeft[d] = lowerLefts[d]; upperRight[d] = upperRights[d]; assert(tmpNumElements[d] > 0 && "Given 'numElements' has to be elementwise positive!"); numElements[d] = tmpNumElements[d]; } return GenericCube(lowerLeft, upperRight, numElements); } // static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id()) ThisType& operator=(ThisType& other) { if (this != &other) { lowerLeft_ = other.lowerLeft(); upperRight_ = other.upperRight(); grid_ = other.grid(); } return this; } // ThisType& operator=(ThisType& other) //! access to shared ptr virtual Dune::shared_ptr< GridType > grid() { return grid_; } virtual const Dune::shared_ptr< const GridType > grid() const { return grid_; } const CoordinateType& lowerLeft() const { return lowerLeft_; } const CoordinateType& upperRight() const { return upperRight_; } /** * \brief Visualizes the grid using Dune::VTKWriter. * \param[in] filename **/ private: void buildGrid(const Dune::array< unsigned int, dim >& numElements) { dune_static_assert(variant >= 1 && variant <= 2, "only variant 1 and 2 are valid"); switch (variant) { case 1: grid_ = Dune::StructuredGridFactory< GridType >::createCubeGrid(lowerLeft_, upperRight_, numElements); break; case 2: default: grid_ = Dune::StructuredGridFactory< GridType >::createSimplexGrid(lowerLeft_, upperRight_, numElements); break; } } // void buildGrid(const CoordinateType& lowerLeft, const CoordinateType& upperRight) CoordinateType lowerLeft_; CoordinateType upperRight_; Dune::shared_ptr< GridType > grid_; }; // class GenericCube template< typename GridType > struct ElementVariant { static const int id = 2; }; template< int dim > struct ElementVariant< Dune::YaspGrid< dim > > { static const int id = 1; }; template< int dim > struct ElementVariant< Dune::SGrid< dim, dim > > { static const int id = 1; }; #if HAVE_ALUGRID template< int dim > struct ElementVariant< Dune::ALUCubeGrid< dim, dim > > { static const int id = 1; }; #endif // HAVE_ALUGRID // default implementation of a cube for any grid // tested for // dim = 2 // ALUGRID_SIMPLEX, variant 2 // ALUGRID_CONFORM, variant 2 // dim = 3 // ALUGRID_SIMPLEX, variant 2 #if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG template< class GridType = Dune::GridSelector::GridType > #else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG template< class GridType = Dune::SGrid< 2, 2 > > #endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG class Cube : public GenericCube< GridType, ElementVariant<GridType>::id > { public: typedef GenericCube< GridType, ElementVariant<GridType>::id > BaseType; typedef Cube< GridType > ThisType; typedef typename BaseType::CoordinateType CoordinateType; Cube(const double _lowerLeft = 0.0, const double _upperRight = 1.0, const unsigned int _numElements = 1) : BaseType(_lowerLeft, _upperRight, _numElements) {} Cube(const CoordinateType& _lowerLeft, const CoordinateType& _upperRight, const unsigned int _numElements = 1) : BaseType(_lowerLeft, _upperRight, _numElements) {} template< class ContainerType > Cube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const ContainerType numElements = boost::assign::list_of< typename ContainerType::value_type>().repeat(GridType::dimensionworld, typename ContainerType::value_type(1u))) : BaseType(lowerLeft, upperRight, numElements) {} Cube(BaseType& other) : BaseType(other) {} static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = BaseType::id()) { BaseType base = BaseType::createFromParamTree(paramTree, subName); return ThisType(base); } }; // class Cube } // namespace Provider } // namespace Grid } // namespace Stuff } // namespace Dune #endif // HAVE_DUNE_GRID #endif // DUNE_STUFF_GRID_PROVIDER_CUBE_HH <commit_msg>[grid.provider.cube] disabled warnings from core modules<commit_after>#ifndef DUNE_STUFF_GRID_PROVIDER_CUBE_HH #define DUNE_STUFF_GRID_PROVIDER_CUBE_HH #include <dune/stuff/common/header/disable_warnings.hh> #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG #include <dune/stuff/common/header/reenable_warnings.hh> #if HAVE_DUNE_GRID #include <dune/stuff/common/header/disable_warnings.hh> #include <sstream> #include <type_traits> #include <boost/assign/list_of.hpp> #include <dune/common/parametertree.hh> #include <dune/common/shared_ptr.hh> #include <dune/common/exceptions.hh> #include <dune/common/fvector.hh> #include <dune/common/static_assert.hh> #include <dune/grid/utility/structuredgridfactory.hh> #include <dune/grid/yaspgrid.hh> #ifdef HAVE_ALUGRID #include <dune/grid/alugrid.hh> #endif #include <dune/grid/sgrid.hh> #include <dune/stuff/common/header/reenable_warnings.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/color.hh> #include "interface.hh" namespace Dune { namespace Stuff { namespace Grid { namespace Provider { /** * \brief Creates a grid of a cube in various dimensions. * * Default implementation using the Dune::StructuredGridFactory to create a grid of a cube in 1, 2 or 3 * dimensions. Tested with * <ul><li> \c YASPGRID, \c variant 1, dim = 1, 2, 3, * <li> \c SGRID, \c variant 1, dim = 1, 2, 3, * <li> \c ALUGRID_SIMPLEX, \c variant 2, dim = 2, 3, * <li> \c ALUGRID_CONFORM, \c variant 2, dim = 2, 2 and * <li> \c ALUGRID_CUBE, \c variant 1, dim = 2, 3.</ul> * \tparam GridImp * Type of the underlying grid. * \tparam variant * Type of the codim 0 elements: * <ul><li>\c 1: cubes * <li>2: simplices</ul> **/ template< typename GridImp, int variant > class GenericCube : public Interface< GridImp > { public: //! Type of the provided grid. typedef GridImp GridType; typedef Interface< GridType > BaseType; typedef GenericCube< GridType, variant > ThisType; private: typedef typename GridType::LeafGridView GridViewType; public: static const unsigned int dim = BaseType::dim; //! Type of the grids coordinates. typedef typename GridType::ctype ctype; typedef Dune::FieldVector< ctype, dim > CoordinateType; //! Unique identifier: \c stuff.grid.provider.cube static const std::string id() { return BaseType::id() + ".cube"; } /** * \brief Creates a cube. * \param[in] lowerLeft * A double that is used as a lower left corner in each dimension. * \param[in] upperRight * A double that is used as a upper right corner in each dimension. * \param[in] numElements (optional) * number of elements. **/ GenericCube(const double _lowerLeft = 0.0, const double _upperRight = 1.0, const unsigned int numElements = 1u) : lowerLeft_(_lowerLeft), upperRight_(_upperRight) { Dune::array< unsigned int, dim > tmpNumElements; std::fill(tmpNumElements.begin(), tmpNumElements.end(), numElements); buildGrid(tmpNumElements); } /** * \brief Creates a cube. * \param[in] lowerLeft * A vector that is used as a lower left corner. * \param[in] upperRight * A vector that is used as a upper right corner. * \param[in] numElements (optional) * number of elements. **/ GenericCube(const CoordinateType& _lowerLeft, const CoordinateType& _upperRight, const unsigned int numElements = 1u) : lowerLeft_(_lowerLeft), upperRight_(_upperRight) { Dune::array< unsigned int, dim > tmpNumElements; std::fill(tmpNumElements.begin(), tmpNumElements.end(), numElements); buildGrid(tmpNumElements); } /** \brief Creates a cube. This signature allows to prescribe anisotopic refinement \param[in] lowerLeft A double that is used as a lower left corner in each dimension. \param[in] upperRight A double that is used as a upper right corner in each dimension. \param[in] numElements number of elements in each dimension. can contain 0 to dim elements (missing dimension are initialized to 1) \tparam Coord anything that CoordinateType allows to copy construct from \tparam ContainerType some sequence type that functions with std::begin/end \tparam T an unsigned integral Type **/ template< class ContainerType > GenericCube(const CoordinateType& _lowerLeft, const CoordinateType& _upperRight, const ContainerType numElements = boost::assign::list_of< typename ContainerType::value_type>().repeat(dim, typename ContainerType::value_type(1u))) : lowerLeft_(_lowerLeft), upperRight_(_upperRight) { Dune::array< unsigned int, dim > tmpNumElements; static_assert(std::is_unsigned< typename ContainerType::value_type >::value && std::is_integral< typename ContainerType::value_type >::value, "only unsigned integral number of elements per dimension allowed"); //base init in case input is shorter std::fill(tmpNumElements.begin(), tmpNumElements.end(), 1u); std::copy(numElements.begin(), numElements.end(), tmpNumElements.begin()); buildGrid(tmpNumElements); } GenericCube(ThisType& other) : lowerLeft_(other.lowerLeft_) , upperRight_(other.upperRight_) , grid_(other.grid_) {} GenericCube(const ThisType& other) : lowerLeft_(other.lowerLeft_) , upperRight_(other.upperRight_) , grid_(other.grid_) {} /** * \brief Creates a cube. * \param[in] paramTree * A Dune::ParameterTree containing * <ul><li> the following keys directly or * <li> a subtree named Cube::id, containing the following keys. If a subtree is present, it is always selected. Also it is solely selceted, so that all keys in the supertree are ignored.</ul> * The actual keys are: * <ul><li> \c lowerLeft: \a double or a vector that is used as lower left corners. * <li> \c upperRight: \a double or a vector that is used as upper right corners. * <li> \c numElements: \a int or vector to denote the number of elements. * </ul> **/ static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id()) { // get correct paramTree Dune::Stuff::Common::ParameterTreeX extendedParamTree; if (paramTree.hasSub(subName)) extendedParamTree = paramTree.sub(subName); else extendedParamTree = paramTree; // get lower left std::vector< ctype > lowerLefts; if (extendedParamTree.hasVector("lowerLeft")) { lowerLefts = extendedParamTree.getVector("lowerLeft", ctype(0), dim); assert(lowerLefts.size() >= dim && "Given vector too short!"); } else if (extendedParamTree.hasKey("lowerLeft")) { const ctype lowerLeft = extendedParamTree.get("lowerLeft", ctype(0)); lowerLefts = std::vector< ctype >(dim, lowerLeft); } else { std::cout << "\n" << Dune::Stuff::Common::highlightString("WARNING in " + id() + ":", Dune::Stuff::Common::Colors::brown) << " neither vector nor key 'lowerLeft' given, defaulting to 0.0!" << std::flush; lowerLefts = std::vector< ctype >(dim, ctype(0)); } // get upper right std::vector< ctype > upperRights; if (extendedParamTree.hasVector("upperRight")) { upperRights = extendedParamTree.getVector("upperRight", ctype(1), dim); assert(upperRights.size() >= dim && "Given vector too short!"); } else if (extendedParamTree.hasKey("upperRight")) { const ctype upperRight = extendedParamTree.get("upperRight", ctype(1)); upperRights = std::vector< ctype >(dim, upperRight); } else { std::cout << "\n" << Dune::Stuff::Common::highlightString("WARNING in " + id() + ":", Dune::Stuff::Common::Colors::brown) << " neither vector nor key 'upperRight' given, defaulting to 1.0!" << std::flush; upperRights = std::vector< ctype >(dim, ctype(1)); } // get number of elements std::vector< unsigned int > tmpNumElements; if (extendedParamTree.hasVector("numElements")) { tmpNumElements = extendedParamTree.getVector("numElements", 1u, dim); assert(tmpNumElements.size() >= dim && "Given vector too short!"); } else if (extendedParamTree.hasKey("numElements")) { const unsigned int numElement = extendedParamTree.get("numElements", 1u); tmpNumElements = std::vector< unsigned int >(dim, numElement); } else { std::cout << "\n" << Dune::Stuff::Common::highlightString("WARNING in " + id() + ":", Dune::Stuff::Common::Colors::brown) << " neither vector nor key 'numElements' given, defaulting to 1!" << std::flush; tmpNumElements = std::vector< unsigned int >(dim, 1u); } // check and save CoordinateType lowerLeft; CoordinateType upperRight; Dune::array< unsigned int, dim > numElements; for (unsigned int d = 0; d < dim; ++d) { assert(lowerLefts[d] < upperRights[d] && "Given 'upperRight' hast to be elementwise larger than given 'lowerLeft'!"); lowerLeft[d] = lowerLefts[d]; upperRight[d] = upperRights[d]; assert(tmpNumElements[d] > 0 && "Given 'numElements' has to be elementwise positive!"); numElements[d] = tmpNumElements[d]; } return GenericCube(lowerLeft, upperRight, numElements); } // static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id()) ThisType& operator=(ThisType& other) { if (this != &other) { lowerLeft_ = other.lowerLeft(); upperRight_ = other.upperRight(); grid_ = other.grid(); } return this; } // ThisType& operator=(ThisType& other) //! access to shared ptr virtual Dune::shared_ptr< GridType > grid() { return grid_; } virtual const Dune::shared_ptr< const GridType > grid() const { return grid_; } const CoordinateType& lowerLeft() const { return lowerLeft_; } const CoordinateType& upperRight() const { return upperRight_; } /** * \brief Visualizes the grid using Dune::VTKWriter. * \param[in] filename **/ private: void buildGrid(const Dune::array< unsigned int, dim >& numElements) { dune_static_assert(variant >= 1 && variant <= 2, "only variant 1 and 2 are valid"); switch (variant) { case 1: grid_ = Dune::StructuredGridFactory< GridType >::createCubeGrid(lowerLeft_, upperRight_, numElements); break; case 2: default: grid_ = Dune::StructuredGridFactory< GridType >::createSimplexGrid(lowerLeft_, upperRight_, numElements); break; } } // void buildGrid(const CoordinateType& lowerLeft, const CoordinateType& upperRight) CoordinateType lowerLeft_; CoordinateType upperRight_; Dune::shared_ptr< GridType > grid_; }; // class GenericCube template< typename GridType > struct ElementVariant { static const int id = 2; }; template< int dim > struct ElementVariant< Dune::YaspGrid< dim > > { static const int id = 1; }; template< int dim > struct ElementVariant< Dune::SGrid< dim, dim > > { static const int id = 1; }; #if HAVE_ALUGRID template< int dim > struct ElementVariant< Dune::ALUCubeGrid< dim, dim > > { static const int id = 1; }; #endif // HAVE_ALUGRID // default implementation of a cube for any grid // tested for // dim = 2 // ALUGRID_SIMPLEX, variant 2 // ALUGRID_CONFORM, variant 2 // dim = 3 // ALUGRID_SIMPLEX, variant 2 #if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG template< class GridType = Dune::GridSelector::GridType > #else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG template< class GridType = Dune::SGrid< 2, 2 > > #endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG class Cube : public GenericCube< GridType, ElementVariant<GridType>::id > { public: typedef GenericCube< GridType, ElementVariant<GridType>::id > BaseType; typedef Cube< GridType > ThisType; typedef typename BaseType::CoordinateType CoordinateType; Cube(const double _lowerLeft = 0.0, const double _upperRight = 1.0, const unsigned int _numElements = 1) : BaseType(_lowerLeft, _upperRight, _numElements) {} Cube(const CoordinateType& _lowerLeft, const CoordinateType& _upperRight, const unsigned int _numElements = 1) : BaseType(_lowerLeft, _upperRight, _numElements) {} template< class ContainerType > Cube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const ContainerType numElements = boost::assign::list_of< typename ContainerType::value_type>().repeat(GridType::dimensionworld, typename ContainerType::value_type(1u))) : BaseType(lowerLeft, upperRight, numElements) {} Cube(BaseType& other) : BaseType(other) {} static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = BaseType::id()) { BaseType base = BaseType::createFromParamTree(paramTree, subName); return ThisType(base); } }; // class Cube } // namespace Provider } // namespace Grid } // namespace Stuff } // namespace Dune #endif // HAVE_DUNE_GRID #endif // DUNE_STUFF_GRID_PROVIDER_CUBE_HH <|endoftext|>
<commit_before>#ifndef DUNE_STUFF_GRID_PROVIDER_CUBE_HH #define DUNE_STUFF_GRID_PROVIDER_CUBE_HH // system #include <sstream> // dune-common #include <dune/common/parametertree.hh> #include <dune/common/shared_ptr.hh> #include <dune/common/exceptions.hh> #include <dune/common/fvector.hh> // dune-grid #include <dune/grid/utility/structuredgridfactory.hh> #include <dune/grid/yaspgrid.hh> #include <dune/grid/alugrid.hh> #include <dune/grid/sgrid.hh> #include <dune/grid/common/mcmgmapper.hh> #include <dune/grid/io/file/vtk/vtkwriter.hh> namespace Dune { namespace Stuff { namespace Grid { namespace Provider { /** * \brief Creates a grid of a cube in various dimensions. * * Default implementation using the Dune::StructuredGridFactory to create a grid of a cube in 1, 2 or 3 * dimensions. Tested with * <ul><li> \c YASPGRID, \c variant 1, dim = 1, 2, 3, * <li> \c SGRID, \c variant 1, dim = 1, 2, 3, * <li> \c ALUGRID_SIMPLEX, \c variant 2, dim = 2, 3, * <li> \c ALUGRID_CONFORM, \c variant 2, dim = 2, 2 and * <li> \c ALUGRID_CUBE, \c variant 1, dim = 2, 3.</ul> * \tparam GridImp * Type of the underlying grid. * \tparam variant * Type of the codim 0 elements: * <ul><li>\c 1: cubes * <li>2: simplices</ul> **/ template< typename GridImp, int variant > class GenericCube { public: //! Type of the provided grid. typedef GridImp GridType; //! Dimension of the provided grid. static const unsigned int dim = GridType::dimension; //! Type of the grids coordinates. typedef Dune::FieldVector< typename GridType::ctype, dim > CoordinateType; //! Unique identifier: \c stuff.grid.provider.cube static const std::string id; /** * \brief Creates a cube. * \param[in] paramTree * A Dune::ParameterTree containing * <ul><li> the following keys directly or * <li> a subtree named Cube::id, containing the following keys. If a subtree is present, it is always selected. Also it is solely selceted, so that all keys in the supertree are ignored.</ul> * The actual keys are: * <ul><li> \c lowerLeft: \a double that is used as a lower left corner in each dimension. * <li> \c upperRight: \a double that is used as an upper right corner in each dimension. * <li> \c numElements.D \a int to denote the number of elements in direction of dimension D (has to be given for each dimension seperately). * <li> \c level: \a int level of refinement. If given, overrides numElements and creates \f$ 2^level \f$ elements per dimension. * </ul> **/ GenericCube(const Dune::ParameterTree paramTree) : lowerLeft_(0.0), upperRight_(1.0) { // select subtree (if necessary) Dune::ParameterTree paramTree_ = paramTree; if (paramTree.hasSub(id)) paramTree_ = paramTree.sub(id); // get outer bounds const double lowerLeft = paramTree_.get("lowerLeft", 0.0); const double upperRight = paramTree_.get("upperRight", 1.0); assert(lowerLeft < upperRight); lowerLeft_ = lowerLeft; upperRight_ = upperRight; // get number of elements per dim if (paramTree.hasKey("level")) std::fill(numElements_.begin(), numElements_.end(), std::pow(2, paramTree_.get("level", 1))); else { for (unsigned int d = 0; d < dim; ++d) { std::stringstream s; s << "numElements." << d; numElements_[d] = paramTree.get(s.str(), 1); } } buildGrid(); } // Cube(const Dune::ParameterTree& paramTree) /** * \brief Creates a cube. * \param[in] lowerLeft * A vector that is used as a lower left corner. * \param[in] upperRight * A vector that is used as a upper right corner. * \param[in] level (optional) * Level of refinement (see constructor for details). **/ GenericCube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const int level = 1) : lowerLeft_(lowerLeft), upperRight_(upperRight) { std::fill(numElements_.begin(), numElements_.end(), std::pow(2, level)); buildGrid(); } /** * \brief Creates a cube. * \param[in] lowerLeft * A double that is used as a lower left corner in each dimension. * \param[in] upperRight * A double that is used as a upper right corner in each dimension. * \param[in] level (optional) * Level of refinement (see constructor for details). **/ GenericCube(const double lowerLeft, const double upperRight, const int level = 1) : lowerLeft_(lowerLeft), upperRight_(upperRight) { std::fill(numElements_.begin(), numElements_.end(), std::pow(2, level)); buildGrid(); } /** * \brief Provides access to the created grid. * \return Reference to the grid. **/ GridType& grid() { return *grid_; } /** * \brief Provides const access to the created grid. * \return Reference to the grid. **/ const GridType& grid() const { return *grid_; } const CoordinateType& lowerLeft() const { return lowerLeft_; } const CoordinateType& upperRight() const { return upperRight_; } private: template< int dim > struct P0Layout { bool DUNE_DEPRECATED_MSG("geometries should be passed by value") contains(Dune::GeometryType& geometry) { return geometry.dim() == dim; } bool contains(const Dune::GeometryType geometry) { return geometry.dim() == dim; } }; // layout class for codim 0 mapper public: /** * \brief Visualizes the grid using Dune::VTKWriter. * \param[in] filename **/ void visualize(const std::string filename = id + ".grid") const { // grid view typedef typename GridType::LeafGridView GridView; GridView gridView = grid().leafView(); // mapper Dune::LeafMultipleCodimMultipleGeomTypeMapper< GridType, P0Layout > mapper(grid()); std::vector< double > data(mapper.size()); // walk the grid typedef typename GridView::template Codim<0>::Iterator ElementIterator; typedef typename GridView::template Codim<0>::Entity ElementType; typedef typename ElementType::LeafIntersectionIterator FacetIteratorType; for (ElementIterator it = gridView.template begin<0>(); it != gridView.template end<0>(); ++it) { ElementType& element = *it; data[mapper.map(element)] = 0.0; int numberOfBoundarySegments = 0; bool isOnBoundary = false; // walk the intersections for (FacetIteratorType facet = element.ileafbegin(); facet != element.ileafend(); ++facet) { if (!facet->neighbor() && facet->boundary()){ isOnBoundary = true; numberOfBoundarySegments += 1; data[mapper.map(element)] += double(facet->boundaryId()); } } // walk the intersections if (isOnBoundary) { data[mapper.map(element)] /= double(numberOfBoundarySegments); } } // walk the grid // write to vtk Dune::VTKWriter< GridView > vtkwriter(gridView); vtkwriter.addCellData(data, "boundaryId"); vtkwriter.write(filename, Dune::VTK::ascii); } // void visualize(const std::string filename = id + ".grid") const private: void buildGrid() { switch (variant) { case 1: grid_ = Dune::StructuredGridFactory< GridType >::createCubeGrid(lowerLeft_, upperRight_, numElements_); break; case 2: grid_ = Dune::StructuredGridFactory< GridType >::createSimplexGrid(lowerLeft_, upperRight_, numElements_); break; default: DUNE_THROW(Dune::NotImplemented, "Variant " << variant << " not valid (only 1 and 2 are)."); } return; } // void buildGrid(const CoordinateType& lowerLeft, const CoordinateType& upperRight) CoordinateType lowerLeft_; CoordinateType upperRight_; Dune::array< unsigned int, dim > numElements_; Dune::shared_ptr< GridType > grid_; }; // class GenericCube template< typename GridImp, int variant > const std::string GenericCube< GridImp, variant >::id = "stuff.grid.provider.cube"; template< typename GridType > struct ElementVariant { static const int id = 2; }; template< int dim > struct ElementVariant< Dune::YaspGrid< dim > > { static const int id = 1; }; template< int dim > struct ElementVariant< Dune::SGrid< dim, dim > > { static const int id = 1; }; #ifdef HAVE_ALUGRID template< int dim > struct ElementVariant< Dune::ALUCubeGrid< dim, dim > > { static const int id = 1; }; #endif // default implementation of a cube for any grid // tested for // dim = 2 // ALUGRID_SIMPLEX, variant 2 // ALUGRID_CONFORM, variant 2 // dim = 3 // ALUGRID_SIMPLEX, variant 2 template< typename GridType > class Cube : public GenericCube< GridType, ElementVariant<GridType>::id > { private: typedef GenericCube< GridType, ElementVariant<GridType>::id > BaseType; public: typedef typename BaseType::CoordinateType CoordinateType; Cube(const Dune::ParameterTree& paramTree) : BaseType(paramTree) {} Cube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const int level = 1) : BaseType(lowerLeft, upperRight, level) {} Cube(const double lowerLeft, const double upperRight, const int level = 1) : BaseType(lowerLeft, upperRight, level) {} }; // class Cube template< typename GridType > class UnitCube : public Cube< GridType > { private: typedef Cube< GridType > BaseType; public: UnitCube(const Dune::ParameterTree& paramTree) : BaseType(0.0, 1.0, paramTree.get("level", 1)) {} UnitCube(const int level = 1) : BaseType(0.0, 1.0, level) {} }; // class UnitCube } // namespace Provider } // namespace Grid } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_GRID_PROVIDER_CUBE_HH <commit_msg>[grid.provider] adds a new a new ctor signature for anisotropic gird gen.<commit_after>#ifndef DUNE_STUFF_GRID_PROVIDER_CUBE_HH #define DUNE_STUFF_GRID_PROVIDER_CUBE_HH // system #include <sstream> #include <boost/assign/list_of.hpp> // dune-common #include <dune/common/parametertree.hh> #include <dune/common/shared_ptr.hh> #include <dune/common/exceptions.hh> #include <dune/common/fvector.hh> // dune-grid #include <dune/grid/utility/structuredgridfactory.hh> #include <dune/grid/yaspgrid.hh> #include <dune/grid/alugrid.hh> #include <dune/grid/sgrid.hh> #include <dune/grid/common/mcmgmapper.hh> #include <dune/grid/io/file/vtk/vtkwriter.hh> namespace Dune { namespace Stuff { namespace Grid { namespace Provider { /** * \brief Creates a grid of a cube in various dimensions. * * Default implementation using the Dune::StructuredGridFactory to create a grid of a cube in 1, 2 or 3 * dimensions. Tested with * <ul><li> \c YASPGRID, \c variant 1, dim = 1, 2, 3, * <li> \c SGRID, \c variant 1, dim = 1, 2, 3, * <li> \c ALUGRID_SIMPLEX, \c variant 2, dim = 2, 3, * <li> \c ALUGRID_CONFORM, \c variant 2, dim = 2, 2 and * <li> \c ALUGRID_CUBE, \c variant 1, dim = 2, 3.</ul> * \tparam GridImp * Type of the underlying grid. * \tparam variant * Type of the codim 0 elements: * <ul><li>\c 1: cubes * <li>2: simplices</ul> **/ template< typename GridImp, int variant > class GenericCube { public: //! Type of the provided grid. typedef GridImp GridType; //! Dimension of the provided grid. static const unsigned int dim = GridType::dimension; //! Type of the grids coordinates. typedef Dune::FieldVector< typename GridType::ctype, dim > CoordinateType; //! Unique identifier: \c stuff.grid.provider.cube static const std::string id; /** * \brief Creates a cube. * \param[in] paramTree * A Dune::ParameterTree containing * <ul><li> the following keys directly or * <li> a subtree named Cube::id, containing the following keys. If a subtree is present, it is always selected. Also it is solely selceted, so that all keys in the supertree are ignored.</ul> * The actual keys are: * <ul><li> \c lowerLeft: \a double that is used as a lower left corner in each dimension. * <li> \c upperRight: \a double that is used as an upper right corner in each dimension. * <li> \c numElements.D \a int to denote the number of elements in direction of dimension D (has to be given for each dimension seperately). * <li> \c level: \a int level of refinement. If given, overrides numElements and creates \f$ 2^level \f$ elements per dimension. * </ul> **/ GenericCube(const Dune::ParameterTree paramTree) : lowerLeft_(0.0), upperRight_(1.0) { // select subtree (if necessary) Dune::ParameterTree paramTree_ = paramTree; if (paramTree.hasSub(id)) paramTree_ = paramTree.sub(id); // get outer bounds const double lowerLeft = paramTree_.get("lowerLeft", 0.0); const double upperRight = paramTree_.get("upperRight", 1.0); assert(lowerLeft < upperRight); lowerLeft_ = lowerLeft; upperRight_ = upperRight; // get number of elements per dim if (paramTree.hasKey("level")) std::fill(std::begin(numElements_), std::end(numElements_), std::pow(2, paramTree.get("level", 1))); else { for (unsigned int d = 0; d < dim; ++d) { std::stringstream s; s << "numElements." << d; numElements_[d] = paramTree.get(s.str(), 1); } } buildGrid(); } // Cube(const Dune::ParameterTree& paramTree) /** * \brief Creates a cube. * \param[in] lowerLeft * A vector that is used as a lower left corner. * \param[in] upperRight * A vector that is used as a upper right corner. * \param[in] level (optional) * Level of refinement (see constructor for details). **/ GenericCube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const int level = 1) : lowerLeft_(lowerLeft), upperRight_(upperRight) { std::fill(numElements_.begin(), numElements_.end(), std::pow(2, level)); buildGrid(); } /** * \brief Creates a cube. * \param[in] lowerLeft * A double that is used as a lower left corner in each dimension. * \param[in] upperRight * A double that is used as a upper right corner in each dimension. * \param[in] level (optional) * Level of refinement (see constructor for details). **/ GenericCube(const double lowerLeft, const double upperRight, const int level = 1) : lowerLeft_(lowerLeft), upperRight_(upperRight) { std::fill(std::begin(numElements_), std::end(numElements_), std::pow(2, level)); buildGrid(); } /** \brief Creates a cube. This signature allows to prescribe anisotopic refinement \param[in] lowerLeft A double that is used as a lower left corner in each dimension. \param[in] upperRight A double that is used as a upper right corner in each dimension. \param[in] elements_per_dim number of elements in each dimension. can contain 0 to dim elements (missing dimension are initialized to 1) \tparam Coord anything that CoordinateType allows to copy construct from \tparam ContainerType some sequence type that functions with std::begin/end \tparam T an unsigned integral Type **/ template < class Coord, class ContainerType > GenericCube(const Coord lowerLeft, const Coord upperRight, const ContainerType elements_per_dim = boost::assign::list_of<typename ContainerType::value_type>().repeat(GridType::dimensionworld,typename ContainerType::value_type(1)) ) : lowerLeft_(lowerLeft), upperRight_(upperRight) { static_assert(std::is_unsigned<typename ContainerType::value_type>::value && std::is_integral<typename ContainerType::value_type>::value, "only unsigned integral number of elements per dimension allowed"); //base init in case input is shorter std::fill(std::begin(numElements_), std::end(numElements_), 1); std::copy(std::begin(elements_per_dim), std::end(elements_per_dim), std::begin(numElements_)); buildGrid(); } /** \brief Provides access to the created grid. \return Reference to the grid. **/ GridType& grid() { return *grid_; } /** * \brief Provides const access to the created grid. * \return Reference to the grid. **/ const GridType& grid() const { return *grid_; } const CoordinateType& lowerLeft() const { return lowerLeft_; } const CoordinateType& upperRight() const { return upperRight_; } private: template< int dim > struct P0Layout { bool DUNE_DEPRECATED_MSG("geometries should be passed by value") contains(Dune::GeometryType& geometry) { return geometry.dim() == dim; } bool contains(const Dune::GeometryType geometry) { return geometry.dim() == dim; } }; // layout class for codim 0 mapper public: /** * \brief Visualizes the grid using Dune::VTKWriter. * \param[in] filename **/ void visualize(const std::string filename = id + ".grid") const { // grid view typedef typename GridType::LeafGridView GridView; GridView gridView = grid().leafView(); // mapper Dune::LeafMultipleCodimMultipleGeomTypeMapper< GridType, P0Layout > mapper(grid()); std::vector< double > data(mapper.size()); // walk the grid typedef typename GridView::template Codim<0>::Iterator ElementIterator; typedef typename GridView::template Codim<0>::Entity ElementType; typedef typename ElementType::LeafIntersectionIterator FacetIteratorType; for (ElementIterator it = gridView.template begin<0>(); it != gridView.template end<0>(); ++it) { ElementType& element = *it; data[mapper.map(element)] = 0.0; int numberOfBoundarySegments = 0; bool isOnBoundary = false; // walk the intersections for (FacetIteratorType facet = element.ileafbegin(); facet != element.ileafend(); ++facet) { if (!facet->neighbor() && facet->boundary()){ isOnBoundary = true; numberOfBoundarySegments += 1; data[mapper.map(element)] += double(facet->boundaryId()); } } // walk the intersections if (isOnBoundary) { data[mapper.map(element)] /= double(numberOfBoundarySegments); } } // walk the grid // write to vtk Dune::VTKWriter< GridView > vtkwriter(gridView); vtkwriter.addCellData(data, "boundaryId"); vtkwriter.write(filename, Dune::VTK::ascii); } // void visualize(const std::string filename = id + ".grid") const private: void buildGrid() { switch (variant) { case 1: grid_ = Dune::StructuredGridFactory< GridType >::createCubeGrid(lowerLeft_, upperRight_, numElements_); break; case 2: grid_ = Dune::StructuredGridFactory< GridType >::createSimplexGrid(lowerLeft_, upperRight_, numElements_); break; default: DUNE_THROW(Dune::NotImplemented, "Variant " << variant << " not valid (only 1 and 2 are)."); } return; } // void buildGrid(const CoordinateType& lowerLeft, const CoordinateType& upperRight) CoordinateType lowerLeft_; CoordinateType upperRight_; Dune::array< unsigned int, dim > numElements_; Dune::shared_ptr< GridType > grid_; }; // class GenericCube template< typename GridImp, int variant > const std::string GenericCube< GridImp, variant >::id = "stuff.grid.provider.cube"; template< typename GridType > struct ElementVariant { static const int id = 2; }; template< int dim > struct ElementVariant< Dune::YaspGrid< dim > > { static const int id = 1; }; template< int dim > struct ElementVariant< Dune::SGrid< dim, dim > > { static const int id = 1; }; #ifdef HAVE_ALUGRID template< int dim > struct ElementVariant< Dune::ALUCubeGrid< dim, dim > > { static const int id = 1; }; #endif // default implementation of a cube for any grid // tested for // dim = 2 // ALUGRID_SIMPLEX, variant 2 // ALUGRID_CONFORM, variant 2 // dim = 3 // ALUGRID_SIMPLEX, variant 2 template< typename GridType > class Cube : public GenericCube< GridType, ElementVariant<GridType>::id > { private: typedef GenericCube< GridType, ElementVariant<GridType>::id > BaseType; public: typedef typename BaseType::CoordinateType CoordinateType; Cube(const Dune::ParameterTree& paramTree) : BaseType(paramTree) {} Cube(const CoordinateType& lowerLeft, const CoordinateType& upperRight, const int level = 1) : BaseType(lowerLeft, upperRight, level) {} Cube(const double lowerLeft, const double upperRight, const int level = 1) : BaseType(lowerLeft, upperRight, level) {} template < class Coord, class ContainerType > Cube(const Coord lowerLeft, const Coord upperRight, const ContainerType elements_per_dim = boost::assign::list_of<typename ContainerType::value_type>().repeat(GridType::dimensionworld,typename ContainerType::value_type(1)) ) : BaseType(lowerLeft, upperRight, elements_per_dim) {} }; // class Cube template< typename GridType > class UnitCube : public Cube< GridType > { private: typedef Cube< GridType > BaseType; public: UnitCube(const Dune::ParameterTree& paramTree) : BaseType(0.0, 1.0, paramTree.get("level", 1)) {} UnitCube(const int level = 1) : BaseType(0.0, 1.0, level) {} }; // class UnitCube } // namespace Provider } // namespace Grid } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_GRID_PROVIDER_CUBE_HH <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xtextedt.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: hr $ $Date: 2007-06-27 21:32:31 $ * * 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_svtools.hxx" #include <svtools/xtextedt.hxx> #include <vcl/svapp.hxx> // International #include <unotools/textsearch.hxx> #ifndef _COM_SUN_STAR_UTIL_SEARCHOPTIONS_HPP_ #include <com/sun/star/util/SearchOptions.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HPP_ #include <com/sun/star/util/SearchFlags.hpp> #endif using namespace ::com::sun::star; // ------------------------------------------------------------------------- // class ExtTextEngine // ------------------------------------------------------------------------- ExtTextEngine::ExtTextEngine() : maGroupChars( String::CreateFromAscii( "(){}[]", 6 ) ) { } ExtTextEngine::~ExtTextEngine() { } TextSelection ExtTextEngine::MatchGroup( const TextPaM& rCursor ) const { TextSelection aSel( rCursor ); USHORT nPos = rCursor.GetIndex(); ULONG nPara = rCursor.GetPara(); ULONG nParas = GetParagraphCount(); if ( ( nPara < nParas ) && ( nPos < GetTextLen( nPara ) ) ) { USHORT nMatchChar = maGroupChars.Search( GetText( rCursor.GetPara() ).GetChar( nPos ) ); if ( nMatchChar != STRING_NOTFOUND ) { if ( ( nMatchChar % 2 ) == 0 ) { // Vorwaerts suchen... sal_Unicode nSC = maGroupChars.GetChar( nMatchChar ); sal_Unicode nEC = maGroupChars.GetChar( nMatchChar+1 ); USHORT nCur = nPos+1; USHORT nLevel = 1; while ( nLevel && ( nPara < nParas ) ) { XubString aStr = GetText( nPara ); while ( nCur < aStr.Len() ) { if ( aStr.GetChar( nCur ) == nSC ) nLevel++; else if ( aStr.GetChar( nCur ) == nEC ) { nLevel--; if ( !nLevel ) break; // while nCur... } nCur++; } if ( nLevel ) { nPara++; nCur = 0; } } if ( nLevel == 0 ) // gefunden { aSel.GetStart() = rCursor; aSel.GetEnd() = TextPaM( nPara, nCur+1 ); } } else { // Rueckwaerts suchen... xub_Unicode nEC = maGroupChars.GetChar( nMatchChar ); xub_Unicode nSC = maGroupChars.GetChar( nMatchChar-1 ); USHORT nCur = rCursor.GetIndex()-1; USHORT nLevel = 1; while ( nLevel ) { if ( GetTextLen( nPara ) ) { XubString aStr = GetText( nPara ); while ( nCur ) { if ( aStr.GetChar( nCur ) == nSC ) { nLevel--; if ( !nLevel ) break; // while nCur... } else if ( aStr.GetChar( nCur ) == nEC ) nLevel++; nCur--; } } if ( nLevel ) { if ( nPara ) { nPara--; nCur = GetTextLen( nPara )-1; // egal ob negativ, weil if Len() } else break; } } if ( nLevel == 0 ) // gefunden { aSel.GetStart() = rCursor; aSel.GetStart().GetIndex()++; // hinter das Zeichen aSel.GetEnd() = TextPaM( nPara, nCur ); } } } } return aSel; } BOOL ExtTextEngine::Search( TextSelection& rSel, const util::SearchOptions& rSearchOptions, BOOL bForward ) { TextSelection aSel( rSel ); aSel.Justify(); BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) ); TextPaM aStartPaM( aSel.GetEnd() ); if ( aSel.HasRange() && ( ( bSearchInSelection && bForward ) || ( !bSearchInSelection && !bForward ) ) ) { aStartPaM = aSel.GetStart(); } bool bFound = false; ULONG nStartNode, nEndNode; if ( bSearchInSelection ) nEndNode = bForward ? aSel.GetEnd().GetPara() : aSel.GetStart().GetPara(); else nEndNode = bForward ? (GetParagraphCount()-1) : 0; nStartNode = aStartPaM.GetPara(); util::SearchOptions aOptions( rSearchOptions ); aOptions.Locale = Application::GetSettings().GetLocale(); utl::TextSearch aSearcher( rSearchOptions ); // ueber die Absaetze iterieren... for ( ULONG nNode = nStartNode; bForward ? ( nNode <= nEndNode) : ( nNode >= nEndNode ); bForward ? nNode++ : nNode-- ) { String aText = GetText( nNode ); USHORT nStartPos = 0; USHORT nEndPos = aText.Len(); if ( nNode == nStartNode ) { if ( bForward ) nStartPos = aStartPaM.GetIndex(); else nEndPos = aStartPaM.GetIndex(); } if ( ( nNode == nEndNode ) && bSearchInSelection ) { if ( bForward ) nEndPos = aSel.GetEnd().GetIndex(); else nStartPos = aSel.GetStart().GetIndex(); } if ( bForward ) bFound = aSearcher.SearchFrwrd( aText, &nStartPos, &nEndPos ); else bFound = aSearcher.SearchBkwrd( aText, &nEndPos, &nStartPos ); if ( bFound ) { rSel.GetStart().GetPara() = nNode; rSel.GetStart().GetIndex() = nStartPos; rSel.GetEnd().GetPara() = nNode; rSel.GetEnd().GetIndex() = nEndPos; // Ueber den Absatz selektieren? // Select over the paragraph? // FIXME This should be max long... if( nEndPos == sal::static_int_cast<USHORT>(-1) ) // USHORT for 0 and -1 ! { if ( (rSel.GetEnd().GetPara()+1) < GetParagraphCount() ) { rSel.GetEnd().GetPara()++; rSel.GetEnd().GetIndex() = 0; } else { rSel.GetEnd().GetIndex() = nStartPos; bFound = false; } } break; } if ( !bForward && !nNode ) // Bei rueckwaertsuche, wenn nEndNode = 0: break; } return bFound; } // ------------------------------------------------------------------------- // class ExtTextView // ------------------------------------------------------------------------- ExtTextView::ExtTextView( ExtTextEngine* pEng, Window* pWindow ) : TextView( pEng, pWindow ) { } ExtTextView::~ExtTextView() { } BOOL ExtTextView::MatchGroup() { TextSelection aTmpSel( GetSelection() ); aTmpSel.Justify(); if ( ( aTmpSel.GetStart().GetPara() != aTmpSel.GetEnd().GetPara() ) || ( ( aTmpSel.GetEnd().GetIndex() - aTmpSel.GetStart().GetIndex() ) > 1 ) ) { return FALSE; } TextSelection aMatchSel = ((ExtTextEngine*)GetTextEngine())->MatchGroup( aTmpSel.GetStart() ); if ( aMatchSel.HasRange() ) SetSelection( aMatchSel ); return aMatchSel.HasRange() ? TRUE : FALSE; } BOOL ExtTextView::Search( const util::SearchOptions& rSearchOptions, BOOL bForward ) { BOOL bFound = FALSE; TextSelection aSel( GetSelection() ); if ( ((ExtTextEngine*)GetTextEngine())->Search( aSel, rSearchOptions, bForward ) ) { bFound = TRUE; // Erstmal den Anfang des Wortes als Selektion einstellen, // damit das ganze Wort in den sichtbaren Bereich kommt. SetSelection( aSel.GetStart() ); ShowCursor( TRUE, FALSE ); } else { aSel = GetSelection().GetEnd(); } SetSelection( aSel ); ShowCursor(); return bFound; } USHORT ExtTextView::Replace( const util::SearchOptions& rSearchOptions, BOOL bAll, BOOL bForward ) { USHORT nFound = 0; if ( !bAll ) { if ( GetSelection().HasRange() ) { InsertText( rSearchOptions.replaceString ); nFound = 1; Search( rSearchOptions, bForward ); // gleich zum naechsten } else { if( Search( rSearchOptions, bForward ) ) nFound = 1; } } else { // Der Writer ersetzt alle, vom Anfang bis Ende... ExtTextEngine* pTextEngine = (ExtTextEngine*)GetTextEngine(); // HideSelection(); TextSelection aSel; BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) ); if ( bSearchInSelection ) { aSel = GetSelection(); aSel.Justify(); } TextSelection aSearchSel( aSel ); BOOL bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE ); if ( bFound ) pTextEngine->UndoActionStart( XTEXTUNDO_REPLACEALL ); while ( bFound ) { nFound++; TextPaM aNewStart = pTextEngine->ImpInsertText( aSel, rSearchOptions.replaceString ); aSel = aSearchSel; aSel.GetStart() = aNewStart; bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE ); } if ( nFound ) { SetSelection( aSel.GetStart() ); pTextEngine->FormatAndUpdate( this ); pTextEngine->UndoActionEnd( XTEXTUNDO_REPLACEALL ); } } return nFound; } BOOL ExtTextView::ImpIndentBlock( BOOL bRight ) { BOOL bDone = FALSE; TextSelection aSel = GetSelection(); aSel.Justify(); HideSelection(); GetTextEngine()->UndoActionStart( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK ); ULONG nStartPara = aSel.GetStart().GetPara(); ULONG nEndPara = aSel.GetEnd().GetPara(); if ( aSel.HasRange() && !aSel.GetEnd().GetIndex() ) { nEndPara--; // den dann nicht einruecken... } for ( ULONG nPara = nStartPara; nPara <= nEndPara; nPara++ ) { if ( bRight ) { // Tabs hinzufuegen GetTextEngine()->ImpInsertText( TextPaM( nPara, 0 ), '\t' ); bDone = TRUE; } else { // Tabs/Blanks entfernen String aText = GetTextEngine()->GetText( nPara ); if ( aText.Len() && ( ( aText.GetChar( 0 ) == '\t' ) || ( aText.GetChar( 0 ) == ' ' ) ) ) { GetTextEngine()->ImpDeleteText( TextSelection( TextPaM( nPara, 0 ), TextPaM( nPara, 1 ) ) ); bDone = TRUE; } } } GetTextEngine()->UndoActionEnd( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK ); BOOL bRange = aSel.HasRange(); if ( bRight ) { aSel.GetStart().GetIndex()++; if ( bRange && ( aSel.GetEnd().GetPara() == nEndPara ) ) aSel.GetEnd().GetIndex()++; } else { if ( aSel.GetStart().GetIndex() ) aSel.GetStart().GetIndex()--; if ( bRange && aSel.GetEnd().GetIndex() ) aSel.GetEnd().GetIndex()--; } ImpSetSelection( aSel ); GetTextEngine()->FormatAndUpdate( this ); return bDone; } BOOL ExtTextView::IndentBlock() { return ImpIndentBlock( TRUE ); } BOOL ExtTextView::UnindentBlock() { return ImpIndentBlock( FALSE ); } <commit_msg>INTEGRATION: CWS changefileheader (1.14.246); FILE MERGED 2008/04/01 12:43:32 thb 1.14.246.2: #i85898# Stripping all external header guards 2008/03/31 13:01:52 rt 1.14.246.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xtextedt.cxx,v $ * $Revision: 1.15 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <svtools/xtextedt.hxx> #include <vcl/svapp.hxx> // International #include <unotools/textsearch.hxx> #include <com/sun/star/util/SearchOptions.hpp> #include <com/sun/star/util/SearchFlags.hpp> using namespace ::com::sun::star; // ------------------------------------------------------------------------- // class ExtTextEngine // ------------------------------------------------------------------------- ExtTextEngine::ExtTextEngine() : maGroupChars( String::CreateFromAscii( "(){}[]", 6 ) ) { } ExtTextEngine::~ExtTextEngine() { } TextSelection ExtTextEngine::MatchGroup( const TextPaM& rCursor ) const { TextSelection aSel( rCursor ); USHORT nPos = rCursor.GetIndex(); ULONG nPara = rCursor.GetPara(); ULONG nParas = GetParagraphCount(); if ( ( nPara < nParas ) && ( nPos < GetTextLen( nPara ) ) ) { USHORT nMatchChar = maGroupChars.Search( GetText( rCursor.GetPara() ).GetChar( nPos ) ); if ( nMatchChar != STRING_NOTFOUND ) { if ( ( nMatchChar % 2 ) == 0 ) { // Vorwaerts suchen... sal_Unicode nSC = maGroupChars.GetChar( nMatchChar ); sal_Unicode nEC = maGroupChars.GetChar( nMatchChar+1 ); USHORT nCur = nPos+1; USHORT nLevel = 1; while ( nLevel && ( nPara < nParas ) ) { XubString aStr = GetText( nPara ); while ( nCur < aStr.Len() ) { if ( aStr.GetChar( nCur ) == nSC ) nLevel++; else if ( aStr.GetChar( nCur ) == nEC ) { nLevel--; if ( !nLevel ) break; // while nCur... } nCur++; } if ( nLevel ) { nPara++; nCur = 0; } } if ( nLevel == 0 ) // gefunden { aSel.GetStart() = rCursor; aSel.GetEnd() = TextPaM( nPara, nCur+1 ); } } else { // Rueckwaerts suchen... xub_Unicode nEC = maGroupChars.GetChar( nMatchChar ); xub_Unicode nSC = maGroupChars.GetChar( nMatchChar-1 ); USHORT nCur = rCursor.GetIndex()-1; USHORT nLevel = 1; while ( nLevel ) { if ( GetTextLen( nPara ) ) { XubString aStr = GetText( nPara ); while ( nCur ) { if ( aStr.GetChar( nCur ) == nSC ) { nLevel--; if ( !nLevel ) break; // while nCur... } else if ( aStr.GetChar( nCur ) == nEC ) nLevel++; nCur--; } } if ( nLevel ) { if ( nPara ) { nPara--; nCur = GetTextLen( nPara )-1; // egal ob negativ, weil if Len() } else break; } } if ( nLevel == 0 ) // gefunden { aSel.GetStart() = rCursor; aSel.GetStart().GetIndex()++; // hinter das Zeichen aSel.GetEnd() = TextPaM( nPara, nCur ); } } } } return aSel; } BOOL ExtTextEngine::Search( TextSelection& rSel, const util::SearchOptions& rSearchOptions, BOOL bForward ) { TextSelection aSel( rSel ); aSel.Justify(); BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) ); TextPaM aStartPaM( aSel.GetEnd() ); if ( aSel.HasRange() && ( ( bSearchInSelection && bForward ) || ( !bSearchInSelection && !bForward ) ) ) { aStartPaM = aSel.GetStart(); } bool bFound = false; ULONG nStartNode, nEndNode; if ( bSearchInSelection ) nEndNode = bForward ? aSel.GetEnd().GetPara() : aSel.GetStart().GetPara(); else nEndNode = bForward ? (GetParagraphCount()-1) : 0; nStartNode = aStartPaM.GetPara(); util::SearchOptions aOptions( rSearchOptions ); aOptions.Locale = Application::GetSettings().GetLocale(); utl::TextSearch aSearcher( rSearchOptions ); // ueber die Absaetze iterieren... for ( ULONG nNode = nStartNode; bForward ? ( nNode <= nEndNode) : ( nNode >= nEndNode ); bForward ? nNode++ : nNode-- ) { String aText = GetText( nNode ); USHORT nStartPos = 0; USHORT nEndPos = aText.Len(); if ( nNode == nStartNode ) { if ( bForward ) nStartPos = aStartPaM.GetIndex(); else nEndPos = aStartPaM.GetIndex(); } if ( ( nNode == nEndNode ) && bSearchInSelection ) { if ( bForward ) nEndPos = aSel.GetEnd().GetIndex(); else nStartPos = aSel.GetStart().GetIndex(); } if ( bForward ) bFound = aSearcher.SearchFrwrd( aText, &nStartPos, &nEndPos ); else bFound = aSearcher.SearchBkwrd( aText, &nEndPos, &nStartPos ); if ( bFound ) { rSel.GetStart().GetPara() = nNode; rSel.GetStart().GetIndex() = nStartPos; rSel.GetEnd().GetPara() = nNode; rSel.GetEnd().GetIndex() = nEndPos; // Ueber den Absatz selektieren? // Select over the paragraph? // FIXME This should be max long... if( nEndPos == sal::static_int_cast<USHORT>(-1) ) // USHORT for 0 and -1 ! { if ( (rSel.GetEnd().GetPara()+1) < GetParagraphCount() ) { rSel.GetEnd().GetPara()++; rSel.GetEnd().GetIndex() = 0; } else { rSel.GetEnd().GetIndex() = nStartPos; bFound = false; } } break; } if ( !bForward && !nNode ) // Bei rueckwaertsuche, wenn nEndNode = 0: break; } return bFound; } // ------------------------------------------------------------------------- // class ExtTextView // ------------------------------------------------------------------------- ExtTextView::ExtTextView( ExtTextEngine* pEng, Window* pWindow ) : TextView( pEng, pWindow ) { } ExtTextView::~ExtTextView() { } BOOL ExtTextView::MatchGroup() { TextSelection aTmpSel( GetSelection() ); aTmpSel.Justify(); if ( ( aTmpSel.GetStart().GetPara() != aTmpSel.GetEnd().GetPara() ) || ( ( aTmpSel.GetEnd().GetIndex() - aTmpSel.GetStart().GetIndex() ) > 1 ) ) { return FALSE; } TextSelection aMatchSel = ((ExtTextEngine*)GetTextEngine())->MatchGroup( aTmpSel.GetStart() ); if ( aMatchSel.HasRange() ) SetSelection( aMatchSel ); return aMatchSel.HasRange() ? TRUE : FALSE; } BOOL ExtTextView::Search( const util::SearchOptions& rSearchOptions, BOOL bForward ) { BOOL bFound = FALSE; TextSelection aSel( GetSelection() ); if ( ((ExtTextEngine*)GetTextEngine())->Search( aSel, rSearchOptions, bForward ) ) { bFound = TRUE; // Erstmal den Anfang des Wortes als Selektion einstellen, // damit das ganze Wort in den sichtbaren Bereich kommt. SetSelection( aSel.GetStart() ); ShowCursor( TRUE, FALSE ); } else { aSel = GetSelection().GetEnd(); } SetSelection( aSel ); ShowCursor(); return bFound; } USHORT ExtTextView::Replace( const util::SearchOptions& rSearchOptions, BOOL bAll, BOOL bForward ) { USHORT nFound = 0; if ( !bAll ) { if ( GetSelection().HasRange() ) { InsertText( rSearchOptions.replaceString ); nFound = 1; Search( rSearchOptions, bForward ); // gleich zum naechsten } else { if( Search( rSearchOptions, bForward ) ) nFound = 1; } } else { // Der Writer ersetzt alle, vom Anfang bis Ende... ExtTextEngine* pTextEngine = (ExtTextEngine*)GetTextEngine(); // HideSelection(); TextSelection aSel; BOOL bSearchInSelection = (0 != (rSearchOptions.searchFlag & util::SearchFlags::REG_NOT_BEGINOFLINE) ); if ( bSearchInSelection ) { aSel = GetSelection(); aSel.Justify(); } TextSelection aSearchSel( aSel ); BOOL bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE ); if ( bFound ) pTextEngine->UndoActionStart( XTEXTUNDO_REPLACEALL ); while ( bFound ) { nFound++; TextPaM aNewStart = pTextEngine->ImpInsertText( aSel, rSearchOptions.replaceString ); aSel = aSearchSel; aSel.GetStart() = aNewStart; bFound = pTextEngine->Search( aSel, rSearchOptions, TRUE ); } if ( nFound ) { SetSelection( aSel.GetStart() ); pTextEngine->FormatAndUpdate( this ); pTextEngine->UndoActionEnd( XTEXTUNDO_REPLACEALL ); } } return nFound; } BOOL ExtTextView::ImpIndentBlock( BOOL bRight ) { BOOL bDone = FALSE; TextSelection aSel = GetSelection(); aSel.Justify(); HideSelection(); GetTextEngine()->UndoActionStart( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK ); ULONG nStartPara = aSel.GetStart().GetPara(); ULONG nEndPara = aSel.GetEnd().GetPara(); if ( aSel.HasRange() && !aSel.GetEnd().GetIndex() ) { nEndPara--; // den dann nicht einruecken... } for ( ULONG nPara = nStartPara; nPara <= nEndPara; nPara++ ) { if ( bRight ) { // Tabs hinzufuegen GetTextEngine()->ImpInsertText( TextPaM( nPara, 0 ), '\t' ); bDone = TRUE; } else { // Tabs/Blanks entfernen String aText = GetTextEngine()->GetText( nPara ); if ( aText.Len() && ( ( aText.GetChar( 0 ) == '\t' ) || ( aText.GetChar( 0 ) == ' ' ) ) ) { GetTextEngine()->ImpDeleteText( TextSelection( TextPaM( nPara, 0 ), TextPaM( nPara, 1 ) ) ); bDone = TRUE; } } } GetTextEngine()->UndoActionEnd( bRight ? XTEXTUNDO_INDENTBLOCK : XTEXTUNDO_UNINDENTBLOCK ); BOOL bRange = aSel.HasRange(); if ( bRight ) { aSel.GetStart().GetIndex()++; if ( bRange && ( aSel.GetEnd().GetPara() == nEndPara ) ) aSel.GetEnd().GetIndex()++; } else { if ( aSel.GetStart().GetIndex() ) aSel.GetStart().GetIndex()--; if ( bRange && aSel.GetEnd().GetIndex() ) aSel.GetEnd().GetIndex()--; } ImpSetSelection( aSel ); GetTextEngine()->FormatAndUpdate( this ); return bDone; } BOOL ExtTextView::IndentBlock() { return ImpIndentBlock( TRUE ); } BOOL ExtTextView::UnindentBlock() { return ImpIndentBlock( FALSE ); } <|endoftext|>
<commit_before>// // Copyright (c) 2014-2016 Ian Godin // All rights reserved. // Copyrights licensed under the MIT License. // See the accompanying LICENSE.txt file for terms // #include "geometry.h" #include <tuple> #include <cmath> namespace { template<int n, typename T> inline const draw::polyline::point &pt( const T &t ) { return std::get<n>( t ); } } namespace draw { //////////////////////////////////////// size_t circle_precision( dim r ) { size_t n = 3; dim error = dim( 0 ); do { n = n * 2; error = r * ( 1.F - std::cos( static_cast<float>( M_PI ) / static_cast<float>( n ) ) ); } while ( error > dim( 0.01F ) ); return n; } //////////////////////////////////////// void add_quadratic( const polyline::point &p1, const polyline::point &p2, const polyline::point &p3, polyline &line ) { using pp = polyline::point; typedef std::tuple<pp,pp,pp> curve; std::vector<curve> stack; stack.reserve( 16 ); stack.emplace_back( p1, p2, p3 ); pp c0, c1, c2, c3; while ( !stack.empty() ) { curve &c = stack.back(); pp mid = ( pt<0>( c ) + pt<2>( c ) ) * 0.5F; if ( distance_squared( mid, pt<1>( c ) ) <= dim( 0.01F ) ) { line.push_back( pt<2>( c ) ); stack.pop_back(); } else { c0 = pt<0>( c ); c1 = ( c0 + pt<1>( c ) ) * 0.5F; c3 = ( pt<1>( c ) + pt<2>( c ) ) * 0.5F; c2 = ( c1 + c3 ) * 0.5F; c = std::make_tuple( c2, c3, pt<2>( c ) ); // right side stack.emplace_back( c0, c1, c2 ); } } } //////////////////////////////////////// void add_cubic( const polyline::point &p1, const polyline::point &p2, const polyline::point &p3, const polyline::point &p4, polyline &line ) { #if 0 using pp = polyline::point; typedef std::tuple<pp,pp,pp,pp> curve; std::vector<curve> stack; stack.reserve( 16 ); stack.emplace_back( p1, p2, p3, p4 ); pp p0, p01, p12, p23, p012, p123, p0123, d, d13, d23; bool first = true; while ( !stack.empty() ) { curve &c = stack.back(); p01 = ( pt<0>( c ) + pt<1>( c ) ) * 0.5F; p12 = ( pt<1>( c ) + pt<2>( c ) ) * 0.5F; p23 = ( pt<2>( c ) + pt<3>( c ) ) * 0.5F; p012 = ( p01 + p12 ) * 0.5F; p123 = ( p12 + p23 ) * 0.5F; p0123 = ( p012 + p123 ) * 0.5F; d = pt<0>( c ) - pt<3>( c ); d13 = pt<1>( c ) - pt<3>( c ); d23 = pt<2>( c ) - pt<3>( c ); dim d2 = d13[0] * d[1] - d13[1] * d[0]; dim d3 = d23[0] * d[1] - d23[1] * d[0]; if ( ( d2 + d3 ) * ( d2 + d3 ) < 0.1F * ( d[0] * d[0] + d[1] * d[1] ) && !first ) { line.push_back( pt<3>( c ) ); stack.pop_back(); } else { p0 = pt<0>( c ); c = std::make_tuple( p0123, p123, p23, pt<3>( c ) ); // right side stack.emplace_back( p0, p01, p012, p0123 ); } first = false; } #endif } //////////////////////////////////////// void add_arc( const polyline::point &center, dim radius, float a1, float a2, polyline &line ) { using pp = polyline::point; size_t n = circle_precision( radius ); float span = std::abs( std::fmod( ( a1 - a2 + float( M_PI ) ), float( 2.0 * M_PI ) ) - float( M_PI ) ); n = size_t( std::ceil( n * span / float( 2.0 * M_PI ) ) ); point bp = base::polar( radius, a1 ); polyline::point p = polyline::point( bp[0], bp[1], dim(0) ) + center; if ( line.empty() || distance_squared( p, line.back() ) > dim( 0.1F ) ) line.push_back( p ); for ( size_t i = 1; i <= n; ++i ) { float m = float(i) / float(n); float a = a1 * ( 1.0F - m ) + a2 * m; bp = base::polar( radius, a ); line.push_back( polyline::point( bp[0], bp[1], dim(0) ) + center ); } } //////////////////////////////////////// } <commit_msg>re-enable code after fix for unit type conversion<commit_after>// // Copyright (c) 2014-2016 Ian Godin // All rights reserved. // Copyrights licensed under the MIT License. // See the accompanying LICENSE.txt file for terms // #include "geometry.h" #include <tuple> #include <cmath> namespace { template<int n, typename T> inline const draw::polyline::point &pt( const T &t ) { return std::get<n>( t ); } } namespace draw { //////////////////////////////////////// size_t circle_precision( dim r ) { size_t n = 3; dim error = dim( 0 ); do { n = n * 2; error = r * ( 1.F - std::cos( static_cast<float>( M_PI ) / static_cast<float>( n ) ) ); } while ( error > dim( 0.01F ) ); return n; } //////////////////////////////////////// void add_quadratic( const polyline::point &p1, const polyline::point &p2, const polyline::point &p3, polyline &line ) { using pp = polyline::point; typedef std::tuple<pp,pp,pp> curve; std::vector<curve> stack; stack.reserve( 16 ); stack.emplace_back( p1, p2, p3 ); pp c0, c1, c2, c3; while ( !stack.empty() ) { curve &c = stack.back(); pp mid = ( pt<0>( c ) + pt<2>( c ) ) * 0.5F; if ( distance_squared( mid, pt<1>( c ) ) <= dim( 0.01F ) ) { line.push_back( pt<2>( c ) ); stack.pop_back(); } else { c0 = pt<0>( c ); c1 = ( c0 + pt<1>( c ) ) * 0.5F; c3 = ( pt<1>( c ) + pt<2>( c ) ) * 0.5F; c2 = ( c1 + c3 ) * 0.5F; c = std::make_tuple( c2, c3, pt<2>( c ) ); // right side stack.emplace_back( c0, c1, c2 ); } } } //////////////////////////////////////// void add_cubic( const polyline::point &p1, const polyline::point &p2, const polyline::point &p3, const polyline::point &p4, polyline &line ) { using pp = polyline::point; typedef std::tuple<pp,pp,pp,pp> curve; std::vector<curve> stack; stack.reserve( 16 ); stack.emplace_back( p1, p2, p3, p4 ); pp p0, p01, p12, p23, p012, p123, p0123, d, d13, d23; bool first = true; while ( !stack.empty() ) { curve &c = stack.back(); p01 = ( pt<0>( c ) + pt<1>( c ) ) * 0.5F; p12 = ( pt<1>( c ) + pt<2>( c ) ) * 0.5F; p23 = ( pt<2>( c ) + pt<3>( c ) ) * 0.5F; p012 = ( p01 + p12 ) * 0.5F; p123 = ( p12 + p23 ) * 0.5F; p0123 = ( p012 + p123 ) * 0.5F; d = pt<0>( c ) - pt<3>( c ); d13 = pt<1>( c ) - pt<3>( c ); d23 = pt<2>( c ) - pt<3>( c ); dim d2 = d13[0] * d[1] - d13[1] * d[0]; dim d3 = d23[0] * d[1] - d23[1] * d[0]; if ( ( d2 + d3 ) * ( d2 + d3 ) < 0.1F * ( d[0] * d[0] + d[1] * d[1] ) && !first ) { line.push_back( pt<3>( c ) ); stack.pop_back(); } else { p0 = pt<0>( c ); c = std::make_tuple( p0123, p123, p23, pt<3>( c ) ); // right side stack.emplace_back( p0, p01, p012, p0123 ); } first = false; } } //////////////////////////////////////// void add_arc( const polyline::point &center, dim radius, float a1, float a2, polyline &line ) { size_t n = circle_precision( radius ); float span = std::abs( std::fmod( ( a1 - a2 + float( M_PI ) ), float( 2.0 * M_PI ) ) - float( M_PI ) ); n = size_t( std::ceil( n * span / float( 2.0 * M_PI ) ) ); point bp = base::polar( radius, a1 ); polyline::point p = polyline::point( bp[0], bp[1], dim(0) ) + center; if ( line.empty() || distance_squared( p, line.back() ) > dim( 0.1F ) ) line.push_back( p ); for ( size_t i = 1; i <= n; ++i ) { float m = float(i) / float(n); float a = a1 * ( 1.0F - m ) + a2 * m; bp = base::polar( radius, a ); line.push_back( polyline::point( bp[0], bp[1], dim(0) ) + center ); } } //////////////////////////////////////// } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: edatmisc.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 03:25:54 $ * * 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 _EDITSH_HXX #include <editsh.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> // fuer aNodes #endif #ifndef _PAM_HXX #include <pam.hxx> // fuer SwPaM #endif #ifndef _EDIMP_HXX #include <edimp.hxx> // fuer MACROS #endif #ifndef _SWUNDO_HXX #include <swundo.hxx> // fuer die UndoIds #endif #ifndef _NDTXT_HXX #include <ndtxt.hxx> // fuer Get-/ChgFmt Set-/GetAttrXXX #endif /************************************* * harte Formatierung (Attribute) *************************************/ void SwEditShell::ResetAttr() { SET_CURR_SHELL( this ); StartAllAction(); BOOL bUndoGroup = GetCrsr()->GetNext() != GetCrsr(); if( bUndoGroup ) GetDoc()->StartUndo(UNDO_RESETATTR); FOREACHPAM_START(this) // if ( PCURCRSR->HasMark() ) GetDoc()->ResetAttr(*PCURCRSR); FOREACHPAM_END() if( bUndoGroup ) GetDoc()->EndUndo(UNDO_RESETATTR); CallChgLnk(); EndAllAction(); } void SwEditShell::GCAttr() { //JP 04.02.97: wozu eine Action-Klammerung - ein Formatierung sollte nicht // ausgeloest werden, so dass es hier ueberfluessig ist. // Sonst Probleme im MouseBut.DownHdl - Bug 35562 // StartAllAction(); FOREACHPAM_START(this) SwTxtNode *pTxtNode; if ( !PCURCRSR->HasMark() ) { if( 0 != (pTxtNode = GetDoc()->GetNodes()[ PCURCRSR->GetPoint()->nNode]->GetTxtNode())) pTxtNode->GCAttr(); } else { const SwNodeIndex& rEnd = PCURCRSR->End()->nNode; SwNodeIndex aIdx( PCURCRSR->Start()->nNode ); SwNode* pNd = &aIdx.GetNode(); do { if( pNd->IsTxtNode() ) ((SwTxtNode*)pNd)->GCAttr(); } while( 0 != ( pNd = GetDoc()->GetNodes().GoNext( &aIdx )) && aIdx <= rEnd ); } FOREACHPAM_END() // EndAllAction(); } // Setze das Attribut als neues default Attribut im Dokument. void SwEditShell::SetDefault( const SfxPoolItem& rFmtHint ) { // 7502: Action-Klammerung StartAllAction(); GetDoc()->SetDefault( rFmtHint ); EndAllAction(); } /* void SwEditShell::SetDefault( const SfxItemSet& rSet ) { // 7502: Action-Klammerung StartAllAction(); GetDoc()->SetDefault( rSet ); EndAllAction(); } */ // Erfrage das Default Attribut in diesem Dokument. const SfxPoolItem& SwEditShell::GetDefault( USHORT nFmtHint ) const { return GetDoc()->GetDefault( nFmtHint ); } void SwEditShell::SetAttr( const SfxPoolItem& rHint, USHORT nFlags ) { SET_CURR_SHELL( this ); StartAllAction(); SwPaM* pCrsr = GetCrsr(); if( pCrsr->GetNext() != pCrsr ) // Ring von Cursorn { FASTBOOL bIsTblMode = IsTableMode(); GetDoc()->StartUndo(UNDO_INSATTR); FOREACHPAM_START(this) if( PCURCRSR->HasMark() && ( bIsTblMode || *PCURCRSR->GetPoint() != *PCURCRSR->GetMark() )) GetDoc()->Insert(*PCURCRSR, rHint, nFlags ); FOREACHPAM_END() GetDoc()->EndUndo(UNDO_INSATTR); } else { if( !HasSelection() ) UpdateAttr(); GetDoc()->Insert( *pCrsr, rHint, nFlags ); } EndAllAction(); } void SwEditShell::SetAttr( const SfxItemSet& rSet, USHORT nFlags ) { SET_CURR_SHELL( this ); StartAllAction(); SwPaM* pCrsr = GetCrsr(); if( pCrsr->GetNext() != pCrsr ) // Ring von Cursorn { FASTBOOL bIsTblMode = IsTableMode(); GetDoc()->StartUndo(UNDO_INSATTR); FOREACHPAM_START(this) if( PCURCRSR->HasMark() && ( bIsTblMode || *PCURCRSR->GetPoint() != *PCURCRSR->GetMark() )) GetDoc()->Insert(*PCURCRSR, rSet, nFlags ); FOREACHPAM_END() GetDoc()->EndUndo(UNDO_INSATTR); } else { if( !HasSelection() ) UpdateAttr(); GetDoc()->Insert( *pCrsr, rSet, nFlags ); } EndAllAction(); } <commit_msg>INTEGRATION: CWS writercorehandoff (1.4.4); FILE MERGED 2005/09/28 14:00:33 tra 1.4.4.1: #i50348#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: edatmisc.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-08-14 16:07:26 $ * * 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 _EDITSH_HXX #include <editsh.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> // fuer aNodes #endif #ifndef _PAM_HXX #include <pam.hxx> // fuer SwPaM #endif #ifndef _EDIMP_HXX #include <edimp.hxx> // fuer MACROS #endif #ifndef _SWUNDO_HXX #include <swundo.hxx> // fuer die UndoIds #endif #ifndef _NDTXT_HXX #include <ndtxt.hxx> // fuer Get-/ChgFmt Set-/GetAttrXXX #endif /************************************* * harte Formatierung (Attribute) *************************************/ void SwEditShell::ResetAttr() { SET_CURR_SHELL( this ); StartAllAction(); BOOL bUndoGroup = GetCrsr()->GetNext() != GetCrsr(); if( bUndoGroup ) GetDoc()->StartUndo(UNDO_RESETATTR, NULL); FOREACHPAM_START(this) // if ( PCURCRSR->HasMark() ) GetDoc()->ResetAttr(*PCURCRSR); FOREACHPAM_END() if( bUndoGroup ) GetDoc()->EndUndo(UNDO_RESETATTR, NULL); CallChgLnk(); EndAllAction(); } void SwEditShell::GCAttr() { //JP 04.02.97: wozu eine Action-Klammerung - ein Formatierung sollte nicht // ausgeloest werden, so dass es hier ueberfluessig ist. // Sonst Probleme im MouseBut.DownHdl - Bug 35562 // StartAllAction(); FOREACHPAM_START(this) SwTxtNode *pTxtNode; if ( !PCURCRSR->HasMark() ) { if( 0 != (pTxtNode = GetDoc()->GetNodes()[ PCURCRSR->GetPoint()->nNode]->GetTxtNode())) pTxtNode->GCAttr(); } else { const SwNodeIndex& rEnd = PCURCRSR->End()->nNode; SwNodeIndex aIdx( PCURCRSR->Start()->nNode ); SwNode* pNd = &aIdx.GetNode(); do { if( pNd->IsTxtNode() ) ((SwTxtNode*)pNd)->GCAttr(); } while( 0 != ( pNd = GetDoc()->GetNodes().GoNext( &aIdx )) && aIdx <= rEnd ); } FOREACHPAM_END() // EndAllAction(); } // Setze das Attribut als neues default Attribut im Dokument. void SwEditShell::SetDefault( const SfxPoolItem& rFmtHint ) { // 7502: Action-Klammerung StartAllAction(); GetDoc()->SetDefault( rFmtHint ); EndAllAction(); } /* void SwEditShell::SetDefault( const SfxItemSet& rSet ) { // 7502: Action-Klammerung StartAllAction(); GetDoc()->SetDefault( rSet ); EndAllAction(); } */ // Erfrage das Default Attribut in diesem Dokument. const SfxPoolItem& SwEditShell::GetDefault( USHORT nFmtHint ) const { return GetDoc()->GetDefault( nFmtHint ); } void SwEditShell::SetAttr( const SfxPoolItem& rHint, USHORT nFlags ) { SET_CURR_SHELL( this ); StartAllAction(); SwPaM* pCrsr = GetCrsr(); if( pCrsr->GetNext() != pCrsr ) // Ring von Cursorn { FASTBOOL bIsTblMode = IsTableMode(); GetDoc()->StartUndo(UNDO_INSATTR, NULL); FOREACHPAM_START(this) if( PCURCRSR->HasMark() && ( bIsTblMode || *PCURCRSR->GetPoint() != *PCURCRSR->GetMark() )) GetDoc()->Insert(*PCURCRSR, rHint, nFlags ); FOREACHPAM_END() GetDoc()->EndUndo(UNDO_INSATTR, NULL); } else { if( !HasSelection() ) UpdateAttr(); GetDoc()->Insert( *pCrsr, rHint, nFlags ); } EndAllAction(); } void SwEditShell::SetAttr( const SfxItemSet& rSet, USHORT nFlags ) { SET_CURR_SHELL( this ); StartAllAction(); SwPaM* pCrsr = GetCrsr(); if( pCrsr->GetNext() != pCrsr ) // Ring von Cursorn { FASTBOOL bIsTblMode = IsTableMode(); GetDoc()->StartUndo(UNDO_INSATTR, NULL); FOREACHPAM_START(this) if( PCURCRSR->HasMark() && ( bIsTblMode || *PCURCRSR->GetPoint() != *PCURCRSR->GetMark() )) GetDoc()->Insert(*PCURCRSR, rSet, nFlags ); FOREACHPAM_END() GetDoc()->EndUndo(UNDO_INSATTR, NULL); } else { if( !HasSelection() ) UpdateAttr(); GetDoc()->Insert( *pCrsr, rSet, nFlags ); } EndAllAction(); } <|endoftext|>
<commit_before>// file PWScore.cpp //----------------------------------------------------------------------------- #if (defined(_MSC_VER) && (_MSC_VER >= 1300)) #include <fstream> #include <string> #include <vector> #include <iostream> using namespace std; #else #include <fstream.h> // for WritePlaintextFile #include <vector.h> #include <iostream.h> #endif #include "PWScore.h" #include "BlowFish.h" PWScore::PWScore() : m_currfile(_T("")), m_changed(false), m_usedefuser(false), m_defusername(_T("")), m_ReadFileVersion(PWSfile::UNKNOWN_VERSION), m_passkey(NULL), m_passkey_len(0) { int i; srand((unsigned)time(NULL)); CItemData::SetSessionKey(); // per-session initialization for (i = 0; i < sizeof(m_session_key); i++) m_session_key[i] = newrand(); for (i = 0; i < sizeof(m_session_salt); i++) m_session_salt[i] = newrand(); } PWScore::~PWScore() { if (m_passkey_len > 0) { trashMemory(m_passkey, ((m_passkey_len + 7)/8)*8); delete[] m_passkey; } } void PWScore::ClearData(void) { if (m_passkey_len > 0) { trashMemory(m_passkey, ((m_passkey_len + 7)/8)*8); delete[] m_passkey; m_passkey_len = 0; } //Composed of ciphertext, so doesn't need to be overwritten m_pwlist.RemoveAll(); } void PWScore::NewFile(const CMyString &passkey) { ClearData(); SetPassKey(passkey); m_changed = false; } int PWScore::WriteFile(const CMyString &filename, PWSfile::VERSION version) { PWSfile out(filename, GetPassKey()); int status; status = out.OpenWriteFile(version); if (status != PWSfile::SUCCESS) return CANT_OPEN_FILE; CItemData temp; POSITION listPos = m_pwlist.GetHeadPosition(); while (listPos != NULL) { temp = m_pwlist.GetAt(listPos); out.WriteRecord(temp); m_pwlist.GetNext(listPos); } out.CloseFile(); m_changed = FALSE; m_ReadFileVersion = version; // needed when saving a V17 as V20 1st time [871893] return SUCCESS; } int PWScore::WritePlaintextFile(const CMyString &filename) { ofstream of(filename); if (!of) return CANT_OPEN_FILE; CItemData temp; POSITION listPos = m_pwlist.GetHeadPosition(); while (listPos != NULL) { temp = m_pwlist.GetAt(listPos); of << temp.GetPlaintext('\t') << endl; m_pwlist.GetNext(listPos); } of.close(); return SUCCESS; } /* int PWScore::WriteXMLFile(const CMyString &filename) { ofstream of(filename); if (!of) return CANT_OPEN_FILE; of << "<?xml version=\"1.0\">" << endl; of << "<passwordsafe>" << endl; POSITION listPos = m_pwlist.GetHeadPosition(); while (listPos != NULL) { CItemData temp = m_pwlist.GetAt(listPos); of << " <entry>" << endl; // TODO: need to handle entity escaping of values. of << " <group>" << temp.GetGroup() << "</group>" << endl; of << " <title>" << temp.GetTitle() << "</title>" << endl; of << " <username>" << temp.GetUser() << "</username>" << endl; of << " <password>" << temp.GetPassword() << "</password>" << endl; of << " <notes>" << temp.GetNotes() << "</notes>" << endl; of << " </entry>" << endl; m_pwlist.GetNext(listPos); } of << "</passwordsafe>" << endl; of.close(); return SUCCESS; } */ int PWScore::ImportPlaintextFile(const CMyString &filename) { static const char *ImportedPrefix = { "Imported" }; ifstream ifs(filename); if (!ifs) return CANT_OPEN_FILE; for (;;) { // read a single line. string linebuf; if (!getline(ifs, linebuf, '\n')) break; // remove MS-DOS linebreaks, if needed. if (!linebuf.empty() && *(linebuf.end() - 1) == '\r') { linebuf.resize(linebuf.size() - 1); } // tokenize into separate elements vector<string> tokens; for (int startpos = 0; ; ) { int nextchar = linebuf.find_first_of('\t', startpos); if (nextchar >= 0 && tokens.size() < 3) { tokens.push_back(linebuf.substr(startpos, nextchar - startpos)); startpos = nextchar + 1; } else { tokens.push_back(linebuf.substr(startpos)); break; } } if (tokens.size() != 4) { ASSERT(0 && "did not find expected number of tokens"); break; } // Start initializing the new record. CItemData temp; temp.CreateUUID(); temp.SetUser(CMyString(tokens[1].c_str())); temp.SetPassword(CMyString(tokens[2].c_str())); // The group and title field are concatenated. const string &grouptitle = tokens[0]; int lastdot = grouptitle.find_last_of('.'); if (lastdot > 0) { CMyString newgroup(ImportedPrefix); newgroup += "."; newgroup += grouptitle.substr(0, lastdot).c_str(); temp.SetGroup(newgroup); temp.SetTitle(grouptitle.substr(lastdot + 1).c_str()); } else { temp.SetGroup(ImportedPrefix); temp.SetTitle(grouptitle.c_str()); } // The notes field begins and ends with a double-quote, with // no special escaping of any other internal characters. string quotedNotes = tokens[3]; if (!quotedNotes.empty() && *quotedNotes.begin() == '\"' && *(quotedNotes.end() - 1) == '\"') { quotedNotes = quotedNotes.substr(1, quotedNotes.size() - 2); temp.SetNotes(CMyString(quotedNotes.c_str())); } AddEntryToTail(temp); } ifs.close(); // TODO: maybe return an error if the full end of the file was not reached? return SUCCESS; } int PWScore::CheckPassword(const CMyString &filename, CMyString& passkey) { PWSfile f(filename, passkey); int status = f.CheckPassword(); switch (status) { case PWSfile::SUCCESS: return SUCCESS; case PWSfile::CANT_OPEN_FILE: return CANT_OPEN_FILE; case PWSfile::WRONG_PASSWORD: return WRONG_PASSWORD; default: ASSERT(0); return status; // should never happen } } int PWScore::ReadFile(const CMyString &a_filename, const CMyString &a_passkey) { //That passkey had better be the same one that came from CheckPassword(...) PWSfile in(a_filename, a_passkey); int status; m_ReadFileVersion = in.GetFileVersion(); if (m_ReadFileVersion == PWSfile::UNKNOWN_VERSION) return UNKNOWN_VERSION; status = in.OpenReadFile(m_ReadFileVersion); if (status != PWSfile::SUCCESS) return CANT_OPEN_FILE; // prepare handling of pre-2.0 DEFUSERCHR conversion if (m_ReadFileVersion == PWSfile::V17) in.SetDefUsername(m_defusername); ClearData(); //Before overwriting old data, but after opening the file... SetPassKey(a_passkey); CItemData temp; status = in.ReadRecord(temp); while (status == PWSfile::SUCCESS) { m_pwlist.AddTail(temp); status = in.ReadRecord(temp); } in.CloseFile(); return SUCCESS; } int PWScore::RenameFile(const CMyString &oldname, const CMyString &newname) { return PWSfile::RenameFile(oldname, newname); } void PWScore::ChangePassword(const CMyString &newPassword) { SetPassKey(newPassword); m_changed = TRUE; } // Finds stuff based on title & user fields only POSITION PWScore::Find(const CMyString &a_title, const CMyString &a_user) { POSITION listPos = m_pwlist.GetHeadPosition(); CMyString title, user; while (listPos != NULL) { title = m_pwlist.GetAt(listPos).GetTitle(); user = m_pwlist.GetAt(listPos).GetUser(); if (title == a_title && user == a_user) break; else m_pwlist.GetNext(listPos); } return listPos; } void PWScore::EncryptPassword(const unsigned char *plaintext, int len, unsigned char *ciphertext) const { // ciphertext is ((len +7)/8)*8 bytes long BlowFish *Algorithm = MakeBlowFish(m_session_key, sizeof(m_session_key), m_session_salt, sizeof(m_session_salt)); int BlockLength = ((len + 7)/8)*8; unsigned char curblock[8]; for (int x=0;x<BlockLength;x+=8) { int i; if ((len == 0) || ((len%8 != 0) && (len - x < 8))) { //This is for an uneven last block memset(curblock, 0, 8); for (i = 0; i < len %8; i++) curblock[i] = plaintext[x + i]; } else for (i = 0; i < 8; i++) curblock[i] = plaintext[x + i]; Algorithm->Encrypt(curblock, curblock); memcpy(ciphertext + x, curblock, 8); } trashMemory(curblock, 8); delete Algorithm; } void PWScore::SetPassKey(const CMyString &new_passkey) { // if changing, clear old if (m_passkey_len > 0) { trashMemory(m_passkey, ((m_passkey_len + 7)/8)*8); delete[] m_passkey; } m_passkey_len = new_passkey.GetLength(); int BlockLength = ((m_passkey_len + 7)/8)*8; m_passkey = new unsigned char[BlockLength]; LPCTSTR plaintext = LPCTSTR(new_passkey); EncryptPassword((const unsigned char *)plaintext, m_passkey_len, m_passkey); } CMyString PWScore::GetPassKey() const { CMyString retval(_T("")); if (m_passkey_len > 0) { unsigned int BlockLength = ((m_passkey_len + 7)/8)*8; BlowFish *Algorithm = MakeBlowFish(m_session_key, sizeof(m_session_key), m_session_salt, sizeof(m_session_salt)); unsigned char curblock[8]; for (unsigned int x = 0; x < BlockLength; x += 8) { unsigned int i; for (i = 0; i < 8; i++) curblock[i] = m_passkey[x + i]; Algorithm->Decrypt(curblock, curblock); for (i = 0; i < 8; i++) if (x + i < m_passkey_len) retval += curblock[i]; } trashMemory(curblock, 8); delete Algorithm; } return retval; } <commit_msg>Compiles (with warnings!) under VC6.0<commit_after>// file PWScore.cpp //----------------------------------------------------------------------------- #include <fstream> // for WritePlaintextFile #include <iostream> #include <string> #include <vector> using namespace std; #include "PWScore.h" #include "BlowFish.h" PWScore::PWScore() : m_currfile(_T("")), m_changed(false), m_usedefuser(false), m_defusername(_T("")), m_ReadFileVersion(PWSfile::UNKNOWN_VERSION), m_passkey(NULL), m_passkey_len(0) { int i; srand((unsigned)time(NULL)); CItemData::SetSessionKey(); // per-session initialization for (i = 0; i < sizeof(m_session_key); i++) m_session_key[i] = newrand(); for (i = 0; i < sizeof(m_session_salt); i++) m_session_salt[i] = newrand(); } PWScore::~PWScore() { if (m_passkey_len > 0) { trashMemory(m_passkey, ((m_passkey_len + 7)/8)*8); delete[] m_passkey; } } void PWScore::ClearData(void) { if (m_passkey_len > 0) { trashMemory(m_passkey, ((m_passkey_len + 7)/8)*8); delete[] m_passkey; m_passkey_len = 0; } //Composed of ciphertext, so doesn't need to be overwritten m_pwlist.RemoveAll(); } void PWScore::NewFile(const CMyString &passkey) { ClearData(); SetPassKey(passkey); m_changed = false; } int PWScore::WriteFile(const CMyString &filename, PWSfile::VERSION version) { PWSfile out(filename, GetPassKey()); int status; status = out.OpenWriteFile(version); if (status != PWSfile::SUCCESS) return CANT_OPEN_FILE; CItemData temp; POSITION listPos = m_pwlist.GetHeadPosition(); while (listPos != NULL) { temp = m_pwlist.GetAt(listPos); out.WriteRecord(temp); m_pwlist.GetNext(listPos); } out.CloseFile(); m_changed = FALSE; m_ReadFileVersion = version; // needed when saving a V17 as V20 1st time [871893] return SUCCESS; } int PWScore::WritePlaintextFile(const CMyString &filename) { ofstream of(filename); if (!of) return CANT_OPEN_FILE; CItemData temp; POSITION listPos = m_pwlist.GetHeadPosition(); while (listPos != NULL) { temp = m_pwlist.GetAt(listPos); of << temp.GetPlaintext('\t') << endl; m_pwlist.GetNext(listPos); } of.close(); return SUCCESS; } /* int PWScore::WriteXMLFile(const CMyString &filename) { ofstream of(filename); if (!of) return CANT_OPEN_FILE; of << "<?xml version=\"1.0\">" << endl; of << "<passwordsafe>" << endl; POSITION listPos = m_pwlist.GetHeadPosition(); while (listPos != NULL) { CItemData temp = m_pwlist.GetAt(listPos); of << " <entry>" << endl; // TODO: need to handle entity escaping of values. of << " <group>" << temp.GetGroup() << "</group>" << endl; of << " <title>" << temp.GetTitle() << "</title>" << endl; of << " <username>" << temp.GetUser() << "</username>" << endl; of << " <password>" << temp.GetPassword() << "</password>" << endl; of << " <notes>" << temp.GetNotes() << "</notes>" << endl; of << " </entry>" << endl; m_pwlist.GetNext(listPos); } of << "</passwordsafe>" << endl; of.close(); return SUCCESS; } */ int PWScore::ImportPlaintextFile(const CMyString &filename) { static const char *ImportedPrefix = { "Imported" }; ifstream ifs(filename); if (!ifs) return CANT_OPEN_FILE; for (;;) { // read a single line. string linebuf; if (!getline(ifs, linebuf, '\n')) break; // remove MS-DOS linebreaks, if needed. if (!linebuf.empty() && *(linebuf.end() - 1) == '\r') { linebuf.resize(linebuf.size() - 1); } // tokenize into separate elements vector<string> tokens; for (int startpos = 0; ; ) { int nextchar = linebuf.find_first_of('\t', startpos); if (nextchar >= 0 && tokens.size() < 3) { tokens.push_back(linebuf.substr(startpos, nextchar - startpos)); startpos = nextchar + 1; } else { tokens.push_back(linebuf.substr(startpos)); break; } } if (tokens.size() != 4) { ASSERT(0 && "did not find expected number of tokens"); break; } // Start initializing the new record. CItemData temp; temp.CreateUUID(); temp.SetUser(CMyString(tokens[1].c_str())); temp.SetPassword(CMyString(tokens[2].c_str())); // The group and title field are concatenated. const string &grouptitle = tokens[0]; int lastdot = grouptitle.find_last_of('.'); if (lastdot > 0) { CMyString newgroup(ImportedPrefix); newgroup += "."; newgroup += grouptitle.substr(0, lastdot).c_str(); temp.SetGroup(newgroup); temp.SetTitle(grouptitle.substr(lastdot + 1).c_str()); } else { temp.SetGroup(ImportedPrefix); temp.SetTitle(grouptitle.c_str()); } // The notes field begins and ends with a double-quote, with // no special escaping of any other internal characters. string quotedNotes = tokens[3]; if (!quotedNotes.empty() && *quotedNotes.begin() == '\"' && *(quotedNotes.end() - 1) == '\"') { quotedNotes = quotedNotes.substr(1, quotedNotes.size() - 2); temp.SetNotes(CMyString(quotedNotes.c_str())); } AddEntryToTail(temp); } ifs.close(); // TODO: maybe return an error if the full end of the file was not reached? return SUCCESS; } int PWScore::CheckPassword(const CMyString &filename, CMyString& passkey) { PWSfile f(filename, passkey); int status = f.CheckPassword(); switch (status) { case PWSfile::SUCCESS: return SUCCESS; case PWSfile::CANT_OPEN_FILE: return CANT_OPEN_FILE; case PWSfile::WRONG_PASSWORD: return WRONG_PASSWORD; default: ASSERT(0); return status; // should never happen } } int PWScore::ReadFile(const CMyString &a_filename, const CMyString &a_passkey) { //That passkey had better be the same one that came from CheckPassword(...) PWSfile in(a_filename, a_passkey); int status; m_ReadFileVersion = in.GetFileVersion(); if (m_ReadFileVersion == PWSfile::UNKNOWN_VERSION) return UNKNOWN_VERSION; status = in.OpenReadFile(m_ReadFileVersion); if (status != PWSfile::SUCCESS) return CANT_OPEN_FILE; // prepare handling of pre-2.0 DEFUSERCHR conversion if (m_ReadFileVersion == PWSfile::V17) in.SetDefUsername(m_defusername); ClearData(); //Before overwriting old data, but after opening the file... SetPassKey(a_passkey); CItemData temp; status = in.ReadRecord(temp); while (status == PWSfile::SUCCESS) { m_pwlist.AddTail(temp); status = in.ReadRecord(temp); } in.CloseFile(); return SUCCESS; } int PWScore::RenameFile(const CMyString &oldname, const CMyString &newname) { return PWSfile::RenameFile(oldname, newname); } void PWScore::ChangePassword(const CMyString &newPassword) { SetPassKey(newPassword); m_changed = TRUE; } // Finds stuff based on title & user fields only POSITION PWScore::Find(const CMyString &a_title, const CMyString &a_user) { POSITION listPos = m_pwlist.GetHeadPosition(); CMyString title, user; while (listPos != NULL) { title = m_pwlist.GetAt(listPos).GetTitle(); user = m_pwlist.GetAt(listPos).GetUser(); if (title == a_title && user == a_user) break; else m_pwlist.GetNext(listPos); } return listPos; } void PWScore::EncryptPassword(const unsigned char *plaintext, int len, unsigned char *ciphertext) const { // ciphertext is ((len +7)/8)*8 bytes long BlowFish *Algorithm = MakeBlowFish(m_session_key, sizeof(m_session_key), m_session_salt, sizeof(m_session_salt)); int BlockLength = ((len + 7)/8)*8; unsigned char curblock[8]; for (int x=0;x<BlockLength;x+=8) { int i; if ((len == 0) || ((len%8 != 0) && (len - x < 8))) { //This is for an uneven last block memset(curblock, 0, 8); for (i = 0; i < len %8; i++) curblock[i] = plaintext[x + i]; } else for (i = 0; i < 8; i++) curblock[i] = plaintext[x + i]; Algorithm->Encrypt(curblock, curblock); memcpy(ciphertext + x, curblock, 8); } trashMemory(curblock, 8); delete Algorithm; } void PWScore::SetPassKey(const CMyString &new_passkey) { // if changing, clear old if (m_passkey_len > 0) { trashMemory(m_passkey, ((m_passkey_len + 7)/8)*8); delete[] m_passkey; } m_passkey_len = new_passkey.GetLength(); int BlockLength = ((m_passkey_len + 7)/8)*8; m_passkey = new unsigned char[BlockLength]; LPCTSTR plaintext = LPCTSTR(new_passkey); EncryptPassword((const unsigned char *)plaintext, m_passkey_len, m_passkey); } CMyString PWScore::GetPassKey() const { CMyString retval(_T("")); if (m_passkey_len > 0) { unsigned int BlockLength = ((m_passkey_len + 7)/8)*8; BlowFish *Algorithm = MakeBlowFish(m_session_key, sizeof(m_session_key), m_session_salt, sizeof(m_session_salt)); unsigned char curblock[8]; for (unsigned int x = 0; x < BlockLength; x += 8) { unsigned int i; for (i = 0; i < 8; i++) curblock[i] = m_passkey[x + i]; Algorithm->Decrypt(curblock, curblock); for (i = 0; i < 8; i++) if (x + i < m_passkey_len) retval += curblock[i]; } trashMemory(curblock, 8); delete Algorithm; } return retval; } <|endoftext|>
<commit_before> #include "stdafx.h" #include "particlesystems.h" #include <graphics/device.h> #include <graphics/camera.h> #include <graphics/shaperenderer2d.h> #include <particles/parser.h> #include <particles/instances.h> #include "../obj.h" #include "../config/config.h" #include "ui/ui_render.h" using namespace gfx; using namespace particles; class PartSysExternal : public IPartSysExternal { public: PartSysExternal(ParticleSysSystem &system, WorldCamera &camera) : mSystem(system), mCamera(camera) {} float GetParticleFidelity() override; bool GetObjLocation(ObjHndl obj, Vec3& worldPos) override; bool GetObjRotation(ObjHndl obj, float& rotation) override; float GetObjRadius(ObjHndl obj) override; bool GetBoneWorldMatrix(ObjHndl obj, const std::string& boneName, Matrix4x4& boneMatrix) override; int GetBoneCount(ObjHndl obj) override; int GetParentChildBonePos(ObjHndl obj, int boneIdx, Vec3& parentPos, Vec3& childPos) override; bool GetBonePos(ObjHndl obj, int boneIdx, Vec3& pos) override; void WorldToScreen(const Vec3& worldPos, Vec2& screenPos) override; bool IsBoxVisible(const Vec2& screenPos, const Box2d& box) override; private: ParticleSysSystem &mSystem; WorldCamera &mCamera; }; ParticleSysSystem::ParticleSysSystem(WorldCamera& camera) { PartSysParser parser; parser.ParseFile("rules\\partsys0.tab"); parser.ParseFile("rules\\partsys1.tab"); parser.ParseFile("rules\\partsys2.tab"); for (auto &spec : parser) { mPartSysByName[spec.first] = spec.second; mPartSysByHash[spec.second->GetNameHash()] = spec.second; } mExternal = std::make_unique<PartSysExternal>(*this, camera); IPartSysExternal::SetCurrent(mExternal.get()); // Register a config for the partsys fidelity config.AddVanillaSetting("partsys_fidelity", "100", [=]() { SetFidelity(config.GetVanillaInt("partsys_fidelity") / 100.0f); }); SetFidelity(config.GetVanillaInt("partsys_fidelity") / 100.0f); } ParticleSysSystem::~ParticleSysSystem() { IPartSysExternal::SetCurrent(nullptr); } void ParticleSysSystem::AdvanceTime(uint32_t time) { // First call if (mLastSimTime == 0) { mLastSimTime = time; return; } auto sinceLastSim = time - mLastSimTime; mLastSimTime = time; auto timeInSecs = sinceLastSim / 1000.0f; if (timeInSecs > 0.5f) { timeInSecs = 0.5f; } auto it = mActiveSys.begin(); while (it != mActiveSys.end()) { auto& sys = *it->second; sys.Simulate(timeInSecs); // Remove dead systems if (sys.IsDead()) { it = mActiveSys.erase(it); } else { it++; } } } const std::string &ParticleSysSystem::GetName() const { static std::string name("ParticleSys"); return name; } int ParticleSysSystem::CreateAt(uint32_t nameHash, XMFLOAT3 pos) { auto it = mPartSysByHash.find(nameHash); if (it == mPartSysByHash.end()) { logger->warn("Unable to spawn unknown particle system: {}", nameHash); return -1; } auto& spec = it->second; auto sys(std::make_shared<PartSys>(spec)); sys->SetWorldPos(mExternal.get(), pos.x, pos.y, pos.z); auto assignedId = mNextId++; mActiveSys[assignedId] = sys; return assignedId; } ParticleSysSystem::Handle ParticleSysSystem::CreateAtObj(const std::string &name, objHndl obj) { auto it = mPartSysByName.find(tolower(name)); if (it == mPartSysByName.end()) { logger->warn("Unable to spawn unknown particle system: {}", name); return -1; } auto& spec = it->second; auto loc = objects.GetLocationFull(obj); auto absLoc = loc.ToInches3D(objects.GetOffsetZ(obj)); auto sys(std::make_shared<PartSys>(spec)); sys->SetWorldPos(mExternal.get(), absLoc.x, absLoc.y, absLoc.z); sys->SetAttachedTo(obj); auto assignedId = mNextId++; mActiveSys[assignedId] = sys; return assignedId; } ParticleSysSystem::Handle ParticleSysSystem::CreateAtPos(const std::string &name, XMFLOAT3 pos) { auto it = mPartSysByName.find(tolower(name)); if (it == mPartSysByName.end()) { logger->warn("Unable to spawn unknown particle system: {}", name); return -1; } auto& spec = it->second; auto sys(std::make_shared<PartSys>(spec)); sys->SetWorldPos(mExternal.get(), pos.x, pos.y, pos.z); auto assignedId = mNextId++; mActiveSys[assignedId] = sys; return assignedId; } bool ParticleSysSystem::DoesNameExist(const std::string & name) { return mPartSysByName.find(tolower(name)) != mPartSysByName.end(); } bool ParticleSysSystem::DoesNameHashExist(uint32_t nameHash) { return mPartSysByHash.find(nameHash) != mPartSysByHash.end(); } particles::PartSysPtr ParticleSysSystem::GetByHandle(Handle handle) { auto it = mActiveSys.find(handle); if (it != mActiveSys.end()) { return it->second; } return nullptr; } void ParticleSysSystem::Remove(Handle handle) { mActiveSys.erase(handle); } void ParticleSysSystem::End(Handle partsysId) { auto partSys = GetByHandle(partsysId); if (partSys) { partSys->EndPrematurely(); } } void ParticleSysSystem::RemoveAll() { mActiveSys.clear(); } float PartSysExternal::GetParticleFidelity() { return mSystem.GetFidelity(); } bool PartSysExternal::GetObjLocation(ObjHndl obj, Vec3& worldPos) { auto locWithOffsets = objects.GetLocationFull(obj); auto offsetZ = objects.GetOffsetZ(obj); auto center3d(locWithOffsets.ToInches3D(offsetZ)); worldPos.x = center3d.x; worldPos.y = center3d.y; worldPos.z = center3d.z; return true; } bool PartSysExternal::GetObjRotation(ObjHndl obj, float& rotation) { rotation = objects.GetRotation(obj); return true; } float PartSysExternal::GetObjRadius(ObjHndl obj) { return objects.GetRadius(obj); } bool PartSysExternal::GetBoneWorldMatrix(ObjHndl obj, const std::string& boneName, Matrix4x4& boneMatrix) { auto model = objects.GetAnimHandle(obj); if (!model) { return false; } auto animParams = objects.GetAnimParams(obj); auto objType = objects.GetType(obj); if (objType >= obj_t_weapon && objType <= obj_t_generic || objType == obj_t_bag) { auto parent = inventory.GetParent(obj); if (parent) { auto parentModel = objects.GetAnimHandle(parent); return parentModel->GetBoneWorldMatrixByNameForChild( model, animParams, boneName, &boneMatrix ); } } return model->GetBoneWorldMatrixByName(animParams, boneName, &boneMatrix); } int PartSysExternal::GetBoneCount(ObjHndl obj) { auto model = objects.GetAnimHandle(obj); if (model) { return model->GetBoneCount(); } else { return 0; } } static bool StrContains(const std::string &str, const char *otherStr) { return str.find(otherStr) != std::string::npos; } static bool IsIgnoredBone(const std::string &name) { if (name[0] == '#') { return true; // Cloth bone } if (tolower(name) == "bip01") { return true; } return StrContains(name, "Pony") || StrContains(name, "Footstep") || StrContains(name, "Origin") || StrContains(name, "Casting_ref") || StrContains(name, "EarthElemental_reg") || StrContains(name, "Casting_ref") || StrContains(name, "origin") || StrContains(name, "Bip01 Footsteps") || StrContains(name, "FootL_ref") || StrContains(name, "FootR_ref") || StrContains(name, "Head_ref") || StrContains(name, "HandL_ref") || StrContains(name, "HandR_ref") || StrContains(name, "Chest_ref") || StrContains(name, "groundParticleRef") || StrContains(name, "effects_ref") || StrContains(name, "trap_ref"); } int PartSysExternal::GetParentChildBonePos(ObjHndl obj, int boneIdx, Vec3& parentPos, Vec3& childPos) { auto model = objects.GetAnimHandle(obj); auto aasParams = objects.GetAnimParams(obj); auto parentId(model->GetBoneParentId(boneIdx)); if (parentId < 0) { return parentId; } auto boneName(model->GetBoneName(boneIdx)); if (boneName.empty()) { return -1; } if (IsIgnoredBone(boneName)) { return -1; } auto parentName(model->GetBoneName(parentId)); if (parentName.empty()) { return -1; } DirectX::XMFLOAT4X4 worldMatrix; if (!model->GetBoneWorldMatrixByName(aasParams, parentName, &worldMatrix)) { return -1; } parentPos.x = worldMatrix._41; parentPos.y = worldMatrix._42; parentPos.z = worldMatrix._43; if (!model->GetBoneWorldMatrixByName(aasParams, boneName, &worldMatrix)) { return -1; } childPos.x = worldMatrix._41; childPos.y = worldMatrix._42; childPos.z = worldMatrix._43; return parentId; } bool PartSysExternal::GetBonePos(ObjHndl obj, int boneIdx, Vec3& pos) { auto model = objects.GetAnimHandle(obj); auto aasParams = objects.GetAnimParams(obj); auto boneName(model->GetBoneName(boneIdx)); if (boneName.empty()) { return false; } DirectX::XMFLOAT4X4 worldMatrix; if (!model->GetBoneWorldMatrixByName(aasParams, boneName, &worldMatrix)) { return false; } pos.x = worldMatrix._41; pos.y = worldMatrix._42; pos.z = worldMatrix._43; return true; } void PartSysExternal::WorldToScreen(const Vec3& worldPos, Vec2& screenPos) { screenPos = mCamera.WorldToScreen(worldPos); auto offset2d = mCamera.Get2dTranslation(); screenPos.x += offset2d.x; screenPos.y += offset2d.y; } bool PartSysExternal::IsBoxVisible(const Vec2& screenPos, const Box2d& box) { return mCamera.IsBoxOnScreen(screenPos, box.left, box.top, box.right, box.bottom); } <commit_msg>Added a missing object rotation offset. Fixes #144<commit_after> #include "stdafx.h" #include "particlesystems.h" #include <graphics/device.h> #include <graphics/camera.h> #include <graphics/shaperenderer2d.h> #include <particles/parser.h> #include <particles/instances.h> #include "../obj.h" #include "../config/config.h" #include "ui/ui_render.h" using namespace gfx; using namespace particles; class PartSysExternal : public IPartSysExternal { public: PartSysExternal(ParticleSysSystem &system, WorldCamera &camera) : mSystem(system), mCamera(camera) {} float GetParticleFidelity() override; bool GetObjLocation(ObjHndl obj, Vec3& worldPos) override; bool GetObjRotation(ObjHndl obj, float& rotation) override; float GetObjRadius(ObjHndl obj) override; bool GetBoneWorldMatrix(ObjHndl obj, const std::string& boneName, Matrix4x4& boneMatrix) override; int GetBoneCount(ObjHndl obj) override; int GetParentChildBonePos(ObjHndl obj, int boneIdx, Vec3& parentPos, Vec3& childPos) override; bool GetBonePos(ObjHndl obj, int boneIdx, Vec3& pos) override; void WorldToScreen(const Vec3& worldPos, Vec2& screenPos) override; bool IsBoxVisible(const Vec2& screenPos, const Box2d& box) override; private: ParticleSysSystem &mSystem; WorldCamera &mCamera; }; ParticleSysSystem::ParticleSysSystem(WorldCamera& camera) { PartSysParser parser; parser.ParseFile("rules\\partsys0.tab"); parser.ParseFile("rules\\partsys1.tab"); parser.ParseFile("rules\\partsys2.tab"); for (auto &spec : parser) { mPartSysByName[spec.first] = spec.second; mPartSysByHash[spec.second->GetNameHash()] = spec.second; } mExternal = std::make_unique<PartSysExternal>(*this, camera); IPartSysExternal::SetCurrent(mExternal.get()); // Register a config for the partsys fidelity config.AddVanillaSetting("partsys_fidelity", "100", [=]() { SetFidelity(config.GetVanillaInt("partsys_fidelity") / 100.0f); }); SetFidelity(config.GetVanillaInt("partsys_fidelity") / 100.0f); } ParticleSysSystem::~ParticleSysSystem() { IPartSysExternal::SetCurrent(nullptr); } void ParticleSysSystem::AdvanceTime(uint32_t time) { // First call if (mLastSimTime == 0) { mLastSimTime = time; return; } auto sinceLastSim = time - mLastSimTime; mLastSimTime = time; auto timeInSecs = sinceLastSim / 1000.0f; if (timeInSecs > 0.5f) { timeInSecs = 0.5f; } auto it = mActiveSys.begin(); while (it != mActiveSys.end()) { auto& sys = *it->second; sys.Simulate(timeInSecs); // Remove dead systems if (sys.IsDead()) { it = mActiveSys.erase(it); } else { it++; } } } const std::string &ParticleSysSystem::GetName() const { static std::string name("ParticleSys"); return name; } int ParticleSysSystem::CreateAt(uint32_t nameHash, XMFLOAT3 pos) { auto it = mPartSysByHash.find(nameHash); if (it == mPartSysByHash.end()) { logger->warn("Unable to spawn unknown particle system: {}", nameHash); return -1; } auto& spec = it->second; auto sys(std::make_shared<PartSys>(spec)); sys->SetWorldPos(mExternal.get(), pos.x, pos.y, pos.z); auto assignedId = mNextId++; mActiveSys[assignedId] = sys; return assignedId; } ParticleSysSystem::Handle ParticleSysSystem::CreateAtObj(const std::string &name, objHndl obj) { auto it = mPartSysByName.find(tolower(name)); if (it == mPartSysByName.end()) { logger->warn("Unable to spawn unknown particle system: {}", name); return -1; } auto& spec = it->second; auto loc = objects.GetLocationFull(obj); auto absLoc = loc.ToInches3D(objects.GetOffsetZ(obj)); auto sys(std::make_shared<PartSys>(spec)); sys->SetWorldPos(mExternal.get(), absLoc.x, absLoc.y, absLoc.z); sys->SetAttachedTo(obj); auto assignedId = mNextId++; mActiveSys[assignedId] = sys; return assignedId; } ParticleSysSystem::Handle ParticleSysSystem::CreateAtPos(const std::string &name, XMFLOAT3 pos) { auto it = mPartSysByName.find(tolower(name)); if (it == mPartSysByName.end()) { logger->warn("Unable to spawn unknown particle system: {}", name); return -1; } auto& spec = it->second; auto sys(std::make_shared<PartSys>(spec)); sys->SetWorldPos(mExternal.get(), pos.x, pos.y, pos.z); auto assignedId = mNextId++; mActiveSys[assignedId] = sys; return assignedId; } bool ParticleSysSystem::DoesNameExist(const std::string & name) { return mPartSysByName.find(tolower(name)) != mPartSysByName.end(); } bool ParticleSysSystem::DoesNameHashExist(uint32_t nameHash) { return mPartSysByHash.find(nameHash) != mPartSysByHash.end(); } particles::PartSysPtr ParticleSysSystem::GetByHandle(Handle handle) { auto it = mActiveSys.find(handle); if (it != mActiveSys.end()) { return it->second; } return nullptr; } void ParticleSysSystem::Remove(Handle handle) { mActiveSys.erase(handle); } void ParticleSysSystem::End(Handle partsysId) { auto partSys = GetByHandle(partsysId); if (partSys) { partSys->EndPrematurely(); } } void ParticleSysSystem::RemoveAll() { mActiveSys.clear(); } float PartSysExternal::GetParticleFidelity() { return mSystem.GetFidelity(); } bool PartSysExternal::GetObjLocation(ObjHndl obj, Vec3& worldPos) { auto locWithOffsets = objects.GetLocationFull(obj); auto offsetZ = objects.GetOffsetZ(obj); auto center3d(locWithOffsets.ToInches3D(offsetZ)); worldPos.x = center3d.x; worldPos.y = center3d.y; worldPos.z = center3d.z; return true; } bool PartSysExternal::GetObjRotation(ObjHndl obj, float& rotation) { rotation = objects.GetRotation(obj) + XM_PIDIV4; return true; } float PartSysExternal::GetObjRadius(ObjHndl obj) { return objects.GetRadius(obj); } bool PartSysExternal::GetBoneWorldMatrix(ObjHndl obj, const std::string& boneName, Matrix4x4& boneMatrix) { auto model = objects.GetAnimHandle(obj); if (!model) { return false; } auto animParams = objects.GetAnimParams(obj); auto objType = objects.GetType(obj); if (objType >= obj_t_weapon && objType <= obj_t_generic || objType == obj_t_bag) { auto parent = inventory.GetParent(obj); if (parent) { auto parentModel = objects.GetAnimHandle(parent); return parentModel->GetBoneWorldMatrixByNameForChild( model, animParams, boneName, &boneMatrix ); } } return model->GetBoneWorldMatrixByName(animParams, boneName, &boneMatrix); } int PartSysExternal::GetBoneCount(ObjHndl obj) { auto model = objects.GetAnimHandle(obj); if (model) { return model->GetBoneCount(); } else { return 0; } } static bool StrContains(const std::string &str, const char *otherStr) { return str.find(otherStr) != std::string::npos; } static bool IsIgnoredBone(const std::string &name) { if (name[0] == '#') { return true; // Cloth bone } if (tolower(name) == "bip01") { return true; } return StrContains(name, "Pony") || StrContains(name, "Footstep") || StrContains(name, "Origin") || StrContains(name, "Casting_ref") || StrContains(name, "EarthElemental_reg") || StrContains(name, "Casting_ref") || StrContains(name, "origin") || StrContains(name, "Bip01 Footsteps") || StrContains(name, "FootL_ref") || StrContains(name, "FootR_ref") || StrContains(name, "Head_ref") || StrContains(name, "HandL_ref") || StrContains(name, "HandR_ref") || StrContains(name, "Chest_ref") || StrContains(name, "groundParticleRef") || StrContains(name, "effects_ref") || StrContains(name, "trap_ref"); } int PartSysExternal::GetParentChildBonePos(ObjHndl obj, int boneIdx, Vec3& parentPos, Vec3& childPos) { auto model = objects.GetAnimHandle(obj); auto aasParams = objects.GetAnimParams(obj); auto parentId(model->GetBoneParentId(boneIdx)); if (parentId < 0) { return parentId; } auto boneName(model->GetBoneName(boneIdx)); if (boneName.empty()) { return -1; } if (IsIgnoredBone(boneName)) { return -1; } auto parentName(model->GetBoneName(parentId)); if (parentName.empty()) { return -1; } DirectX::XMFLOAT4X4 worldMatrix; if (!model->GetBoneWorldMatrixByName(aasParams, parentName, &worldMatrix)) { return -1; } parentPos.x = worldMatrix._41; parentPos.y = worldMatrix._42; parentPos.z = worldMatrix._43; if (!model->GetBoneWorldMatrixByName(aasParams, boneName, &worldMatrix)) { return -1; } childPos.x = worldMatrix._41; childPos.y = worldMatrix._42; childPos.z = worldMatrix._43; return parentId; } bool PartSysExternal::GetBonePos(ObjHndl obj, int boneIdx, Vec3& pos) { auto model = objects.GetAnimHandle(obj); auto aasParams = objects.GetAnimParams(obj); auto boneName(model->GetBoneName(boneIdx)); if (boneName.empty()) { return false; } DirectX::XMFLOAT4X4 worldMatrix; if (!model->GetBoneWorldMatrixByName(aasParams, boneName, &worldMatrix)) { return false; } pos.x = worldMatrix._41; pos.y = worldMatrix._42; pos.z = worldMatrix._43; return true; } void PartSysExternal::WorldToScreen(const Vec3& worldPos, Vec2& screenPos) { screenPos = mCamera.WorldToScreen(worldPos); auto offset2d = mCamera.Get2dTranslation(); screenPos.x += offset2d.x; screenPos.y += offset2d.y; } bool PartSysExternal::IsBoxVisible(const Vec2& screenPos, const Box2d& box) { return mCamera.IsBoxOnScreen(screenPos, box.left, box.top, box.right, box.bottom); } <|endoftext|>
<commit_before>/******************************************************************************//** * @copyright (c) RDO-Team, 2011 * @file braces.cpp * @authors * @date 16.04.2011 * @brief unknown * @indent 4T *********************************************************************************/ #ifndef _LIB_RUNTIME_CALC_BINARY_H_ #define _LIB_RUNTIME_CALC_BINARY_H_ // **************************************************************************** PCH #include "rdo_lib/rdo_runtime/pch.h" // *********************************************************************** INCLUDES // *********************************************************************** SYNOPSIS #include "rdo_lib/rdo_runtime/calc/braces.h" // ******************************************************************************** OPEN_RDO_RUNTIME_NAMESPACE // ******************************************************************************** // ******************** RDOCalcOpenBrace // ******************************************************************************** RDOCalcOpenBrace::RDOCalcOpenBrace() {} REF(RDOValue) RDOCalcOpenBrace::doCalc(CREF(LPRDORuntime) pRuntime) { LPRDOMemory pLocalMemory = rdo::Factory<RDOMemory>::create(); pRuntime->getMemoryStack()->push(pLocalMemory); return m_value; } // ******************************************************************************** // ******************** RDOCalcCloseBrace // ******************************************************************************** RDOCalcCloseBrace::RDOCalcCloseBrace() {} REF(RDOValue) RDOCalcCloseBrace::doCalc(CREF(LPRDORuntime) pRuntime) { pRuntime->getMemoryStack()->pop(); return m_value; } // ******************************************************************************** // ******************** RDOCalcBodyBrace // ******************************************************************************** RDOCalcBodyBrace::RDOCalcBodyBrace() {} void RDOCalcBodyBrace::addCalc(CREF(LPRDOCalc) pCalc) { ASSERT(pCalc); m_calcList.push_back(pCalc); } REF(RDOValue) RDOCalcBodyBrace::doCalc(CREF(LPRDORuntime) pRuntime) { STL_FOR_ALL(m_calcList, calc_it) { (*calc_it)->calcValue(pRuntime); } m_value = RDOValue(m_calcList.size()); return m_value; } // ******************************************************************************** // ******************** RDOCalcFunBodyBrace // ******************************************************************************** RDOCalcFunBodyBrace::RDOCalcFunBodyBrace() {} void RDOCalcFunBodyBrace::addFunCalc(CREF(LPRDOCalc) pCalc) { ASSERT(pCalc); m_calcFunList.push_back(pCalc); } void RDOCalcFunBodyBrace::addRetCalc(CREF(LPRDOCalc) pCalc) { ASSERT(pCalc); LPRDOCalc pCalcReturn = rdo::Factory<rdoRuntime::RDOCalcFunReturn>::create(pCalc); m_calcFunList.insert(--m_calcFunList.end(), pCalcReturn); } REF(RDOValue) RDOCalcFunBodyBrace::doCalc(CREF(LPRDORuntime) pRuntime) { if (pRuntime->getFunBreakFlag() == RDORuntime::FBF_CONTINUE) { STL_FOR_ALL(m_calcFunList, calcIt) { LPRDOCalc pCalc = *calcIt; ASSERT(pCalc); m_value = pCalc->calcValue(pRuntime); if (pRuntime->getFunBreakFlag() == RDORuntime::FBF_BREAK) { m_calcFunList.back()->calcValue(pRuntime); pRuntime->setFunBreakFlag(RDORuntime::FBF_CONTINUE); m_value = RDOValue(false); //! break return m_value; } if (pRuntime->getFunBreakFlag() == RDORuntime::FBF_RETURN) { m_calcFunList.back()->calcValue(pRuntime); return m_value; } } } return m_value; } // ******************************************************************************** // ******************** RDOCalcFunEnd // ******************************************************************************** RDOCalcFunEnd::RDOCalcFunEnd() {} REF(RDOValue) RDOCalcFunEnd::doCalc(CREF(LPRDORuntime) pRuntime) { pRuntime->getMemoryStack()->pop(); pRuntime->setFunBreakFlag(RDORuntime::FBF_CONTINUE); return m_value; } CLOSE_RDO_RUNTIME_NAMESPACE <commit_msg> - repair<commit_after>/******************************************************************************//** * @copyright (c) RDO-Team, 2011 * @file braces.cpp * @authors * @date 16.04.2011 * @brief unknown * @indent 4T *********************************************************************************/ // **************************************************************************** PCH #include "rdo_lib/rdo_runtime/pch.h" // *********************************************************************** INCLUDES // *********************************************************************** SYNOPSIS #include "rdo_lib/rdo_runtime/calc/braces.h" // ******************************************************************************** OPEN_RDO_RUNTIME_NAMESPACE // ******************************************************************************** // ******************** RDOCalcOpenBrace // ******************************************************************************** RDOCalcOpenBrace::RDOCalcOpenBrace() {} REF(RDOValue) RDOCalcOpenBrace::doCalc(CREF(LPRDORuntime) pRuntime) { LPRDOMemory pLocalMemory = rdo::Factory<RDOMemory>::create(); pRuntime->getMemoryStack()->push(pLocalMemory); return m_value; } // ******************************************************************************** // ******************** RDOCalcCloseBrace // ******************************************************************************** RDOCalcCloseBrace::RDOCalcCloseBrace() {} REF(RDOValue) RDOCalcCloseBrace::doCalc(CREF(LPRDORuntime) pRuntime) { pRuntime->getMemoryStack()->pop(); return m_value; } // ******************************************************************************** // ******************** RDOCalcBodyBrace // ******************************************************************************** RDOCalcBodyBrace::RDOCalcBodyBrace() {} void RDOCalcBodyBrace::addCalc(CREF(LPRDOCalc) pCalc) { ASSERT(pCalc); m_calcList.push_back(pCalc); } REF(RDOValue) RDOCalcBodyBrace::doCalc(CREF(LPRDORuntime) pRuntime) { STL_FOR_ALL(m_calcList, calc_it) { (*calc_it)->calcValue(pRuntime); } m_value = RDOValue(m_calcList.size()); return m_value; } // ******************************************************************************** // ******************** RDOCalcFunBodyBrace // ******************************************************************************** RDOCalcFunBodyBrace::RDOCalcFunBodyBrace() {} void RDOCalcFunBodyBrace::addFunCalc(CREF(LPRDOCalc) pCalc) { ASSERT(pCalc); m_calcFunList.push_back(pCalc); } void RDOCalcFunBodyBrace::addRetCalc(CREF(LPRDOCalc) pCalc) { ASSERT(pCalc); LPRDOCalc pCalcReturn = rdo::Factory<rdoRuntime::RDOCalcFunReturn>::create(pCalc); m_calcFunList.insert(--m_calcFunList.end(), pCalcReturn); } REF(RDOValue) RDOCalcFunBodyBrace::doCalc(CREF(LPRDORuntime) pRuntime) { if (pRuntime->getFunBreakFlag() == RDORuntime::FBF_CONTINUE) { STL_FOR_ALL(m_calcFunList, calcIt) { LPRDOCalc pCalc = *calcIt; ASSERT(pCalc); m_value = pCalc->calcValue(pRuntime); if (pRuntime->getFunBreakFlag() == RDORuntime::FBF_BREAK) { m_calcFunList.back()->calcValue(pRuntime); pRuntime->setFunBreakFlag(RDORuntime::FBF_CONTINUE); m_value = RDOValue(false); //! break return m_value; } if (pRuntime->getFunBreakFlag() == RDORuntime::FBF_RETURN) { m_calcFunList.back()->calcValue(pRuntime); return m_value; } } } return m_value; } // ******************************************************************************** // ******************** RDOCalcFunEnd // ******************************************************************************** RDOCalcFunEnd::RDOCalcFunEnd() {} REF(RDOValue) RDOCalcFunEnd::doCalc(CREF(LPRDORuntime) pRuntime) { pRuntime->getMemoryStack()->pop(); pRuntime->setFunBreakFlag(RDORuntime::FBF_CONTINUE); return m_value; } CLOSE_RDO_RUNTIME_NAMESPACE <|endoftext|>
<commit_before>#include <boost/python.hpp> #include <boost/python/docstring_options.hpp> #include <boost/numpy.hpp> #include <boost/scoped_array.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <sstream> #include "zhangsuen.h" typedef unsigned char uchar_t; namespace py = boost::python; namespace np = boost::numpy; /** * ndarray_to_mat(const np::ndarray& array, cv::Mat& result) * * Args: * array: The input boost::numpy::ndarray. Must be 2D and the data type * should be unsigned char. Also, the inner data alignment should be * row major. * * result: The resulting cv::Mat. It is assumed to be initialized to * have appropriate number of rows and columns * * NOTE: The memory is NOT shared between the input ndarray and the resultant * mat, unlike the reverse ndarray_to_mat() function. * */ void ndarray_to_mat(const np::ndarray& array, cv::Mat& result) { // Ensure dtype is unsigned char if (array.get_dtype() != np::dtype::get_builtin<uchar_t>()) { np::dtype need_dtype = np::dtype::get_builtin<uchar_t>(); std::stringstream ss; ss << "Incorrect data type: " << "Expected: " << py::extract<const char*>(py::str(need_dtype)) << ", Got: " << py::extract<const char*>(py::str(array.get_dtype())); PyErr_SetString(PyExc_TypeError, ss.str().c_str()); py::throw_error_already_set(); } // Ensure the array is 2D if (array.get_nd() != 2) { std::stringstream ss; ss << "Expecting a 2D array, got a " << array.get_nd() << " array."; PyErr_SetString(PyExc_TypeError, ss.str().c_str()); py::throw_error_already_set(); } // Ensure the array is row major if (!(array.get_flags() & np::ndarray::C_CONTIGUOUS)) { PyErr_SetString(PyExc_TypeError, "Array must be row major contiguous"); py::throw_error_already_set(); } uchar_t *data = reinterpret_cast<uchar_t*>(array.get_data()); int row_incr = array.strides(0) / sizeof(*data), col_incr = array.strides(1) / sizeof(*data); uchar_t *iter; int rows = array.shape(0), cols = array.shape(1); for (int i = 0; i < rows; i++) { iter = data + i * row_incr; uchar_t *row = result.ptr<uchar_t>(i); for (int j = 0; j < cols; j++) { *(row + j) = *(iter + j * col_incr); } } } // Return an ndarray that holds the same information as the underlying cv::Mat // NOTE: The memory is shared between the returned ndarray and the input image. static np::ndarray mat_to_ndarray(const cv::Mat& image, bool share_mem=true) { uchar_t* data = image.data; // Our images are all grayscale, so the datatype will be (the numpy // equivalent of) uchar_t np::dtype type(np::dtype::get_builtin<uchar_t>()); // This is the shape of the resulting ndarray, the number of rows and the // number of columns. py::tuple shape = py::make_tuple(image.rows, image.cols); // Strides for rows and columns. Given a current position in a 2D array, // the row stride is the number of bytes to be traversed from the current // position to get to the corresponding column in the next row. The column // stride is the number of bytes to be traversed from the current position // to get to the next element(column) in the same row. py::tuple strides = py::make_tuple(image.step[0] * sizeof(*data), image.step[1] * sizeof(*data)); // The owner of the resulting ndarray. Since we are sharing the memory used // by the |image| and the resulting ndarray, we need the resultant to hold // a reference to this piece of memory. Since the resultant array holds // a reference to its owner object, it is prevented from being deallocated // by the GC. if (share_mem) { //TODO: This doesn't seem to work as the thinned image, when viewed //from Python, is all screwed up. np::ndarray array = np::from_data(data, type, shape, strides, py::object()); return array; } else { np::ndarray array(np::zeros(shape, type)); uchar_t *result_data = reinterpret_cast<uchar_t*>(array.get_data()); int row_incr = array.strides(0) / sizeof(*data), col_incr = array.strides(1) / sizeof(*data); int mat_row_incr = image.step[0], mat_col_incr = image.step[1]; for (int i = 0; i < image.rows; i++) { uchar_t *result_iter = result_data + i * row_incr; uchar_t *mat_iter = data + i * mat_row_incr; for (int j = 0; j < image.cols; j++, result_iter += col_incr, mat_iter += mat_col_incr) { *result_iter = *mat_iter; } } return array; } } void show(const std::string& window, const cv::Mat& mat) { cv::namedWindow(window, CV_WINDOW_NORMAL); cv::imshow(window, mat); cv::waitKey(0); } void show(const std::string& window, const np::ndarray& array) { cv::Mat img(array.shape(0), array.shape(1), CV_8U); ndarray_to_mat(array, img); show(window, img); } static np::ndarray wrap_thin(const np::ndarray& image, bool need_boundary_smoothing=false, bool need_acute_angle_emphasis=false, bool destair=false) { cv::Mat mat(image.shape(0), image.shape(1), CV_8U); ndarray_to_mat(image, mat); thin(mat, need_boundary_smoothing, need_acute_angle_emphasis, destair); return mat_to_ndarray(mat, false /* don't share memory */); } static const std::string docstring_thin( "Perform Zhang-Suen thinning on `image`.\n\n" "Args: \n" " image(numpy.ndarray): The binarized image to thin. A black foreground on\n" " a lighter background is expected.\n\n" " need_boundary_smoothing(bool): Whether to perform the Stentiford boundary\n" " smoothing operation as a preprocessing step\n" " or not. This operation is performed to reduce\n" " line fuzz. Default false.\n\n" " need_acute_angle_emphasis(bool): Whether to perform the acute-angle emphasis\n" " preprocessing operation or not. This\n" " operation is used to decrease the necking\n" " effect. Default false.\n\n" " destair(bool): Whether to perform the Holt\'s destair post-processing. This\n" " reduces the staircase effect in oblique lines.\n" " Default false.\n"); BOOST_PYTHON_MODULE(zhangsuen) { // Initialize the Python runtime and the Boost.Numpy lib. // This is a must! Otherwise we will get a segfault. Py_Initialize(); np::initialize(); py::docstring_options doc_options; doc_options.disable_cpp_signatures(); py::def("thin", wrap_thin, docstring_thin.c_str()); } <commit_msg>Breaking free from Boost::Numpy<commit_after>#include "../zhangsuen.h" #include <Python.h> #include <boost/python.hpp> #include <boost/python/docstring_options.hpp> #include <boost/scoped_array.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include "numpy/ndarrayobject.h" #include <string> #include <iostream> namespace py = boost::python; static const std::string docstring_thin( "Perform Zhang-Suen thinning on `image`.\n\n" "Args: \n" " image(numpy.ndarray): The binarized image to thin. A black foreground on\n" " a lighter background is expected.\n\n" " need_boundary_smoothing(bool): Whether to perform the Stentiford boundary\n" " smoothing operation as a preprocessing step\n" " or not. This operation is performed to reduce\n" " line fuzz. Default false.\n\n" " need_acute_angle_emphasis(bool): Whether to perform the acute-angle emphasis\n" " preprocessing operation or not. This\n" " operation is used to decrease the necking\n" " effect. Default false.\n\n" " destair(bool): Whether to perform the Holt\'s destair post-processing. This\n" " reduces the staircase effect in oblique lines.\n" " Default false.\n"); // The following conversion functions are taken from OpenCV's cv2.cpp file inside modules/python/src2 folder. static PyObject* opencv_error = 0; static int failmsg(const char *fmt, ...) { char str[1000]; va_list ap; va_start(ap, fmt); vsnprintf(str, sizeof(str), fmt, ap); va_end(ap); PyErr_SetString(PyExc_TypeError, str); return 0; } class PyAllowThreads { public: PyAllowThreads() : _state(PyEval_SaveThread()) {} ~PyAllowThreads() { PyEval_RestoreThread(_state); } private: PyThreadState* _state; }; class PyEnsureGIL { public: PyEnsureGIL() : _state(PyGILState_Ensure()) {} ~PyEnsureGIL() { PyGILState_Release(_state); } private: PyGILState_STATE _state; }; #define ERRWRAP2(expr) \ try \ { \ PyAllowThreads allowThreads; \ expr; \ } \ catch (const cv::Exception &e) \ { \ PyErr_SetString(opencv_error, e.what()); \ return 0; \ } using namespace cv; static PyObject* failmsgp(const char *fmt, ...) { char str[1000]; va_list ap; va_start(ap, fmt); vsnprintf(str, sizeof(str), fmt, ap); va_end(ap); PyErr_SetString(PyExc_TypeError, str); return 0; } static size_t REFCOUNT_OFFSET = (size_t)&(((PyObject*)0)->ob_refcnt) + (0x12345678 != *(const size_t*)"\x78\x56\x34\x12\0\0\0\0\0")*sizeof(int); static inline PyObject* pyObjectFromRefcount(const int* refcount) { return (PyObject*)((size_t)refcount - REFCOUNT_OFFSET); } static inline int* refcountFromPyObject(const PyObject* obj) { return (int*)((size_t)obj + REFCOUNT_OFFSET); } class NumpyAllocator : public MatAllocator { public: NumpyAllocator() {} ~NumpyAllocator() {} void allocate(int dims, const int* sizes, int type, int*& refcount, uchar*& datastart, uchar*& data, size_t* step) { PyEnsureGIL gil; int depth = CV_MAT_DEPTH(type); int cn = CV_MAT_CN(type); const int f = (int)(sizeof(size_t)/8); int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE : depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT : depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT : depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT; int i; npy_intp _sizes[CV_MAX_DIM+1]; for( i = 0; i < dims; i++ ) { _sizes[i] = sizes[i]; } if( cn > 1 ) { /*if( _sizes[dims-1] == 1 ) _sizes[dims-1] = cn; else*/ _sizes[dims++] = cn; } PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum); if(!o) { CV_Error_(CV_StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims)); } refcount = refcountFromPyObject(o); npy_intp* _strides = PyArray_STRIDES(o); for( i = 0; i < dims - (cn > 1); i++ ) step[i] = (size_t)_strides[i]; datastart = data = (uchar*)PyArray_DATA(o); } void deallocate(int* refcount, uchar*, uchar*) { PyEnsureGIL gil; if( !refcount ) return; PyObject* o = pyObjectFromRefcount(refcount); Py_INCREF(o); Py_DECREF(o); } }; NumpyAllocator g_numpyAllocator; enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 }; static int pyopencv_to(const PyObject* o, Mat& m, const char* name = "<unknown>", bool allowND=true) { //NumpyAllocator g_numpyAllocator; if(!o || o == Py_None) { if( !m.data ) m.allocator = &g_numpyAllocator; return true; } if( !PyArray_Check(o) ) { failmsg("%s is not a numpy array", name); return false; } int typenum = PyArray_TYPE(o); int type = typenum == NPY_UBYTE ? CV_8U : typenum == NPY_BYTE ? CV_8S : typenum == NPY_USHORT ? CV_16U : typenum == NPY_SHORT ? CV_16S : typenum == NPY_INT || typenum == NPY_LONG ? CV_32S : typenum == NPY_FLOAT ? CV_32F : typenum == NPY_DOUBLE ? CV_64F : -1; if( type < 0 ) { failmsg("%s data type = %d is not supported", name, typenum); return false; } int ndims = PyArray_NDIM(o); if(ndims >= CV_MAX_DIM) { failmsg("%s dimensionality (=%d) is too high", name, ndims); return false; } int size[CV_MAX_DIM+1]; size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type); const npy_intp* _sizes = PyArray_DIMS(o); const npy_intp* _strides = PyArray_STRIDES(o); bool transposed = false; for(int i = 0; i < ndims; i++) { size[i] = (int)_sizes[i]; step[i] = (size_t)_strides[i]; } if( ndims == 0 || step[ndims-1] > elemsize ) { size[ndims] = 1; step[ndims] = elemsize; ndims++; } if( ndims >= 2 && step[0] < step[1] ) { std::swap(size[0], size[1]); std::swap(step[0], step[1]); transposed = true; } if( ndims == 3 && size[2] <= CV_CN_MAX && step[1] == elemsize*size[2] ) { ndims--; type |= CV_MAKETYPE(0, size[2]); } if( ndims > 2 && !allowND ) { failmsg("%s has more than 2 dimensions", name); return false; } m = Mat(ndims, size, type, PyArray_DATA(o), step); if( m.data ) { m.refcount = refcountFromPyObject(o); m.addref(); // protect the original numpy array from deallocation // (since Mat destructor will decrement the reference counter) }; m.allocator = &g_numpyAllocator; if( transposed ) { Mat tmp; tmp.allocator = &g_numpyAllocator; transpose(m, tmp); m = tmp; } return true; } static PyObject* pyopencv_from(const Mat& m) { if( !m.data ) Py_RETURN_NONE; Mat temp, *p = (Mat*)&m; if(!p->refcount || p->allocator != &g_numpyAllocator) { temp.allocator = &g_numpyAllocator; m.copyTo(temp); p = &temp; } p->addref(); return pyObjectFromRefcount(p->refcount); } // The conversions functions above are taken from OpenCV. The following function is // what we define to access the C++ code we are interested in. PyObject* wrap_thin(PyObject* image, bool need_boundary_smoothing, bool need_acute_angle_emphasis, bool destair) { std::cout << "Here" << std::endl; cv::Mat cvImage; pyopencv_to(image, cvImage); // From OpenCV's source std::cout << "Converted to Mat" << std::endl; thin(cvImage, need_boundary_smoothing, need_acute_angle_emphasis, destair); std::cout << "Thinning done" << std::endl; PyObject *ret = pyopencv_from(cvImage); std::cout << "Converted to PyObject*" << std::endl; return ret; } static void init() { Py_Initialize(); import_array(); } BOOST_PYTHON_MODULE(zhangsuen) { init(); py::docstring_options doc_options; doc_options.disable_cpp_signatures(); py::def("thin", wrap_thin, docstring_thin.c_str()); } <|endoftext|>
<commit_before>#include <algorithm> /* max, min, next_permutation, prev_permutation */ #include <functional> /* greater */ #include <list> #include <sstream> /* istringstream, ostringstream */ #include <stdexcept> /* logic_error, invalid_argument */ #include <string> #include <vector> #include "Permutation.hpp" #include "Groups/util.hpp" /* lcm, factorial */ using namespace std; Permutation::Permutation() : pmap(0), _even(1), _order(1), _lehmer(0) { } Permutation::Permutation(const vector<int>& mapping, int ev, int ord, int lehm) : pmap(mapping), _even(ev), _order(ord), _lehmer(lehm) { while (!pmap.empty() && pmap.back() == (int) pmap.size()) pmap.pop_back(); } Permutation Permutation::identity() {return Permutation(); } int Permutation::operator()(int i) const { if (0 < i && i <= (int) pmap.size()) return pmap[i-1]; else return i; } Permutation Permutation::operator*(const Permutation& other) const { int newdeg = max(degree(), other.degree()); vector<int> newmap(newdeg); for (int i=0; i<newdeg; i++) newmap[i] = (*this)(other(i+1)); return Permutation(newmap, _even != -1 && other._even != -1 ? _even == other._even : -1); } Permutation& Permutation::operator*=(const Permutation& other) { *this = *this * other; return *this; } Permutation::operator string() const { vector< vector<int> > cycles = toCycles(); if (cycles.empty()) return string("1"); else { ostringstream out; for (size_t i=0; i<cycles.size(); i++) { out << '('; for (size_t j=0; j<cycles[i].size(); j++) { if (j>0) out << ' '; out << cycles[i][j]; } out << ')'; } return out.str(); } } Permutation::operator bool() const {return !pmap.empty(); } int Permutation::degree() const {return pmap.size(); } Permutation Permutation::inverse() const { vector<int> newmap(pmap.size()); for (size_t i=0; i<pmap.size(); i++) newmap[pmap[i]-1] = i+1; return Permutation(newmap, _even, _order); } int Permutation::order() const { if (_order == -1) { _order = 1; vector< vector<int> > cycles = toCycles(); for (size_t i=0; i<cycles.size(); i++) { _order = Groups::lcm(_order, cycles[i].size()); } } return _order; } bool Permutation::isEven() const { if (_even == -1) { size_t lensum = 0; vector< vector<int> > cycles = toCycles(); for (size_t i=0; i<cycles.size(); i++) { lensum += cycles[i].size() - 1; } _even = lensum % 2 == 0; } return bool(_even); } bool Permutation::isOdd() const {return !isEven(); } int Permutation::sign() const {return isEven() ? 1 : -1; } int Permutation::lehmer() const { if (_lehmer == -1) { _lehmer = 0; list<int> left; for (int i=degree(); i>0; i--) left.push_back(i); for (int x=degree(); x>0; x--) { int y = (*this)(x); list<int>::iterator iter = left.begin(); int i=0; while (*iter != y) {iter++; i++; } left.erase(iter); _lehmer = _lehmer * x + i; } } return _lehmer; } Permutation Permutation::fromLehmer(int x) { int x0 = x; vector<int> mapping; vector<int>::iterator iter; for (int f=1; x>0; x /= f++) { int c = x % f; for (iter = mapping.begin(); iter != mapping.end(); iter++) { if (*iter >= c) (*iter)++; } mapping.push_back(c); } for (iter = mapping.begin(); iter != mapping.end(); iter++) { *iter = mapping.size() - *iter; } return Permutation(mapping, -1, -1, max(x0,0)); } vector< vector<int> > Permutation::toCycles() const { vector<int> cmap(pmap); vector< vector<int> > cycles; for (int i=0; i<(int)cmap.size(); i++) { if (cmap[i] != 0 && cmap[i] != i+1) { int x = i+1; vector<int> cyke(1, x); int y = cmap[x-1]; cmap[x-1] = 0; while (y != x) { cyke.push_back(y); int next = cmap[y-1]; cmap[y-1] = 0; y = next; } cycles.push_back(cyke); } } return cycles; } /* Returns the permutation representing the transposition of the positive * integers `a` and `b` */ Permutation Permutation::transposition(int a, int b) { if (a < 1 || b < 1) throw invalid_argument("Permutation::transposition: arguments must be positive"); if (a == b) return Permutation(); else { int big = max(a,b), small = min(a,b); vector<int> mapping(big); for (int i=0; i<big; i++) mapping[i] = i+1 == a ? b : i+1 == b ? a : i+1; /* For $a<b$, $Lehmer((a b)) = (b-a) (b-1)! + \sum_{i=a}^{b-2} i!$ */ int lehmer = 0, fac = Groups::factorial(small); for (int i=small; i<big-1; i++) { lehmer += fac; fac *= i+1; } lehmer += fac * (big-small); return Permutation(mapping, 0, 2, lehmer); } } Permutation Permutation::firstOfDegree(int n) { if (n <= 1) return identity(); else return transposition(n, n-1); } /* This comparison method produces the same ordering as the modified Lehmer * codes. */ int Permutation::cmp(const Permutation& other) const { if (degree() < other.degree()) return -1; if (degree() > other.degree()) return 1; for (int i=degree()-1; i>=0; i--) { if (pmap[i] > other.pmap[i]) return -1; if (pmap[i] < other.pmap[i]) return 1; } return 0; } Permutation& Permutation::operator++() { if (degree() == 0) { *this = transposition(1,2); } else if (!next_permutation(pmap.rbegin(), pmap.rend(), greater<int>())) { *this = firstOfDegree(degree()+1); } else { _even = -1; _order = -1; if (_lehmer != -1) _lehmer++; } return *this; } Permutation Permutation::operator++(int) { Permutation tmp(*this); ++*this; return tmp; } Permutation& Permutation::operator--() { if (degree() == 0) throw logic_error("Permutation::operator--: cannot decrement identity"); prev_permutation(pmap.rbegin(), pmap.rend(), greater<int>()); while (!pmap.empty() && pmap.back() == (int) pmap.size()) pmap.pop_back(); _even = -1; _order = -1; if (_lehmer != -1) _lehmer--; return *this; } Permutation Permutation::operator--(int) { Permutation tmp(*this); --*this; return tmp; } bool Permutation::disjoint(const Permutation& other) const { for (int i=0; i < min(degree(), other.degree()); i++) { if (i+1 != pmap[i] && i+1 != other.pmap[i]) return false; } return true; } vector<Permutation> Permutation::s_n(int degree) { vector<Permutation> elems(Groups::factorial(degree), identity()); vector<Permutation>::iterator iter = elems.begin(); Permutation p = *iter; for (iter++, p++; iter != elems.end(); iter++, p++) { *iter = p; } return elems; } vector<int> Permutation::toImage() const {return pmap; } Permutation Permutation::fromImage(const vector<int>& img) { vector<bool> used(img.size(), false); vector<int>::const_iterator iter; for (iter = img.begin(); iter != img.end(); iter++) { if (*iter < 1) throw invalid_argument("Permutation::fromImage: values must be positive"); if (*iter > (int) img.size()) throw invalid_argument("Permutation::fromImage: value missing from input"); if (used[*iter-1]) throw invalid_argument("Permutation::fromImage: value repeated in input"); used[*iter-1] = true; } return Permutation(img); } Permutation Permutation::parse(const string& s) { istringstream in(s); char c; in >> ws; if (in >> c) { if (c == '(') { vector< vector<int> > cycles; for (;;) { vector<int> cyc; int i; while (in >> i) cyc.push_back(i); if (cyc.empty()) throw invalid_argument("Permutation::parse"); in >> ws; if ((in >> c) && c == ')') { cycles.push_back(cyc); in >> ws; if (ws.eof()) return fromCycles<vector< vector<int> >::const_iterator>(cycles.begin(), cycles.end()); else if ((in >> c) && c == '(') continue; else throw invalid_argument("Permutation::parse"); } else throw invalid_argument("Permutation::parse"); } } else if (c == '1') { in >> ws; if (in.eof()) return identity(); else throw invalid_argument("Permutation::parse"); } else throw invalid_argument("Permutation::parse"); } else throw invalid_argument("Permutation::parse"); } <commit_msg>Fixed compilation error. Stupid ambiguous compiler messages.<commit_after>#include <algorithm> /* max, min, next_permutation, prev_permutation */ #include <functional> /* greater */ #include <list> #include <sstream> /* istringstream, ostringstream */ #include <stdexcept> /* logic_error, invalid_argument */ #include <string> #include <vector> #include "Permutation.hpp" #include "Groups/util.hpp" /* lcm, factorial */ using namespace std; Permutation::Permutation() : pmap(0), _even(1), _order(1), _lehmer(0) { } Permutation::Permutation(const vector<int>& mapping, int ev, int ord, int lehm) : pmap(mapping), _even(ev), _order(ord), _lehmer(lehm) { while (!pmap.empty() && pmap.back() == (int) pmap.size()) pmap.pop_back(); } Permutation Permutation::identity() {return Permutation(); } int Permutation::operator()(int i) const { if (0 < i && i <= (int) pmap.size()) return pmap[i-1]; else return i; } Permutation Permutation::operator*(const Permutation& other) const { int newdeg = max(degree(), other.degree()); vector<int> newmap(newdeg); for (int i=0; i<newdeg; i++) newmap[i] = (*this)(other(i+1)); return Permutation(newmap, _even != -1 && other._even != -1 ? _even == other._even : -1); } Permutation& Permutation::operator*=(const Permutation& other) { *this = *this * other; return *this; } Permutation::operator string() const { vector< vector<int> > cycles = toCycles(); if (cycles.empty()) return string("1"); else { ostringstream out; for (size_t i=0; i<cycles.size(); i++) { out << '('; for (size_t j=0; j<cycles[i].size(); j++) { if (j>0) out << ' '; out << cycles[i][j]; } out << ')'; } return out.str(); } } Permutation::operator bool() const {return !pmap.empty(); } int Permutation::degree() const {return pmap.size(); } Permutation Permutation::inverse() const { vector<int> newmap(pmap.size()); for (size_t i=0; i<pmap.size(); i++) newmap[pmap[i]-1] = i+1; return Permutation(newmap, _even, _order); } int Permutation::order() const { if (_order == -1) { _order = 1; vector< vector<int> > cycles = toCycles(); for (size_t i=0; i<cycles.size(); i++) { _order = Groups::lcm(_order, cycles[i].size()); } } return _order; } bool Permutation::isEven() const { if (_even == -1) { size_t lensum = 0; vector< vector<int> > cycles = toCycles(); for (size_t i=0; i<cycles.size(); i++) { lensum += cycles[i].size() - 1; } _even = lensum % 2 == 0; } return bool(_even); } bool Permutation::isOdd() const {return !isEven(); } int Permutation::sign() const {return isEven() ? 1 : -1; } int Permutation::lehmer() const { if (_lehmer == -1) { _lehmer = 0; list<int> left; for (int i=degree(); i>0; i--) left.push_back(i); for (int x=degree(); x>0; x--) { int y = (*this)(x); list<int>::iterator iter = left.begin(); int i=0; while (*iter != y) {iter++; i++; } left.erase(iter); _lehmer = _lehmer * x + i; } } return _lehmer; } Permutation Permutation::fromLehmer(int x) { int x0 = x; vector<int> mapping; vector<int>::iterator iter; for (int f=1; x>0; x /= f++) { int c = x % f; for (iter = mapping.begin(); iter != mapping.end(); iter++) { if (*iter >= c) (*iter)++; } mapping.push_back(c); } for (iter = mapping.begin(); iter != mapping.end(); iter++) { *iter = mapping.size() - *iter; } return Permutation(mapping, -1, -1, max(x0,0)); } vector< vector<int> > Permutation::toCycles() const { vector<int> cmap(pmap); vector< vector<int> > cycles; for (int i=0; i<(int)cmap.size(); i++) { if (cmap[i] != 0 && cmap[i] != i+1) { int x = i+1; vector<int> cyke(1, x); int y = cmap[x-1]; cmap[x-1] = 0; while (y != x) { cyke.push_back(y); int next = cmap[y-1]; cmap[y-1] = 0; y = next; } cycles.push_back(cyke); } } return cycles; } /* Returns the permutation representing the transposition of the positive * integers `a` and `b` */ Permutation Permutation::transposition(int a, int b) { if (a < 1 || b < 1) throw invalid_argument("Permutation::transposition: arguments must be positive"); if (a == b) return Permutation(); else { int big = max(a,b), small = min(a,b); vector<int> mapping(big); for (int i=0; i<big; i++) mapping[i] = i+1 == a ? b : i+1 == b ? a : i+1; /* For $a<b$, $Lehmer((a b)) = (b-a) (b-1)! + \sum_{i=a}^{b-2} i!$ */ int lehmer = 0, fac = Groups::factorial(small); for (int i=small; i<big-1; i++) { lehmer += fac; fac *= i+1; } lehmer += fac * (big-small); return Permutation(mapping, 0, 2, lehmer); } } Permutation Permutation::firstOfDegree(int n) { if (n <= 1) return identity(); else return transposition(n, n-1); } /* This comparison method produces the same ordering as the modified Lehmer * codes. */ int Permutation::cmp(const Permutation& other) const { if (degree() < other.degree()) return -1; if (degree() > other.degree()) return 1; for (int i=degree()-1; i>=0; i--) { if (pmap[i] > other.pmap[i]) return -1; if (pmap[i] < other.pmap[i]) return 1; } return 0; } Permutation& Permutation::operator++() { if (degree() == 0) { *this = transposition(1,2); } else if (!next_permutation(pmap.rbegin(), pmap.rend(), greater<int>())) { *this = firstOfDegree(degree()+1); } else { _even = -1; _order = -1; if (_lehmer != -1) _lehmer++; } return *this; } Permutation Permutation::operator++(int) { Permutation tmp(*this); ++*this; return tmp; } Permutation& Permutation::operator--() { if (degree() == 0) throw logic_error("Permutation::operator--: cannot decrement identity"); prev_permutation(pmap.rbegin(), pmap.rend(), greater<int>()); while (!pmap.empty() && pmap.back() == (int) pmap.size()) pmap.pop_back(); _even = -1; _order = -1; if (_lehmer != -1) _lehmer--; return *this; } Permutation Permutation::operator--(int) { Permutation tmp(*this); --*this; return tmp; } bool Permutation::disjoint(const Permutation& other) const { for (int i=0; i < min(degree(), other.degree()); i++) { if (i+1 != pmap[i] && i+1 != other.pmap[i]) return false; } return true; } vector<Permutation> Permutation::s_n(int degree) { vector<Permutation> elems(Groups::factorial(degree), identity()); vector<Permutation>::iterator iter = elems.begin(); Permutation p = *iter; for (iter++, p++; iter != elems.end(); iter++, p++) { *iter = p; } return elems; } vector<int> Permutation::toImage() const {return pmap; } Permutation Permutation::fromImage(const vector<int>& img) { vector<bool> used(img.size(), false); vector<int>::const_iterator iter; for (iter = img.begin(); iter != img.end(); iter++) { if (*iter < 1) throw invalid_argument("Permutation::fromImage: values must be positive"); if (*iter > (int) img.size()) throw invalid_argument("Permutation::fromImage: value missing from input"); if (used[*iter-1]) throw invalid_argument("Permutation::fromImage: value repeated in input"); used[*iter-1] = true; } return Permutation(img); } Permutation Permutation::parse(const string& s) { istringstream in(s); char c; in >> ws; if (in >> c) { if (c == '(') { vector< vector<int> > cycles; for (;;) { vector<int> cyc; int i; while (in >> i) cyc.push_back(i); if (cyc.empty()) throw invalid_argument("Permutation::parse"); in >> ws; if ((in >> c) && c == ')') { cycles.push_back(cyc); in >> ws; if (in.eof()) return fromCycles(cycles.begin(), cycles.end()); else if ((in >> c) && c == '(') continue; else throw invalid_argument("Permutation::parse"); } else throw invalid_argument("Permutation::parse"); } } else if (c == '1') { in >> ws; if (in.eof()) return identity(); else throw invalid_argument("Permutation::parse"); } else throw invalid_argument("Permutation::parse"); } else throw invalid_argument("Permutation::parse"); } <|endoftext|>
<commit_before>#ifndef OPENBFME_STRING_HPP #define OPENBFME_STRING_HPP #include "types.hpp" #include <vector> namespace OpenBFME { struct Printable{ // TODO - support more stuffs. enum Type{ Integer, Decimal, Character, String }; Type type; union { integer num; decimal dec; character ch; cstring str; }; template<typename T> Printable(T n, typename std::enable_if<std::is_integral<T>::value>::type* = 0) : type(Integer), num(n) {} template<typename T> Printable(T d, typename std::enable_if<std::is_floating_point<T>::value>::type* = 0) : type(Decimal), dec(d) {} inline Printable(char c) : type(Character), ch(c) {} inline Printable(const std::string& s) : type(String), str(s.c_str()) {} inline Printable(cstring s) : type(String), str(s) {} }; string to_base(unsigned int value, unsigned int base, char start = 'a'); string format(const string& fmt, std::vector<Printable> args); /*! * \brief Formats the string with a subset of printf syntax. * \todo Support more printf options. * \todo Make it more safe. */ template<typename... Args> inline string format(const string& fmt, Args... args){ return format(fmt, std::vector<Printable>{ args... }); } } #endif //OPENBFME_STRING_HPP <commit_msg>added an empty format function for when format is called with no additional arguments.<commit_after>#ifndef OPENBFME_STRING_HPP #define OPENBFME_STRING_HPP #include "types.hpp" #include <vector> namespace OpenBFME { struct Printable{ // TODO - support more stuffs. enum Type{ Integer, Decimal, Character, String }; Type type; union { integer num; decimal dec; character ch; cstring str; }; template<typename T> Printable(T n, typename std::enable_if<std::is_integral<T>::value>::type* = 0) : type(Integer), num(n) {} template<typename T> Printable(T d, typename std::enable_if<std::is_floating_point<T>::value>::type* = 0) : type(Decimal), dec(d) {} inline Printable(char c) : type(Character), ch(c) {} inline Printable(const std::string& s) : type(String), str(s.c_str()) {} inline Printable(cstring s) : type(String), str(s) {} }; string to_base(unsigned int value, unsigned int base, char start = 'a'); inline string format(const string& fmt){ return fmt; } string format(const string& fmt, std::vector<Printable> args); /*! * \brief Formats the string with a subset of printf syntax. * \todo Support more printf options. * \todo Make it more safe. */ template<typename... Args> inline string format(const string& fmt, Args... args){ return format(fmt, std::vector<Printable>{ args... }); } } #endif //OPENBFME_STRING_HPP <|endoftext|>
<commit_before>/** \file add_synonyms.cc * \brief Generic version for augmenting title data with synonyms found in the authority data * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* We offer a list of tags and subfields where the primary data resides along with a list of tags and subfields where the synonym data is found and a list of unused fields in the title data where the synonyms can be stored */ #include <iostream> #include <map> #include <vector> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MarcUtil.h" #include "MarcXmlWriter.h" #include "MediaTypeUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" static unsigned modified_count(0); static unsigned record_count(0); void Usage() { std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n"; std::exit(EXIT_FAILURE); } std::string GetTag(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(0, 3); } std::string GetSubfields(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(3); } void ExtractSynonyms(File * const norm_data_marc_input, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &synonym_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> * const synonym_maps) { while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(norm_data_marc_input)) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator synonym; unsigned int i(0); for (primary = primary_tags_and_subfield_codes.begin(), synonym = synonym_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++synonym, ++i) { // Fill maps with synonyms std::vector<std::string> primary_values; std::vector<std::string> synonym_values; if (record.extractSubfields(GetTag(*primary), GetSubfields(*primary), &primary_values) and record.extractSubfields(GetTag(*synonym), GetSubfields(*synonym), &synonym_values)) (*synonym_maps)[i].emplace(StringUtil::Join(primary_values, ','), StringUtil::Join(synonym_values, ',')); } } } void ProcessRecord(MarcUtil::Record * const record, const std::vector<std::map<std::string, std::string>> &synonym_maps, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator output; unsigned int i(0); if (primary_tags_and_subfield_codes.size() == output_tags_and_subfield_codes.size()) { for (primary = primary_tags_and_subfield_codes.begin(), output = output_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++output, ++i) { std::vector<std::string> primary_values; std::string synonyms; if (record->extractSubfields(GetTag(*primary), GetSubfields(*primary), &primary_values)) { // First case: Look up synonyms only in one category if (i < synonym_maps.size()) { const auto synonym_map(synonym_maps[i]); synonyms = synonym_map.find(StringUtil::Join(primary_values, ','))->second; } // Second case: Look up synonyms in all categories else { for (auto sm : synonym_maps) synonyms += sm[StringUtil::Join(primary_values, ',')]; } if (synonyms.empty()) continue; // Insert synonyms // Abort if field is already populated std::string tag(GetTag(*output)); if (record->getFieldIndex(tag) != -1) Error("Field with tag " + tag + " is not empty for PPN " + record->getControlNumber() + '\n'); std::string subfield_spec = GetSubfields(*output); if (subfield_spec.size() != 1) Error("We currently only support a single subfield and thus specifying " + subfield_spec + " as output subfield is not valid\n"); Subfields subfields(' ', ' '); // <- indicators must be set explicitly although empty subfields.addSubfield(subfield_spec.at(0), synonyms); if (not(record->insertField(tag, subfields.toString()))) Warning("Could not insert field " + tag + " for PPN " + record->getControlNumber() + '\n'); ++modified_count; } } } } void InsertSynonyms(File * const marc_input, File * marc_output, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> &synonym_maps) { MarcXmlWriter xml_writer(marc_output); while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_input)) { ProcessRecord(&record, synonym_maps, primary_tags_and_subfield_codes, output_tags_and_subfield_codes); record.write(&xml_writer); ++record_count; } std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n"; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 4) Usage(); const std::string marc_input_filename(argv[1]); std::unique_ptr<File> marc_input(FileUtil::OpenInputFileOrDie(marc_input_filename)); const std::string norm_data_marc_input_filename(argv[2]); std::unique_ptr<File> norm_data_marc_input(FileUtil::OpenInputFileOrDie(norm_data_marc_input_filename)); const std::string marc_output_filename(argv[3]); if (unlikely(marc_input_filename == marc_output_filename)) Error("Title data input file name equals output file name!"); if (unlikely(norm_data_marc_input_filename == marc_output_filename)) Error("Authority data input file name equals output file name!"); File marc_output(marc_output_filename, "w"); if (not marc_output) Error("can't open \"" + marc_output_filename + "\" for writing!"); try { // Determine possible mappings const std::string AUTHORITY_DATA_PRIMARY_SPEC("110abcd:111abcd:130abcd:150abcd:151abcd"); const std::string AUTHORITY_DATA_SYNONYM_SPEC("410abcd:411abcd:430abcd:450abcd:451abcd"); const std::string TITLE_DATA_PRIMARY_SPEC("610abcd:611abcd:630abcd:650abcd:651abcd:689abcd"); const std::string TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS("180a:181a:182a:183a:184a:185a"); // Determine fields to handle std::set<std::string> primary_tags_and_subfield_codes; std::set<std::string> synonym_tags_and_subfield_codes; std::set<std::string> input_tags_and_subfield_codes; std::set<std::string> output_tags_and_subfield_codes; if (unlikely(StringUtil::Split(AUTHORITY_DATA_PRIMARY_SPEC, ":", &primary_tags_and_subfield_codes) < 1)) Error("Need at least one primary field"); if (unlikely(StringUtil::Split(AUTHORITY_DATA_SYNONYM_SPEC, ":", &synonym_tags_and_subfield_codes) < 1)) Error("Need at least one synonym field"); if (unlikely(StringUtil::Split(TITLE_DATA_PRIMARY_SPEC, ":", &input_tags_and_subfield_codes) < 1)) Error("Need at least one input field"); if (unlikely(StringUtil::Split(TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS, ":", &output_tags_and_subfield_codes) < 1)) Error("Need at least one output field"); unsigned num_of_authority_entries(primary_tags_and_subfield_codes.size()); if (synonym_tags_and_subfield_codes.size() != num_of_authority_entries) Error("Number of authority primary specs must match number of synonym specs"); if (input_tags_and_subfield_codes.size() != output_tags_and_subfield_codes.size()) Error("Number of fields title entry specs must match number of output specs"); std::vector<std::map<std::string, std::string>> synonym_maps(num_of_authority_entries, std::map<std::string, std::string>()); // Extract the synonyms from authority data ExtractSynonyms(norm_data_marc_input.get(), primary_tags_and_subfield_codes, synonym_tags_and_subfield_codes, &synonym_maps); // Iterate over the title data InsertSynonyms(marc_input.get(), &marc_output, input_tags_and_subfield_codes, output_tags_and_subfield_codes, synonym_maps); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <commit_msg>Update add_synonyms.cc<commit_after>/** \file add_synonyms.cc * \brief Generic version for augmenting title data with synonyms found in the authority data * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* We offer a list of tags and subfields where the primary data resides along with a list of tags and subfields where the synonym data is found and a list of unused fields in the title data where the synonyms can be stored */ #include <iostream> #include <map> #include <vector> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MarcUtil.h" #include "MarcXmlWriter.h" #include "MediaTypeUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" static unsigned modified_count(0); static unsigned record_count(0); void Usage() { std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n"; std::exit(EXIT_FAILURE); } std::string GetTag(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(0, 3); } std::string GetSubfieldCodes(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(3); } void ExtractSynonyms(File * const norm_data_marc_input, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &synonym_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> * const synonym_maps) { while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(norm_data_marc_input)) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator synonym; unsigned int i(0); for (primary = primary_tags_and_subfield_codes.begin(), synonym = synonym_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++synonym, ++i) { // Fill maps with synonyms std::vector<std::string> primary_values; std::vector<std::string> synonym_values; if (record.extractSubfields(GetTag(*primary), GetSubfieldCodes(*primary), &primary_values) and record.extractSubfields(GetTag(*synonym), GetSubfieldCodes(*synonym), &synonym_values)) (*synonym_maps)[i].emplace(StringUtil::Join(primary_values, ','), StringUtil::Join(synonym_values, ',')); } } } void ProcessRecord(MarcUtil::Record * const record, const std::vector<std::map<std::string, std::string>> &synonym_maps, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator output; unsigned int i(0); if (primary_tags_and_subfield_codes.size() == output_tags_and_subfield_codes.size()) { for (primary = primary_tags_and_subfield_codes.begin(), output = output_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++output, ++i) { std::vector<std::string> primary_values; std::string synonyms; if (record->extractSubfields(GetTag(*primary), GetSubfieldCodes(*primary), &primary_values)) { // First case: Look up synonyms only in one category if (i < synonym_maps.size()) { const auto synonym_map(synonym_maps[i]); synonyms = synonym_map.find(StringUtil::Join(primary_values, ','))->second; } // Second case: Look up synonyms in all categories else { for (auto sm : synonym_maps) synonyms += sm[StringUtil::Join(primary_values, ',')]; } if (synonyms.empty()) continue; // Insert synonyms // Abort if field is already populated std::string tag(GetTag(*output)); if (record->getFieldIndex(tag) != -1) Error("Field with tag " + tag + " is not empty for PPN " + record->getControlNumber() + '\n'); std::string subfield_spec = GetSubfieldCodes(*output); if (subfield_spec.size() != 1) Error("We currently only support a single subfield and thus specifying " + subfield_spec + " as output subfield is not valid\n"); Subfields subfields(' ', ' '); // <- indicators must be set explicitly although empty subfields.addSubfield(subfield_spec.at(0), synonyms); if (not(record->insertField(tag, subfields.toString()))) Warning("Could not insert field " + tag + " for PPN " + record->getControlNumber() + '\n'); ++modified_count; } } } } void InsertSynonyms(File * const marc_input, File * marc_output, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> &synonym_maps) { MarcXmlWriter xml_writer(marc_output); while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_input)) { ProcessRecord(&record, synonym_maps, primary_tags_and_subfield_codes, output_tags_and_subfield_codes); record.write(&xml_writer); ++record_count; } std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n"; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 4) Usage(); const std::string marc_input_filename(argv[1]); std::unique_ptr<File> marc_input(FileUtil::OpenInputFileOrDie(marc_input_filename)); const std::string norm_data_marc_input_filename(argv[2]); std::unique_ptr<File> norm_data_marc_input(FileUtil::OpenInputFileOrDie(norm_data_marc_input_filename)); const std::string marc_output_filename(argv[3]); if (unlikely(marc_input_filename == marc_output_filename)) Error("Title data input file name equals output file name!"); if (unlikely(norm_data_marc_input_filename == marc_output_filename)) Error("Authority data input file name equals output file name!"); File marc_output(marc_output_filename, "w"); if (not marc_output) Error("can't open \"" + marc_output_filename + "\" for writing!"); try { // Determine possible mappings const std::string AUTHORITY_DATA_PRIMARY_SPEC("110abcd:111abcd:130abcd:150abcd:151abcd"); const std::string AUTHORITY_DATA_SYNONYM_SPEC("410abcd:411abcd:430abcd:450abcd:451abcd"); const std::string TITLE_DATA_PRIMARY_SPEC("610abcd:611abcd:630abcd:650abcd:651abcd:689abcd"); const std::string TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS("180a:181a:182a:183a:184a:185a"); // Determine fields to handle std::set<std::string> primary_tags_and_subfield_codes; std::set<std::string> synonym_tags_and_subfield_codes; std::set<std::string> input_tags_and_subfield_codes; std::set<std::string> output_tags_and_subfield_codes; if (unlikely(StringUtil::Split(AUTHORITY_DATA_PRIMARY_SPEC, ":", &primary_tags_and_subfield_codes) < 1)) Error("Need at least one primary field"); if (unlikely(StringUtil::Split(AUTHORITY_DATA_SYNONYM_SPEC, ":", &synonym_tags_and_subfield_codes) < 1)) Error("Need at least one synonym field"); if (unlikely(StringUtil::Split(TITLE_DATA_PRIMARY_SPEC, ":", &input_tags_and_subfield_codes) < 1)) Error("Need at least one input field"); if (unlikely(StringUtil::Split(TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS, ":", &output_tags_and_subfield_codes) < 1)) Error("Need at least one output field"); unsigned num_of_authority_entries(primary_tags_and_subfield_codes.size()); if (synonym_tags_and_subfield_codes.size() != num_of_authority_entries) Error("Number of authority primary specs must match number of synonym specs"); if (input_tags_and_subfield_codes.size() != output_tags_and_subfield_codes.size()) Error("Number of fields title entry specs must match number of output specs"); std::vector<std::map<std::string, std::string>> synonym_maps(num_of_authority_entries, std::map<std::string, std::string>()); // Extract the synonyms from authority data ExtractSynonyms(norm_data_marc_input.get(), primary_tags_and_subfield_codes, synonym_tags_and_subfield_codes, &synonym_maps); // Iterate over the title data InsertSynonyms(marc_input.get(), &marc_output, input_tags_and_subfield_codes, output_tags_and_subfield_codes, synonym_maps); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>// SqlPipe.cpp : Defines the entry point for the console application. // #include "stdafx.h" // The following come from "SQL Server 2005 Virtual Backup Device Interface (VDI) Specification" // http://www.microsoft.com/downloads/en/details.aspx?familyid=416f8a51-65a3-4e8e-a4c8-adfe15e850fc #include "vdi/vdi.h" // interface declaration #include "vdi/vdierror.h" // error constants #include "vdi/vdiguid.h" // define the interface identifiers. // Globals TCHAR* _serverInstanceName; bool _optionQuiet = false; // printf to stdout (if -q quiet option isn't specified) void log(const TCHAR* format, ...) { if (_optionQuiet) return; // Basically do a fprintf to stderr. The va_* stuff is just to handle variable args va_list arglist; va_start(arglist, format); vfwprintf(stderr, format, arglist); } // printf to stdout (regardless of -q quiet option) void err(const TCHAR* format, ...) { va_list arglist; va_start(arglist, format); vfwprintf(stderr, format, arglist); } // Get human-readable message given a HRESULT _bstr_t errorMessage(DWORD messageId) { LPTSTR szMessage; if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, messageId, 0, (LPTSTR)&szMessage, 0, NULL)) { szMessage = (LPTSTR)LocalAlloc(LPTR, 50 * sizeof(TCHAR)); _snwprintf(szMessage, 50 * sizeof(TCHAR), L"Unknown error 0x%x.\n", messageId); } _bstr_t retval = szMessage; LocalFree(szMessage); return retval; } // Execute the given SQL against _serverInstanceName DWORD executeSql(TCHAR* sql) { //log(L"\nexecuteSql '%s'\n", sql); HRESULT hr; // Use '_Connection_Deprecated' interface for maximum MDAC compatibility // BTW: Windows 7 SP1 introduced _Connection_Deprecated: See: // http://social.msdn.microsoft.com/Forums/en/windowsgeneraldevelopmentissues/thread/3a4ce946-effa-4f77-98a6-34f11c6b5a13 // and // http://support.microsoft.com/kb/2517589 _Connection_DeprecatedPtr conn; hr = conn.CreateInstance(__uuidof(Connection)); if (FAILED(hr)) { err(L"ADODB.Connection CreateInstance failed: %s", (TCHAR*)errorMessage(hr)); return hr; } // "lpc:..." ensures shared memory... _bstr_t serverName = "lpc:."; if (_serverInstanceName != NULL) serverName += "\\" + _bstr_t(_serverInstanceName); try { conn->ConnectionString = "Provider=SQLOLEDB; Data Source=" + serverName + "; Initial Catalog=master; Integrated Security=SSPI;"; //log(L"> Connect: %s\n", (TCHAR*)conn->ConnectionString); conn->ConnectionTimeout = 25; conn->Open("", "", "", adConnectUnspecified); } catch(_com_error e) { err(L"\nFailed to open connection to '" + serverName + L"': "); err(L"%s [%s]\n", (TCHAR*)e.Description(), (TCHAR*)e.Source()); return e.Error(); } try { //log(L"> SQL: %s\n", sql); variant_t recordsAffected; conn->CommandTimeout = 0; conn->Execute(sql, &recordsAffected, adExecuteNoRecords); conn->Close(); } catch(_com_error e) { err(L"\nQuery failed: '%s'\n\n%s [%s]\n", sql, (TCHAR*)e.Description(), (TCHAR*)e.Source()); //err(L" Errors:\n", conn->Errors->Count); //for (int i = 0; i < conn->Errors->Count; i++) // err(L" - %s\n\n", (TCHAR*)conn->Errors->Item[i]->Description); conn->Close(); return e.Error(); } return 0; } // Transfer data from virtualDevice to backupfile or vice-versa HRESULT performTransfer(IClientVirtualDevice* virtualDevice, FILE* backupfile) { VDC_Command * cmd; DWORD completionCode; DWORD bytesTransferred; HRESULT hr; DWORD totalBytes = 0; while (SUCCEEDED (hr = virtualDevice->GetCommand(3 * 60 * 1000, &cmd))) { //log(L">command %d, size %d\n", cmd->commandCode, cmd->size); bytesTransferred = 0; switch (cmd->commandCode) { case VDC_Read: while(bytesTransferred < cmd->size) bytesTransferred += fread(cmd->buffer + bytesTransferred, 1, cmd->size - bytesTransferred, backupfile); totalBytes += bytesTransferred; log(L"%d bytes read \r", totalBytes); cmd->size = bytesTransferred; completionCode = ERROR_SUCCESS; break; case VDC_Write: //log(L"VDC_Write - size: %d\r\n", cmd->size); while(bytesTransferred < cmd->size) bytesTransferred += fwrite(cmd->buffer + bytesTransferred, 1, cmd->size - bytesTransferred, backupfile); totalBytes += bytesTransferred; log(L"%d bytes written\r", totalBytes); completionCode = ERROR_SUCCESS; break; case VDC_Flush: //log(L"\nVDC_Flush %d\n", cmd->size); completionCode = ERROR_SUCCESS; break; case VDC_ClearError: log(L"\nVDC_ClearError\n"); //Debug::WriteLine("VDC_ClearError"); completionCode = ERROR_SUCCESS; break; default: // If command is unknown... completionCode = ERROR_NOT_SUPPORTED; } hr = virtualDevice->CompleteCommand(cmd, completionCode, bytesTransferred, 0); if (FAILED(hr)) { err(L"\nvirtualDevice->CompleteCommand failed: %s\n", (TCHAR*)errorMessage(hr)); return hr; } } log(L"\n"); if (hr != VD_E_CLOSE) { err(L"virtualDevice->GetCommand failed: "); if (hr == VD_E_TIMEOUT) err(L" timeout awaiting data.\n"); else if (hr == VD_E_ABORT) err(L" transfer was aborted.\n"); else err(L"%s\n", (TCHAR*)errorMessage(hr)); return hr; } return NOERROR; } // Entry point int _tmain(int argc, _TCHAR* argv[]) { if (argc < 3) { err(L"\n\ Action and database required.\n\ \n\ Usage: sqlpipe backup|restore <database> [options]\n\ Options:\n\ -q Quiet, don't print messages to STDERR\n\ -i \"instancename\"\n\ -f \"file\" Write/read file instead of STDOUT/STDIN\n"); return 1; } TCHAR* command = _wcslwr(argv[1]); TCHAR* databaseName = argv[2]; TCHAR* filePath = NULL; // Parse options for (int i = 0; i < argc; i++) { TCHAR* arg = _wcslwr(_wcsdup(argv[i])); if (wcscmp(arg, L"-q") == 0) _optionQuiet = true; if (wcscmp(arg, L"-i") == 0) _serverInstanceName = argv[i+1]; if (wcscmp(arg, L"-f") == 0) filePath = argv[i+1]; free(arg); } HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (FAILED(hr)) { // Switching from apartment to multi-threaded is OK if(hr != RPC_E_CHANGED_MODE) { err(L"CoInitializeEx failed: ", hr); return 1; } } // Create Device Set IClientVirtualDeviceSet2 * virtualDeviceSet; hr = CoCreateInstance( CLSID_MSSQL_ClientVirtualDeviceSet, NULL, CLSCTX_INPROC_SERVER, IID_IClientVirtualDeviceSet2, (void**)&virtualDeviceSet); if (FAILED(hr)) { err(L"Could not create VDI component. Check registration of SQLVDI.DLL. %s\n", (TCHAR*)errorMessage(hr)); return 2; } // Generate virtualDeviceName TCHAR virtualDeviceName[39]; GUID guid; CoCreateGuid(&guid); StringFromGUID2(guid, virtualDeviceName, sizeof(virtualDeviceName)); // Create Device VDConfig vdConfig = {0}; vdConfig.deviceCount = 1; hr = virtualDeviceSet->CreateEx(_serverInstanceName, virtualDeviceName, &vdConfig); if (!SUCCEEDED (hr)) { err(L"IClientVirtualDeviceSet2.CreateEx failed\r\n"); switch(hr) { case VD_E_INSTANCE_NAME: err(L"Didn't recognize the SQL Server instance name '"+ _bstr_t(_serverInstanceName) + L"'.\r\n"); break; case E_ACCESSDENIED: err(L"Access Denied: You must be logged in as a Windows administrator to create virtual devices.\r\n"); break; default: err(L"%s\n", (TCHAR*)errorMessage(hr)); break; } return 3; } TCHAR* sql; FILE* backupFile = NULL; if (wcscmp(command, L"backup") == 0) { sql = "BACKUP DATABASE [" + _bstr_t(databaseName) + "] TO VIRTUAL_DEVICE = '" + virtualDeviceName + "'"; if (filePath == NULL) backupFile = stdout; else { backupFile = _wfopen(filePath, L"w"); if (backupFile == NULL) { err(L"Error creating '%s': %s\n", filePath, _wcserror(errno)); return errno; } } } else if(wcscmp(command, L"restore") == 0) { hr = executeSql("CREATE DATABASE ["+ _bstr_t(databaseName) +"]"); if (FAILED(hr)) return hr; sql = "RESTORE DATABASE [" + _bstr_t(databaseName) + "] FROM VIRTUAL_DEVICE = '" + virtualDeviceName + "' WITH REPLACE"; if (filePath == NULL) backupFile = stdin; else { backupFile = _wfopen(filePath, L"r"); if (backupFile == NULL) { err(L"Error opening '%s': %s\n", filePath, _wcserror(errno)); return errno; } } } else { err(L"Unsupported command '%s': only BACKUP or RESTORE are supported.\n", command); return 1; } // Invoke backup on separate thread because virtualDeviceSet->GetConfiguration will block until "BACKUP DATABASE..." DWORD threadId; HANDLE executeSqlThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&executeSql, sql, 0, &threadId); // Ready... hr = virtualDeviceSet->GetConfiguration(30000, &vdConfig); if (FAILED(hr)) { err(L"\n%s: virtualDeviceSet->GetConfiguration failed: ", command); if (hr == VD_E_TIMEOUT) err(L"Timed out waiting for backup to be initiated.\n"); else err(L"%s\n", (TCHAR*)errorMessage(hr)); return 3; } // Steady... IClientVirtualDevice *virtualDevice = NULL; hr = virtualDeviceSet->OpenDevice(virtualDeviceName, &virtualDevice); if (FAILED(hr)) { err(L"virtualDeviceSet->OpenDevice failed: 0x%x - "); if (hr == VD_E_TIMEOUT) err(L" timeout.\n"); else err(L" %s.\n", (TCHAR*)errorMessage(hr)); return 4; } // Go _setmode(_fileno(backupFile), _O_BINARY); //ensure \n's in STDOUT don't get tampered with hr = performTransfer(virtualDevice, backupFile); WaitForSingleObject(executeSqlThread, 5000); // Tidy up CloseHandle(executeSqlThread); virtualDeviceSet->Close(); virtualDevice->Release(); virtualDeviceSet->Release(); //log(L"%s: Finished.\n", command); return hr; } <commit_msg>refactor out functions `executeRecordset` and `mountAndTransferVirtualDevice`<commit_after>// SqlPipe.cpp : Defines the entry point for the console application. // #include "stdafx.h" // The following come from "SQL Server 2005 Virtual Backup Device Interface (VDI) Specification" // http://www.microsoft.com/downloads/en/details.aspx?familyid=416f8a51-65a3-4e8e-a4c8-adfe15e850fc #include "vdi/vdi.h" // interface declaration #include "vdi/vdierror.h" // error constants #include "vdi/vdiguid.h" // define the interface identifiers. // Globals TCHAR* _serverInstanceName; bool _optionQuiet = false; // printf to stdout (if -q quiet option isn't specified) void log(const TCHAR* format, ...) { if (_optionQuiet) return; // Basically do a fprintf to stderr. The va_* stuff is just to handle variable args va_list arglist; va_start(arglist, format); vfwprintf(stderr, format, arglist); } // printf to stdout (regardless of -q quiet option) void err(const TCHAR* format, ...) { va_list arglist; va_start(arglist, format); vfwprintf(stderr, format, arglist); } // Get human-readable message given a HRESULT _bstr_t errorMessage(DWORD messageId) { LPTSTR szMessage; if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, messageId, 0, (LPTSTR)&szMessage, 0, NULL)) { szMessage = (LPTSTR)LocalAlloc(LPTR, 50 * sizeof(TCHAR)); _snwprintf(szMessage, 50 * sizeof(TCHAR), L"Unknown error 0x%x.\n", messageId); } _bstr_t retval = szMessage; LocalFree(szMessage); return retval; } // Execute the given SQL against _serverInstanceName DWORD executeSql(TCHAR* sql) { //log(L"\nexecuteSql '%s'\n", sql); HRESULT hr; // Use '_Connection_Deprecated' interface for maximum MDAC compatibility // BTW: Windows 7 SP1 introduced _Connection_Deprecated: See: // http://social.msdn.microsoft.com/Forums/en/windowsgeneraldevelopmentissues/thread/3a4ce946-effa-4f77-98a6-34f11c6b5a13 // and // http://support.microsoft.com/kb/2517589 _ConnectionPtr conn; hr = conn.CreateInstance(__uuidof(Connection)); if (FAILED(hr)) { err(L"ADODB.Connection CreateInstance failed: %s", (TCHAR*)errorMessage(hr)); return hr; } // "lpc:..." ensures shared memory... _bstr_t serverName = "lpc:."; if (_serverInstanceName != NULL) serverName += "\\" + _bstr_t(_serverInstanceName); try { conn->ConnectionString = "Provider=SQLOLEDB; Data Source=" + serverName + "; Initial Catalog=master; Integrated Security=SSPI;"; //log(L"> Connect: %s\n", (TCHAR*)conn->ConnectionString); conn->ConnectionTimeout = 25; conn->Open("", "", "", adConnectUnspecified); } catch(_com_error e) { err(L"\nFailed to open connection to '" + serverName + L"': "); err(L"%s [%s]\n", (TCHAR*)e.Description(), (TCHAR*)e.Source()); return e.Error(); } try { //log(L"> SQL: %s\n", sql); variant_t recordsAffected; conn->CommandTimeout = 0; conn->Execute(sql, &recordsAffected, adExecuteNoRecords); conn->Close(); } catch(_com_error e) { err(L"\nQuery failed: '%s'\n\n%s [%s]\n", sql, (TCHAR*)e.Description(), (TCHAR*)e.Source()); //err(L" Errors:\n", conn->Errors->Count); //for (int i = 0; i < conn->Errors->Count; i++) // err(L" - %s\n\n", (TCHAR*)conn->Errors->Item[i]->Description); conn->Close(); return e.Error(); } return 0; } _RecordsetPtr executeRecordset(TCHAR* sql) { HRESULT hr; _ConnectionPtr conn; hr = conn.CreateInstance(__uuidof(Connection)); if (FAILED(hr)) { err(L"ADODB.Connection CreateInstance failed: %s", (TCHAR*)errorMessage(hr)); return hr; } // "lpc:..." ensures shared memory... _bstr_t serverName = "lpc:."; if (_serverInstanceName != NULL) serverName += "\\" + _bstr_t(_serverInstanceName); try { conn->ConnectionString = "Provider=SQLOLEDB; Data Source=" + serverName + "; Initial Catalog=master; Integrated Security=SSPI;"; //log(L"> Connect: %s\n", (TCHAR*)conn->ConnectionString); conn->ConnectionTimeout = 25; conn->Open("", "", "", adConnectUnspecified); } catch(_com_error e) { err(L"\nFailed to open connection to '" + serverName + L"': "); err(L"%s [%s]\n", (TCHAR*)e.Description(), (TCHAR*)e.Source()); return NULL; } try { //log(L"> SQL: %s\n", sql); variant_t recordsAffected; conn->CommandTimeout = 0; _RecordsetPtr recordset = conn->Execute(sql, &recordsAffected, adExecuteNoRecords); conn->Close(); return recordset; } catch(_com_error e) { err(L"\nQuery failed: '%s'\n\n%s [%s]\n", sql, (TCHAR*)e.Description(), (TCHAR*)e.Source()); //err(L" Errors:\n", conn->Errors->Count); //for (int i = 0; i < conn->Errors->Count; i++) // err(L" - %s\n\n", (TCHAR*)conn->Errors->Item[i]->Description); conn->Close(); return NULL; } return NULL; } // Transfer data from virtualDevice to backupfile or vice-versa HRESULT performTransfer(IClientVirtualDevice* virtualDevice, FILE* backupfile) { VDC_Command * cmd; DWORD completionCode; DWORD bytesTransferred; HRESULT hr; DWORD totalBytes = 0; while (SUCCEEDED (hr = virtualDevice->GetCommand(3 * 60 * 1000, &cmd))) { //log(L">command %d, size %d\n", cmd->commandCode, cmd->size); bytesTransferred = 0; switch (cmd->commandCode) { case VDC_Read: while(bytesTransferred < cmd->size) bytesTransferred += fread(cmd->buffer + bytesTransferred, 1, cmd->size - bytesTransferred, backupfile); totalBytes += bytesTransferred; log(L"%d bytes read \r", totalBytes); cmd->size = bytesTransferred; completionCode = ERROR_SUCCESS; break; case VDC_Write: //log(L"VDC_Write - size: %d\r\n", cmd->size); while(bytesTransferred < cmd->size) bytesTransferred += fwrite(cmd->buffer + bytesTransferred, 1, cmd->size - bytesTransferred, backupfile); totalBytes += bytesTransferred; log(L"%d bytes written\r", totalBytes); completionCode = ERROR_SUCCESS; break; case VDC_Flush: //log(L"\nVDC_Flush %d\n", cmd->size); completionCode = ERROR_SUCCESS; break; case VDC_ClearError: log(L"\nVDC_ClearError\n"); //Debug::WriteLine("VDC_ClearError"); completionCode = ERROR_SUCCESS; break; default: // If command is unknown... completionCode = ERROR_NOT_SUPPORTED; } hr = virtualDevice->CompleteCommand(cmd, completionCode, bytesTransferred, 0); if (FAILED(hr)) { err(L"\nvirtualDevice->CompleteCommand failed: %s\n", (TCHAR*)errorMessage(hr)); return hr; } } log(L"\n"); if (hr != VD_E_CLOSE) { err(L"virtualDevice->GetCommand failed: "); if (hr == VD_E_TIMEOUT) err(L" timeout awaiting data.\n"); else if (hr == VD_E_ABORT) err(L" transfer was aborted.\n"); else err(L"%s\n", (TCHAR*)errorMessage(hr)); return hr; } return NOERROR; } int mountAndTransferVirtualDevice(TCHAR *command, HRESULT &hr, TCHAR virtualDeviceName[39], TCHAR *sql, FILE *backupFile) { // Create Device Set IClientVirtualDeviceSet2 * virtualDeviceSet; hr = CoCreateInstance( CLSID_MSSQL_ClientVirtualDeviceSet, NULL, CLSCTX_INPROC_SERVER, IID_IClientVirtualDeviceSet2, (void**)&virtualDeviceSet); if (FAILED(hr)) { err(L"Could not create VDI component. Check registration of SQLVDI.DLL. %s\n", (TCHAR*)errorMessage(hr)); return 2; } // Create Device VDConfig vdConfig = {0}; vdConfig.deviceCount = 1; hr = virtualDeviceSet->CreateEx(_serverInstanceName, virtualDeviceName, &vdConfig); if (!SUCCEEDED (hr)) { err(L"IClientVirtualDeviceSet2.CreateEx failed\r\n"); switch(hr) { case VD_E_INSTANCE_NAME: err(L"Didn't recognize the SQL Server instance name '"+ _bstr_t(_serverInstanceName) + L"'.\r\n"); break; case E_ACCESSDENIED: err(L"Access Denied: You must be logged in as a Windows administrator to create virtual devices.\r\n"); break; default: err(L"%s\n", (TCHAR*)errorMessage(hr)); break; } return 3; } // Invoke backup on separate thread because virtualDeviceSet->GetConfiguration will block until "BACKUP DATABASE..." DWORD threadId; HANDLE executeSqlThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&executeSql, sql, 0, &threadId); // Ready... hr = virtualDeviceSet->GetConfiguration(30000, &vdConfig); if (FAILED(hr)) { err(L"\n%s: virtualDeviceSet->GetConfiguration failed: ", command); if (hr == VD_E_TIMEOUT) err(L"Timed out waiting for backup to be initiated.\n"); else err(L"%s\n", (TCHAR*)errorMessage(hr)); return 3; } // Steady... IClientVirtualDevice *virtualDevice = NULL; hr = virtualDeviceSet->OpenDevice(virtualDeviceName, &virtualDevice); if (FAILED(hr)) { err(L"virtualDeviceSet->OpenDevice failed: 0x%x - "); if (hr == VD_E_TIMEOUT) err(L" timeout.\n"); else err(L" %s.\n", (TCHAR*)errorMessage(hr)); return 4; } // Go _setmode(_fileno(backupFile), _O_BINARY); //ensure \n's in STDOUT don't get tampered with hr = performTransfer(virtualDevice, backupFile); WaitForSingleObject(executeSqlThread, 5000); // Tidy up CloseHandle(executeSqlThread); virtualDeviceSet->Close(); virtualDevice->Release(); virtualDeviceSet->Release(); return 0; } // Entry point int _tmain(int argc, _TCHAR* argv[]) { if (argc < 3) { err(L"\n\ Action and database required.\n\ \n\ Usage: sqlpipe backup|restore <database> [options]\n\ Options:\n\ -q Quiet, don't print messages to STDERR\n\ -i \"instancename\"\n\ -f \"file\" Write/read file instead of STDOUT/STDIN\n"); return 1; } TCHAR* command = _wcslwr(argv[1]); TCHAR* databaseName = argv[2]; TCHAR* filePath = NULL; // Parse options for (int i = 0; i < argc; i++) { TCHAR* arg = _wcslwr(_wcsdup(argv[i])); if (wcscmp(arg, L"-q") == 0) _optionQuiet = true; if (wcscmp(arg, L"-i") == 0) _serverInstanceName = argv[i+1]; if (wcscmp(arg, L"-f") == 0) filePath = argv[i+1]; free(arg); } HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (FAILED(hr)) { // Switching from apartment to multi-threaded is OK if(hr != RPC_E_CHANGED_MODE) { err(L"CoInitializeEx failed: ", hr); return 1; } } // Generate virtualDeviceName TCHAR virtualDeviceName[39]; GUID guid; CoCreateGuid(&guid); StringFromGUID2(guid, virtualDeviceName, sizeof(virtualDeviceName)); TCHAR* sql; FILE* backupFile = NULL; if (wcscmp(command, L"backup") == 0) { sql = "BACKUP DATABASE [" + _bstr_t(databaseName) + "] TO VIRTUAL_DEVICE = '" + virtualDeviceName + "'"; if (filePath == NULL) backupFile = stdout; else { backupFile = _wfopen(filePath, L"w"); if (backupFile == NULL) { err(L"Error creating '%s': %s\n", filePath, _wcserror(errno)); return errno; } } } else if(wcscmp(command, L"restore") == 0) { hr = executeSql("CREATE DATABASE ["+ _bstr_t(databaseName) +"]"); if (FAILED(hr)) return hr; _RecordsetPtr fileList = executeRecordset("RESTORE FILELISTONLY FROM VIRTUAL_DEVICE = '" + _bstr_t(virtualDeviceName) + "'"); _bstr_t restoreSql("RESTORE DATABASE [" + _bstr_t(databaseName) + "] FROM VIRTUAL_DEVICE = '" + virtualDeviceName + "' WITH"); while(!fileList->EndOfFile) { _bstr_t fileType(fileList->Fields->GetItem("Type")->Value); _bstr_t logicalName = fileList->Fields->GetItem("LogicalName")->Value; restoreSql += " MOVE '" + logicalName + "' TO 'C:\\temp\\foo\\" + logicalName + ".xdf'"; fileList->MoveNext(); } err(restoreSql); hr = mountAndTransferVirtualDevice(command, hr, virtualDeviceName, sql, backupFile); sql = "RESTORE DATABASE [" + _bstr_t(databaseName) + "] FROM VIRTUAL_DEVICE = '" + virtualDeviceName + "' WITH REPLACE"; if (filePath == NULL) backupFile = stdin; else { backupFile = _wfopen(filePath, L"r"); if (backupFile == NULL) { err(L"Error opening '%s': %s\n", filePath, _wcserror(errno)); return errno; } } } else { err(L"Unsupported command '%s': only BACKUP or RESTORE are supported.\n", command); return 1; } hr = mountAndTransferVirtualDevice(command, hr, virtualDeviceName, sql, backupFile); //log(L"%s: Finished.\n", command); return hr; } <|endoftext|>
<commit_before>/* * Copyright (C) 2016 Patrizio Bekerle -- http://www.bekerle.com * * 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; version 2 of the License. * * 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. * */ #include "qtexteditsearchwidget.h" #include "ui_qtexteditsearchwidget.h" #include <QEvent> #include <QKeyEvent> #include <QDebug> QTextEditSearchWidget::QTextEditSearchWidget(QTextEdit *parent) : QWidget(parent), ui(new Ui::QTextEditSearchWidget) { ui->setupUi(this); _textEdit = parent; hide(); QObject::connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(deactivate())); QObject::connect(ui->searchLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(searchLineEditTextChanged(const QString &))); QObject::connect(ui->searchDownButton, SIGNAL(clicked()), this, SLOT(doSearchDown())); QObject::connect(ui->searchUpButton, SIGNAL(clicked()), this, SLOT(doSearchUp())); QObject::connect(ui->replaceToggleButton, SIGNAL(toggled(bool)), this, SLOT(setReplaceMode(bool))); QObject::connect(ui->replaceButton, SIGNAL(clicked()), this, SLOT(doReplace())); QObject::connect(ui->replaceAllButton, SIGNAL(clicked()), this, SLOT(doReplaceAll())); installEventFilter(this); ui->searchLineEdit->installEventFilter(this); ui->replaceLineEdit->installEventFilter(this); #ifdef Q_OS_MAC // set the spacing to 8 for OS X layout()->setSpacing(8); ui->buttonFrame->layout()->setSpacing(9); // set the margin to 0 for the top buttons for OS X QString buttonStyle = "QPushButton {margin: 0}"; ui->closeButton->setStyleSheet(buttonStyle); ui->searchDownButton->setStyleSheet(buttonStyle); ui->searchUpButton->setStyleSheet(buttonStyle); ui->replaceToggleButton->setStyleSheet(buttonStyle); ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle); #endif } QTextEditSearchWidget::~QTextEditSearchWidget() { delete ui; } void QTextEditSearchWidget::activate() { setReplaceMode(false); show(); ui->searchLineEdit->setFocus(); ui->searchLineEdit->selectAll(); doSearchDown(); } void QTextEditSearchWidget::activateReplace() { ui->searchLineEdit->setText(_textEdit->textCursor().selectedText()); ui->searchLineEdit->selectAll(); activate(); setReplaceMode(true); } void QTextEditSearchWidget::deactivate() { hide(); _textEdit->setFocus(); } void QTextEditSearchWidget::setReplaceMode(bool enabled) { ui->replaceToggleButton->setChecked(enabled); ui->replaceLabel->setVisible(enabled); ui->replaceLineEdit->setVisible(enabled); ui->modeLabel->setVisible(enabled); ui->buttonFrame->setVisible(enabled); ui->matchCaseSensitiveButton->setVisible(enabled); } bool QTextEditSearchWidget::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Escape) { deactivate(); return true; } else if ((keyEvent->modifiers().testFlag(Qt::ShiftModifier) && (keyEvent->key() == Qt::Key_Return)) || (keyEvent->key() == Qt::Key_Up)) { doSearchUp(); return true; } else if ((keyEvent->key() == Qt::Key_Return) || (keyEvent->key() == Qt::Key_Down)) { doSearchDown(); return true; } else if (keyEvent->key() == Qt::Key_F3) { doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier)); return true; } // if ((obj == ui->replaceLineEdit) && (keyEvent->key() == Qt::Key_Tab) // && ui->replaceToggleButton->isChecked()) { // ui->replaceLineEdit->setFocus(); // } return false; } return QWidget::eventFilter(obj, event); } void QTextEditSearchWidget::searchLineEditTextChanged(const QString &arg1) { Q_UNUSED(arg1); doSearchDown(); } void QTextEditSearchWidget::doSearchUp() { doSearch(false); } void QTextEditSearchWidget::doSearchDown() { doSearch(true); } bool QTextEditSearchWidget::doReplace(bool forAll) { if (_textEdit->isReadOnly()) { return false; } QTextCursor c = _textEdit->textCursor(); if (!forAll && c.selectedText().isEmpty()) { return false; } int searchMode = ui->modeComboBox->currentIndex(); if (searchMode == RegularExpressionMode) { QString text = c.selectedText(); text.replace(QRegExp(ui->searchLineEdit->text()), ui->replaceLineEdit->text()); c.insertText(text); } else { c.insertText(ui->replaceLineEdit->text()); } if (!forAll) { doSearch(true); } return true; } void QTextEditSearchWidget::doReplaceAll() { if (_textEdit->isReadOnly()) { return; } // start at the top _textEdit->moveCursor(QTextCursor::Start); // replace until everything to the bottom is replaced while (doSearch(true, false) && doReplace(true)) {} } /** * @brief Searches for text in the text edit */ bool QTextEditSearchWidget::doSearch(bool searchDown, bool allowRestartAtTop) { QString text = ui->searchLineEdit->text(); if (text == "") { ui->searchLineEdit->setStyleSheet("* { background: none; }"); return false; } int searchMode = ui->modeComboBox->currentIndex(); QFlags<QTextDocument::FindFlag> options = searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward; if (searchMode == WholeWordsMode) { options |= QTextDocument::FindWholeWords; } if (ui->matchCaseSensitiveButton->isChecked()) { options |= QTextDocument::FindCaseSensitively; } bool found; if (searchMode == RegularExpressionMode) { found = _textEdit->find(QRegExp(text), options); } else { found = _textEdit->find(text, options); } // start at the top (or bottom) if not found if (!found && allowRestartAtTop) { _textEdit->moveCursor( searchDown ? QTextCursor::Start : QTextCursor::End); found = _textEdit->find(text, options); } QRect rect = _textEdit->cursorRect(); QMargins margins = _textEdit->layout()->contentsMargins(); int searchWidgetHotArea = _textEdit->height() - this->height(); int marginBottom = (rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0; // move the search box a bit up if we would block the search result if (margins.bottom() != marginBottom) { margins.setBottom(marginBottom); _textEdit->layout()->setContentsMargins(margins); } // add a background color according if we found the text or not QString colorCode = found ? "#D5FAE2" : "#FAE9EB"; ui->searchLineEdit->setStyleSheet("* { background: " + colorCode + "; }"); return found; } <commit_msg>restore the last cursor position if text wasn't found any more<commit_after>/* * Copyright (C) 2016 Patrizio Bekerle -- http://www.bekerle.com * * 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; version 2 of the License. * * 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. * */ #include "qtexteditsearchwidget.h" #include "ui_qtexteditsearchwidget.h" #include <QEvent> #include <QKeyEvent> #include <QDebug> QTextEditSearchWidget::QTextEditSearchWidget(QTextEdit *parent) : QWidget(parent), ui(new Ui::QTextEditSearchWidget) { ui->setupUi(this); _textEdit = parent; hide(); QObject::connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(deactivate())); QObject::connect(ui->searchLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(searchLineEditTextChanged(const QString &))); QObject::connect(ui->searchDownButton, SIGNAL(clicked()), this, SLOT(doSearchDown())); QObject::connect(ui->searchUpButton, SIGNAL(clicked()), this, SLOT(doSearchUp())); QObject::connect(ui->replaceToggleButton, SIGNAL(toggled(bool)), this, SLOT(setReplaceMode(bool))); QObject::connect(ui->replaceButton, SIGNAL(clicked()), this, SLOT(doReplace())); QObject::connect(ui->replaceAllButton, SIGNAL(clicked()), this, SLOT(doReplaceAll())); installEventFilter(this); ui->searchLineEdit->installEventFilter(this); ui->replaceLineEdit->installEventFilter(this); #ifdef Q_OS_MAC // set the spacing to 8 for OS X layout()->setSpacing(8); ui->buttonFrame->layout()->setSpacing(9); // set the margin to 0 for the top buttons for OS X QString buttonStyle = "QPushButton {margin: 0}"; ui->closeButton->setStyleSheet(buttonStyle); ui->searchDownButton->setStyleSheet(buttonStyle); ui->searchUpButton->setStyleSheet(buttonStyle); ui->replaceToggleButton->setStyleSheet(buttonStyle); ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle); #endif } QTextEditSearchWidget::~QTextEditSearchWidget() { delete ui; } void QTextEditSearchWidget::activate() { setReplaceMode(false); show(); ui->searchLineEdit->setFocus(); ui->searchLineEdit->selectAll(); doSearchDown(); } void QTextEditSearchWidget::activateReplace() { ui->searchLineEdit->setText(_textEdit->textCursor().selectedText()); ui->searchLineEdit->selectAll(); activate(); setReplaceMode(true); } void QTextEditSearchWidget::deactivate() { hide(); _textEdit->setFocus(); } void QTextEditSearchWidget::setReplaceMode(bool enabled) { ui->replaceToggleButton->setChecked(enabled); ui->replaceLabel->setVisible(enabled); ui->replaceLineEdit->setVisible(enabled); ui->modeLabel->setVisible(enabled); ui->buttonFrame->setVisible(enabled); ui->matchCaseSensitiveButton->setVisible(enabled); } bool QTextEditSearchWidget::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Escape) { deactivate(); return true; } else if ((keyEvent->modifiers().testFlag(Qt::ShiftModifier) && (keyEvent->key() == Qt::Key_Return)) || (keyEvent->key() == Qt::Key_Up)) { doSearchUp(); return true; } else if ((keyEvent->key() == Qt::Key_Return) || (keyEvent->key() == Qt::Key_Down)) { doSearchDown(); return true; } else if (keyEvent->key() == Qt::Key_F3) { doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier)); return true; } // if ((obj == ui->replaceLineEdit) && (keyEvent->key() == Qt::Key_Tab) // && ui->replaceToggleButton->isChecked()) { // ui->replaceLineEdit->setFocus(); // } return false; } return QWidget::eventFilter(obj, event); } void QTextEditSearchWidget::searchLineEditTextChanged(const QString &arg1) { Q_UNUSED(arg1); doSearchDown(); } void QTextEditSearchWidget::doSearchUp() { doSearch(false); } void QTextEditSearchWidget::doSearchDown() { doSearch(true); } bool QTextEditSearchWidget::doReplace(bool forAll) { if (_textEdit->isReadOnly()) { return false; } QTextCursor c = _textEdit->textCursor(); if (!forAll && c.selectedText().isEmpty()) { return false; } int searchMode = ui->modeComboBox->currentIndex(); if (searchMode == RegularExpressionMode) { QString text = c.selectedText(); text.replace(QRegExp(ui->searchLineEdit->text()), ui->replaceLineEdit->text()); c.insertText(text); } else { c.insertText(ui->replaceLineEdit->text()); } if (!forAll) { int position = c.position(); if (!doSearch(true)) { // restore the last cursor position if text wasn't found any more c.setPosition(position); _textEdit->setTextCursor(c); } } return true; } void QTextEditSearchWidget::doReplaceAll() { if (_textEdit->isReadOnly()) { return; } // start at the top _textEdit->moveCursor(QTextCursor::Start); // replace until everything to the bottom is replaced while (doSearch(true, false) && doReplace(true)) {} } /** * @brief Searches for text in the text edit * @returns true if found */ bool QTextEditSearchWidget::doSearch(bool searchDown, bool allowRestartAtTop) { QString text = ui->searchLineEdit->text(); if (text == "") { ui->searchLineEdit->setStyleSheet("* { background: none; }"); return false; } int searchMode = ui->modeComboBox->currentIndex(); QFlags<QTextDocument::FindFlag> options = searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward; if (searchMode == WholeWordsMode) { options |= QTextDocument::FindWholeWords; } if (ui->matchCaseSensitiveButton->isChecked()) { options |= QTextDocument::FindCaseSensitively; } bool found; if (searchMode == RegularExpressionMode) { found = _textEdit->find(QRegExp(text), options); } else { found = _textEdit->find(text, options); } // start at the top (or bottom) if not found if (!found && allowRestartAtTop) { _textEdit->moveCursor( searchDown ? QTextCursor::Start : QTextCursor::End); found = _textEdit->find(text, options); } QRect rect = _textEdit->cursorRect(); QMargins margins = _textEdit->layout()->contentsMargins(); int searchWidgetHotArea = _textEdit->height() - this->height(); int marginBottom = (rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0; // move the search box a bit up if we would block the search result if (margins.bottom() != marginBottom) { margins.setBottom(marginBottom); _textEdit->layout()->setContentsMargins(margins); } // add a background color according if we found the text or not QString colorCode = found ? "#D5FAE2" : "#FAE9EB"; ui->searchLineEdit->setStyleSheet("* { background: " + colorCode + "; }"); return found; } <|endoftext|>
<commit_before>/** \file add_synonyms.cc * \brief Generic version for augmenting title data with synonyms found in the authority data * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* We offer a list of tags and subfields where the primary data resides along with a list of tags and subfields where the synonym data is found and a list of unused fields in the title data where the synonyms can be stored */ #include <iostream> #include <map> #include <vector> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MarcReader.h" #include "MarcRecord.h" #include "MarcWriter.h" #include "MediaTypeUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" static unsigned modified_count(0); static unsigned record_count(0); void Usage() { std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n"; std::exit(EXIT_FAILURE); } std::string GetTag(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(0, 3); } std::string GetSubfieldCodes(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(3); } bool FilterPasses(const MarcRecord &record, const std::map<std::string, std::pair<std::string, std::string>> &filter_specs, const std::string &field_spec) { auto filter_spec(filter_specs.find(field_spec)); if (filter_spec == filter_specs.cend()) return true; auto rule(filter_spec->second); // We have field_spec in key and rule to match in value std::string subfield_codes(GetSubfieldCodes(rule.first)); if (subfield_codes.length() != 1) Error("Invalid subfield specification " + subfield_codes + " for filter"); std::string subfield_value; if ((subfield_value = record.extractFirstSubfield(GetTag(rule.first), subfield_codes.c_str()[0])).empty()) return false; return subfield_value == rule.second; } void ExtractSynonyms(MarcReader * const authority_reader, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &synonym_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> * const synonym_maps, const std::map<std::string, std::pair<std::string, std::string>> &filter_spec) { while (const MarcRecord record = authority_reader->read()) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator synonym; unsigned int i(0); for (primary = primary_tags_and_subfield_codes.begin(), synonym = synonym_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++synonym, ++i) { // Fill maps with synonyms std::vector<std::string> primary_values; std::vector<std::string> synonym_values; if (FilterPasses(record, filter_spec, *primary) and record.extractSubfields(GetTag(*primary), GetSubfieldCodes(*primary), &primary_values) and record.extractSubfields(GetTag(*synonym), GetSubfieldCodes(*synonym), &synonym_values)) (*synonym_maps)[i].emplace(StringUtil::Join(primary_values, ','), StringUtil::Join(synonym_values, ',')); } } } inline std::string GetMapValueOrEmptyString(const std::map<std::string, std::string> &map, const std::string &searchterm) { auto value(map.find(searchterm)); return (value != map.cend()) ? value->second : ""; } void ProcessRecord(MarcRecord * const record, const std::vector<std::map<std::string, std::string>> &synonym_maps, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator output; unsigned int i(0); if (primary_tags_and_subfield_codes.size() == output_tags_and_subfield_codes.size()) { for (primary = primary_tags_and_subfield_codes.begin(), output = output_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++output, ++i) { std::vector<std::string> primary_values; std::set<std::string> synonym_values; std::vector<size_t> field_indices; if (record->getFieldIndices(GetTag(*primary), &field_indices) != MarcRecord::FIELD_NOT_FOUND) { for (auto field_index : field_indices) { primary_values.clear(); if (record->getSubfields(field_index).extractSubfields(GetSubfieldCodes(*primary), &primary_values)) { std::string searchterm = StringUtil::Join(primary_values, ','); // First case: Look up synonyms only in one category if (i < synonym_maps.size()) { const auto &synonym_map(synonym_maps[i]); const auto &synonym(GetMapValueOrEmptyString(synonym_map, searchterm)); if (not synonym.empty()) synonym_values.insert(synonym); } // Second case: Look up synonyms in all categories else { for (auto &synonym_map : synonym_maps) { const auto &synonym(GetMapValueOrEmptyString(synonym_map, searchterm)); if (not synonym.empty()) synonym_values.insert(synonym); } } } } if (synonym_values.empty()) continue; const std::string synonyms(StringUtil::Join(synonym_values, ',')); // Insert synonyms // Abort if field is already populated std::string tag(GetTag(*output)); if (record->getFieldIndex(tag) != MarcRecord::FIELD_NOT_FOUND) Error("Field with tag " + tag + " is not empty for PPN " + record->getControlNumber() + '\n'); std::string subfield_spec = GetSubfieldCodes(*output); if (unlikely(subfield_spec.size() != 1)) Error("We currently only support a single subfield and thus specifying " + subfield_spec + " as output subfield is not valid\n"); Subfields subfields(' ', ' '); // <- indicators must be set explicitly although empty subfields.addSubfield(subfield_spec.at(0), synonyms); if (not(record->insertField(tag, subfields.toString()))) Warning("Could not insert field " + tag + " for PPN " + record->getControlNumber() + '\n'); ++modified_count; } } } } void InsertSynonyms(MarcReader * const marc_reader, MarcWriter * const marc_writer, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> &synonym_maps) { while (MarcRecord record = marc_reader->read()) { ProcessRecord(&record, synonym_maps, primary_tags_and_subfield_codes, output_tags_and_subfield_codes); marc_writer->write(record); ++record_count; } std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n"; } int ParseSpec(std::string spec_str, std::set<std::string> * const field_specs, std::map<std::string, std::pair<std::string, std::string>> * filter_specs = nullptr) { std::set<std::string> raw_field_specs; if (unlikely(StringUtil::Split(spec_str, ':', &raw_field_specs) < 1)) { Error("Need at least one field"); return -1; } if (filter_specs == nullptr) { *field_specs = raw_field_specs; return 0; } // Iterate over all Field-specs and extract possible filters static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory("(\\d{1,3}[a-z]+)\\[(\\d{1,3}[a-z])=(.*)\\]")); for (auto field_spec : raw_field_specs) { if (matcher->matched(field_spec)) { filter_specs->emplace((*matcher)[1], std::make_pair((*matcher)[2], (*matcher)[3])); auto bracket = field_spec.find("["); field_spec = (bracket != std::string::npos) ? field_spec.erase(bracket, field_spec.length()) : field_spec; } field_specs->insert(field_spec); } return 0; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 4) Usage(); const std::string marc_input_filename(argv[1]); const std::string authority_data_marc_input_filename(argv[2]); const std::string marc_output_filename(argv[3]); if (unlikely(marc_input_filename == marc_output_filename)) Error("Title data input file name equals output file name!"); if (unlikely(authority_data_marc_input_filename == marc_output_filename)) Error("Authority data input file name equals output file name!"); std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(marc_input_filename, MarcReader::BINARY)); std::unique_ptr<MarcReader> authority_reader(MarcReader::Factory(authority_data_marc_input_filename, MarcReader::BINARY)); std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(marc_output_filename, MarcWriter::BINARY)); try { // Determine possible mappings // Values in square brackets specify a positive criterion for values to be taken into account const std::string AUTHORITY_DATA_PRIMARY_SPEC("100abcd[079v=piz]:110abcd:111abcd:130abcd:150abcd:151abcd"); const std::string AUTHORITY_DATA_SYNONYM_SPEC("400abcd:410abcd:411abcd:430abcd:450abcd:451abcd"); const std::string TITLE_DATA_PRIMARY_SPEC("600abcd:610abcd:611abcd:630abcd:650abcd:651abcd:689abcd"); const std::string TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS("180a:181a:182a:183a:184a:185a:186a"); // Determine fields to handle std::set<std::string> primary_tags_and_subfield_codes; std::set<std::string> synonym_tags_and_subfield_codes; std::set<std::string> input_tags_and_subfield_codes; std::set<std::string> output_tags_and_subfield_codes; std::map<std::string, std::pair<std::string, std::string>> filter_specs; if (unlikely(ParseSpec(AUTHORITY_DATA_PRIMARY_SPEC, &primary_tags_and_subfield_codes, &filter_specs) < 0)) Error("Could not properly parse " + AUTHORITY_DATA_PRIMARY_SPEC); if (unlikely(StringUtil::Split(AUTHORITY_DATA_SYNONYM_SPEC, ":", &synonym_tags_and_subfield_codes) == 0)) Error("Need at least one synonym field"); if (unlikely(StringUtil::Split(TITLE_DATA_PRIMARY_SPEC, ":", &input_tags_and_subfield_codes) == 0)) Error("Need at least one input field"); if (unlikely(StringUtil::Split(TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS, ":", &output_tags_and_subfield_codes) == 0)) Error("Need at least one output field"); unsigned num_of_authority_entries(primary_tags_and_subfield_codes.size()); if (synonym_tags_and_subfield_codes.size() != num_of_authority_entries) Error("Number of authority primary specs must match number of synonym specs"); if (input_tags_and_subfield_codes.size() != output_tags_and_subfield_codes.size()) Error("Number of fields title entry specs must match number of output specs"); std::vector<std::map<std::string, std::string>> synonym_maps(num_of_authority_entries, std::map<std::string, std::string>()); // Extract the synonyms from authority data ExtractSynonyms(authority_reader.get(), primary_tags_and_subfield_codes, synonym_tags_and_subfield_codes, &synonym_maps, filter_specs); // Iterate over the title data InsertSynonyms(marc_reader.get(), marc_writer.get(), input_tags_and_subfield_codes, output_tags_and_subfield_codes, synonym_maps); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <commit_msg>Required changes<commit_after>/** \file add_synonyms.cc * \brief Generic version for augmenting title data with synonyms found in the authority data * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* We offer a list of tags and subfields where the primary data resides along with a list of tags and subfields where the synonym data is found and a list of unused fields in the title data where the synonyms can be stored */ #include <iostream> #include <map> #include <vector> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MarcReader.h" #include "MarcRecord.h" #include "MarcWriter.h" #include "MediaTypeUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" static unsigned modified_count(0); static unsigned record_count(0); void Usage() { std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n"; std::exit(EXIT_FAILURE); } std::string GetTag(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(0, 3); } std::string GetSubfieldCodes(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(3); } bool FilterPasses(const MarcRecord &record, const std::map<std::string, std::pair<std::string, std::string>> &filter_specs, const std::string &field_spec) { auto filter_spec(filter_specs.find(field_spec)); if (filter_spec == filter_specs.cend()) return true; auto rule(filter_spec->second); // We have field_spec in key and rule to match in value std::string subfield_codes(GetSubfieldCodes(rule.first)); if (subfield_codes.length() != 1) Error("Invalid subfield specification " + subfield_codes + " for filter"); std::string subfield_value; if ((subfield_value = record.extractFirstSubfield(GetTag(rule.first), subfield_codes.c_str()[0])).empty()) return false; return subfield_value == rule.second; } void ExtractSynonyms(MarcReader * const authority_reader, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &synonym_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> * const synonym_maps, const std::map<std::string, std::pair<std::string, std::string>> &filter_spec) { while (const MarcRecord record = authority_reader->read()) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator synonym; unsigned int i(0); for (primary = primary_tags_and_subfield_codes.begin(), synonym = synonym_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++synonym, ++i) { // Fill maps with synonyms std::vector<std::string> primary_values; std::vector<std::string> synonym_values; if (FilterPasses(record, filter_spec, *primary) and record.extractSubfields(GetTag(*primary), GetSubfieldCodes(*primary), &primary_values) and record.extractSubfields(GetTag(*synonym), GetSubfieldCodes(*synonym), &synonym_values)) (*synonym_maps)[i].emplace(StringUtil::Join(primary_values, ','), StringUtil::Join(synonym_values, ',')); } } } inline std::string GetMapValueOrEmptyString(const std::map<std::string, std::string> &map, const std::string &searchterm) { auto value(map.find(searchterm)); return (value != map.cend()) ? value->second : ""; } void ProcessRecord(MarcRecord * const record, const std::vector<std::map<std::string, std::string>> &synonym_maps, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator output; unsigned int i(0); if (primary_tags_and_subfield_codes.size() == output_tags_and_subfield_codes.size()) { for (primary = primary_tags_and_subfield_codes.begin(), output = output_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++output, ++i) { std::vector<std::string> primary_values; std::set<std::string> synonym_values; std::vector<size_t> field_indices; if (record->getFieldIndices(GetTag(*primary), &field_indices) != MarcRecord::FIELD_NOT_FOUND) { for (auto field_index : field_indices) { primary_values.clear(); if (record->getSubfields(field_index).extractSubfields(GetSubfieldCodes(*primary), &primary_values)) { std::string searchterm = StringUtil::Join(primary_values, ','); // First case: Look up synonyms only in one category if (i < synonym_maps.size()) { const auto &synonym_map(synonym_maps[i]); const auto &synonym(GetMapValueOrEmptyString(synonym_map, searchterm)); if (not synonym.empty()) synonym_values.insert(synonym); } // Second case: Look up synonyms in all categories else { for (auto &synonym_map : synonym_maps) { const auto &synonym(GetMapValueOrEmptyString(synonym_map, searchterm)); if (not synonym.empty()) synonym_values.insert(synonym); } } } } if (synonym_values.empty()) continue; const std::string synonyms(StringUtil::Join(synonym_values, ',')); // Insert synonyms // Abort if field is already populated std::string tag(GetTag(*output)); if (record->getFieldIndex(tag) != MarcRecord::FIELD_NOT_FOUND) Error("Field with tag " + tag + " is not empty for PPN " + record->getControlNumber() + '\n'); std::string subfield_spec = GetSubfieldCodes(*output); if (unlikely(subfield_spec.size() != 1)) Error("We currently only support a single subfield and thus specifying " + subfield_spec + " as output subfield is not valid\n"); Subfields subfields(' ', ' '); // <- indicators must be set explicitly although empty subfields.addSubfield(subfield_spec.at(0), synonyms); if (not(record->insertField(tag, subfields.toString()))) Warning("Could not insert field " + tag + " for PPN " + record->getControlNumber() + '\n'); ++modified_count; } } } } void InsertSynonyms(MarcReader * const marc_reader, MarcWriter * const marc_writer, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> &synonym_maps) { while (MarcRecord record = marc_reader->read()) { ProcessRecord(&record, synonym_maps, primary_tags_and_subfield_codes, output_tags_and_subfield_codes); marc_writer->write(record); ++record_count; } std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n"; } bool ParseSpec(std::string spec_str, std::set<std::string> * const field_specs, std::map<std::string, std::pair<std::string, std::string>> * filter_specs = nullptr) { std::set<std::string> raw_field_specs; if (unlikely(StringUtil::Split(spec_str, ':', &raw_field_specs) < 1)) { Error("Need at least one field"); return false; } if (filter_specs == nullptr) { *field_specs = raw_field_specs; return true; } // Iterate over all Field-specs and extract possible filters static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory("(\\d{1,3}[a-z]+)\\[(\\d{1,3}[a-z])=(.*)\\]")); for (auto field_spec : raw_field_specs) { if (matcher->matched(field_spec)) { filter_specs->emplace((*matcher)[1], std::make_pair((*matcher)[2], (*matcher)[3])); auto bracket = field_spec.find("["); field_spec = (bracket != std::string::npos) ? field_spec.erase(bracket, field_spec.length()) : field_spec; } field_specs->insert(field_spec); } return true; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 4) Usage(); const std::string marc_input_filename(argv[1]); const std::string authority_data_marc_input_filename(argv[2]); const std::string marc_output_filename(argv[3]); if (unlikely(marc_input_filename == marc_output_filename)) Error("Title data input file name equals output file name!"); if (unlikely(authority_data_marc_input_filename == marc_output_filename)) Error("Authority data input file name equals output file name!"); std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(marc_input_filename, MarcReader::BINARY)); std::unique_ptr<MarcReader> authority_reader(MarcReader::Factory(authority_data_marc_input_filename, MarcReader::BINARY)); std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(marc_output_filename, MarcWriter::BINARY)); try { // Determine possible mappings // Values in square brackets specify a positive criterion for values to be taken into account const std::string AUTHORITY_DATA_PRIMARY_SPEC("100abcd[079v=piz]:110abcd:111abcd:130abcd:150abcd:151abcd"); const std::string AUTHORITY_DATA_SYNONYM_SPEC("400abcd:410abcd:411abcd:430abcd:450abcd:451abcd"); const std::string TITLE_DATA_PRIMARY_SPEC("600abcd:610abcd:611abcd:630abcd:650abcd:651abcd:689abcd"); const std::string TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS("180a:181a:182a:183a:184a:185a:186a"); // Determine fields to handle std::set<std::string> primary_tags_and_subfield_codes; std::set<std::string> synonym_tags_and_subfield_codes; std::set<std::string> input_tags_and_subfield_codes; std::set<std::string> output_tags_and_subfield_codes; std::map<std::string, std::pair<std::string, std::string>> filter_specs; if (unlikely(ParseSpec(AUTHORITY_DATA_PRIMARY_SPEC, &primary_tags_and_subfield_codes, &filter_specs) < 0)) Error("Could not properly parse " + AUTHORITY_DATA_PRIMARY_SPEC); if (unlikely(StringUtil::Split(AUTHORITY_DATA_SYNONYM_SPEC, ":", &synonym_tags_and_subfield_codes) == 0)) Error("Need at least one synonym field"); if (unlikely(StringUtil::Split(TITLE_DATA_PRIMARY_SPEC, ":", &input_tags_and_subfield_codes) == 0)) Error("Need at least one input field"); if (unlikely(StringUtil::Split(TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS, ":", &output_tags_and_subfield_codes) == 0)) Error("Need at least one output field"); unsigned num_of_authority_entries(primary_tags_and_subfield_codes.size()); if (synonym_tags_and_subfield_codes.size() != num_of_authority_entries) Error("Number of authority primary specs must match number of synonym specs"); if (input_tags_and_subfield_codes.size() != output_tags_and_subfield_codes.size()) Error("Number of fields title entry specs must match number of output specs"); std::vector<std::map<std::string, std::string>> synonym_maps(num_of_authority_entries, std::map<std::string, std::string>()); // Extract the synonyms from authority data ExtractSynonyms(authority_reader.get(), primary_tags_and_subfield_codes, synonym_tags_and_subfield_codes, &synonym_maps, filter_specs); // Iterate over the title data InsertSynonyms(marc_reader.get(), marc_writer.get(), input_tags_and_subfield_codes, output_tags_and_subfield_codes, synonym_maps); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>#include <chrono> #include <ctime> #include <fstream> #include <iostream> #include <map> #include <queue> #include <ratio> #include <string> #include <stdlib.h> #include <time.h> #include<sys/time.h> #include "omp.h" #include <vector> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/classification.hpp> #include "boost/lexical_cast.hpp" using namespace boost::algorithm; #include "pass_runner.h" #define NUM_THREADS 8 // default number of threads #define MAX_NUM_PER_THREAD 1 #define RERUN_COUNT 10 #define MAX_PASS_LENGTH 10 #if(0) #ifdef DEBUG #ifndef TIME #define TIME #endif #endif #endif using namespace std; using namespace std::chrono; /*------- GLOBAL VARIABES --------*/ // vector with permutations of passorder vector<string> passOrder; char *binaryName; char *binaryArgs; char *input_combination_file; string dir_name; struct timeval start, end_time; #define _SYSTEM_CALL( CMD ) ( { \ int err = ( system( CMD.c_str() ) ); \ if ( err < 0 ) { \ fprintf(stderr, #CMD, " failed."); \ abort(); \ } \ err; \ }) \ inline COMMAND::COMMAND(string pass_order, long double threadId) { // opt -pass1 -pass2 ./bcfile -o temp.out.threadId >> /dev/null // combination_file_name/temp.out.input_combination_filename string temp_name = dir_name + string("./temp.out") + to_string(threadId); //+ input_combination_file; opt = string("opt ") + pass_order + " ./" + binaryName + " -o "+ temp_name + "" + " >> /dev/null"; // Command to execute the file. lli = string("lli ") + temp_name + " " + binaryArgs; } struct passTime { string pass_name; double time; }; class PassTimeComparator { public: bool operator()(passTime& n1, passTime& n2) { if (n1.time > n2.time) return true; else return false; } }; void cleanUpTheMess() { string rm_command = string("rm -rf ") + dir_name; #ifdef DEBUG cout << "Cleaning temporary files.." << endl; cout << "Running Command: " << rm_command << endl; #endif _SYSTEM_CALL ( rm_command) ; } vector<string>& getOptimizationPasses() { vector<string> *optimizationPasses = new vector<string>(); for(std::map<int, std::string>::iterator it = A::PASS_MAP.begin(), ie = A::PASS_MAP.end(); ie != it; ++it) { optimizationPasses->push_back(it->second); } return *optimizationPasses; } void runOptimizationPasses() { //map<string, double> optExecMap; std::map<string, long> after_pass_time; vector<string> &optimizationPasses = getOptimizationPasses(); clock_t t1,t2; std::chrono::time_point<std::chrono::system_clock> start, end; float diff; long double tid; string pass_name; int pass_length = 0; string curr_pass_order = string(""); while(pass_length < MAX_PASS_LENGTH) { priority_queue< passTime, vector< passTime >, PassTimeComparator> curr_pq; #pragma omp parallel for private(pass_name, tid) for( int i = 0; i < optimizationPasses.size() ; ++i ) { pass_name = optimizationPasses[i]; string temp_pass_order = curr_pass_order + string(" ") + pass_name; std::cout << pass_name << std::endl; tid = omp_get_thread_num(); // apply pass here COMMAND Cmd(temp_pass_order, tid); _SYSTEM_CALL(Cmd.opt); // run RERUN_COUNT number of times to get the time // START TIMER HERE start = std::chrono::system_clock::now(); for(int j=0; j < RERUN_COUNT; j++) { _SYSTEM_CALL(Cmd.lli); } end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; double time_taken_by_current_pass = elapsed_seconds.count(); // STOP TIMER HERE #ifdef DEBUG cout << "Running Command: " << Cmd.opt << "time taken " << time_taken_by_current_pass << endl; #endif // store the time taken by current pass passTime curr = {pass_name, time_taken_by_current_pass}; curr_pq.push(curr); } passTime pt = curr_pq.top(); curr_pass_order = curr_pass_order + string(" ") + pt.pass_name; cout << "Appending " << pt.pass_name << " | Current Pass Order " << curr_pass_order << endl; pass_length++; } cleanUpTheMess(); } int main(int argc, char** argv) { int numThreads = NUM_THREADS; if(argc > 1) { binaryName = argv[1]; binaryArgs = argv[2]; numThreads = atoi(argv[3]); std::cout << binaryName << " " << binaryArgs << " " << numThreads << " " << endl;//<< input_combination_file << endl; } else { std::cout << "Usage: pass_runner <Binary Name> <NumThreads(optional)>" << std::endl; abort(); } // set openmp number of threads omp_set_num_threads(numThreads); //dir_name = string(input_combination_file) + "dir"; //string create_dir_cmd = string("mkdir ") + dir_name; //_SYSTEM_CALL(create_dir_cmd ); runOptimizationPasses(); return EXIT_SUCCESS; } <commit_msg>adding markov<commit_after>#include <chrono> #include <ctime> #include <fstream> #include <iostream> #include <map> #include <queue> #include <ratio> #include <string> #include <stdlib.h> #include <time.h> #include<sys/time.h> #include "omp.h" #include <vector> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/classification.hpp> #include "boost/lexical_cast.hpp" using namespace boost::algorithm; #include "pass_runner.h" #define NUM_THREADS 8 // default number of threads #define MAX_NUM_PER_THREAD 1 #define RERUN_COUNT 10 #define MAX_PASS_LENGTH 10 #if(0) #ifdef DEBUG #ifndef TIME #define TIME #endif #endif #endif using namespace std; using namespace std::chrono; /*------- GLOBAL VARIABES --------*/ // vector with permutations of passorder vector<string> passOrder; char *binaryName; char *binaryArgs; char *input_combination_file; string dir_name; struct timeval start, end_time; #define _SYSTEM_CALL( CMD ) ( { \ int err = ( system( CMD.c_str() ) ); \ if ( err < 0 ) { \ fprintf(stderr, #CMD, " failed."); \ abort(); \ } \ err; \ }) \ inline COMMAND::COMMAND(string pass_order, long double threadId) { // opt -pass1 -pass2 ./bcfile -o temp.out.threadId >> /dev/null // combination_file_name/temp.out.input_combination_filename string temp_name = dir_name + string("./temp.out") + to_string(threadId); //+ input_combination_file; opt = string("opt ") + pass_order + " ./" + binaryName + " -o "+ temp_name + "" + " >> /dev/null"; // Command to execute the file. lli = string("lli ") + temp_name + " " + binaryArgs; } struct passTime { string pass_name; double time; }; class PassTimeComparator { public: bool operator()(passTime& n1, passTime& n2) { if (n1.time > n2.time) return true; else return false; } }; void cleanUpTheMess() { string rm_command = string("rm -rf ") + dir_name; #ifdef DEBUG cout << "Cleaning temporary files.." << endl; cout << "Running Command: " << rm_command << endl; #endif _SYSTEM_CALL ( rm_command) ; } vector<string>& getOptimizationPasses() { vector<string> *optimizationPasses = new vector<string>(); for(std::map<int, std::string>::iterator it = A::PASS_MAP.begin(), ie = A::PASS_MAP.end(); ie != it; ++it) { optimizationPasses->push_back(it->second); } return *optimizationPasses; } void runOptimizationPasses() { //map<string, double> optExecMap; std::map<string, long> after_pass_time; vector<string> &optimizationPasses = getOptimizationPasses(); clock_t t1,t2; std::chrono::time_point<std::chrono::system_clock> start, end; float diff; long double tid; string pass_name; int pass_length = 0; string curr_pass_order = string(""); while(pass_length < MAX_PASS_LENGTH) { priority_queue< passTime, vector< passTime >, PassTimeComparator> curr_pq; #pragma omp parallel for private(pass_name, tid) for( int i = 0; i < optimizationPasses.size() ; ++i ) { pass_name = optimizationPasses[i]; string temp_pass_order = curr_pass_order + string(" ") + pass_name; std::cout << pass_name << std::endl; tid = omp_get_thread_num(); // apply pass here COMMAND Cmd(temp_pass_order, tid); _SYSTEM_CALL(Cmd.opt); // run RERUN_COUNT number of times to get the time // START TIMER HERE start = std::chrono::system_clock::now(); for(int j=0; j < RERUN_COUNT; j++) { _SYSTEM_CALL(Cmd.lli); } end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; double time_taken_by_current_pass = elapsed_seconds.count(); // STOP TIMER HERE #ifdef DEBUG cout << "Running Command: " << Cmd.opt << "time taken " << time_taken_by_current_pass << endl; #endif // store the time taken by current pass passTime curr = {pass_name, time_taken_by_current_pass}; curr_pq.push(curr); } passTime pt = curr_pq.top(); curr_pass_order = curr_pass_order + string(" ") + pt.pass_name; cout << "Appending " << pt.pass_name << " | Current Pass Order " << curr_pass_order << " PassTime " << pt.time << endl; pass_length++; } cleanUpTheMess(); } int main(int argc, char** argv) { int numThreads = NUM_THREADS; if(argc > 1) { binaryName = argv[1]; binaryArgs = argv[2]; numThreads = atoi(argv[3]); std::cout << binaryName << " " << binaryArgs << " " << numThreads << " " << endl;//<< input_combination_file << endl; } else { std::cout << "Usage: pass_runner <Binary Name> <NumThreads(optional)>" << std::endl; abort(); } // set openmp number of threads omp_set_num_threads(numThreads); //dir_name = string(input_combination_file) + "dir"; //string create_dir_cmd = string("mkdir ") + dir_name; //_SYSTEM_CALL(create_dir_cmd ); runOptimizationPasses(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (C) 2012 David Edmundson <kde@davidedmundson.co.uk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact.h" #include <TelepathyQt/ContactManager> #include <TelepathyQt/Connection> #include <TelepathyQt/ContactCapabilities> #include <TelepathyQt/AvatarData> #include <QBitmap> #include <QPixmap> #include <QPixmapCache> #include <KIconLoader> #include "capabilities-hack-private.h" KTp::Contact::Contact(Tp::ContactManager *manager, const Tp::ReferencedHandles &handle, const Tp::Features &requestedFeatures, const QVariantMap &attributes) : Tp::Contact(manager, handle, requestedFeatures, attributes) { connect(manager->connection().data(), SIGNAL(destroyed()), SIGNAL(invalidated())); connect(manager->connection().data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), SIGNAL(invalidated())); } KTp::Presence KTp::Contact::presence() const { return KTp::Presence(Tp::Contact::presence()); } bool KTp::Contact::audioCallCapability() const { if (! manager()->connection()) { return false; } Tp::ConnectionPtr connection = manager()->connection(); if (connection) { bool contactCanStreamAudio = CapabilitiesHackPrivate::audioCalls( capabilities(), connection->cmName()); bool selfCanStreamAudio = CapabilitiesHackPrivate::audioCalls( connection->selfContact()->capabilities(), connection->cmName()); return contactCanStreamAudio && selfCanStreamAudio; } return false; } bool KTp::Contact::videoCallCapability() const { if (! manager()->connection()) { return false; } Tp::ConnectionPtr connection = manager()->connection(); if (connection) { bool contactCanStreamVideo = CapabilitiesHackPrivate::videoCalls( capabilities(), connection->cmName()); bool selfCanStreamVideo = CapabilitiesHackPrivate::videoCalls( connection->selfContact()->capabilities(), connection->cmName()); return contactCanStreamVideo && selfCanStreamVideo; } return false; } bool KTp::Contact::fileTransferCapability() const { if (! manager()->connection()) { return false; } if (manager()->connection()) { bool contactCanHandleFiles = capabilities().fileTransfers(); bool selfCanHandleFiles = manager()->connection()->selfContact()->capabilities().fileTransfers(); return contactCanHandleFiles && selfCanHandleFiles; } return false; } QStringList KTp::Contact::clientTypes() const { /* Temporary workaround for upstream bug https://bugs.freedesktop.org/show_bug.cgi?id=55883) * Close https://bugs.kde.org/show_bug.cgi?id=308217 when fixed upstream */ if (Tp::Contact::presence().type() == Tp::ConnectionPresenceTypeOffline) { return QStringList(); } return Tp::Contact::clientTypes(); } QPixmap KTp::Contact::avatarPixmap() { QPixmap avatar; QString file = avatarData().fileName; if (file.isEmpty()) { avatar = KIconLoader::global()->loadIcon(QLatin1String("im-user"), KIconLoader::NoGroup, 96); } else { avatar.load(file); } if (presence().type() == Tp::ConnectionPresenceTypeOffline) { if (!QPixmapCache::find(keyCache(),avatar)){ avatarToGray(avatar); QPixmapCache::insert(keyCache(), avatar); } } return avatar; } void KTp::Contact::avatarToGray(QPixmap &avatar) { QImage image = avatar.toImage(); QBitmap alphaMask = avatar.mask(); for (int i = 0; i < image.width(); ++i) { for (int j = 0; j < image.height(); ++j) { int colour = qGray(image.pixel(i, j)); image.setPixel(i, j, qRgb(colour, colour, colour)); } } avatar = avatar.fromImage(image); avatar.setMask(alphaMask); } QString KTp::Contact::keyCache() const { return avatarToken()+QLatin1String("-offline"); } <commit_msg>fixes bad quality gray avatars BUG: 316109 REVIEW: 109279<commit_after>/* * Copyright (C) 2012 David Edmundson <kde@davidedmundson.co.uk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact.h" #include <TelepathyQt/ContactManager> #include <TelepathyQt/Connection> #include <TelepathyQt/ContactCapabilities> #include <TelepathyQt/AvatarData> #include <QBitmap> #include <QPixmap> #include <QPixmapCache> #include <KIconLoader> #include "capabilities-hack-private.h" KTp::Contact::Contact(Tp::ContactManager *manager, const Tp::ReferencedHandles &handle, const Tp::Features &requestedFeatures, const QVariantMap &attributes) : Tp::Contact(manager, handle, requestedFeatures, attributes) { connect(manager->connection().data(), SIGNAL(destroyed()), SIGNAL(invalidated())); connect(manager->connection().data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), SIGNAL(invalidated())); } KTp::Presence KTp::Contact::presence() const { return KTp::Presence(Tp::Contact::presence()); } bool KTp::Contact::audioCallCapability() const { if (! manager()->connection()) { return false; } Tp::ConnectionPtr connection = manager()->connection(); if (connection) { bool contactCanStreamAudio = CapabilitiesHackPrivate::audioCalls( capabilities(), connection->cmName()); bool selfCanStreamAudio = CapabilitiesHackPrivate::audioCalls( connection->selfContact()->capabilities(), connection->cmName()); return contactCanStreamAudio && selfCanStreamAudio; } return false; } bool KTp::Contact::videoCallCapability() const { if (! manager()->connection()) { return false; } Tp::ConnectionPtr connection = manager()->connection(); if (connection) { bool contactCanStreamVideo = CapabilitiesHackPrivate::videoCalls( capabilities(), connection->cmName()); bool selfCanStreamVideo = CapabilitiesHackPrivate::videoCalls( connection->selfContact()->capabilities(), connection->cmName()); return contactCanStreamVideo && selfCanStreamVideo; } return false; } bool KTp::Contact::fileTransferCapability() const { if (! manager()->connection()) { return false; } if (manager()->connection()) { bool contactCanHandleFiles = capabilities().fileTransfers(); bool selfCanHandleFiles = manager()->connection()->selfContact()->capabilities().fileTransfers(); return contactCanHandleFiles && selfCanHandleFiles; } return false; } QStringList KTp::Contact::clientTypes() const { /* Temporary workaround for upstream bug https://bugs.freedesktop.org/show_bug.cgi?id=55883) * Close https://bugs.kde.org/show_bug.cgi?id=308217 when fixed upstream */ if (Tp::Contact::presence().type() == Tp::ConnectionPresenceTypeOffline) { return QStringList(); } return Tp::Contact::clientTypes(); } QPixmap KTp::Contact::avatarPixmap() { QPixmap avatar; QString file = avatarData().fileName; if (file.isEmpty()) { avatar = KIconLoader::global()->loadIcon(QLatin1String("im-user"), KIconLoader::NoGroup, 96); } else { avatar.load(file); } if (presence().type() == Tp::ConnectionPresenceTypeOffline) { if (!QPixmapCache::find(keyCache(),avatar)){ avatarToGray(avatar); QPixmapCache::insert(keyCache(), avatar); } } return avatar; } void KTp::Contact::avatarToGray(QPixmap &avatar) { QImage image = avatar.toImage(); QPixmap alpha= avatar.alphaChannel(); for (int i = 0; i < image.width(); ++i) { for (int j = 0; j < image.height(); ++j) { int colour = qGray(image.pixel(i, j)); image.setPixel(i, j, qRgb(colour, colour, colour)); } } avatar = avatar.fromImage(image); avatar.setAlphaChannel(alpha); } QString KTp::Contact::keyCache() const { return avatarToken()+QLatin1String("-offline"); } <|endoftext|>
<commit_before>// "Hello World" in C++ #include <iostream> using namespace std; int main () { cout << "Hello World!" <<endl; cout << "Hello World!" <<endl; cout << "Hello World!" <<endl; cout << "Hello World!" <<endl; cout << "Hello World!" <<endl; return 0; } <commit_msg>insert blank line after each row<commit_after>// "Hello World" in C++ #include <iostream> using namespace std; int main () { cout << "Hello World!" <<endl; cout <<endl; cout << "Hello World!" <<endl; cout <<endl; cout << "Hello World!" <<endl; cout <<endl; cout << "Hello World!" <<endl; cout <<endl; cout << "Hello World!" <<endl; cout <<endl; return 0; } <|endoftext|>
<commit_before>/* Rapicorn * Copyright (C) 2005 Tim Janik * * 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. * * A copy of the GNU Lesser General Public License should ship along * with this library; if not, see http://www.gnu.org/copyleft/. */ #ifndef __RAPICORN_ENUMDEFS_HH__ #define __RAPICORN_ENUMDEFS_HH__ #include <rapicorn-core/rapicornutils.hh> namespace Rapicorn { /* --- enum/flags type descriptions --- */ struct EnumClass { struct Value { const int64 value; const char *const value_name; const uint name_length; }; virtual ~EnumClass () {} virtual void list_values (uint &n_values, const Value* &values) const = 0; virtual const char* enum_name () const = 0; virtual bool flag_combinable () const = 0; virtual int64 constrain (int64 value) const = 0; bool match_partial (const char *value_name1, const char *partial_value_name) const; bool match (const char *value_name1, const char *value_name2) const; const Value* find_first (int64 value) const; const Value* find_first (const String &value_name) const; int64 parse (const char *value_string, String *error = NULL) const; String string (int64 value) const; }; template<typename EnumType> EnumType inline enum_type_constrain (EnumType value) { return value; } template<typename EType> struct EnumType : public virtual EnumClass { typedef EType Type; virtual void list_values (uint &c_n_values, const Value* &c_values) const { c_n_values = n_values, c_values = values; } virtual const char* enum_name () const { return ename; } virtual bool flag_combinable () const { return false; } virtual int64 constrain (int64 value) const { return enum_type_constrain<EType> (EType (value)); } private: static const uint n_values; static const Value *const values; static const char *ename; }; template<typename EType> struct FlagsType : public virtual EnumClass { typedef EType Type; virtual void list_values (uint &c_n_values, const Value* &c_values) const { c_n_values = n_values, c_values = values; } virtual const char* enum_name () const { return ename; } virtual bool flag_combinable () const { return true; } virtual int64 constrain (int64 value) const { return enum_type_constrain<EType> (EType (value)); } private: static const uint n_values; static const Value *const values; static const char *ename; }; /* --- enums --- */ typedef enum { ADJUSTMENT_SOURCE_NONE = 0, ADJUSTMENT_SOURCE_ANCESTRY_HORIZONTAL, ADJUSTMENT_SOURCE_ANCESTRY_VERTICAL, ADJUSTMENT_SOURCE_ANCESTRY_VALUE } AdjustmentSourceType; typedef EnumType<AdjustmentSourceType> EnumTypeAdjustmentSourceType; typedef enum { ALIGN_LEFT = 1, ALIGN_CENTER, ALIGN_RIGHT, } AlignType; typedef EnumType<AlignType> EnumTypeAlignType; typedef enum { ANCHOR_NONE, ANCHOR_CENTER, ANCHOR_EAST, ANCHOR_NORTH_EAST, ANCHOR_NORTH, ANCHOR_NORTH_WEST, ANCHOR_WEST, ANCHOR_SOUTH_WEST, ANCHOR_SOUTH, ANCHOR_SOUTH_EAST, } AnchorType; typedef EnumType<AnchorType> EnumTypeAnchorType; typedef enum { CLICK_ON_PRESS = 1, CLICK_ON_RELEASE, CLICK_SLOW_REPEAT, CLICK_FAST_REPEAT, CLICK_KEY_REPEAT, } ClickType; typedef EnumType<ClickType> EnumTypeClickType; typedef enum { COLOR_NONE, COLOR_FOREGROUND, COLOR_BACKGROUND, COLOR_BACKGROUND_EVEN, COLOR_BACKGROUND_ODD, COLOR_DARK, COLOR_DARK_SHADOW, COLOR_DARK_GLINT, COLOR_LIGHT, COLOR_LIGHT_SHADOW, COLOR_LIGHT_GLINT, COLOR_FOCUS, COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_YELLOW, COLOR_GREEN, COLOR_CYAN, COLOR_BLUE, COLOR_MAGENTA, } ColorType; typedef EnumType<ColorType> EnumTypeColorType; typedef enum { COLOR_INHERIT, COLOR_NORMAL, COLOR_SELECTED, COLOR_BASE, } ColorSchemeType; typedef EnumType<ColorSchemeType> EnumTypeColorSchemeType; typedef enum { DIR_NONE, DIR_RIGHT, DIR_UP, DIR_LEFT, DIR_DOWN, } DirType; typedef EnumType<DirType> EnumTypeDirType; typedef enum { ELLIPSIZE_START = 1, ELLIPSIZE_MIDDLE, ELLIPSIZE_END } EllipsizeType; typedef EnumType<EllipsizeType> EnumTypeEllipsizeType; typedef enum { FOCUS_NEXT = 1, FOCUS_PREV, FOCUS_RIGHT, FOCUS_UP, FOCUS_LEFT, FOCUS_DOWN } FocusDirType; typedef EnumType<FocusDirType> EnumTypeFocusDirType; typedef enum { FRAME_NONE, FRAME_BACKGROUND, FRAME_IN, FRAME_OUT, FRAME_ETCHED_IN, FRAME_ETCHED_OUT, FRAME_FOCUS, FRAME_ALERT_FOCUS, } FrameType; typedef EnumType<FrameType> EnumTypeFrameType; typedef enum { LIGHTING_NONE, LIGHTING_UPPER_LEFT, LIGHTING_UPPER_RIGHT, LIGHTING_LOWER_LEFT, LIGHTING_LOWER_RIGHT, LIGHTING_CENTER, LIGHTING_DIFFUSE, LIGHTING_DARK_UPPER_LEFT = 0x80 | LIGHTING_UPPER_LEFT, LIGHTING_DARK_UPPER_RIGHT = 0x80 | LIGHTING_UPPER_RIGHT, LIGHTING_DARK_LOWER_LEFT = 0x80 | LIGHTING_LOWER_LEFT, LIGHTING_DARK_LOWER_RIGHT = 0x80 | LIGHTING_LOWER_RIGHT, LIGHTING_DARK_CENTER = 0x80 | LIGHTING_CENTER, LIGHTING_DARK_DIFFUSE = 0x80 | LIGHTING_DIFFUSE, } LightingType; static const LightingType LIGHTING_DARK_FLAG = LightingType (0x80); typedef EnumType<LightingType> EnumTypeLightingType; inline LightingType operator& (LightingType s1, LightingType s2) { return LightingType (s1 & (uint64) s2); } inline LightingType& operator&= (LightingType &s1, LightingType s2) { s1 = s1 & s2; return s1; } inline LightingType operator| (LightingType s1, LightingType s2) { return LightingType (s1 | (uint64) s2); } inline LightingType& operator|= (LightingType &s1, LightingType s2) { s1 = s1 | s2; return s1; } typedef enum { SIZE_POLICY_NORMAL = 0, SIZE_POLICY_WIDTH_FROM_HEIGHT, SIZE_POLICY_HEIGHT_FROM_WIDTH, } SizePolicyType; typedef EnumType<SizePolicyType> EnumTypeSizePolicyType; typedef enum { STATE_INSENSITIVE = 1 << 0, STATE_PRELIGHT = 1 << 1, STATE_IMPRESSED = 1 << 2, STATE_FOCUS = 1 << 3, STATE_DEFAULT = 1 << 4, } StateType; static const StateType STATE_NORMAL = StateType (0); static const StateType STATE_MASK = StateType (0x1f); typedef FlagsType<StateType> FlagsTypeStateType; inline StateType operator& (StateType s1, StateType s2) { return StateType (s1 & (uint64) s2); } inline StateType& operator&= (StateType &s1, StateType s2) { s1 = s1 & s2; return s1; } inline StateType operator| (StateType s1, StateType s2) { return StateType (s1 | (uint64) s2); } inline StateType& operator|= (StateType &s1, StateType s2) { s1 = s1 | s2; return s1; } typedef enum /*<enum>*/ { NUM = 'i', REAL = 'f', STRING = 's', ARRAY = 'a', OBJECT = 'c', INTERFACE = OBJECT, CHOICE = ('C' * 256) + STRING, TYPE_REFERENCE = ('T' * 256) + STRING, SEQUENCE = ('Q' * 256) + ARRAY, RECORD = ('R' * 256) + ARRAY, } StorageType; typedef EnumType<StorageType> EnumTypeStorageType; typedef enum { TEXT_MODE_WRAPPED = 1, TEXT_MODE_ELLIPSIZED, TEXT_MODE_SINGLE_LINE, } TextMode; typedef EnumType<TextMode> EnumTypeTextMode; typedef enum { /* main window types */ WINDOW_TYPE_NORMAL = 0, WINDOW_TYPE_DESKTOP, /* desktop background */ WINDOW_TYPE_DOCK, /* dock or panel */ WINDOW_TYPE_TOOLBAR, /* torn-off toolbar */ WINDOW_TYPE_MENU, /* torn-off menu */ WINDOW_TYPE_UTILITY, /* palette or toolbox */ WINDOW_TYPE_SPLASH, /* startup/splash screen */ WINDOW_TYPE_DIALOG, /* dialog window, usually transient */ WINDOW_TYPE_DROPDOWN_MENU, /* menu, opened from menubar */ WINDOW_TYPE_POPUP_MENU, /* menu, opened as context menu */ WINDOW_TYPE_TOOLTIP, /* transient context info window */ WINDOW_TYPE_NOTIFICATION, /* transient info window (e.g. info bubble) */ WINDOW_TYPE_COMBO, /* combo box menu or list window */ WINDOW_TYPE_DND, /* window being dragged in a DND operation */ } WindowType; typedef EnumType<WindowType> EnumTypeWindowType; } // Rapicorn #endif /* __RAPICORN_ENUMDEFS_HH__ */ <commit_msg>enumdefs.hh: adapt type code to latest Plic version<commit_after>/* Rapicorn * Copyright (C) 2005 Tim Janik * * 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. * * A copy of the GNU Lesser General Public License should ship along * with this library; if not, see http://www.gnu.org/copyleft/. */ #ifndef __RAPICORN_ENUMDEFS_HH__ #define __RAPICORN_ENUMDEFS_HH__ #include <rapicorn-core/rapicornutils.hh> namespace Rapicorn { /* --- enum/flags type descriptions --- */ struct EnumClass { struct Value { const int64 value; const char *const value_name; const uint name_length; }; virtual ~EnumClass () {} virtual void list_values (uint &n_values, const Value* &values) const = 0; virtual const char* enum_name () const = 0; virtual bool flag_combinable () const = 0; virtual int64 constrain (int64 value) const = 0; bool match_partial (const char *value_name1, const char *partial_value_name) const; bool match (const char *value_name1, const char *value_name2) const; const Value* find_first (int64 value) const; const Value* find_first (const String &value_name) const; int64 parse (const char *value_string, String *error = NULL) const; String string (int64 value) const; }; template<typename EnumType> EnumType inline enum_type_constrain (EnumType value) { return value; } template<typename EType> struct EnumType : public virtual EnumClass { typedef EType Type; virtual void list_values (uint &c_n_values, const Value* &c_values) const { c_n_values = n_values, c_values = values; } virtual const char* enum_name () const { return ename; } virtual bool flag_combinable () const { return false; } virtual int64 constrain (int64 value) const { return enum_type_constrain<EType> (EType (value)); } private: static const uint n_values; static const Value *const values; static const char *ename; }; template<typename EType> struct FlagsType : public virtual EnumClass { typedef EType Type; virtual void list_values (uint &c_n_values, const Value* &c_values) const { c_n_values = n_values, c_values = values; } virtual const char* enum_name () const { return ename; } virtual bool flag_combinable () const { return true; } virtual int64 constrain (int64 value) const { return enum_type_constrain<EType> (EType (value)); } private: static const uint n_values; static const Value *const values; static const char *ename; }; /* --- enums --- */ typedef enum { ADJUSTMENT_SOURCE_NONE = 0, ADJUSTMENT_SOURCE_ANCESTRY_HORIZONTAL, ADJUSTMENT_SOURCE_ANCESTRY_VERTICAL, ADJUSTMENT_SOURCE_ANCESTRY_VALUE } AdjustmentSourceType; typedef EnumType<AdjustmentSourceType> EnumTypeAdjustmentSourceType; typedef enum { ALIGN_LEFT = 1, ALIGN_CENTER, ALIGN_RIGHT, } AlignType; typedef EnumType<AlignType> EnumTypeAlignType; typedef enum { ANCHOR_NONE, ANCHOR_CENTER, ANCHOR_EAST, ANCHOR_NORTH_EAST, ANCHOR_NORTH, ANCHOR_NORTH_WEST, ANCHOR_WEST, ANCHOR_SOUTH_WEST, ANCHOR_SOUTH, ANCHOR_SOUTH_EAST, } AnchorType; typedef EnumType<AnchorType> EnumTypeAnchorType; typedef enum { CLICK_ON_PRESS = 1, CLICK_ON_RELEASE, CLICK_SLOW_REPEAT, CLICK_FAST_REPEAT, CLICK_KEY_REPEAT, } ClickType; typedef EnumType<ClickType> EnumTypeClickType; typedef enum { COLOR_NONE, COLOR_FOREGROUND, COLOR_BACKGROUND, COLOR_BACKGROUND_EVEN, COLOR_BACKGROUND_ODD, COLOR_DARK, COLOR_DARK_SHADOW, COLOR_DARK_GLINT, COLOR_LIGHT, COLOR_LIGHT_SHADOW, COLOR_LIGHT_GLINT, COLOR_FOCUS, COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_YELLOW, COLOR_GREEN, COLOR_CYAN, COLOR_BLUE, COLOR_MAGENTA, } ColorType; typedef EnumType<ColorType> EnumTypeColorType; typedef enum { COLOR_INHERIT, COLOR_NORMAL, COLOR_SELECTED, COLOR_BASE, } ColorSchemeType; typedef EnumType<ColorSchemeType> EnumTypeColorSchemeType; typedef enum { DIR_NONE, DIR_RIGHT, DIR_UP, DIR_LEFT, DIR_DOWN, } DirType; typedef EnumType<DirType> EnumTypeDirType; typedef enum { ELLIPSIZE_START = 1, ELLIPSIZE_MIDDLE, ELLIPSIZE_END } EllipsizeType; typedef EnumType<EllipsizeType> EnumTypeEllipsizeType; typedef enum { FOCUS_NEXT = 1, FOCUS_PREV, FOCUS_RIGHT, FOCUS_UP, FOCUS_LEFT, FOCUS_DOWN } FocusDirType; typedef EnumType<FocusDirType> EnumTypeFocusDirType; typedef enum { FRAME_NONE, FRAME_BACKGROUND, FRAME_IN, FRAME_OUT, FRAME_ETCHED_IN, FRAME_ETCHED_OUT, FRAME_FOCUS, FRAME_ALERT_FOCUS, } FrameType; typedef EnumType<FrameType> EnumTypeFrameType; typedef enum { LIGHTING_NONE, LIGHTING_UPPER_LEFT, LIGHTING_UPPER_RIGHT, LIGHTING_LOWER_LEFT, LIGHTING_LOWER_RIGHT, LIGHTING_CENTER, LIGHTING_DIFFUSE, LIGHTING_DARK_UPPER_LEFT = 0x80 | LIGHTING_UPPER_LEFT, LIGHTING_DARK_UPPER_RIGHT = 0x80 | LIGHTING_UPPER_RIGHT, LIGHTING_DARK_LOWER_LEFT = 0x80 | LIGHTING_LOWER_LEFT, LIGHTING_DARK_LOWER_RIGHT = 0x80 | LIGHTING_LOWER_RIGHT, LIGHTING_DARK_CENTER = 0x80 | LIGHTING_CENTER, LIGHTING_DARK_DIFFUSE = 0x80 | LIGHTING_DIFFUSE, } LightingType; static const LightingType LIGHTING_DARK_FLAG = LightingType (0x80); typedef EnumType<LightingType> EnumTypeLightingType; inline LightingType operator& (LightingType s1, LightingType s2) { return LightingType (s1 & (uint64) s2); } inline LightingType& operator&= (LightingType &s1, LightingType s2) { s1 = s1 & s2; return s1; } inline LightingType operator| (LightingType s1, LightingType s2) { return LightingType (s1 | (uint64) s2); } inline LightingType& operator|= (LightingType &s1, LightingType s2) { s1 = s1 | s2; return s1; } typedef enum { SIZE_POLICY_NORMAL = 0, SIZE_POLICY_WIDTH_FROM_HEIGHT, SIZE_POLICY_HEIGHT_FROM_WIDTH, } SizePolicyType; typedef EnumType<SizePolicyType> EnumTypeSizePolicyType; typedef enum { STATE_INSENSITIVE = 1 << 0, STATE_PRELIGHT = 1 << 1, STATE_IMPRESSED = 1 << 2, STATE_FOCUS = 1 << 3, STATE_DEFAULT = 1 << 4, } StateType; static const StateType STATE_NORMAL = StateType (0); static const StateType STATE_MASK = StateType (0x1f); typedef FlagsType<StateType> FlagsTypeStateType; inline StateType operator& (StateType s1, StateType s2) { return StateType (s1 & (uint64) s2); } inline StateType& operator&= (StateType &s1, StateType s2) { s1 = s1 & s2; return s1; } inline StateType operator| (StateType s1, StateType s2) { return StateType (s1 | (uint64) s2); } inline StateType& operator|= (StateType &s1, StateType s2) { s1 = s1 | s2; return s1; } typedef enum /*<enum>*/ { NUM = 'i', REAL = 'f', STRING = 's', ARRAY = 'a', OBJECT = 'c', INTERFACE = OBJECT, CHOICE = ('E' * 256) + STRING, TYPE_REFERENCE = ('T' * 256) + STRING, SEQUENCE = ('Q' * 256) + ARRAY, RECORD = ('R' * 256) + ARRAY, } StorageType; typedef EnumType<StorageType> EnumTypeStorageType; typedef enum { TEXT_MODE_WRAPPED = 1, TEXT_MODE_ELLIPSIZED, TEXT_MODE_SINGLE_LINE, } TextMode; typedef EnumType<TextMode> EnumTypeTextMode; typedef enum { /* main window types */ WINDOW_TYPE_NORMAL = 0, WINDOW_TYPE_DESKTOP, /* desktop background */ WINDOW_TYPE_DOCK, /* dock or panel */ WINDOW_TYPE_TOOLBAR, /* torn-off toolbar */ WINDOW_TYPE_MENU, /* torn-off menu */ WINDOW_TYPE_UTILITY, /* palette or toolbox */ WINDOW_TYPE_SPLASH, /* startup/splash screen */ WINDOW_TYPE_DIALOG, /* dialog window, usually transient */ WINDOW_TYPE_DROPDOWN_MENU, /* menu, opened from menubar */ WINDOW_TYPE_POPUP_MENU, /* menu, opened as context menu */ WINDOW_TYPE_TOOLTIP, /* transient context info window */ WINDOW_TYPE_NOTIFICATION, /* transient info window (e.g. info bubble) */ WINDOW_TYPE_COMBO, /* combo box menu or list window */ WINDOW_TYPE_DND, /* window being dragged in a DND operation */ } WindowType; typedef EnumType<WindowType> EnumTypeWindowType; } // Rapicorn #endif /* __RAPICORN_ENUMDEFS_HH__ */ <|endoftext|>
<commit_before>/* open source routing machine Copyright (C) Dennis Luxen, 2010 This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO General Public License as published by the Free Software Foundation; either version 3 of the License, or 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 Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/agpl.txt. */ #include "Algorithms/IteratorBasedCRC32.h" #include "Contractor/Contractor.h" #include "Contractor/EdgeBasedGraphFactory.h" #include "DataStructures/BinaryHeap.h" #include "DataStructures/DeallocatingVector.h" #include "DataStructures/NNGrid.h" #include "DataStructures/QueryEdge.h" #include "Util/BaseConfiguration.h" #include "Util/GraphLoader.h" #include "Util/InputFileUtil.h" #include "Util/LuaUtil.h" #include "Util/OpenMPWrapper.h" #include "Util/StringUtil.h" #include "typedefs.h" #include <boost/foreach.hpp> #include <luabind/luabind.hpp> #include <fstream> #include <istream> #include <iostream> #include <cstring> #include <string> #include <vector> typedef QueryEdge::EdgeData EdgeData; typedef DynamicGraph<EdgeData>::InputEdge InputEdge; typedef StaticGraph<EdgeData>::InputEdge StaticEdge; typedef BaseConfiguration ContractorConfiguration; std::vector<NodeInfo> internalToExternalNodeMapping; std::vector<_Restriction> inputRestrictions; std::vector<NodeID> bollardNodes; std::vector<NodeID> trafficLightNodes; std::vector<ImportEdge> edgeList; int main (int argc, char *argv[]) { if(argc < 3) { ERR("usage: " << std::endl << argv[0] << " <osrm-data> <osrm-restrictions> [<profile>]"); } double startupTime = get_timestamp(); unsigned numberOfThreads = omp_get_num_procs(); if(testDataFile("contractor.ini")) { ContractorConfiguration contractorConfig("contractor.ini"); unsigned rawNumber = stringToInt(contractorConfig.GetParameter("Threads")); if(rawNumber != 0 && rawNumber <= numberOfThreads) numberOfThreads = rawNumber; } omp_set_num_threads(numberOfThreads); INFO("Using restrictions from file: " << argv[2]); std::ifstream restrictionsInstream(argv[2], std::ios::binary); if(!restrictionsInstream.good()) { ERR("Could not access <osrm-restrictions> files"); } _Restriction restriction; unsigned usableRestrictionsCounter(0); restrictionsInstream.read((char*)&usableRestrictionsCounter, sizeof(unsigned)); inputRestrictions.resize(usableRestrictionsCounter); restrictionsInstream.read((char *)&(inputRestrictions[0]), usableRestrictionsCounter*sizeof(_Restriction)); restrictionsInstream.close(); std::ifstream in; in.open (argv[1], std::ifstream::in | std::ifstream::binary); if (!in.is_open()) { ERR("Cannot open " << argv[1]); } std::string nodeOut(argv[1]); nodeOut += ".nodes"; std::string edgeOut(argv[1]); edgeOut += ".edges"; std::string graphOut(argv[1]); graphOut += ".hsgr"; std::string ramIndexOut(argv[1]); ramIndexOut += ".ramIndex"; std::string fileIndexOut(argv[1]); fileIndexOut += ".fileIndex"; /*** Setup Scripting Environment ***/ if(!testDataFile( (argc > 3 ? argv[3] : "profile.lua") )) { ERR("Need profile.lua to apply traffic signal penalty"); } // Create a new lua state lua_State *myLuaState = luaL_newstate(); // Connect LuaBind to this lua state luabind::open(myLuaState); //open utility libraries string library; luaL_openlibs(myLuaState); //adjust lua load path luaAddScriptFolderToLoadPath( myLuaState, (argc > 3 ? argv[3] : "profile.lua") ); // Now call our function in a lua script INFO("Parsing speedprofile from " << (argc > 3 ? argv[3] : "profile.lua") ); if(0 != luaL_dofile(myLuaState, (argc > 3 ? argv[3] : "profile.lua") )) { ERR(lua_tostring(myLuaState,-1)<< " occured in scripting block"); } EdgeBasedGraphFactory::SpeedProfileProperties speedProfile; if(0 != luaL_dostring( myLuaState, "return traffic_signal_penalty\n")) { ERR(lua_tostring(myLuaState,-1)<< " occured in scripting block"); } speedProfile.trafficSignalPenalty = 10*lua_tointeger(myLuaState, -1); if(0 != luaL_dostring( myLuaState, "return u_turn_penalty\n")) { ERR(lua_tostring(myLuaState,-1)<< " occured in scripting block"); } speedProfile.uTurnPenalty = 10*lua_tointeger(myLuaState, -1); speedProfile.has_turn_penalty_function = lua_function_exists( myLuaState, "turn_function" ); std::vector<ImportEdge> edgeList; NodeID nodeBasedNodeNumber = readBinaryOSRMGraphFromStream(in, edgeList, bollardNodes, trafficLightNodes, &internalToExternalNodeMapping, inputRestrictions); in.close(); INFO(inputRestrictions.size() << " restrictions, " << bollardNodes.size() << " bollard nodes, " << trafficLightNodes.size() << " traffic lights"); if(0 == edgeList.size()) ERR("The input data is broken. It is impossible to do any turns in this graph"); /*** * Building an edge-expanded graph from node-based input an turn restrictions */ INFO("Generating edge-expanded graph representation"); EdgeBasedGraphFactory * edgeBasedGraphFactory = new EdgeBasedGraphFactory (nodeBasedNodeNumber, edgeList, bollardNodes, trafficLightNodes, inputRestrictions, internalToExternalNodeMapping, speedProfile); std::vector<ImportEdge>().swap(edgeList); edgeBasedGraphFactory->Run(edgeOut.c_str(), myLuaState); std::vector<_Restriction>().swap(inputRestrictions); std::vector<NodeID>().swap(bollardNodes); std::vector<NodeID>().swap(trafficLightNodes); NodeID edgeBasedNodeNumber = edgeBasedGraphFactory->GetNumberOfNodes(); DeallocatingVector<EdgeBasedEdge> edgeBasedEdgeList; edgeBasedGraphFactory->GetEdgeBasedEdges(edgeBasedEdgeList); DeallocatingVector<EdgeBasedGraphFactory::EdgeBasedNode> nodeBasedEdgeList; edgeBasedGraphFactory->GetEdgeBasedNodes(nodeBasedEdgeList); delete edgeBasedGraphFactory; /*** * Writing info on original (node-based) nodes */ INFO("writing node map ..."); std::ofstream mapOutFile(nodeOut.c_str(), std::ios::binary); mapOutFile.write((char *)&(internalToExternalNodeMapping[0]), internalToExternalNodeMapping.size()*sizeof(NodeInfo)); mapOutFile.close(); std::vector<NodeInfo>().swap(internalToExternalNodeMapping); double expansionHasFinishedTime = get_timestamp() - startupTime; /*** * Building grid-like nearest-neighbor data structure */ INFO("building grid ..."); WritableGrid * writeableGrid = new WritableGrid(); writeableGrid->ConstructGrid(nodeBasedEdgeList, ramIndexOut.c_str(), fileIndexOut.c_str()); delete writeableGrid; IteratorbasedCRC32<DeallocatingVector<EdgeBasedGraphFactory::EdgeBasedNode> > crc32; unsigned crc32OfNodeBasedEdgeList = crc32(nodeBasedEdgeList.begin(), nodeBasedEdgeList.end() ); nodeBasedEdgeList.clear(); INFO("CRC32 based checksum is " << crc32OfNodeBasedEdgeList); /*** * Contracting the edge-expanded graph */ INFO("initializing contractor"); Contractor* contractor = new Contractor( edgeBasedNodeNumber, edgeBasedEdgeList ); double contractionStartedTimestamp(get_timestamp()); contractor->Run(); INFO("Contraction took " << get_timestamp() - contractionStartedTimestamp << " sec"); DeallocatingVector< QueryEdge > contractedEdgeList; contractor->GetEdges( contractedEdgeList ); delete contractor; /*** * Sorting contracted edges in a way that the static query graph can read some in in-place. */ INFO("Building Node Array"); std::sort(contractedEdgeList.begin(), contractedEdgeList.end()); unsigned numberOfNodes = 0; unsigned numberOfEdges = contractedEdgeList.size(); INFO("Serializing compacted graph"); std::ofstream edgeOutFile(graphOut.c_str(), std::ios::binary); BOOST_FOREACH(const QueryEdge & edge, contractedEdgeList) { if(edge.source > numberOfNodes) { numberOfNodes = edge.source; } if(edge.target > numberOfNodes) { numberOfNodes = edge.target; } } numberOfNodes+=1; std::vector< StaticGraph<EdgeData>::_StrNode > _nodes; _nodes.resize( numberOfNodes + 1 ); StaticGraph<EdgeData>::EdgeIterator edge = 0; StaticGraph<EdgeData>::EdgeIterator position = 0; for ( StaticGraph<EdgeData>::NodeIterator node = 0; node <= numberOfNodes; ++node ) { StaticGraph<EdgeData>::EdgeIterator lastEdge = edge; while ( edge < numberOfEdges && contractedEdgeList[edge].source == node ) ++edge; _nodes[node].firstEdge = position; //=edge position += edge - lastEdge; //remove } ++numberOfNodes; //Serialize numberOfNodes, nodes edgeOutFile.write((char*) &crc32OfNodeBasedEdgeList, sizeof(unsigned)); edgeOutFile.write((char*) &numberOfNodes, sizeof(unsigned)); edgeOutFile.write((char*) &_nodes[0], sizeof(StaticGraph<EdgeData>::_StrNode)*(numberOfNodes)); //Serialize number of Edges edgeOutFile.write((char*) &position, sizeof(unsigned)); --numberOfNodes; edge = 0; int usedEdgeCounter = 0; StaticGraph<EdgeData>::_StrEdge currentEdge; for ( StaticGraph<EdgeData>::NodeIterator node = 0; node < numberOfNodes; ++node ) { for ( StaticGraph<EdgeData>::EdgeIterator i = _nodes[node].firstEdge, e = _nodes[node+1].firstEdge; i != e; ++i ) { assert(node != contractedEdgeList[edge].target); currentEdge.target = contractedEdgeList[edge].target; currentEdge.data = contractedEdgeList[edge].data; if(currentEdge.data.distance <= 0) { INFO("Edge: " << i << ",source: " << contractedEdgeList[edge].source << ", target: " << contractedEdgeList[edge].target << ", dist: " << currentEdge.data.distance); ERR("Failed at edges of node " << node << " of " << numberOfNodes); } //Serialize edges edgeOutFile.write((char*) &currentEdge, sizeof(StaticGraph<EdgeData>::_StrEdge)); ++edge; ++usedEdgeCounter; } } double endTime = (get_timestamp() - startupTime); INFO("Expansion : " << (nodeBasedNodeNumber/expansionHasFinishedTime) << " nodes/sec and "<< (edgeBasedNodeNumber/expansionHasFinishedTime) << " edges/sec"); INFO("Contraction: " << (edgeBasedNodeNumber/expansionHasFinishedTime) << " nodes/sec and "<< usedEdgeCounter/endTime << " edges/sec"); edgeOutFile.close(); //cleanedEdgeList.clear(); _nodes.clear(); INFO("finished preprocessing"); return 0; } <commit_msg>Catching any left-over exception that may occur during preprocessing (stxxl)<commit_after>/* open source routing machine Copyright (C) Dennis Luxen, 2010 This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO General Public License as published by the Free Software Foundation; either version 3 of the License, or 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 Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/agpl.txt. */ #include "Algorithms/IteratorBasedCRC32.h" #include "Contractor/Contractor.h" #include "Contractor/EdgeBasedGraphFactory.h" #include "DataStructures/BinaryHeap.h" #include "DataStructures/DeallocatingVector.h" #include "DataStructures/NNGrid.h" #include "DataStructures/QueryEdge.h" #include "Util/BaseConfiguration.h" #include "Util/GraphLoader.h" #include "Util/InputFileUtil.h" #include "Util/LuaUtil.h" #include "Util/OpenMPWrapper.h" #include "Util/StringUtil.h" #include "typedefs.h" #include <boost/foreach.hpp> #include <luabind/luabind.hpp> #include <fstream> #include <istream> #include <iostream> #include <cstring> #include <string> #include <vector> typedef QueryEdge::EdgeData EdgeData; typedef DynamicGraph<EdgeData>::InputEdge InputEdge; typedef StaticGraph<EdgeData>::InputEdge StaticEdge; typedef BaseConfiguration ContractorConfiguration; std::vector<NodeInfo> internalToExternalNodeMapping; std::vector<_Restriction> inputRestrictions; std::vector<NodeID> bollardNodes; std::vector<NodeID> trafficLightNodes; std::vector<ImportEdge> edgeList; int main (int argc, char *argv[]) { try { if(argc < 3) { ERR("usage: " << std::endl << argv[0] << " <osrm-data> <osrm-restrictions> [<profile>]"); } double startupTime = get_timestamp(); unsigned numberOfThreads = omp_get_num_procs(); if(testDataFile("contractor.ini")) { ContractorConfiguration contractorConfig("contractor.ini"); unsigned rawNumber = stringToInt(contractorConfig.GetParameter("Threads")); if(rawNumber != 0 && rawNumber <= numberOfThreads) numberOfThreads = rawNumber; } omp_set_num_threads(numberOfThreads); INFO("Using restrictions from file: " << argv[2]); std::ifstream restrictionsInstream(argv[2], std::ios::binary); if(!restrictionsInstream.good()) { ERR("Could not access <osrm-restrictions> files"); } _Restriction restriction; unsigned usableRestrictionsCounter(0); restrictionsInstream.read((char*)&usableRestrictionsCounter, sizeof(unsigned)); inputRestrictions.resize(usableRestrictionsCounter); restrictionsInstream.read((char *)&(inputRestrictions[0]), usableRestrictionsCounter*sizeof(_Restriction)); restrictionsInstream.close(); std::ifstream in; in.open (argv[1], std::ifstream::in | std::ifstream::binary); if (!in.is_open()) { ERR("Cannot open " << argv[1]); } std::string nodeOut(argv[1]); nodeOut += ".nodes"; std::string edgeOut(argv[1]); edgeOut += ".edges"; std::string graphOut(argv[1]); graphOut += ".hsgr"; std::string ramIndexOut(argv[1]); ramIndexOut += ".ramIndex"; std::string fileIndexOut(argv[1]); fileIndexOut += ".fileIndex"; /*** Setup Scripting Environment ***/ if(!testDataFile( (argc > 3 ? argv[3] : "profile.lua") )) { ERR("Need profile.lua to apply traffic signal penalty"); } // Create a new lua state lua_State *myLuaState = luaL_newstate(); // Connect LuaBind to this lua state luabind::open(myLuaState); //open utility libraries string library; luaL_openlibs(myLuaState); //adjust lua load path luaAddScriptFolderToLoadPath( myLuaState, (argc > 3 ? argv[3] : "profile.lua") ); // Now call our function in a lua script INFO("Parsing speedprofile from " << (argc > 3 ? argv[3] : "profile.lua") ); if(0 != luaL_dofile(myLuaState, (argc > 3 ? argv[3] : "profile.lua") )) { ERR(lua_tostring(myLuaState,-1)<< " occured in scripting block"); } EdgeBasedGraphFactory::SpeedProfileProperties speedProfile; if(0 != luaL_dostring( myLuaState, "return traffic_signal_penalty\n")) { ERR(lua_tostring(myLuaState,-1)<< " occured in scripting block"); } speedProfile.trafficSignalPenalty = 10*lua_tointeger(myLuaState, -1); if(0 != luaL_dostring( myLuaState, "return u_turn_penalty\n")) { ERR(lua_tostring(myLuaState,-1)<< " occured in scripting block"); } speedProfile.uTurnPenalty = 10*lua_tointeger(myLuaState, -1); speedProfile.has_turn_penalty_function = lua_function_exists( myLuaState, "turn_function" ); std::vector<ImportEdge> edgeList; NodeID nodeBasedNodeNumber = readBinaryOSRMGraphFromStream(in, edgeList, bollardNodes, trafficLightNodes, &internalToExternalNodeMapping, inputRestrictions); in.close(); INFO(inputRestrictions.size() << " restrictions, " << bollardNodes.size() << " bollard nodes, " << trafficLightNodes.size() << " traffic lights"); if(0 == edgeList.size()) ERR("The input data is broken. It is impossible to do any turns in this graph"); /*** * Building an edge-expanded graph from node-based input an turn restrictions */ INFO("Generating edge-expanded graph representation"); EdgeBasedGraphFactory * edgeBasedGraphFactory = new EdgeBasedGraphFactory (nodeBasedNodeNumber, edgeList, bollardNodes, trafficLightNodes, inputRestrictions, internalToExternalNodeMapping, speedProfile); std::vector<ImportEdge>().swap(edgeList); edgeBasedGraphFactory->Run(edgeOut.c_str(), myLuaState); std::vector<_Restriction>().swap(inputRestrictions); std::vector<NodeID>().swap(bollardNodes); std::vector<NodeID>().swap(trafficLightNodes); NodeID edgeBasedNodeNumber = edgeBasedGraphFactory->GetNumberOfNodes(); DeallocatingVector<EdgeBasedEdge> edgeBasedEdgeList; edgeBasedGraphFactory->GetEdgeBasedEdges(edgeBasedEdgeList); DeallocatingVector<EdgeBasedGraphFactory::EdgeBasedNode> nodeBasedEdgeList; edgeBasedGraphFactory->GetEdgeBasedNodes(nodeBasedEdgeList); delete edgeBasedGraphFactory; /*** * Writing info on original (node-based) nodes */ INFO("writing node map ..."); std::ofstream mapOutFile(nodeOut.c_str(), std::ios::binary); mapOutFile.write((char *)&(internalToExternalNodeMapping[0]), internalToExternalNodeMapping.size()*sizeof(NodeInfo)); mapOutFile.close(); std::vector<NodeInfo>().swap(internalToExternalNodeMapping); double expansionHasFinishedTime = get_timestamp() - startupTime; /*** * Building grid-like nearest-neighbor data structure */ INFO("building grid ..."); WritableGrid * writeableGrid = new WritableGrid(); writeableGrid->ConstructGrid(nodeBasedEdgeList, ramIndexOut.c_str(), fileIndexOut.c_str()); delete writeableGrid; IteratorbasedCRC32<DeallocatingVector<EdgeBasedGraphFactory::EdgeBasedNode> > crc32; unsigned crc32OfNodeBasedEdgeList = crc32(nodeBasedEdgeList.begin(), nodeBasedEdgeList.end() ); nodeBasedEdgeList.clear(); INFO("CRC32 based checksum is " << crc32OfNodeBasedEdgeList); /*** * Contracting the edge-expanded graph */ INFO("initializing contractor"); Contractor* contractor = new Contractor( edgeBasedNodeNumber, edgeBasedEdgeList ); double contractionStartedTimestamp(get_timestamp()); contractor->Run(); INFO("Contraction took " << get_timestamp() - contractionStartedTimestamp << " sec"); DeallocatingVector< QueryEdge > contractedEdgeList; contractor->GetEdges( contractedEdgeList ); delete contractor; /*** * Sorting contracted edges in a way that the static query graph can read some in in-place. */ INFO("Building Node Array"); std::sort(contractedEdgeList.begin(), contractedEdgeList.end()); unsigned numberOfNodes = 0; unsigned numberOfEdges = contractedEdgeList.size(); INFO("Serializing compacted graph"); std::ofstream edgeOutFile(graphOut.c_str(), std::ios::binary); BOOST_FOREACH(const QueryEdge & edge, contractedEdgeList) { if(edge.source > numberOfNodes) { numberOfNodes = edge.source; } if(edge.target > numberOfNodes) { numberOfNodes = edge.target; } } numberOfNodes+=1; std::vector< StaticGraph<EdgeData>::_StrNode > _nodes; _nodes.resize( numberOfNodes + 1 ); StaticGraph<EdgeData>::EdgeIterator edge = 0; StaticGraph<EdgeData>::EdgeIterator position = 0; for ( StaticGraph<EdgeData>::NodeIterator node = 0; node <= numberOfNodes; ++node ) { StaticGraph<EdgeData>::EdgeIterator lastEdge = edge; while ( edge < numberOfEdges && contractedEdgeList[edge].source == node ) ++edge; _nodes[node].firstEdge = position; //=edge position += edge - lastEdge; //remove } ++numberOfNodes; //Serialize numberOfNodes, nodes edgeOutFile.write((char*) &crc32OfNodeBasedEdgeList, sizeof(unsigned)); edgeOutFile.write((char*) &numberOfNodes, sizeof(unsigned)); edgeOutFile.write((char*) &_nodes[0], sizeof(StaticGraph<EdgeData>::_StrNode)*(numberOfNodes)); //Serialize number of Edges edgeOutFile.write((char*) &position, sizeof(unsigned)); --numberOfNodes; edge = 0; int usedEdgeCounter = 0; StaticGraph<EdgeData>::_StrEdge currentEdge; for ( StaticGraph<EdgeData>::NodeIterator node = 0; node < numberOfNodes; ++node ) { for ( StaticGraph<EdgeData>::EdgeIterator i = _nodes[node].firstEdge, e = _nodes[node+1].firstEdge; i != e; ++i ) { assert(node != contractedEdgeList[edge].target); currentEdge.target = contractedEdgeList[edge].target; currentEdge.data = contractedEdgeList[edge].data; if(currentEdge.data.distance <= 0) { INFO("Edge: " << i << ",source: " << contractedEdgeList[edge].source << ", target: " << contractedEdgeList[edge].target << ", dist: " << currentEdge.data.distance); ERR("Failed at edges of node " << node << " of " << numberOfNodes); } //Serialize edges edgeOutFile.write((char*) &currentEdge, sizeof(StaticGraph<EdgeData>::_StrEdge)); ++edge; ++usedEdgeCounter; } } double endTime = (get_timestamp() - startupTime); INFO("Expansion : " << (nodeBasedNodeNumber/expansionHasFinishedTime) << " nodes/sec and "<< (edgeBasedNodeNumber/expansionHasFinishedTime) << " edges/sec"); INFO("Contraction: " << (edgeBasedNodeNumber/expansionHasFinishedTime) << " nodes/sec and "<< usedEdgeCounter/endTime << " edges/sec"); edgeOutFile.close(); //cleanedEdgeList.clear(); _nodes.clear(); INFO("finished preprocessing"); } catch (std::exception &e) { ERR("Exception occured: " << e.what()); } return 0; } <|endoftext|>
<commit_before>#pragma once #include <future> #include <agency/execution_categories.hpp> #include <agency/functional.hpp> #include <functional> namespace agency { class sequential_executor { public: using execution_category = sequential_execution_tag; template<class Function, class T> void execute(Function f, size_t n, T shared_init) { auto shared_parm = agency::decay_construct(shared_init); for(size_t i = 0; i < n; ++i) { f(i, shared_parm); } } template<class Function, class T> std::future<void> async_execute(Function f, size_t n, T shared_init) { return std::async(std::launch::deferred, [=] { this->execute(f, n, shared_init); }); } }; } // end agency <commit_msg>Receive shared initializers by forwarding reference in sequential_executor<commit_after>#pragma once #include <future> #include <agency/execution_categories.hpp> #include <agency/functional.hpp> #include <functional> namespace agency { class sequential_executor { public: using execution_category = sequential_execution_tag; template<class Function, class T> void execute(Function f, size_t n, T&& shared_init) { auto shared_parm = agency::decay_construct(std::forward<T>(shared_init)); for(size_t i = 0; i < n; ++i) { f(i, shared_parm); } } template<class Function, class T> std::future<void> async_execute(Function f, size_t n, T&& shared_init) { return std::async(std::launch::deferred, [=] { this->execute(f, n, shared_init); }); } }; } // end agency <|endoftext|>
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html // rapicorn-zintern - small C source compression utility #include <cxxaux.hh> #include <glib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <zlib.h> #include <string> typedef Rapicorn::uint8 uint8; typedef std::string String; namespace { static void zintern_error (const char *format, ...) RAPICORN_PRINTF (1, 2); static void zintern_error (const char *format, ...) { gchar *buffer; va_list args; va_start (args, format); buffer = g_strdup_vprintf (format, args); va_end (args); g_printerr ("\nERROR: %s\n", buffer); _exit (1); g_free (buffer); } static bool use_compression = FALSE; static bool use_base_name = FALSE; static bool break_at_newlines = FALSE; static bool as_resource = false; typedef struct { uint pos; bool pad; } Config; static Config config_init = { 0, 0 }; static inline void print_uchar (Config *config, uint8 d) { if (config->pos > 70) { printf ("\"\n \""); config->pos = 3; config->pad = FALSE; } if (d == '\\') { printf ("\\\\"); config->pos += 2; } else if (d == '\n') { printf ("\\n"); config->pos += 2; if (break_at_newlines && config->pos > 3) config->pos |= 1 << 31; } else if (d == '"') { printf ("\\\""); config->pos += 2; } else if (d < 33 || d > 126 || d == '?') { printf ("\\%o", d); config->pos += 1 + 1 + (d > 7) + (d > 63); config->pad = d < 64; return; } else if (config->pad && d >= '0' && d <= '9') { printf ("\"\""); printf ("%c", d); config->pos += 3; } else { printf ("%c", d); config->pos += 1; } config->pad = FALSE; } #define to_upper(c) ((c) >='a' && (c) <='z' ? (c) - 'a' + 'A' : (c)) #define is_alnum(c) (((c) >='A' && (c) <='Z') || ((c) >='a' && (c) <='z') || ((c) >='0' && (c) <='9')) static String to_cupper (const String &str) { String s (str); for (uint i = 0; i < s.size(); i++) if (is_alnum (s[i])) s[i] = to_upper (s[i]); else s[i] = '_'; return s; } static void gen_zfile (const char *name, const char *file) { FILE *f = fopen (file, "r"); uint8 *data = NULL; uint i, dlen = 0, mlen = 0; Bytef *cdata; uLongf clen; gchar *basefile = g_path_get_basename (file); String fname = use_base_name ? basefile : file; g_free (basefile); basefile = NULL; Config config; if (!f) zintern_error ("failed to open \"%s\": %s", file, g_strerror (errno)); do { if (mlen <= dlen + 1024) { mlen += 8192; data = g_renew (uint8, data, mlen); } dlen += fread (data + dlen, 1, mlen - dlen, f); } while (!feof (f)); if (ferror (f)) zintern_error ("failed to read from \"%s\": %s", file, g_strerror (errno)); if (use_compression || as_resource) { int result; const char *err; clen = dlen + dlen / 100 + 64; cdata = g_new (uint8, clen); result = compress2 (cdata, &clen, data, dlen, Z_BEST_COMPRESSION); switch (result) { case Z_OK: err = NULL; break; case Z_MEM_ERROR: err = "out of memory"; break; case Z_BUF_ERROR: err = "insufficient buffer size"; break; default: err = "unknown error"; break; } if (err) zintern_error ("while compressing \"%s\": %s", file, err); } else { clen = dlen; cdata = data; } g_print ("/* rapicorn-zintern file dump of %s */\n", file); if (as_resource) { if (name[0] == '/') g_error ("invalid absolute resource path (must be relative): %s", name); /* two things to consider for using the compressed data: * 1) for the reader code, pack_size + 1 must be smaller than data_size to identify compressed data. * 2) using compressed data requires runtime unpacking overhead and extra dynamic memory allocation, * so it should provide a *significant* benefit if it's used. */ const bool compress_resource = clen <= 0.75 * dlen && clen + 1 < dlen; const size_t rlen = compress_resource ? clen : dlen; const uint8 *rdata = rlen == dlen ? data : cdata; gchar *ident = g_strcanon (g_strdup (name), "0123456789abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ", '_'); config = config_init; printf ("RAPICORN_STATIC_RESOURCE_DATA (%s) =\n \"", ident); for (i = 0; i < rlen; i++) print_uchar (&config, rdata[i]); printf ("\"; // %lu + 1\n", rlen); config = config_init; printf ("RAPICORN_STATIC_RESOURCE_ENTRY (%s, \"", ident); for (i = 0; i < strlen (name); i++) print_uchar (&config, name[i]); printf ("\", %u);\n", dlen); g_free (ident); } else { config = config_init; printf ("#define %s_NAME \"", to_cupper (name).c_str()); for (i = 0; i < fname.size(); i++) print_uchar (&config, fname[i]); printf ("\"\n"); printf ("#define %s_SIZE (%u)\n", to_cupper (name).c_str(), dlen); config = config_init; printf ("static const unsigned char %s_DATA[%lu + 1] =\n", to_cupper (name).c_str(), clen); printf ("( \""); for (i = 0; i < clen; i++) print_uchar (&config, cdata[i]); printf ("\");\n"); } fclose (f); g_free (data); if (cdata != data) g_free (cdata); } static int help (char *arg) { g_printerr ("usage: rapicorn-zintern [-h] [-b] [-z] [[name file]...]\n"); g_printerr (" -h Print usage information\n"); g_printerr (" -b Strip directories from file names\n"); g_printerr (" -n Break output lines after newlines raw data\n"); g_printerr (" -r Produce Rapicorn resource declarations\n"); g_printerr (" -z Compress data blocks with libz\n"); g_printerr ("Parse (name, file) pairs and generate C source\n"); g_printerr ("containing inlined data blocks of the files given.\n"); return arg != NULL; } extern "C" int main (int argc, char *argv[]) { GSList *plist = NULL; for (int i = 1; i < argc; i++) { if (strcmp ("-z", argv[i]) == 0) { use_compression = TRUE; } else if (strcmp ("-r", argv[i]) == 0) { as_resource = true; } else if (strcmp ("-b", argv[i]) == 0) { use_base_name = TRUE; } else if (strcmp ("-n", argv[i]) == 0) { break_at_newlines = TRUE; } else if (strcmp ("-h", argv[i]) == 0) { return help (NULL); } else plist = g_slist_append (plist, argv[i]); } if (argc <= 1) return help (NULL); while (plist && plist->next) { const char *name = (char*) plist->data; GSList *tmp = plist; plist = tmp->next; g_slist_free_1 (tmp); const char *file = (char*) plist->data; tmp = plist; plist = tmp->next; g_slist_free_1 (tmp); gen_zfile (name, file); } return 0; } } // anon <commit_msg>RCORE: zintern: fix bool constants<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html // rapicorn-zintern - small C source compression utility #include "cxxaux.hh" #include <glib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <zlib.h> #include <string> using namespace Rapicorn; typedef std::string String; static void zintern_error (const char *format, ...) RAPICORN_PRINTF (1, 2); static void zintern_error (const char *format, ...) { char buffer[4096]; va_list args; va_start (args, format); vsnprintf (buffer, sizeof (buffer), format, args); va_end (args); buffer[sizeof (buffer) - 1] = 0; fprintf (stderr, "\nERROR: %s\n", buffer); _exit (1); } static bool use_compression = false; static bool use_base_name = false; static bool break_at_newlines = false; static bool as_resource = false; typedef struct { uint pos; bool pad; } Config; static Config config_init = { 0, 0 }; static inline void print_uchar (Config *config, uint8 d) { if (config->pos > 70) { printf ("\"\n \""); config->pos = 3; config->pad = false; } if (d == '\\') { printf ("\\\\"); config->pos += 2; } else if (d == '\n') { printf ("\\n"); config->pos += 2; if (break_at_newlines && config->pos > 3) config->pos |= 1 << 31; } else if (d == '"') { printf ("\\\""); config->pos += 2; } else if (d < 33 || d > 126 || d == '?') { printf ("\\%o", d); config->pos += 1 + 1 + (d > 7) + (d > 63); config->pad = d < 64; return; } else if (config->pad && d >= '0' && d <= '9') { printf ("\"\""); printf ("%c", d); config->pos += 3; } else { printf ("%c", d); config->pos += 1; } config->pad = false; } #define to_upper(c) ((c) >='a' && (c) <='z' ? (c) - 'a' + 'A' : (c)) #define is_alnum(c) (((c) >='A' && (c) <='Z') || ((c) >='a' && (c) <='z') || ((c) >='0' && (c) <='9')) static String to_cupper (const String &str) { String s (str); for (uint i = 0; i < s.size(); i++) if (is_alnum (s[i])) s[i] = to_upper (s[i]); else s[i] = '_'; return s; } static void gen_zfile (const char *name, const char *file) { FILE *f = fopen (file, "r"); uint8 *data = NULL; uint i, dlen = 0, mlen = 0; Bytef *cdata; uLongf clen; gchar *basefile = g_path_get_basename (file); String fname = use_base_name ? basefile : file; g_free (basefile); basefile = NULL; Config config; if (!f) zintern_error ("failed to open \"%s\": %s", file, g_strerror (errno)); do { if (mlen <= dlen + 1024) { mlen += 8192; data = g_renew (uint8, data, mlen); } dlen += fread (data + dlen, 1, mlen - dlen, f); } while (!feof (f)); if (ferror (f)) zintern_error ("failed to read from \"%s\": %s", file, g_strerror (errno)); if (use_compression || as_resource) { int result; const char *err; clen = dlen + dlen / 100 + 64; cdata = g_new (uint8, clen); result = compress2 (cdata, &clen, data, dlen, Z_BEST_COMPRESSION); switch (result) { case Z_OK: err = NULL; break; case Z_MEM_ERROR: err = "out of memory"; break; case Z_BUF_ERROR: err = "insufficient buffer size"; break; default: err = "unknown error"; break; } if (err) zintern_error ("while compressing \"%s\": %s", file, err); } else { clen = dlen; cdata = data; } g_print ("/* rapicorn-zintern file dump of %s */\n", file); if (as_resource) { if (name[0] == '/') g_error ("invalid absolute resource path (must be relative): %s", name); /* two things to consider for using the compressed data: * 1) for the reader code, pack_size + 1 must be smaller than data_size to identify compressed data. * 2) using compressed data requires runtime unpacking overhead and extra dynamic memory allocation, * so it should provide a *significant* benefit if it's used. */ const bool compress_resource = clen <= 0.75 * dlen && clen + 1 < dlen; const size_t rlen = compress_resource ? clen : dlen; const uint8 *rdata = rlen == dlen ? data : cdata; gchar *ident = g_strcanon (g_strdup (name), "0123456789abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ", '_'); config = config_init; printf ("RAPICORN_STATIC_RESOURCE_DATA (%s) =\n \"", ident); for (i = 0; i < rlen; i++) print_uchar (&config, rdata[i]); printf ("\"; // %lu + 1\n", rlen); config = config_init; printf ("RAPICORN_STATIC_RESOURCE_ENTRY (%s, \"", ident); for (i = 0; i < strlen (name); i++) print_uchar (&config, name[i]); printf ("\", %u);\n", dlen); g_free (ident); } else { config = config_init; printf ("#define %s_NAME \"", to_cupper (name).c_str()); for (i = 0; i < fname.size(); i++) print_uchar (&config, fname[i]); printf ("\"\n"); printf ("#define %s_SIZE (%u)\n", to_cupper (name).c_str(), dlen); config = config_init; printf ("static const unsigned char %s_DATA[%lu + 1] =\n", to_cupper (name).c_str(), clen); printf ("( \""); for (i = 0; i < clen; i++) print_uchar (&config, cdata[i]); printf ("\");\n"); } fclose (f); g_free (data); if (cdata != data) g_free (cdata); } static int help (char *arg) { g_printerr ("usage: rapicorn-zintern [-h] [-b] [-z] [[name file]...]\n"); g_printerr (" -h Print usage information\n"); g_printerr (" -b Strip directories from file names\n"); g_printerr (" -n Break output lines after newlines raw data\n"); g_printerr (" -r Produce Rapicorn resource declarations\n"); g_printerr (" -z Compress data blocks with libz\n"); g_printerr ("Parse (name, file) pairs and generate C source\n"); g_printerr ("containing inlined data blocks of the files given.\n"); return arg != NULL; } int main (int argc, char *argv[]) { GSList *plist = NULL; for (int i = 1; i < argc; i++) { if (strcmp ("-z", argv[i]) == 0) { use_compression = true; } else if (strcmp ("-r", argv[i]) == 0) { as_resource = true; } else if (strcmp ("-b", argv[i]) == 0) { use_base_name = true; } else if (strcmp ("-n", argv[i]) == 0) { break_at_newlines = true; } else if (strcmp ("-h", argv[i]) == 0) { return help (NULL); } else plist = g_slist_append (plist, argv[i]); } if (argc <= 1) return help (NULL); while (plist && plist->next) { const char *name = (char*) plist->data; GSList *tmp = plist; plist = tmp->next; g_slist_free_1 (tmp); const char *file = (char*) plist->data; tmp = plist; plist = tmp->next; g_slist_free_1 (tmp); gen_zfile (name, file); } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2017-2018 Baidu 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 "openrasp_hook.h" #include "openrasp_ini.h" #include <string> #include <map> extern "C" { #include "ext/pdo/php_pdo_driver.h" #include "zend_ini.h" #include "openrasp_shared_alloc.h" } /** * sql connection alarm */ static void connection_via_default_username_policy(char *check_message, sql_connection_entry *sql_connection_p TSRMLS_DC) { zval *policy_array = nullptr; MAKE_STD_ZVAL(policy_array); array_init(policy_array); add_assoc_string(policy_array, "message", check_message, 1); add_assoc_long(policy_array, "policy_id", 3006); zval *connection_params = nullptr; MAKE_STD_ZVAL(connection_params); array_init(connection_params); add_assoc_string(connection_params, "server", sql_connection_p->server, 1); add_assoc_string(connection_params, "host", sql_connection_p->host, 1); add_assoc_long(connection_params, "port", sql_connection_p->port); add_assoc_string(connection_params, "user", sql_connection_p->username, 1); add_assoc_zval(policy_array, "params", connection_params); policy_info(policy_array TSRMLS_CC); zval_ptr_dtor(&policy_array); } void slow_query_alarm(int rows TSRMLS_DC) { zval *attack_params = nullptr; MAKE_STD_ZVAL(attack_params); ZVAL_LONG(attack_params, rows); zval *plugin_message = nullptr; MAKE_STD_ZVAL(plugin_message); char *message_str = nullptr; spprintf(&message_str, 0, _("SQL slow query detected: selected %d rows, exceeding %d"), rows, openrasp_ini.slowquery_min_rows); ZVAL_STRING(plugin_message, message_str, 1); efree(message_str); openrasp_buildin_php_risk_handle(0, "sqlSlowQuery", 100, attack_params, plugin_message TSRMLS_CC); } zend_bool check_database_connection_username(INTERNAL_FUNCTION_PARAMETERS, init_connection_t connection_init_func, int enforce_policy) { static const std::multimap<std::string, std::string> database_username_blacklists = { {"mysql", "root"}, {"mssql", "sa"}, {"pgsql", "postgres"}, {"oci", "dbsnmp"}, {"oci", "sysman"}, {"oci", "system"}, {"oci", "sys"} }; sql_connection_entry conn_entry; char *check_message = nullptr; zend_bool need_block= 0; connection_init_func(INTERNAL_FUNCTION_PARAM_PASSTHRU, &conn_entry); if (conn_entry.server && conn_entry.username && conn_entry.host) { auto pos = database_username_blacklists.equal_range(std::string(conn_entry.server)); while (pos.first != pos.second) { if (std::string(conn_entry.username) == pos.first->second) { spprintf(&check_message, 0, _("Connecting to a %s instance using the high privileged account: %s - (%s:%d)"), conn_entry.server, conn_entry.username, conn_entry.host, conn_entry.port); break; } pos.first++; } if (check_message) { if (enforce_policy) { connection_via_default_username_policy(check_message, &conn_entry TSRMLS_CC); need_block = 1; } else { ulong connection_hash = zend_inline_hash_func(conn_entry.host, strlen(conn_entry.host)); openrasp_shared_alloc_lock(TSRMLS_C); if (!openrasp_shared_hash_exist(connection_hash, OPENRASP_LOG_G(formatted_date_suffix))) { connection_via_default_username_policy(check_message, &conn_entry TSRMLS_CC); } openrasp_shared_alloc_unlock(TSRMLS_C); } efree(check_message); } } if (conn_entry.host) { efree(conn_entry.host); } if (conn_entry.username) { efree(conn_entry.username); } return need_block; } /* check sql query clause */ void check_query_clause(INTERNAL_FUNCTION_PARAMETERS, char *server, int num) { if (openrasp_check_type_ignored(ZEND_STRL("sql") TSRMLS_CC)) { return; } int argc = MIN(num, ZEND_NUM_ARGS()); zval ***args = (zval ***)safe_emalloc(argc, sizeof(zval **), 0); if (argc == num && zend_get_parameters_array_ex(argc, args) == SUCCESS && Z_TYPE_PP(args[num - 1]) == IS_STRING) { zval *params; MAKE_STD_ZVAL(params); array_init(params); add_assoc_zval(params, "query", *args[num - 1]); Z_ADDREF_P(*args[num - 1]); add_assoc_string(params, "server", server, 1); check("sql", params TSRMLS_CC); } efree(args); } long fetch_rows_via_user_function(const char *f_name_str, zend_uint param_count, zval *params[] TSRMLS_DC) { zval function_name, retval; INIT_ZVAL(function_name); ZVAL_STRING(&function_name, f_name_str, 0); if (call_user_function(EG(function_table), nullptr, &function_name, &retval, param_count, params TSRMLS_CC) == SUCCESS && Z_TYPE(retval) == IS_LONG) { return Z_LVAL(retval); } return 0; } <commit_msg>[PHP]修改数据库连接hash计算方法(server-host:port)<commit_after>/* * Copyright 2017-2018 Baidu 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 "openrasp_hook.h" #include "openrasp_ini.h" #include <string> #include <map> extern "C" { #include "ext/pdo/php_pdo_driver.h" #include "zend_ini.h" #include "openrasp_shared_alloc.h" } /** * sql connection alarm */ static void connection_via_default_username_policy(char *check_message, sql_connection_entry *sql_connection_p TSRMLS_DC) { zval *policy_array = nullptr; MAKE_STD_ZVAL(policy_array); array_init(policy_array); add_assoc_string(policy_array, "message", check_message, 1); add_assoc_long(policy_array, "policy_id", 3006); zval *connection_params = nullptr; MAKE_STD_ZVAL(connection_params); array_init(connection_params); add_assoc_string(connection_params, "server", sql_connection_p->server, 1); add_assoc_string(connection_params, "host", sql_connection_p->host, 1); add_assoc_long(connection_params, "port", sql_connection_p->port); add_assoc_string(connection_params, "user", sql_connection_p->username, 1); add_assoc_zval(policy_array, "params", connection_params); policy_info(policy_array TSRMLS_CC); zval_ptr_dtor(&policy_array); } void slow_query_alarm(int rows TSRMLS_DC) { zval *attack_params = nullptr; MAKE_STD_ZVAL(attack_params); ZVAL_LONG(attack_params, rows); zval *plugin_message = nullptr; MAKE_STD_ZVAL(plugin_message); char *message_str = nullptr; spprintf(&message_str, 0, _("SQL slow query detected: selected %d rows, exceeding %d"), rows, openrasp_ini.slowquery_min_rows); ZVAL_STRING(plugin_message, message_str, 1); efree(message_str); openrasp_buildin_php_risk_handle(0, "sqlSlowQuery", 100, attack_params, plugin_message TSRMLS_CC); } zend_bool check_database_connection_username(INTERNAL_FUNCTION_PARAMETERS, init_connection_t connection_init_func, int enforce_policy) { static const std::multimap<std::string, std::string> database_username_blacklists = { {"mysql", "root"}, {"mssql", "sa"}, {"pgsql", "postgres"}, {"oci", "dbsnmp"}, {"oci", "sysman"}, {"oci", "system"}, {"oci", "sys"} }; sql_connection_entry conn_entry; char *check_message = nullptr; zend_bool need_block= 0; connection_init_func(INTERNAL_FUNCTION_PARAM_PASSTHRU, &conn_entry); if (conn_entry.server && conn_entry.username && conn_entry.host) { auto pos = database_username_blacklists.equal_range(std::string(conn_entry.server)); while (pos.first != pos.second) { if (std::string(conn_entry.username) == pos.first->second) { spprintf(&check_message, 0, _("Connecting to a %s instance using the high privileged account: %s - (%s:%d)"), conn_entry.server, conn_entry.username, conn_entry.host, conn_entry.port); break; } pos.first++; } if (check_message) { if (enforce_policy) { connection_via_default_username_policy(check_message, &conn_entry TSRMLS_CC); need_block = 1; } else { char *server_host_port = nullptr; int server_host_port_len = spprintf(&server_host_port, 0, "%s-%s:%d", conn_entry.server, conn_entry.host, conn_entry.port); ulong connection_hash = zend_inline_hash_func(server_host_port, server_host_port_len); openrasp_shared_alloc_lock(TSRMLS_C); if (!openrasp_shared_hash_exist(connection_hash, OPENRASP_LOG_G(formatted_date_suffix))) { connection_via_default_username_policy(check_message, &conn_entry TSRMLS_CC); } openrasp_shared_alloc_unlock(TSRMLS_C); efree(server_host_port); } efree(check_message); } } if (conn_entry.host) { efree(conn_entry.host); } if (conn_entry.username) { efree(conn_entry.username); } return need_block; } /* check sql query clause */ void check_query_clause(INTERNAL_FUNCTION_PARAMETERS, char *server, int num) { if (openrasp_check_type_ignored(ZEND_STRL("sql") TSRMLS_CC)) { return; } int argc = MIN(num, ZEND_NUM_ARGS()); zval ***args = (zval ***)safe_emalloc(argc, sizeof(zval **), 0); if (argc == num && zend_get_parameters_array_ex(argc, args) == SUCCESS && Z_TYPE_PP(args[num - 1]) == IS_STRING) { zval *params; MAKE_STD_ZVAL(params); array_init(params); add_assoc_zval(params, "query", *args[num - 1]); Z_ADDREF_P(*args[num - 1]); add_assoc_string(params, "server", server, 1); check("sql", params TSRMLS_CC); } efree(args); } long fetch_rows_via_user_function(const char *f_name_str, zend_uint param_count, zval *params[] TSRMLS_DC) { zval function_name, retval; INIT_ZVAL(function_name); ZVAL_STRING(&function_name, f_name_str, 0); if (call_user_function(EG(function_table), nullptr, &function_name, &retval, param_count, params TSRMLS_CC) == SUCCESS && Z_TYPE(retval) == IS_LONG) { return Z_LVAL(retval); } return 0; } <|endoftext|>
<commit_before>#include "audio_player.h" #include <QtMath> #include <QDebug> //Get the percentage downloaded of an internet file stream, or the buffer level when streaming in blocks. //QWORD len=BASS_StreamGetFilePosition(stream, BASS_FILEPOS_END); // file/buffer length //QWORD buf=BASS_StreamGetFilePosition(stream, BASS_FILEPOS_BUFFER); // buffer level //float progress=buf*100.0/len; // percentage of buffer filled //void endTrackSync(HSYNC handle, DWORD channel, DWORD data, void * user) void endTrackSync(HSYNC, DWORD, DWORD, void * user) { // BASS_ChannelStop(channel); // BASS_ChannelRemoveSync(channel, handle); AudioPlayer * player = static_cast<AudioPlayer *>(user); emit player -> playbackEnded(); } AudioPlayer::AudioPlayer(QObject * parent) : QObject(parent) { qRegisterMetaType<AudioPlayer::MediaStatus>("MediaStatus"); qRegisterMetaType<AudioPlayer::MediaState>("MediaState"); // cheat for cross treadhing connect(this, SIGNAL(playbackEnded()), this, SLOT(endOfPlayback())); duration = -1; notifyInterval = 100; volumeVal = 1.0; spectrumHeight = 0; spectrumBandsCount = 28; currentState = StoppedState; if (HIWORD(BASS_GetVersion()) != BASSVERSION) { throw "An incorrect version of BASS.DLL was loaded"; } if (HIWORD(BASS_FX_GetVersion()) != BASSVERSION) { throw "An incorrect version of BASS_FX.DLL was loaded"; } if (!BASS_Init(-1, 44100, 0, NULL, NULL)) qDebug() << "Init error: " << BASS_ErrorGetCode(); // throw "Cannot initialize device"; /////////////////////////////////////////////// /// load plugins /////////////////////////////////////////////// QFileInfoList list = QDir(QCoreApplication::applicationDirPath() + "/libs/bass/plugins").entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden); foreach(QFileInfo file, list) { /*int res = */BASS_PluginLoad(file.filePath().toLatin1(), 0); // if (res == 0) // qDebug() << file.filePath() << BASS_ErrorGetCode(); // else // qDebug() << file.filePath() << res; } /////////////////////////////////////////////// notifyTimer = new NotifyTimer(this); connect(notifyTimer, SIGNAL(timeout()), this, SLOT(signalUpdate())); connect(notifyTimer, SIGNAL(started()), this, SLOT(started())); connect(notifyTimer, SIGNAL(stoped()), this, SLOT(stoped())); spectrumTimer = new NotifyTimer(this); connect(spectrumTimer, SIGNAL(timeout()), this, SLOT(calcSpectrum())); spectrumTimer -> start(25); //40 Hz } AudioPlayer::~AudioPlayer() { BASS_PluginFree(0); notifyTimer -> stop(); delete notifyTimer; spectrumTimer -> stop(); delete spectrumTimer; } int AudioPlayer::getPosition() const { return BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetPosition(chan, BASS_POS_BYTE)) * 1000; } int AudioPlayer::getDuration() const { return duration; } int AudioPlayer::getNotifyInterval() { return notifyInterval; } void AudioPlayer::setNotifyInterval(signed int milis) { notifyInterval = milis; if (notifyTimer -> isActive()) notifyTimer -> setInterval(notifyInterval); } void AudioPlayer::setMedia(QUrl mediaPath) { mediaUri = mediaPath; } void AudioPlayer::setSpectrumBandsCount(int bandsCount) { spectrumBandsCount = bandsCount; } void AudioPlayer::setSpectrumHeight(int newHeight) { spectrumHeight = newHeight; } AudioPlayer::MediaState AudioPlayer::state() const { return currentState; } bool AudioPlayer::isPlayed() const { return currentState == PlayingState; } bool AudioPlayer::isPaused() const { return currentState == PausedState; } bool AudioPlayer::isStoped() const { return currentState == StoppedState; } //////////////////////////////////////////////////////////////////////// /// PRIVATE //////////////////////////////////////////////////////////////////////// int AudioPlayer::openRemoteChannel(QString path) { BASS_ChannelStop(chan); chan = BASS_StreamCreateURL(path.toStdWString().c_str(), 0, BASS_SAMPLE_FLOAT, NULL, 0); // BASS_Encode_Start(channel, "output.wav", BASS_ENCODE_PCM, NULL, 0); // BASS_Encode_StartCAFile(channel, 'mp4f', 'aac ', 0, 128000, "output.mp4"); // only macos // BASS_Encode_StartCAFile(channel, 'm4af', 'alac', 0, 0, "output.m4a"); // only macos if (!chan) { int status = BASS_ErrorGetCode(); if (status == BASS_ERROR_FILEOPEN)// || status == BASS_ERROR_NONET) emit remoteUnprocessed(); qDebug() << "Can't play stream" << BASS_ErrorGetCode() << path.toUtf8(); } return chan; } int AudioPlayer::openChannel(QString path) { BASS_ChannelStop(chan); if (!(chan = BASS_StreamCreateFile(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_FLOAT | BASS_ASYNCFILE))) // if (!(stream = BASS_StreamCreateFile(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_LOOP)) // && !(chan = BASS_MusicLoad(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP | BASS_MUSIC_POSRESET | BASS_MUSIC_STOPBACK | BASS_STREAM_PRESCAN | BASS_MUSIC_AUTOFREE, 1))) qDebug() << "Can't play file " << BASS_ErrorGetCode() << path.toUtf8(); return chan; } void AudioPlayer::closeChannel() { BASS_ChannelStop(chan); BASS_ChannelRemoveSync(chan, syncHandle); BASS_StreamFree(chan); // BASS_MusicFree(chan); } //////////////////////////////////////////////////////////////////////// /// SLOTS //////////////////////////////////////////////////////////////////////// void AudioPlayer::started() { currentState = PlayingState; emit stateChanged(PlayingState); } void AudioPlayer::stoped() { currentState = StoppedState; } void AudioPlayer::signalUpdate() { int curr_pos = BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetPosition(chan, BASS_POS_BYTE)) * 1000; emit positionChanged(curr_pos); } void AudioPlayer::calcSpectrum() { if (spectrumHeight > 0) emit spectrumChanged(getSpectrum()); } void AudioPlayer::slidePosForward() { if (currentState == PlayingState || currentState == PausedState) { int dur = getDuration(); int pos = getPosition() + dur / 10; if (pos < dur) setPosition(pos); } } void AudioPlayer::slidePosBackward() { if (currentState == PlayingState || currentState == PausedState) { int pos = getPosition() - (getDuration() / 10); if (pos < 0) pos = 0; setPosition(pos); } } //0 to 10000 void AudioPlayer::setChannelVolume(int val) { volumeVal = val > 0 ? (val / 10000.0) : 0; BASS_ChannelSetAttribute(chan, BASS_ATTRIB_VOL, volumeVal); emit volumeChanged(val); } void AudioPlayer::slideVolForward() { int newVolLevel = getVolume() + 1000; if (newVolLevel > 10000) newVolLevel = 10000; setChannelVolume(newVolLevel); } void AudioPlayer::slideVolBackward() { int newVolLevel = getVolume() - 1000; if (newVolLevel < 0) newVolLevel = 0; setChannelVolume(newVolLevel); } // 0 to 10000 void AudioPlayer::setVolume(int val) { BASS_SetConfig(BASS_CONFIG_GVOL_STREAM, val); emit volumeChanged(val); } float AudioPlayer::getSize() const { return size; } int AudioPlayer::getVolume() const { return volumeVal * 10000; } //from 0 to 1 float AudioPlayer::getRemoteFileDownloadPosition() { if (size == -1) { prevDownloadPos = 0; DWORD len = BASS_StreamGetFilePosition(chan, BASS_FILEPOS_END); size = len + BASS_StreamGetFilePosition(chan, BASS_FILEPOS_START); } if (prevDownloadPos != 1) { float currDownloadPos = ((BASS_StreamGetFilePosition(chan, BASS_FILEPOS_DOWNLOAD)) / size); if (prevDownloadPos == currDownloadPos && currDownloadPos > 0.8) prevDownloadPos = 1; else prevDownloadPos = currDownloadPos; } return prevDownloadPos; } QHash<QString, QString> AudioPlayer::getRemoteFileInfo(QString uri) { QHash<QString, QString> ret; int chUID = BASS_StreamCreateURL(uri.toStdWString().c_str(), 0, 0, NULL, 0); if (!chUID) return ret; float time = BASS_ChannelBytes2Seconds(chUID, BASS_ChannelGetLength(chUID, BASS_POS_BYTE)); // playback duration DWORD len = BASS_StreamGetFilePosition(chUID, BASS_FILEPOS_END); // file length int bitrate = (len / (125 * time) + 0.5); // average bitrate (Kbps) ret.insert("duration", Duration::fromSeconds(time)); BASS_CHANNELINFO info; if (BASS_ChannelGetInfo(chUID, &info)) { int size = len + BASS_StreamGetFilePosition(chUID, BASS_FILEPOS_START); ret.insert("info", Format::toInfo(Format::toUnits(size), bitrate, info.freq, info.chans)); } BASS_StreamFree(chUID); return ret; } float AudioPlayer::getBpmValue(QUrl uri) { int cochan; if (uri.isLocalFile()) cochan = BASS_StreamCreateFile(false, uri.toLocalFile().toStdWString().c_str(), 0, 0, BASS_SAMPLE_FLOAT | BASS_STREAM_DECODE | BASS_STREAM_PRESCAN | BASS_SAMPLE_MONO); else cochan = BASS_StreamCreateURL(uri.toString().toStdWString().c_str(), 0, BASS_SAMPLE_FLOAT | BASS_STREAM_DECODE | BASS_SAMPLE_MONO, NULL, 0); if (cochan) { int playBackDuration = BASS_ChannelBytes2Seconds(cochan, BASS_ChannelGetLength(cochan, BASS_POS_BYTE)); BASS_ChannelSetAttribute(cochan, BASS_ATTRIB_VOL, 0); qDebug() << playBackDuration; return BASS_FX_BPM_DecodeGet(cochan, 0, 60, 0, //MAKEWORD(60, 230), BASS_FX_FREESOURCE, //BASS_FX_BPM_BKGRND // BASS_FX_BPM_MULT2 NULL, NULL); // float last = BASS_FX_BPM_DecodeGet(cochan, // 0.0, // playBackDuration, // MAKELONG(85, 90), // BASS_FX_FREESOURCE, //BASS_FX_BPM_BKGRND // BASS_FX_BPM_MULT2 // NULL, NULL); // qDebug() << last << " " << first; } else return 0; } QList<int> AudioPlayer::getSpectrum() { float fft[1024]; BASS_ChannelGetData(chan, fft, BASS_DATA_FFT2048); QList<int> res; int b0 = 0, x, y; for (x = 0; x < spectrumBandsCount; x++) { float peak = 0; int b1 = qPow(2, x * 10.0 / (spectrumBandsCount - 1)); if (b1 > 1023) b1 = 1023; if (b1 <= b0) b1 = b0 + 1; // make sure it uses at least 1 FFT bin for (; b0 < b1; b0++) if (peak < fft[1 + b0]) peak = fft[1 + b0]; y = qSqrt(peak) * 3 * spectrumHeight - 4; // scale it (sqrt to make low values more visible) if (y > spectrumHeight) y = spectrumHeight; // cap it res.append(y); } return res; } //////////////////////////////////////////////////////////////////////// void AudioPlayer::play() { if (currentState == PausedState) { resume(); } else { closeChannel(); if (mediaUri.isEmpty()) { emit mediaStatusChanged(NoMedia); } else { qDebug() << mediaUri.toString(); if (mediaUri.isLocalFile()) { openChannel(mediaUri.toLocalFile()); size = 0; prevDownloadPos = 1; } else { openRemoteChannel(mediaUri.toString()); size = -1; } if (chan) { BASS_ChannelSetAttribute(chan, BASS_ATTRIB_VOL, volumeVal); duration = BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetLength(chan, BASS_POS_BYTE)) * 1000; durationChanged(duration); BASS_ChannelPlay(chan, true); notifyTimer -> start(notifyInterval); //TODO: remove sync and check end of file by timer syncHandle = BASS_ChannelSetSync(chan, BASS_SYNC_END, 0, &endTrackSync, this); // BASS_SYNC_DOWNLOAD } else { qDebug() << "Can't play file"; } } } } void AudioPlayer::pause() { notifyTimer -> stop(); BASS_ChannelPause(chan); emit stateChanged(PausedState); currentState = PausedState; } void AudioPlayer::resume() { if (!BASS_ChannelPlay(chan, false)) { emit mediaStatusChanged(StalledMedia); qDebug() << "Error resuming"; } else { notifyTimer -> start(notifyInterval); } } void AudioPlayer::stop() { closeChannel(); notifyTimer -> stop(); emit stateChanged(StoppedState); } void AudioPlayer::endOfPlayback() { stop(); closeChannel(); emit mediaStatusChanged(EndOfMedia); } void AudioPlayer::setPosition(int position) { BASS_ChannelSetPosition(chan, BASS_ChannelSeconds2Bytes(chan, position / 1000.0), BASS_POS_BYTE); } <commit_msg>improve spectrum delay<commit_after>#include "audio_player.h" #include <QtMath> #include <QDebug> //Get the percentage downloaded of an internet file stream, or the buffer level when streaming in blocks. //QWORD len=BASS_StreamGetFilePosition(stream, BASS_FILEPOS_END); // file/buffer length //QWORD buf=BASS_StreamGetFilePosition(stream, BASS_FILEPOS_BUFFER); // buffer level //float progress=buf*100.0/len; // percentage of buffer filled //void endTrackSync(HSYNC handle, DWORD channel, DWORD data, void * user) void endTrackSync(HSYNC, DWORD, DWORD, void * user) { // BASS_ChannelStop(channel); // BASS_ChannelRemoveSync(channel, handle); AudioPlayer * player = static_cast<AudioPlayer *>(user); emit player -> playbackEnded(); } AudioPlayer::AudioPlayer(QObject * parent) : QObject(parent) { qRegisterMetaType<AudioPlayer::MediaStatus>("MediaStatus"); qRegisterMetaType<AudioPlayer::MediaState>("MediaState"); // cheat for cross treadhing connect(this, SIGNAL(playbackEnded()), this, SLOT(endOfPlayback())); duration = -1; notifyInterval = 100; volumeVal = 1.0; spectrumHeight = 0; spectrumBandsCount = 28; currentState = StoppedState; if (HIWORD(BASS_GetVersion()) != BASSVERSION) { throw "An incorrect version of BASS.DLL was loaded"; } if (HIWORD(BASS_FX_GetVersion()) != BASSVERSION) { throw "An incorrect version of BASS_FX.DLL was loaded"; } if (!BASS_Init(-1, 44100, 0, NULL, NULL)) qDebug() << "Init error: " << BASS_ErrorGetCode(); // throw "Cannot initialize device"; /////////////////////////////////////////////// /// load plugins /////////////////////////////////////////////// QFileInfoList list = QDir(QCoreApplication::applicationDirPath() + "/libs/bass/plugins").entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden); foreach(QFileInfo file, list) { /*int res = */BASS_PluginLoad(file.filePath().toLatin1(), 0); // if (res == 0) // qDebug() << file.filePath() << BASS_ErrorGetCode(); // else // qDebug() << file.filePath() << res; } /////////////////////////////////////////////// notifyTimer = new NotifyTimer(this); connect(notifyTimer, SIGNAL(timeout()), this, SLOT(signalUpdate())); connect(notifyTimer, SIGNAL(started()), this, SLOT(started())); connect(notifyTimer, SIGNAL(stoped()), this, SLOT(stoped())); spectrumTimer = new NotifyTimer(this); connect(spectrumTimer, SIGNAL(timeout()), this, SLOT(calcSpectrum())); spectrumTimer -> start(25); //40 Hz } AudioPlayer::~AudioPlayer() { BASS_PluginFree(0); notifyTimer -> stop(); delete notifyTimer; spectrumTimer -> stop(); delete spectrumTimer; } int AudioPlayer::getPosition() const { return BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetPosition(chan, BASS_POS_BYTE)) * 1000; } int AudioPlayer::getDuration() const { return duration; } int AudioPlayer::getNotifyInterval() { return notifyInterval; } void AudioPlayer::setNotifyInterval(signed int milis) { notifyInterval = milis; if (notifyTimer -> isActive()) notifyTimer -> setInterval(notifyInterval); } void AudioPlayer::setMedia(QUrl mediaPath) { mediaUri = mediaPath; } void AudioPlayer::setSpectrumBandsCount(int bandsCount) { spectrumBandsCount = bandsCount; } void AudioPlayer::setSpectrumHeight(int newHeight) { spectrumHeight = newHeight; } AudioPlayer::MediaState AudioPlayer::state() const { return currentState; } bool AudioPlayer::isPlayed() const { return currentState == PlayingState; } bool AudioPlayer::isPaused() const { return currentState == PausedState; } bool AudioPlayer::isStoped() const { return currentState == StoppedState; } //////////////////////////////////////////////////////////////////////// /// PRIVATE //////////////////////////////////////////////////////////////////////// int AudioPlayer::openRemoteChannel(QString path) { BASS_ChannelStop(chan); chan = BASS_StreamCreateURL(path.toStdWString().c_str(), 0, BASS_SAMPLE_FLOAT, NULL, 0); // BASS_Encode_Start(channel, "output.wav", BASS_ENCODE_PCM, NULL, 0); // BASS_Encode_StartCAFile(channel, 'mp4f', 'aac ', 0, 128000, "output.mp4"); // only macos // BASS_Encode_StartCAFile(channel, 'm4af', 'alac', 0, 0, "output.m4a"); // only macos if (!chan) { int status = BASS_ErrorGetCode(); if (status == BASS_ERROR_FILEOPEN)// || status == BASS_ERROR_NONET) emit remoteUnprocessed(); qDebug() << "Can't play stream" << BASS_ErrorGetCode() << path.toUtf8(); } return chan; } int AudioPlayer::openChannel(QString path) { BASS_ChannelStop(chan); if (!(chan = BASS_StreamCreateFile(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_FLOAT | BASS_ASYNCFILE))) // if (!(stream = BASS_StreamCreateFile(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_LOOP)) // && !(chan = BASS_MusicLoad(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP | BASS_MUSIC_POSRESET | BASS_MUSIC_STOPBACK | BASS_STREAM_PRESCAN | BASS_MUSIC_AUTOFREE, 1))) qDebug() << "Can't play file " << BASS_ErrorGetCode() << path.toUtf8(); return chan; } void AudioPlayer::closeChannel() { BASS_ChannelStop(chan); BASS_ChannelRemoveSync(chan, syncHandle); BASS_StreamFree(chan); // BASS_MusicFree(chan); } //////////////////////////////////////////////////////////////////////// /// SLOTS //////////////////////////////////////////////////////////////////////// void AudioPlayer::started() { currentState = PlayingState; emit stateChanged(PlayingState); } void AudioPlayer::stoped() { currentState = StoppedState; } void AudioPlayer::signalUpdate() { int curr_pos = BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetPosition(chan, BASS_POS_BYTE)) * 1000; emit positionChanged(curr_pos); } void AudioPlayer::calcSpectrum() { if (spectrumHeight > 0) { if (currentState == StoppedState) { QVector<int> l; emit spectrumChanged(l.fill(-2, spectrumBandsCount).toList()); } else emit spectrumChanged(getSpectrum()); } } void AudioPlayer::slidePosForward() { if (currentState == PlayingState || currentState == PausedState) { int dur = getDuration(); int pos = getPosition() + dur / 10; if (pos < dur) setPosition(pos); } } void AudioPlayer::slidePosBackward() { if (currentState == PlayingState || currentState == PausedState) { int pos = getPosition() - (getDuration() / 10); if (pos < 0) pos = 0; setPosition(pos); } } //0 to 10000 void AudioPlayer::setChannelVolume(int val) { volumeVal = val > 0 ? (val / 10000.0) : 0; BASS_ChannelSetAttribute(chan, BASS_ATTRIB_VOL, volumeVal); emit volumeChanged(val); } void AudioPlayer::slideVolForward() { int newVolLevel = getVolume() + 1000; if (newVolLevel > 10000) newVolLevel = 10000; setChannelVolume(newVolLevel); } void AudioPlayer::slideVolBackward() { int newVolLevel = getVolume() - 1000; if (newVolLevel < 0) newVolLevel = 0; setChannelVolume(newVolLevel); } // 0 to 10000 void AudioPlayer::setVolume(int val) { BASS_SetConfig(BASS_CONFIG_GVOL_STREAM, val); emit volumeChanged(val); } float AudioPlayer::getSize() const { return size; } int AudioPlayer::getVolume() const { return volumeVal * 10000; } //from 0 to 1 float AudioPlayer::getRemoteFileDownloadPosition() { if (size == -1) { prevDownloadPos = 0; DWORD len = BASS_StreamGetFilePosition(chan, BASS_FILEPOS_END); size = len + BASS_StreamGetFilePosition(chan, BASS_FILEPOS_START); } if (prevDownloadPos != 1) { float currDownloadPos = ((BASS_StreamGetFilePosition(chan, BASS_FILEPOS_DOWNLOAD)) / size); if (prevDownloadPos == currDownloadPos && currDownloadPos > 0.8) prevDownloadPos = 1; else prevDownloadPos = currDownloadPos; } return prevDownloadPos; } QHash<QString, QString> AudioPlayer::getRemoteFileInfo(QString uri) { QHash<QString, QString> ret; int chUID = BASS_StreamCreateURL(uri.toStdWString().c_str(), 0, 0, NULL, 0); if (!chUID) return ret; float time = BASS_ChannelBytes2Seconds(chUID, BASS_ChannelGetLength(chUID, BASS_POS_BYTE)); // playback duration DWORD len = BASS_StreamGetFilePosition(chUID, BASS_FILEPOS_END); // file length int bitrate = (len / (125 * time) + 0.5); // average bitrate (Kbps) ret.insert("duration", Duration::fromSeconds(time)); BASS_CHANNELINFO info; if (BASS_ChannelGetInfo(chUID, &info)) { int size = len + BASS_StreamGetFilePosition(chUID, BASS_FILEPOS_START); ret.insert("info", Format::toInfo(Format::toUnits(size), bitrate, info.freq, info.chans)); } BASS_StreamFree(chUID); return ret; } float AudioPlayer::getBpmValue(QUrl uri) { int cochan; if (uri.isLocalFile()) cochan = BASS_StreamCreateFile(false, uri.toLocalFile().toStdWString().c_str(), 0, 0, BASS_SAMPLE_FLOAT | BASS_STREAM_DECODE | BASS_STREAM_PRESCAN | BASS_SAMPLE_MONO); else cochan = BASS_StreamCreateURL(uri.toString().toStdWString().c_str(), 0, BASS_SAMPLE_FLOAT | BASS_STREAM_DECODE | BASS_SAMPLE_MONO, NULL, 0); if (cochan) { int playBackDuration = BASS_ChannelBytes2Seconds(cochan, BASS_ChannelGetLength(cochan, BASS_POS_BYTE)); BASS_ChannelSetAttribute(cochan, BASS_ATTRIB_VOL, 0); qDebug() << playBackDuration; return BASS_FX_BPM_DecodeGet(cochan, 0, 60, 0, //MAKEWORD(60, 230), BASS_FX_FREESOURCE, //BASS_FX_BPM_BKGRND // BASS_FX_BPM_MULT2 NULL, NULL); // float last = BASS_FX_BPM_DecodeGet(cochan, // 0.0, // playBackDuration, // MAKELONG(85, 90), // BASS_FX_FREESOURCE, //BASS_FX_BPM_BKGRND // BASS_FX_BPM_MULT2 // NULL, NULL); // qDebug() << last << " " << first; } else return 0; } QList<int> AudioPlayer::getSpectrum() { float fft[1024]; BASS_ChannelGetData(chan, fft, BASS_DATA_FFT2048); QList<int> res; int b0 = 0, x, y; for (x = 0; x < spectrumBandsCount; x++) { float peak = 0; int b1 = qPow(2, x * 10.0 / (spectrumBandsCount - 1)); if (b1 > 1023) b1 = 1023; if (b1 <= b0) b1 = b0 + 1; // make sure it uses at least 1 FFT bin for (; b0 < b1; b0++) if (peak < fft[1 + b0]) peak = fft[1 + b0]; y = qSqrt(peak) * 3 * spectrumHeight - 4; // scale it (sqrt to make low values more visible) if (y > spectrumHeight) y = spectrumHeight; // cap it res.append(y); } return res; } //////////////////////////////////////////////////////////////////////// void AudioPlayer::play() { if (currentState == PausedState) { resume(); } else { closeChannel(); if (mediaUri.isEmpty()) { emit mediaStatusChanged(NoMedia); } else { qDebug() << mediaUri.toString(); if (mediaUri.isLocalFile()) { openChannel(mediaUri.toLocalFile()); size = 0; prevDownloadPos = 1; } else { openRemoteChannel(mediaUri.toString()); size = -1; } if (chan) { BASS_ChannelSetAttribute(chan, BASS_ATTRIB_VOL, volumeVal); duration = BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetLength(chan, BASS_POS_BYTE)) * 1000; durationChanged(duration); BASS_ChannelPlay(chan, true); notifyTimer -> start(notifyInterval); //TODO: remove sync and check end of file by timer syncHandle = BASS_ChannelSetSync(chan, BASS_SYNC_END, 0, &endTrackSync, this); // BASS_SYNC_DOWNLOAD } else { qDebug() << "Can't play file"; } } } } void AudioPlayer::pause() { notifyTimer -> stop(); BASS_ChannelPause(chan); emit stateChanged(PausedState); currentState = PausedState; } void AudioPlayer::resume() { if (!BASS_ChannelPlay(chan, false)) { emit mediaStatusChanged(StalledMedia); qDebug() << "Error resuming"; } else { notifyTimer -> start(notifyInterval); } } void AudioPlayer::stop() { closeChannel(); notifyTimer -> stop(); emit stateChanged(StoppedState); } void AudioPlayer::endOfPlayback() { stop(); closeChannel(); emit mediaStatusChanged(EndOfMedia); } void AudioPlayer::setPosition(int position) { BASS_ChannelSetPosition(chan, BASS_ChannelSeconds2Bytes(chan, position / 1000.0), BASS_POS_BYTE); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: labelexp.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2003-04-17 15:25:22 $ * * 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 #ifndef _COM_SUN_STAR_TEXT_XTEXTFIELDSSUPPLIER_HPP_ #include <com/sun/star/text/XTextFieldsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_ #include <com/sun/star/util/XRefreshable.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _LABFMT_HXX #include <labfmt.hxx> #endif #ifndef _UNOTOOLS_HXX #include <unotools.hxx> #endif #ifndef _UNOATXT_HXX //autogen wg. SwXAutoTextEntry #include <unoatxt.hxx> #endif #ifndef _UNOOBJ_HXX // #include <unoobj.hxx> #endif #ifndef _UNOPRNMS_HXX // #include <unoprnms.hxx> #endif using namespace ::com::sun::star; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace com::sun::star::uno; using namespace ::comphelper; using namespace ::rtl; #define C2U(char) rtl::OUString::createFromAscii(char) /* -----------------08.07.99 15:15------------------- --------------------------------------------------*/ void SwVisitingCardPage::InitFrameControl() { Link aLink(LINK(this, SwVisitingCardPage, FrameControlInitializedHdl)); pExampleFrame = new SwOneExampleFrame( aExampleWIN, EX_SHOW_BUSINESS_CARDS, &aLink ); uno::Reference< lang::XMultiServiceFactory > xMgr = getProcessServiceFactory(); //now the AutoText ListBoxes have to be filled uno::Reference< uno::XInterface > xAText = xMgr->createInstance( C2U("com.sun.star.text.AutoTextContainer") ); _xAutoText = uno::Reference< container::XNameAccess >(xAText, uno::UNO_QUERY); uno::Sequence<OUString> aNames = _xAutoText->getElementNames(); const OUString* pGroups = aNames.getConstArray(); OUString uTitleName( C2U(SW_PROP_NAME_STR(UNO_NAME_TITLE)) ); for(sal_uInt16 i = 0; i < aNames.getLength(); i++) { uno::Any aGroup = _xAutoText->getByName(pGroups[i]); uno::Reference< text::XAutoTextGroup > xGroup; aGroup >>= xGroup; uno::Reference< container::XIndexAccess > xIdxAcc(xGroup, uno::UNO_QUERY); try { if(!xIdxAcc.is() || xIdxAcc->getCount()) { uno::Reference< beans::XPropertySet > xPrSet(xGroup, uno::UNO_QUERY); uno::Any aTitle = xPrSet->getPropertyValue( uTitleName ); OUString uTitle; aTitle >>= uTitle; String sGroup(pGroups[i]); sal_uInt16 nEntry = aAutoTextGroupLB.InsertEntry(uTitle); aAutoTextGroupLB.SetEntryData(nEntry, new String(sGroup)); } } catch(Exception&) { } } if(aAutoTextGroupLB.GetEntryCount()) { if(LISTBOX_ENTRY_NOTFOUND == aAutoTextGroupLB.GetSelectEntryPos()) aAutoTextGroupLB.SelectEntryPos(0); String sCurGroupName( *(String*)aAutoTextGroupLB.GetEntryData(aAutoTextGroupLB.GetSelectEntryPos())); if(_xAutoText->hasByName(sCurGroupName)) { uno::Any aGroup = _xAutoText->getByName(sCurGroupName); try { uno::Reference< text::XAutoTextGroup > xGroup; aGroup >>= xGroup; uno::Sequence< OUString > aBlockNames = xGroup->getElementNames(); uno::Sequence< OUString > aTitles = xGroup->getTitles() ; SetUserData( aBlockNames.getLength(), aTitles.getConstArray(), aBlockNames.getConstArray() ); } catch( uno::RuntimeException& ) { // we'll be her if path settings were wrong } } } } /* -----------------01.10.99 13:19------------------- --------------------------------------------------*/ IMPL_LINK( SwVisitingCardPage, FrameControlInitializedHdl, void*, EMPTYARG ) { SvLBoxEntry* pSel = aAutoTextLB.FirstSelected(); String sEntry; if( pSel ) sEntry = *(String*)pSel->GetUserData(); uno::Reference< text::XTextCursor > & xCrsr = pExampleFrame->GetTextCursor(); OUString uEntry(sEntry); if(LISTBOX_ENTRY_NOTFOUND != aAutoTextGroupLB.GetSelectEntryPos()) { String sGroup( *(String*)aAutoTextGroupLB.GetEntryData( aAutoTextGroupLB.GetSelectEntryPos() ) ); uno::Any aGroup = _xAutoText->getByName(sGroup); uno::Reference< text::XAutoTextGroup > xGroup; aGroup >>= xGroup; if( sEntry.Len() && xGroup->hasByName( uEntry ) ) { uno::Any aEntry(xGroup->getByName(uEntry)); uno::Reference< text::XAutoTextEntry > xEntry; aEntry >>= xEntry; if(xEntry.is()) { uno::Reference< text::XTextRange > xRange(xCrsr, uno::UNO_QUERY); xEntry->applyTo(xRange); } UpdateFields(); } } return 0; } /* -----------------22.07.99 11:06------------------- --------------------------------------------------*/ IMPL_LINK( SwVisitingCardPage, AutoTextSelectHdl, void*, pBox ) { if(_xAutoText.is()) { if( &aAutoTextGroupLB == pBox ) { String sGroup( *(String*)aAutoTextGroupLB.GetEntryData( aAutoTextGroupLB.GetSelectEntryPos())); uno::Any aGroup = _xAutoText->getByName(sGroup); uno::Reference< text::XAutoTextGroup > xGroup; aGroup >>= xGroup; ClearUserData(); aAutoTextLB.Clear(); uno::Sequence<OUString> aBlockNames = xGroup->getElementNames(); uno::Sequence< OUString > aTitles = xGroup->getTitles() ; SetUserData( aBlockNames.getLength(), aTitles.getConstArray(), aBlockNames.getConstArray() ); } if(pExampleFrame->IsInitialized()) pExampleFrame->ClearDocument( TRUE ); } return 0; } /* -----------------01.10.99 11:59------------------- --------------------------------------------------*/ void SwVisitingCardPage::UpdateFields() { uno::Reference< frame::XModel > xModel; if( pExampleFrame && (xModel = pExampleFrame->GetModel()).is()) { SwLabDlg::UpdateFieldInformation(xModel, aLabItem); } } /* -----------------01.10.99 15:16------------------- --------------------------------------------------*/ void SwLabDlg::UpdateFieldInformation(uno::Reference< frame::XModel > & xModel, const SwLabItem& rItem) { uno::Reference< text::XTextFieldsSupplier > xFlds(xModel, uno::UNO_QUERY); uno::Reference< container::XNameAccess > xFldMasters = xFlds->getTextFieldMasters(); static const struct _SwLabItemMap { const char* pName; rtl::OUString SwLabItem:: *pValue; } aArr[] = { { "BC_PRIV_FIRSTNAME" , &SwLabItem::aPrivFirstName }, { "BC_PRIV_NAME" , &SwLabItem::aPrivName }, { "BC_PRIV_INITIALS" , &SwLabItem::aPrivShortCut }, { "BC_PRIV_FIRSTNAME_2", &SwLabItem::aPrivFirstName2 }, { "BC_PRIV_NAME_2" , &SwLabItem::aPrivName2 }, { "BC_PRIV_INITIALS_2" , &SwLabItem::aPrivShortCut2 }, { "BC_PRIV_STREET" , &SwLabItem::aPrivStreet }, { "BC_PRIV_ZIP" , &SwLabItem::aPrivZip }, { "BC_PRIV_CITY" , &SwLabItem::aPrivCity }, { "BC_PRIV_COUNTRY" , &SwLabItem::aPrivCountry }, { "BC_PRIV_STATE" , &SwLabItem::aPrivState }, { "BC_PRIV_TITLE" , &SwLabItem::aPrivTitle }, { "BC_PRIV_PROFESSION" , &SwLabItem::aPrivProfession }, { "BC_PRIV_PHONE" , &SwLabItem::aPrivPhone }, { "BC_PRIV_MOBILE" , &SwLabItem::aPrivMobile }, { "BC_PRIV_FAX" , &SwLabItem::aPrivFax }, { "BC_PRIV_WWW" , &SwLabItem::aPrivWWW }, { "BC_PRIV_MAIL" , &SwLabItem::aPrivMail }, { "BC_COMP_COMPANY" , &SwLabItem::aCompCompany }, { "BC_COMP_COMPANYEXT" , &SwLabItem::aCompCompanyExt }, { "BC_COMP_SLOGAN" , &SwLabItem::aCompSlogan }, { "BC_COMP_STREET" , &SwLabItem::aCompStreet }, { "BC_COMP_ZIP" , &SwLabItem::aCompZip }, { "BC_COMP_CITY" , &SwLabItem::aCompCity }, { "BC_COMP_COUNTRY" , &SwLabItem::aCompCountry }, { "BC_COMP_STATE" , &SwLabItem::aCompState }, { "BC_COMP_POSITION" , &SwLabItem::aCompPosition }, { "BC_COMP_PHONE" , &SwLabItem::aCompPhone }, { "BC_COMP_MOBILE" , &SwLabItem::aCompMobile }, { "BC_COMP_FAX" , &SwLabItem::aCompFax }, { "BC_COMP_WWW" , &SwLabItem::aCompWWW }, { "BC_COMP_MAIL" , &SwLabItem::aCompMail }, { 0, 0 } }; try { String sFldName( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "com.sun.star.text.FieldMaster.User." ))); OUString uCntName( C2U( SW_PROP_NAME_STR(UNO_NAME_CONTENT ))); for( const _SwLabItemMap* p = aArr; p->pName; ++p ) { String sCurFldName( sFldName ); sCurFldName.AppendAscii( p->pName ); OUString uFldName( sCurFldName ); if( xFldMasters->hasByName( uFldName )) { uno::Any aFirstName = xFldMasters->getByName( uFldName ); uno::Reference< beans::XPropertySet > xFld; aFirstName >>= xFld; uno::Any aContent; aContent <<= rItem.*p->pValue; xFld->setPropertyValue( uCntName, aContent ); } } } catch( uno::RuntimeException&) { // } uno::Reference< container::XEnumerationAccess > xFldAcc = xFlds->getTextFields(); uno::Reference< util::XRefreshable > xRefresh(xFldAcc, uno::UNO_QUERY); xRefresh->refresh(); } <commit_msg>INTEGRATION: CWS tune03 (1.4.580); FILE MERGED 2004/07/19 19:11:11 mhu 1.4.580.1: #i29979# Added SW_DLLPUBLIC/PRIVATE (see swdllapi.h) to exported symbols/classes.<commit_after>/************************************************************************* * * $RCSfile: labelexp.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2004-08-23 08:51:14 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #pragma hdrstop #ifndef _COM_SUN_STAR_TEXT_XTEXTFIELDSSUPPLIER_HPP_ #include <com/sun/star/text/XTextFieldsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_ #include <com/sun/star/util/XRefreshable.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _LABFMT_HXX #include <labfmt.hxx> #endif #ifndef _UNOTOOLS_HXX #include <unotools.hxx> #endif #ifndef _UNOATXT_HXX //autogen wg. SwXAutoTextEntry #include <unoatxt.hxx> #endif #ifndef _UNOOBJ_HXX // #include <unoobj.hxx> #endif #ifndef _UNOPRNMS_HXX // #include <unoprnms.hxx> #endif using namespace ::com::sun::star; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace com::sun::star::uno; using namespace ::comphelper; using namespace ::rtl; #define C2U(char) rtl::OUString::createFromAscii(char) #ifdef SW_PROP_NAME_STR #undef SW_PROP_NAME_STR #endif #define SW_PROP_NAME_STR(nId) SwGetPropName((nId)).pName /* -----------------08.07.99 15:15------------------- --------------------------------------------------*/ void SwVisitingCardPage::InitFrameControl() { Link aLink(LINK(this, SwVisitingCardPage, FrameControlInitializedHdl)); pExampleFrame = new SwOneExampleFrame( aExampleWIN, EX_SHOW_BUSINESS_CARDS, &aLink ); uno::Reference< lang::XMultiServiceFactory > xMgr = getProcessServiceFactory(); //now the AutoText ListBoxes have to be filled uno::Reference< uno::XInterface > xAText = xMgr->createInstance( C2U("com.sun.star.text.AutoTextContainer") ); _xAutoText = uno::Reference< container::XNameAccess >(xAText, uno::UNO_QUERY); uno::Sequence<OUString> aNames = _xAutoText->getElementNames(); const OUString* pGroups = aNames.getConstArray(); OUString uTitleName( C2U(SW_PROP_NAME_STR(UNO_NAME_TITLE)) ); for(sal_uInt16 i = 0; i < aNames.getLength(); i++) { uno::Any aGroup = _xAutoText->getByName(pGroups[i]); uno::Reference< text::XAutoTextGroup > xGroup; aGroup >>= xGroup; uno::Reference< container::XIndexAccess > xIdxAcc(xGroup, uno::UNO_QUERY); try { if(!xIdxAcc.is() || xIdxAcc->getCount()) { uno::Reference< beans::XPropertySet > xPrSet(xGroup, uno::UNO_QUERY); uno::Any aTitle = xPrSet->getPropertyValue( uTitleName ); OUString uTitle; aTitle >>= uTitle; String sGroup(pGroups[i]); sal_uInt16 nEntry = aAutoTextGroupLB.InsertEntry(uTitle); aAutoTextGroupLB.SetEntryData(nEntry, new String(sGroup)); } } catch(Exception&) { } } if(aAutoTextGroupLB.GetEntryCount()) { if(LISTBOX_ENTRY_NOTFOUND == aAutoTextGroupLB.GetSelectEntryPos()) aAutoTextGroupLB.SelectEntryPos(0); String sCurGroupName( *(String*)aAutoTextGroupLB.GetEntryData(aAutoTextGroupLB.GetSelectEntryPos())); if(_xAutoText->hasByName(sCurGroupName)) { uno::Any aGroup = _xAutoText->getByName(sCurGroupName); try { uno::Reference< text::XAutoTextGroup > xGroup; aGroup >>= xGroup; uno::Sequence< OUString > aBlockNames = xGroup->getElementNames(); uno::Sequence< OUString > aTitles = xGroup->getTitles() ; SetUserData( aBlockNames.getLength(), aTitles.getConstArray(), aBlockNames.getConstArray() ); } catch( uno::RuntimeException& ) { // we'll be her if path settings were wrong } } } } /* -----------------01.10.99 13:19------------------- --------------------------------------------------*/ IMPL_LINK( SwVisitingCardPage, FrameControlInitializedHdl, void*, EMPTYARG ) { SvLBoxEntry* pSel = aAutoTextLB.FirstSelected(); String sEntry; if( pSel ) sEntry = *(String*)pSel->GetUserData(); uno::Reference< text::XTextCursor > & xCrsr = pExampleFrame->GetTextCursor(); OUString uEntry(sEntry); if(LISTBOX_ENTRY_NOTFOUND != aAutoTextGroupLB.GetSelectEntryPos()) { String sGroup( *(String*)aAutoTextGroupLB.GetEntryData( aAutoTextGroupLB.GetSelectEntryPos() ) ); uno::Any aGroup = _xAutoText->getByName(sGroup); uno::Reference< text::XAutoTextGroup > xGroup; aGroup >>= xGroup; if( sEntry.Len() && xGroup->hasByName( uEntry ) ) { uno::Any aEntry(xGroup->getByName(uEntry)); uno::Reference< text::XAutoTextEntry > xEntry; aEntry >>= xEntry; if(xEntry.is()) { uno::Reference< text::XTextRange > xRange(xCrsr, uno::UNO_QUERY); xEntry->applyTo(xRange); } UpdateFields(); } } return 0; } /* -----------------22.07.99 11:06------------------- --------------------------------------------------*/ IMPL_LINK( SwVisitingCardPage, AutoTextSelectHdl, void*, pBox ) { if(_xAutoText.is()) { if( &aAutoTextGroupLB == pBox ) { String sGroup( *(String*)aAutoTextGroupLB.GetEntryData( aAutoTextGroupLB.GetSelectEntryPos())); uno::Any aGroup = _xAutoText->getByName(sGroup); uno::Reference< text::XAutoTextGroup > xGroup; aGroup >>= xGroup; ClearUserData(); aAutoTextLB.Clear(); uno::Sequence<OUString> aBlockNames = xGroup->getElementNames(); uno::Sequence< OUString > aTitles = xGroup->getTitles() ; SetUserData( aBlockNames.getLength(), aTitles.getConstArray(), aBlockNames.getConstArray() ); } if(pExampleFrame->IsInitialized()) pExampleFrame->ClearDocument( TRUE ); } return 0; } /* -----------------01.10.99 11:59------------------- --------------------------------------------------*/ void SwVisitingCardPage::UpdateFields() { uno::Reference< frame::XModel > xModel; if( pExampleFrame && (xModel = pExampleFrame->GetModel()).is()) { SwLabDlg::UpdateFieldInformation(xModel, aLabItem); } } /* -----------------01.10.99 15:16------------------- --------------------------------------------------*/ void SwLabDlg::UpdateFieldInformation(uno::Reference< frame::XModel > & xModel, const SwLabItem& rItem) { uno::Reference< text::XTextFieldsSupplier > xFlds(xModel, uno::UNO_QUERY); uno::Reference< container::XNameAccess > xFldMasters = xFlds->getTextFieldMasters(); static const struct _SwLabItemMap { const char* pName; rtl::OUString SwLabItem:: *pValue; } aArr[] = { { "BC_PRIV_FIRSTNAME" , &SwLabItem::aPrivFirstName }, { "BC_PRIV_NAME" , &SwLabItem::aPrivName }, { "BC_PRIV_INITIALS" , &SwLabItem::aPrivShortCut }, { "BC_PRIV_FIRSTNAME_2", &SwLabItem::aPrivFirstName2 }, { "BC_PRIV_NAME_2" , &SwLabItem::aPrivName2 }, { "BC_PRIV_INITIALS_2" , &SwLabItem::aPrivShortCut2 }, { "BC_PRIV_STREET" , &SwLabItem::aPrivStreet }, { "BC_PRIV_ZIP" , &SwLabItem::aPrivZip }, { "BC_PRIV_CITY" , &SwLabItem::aPrivCity }, { "BC_PRIV_COUNTRY" , &SwLabItem::aPrivCountry }, { "BC_PRIV_STATE" , &SwLabItem::aPrivState }, { "BC_PRIV_TITLE" , &SwLabItem::aPrivTitle }, { "BC_PRIV_PROFESSION" , &SwLabItem::aPrivProfession }, { "BC_PRIV_PHONE" , &SwLabItem::aPrivPhone }, { "BC_PRIV_MOBILE" , &SwLabItem::aPrivMobile }, { "BC_PRIV_FAX" , &SwLabItem::aPrivFax }, { "BC_PRIV_WWW" , &SwLabItem::aPrivWWW }, { "BC_PRIV_MAIL" , &SwLabItem::aPrivMail }, { "BC_COMP_COMPANY" , &SwLabItem::aCompCompany }, { "BC_COMP_COMPANYEXT" , &SwLabItem::aCompCompanyExt }, { "BC_COMP_SLOGAN" , &SwLabItem::aCompSlogan }, { "BC_COMP_STREET" , &SwLabItem::aCompStreet }, { "BC_COMP_ZIP" , &SwLabItem::aCompZip }, { "BC_COMP_CITY" , &SwLabItem::aCompCity }, { "BC_COMP_COUNTRY" , &SwLabItem::aCompCountry }, { "BC_COMP_STATE" , &SwLabItem::aCompState }, { "BC_COMP_POSITION" , &SwLabItem::aCompPosition }, { "BC_COMP_PHONE" , &SwLabItem::aCompPhone }, { "BC_COMP_MOBILE" , &SwLabItem::aCompMobile }, { "BC_COMP_FAX" , &SwLabItem::aCompFax }, { "BC_COMP_WWW" , &SwLabItem::aCompWWW }, { "BC_COMP_MAIL" , &SwLabItem::aCompMail }, { 0, 0 } }; try { String sFldName( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "com.sun.star.text.FieldMaster.User." ))); OUString uCntName( C2U( SW_PROP_NAME_STR(UNO_NAME_CONTENT ))); for( const _SwLabItemMap* p = aArr; p->pName; ++p ) { String sCurFldName( sFldName ); sCurFldName.AppendAscii( p->pName ); OUString uFldName( sCurFldName ); if( xFldMasters->hasByName( uFldName )) { uno::Any aFirstName = xFldMasters->getByName( uFldName ); uno::Reference< beans::XPropertySet > xFld; aFirstName >>= xFld; uno::Any aContent; aContent <<= rItem.*p->pValue; xFld->setPropertyValue( uCntName, aContent ); } } } catch( uno::RuntimeException&) { // } uno::Reference< container::XEnumerationAccess > xFldAcc = xFlds->getTextFields(); uno::Reference< util::XRefreshable > xRefresh(xFldAcc, uno::UNO_QUERY); xRefresh->refresh(); } <|endoftext|>
<commit_before>void loadlibs () { gSystem->Load("libPhysics"); gSystem->Load("libMinuit"); gSystem->Load("libmicrocern"); gSystem->Load("libpdf"); gSystem->Load("libpythia6"); gSystem->Load("libEG"); gSystem->Load("libGeom"); gSystem->Load("libVMC"); gSystem->Load("libEGPythia6"); gSystem->Load("libRAWData"); gSystem->Load("libESD"); gSystem->Load("libSTEER"); gSystem->Load("libEVGEN"); gSystem->Load("libFASTSIM"); gSystem->Load("libAliPythia6"); gSystem->Load("libSTRUCT"); gSystem->Load("libMUONmapping"); gSystem->Load("libMUONgeometry"); gSystem->Load("libMUONbase"); gSystem->Load("libMUONsim"); new AliRun("gAlice","The ALICE Off-line Simulation Framework"); gSystem->Load("libMUONrec"); } <commit_msg>Adding libMUONraw.so in loading (Christian)<commit_after>void loadlibs () { gSystem->Load("libPhysics"); gSystem->Load("libmicrocern"); gSystem->Load("libpdf"); gSystem->Load("libpythia6"); gSystem->Load("libEG"); gSystem->Load("libGeom"); gSystem->Load("libVMC"); gSystem->Load("libEGPythia6"); gSystem->Load("libRAWData"); gSystem->Load("libESD"); gSystem->Load("libSTEER"); gSystem->Load("libEVGEN"); gSystem->Load("libFASTSIM"); gSystem->Load("libAliPythia6"); gSystem->Load("libSTRUCT"); gSystem->Load("libMUONmapping"); gSystem->Load("libMUONgeometry"); gSystem->Load("libMUONbase"); gSystem->Load("libMUONraw"); gSystem->Load("libMUONsim"); new AliRun("gAlice","The ALICE Off-line Simulation Framework"); gSystem->Load("libMUONrec"); } <|endoftext|>
<commit_before>/* This file is part of the E_Rendering library. Copyright (C) 2009-2012 Benjamin Eikel <benjamin@eikel.org> Copyright (C) 2009-2012 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2009-2012 Ralf Petring <ralf@petring.net> 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/. */ #include "E_Mesh.h" #include "E_VertexDescription.h" #include "../E_RenderingContext.h" #include "../E_BufferObject.h" #include <Rendering/Mesh/MeshVertexData.h> #include <Rendering/Mesh/MeshIndexData.h> #include <E_Geometry/E_Box.h> #include <E_Util/E_FileName.h> #include <E_Util/E_Utils.h> #include <EScript/EScript.h> using namespace EScript; namespace E_Rendering { //! (static) EScript::Type * E_Mesh::getTypeObject() { // E_Mesh ---|> Object static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject()); return typeObject.get(); } //! initMembers void E_Mesh::init(EScript::Namespace & lib) { EScript::Type * typeObject = getTypeObject(); initPrintableName(typeObject,getClassName()); declareConstant(&lib,getClassName(),typeObject); using namespace Rendering; //! [ESMF] new Rendering.Mesh( Mesh ) ES_CONSTRUCTOR(typeObject,1,1, { Mesh* source = parameter[0].to<Mesh*>(rt); MeshIndexData indexData(source->openIndexData()); MeshVertexData vertexData(source->openVertexData()); Mesh* mesh = new Mesh(indexData, vertexData); mesh->setDataStrategy(source->getDataStrategy()); mesh->setDrawMode(source->getDrawMode()); mesh->setFileName(source->getFileName()); mesh->setUseIndexData(mesh->isUsingIndexData()); return EScript::create(mesh); }) //! [ESMF] VertexDescription Mesh.getVertexDescription() ES_MFUN(typeObject,const Mesh,"getVertexDescription",0,0,thisObj->getVertexDescription()) //! [ESMF] Number Mesh.getVertexCount() ES_MFUN(typeObject,const Mesh,"getVertexCount",0,0,thisObj->getVertexCount()) //! [ESMF] Array Mesh._getIndices() ES_MFUNCTION(typeObject,Mesh,"_getIndices",0,0,{ MeshIndexData & indexData = thisObj->openIndexData(); auto arr = EScript::Array::create(); arr->reserve(indexData.getIndexCount()); for(size_t idx = 0; idx<indexData.getIndexCount(); ++idx) arr->pushBack(EScript::create(indexData[idx])); return arr; }) //! [ESMF] Number Mesh.getIndexCount() ES_MFUN(typeObject,const Mesh,"getIndexCount",0,0,thisObj->getIndexCount()) //! [ESMF] Box Mesh.getBoundingBox() ES_MFUN(typeObject,const Mesh,"getBoundingBox",0,0,thisObj->getBoundingBox()) //! [ESMF] FileName Mesh.getFileName() ES_MFUN(typeObject,const Mesh,"getFileName",0,0, new E_Util::E_FileName(thisObj->getFileName())) //! [ESMF] FileName Mesh.getMainMemoryUsage() ES_MFUN(typeObject,const Mesh,"getMainMemoryUsage",0,0, static_cast<double>(thisObj->getMainMemoryUsage())) //! [ESMF] FileName Mesh.getGraphicsMemoryUsage() ES_MFUN(typeObject,const Mesh,"getGraphicsMemoryUsage",0,0, static_cast<double>(thisObj->getGraphicsMemoryUsage())) //! [ESMF] Number Mesh.getPrimitiveCount() ES_MFUN(typeObject,const Mesh,"getPrimitiveCount",0,0, static_cast<double>(thisObj->getPrimitiveCount())) //! [ESMF] Bool Mesh.isUsingIndexData() ES_MFUN(typeObject,const Mesh,"isUsingIndexData",0,0,thisObj->isUsingIndexData()) //! [ESMF] thisEObj Mesh.releaseLocalData() ES_MFUNCTION(typeObject, Mesh, "releaseLocalData", 0, 0, { thisObj->openVertexData().releaseLocalData(); thisObj->openIndexData().releaseLocalData(); return thisEObj; }) //! [ESMF] thisEObj Mesh.releaseLocalData() ES_MFUNCTION(typeObject, Mesh, "assureLocalData", 0, 0, { thisObj->openVertexData(); thisObj->openIndexData(); return thisEObj; }) //! [ESMF] thisEObj Mesh.setDrawMode(Number) ES_MFUN(typeObject,Mesh,"setDrawMode",1,1,(thisObj->setDrawMode(static_cast<Rendering::Mesh::draw_mode_t>(parameter[0].toUInt())),thisEObj)) //! [ESMF] Number Mesh.getDrawMode() ES_MFUN(typeObject,const Mesh,"getDrawMode",0,0, static_cast<uint32_t>(thisObj->getDrawMode())) //! [ESMF] thisEObj Mesh.setDrawLines() ES_MFUN(typeObject,Mesh,"setDrawLines",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_LINES),thisEObj)) //! [ESMF] thisEObj Mesh.setDrawLineStrip() ES_MFUN(typeObject,Mesh,"setDrawLineStrip",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_LINE_STRIP),thisEObj)) //! [ESMF] thisEObj Mesh.setDrawPoints() ES_MFUN(typeObject,Mesh,"setDrawPoints",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_POINTS),thisEObj)) //! [ESMF] thisEObj Mesh.setDrawTriangles() ES_MFUN(typeObject,Mesh,"setDrawTriangles",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_TRIANGLES),thisEObj)) //! [ESMF] thisEObj Mesh._setIndices(Array) ES_MFUNCTION(typeObject,Mesh,"_setIndices",1,1,{ auto arr = parameter[0].to<EScript::Array*>(rt); MeshIndexData & indices = thisObj->_getIndexData(); indices.allocate(arr->size()); for(size_t i=0;i<arr->size();++i) indices[i] = arr->at(i).to<uint32_t>(rt); indices.updateIndexRange(); return thisEObj; }) //! [ESMF] thisEObj Mesh.setFileName([[FileName, String] name]) ES_MFUNCTION(typeObject,Mesh,"setFileName",0,1,{ if(parameter.count() == 0){ thisObj->setFileName(Util::FileName()); }else{ E_Util::E_FileName * t = dynamic_cast<E_Util::E_FileName *>(parameter[0].get()); if(t){ thisObj->setFileName(t->ref()); }else{ thisObj->setFileName(Util::FileName(parameter[0].toString())); } } return thisEObj; }) //! [ESMF] thisEObj Mesh.setUseIndexData(Bool) ES_MFUN(typeObject,Mesh,"setUseIndexData",1,1,(thisObj->setUseIndexData(parameter[0].toBool()),thisEObj)) //! [ESMF] thisEObj Mesh.swap(Mesh) ES_MFUN(typeObject,Mesh,"swap",1,1,(thisObj->swap(*parameter[0].to<Mesh*>(rt)),thisEObj)) //! [ESMF] thisEObj Mesh._markAsChanged() (wrapper for VertexData and IndexData.markAsChanged(), updateBB, and updateIndexRange , as these have no wrapper objects) ES_MFUNCTION(typeObject,Mesh,"_markAsChanged",0,0,{ thisObj->openVertexData().markAsChanged(); thisObj->openVertexData().updateBoundingBox(); thisObj->openIndexData().markAsChanged(); thisObj->openIndexData().updateIndexRange(); return thisEObj; }) //! [ESMF] thisEObj Mesh._swapVertexBuffer(BufferObject) ES_MFUN(typeObject,Mesh,"_swapVertexBuffer",1,1,(thisObj->_getVertexData()._swapBufferObject(parameter[0].to<CountedBufferObject*>(rt)->get()),thisEObj)) //! [ESMF] thisEObj Mesh._swapIndexBuffer(BufferObject) ES_MFUN(typeObject,Mesh,"_swapIndexBuffer",1,1,(thisObj->_getIndexData()._swapBufferObject(parameter[0].to<CountedBufferObject*>(rt)->get()),thisEObj)) //! [ESMF] thisEObj Mesh._upload([usageHint]) ES_MFUN(typeObject,Mesh,"_upload",0,1,(parameter.size() > 0 ? thisObj->_getVertexData().upload(parameter[0].toUInt()) : thisObj->_getVertexData().upload(),thisEObj)) E_Util::E_Utils::registerConverter(new E_Util::E_Utils::CountedRefAttrConverter<Rendering::Mesh,E_Mesh>); } //--- std::string E_Mesh::toString() const{ std::stringstream ss; ss << "#Mesh:" << (**this).get(); return ss.str(); } } <commit_msg>Mesh._upload didn't upload index data<commit_after>/* This file is part of the E_Rendering library. Copyright (C) 2009-2012 Benjamin Eikel <benjamin@eikel.org> Copyright (C) 2009-2012 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2009-2012 Ralf Petring <ralf@petring.net> 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/. */ #include "E_Mesh.h" #include "E_VertexDescription.h" #include "../E_RenderingContext.h" #include "../E_BufferObject.h" #include <Rendering/Mesh/MeshVertexData.h> #include <Rendering/Mesh/MeshIndexData.h> #include <E_Geometry/E_Box.h> #include <E_Util/E_FileName.h> #include <E_Util/E_Utils.h> #include <EScript/EScript.h> using namespace EScript; namespace E_Rendering { //! (static) EScript::Type * E_Mesh::getTypeObject() { // E_Mesh ---|> Object static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject()); return typeObject.get(); } //! initMembers void E_Mesh::init(EScript::Namespace & lib) { EScript::Type * typeObject = getTypeObject(); initPrintableName(typeObject,getClassName()); declareConstant(&lib,getClassName(),typeObject); using namespace Rendering; //! [ESMF] new Rendering.Mesh( Mesh ) ES_CONSTRUCTOR(typeObject,1,1, { Mesh* source = parameter[0].to<Mesh*>(rt); MeshIndexData indexData(source->openIndexData()); MeshVertexData vertexData(source->openVertexData()); Mesh* mesh = new Mesh(indexData, vertexData); mesh->setDataStrategy(source->getDataStrategy()); mesh->setDrawMode(source->getDrawMode()); mesh->setFileName(source->getFileName()); mesh->setUseIndexData(mesh->isUsingIndexData()); return EScript::create(mesh); }) //! [ESMF] VertexDescription Mesh.getVertexDescription() ES_MFUN(typeObject,const Mesh,"getVertexDescription",0,0,thisObj->getVertexDescription()) //! [ESMF] Number Mesh.getVertexCount() ES_MFUN(typeObject,const Mesh,"getVertexCount",0,0,thisObj->getVertexCount()) //! [ESMF] Array Mesh._getIndices() ES_MFUNCTION(typeObject,Mesh,"_getIndices",0,0,{ MeshIndexData & indexData = thisObj->openIndexData(); auto arr = EScript::Array::create(); arr->reserve(indexData.getIndexCount()); for(size_t idx = 0; idx<indexData.getIndexCount(); ++idx) arr->pushBack(EScript::create(indexData[idx])); return arr; }) //! [ESMF] Number Mesh.getIndexCount() ES_MFUN(typeObject,const Mesh,"getIndexCount",0,0,thisObj->getIndexCount()) //! [ESMF] Box Mesh.getBoundingBox() ES_MFUN(typeObject,const Mesh,"getBoundingBox",0,0,thisObj->getBoundingBox()) //! [ESMF] FileName Mesh.getFileName() ES_MFUN(typeObject,const Mesh,"getFileName",0,0, new E_Util::E_FileName(thisObj->getFileName())) //! [ESMF] FileName Mesh.getMainMemoryUsage() ES_MFUN(typeObject,const Mesh,"getMainMemoryUsage",0,0, static_cast<double>(thisObj->getMainMemoryUsage())) //! [ESMF] FileName Mesh.getGraphicsMemoryUsage() ES_MFUN(typeObject,const Mesh,"getGraphicsMemoryUsage",0,0, static_cast<double>(thisObj->getGraphicsMemoryUsage())) //! [ESMF] Number Mesh.getPrimitiveCount() ES_MFUN(typeObject,const Mesh,"getPrimitiveCount",0,0, static_cast<double>(thisObj->getPrimitiveCount())) //! [ESMF] Bool Mesh.isUsingIndexData() ES_MFUN(typeObject,const Mesh,"isUsingIndexData",0,0,thisObj->isUsingIndexData()) //! [ESMF] thisEObj Mesh.releaseLocalData() ES_MFUNCTION(typeObject, Mesh, "releaseLocalData", 0, 0, { thisObj->openVertexData().releaseLocalData(); thisObj->openIndexData().releaseLocalData(); return thisEObj; }) //! [ESMF] thisEObj Mesh.releaseLocalData() ES_MFUNCTION(typeObject, Mesh, "assureLocalData", 0, 0, { thisObj->openVertexData(); thisObj->openIndexData(); return thisEObj; }) //! [ESMF] thisEObj Mesh.setDrawMode(Number) ES_MFUN(typeObject,Mesh,"setDrawMode",1,1,(thisObj->setDrawMode(static_cast<Rendering::Mesh::draw_mode_t>(parameter[0].toUInt())),thisEObj)) //! [ESMF] Number Mesh.getDrawMode() ES_MFUN(typeObject,const Mesh,"getDrawMode",0,0, static_cast<uint32_t>(thisObj->getDrawMode())) //! [ESMF] thisEObj Mesh.setDrawLines() ES_MFUN(typeObject,Mesh,"setDrawLines",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_LINES),thisEObj)) //! [ESMF] thisEObj Mesh.setDrawLineStrip() ES_MFUN(typeObject,Mesh,"setDrawLineStrip",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_LINE_STRIP),thisEObj)) //! [ESMF] thisEObj Mesh.setDrawPoints() ES_MFUN(typeObject,Mesh,"setDrawPoints",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_POINTS),thisEObj)) //! [ESMF] thisEObj Mesh.setDrawTriangles() ES_MFUN(typeObject,Mesh,"setDrawTriangles",0,0,(thisObj->setDrawMode(Rendering::Mesh::DRAW_TRIANGLES),thisEObj)) //! [ESMF] thisEObj Mesh._setIndices(Array) ES_MFUNCTION(typeObject,Mesh,"_setIndices",1,1,{ auto arr = parameter[0].to<EScript::Array*>(rt); MeshIndexData & indices = thisObj->_getIndexData(); indices.allocate(arr->size()); for(size_t i=0;i<arr->size();++i) indices[i] = arr->at(i).to<uint32_t>(rt); indices.updateIndexRange(); return thisEObj; }) //! [ESMF] thisEObj Mesh.setFileName([[FileName, String] name]) ES_MFUNCTION(typeObject,Mesh,"setFileName",0,1,{ if(parameter.count() == 0){ thisObj->setFileName(Util::FileName()); }else{ E_Util::E_FileName * t = dynamic_cast<E_Util::E_FileName *>(parameter[0].get()); if(t){ thisObj->setFileName(t->ref()); }else{ thisObj->setFileName(Util::FileName(parameter[0].toString())); } } return thisEObj; }) //! [ESMF] thisEObj Mesh.setUseIndexData(Bool) ES_MFUN(typeObject,Mesh,"setUseIndexData",1,1,(thisObj->setUseIndexData(parameter[0].toBool()),thisEObj)) //! [ESMF] thisEObj Mesh.swap(Mesh) ES_MFUN(typeObject,Mesh,"swap",1,1,(thisObj->swap(*parameter[0].to<Mesh*>(rt)),thisEObj)) //! [ESMF] thisEObj Mesh._markAsChanged() (wrapper for VertexData and IndexData.markAsChanged(), updateBB, and updateIndexRange , as these have no wrapper objects) ES_MFUNCTION(typeObject,Mesh,"_markAsChanged",0,0,{ thisObj->openVertexData().markAsChanged(); thisObj->openVertexData().updateBoundingBox(); thisObj->openIndexData().markAsChanged(); thisObj->openIndexData().updateIndexRange(); return thisEObj; }) //! [ESMF] thisEObj Mesh._swapVertexBuffer(BufferObject) ES_MFUN(typeObject,Mesh,"_swapVertexBuffer",1,1,(thisObj->_getVertexData()._swapBufferObject(parameter[0].to<CountedBufferObject*>(rt)->get()),thisEObj)) //! [ESMF] thisEObj Mesh._swapIndexBuffer(BufferObject) ES_MFUN(typeObject,Mesh,"_swapIndexBuffer",1,1,(thisObj->_getIndexData()._swapBufferObject(parameter[0].to<CountedBufferObject*>(rt)->get()),thisEObj)) //! [ESMF] thisEObj Mesh._upload([usageHint]) ES_MFUNCTION(typeObject,Mesh,"_upload",0,1,{ if(parameter.size() > 0) { thisObj->_getVertexData().upload(parameter[0].toUInt()); if(thisObj->isUsingIndexData()) thisObj->_getIndexData().upload(parameter[0].toUInt()); } else { thisObj->_getVertexData().upload(); if(thisObj->isUsingIndexData()) thisObj->_getIndexData().upload(); } return thisEObj; }) E_Util::E_Utils::registerConverter(new E_Util::E_Utils::CountedRefAttrConverter<Rendering::Mesh,E_Mesh>); } //--- std::string E_Mesh::toString() const{ std::stringstream ss; ss << "#Mesh:" << (**this).get(); return ss.str(); } } <|endoftext|>
<commit_before> // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #include <boost/test/unit_test.hpp> #include "Grappa.hpp" #include "ParallelLoop.hpp" #include "GlobalAllocator.hpp" #include "Delegate.hpp" #include "GlobalHashTable.hpp" #include "GlobalHashSet.hpp" #include "Statistics.hpp" #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int.hpp> #include <boost/random/variate_generator.hpp> using namespace Grappa; BOOST_AUTO_TEST_SUITE( GlobalHashTable_tests ); DEFINE_int64(nelems, 100, "number of elements in (large) test arrays"); DEFINE_int64(global_hash_size, 1024, "number of elements in (large) test arrays"); DEFINE_int64(max_key, 1<<10, "maximum random key"); DEFINE_int64(ntrials, 1, "number of independent trials to average over"); DEFINE_bool(table_perf, false, "do performance test of GlobalHashTable"); DEFINE_bool(set_perf, false, "do performance test of GlobalHashSet"); GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, ght_insert_time, 0); GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, hashset_insert_time, 0); template< typename T > inline T next_random() { using engine_t = boost::mt19937_64; using dist_t = boost::uniform_int<T>; using gen_t = boost::variate_generator<engine_t&,dist_t>; // continue using same generator with multiple calls (to not repeat numbers) // but start at different seed on each node so we don't get overlap static engine_t engine(12345L*mycore()); static gen_t gen(engine, dist_t(0, std::numeric_limits<T>::max())); return gen(); } uint64_t kahan_hash(long k) { return k * 1299227; } // "Kahan's Hash" uint64_t identity_hash(long k) { return k; } enum class Exp { INSERT_UNIQUE }; template< Exp EXP, typename K, typename V, uint64_t (*H)(K), CompletionEvent* CE = &impl::local_ce, int64_t TH = impl::USE_LOOP_THRESHOLD_FLAG > double test_insert_throughput(GlobalAddress<GlobalHashTable<K,V,H>> ha) { double t = Grappa_walltime(); forall_global_private<CE,TH>(0, FLAGS_nelems, [ha](int64_t i){ if (EXP == Exp::INSERT_UNIQUE) { ha->insert_unique(next_random<long>()); } }); t = Grappa_walltime() - t; return t; } void test_correctness() { LOG(INFO) << "Testing correctness..."; auto ha = GlobalHashTable<long,long,&identity_hash>::create(FLAGS_global_hash_size); for (int i=0; i<10; i++) { ha->insert(i, 42); } ha->global_set_RO(); for (int i=0; i<10; i++) { GlobalAddress<long> res; BOOST_CHECK_EQUAL(ha->lookup(i, &res), 1); BOOST_CHECK_EQUAL(delegate::read(res), 42); } ha->forall_entries([](long key, BufferVector<long>& vs){ vs.setReadWriteMode(); }); forall_global_private(10, FLAGS_nelems-10, [ha](int64_t i){ ha->insert(i, 42); }); ha->forall_entries([](long key, BufferVector<long>& vs){ vs.setReadWriteMode(); }); ha->forall_entries([](long key, BufferVector<long>& vals){ BOOST_CHECK_EQUAL(vals.size(), 1); auto a = vals.getReadBuffer(); BOOST_CHECK_EQUAL(a.core(), mycore()); BOOST_CHECK_EQUAL(delegate::read(a), 42); }); ha->destroy(); } void test_set_correctness() { LOG(INFO) << "Testing correctness of GlobalHashSet..."; auto sa = GlobalHashSet<long>::create(FLAGS_global_hash_size); for (int i=0; i<10; i++) { // BOOST_CHECK_EQUAL(sa->insert(i), false); sa->insert(42+i); } for (int i=0; i<10; i++) { // BOOST_CHECK_EQUAL(sa->insert(i), true); BOOST_CHECK_EQUAL(sa->lookup(42+i), true); } on_all_cores([sa]{ for (int i=10; i<20; i++) { sa->insert(42+i); } }); sa->forall_keys([](long& k) { BOOST_CHECK(k < 42+20 && k >= 42); }); BOOST_CHECK_EQUAL(sa->size(), 20); sa->destroy(); } double test_set_insert_throughput() { auto sa = GlobalHashSet<long>::create(FLAGS_global_hash_size); double t = walltime(); forall_global_private(0, FLAGS_nelems, [sa](int64_t i){ sa->insert(next_random<long>() % FLAGS_max_key); }); t = walltime() - t; VLOG(1) << "set_size: " << sa->size(); sa->destroy(); return t; } void user_main( void * ignore ) { if (FLAGS_table_perf) { auto ha = GlobalHashTable<long,long,&kahan_hash>::create(FLAGS_global_hash_size); for (int i=0; i<FLAGS_ntrials; i++) { ght_insert_time += test_insert_throughput<Exp::INSERT_UNIQUE>(ha); } ha->destroy(); } else if (FLAGS_set_perf) { for (int i=0; i<FLAGS_ntrials; i++) { hashset_insert_time += test_set_insert_throughput(); } } else { test_correctness(); test_set_correctness(); } Statistics::merge_and_print(); } BOOST_AUTO_TEST_CASE( test1 ) { Grappa_init( &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv) ); Grappa_activate(); Grappa_run_user_main( &user_main, (void*)NULL ); Grappa_finish( 0 ); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Add option to test GHS insert_async<commit_after> // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #include <boost/test/unit_test.hpp> #include "Grappa.hpp" #include "ParallelLoop.hpp" #include "GlobalAllocator.hpp" #include "Delegate.hpp" #include "GlobalHashTable.hpp" #include "GlobalHashSet.hpp" #include "Statistics.hpp" #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int.hpp> #include <boost/random/variate_generator.hpp> using namespace Grappa; BOOST_AUTO_TEST_SUITE( GlobalHashTable_tests ); DEFINE_int64(nelems, 100, "number of elements in (large) test arrays"); DEFINE_int64(global_hash_size, 1024, "number of elements in (large) test arrays"); DEFINE_int64(max_key, 1<<10, "maximum random key"); DEFINE_int64(ntrials, 1, "number of independent trials to average over"); DEFINE_bool(table_perf, false, "do performance test of GlobalHashTable"); DEFINE_bool(set_perf, false, "do performance test of GlobalHashSet"); DEFINE_bool(insert_async, false, "do async inserts"); GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, ght_insert_time, 0); GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, hashset_insert_time, 0); template< typename T > inline T next_random() { using engine_t = boost::mt19937_64; using dist_t = boost::uniform_int<T>; using gen_t = boost::variate_generator<engine_t&,dist_t>; // continue using same generator with multiple calls (to not repeat numbers) // but start at different seed on each node so we don't get overlap static engine_t engine(12345L*mycore()); static gen_t gen(engine, dist_t(0, std::numeric_limits<T>::max())); return gen(); } uint64_t kahan_hash(long k) { return k * 1299227; } // "Kahan's Hash" uint64_t identity_hash(long k) { return k; } enum class Exp { INSERT_UNIQUE }; template< Exp EXP, typename K, typename V, uint64_t (*H)(K), CompletionEvent* CE = &impl::local_ce, int64_t TH = impl::USE_LOOP_THRESHOLD_FLAG > double test_insert_throughput(GlobalAddress<GlobalHashTable<K,V,H>> ha) { double t = Grappa_walltime(); forall_global_private<CE,TH>(0, FLAGS_nelems, [ha](int64_t i){ if (EXP == Exp::INSERT_UNIQUE) { ha->insert_unique(next_random<long>()); } }); t = Grappa_walltime() - t; return t; } void test_correctness() { LOG(INFO) << "Testing correctness..."; auto ha = GlobalHashTable<long,long,&identity_hash>::create(FLAGS_global_hash_size); for (int i=0; i<10; i++) { ha->insert(i, 42); } ha->global_set_RO(); for (int i=0; i<10; i++) { GlobalAddress<long> res; BOOST_CHECK_EQUAL(ha->lookup(i, &res), 1); BOOST_CHECK_EQUAL(delegate::read(res), 42); } ha->forall_entries([](long key, BufferVector<long>& vs){ vs.setReadWriteMode(); }); forall_global_private(10, FLAGS_nelems-10, [ha](int64_t i){ ha->insert(i, 42); }); ha->forall_entries([](long key, BufferVector<long>& vs){ vs.setReadWriteMode(); }); ha->forall_entries([](long key, BufferVector<long>& vals){ BOOST_CHECK_EQUAL(vals.size(), 1); auto a = vals.getReadBuffer(); BOOST_CHECK_EQUAL(a.core(), mycore()); BOOST_CHECK_EQUAL(delegate::read(a), 42); }); ha->destroy(); } void test_set_correctness() { LOG(INFO) << "Testing correctness of GlobalHashSet..."; auto sa = GlobalHashSet<long>::create(FLAGS_global_hash_size); for (int i=0; i<10; i++) { // BOOST_CHECK_EQUAL(sa->insert(i), false); sa->insert(42+i); } for (int i=0; i<10; i++) { // BOOST_CHECK_EQUAL(sa->insert(i), true); BOOST_CHECK_EQUAL(sa->lookup(42+i), true); } on_all_cores([sa]{ for (int i=10; i<20; i++) { sa->insert(42+i); } }); sa->forall_keys([](long& k) { BOOST_CHECK(k < 42+20 && k >= 42); }); BOOST_CHECK_EQUAL(sa->size(), 20); sa->destroy(); } CompletionEvent lce; double test_set_insert_throughput() { auto sa = GlobalHashSet<long>::create(FLAGS_global_hash_size); double t = walltime(); if (FLAGS_insert_async) { forall_global_private<&lce>(0, FLAGS_nelems, [sa](int64_t i){ auto k = next_random<long>() % FLAGS_max_key; lce.enroll(); sa->insert_async(k, []{ lce.complete(); }); }); sa->sync_all_cores(); } else { forall_global_private(0, FLAGS_nelems, [sa](int64_t i){ auto k = next_random<long>() % FLAGS_max_key; sa->insert(k); }); } t = walltime() - t; VLOG(1) << "set_size: " << sa->size(); sa->destroy(); return t; } void user_main( void * ignore ) { if (FLAGS_table_perf) { auto ha = GlobalHashTable<long,long,&kahan_hash>::create(FLAGS_global_hash_size); for (int i=0; i<FLAGS_ntrials; i++) { ght_insert_time += test_insert_throughput<Exp::INSERT_UNIQUE>(ha); } ha->destroy(); } else if (FLAGS_set_perf) { for (int i=0; i<FLAGS_ntrials; i++) { hashset_insert_time += test_set_insert_throughput(); } } else { test_correctness(); test_set_correctness(); } Statistics::merge_and_print(); } BOOST_AUTO_TEST_CASE( test1 ) { Grappa_init( &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv) ); Grappa_activate(); Grappa_run_user_main( &user_main, (void*)NULL ); Grappa_finish( 0 ); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>#ifndef __SNOWMAN_HPP__ #define __SNOWMAN_HPP__ #include <stdexcept> #include <vector> #include <string> #include <map> struct Variable; typedef bool tUndefined; typedef double tNum; typedef std::vector<Variable> tArray; typedef std::string tBlock; typedef tArray::size_type vvs; typedef tBlock::size_type ss; class SnowmanException: public std::runtime_error { public: SnowmanException(std::string msg = "Snowman error occurred", bool fatal = false): std::runtime_error(msg), fatal(fatal) {} bool fatal; }; struct Variable { // constructors Variable(): undefinedVal(true) { type = UNDEFINED; } Variable(tUndefined x): undefinedVal(x) { type = UNDEFINED; } Variable(tNum x): numVal(x) { type = NUM; } Variable(tArray* x): arrayVal(x) { type = ARRAY; } Variable(tBlock* x): blockVal(x) { type = BLOCK; } // destructor ~Variable() {} // copy constructor Variable(const Variable& v) { switch (v.type) { case UNDEFINED: type = UNDEFINED; undefinedVal = false; break; case NUM: type = NUM; numVal = v.numVal; break; case ARRAY: type = ARRAY; arrayVal = new tArray(*v.arrayVal); break; case BLOCK: type = BLOCK; blockVal = new tBlock(*v.blockVal); break; } } // assignment operator Variable& operator=(const Variable& v) { switch (v.type) { case UNDEFINED: type = UNDEFINED; undefinedVal = false; break; case NUM: type = NUM; numVal = v.numVal; break; case ARRAY: type = ARRAY; arrayVal = new tArray(*v.arrayVal); break; case BLOCK: type = BLOCK; blockVal = new tBlock(*v.blockVal); break; } return *this; } // operators bool operator==(const Variable& v) const { if (type != v.type) return false; switch (v.type) { case UNDEFINED: return true; case NUM: return numVal == v.numVal; case ARRAY: return arrayVal == v.arrayVal; case BLOCK: return blockVal == v.blockVal; default: throw SnowmanException("at Variable::operator==: impossible" "type?", true); } } bool operator<(const Variable& v) const { if (type != v.type) return type < v.type; switch (v.type) { case UNDEFINED: return false; case NUM: return numVal < v.numVal; case ARRAY: return arrayVal < v.arrayVal; case BLOCK: return blockVal < v.blockVal; default: throw SnowmanException("at Variable::operator<: impossible" "type?", true); } } // manage memory (use when modifying value) // BE VERY CAREFUL when calling this function void mm() { switch (type) { case ARRAY: delete arrayVal; break; case BLOCK: delete blockVal; break; default: break; } } // the actual data enum { UNDEFINED, NUM, ARRAY, BLOCK } type; union { tUndefined undefinedVal; tNum numVal; tArray* arrayVal; tBlock* blockVal; }; }; // used for subroutines struct VarState { Variable vars[8]; bool activeVars[8]; }; class Snowman { private: // internal evaluation methods void evalToken(std::string token); void store(Variable v); Variable retrieve(int type, bool consume = true, int skip = 0); template<typename T = tUndefined, typename U = tUndefined, typename V = tUndefined, typename W = tUndefined> class Retrieval{}; // utility methods having to do with the language itself static std::string arrToString(tArray arr); static Variable stringToArr(std::string str); static std::string inspect(Variable str); static bool toBool(Variable v); // command line args tArray args; // variables and permavars Variable vars[8]; bool activeVars[8]; std::vector<VarState> subroutines; std::map<int, Variable> permavars; int activePermavar; bool savedActiveState[8]; public: // constructor / destructor Snowman(); ~Snowman(); // for manipulating a string of code static std::vector<std::string> tokenize(std::string code); void run(std::string code); // command line args void addArg(std::string arg); // debugging (also used for REPL) std::string debug(); bool debugOutput; // version const static int MAJOR_VERSION = 1; const static int MINOR_VERSION = 0; const static int PATCH_VERSION = 1; }; #endif <commit_msg>release 1.0.2<commit_after>#ifndef __SNOWMAN_HPP__ #define __SNOWMAN_HPP__ #include <stdexcept> #include <vector> #include <string> #include <map> struct Variable; typedef bool tUndefined; typedef double tNum; typedef std::vector<Variable> tArray; typedef std::string tBlock; typedef tArray::size_type vvs; typedef tBlock::size_type ss; class SnowmanException: public std::runtime_error { public: SnowmanException(std::string msg = "Snowman error occurred", bool fatal = false): std::runtime_error(msg), fatal(fatal) {} bool fatal; }; struct Variable { // constructors Variable(): undefinedVal(true) { type = UNDEFINED; } Variable(tUndefined x): undefinedVal(x) { type = UNDEFINED; } Variable(tNum x): numVal(x) { type = NUM; } Variable(tArray* x): arrayVal(x) { type = ARRAY; } Variable(tBlock* x): blockVal(x) { type = BLOCK; } // destructor ~Variable() {} // copy constructor Variable(const Variable& v) { switch (v.type) { case UNDEFINED: type = UNDEFINED; undefinedVal = false; break; case NUM: type = NUM; numVal = v.numVal; break; case ARRAY: type = ARRAY; arrayVal = new tArray(*v.arrayVal); break; case BLOCK: type = BLOCK; blockVal = new tBlock(*v.blockVal); break; } } // assignment operator Variable& operator=(const Variable& v) { switch (v.type) { case UNDEFINED: type = UNDEFINED; undefinedVal = false; break; case NUM: type = NUM; numVal = v.numVal; break; case ARRAY: type = ARRAY; arrayVal = new tArray(*v.arrayVal); break; case BLOCK: type = BLOCK; blockVal = new tBlock(*v.blockVal); break; } return *this; } // operators bool operator==(const Variable& v) const { if (type != v.type) return false; switch (v.type) { case UNDEFINED: return true; case NUM: return numVal == v.numVal; case ARRAY: return arrayVal == v.arrayVal; case BLOCK: return blockVal == v.blockVal; default: throw SnowmanException("at Variable::operator==: impossible" "type?", true); } } bool operator<(const Variable& v) const { if (type != v.type) return type < v.type; switch (v.type) { case UNDEFINED: return false; case NUM: return numVal < v.numVal; case ARRAY: return arrayVal < v.arrayVal; case BLOCK: return blockVal < v.blockVal; default: throw SnowmanException("at Variable::operator<: impossible" "type?", true); } } // manage memory (use when modifying value) // BE VERY CAREFUL when calling this function void mm() { switch (type) { case ARRAY: delete arrayVal; break; case BLOCK: delete blockVal; break; default: break; } } // the actual data enum { UNDEFINED, NUM, ARRAY, BLOCK } type; union { tUndefined undefinedVal; tNum numVal; tArray* arrayVal; tBlock* blockVal; }; }; // used for subroutines struct VarState { Variable vars[8]; bool activeVars[8]; }; class Snowman { private: // internal evaluation methods void evalToken(std::string token); void store(Variable v); Variable retrieve(int type, bool consume = true, int skip = 0); template<typename T = tUndefined, typename U = tUndefined, typename V = tUndefined, typename W = tUndefined> class Retrieval{}; // utility methods having to do with the language itself static std::string arrToString(tArray arr); static Variable stringToArr(std::string str); static std::string inspect(Variable str); static bool toBool(Variable v); // command line args tArray args; // variables and permavars Variable vars[8]; bool activeVars[8]; std::vector<VarState> subroutines; std::map<int, Variable> permavars; int activePermavar; bool savedActiveState[8]; public: // constructor / destructor Snowman(); ~Snowman(); // for manipulating a string of code static std::vector<std::string> tokenize(std::string code); void run(std::string code); // command line args void addArg(std::string arg); // debugging (also used for REPL) std::string debug(); bool debugOutput; // version const static int MAJOR_VERSION = 1; const static int MINOR_VERSION = 0; const static int PATCH_VERSION = 2; }; #endif <|endoftext|>
<commit_before>#ifndef __SNOWMAN_HPP__ #define __SNOWMAN_HPP__ #include <stdexcept> #include <vector> #include <string> #include <map> struct Variable; typedef std::vector<Variable>::size_type vvs; typedef std::string::size_type ss; class SnowmanException: public std::runtime_error { public: SnowmanException(std::string msg = "Snowman error occurred", bool fatal = false): std::runtime_error(msg), fatal(fatal) {} bool fatal; }; struct Variable { // constructors Variable(): undefinedVal(true) { type = UNDEFINED; } Variable(bool x): undefinedVal(x) { type = UNDEFINED; } Variable(double x): numVal(x) { type = NUM; } Variable(std::vector<Variable>* x): arrayVal(x) { type = ARRAY; } Variable(std::string* x): blockVal(x) { type = BLOCK; } // destructor ~Variable() {} // copy constructor Variable(const Variable& v) { switch (v.type) { case UNDEFINED: type = UNDEFINED; undefinedVal = false; break; case NUM: type = NUM; numVal = v.numVal; break; case ARRAY: type = ARRAY; arrayVal = new std::vector<Variable>(*v.arrayVal); break; case BLOCK: type = BLOCK; blockVal = new std::string(*v.blockVal); break; } } // operators bool operator==(const Variable& v) const { if (type != v.type) return false; switch (v.type) { case UNDEFINED: return true; case NUM: return numVal == v.numVal; case ARRAY: return arrayVal == v.arrayVal; case BLOCK: return blockVal == v.blockVal; default: throw SnowmanException("at Variable::operator==: impossible" "type?", true); } } bool operator<(const Variable& v) const { if (type != v.type) return type < v.type; switch (v.type) { case UNDEFINED: return false; case NUM: return numVal < v.numVal; case ARRAY: return arrayVal < v.arrayVal; case BLOCK: return blockVal < v.blockVal; default: throw SnowmanException("at Variable::operator<: impossible" "type?", true); } } // manage memory (use when modifying value) // BE VERY CAREFUL when calling this function void mm() { switch (type) { case ARRAY: delete arrayVal; break; case BLOCK: delete blockVal; break; default: break; } } // the actual data enum { UNDEFINED, NUM, ARRAY, BLOCK } type; union { bool undefinedVal; double numVal; std::vector<Variable>* arrayVal; std::string* blockVal; }; }; // used for subroutines struct VarState { Variable vars[8]; bool activeVars[8]; }; class Snowman { private: // internal evaluation methods void evalToken(std::string token); void store(Variable v); std::vector<Variable> retrieve(int type, vvs count = 1, bool consume = true, int skip = 0, bool doNotDelete = false); // utility methods having to do with the language itself static std::string arrToString(Variable arr); static Variable stringToArr(std::string str); static std::string inspect(Variable str); static bool toBool(Variable v); // command line args std::vector<Variable> args; // variables and permavars Variable vars[8]; bool activeVars[8]; std::vector<VarState> subroutines; std::map<int, Variable> permavars; int activePermavar; bool savedActiveState[8]; // ugly, ugly "garbage collector" std::vector<Variable> gc; public: // constructor / destructor Snowman(); ~Snowman(); // for manipulating a string of code static std::vector<std::string> tokenize(std::string code); void run(std::string code); // command line args void addArg(std::string arg); // debugging (also used for REPL) std::string debug(); bool debugOutput; // version const static int MAJOR_VERSION = 1; const static int MINOR_VERSION = 0; const static int PATCH_VERSION = 0; }; #endif <commit_msg>release 1.0.1<commit_after>#ifndef __SNOWMAN_HPP__ #define __SNOWMAN_HPP__ #include <stdexcept> #include <vector> #include <string> #include <map> struct Variable; typedef std::vector<Variable>::size_type vvs; typedef std::string::size_type ss; class SnowmanException: public std::runtime_error { public: SnowmanException(std::string msg = "Snowman error occurred", bool fatal = false): std::runtime_error(msg), fatal(fatal) {} bool fatal; }; struct Variable { // constructors Variable(): undefinedVal(true) { type = UNDEFINED; } Variable(bool x): undefinedVal(x) { type = UNDEFINED; } Variable(double x): numVal(x) { type = NUM; } Variable(std::vector<Variable>* x): arrayVal(x) { type = ARRAY; } Variable(std::string* x): blockVal(x) { type = BLOCK; } // destructor ~Variable() {} // copy constructor Variable(const Variable& v) { switch (v.type) { case UNDEFINED: type = UNDEFINED; undefinedVal = false; break; case NUM: type = NUM; numVal = v.numVal; break; case ARRAY: type = ARRAY; arrayVal = new std::vector<Variable>(*v.arrayVal); break; case BLOCK: type = BLOCK; blockVal = new std::string(*v.blockVal); break; } } // operators bool operator==(const Variable& v) const { if (type != v.type) return false; switch (v.type) { case UNDEFINED: return true; case NUM: return numVal == v.numVal; case ARRAY: return arrayVal == v.arrayVal; case BLOCK: return blockVal == v.blockVal; default: throw SnowmanException("at Variable::operator==: impossible" "type?", true); } } bool operator<(const Variable& v) const { if (type != v.type) return type < v.type; switch (v.type) { case UNDEFINED: return false; case NUM: return numVal < v.numVal; case ARRAY: return arrayVal < v.arrayVal; case BLOCK: return blockVal < v.blockVal; default: throw SnowmanException("at Variable::operator<: impossible" "type?", true); } } // manage memory (use when modifying value) // BE VERY CAREFUL when calling this function void mm() { switch (type) { case ARRAY: delete arrayVal; break; case BLOCK: delete blockVal; break; default: break; } } // the actual data enum { UNDEFINED, NUM, ARRAY, BLOCK } type; union { bool undefinedVal; double numVal; std::vector<Variable>* arrayVal; std::string* blockVal; }; }; // used for subroutines struct VarState { Variable vars[8]; bool activeVars[8]; }; class Snowman { private: // internal evaluation methods void evalToken(std::string token); void store(Variable v); std::vector<Variable> retrieve(int type, vvs count = 1, bool consume = true, int skip = 0, bool doNotDelete = false); // utility methods having to do with the language itself static std::string arrToString(Variable arr); static Variable stringToArr(std::string str); static std::string inspect(Variable str); static bool toBool(Variable v); // command line args std::vector<Variable> args; // variables and permavars Variable vars[8]; bool activeVars[8]; std::vector<VarState> subroutines; std::map<int, Variable> permavars; int activePermavar; bool savedActiveState[8]; // ugly, ugly "garbage collector" std::vector<Variable> gc; public: // constructor / destructor Snowman(); ~Snowman(); // for manipulating a string of code static std::vector<std::string> tokenize(std::string code); void run(std::string code); // command line args void addArg(std::string arg); // debugging (also used for REPL) std::string debug(); bool debugOutput; // version const static int MAJOR_VERSION = 1; const static int MINOR_VERSION = 0; const static int PATCH_VERSION = 1; }; #endif <|endoftext|>
<commit_before>#include "CPU.h" #if defined(__x86_64__) || defined(__i386__) #include <cpuid.h> #endif #include "Log.h" namespace i2p { namespace cpu { bool aesni = false; bool avx = false; void Detect() { #if defined(__x86_64__) || defined(__i386__) int info[4]; __cpuid(0, info[0], info[1], info[2], info[3]); if (info[0] >= 0x00000001) { __cpuid(0x00000001, info[0], info[1], info[2], info[3]); aesni = info[2] & bit_AES; // AESNI avx = info[2] & bit_AVX; // AVX } #endif if(aesni) { LogPrint(eLogInfo, "AESNI enabled"); } if(avx) { LogPrint(eLogInfo, "AVX enabled"); } } } } <commit_msg>define cpu_* if not set<commit_after>#include "CPU.h" #if defined(__x86_64__) || defined(__i386__) #include <cpuid.h> #endif #include "Log.h" #ifndef bit_AES #define bit_AES (1 << 25) #endif #ifndef bit_AVX #define bit_AVX (1 << 28) #endif namespace i2p { namespace cpu { bool aesni = false; bool avx = false; void Detect() { #if defined(__x86_64__) || defined(__i386__) int info[4]; __cpuid(0, info[0], info[1], info[2], info[3]); if (info[0] >= 0x00000001) { __cpuid(0x00000001, info[0], info[1], info[2], info[3]); aesni = info[2] & bit_AES; // AESNI avx = info[2] & bit_AVX; // AVX } #endif if(aesni) { LogPrint(eLogInfo, "AESNI enabled"); } if(avx) { LogPrint(eLogInfo, "AVX enabled"); } } } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////// // OBJ.cpp // // Copyright 2007 cDc@seacave // Distributed under the Boost Software License, Version 1.0 // (See http://www.boost.org/LICENSE_1_0.txt) #include "Common.h" #include "OBJ.h" using namespace SEACAVE; // D E F I N E S /////////////////////////////////////////////////// // uncomment to enable multi-threading based on OpenMP #ifdef _USE_OPENMP #define OBJ_USE_OPENMP #endif #define OBJ_INDEX_OFFSET 1 // S T R U C T S /////////////////////////////////////////////////// ObjModel::MaterialLib::Material::Material(const Image8U3& _diffuse_map, const Color& _Kd) : diffuse_map(_diffuse_map), Kd(_Kd) { } bool ObjModel::MaterialLib::Material::LoadDiffuseMap() { if (diffuse_map.empty()) return diffuse_map.Load(diffuse_name); return true; } /*----------------------------------------------------------------*/ // S T R U C T S /////////////////////////////////////////////////// ObjModel::MaterialLib::MaterialLib() { } bool ObjModel::MaterialLib::Save(const String& prefix, bool texLossless) const { std::ofstream out((prefix+".mtl").c_str()); if (!out.good()) return false; const String pathName(Util::getFilePath(prefix)); const String name(Util::getFileNameExt(prefix)); #ifdef OBJ_USE_OPENMP bool bSuccess(true); #pragma omp parallel for #endif for (int_t i = 0; i < (int_t)materials.size(); ++i) { const Material& mat = materials[i]; // save material description out << "newmtl " << mat.name << "\n" << "Ka 1.000000 1.000000 1.000000" << "\n" << "Kd " << mat.Kd.r << " " << mat.Kd.g << " " << mat.Kd.b << "\n" << "Ks 0.000000 0.000000 0.000000" << "\n" << "Tr 1.000000" << "\n" << "illum 1" << "\n" << "Ns 1.000000" << "\n"; // save material maps if (mat.diffuse_map.empty()) continue; if (mat.diffuse_name.IsEmpty()) const_cast<String&>(mat.diffuse_name) = name+"_"+mat.name+"_map_Kd."+(texLossless?"png":"jpg"); out << "map_Kd " << mat.diffuse_name << "\n"; const bool bRet(mat.diffuse_map.Save(pathName+mat.diffuse_name)); #ifdef OBJ_USE_OPENMP #pragma omp critical if (!bRet) bSuccess = false; #else if (!bRet) return false; #endif } #ifdef OBJ_USE_OPENMP return bSuccess; #else return true; #endif } bool ObjModel::MaterialLib::Load(const String& fileName) { const size_t numMaterials(materials.size()); std::ifstream in(fileName.c_str()); String keyword; while (in.good() && in >> keyword) { if (keyword == "newmtl") { in >> keyword; materials.push_back(Material(keyword)); } else if (keyword == "Kd") { ASSERT(numMaterials < materials.size()); Color c; in >> c.r >> c.g >> c.b; materials.back().Kd = c; } else if (keyword == "map_Kd") { ASSERT(numMaterials < materials.size()); String& diffuse_name = materials.back().diffuse_name; in >> diffuse_name; diffuse_name = Util::getFilePath(fileName) + diffuse_name; } } return numMaterials < materials.size(); } /*----------------------------------------------------------------*/ // S T R U C T S /////////////////////////////////////////////////// bool ObjModel::Save(const String& fileName, unsigned precision, bool texLossless) const { if (vertices.empty()) return false; const String prefix(Util::getFileFullName(fileName)); const String name(Util::getFileNameExt(prefix)); if (!material_lib.Save(prefix, texLossless)) return false; std::ofstream out((prefix + ".obj").c_str()); if (!out.good()) return false; out << "mtllib " << name << ".mtl" << "\n"; out << std::fixed << std::setprecision(precision); for (size_t i = 0; i < vertices.size(); ++i) { out << "v " << vertices[i][0] << " " << vertices[i][1] << " " << vertices[i][2] << "\n"; } for (size_t i = 0; i < texcoords.size(); ++i) { out << "vt " << texcoords[i][0] << " " << texcoords[i][1] << "\n"; } for (size_t i = 0; i < normals.size(); ++i) { out << "vn " << normals[i][0] << " " << normals[i][1] << " " << normals[i][2] << "\n"; } for (size_t i = 0; i < groups.size(); ++i) { out << "usemtl " << groups[i].material_name << "\n"; for (size_t j = 0; j < groups[i].faces.size(); ++j) { const Face& face = groups[i].faces[j]; out << "f"; for (size_t k = 0; k < 3; ++k) { out << " " << face.vertices[k] + OBJ_INDEX_OFFSET; if (!texcoords.empty()) { out << "/" << face.texcoords[k] + OBJ_INDEX_OFFSET; if (!normals.empty()) out << "/" << face.normals[k] + OBJ_INDEX_OFFSET; } else if (!normals.empty()) out << "//" << face.normals[k] + OBJ_INDEX_OFFSET; } out << "\n"; } } return true; } bool ObjModel::Load(const String& fileName) { ASSERT(vertices.empty() && groups.empty() && material_lib.materials.empty()); std::ifstream fin(fileName.c_str()); String line, keyword; std::istringstream in; while (fin.good()) { std::getline(fin, line); if (line.empty() || line[0u] == '#') continue; in.str(line); in >> keyword; if (keyword == "v") { Vertex v; in >> v[0] >> v[1] >> v[2]; if (in.fail()) return false; vertices.push_back(v); } else if (keyword == "vt") { TexCoord vt; in >> vt[0] >> vt[1]; if (in.fail()) return false; texcoords.push_back(vt); } else if (keyword == "vn") { Normal vn; in >> vn[0] >> vn[1] >> vn[2]; if (in.fail()) return false; normals.push_back(vn); } else if (keyword == "f") { Face f; memset(&f, 0xFF, sizeof(Face)); for (size_t k = 0; k < 3; ++k) { in >> keyword; switch (sscanf(keyword, "%u/%u/%u", f.vertices+k, f.texcoords+k, f.normals+k)) { case 1: f.vertices[k] -= OBJ_INDEX_OFFSET; break; case 2: f.vertices[k] -= OBJ_INDEX_OFFSET; if (f.texcoords[k] != NO_ID) f.texcoords[k] -= OBJ_INDEX_OFFSET; if (f.normals[k] != NO_ID) f.normals[k] -= OBJ_INDEX_OFFSET; break; case 3: f.vertices[k] -= OBJ_INDEX_OFFSET; f.texcoords[k] -= OBJ_INDEX_OFFSET; f.normals[k] -= OBJ_INDEX_OFFSET; break; default: return false; } } if (in.fail()) return false; groups.back().faces.push_back(f); } else if (keyword == "mtllib") { in >> keyword; if (!material_lib.Load(keyword)) return false; } else if (keyword == "usemtl") { Group group; in >> group.material_name; if (in.fail()) return false; groups.push_back(group); } in.clear(); } return !vertices.empty(); } ObjModel::Group& ObjModel::AddGroup(const String& material_name) { groups.push_back(Group()); Group& group = groups.back(); group.material_name = material_name; if (!GetMaterial(material_name)) material_lib.materials.push_back(MaterialLib::Material(material_name)); return group; } ObjModel::MaterialLib::Material* ObjModel::GetMaterial(const String& name) { MaterialLib::Materials::iterator it(std::find_if(material_lib.materials.begin(), material_lib.materials.end(), [&name](const MaterialLib::Material& mat) { return mat.name == name; })); if (it == material_lib.materials.end()) return NULL; return &(*it); } /*----------------------------------------------------------------*/ <commit_msg>io: fix read obj without material<commit_after>//////////////////////////////////////////////////////////////////// // OBJ.cpp // // Copyright 2007 cDc@seacave // Distributed under the Boost Software License, Version 1.0 // (See http://www.boost.org/LICENSE_1_0.txt) #include "Common.h" #include "OBJ.h" using namespace SEACAVE; // D E F I N E S /////////////////////////////////////////////////// // uncomment to enable multi-threading based on OpenMP #ifdef _USE_OPENMP #define OBJ_USE_OPENMP #endif #define OBJ_INDEX_OFFSET 1 // S T R U C T S /////////////////////////////////////////////////// ObjModel::MaterialLib::Material::Material(const Image8U3& _diffuse_map, const Color& _Kd) : diffuse_map(_diffuse_map), Kd(_Kd) { } bool ObjModel::MaterialLib::Material::LoadDiffuseMap() { if (diffuse_map.empty()) return diffuse_map.Load(diffuse_name); return true; } /*----------------------------------------------------------------*/ // S T R U C T S /////////////////////////////////////////////////// ObjModel::MaterialLib::MaterialLib() { } bool ObjModel::MaterialLib::Save(const String& prefix, bool texLossless) const { std::ofstream out((prefix+".mtl").c_str()); if (!out.good()) return false; const String pathName(Util::getFilePath(prefix)); const String name(Util::getFileNameExt(prefix)); #ifdef OBJ_USE_OPENMP bool bSuccess(true); #pragma omp parallel for #endif for (int_t i = 0; i < (int_t)materials.size(); ++i) { const Material& mat = materials[i]; // save material description out << "newmtl " << mat.name << "\n" << "Ka 1.000000 1.000000 1.000000" << "\n" << "Kd " << mat.Kd.r << " " << mat.Kd.g << " " << mat.Kd.b << "\n" << "Ks 0.000000 0.000000 0.000000" << "\n" << "Tr 1.000000" << "\n" << "illum 1" << "\n" << "Ns 1.000000" << "\n"; // save material maps if (mat.diffuse_map.empty()) continue; if (mat.diffuse_name.IsEmpty()) const_cast<String&>(mat.diffuse_name) = name+"_"+mat.name+"_map_Kd."+(texLossless?"png":"jpg"); out << "map_Kd " << mat.diffuse_name << "\n"; const bool bRet(mat.diffuse_map.Save(pathName+mat.diffuse_name)); #ifdef OBJ_USE_OPENMP #pragma omp critical if (!bRet) bSuccess = false; #else if (!bRet) return false; #endif } #ifdef OBJ_USE_OPENMP return bSuccess; #else return true; #endif } bool ObjModel::MaterialLib::Load(const String& fileName) { const size_t numMaterials(materials.size()); std::ifstream in(fileName.c_str()); String keyword; while (in.good() && in >> keyword) { if (keyword == "newmtl") { in >> keyword; materials.push_back(Material(keyword)); } else if (keyword == "Kd") { ASSERT(numMaterials < materials.size()); Color c; in >> c.r >> c.g >> c.b; materials.back().Kd = c; } else if (keyword == "map_Kd") { ASSERT(numMaterials < materials.size()); String& diffuse_name = materials.back().diffuse_name; in >> diffuse_name; diffuse_name = Util::getFilePath(fileName) + diffuse_name; } } return numMaterials < materials.size(); } /*----------------------------------------------------------------*/ // S T R U C T S /////////////////////////////////////////////////// bool ObjModel::Save(const String& fileName, unsigned precision, bool texLossless) const { if (vertices.empty()) return false; const String prefix(Util::getFileFullName(fileName)); const String name(Util::getFileNameExt(prefix)); if (!material_lib.Save(prefix, texLossless)) return false; std::ofstream out((prefix + ".obj").c_str()); if (!out.good()) return false; out << "mtllib " << name << ".mtl" << "\n"; out << std::fixed << std::setprecision(precision); for (size_t i = 0; i < vertices.size(); ++i) { out << "v " << vertices[i][0] << " " << vertices[i][1] << " " << vertices[i][2] << "\n"; } for (size_t i = 0; i < texcoords.size(); ++i) { out << "vt " << texcoords[i][0] << " " << texcoords[i][1] << "\n"; } for (size_t i = 0; i < normals.size(); ++i) { out << "vn " << normals[i][0] << " " << normals[i][1] << " " << normals[i][2] << "\n"; } for (size_t i = 0; i < groups.size(); ++i) { out << "usemtl " << groups[i].material_name << "\n"; for (size_t j = 0; j < groups[i].faces.size(); ++j) { const Face& face = groups[i].faces[j]; out << "f"; for (size_t k = 0; k < 3; ++k) { out << " " << face.vertices[k] + OBJ_INDEX_OFFSET; if (!texcoords.empty()) { out << "/" << face.texcoords[k] + OBJ_INDEX_OFFSET; if (!normals.empty()) out << "/" << face.normals[k] + OBJ_INDEX_OFFSET; } else if (!normals.empty()) out << "//" << face.normals[k] + OBJ_INDEX_OFFSET; } out << "\n"; } } return true; } bool ObjModel::Load(const String& fileName) { ASSERT(vertices.empty() && groups.empty() && material_lib.materials.empty()); std::ifstream fin(fileName.c_str()); String line, keyword; std::istringstream in; while (fin.good()) { std::getline(fin, line); if (line.empty() || line[0u] == '#') continue; in.str(line); in >> keyword; if (keyword == "v") { Vertex v; in >> v[0] >> v[1] >> v[2]; if (in.fail()) return false; vertices.push_back(v); } else if (keyword == "vt") { TexCoord vt; in >> vt[0] >> vt[1]; if (in.fail()) return false; texcoords.push_back(vt); } else if (keyword == "vn") { Normal vn; in >> vn[0] >> vn[1] >> vn[2]; if (in.fail()) return false; normals.push_back(vn); } else if (keyword == "f") { Face f; memset(&f, 0xFF, sizeof(Face)); for (size_t k = 0; k < 3; ++k) { in >> keyword; switch (sscanf(keyword, "%u/%u/%u", f.vertices+k, f.texcoords+k, f.normals+k)) { case 1: f.vertices[k] -= OBJ_INDEX_OFFSET; break; case 2: f.vertices[k] -= OBJ_INDEX_OFFSET; if (f.texcoords[k] != NO_ID) f.texcoords[k] -= OBJ_INDEX_OFFSET; if (f.normals[k] != NO_ID) f.normals[k] -= OBJ_INDEX_OFFSET; break; case 3: f.vertices[k] -= OBJ_INDEX_OFFSET; f.texcoords[k] -= OBJ_INDEX_OFFSET; f.normals[k] -= OBJ_INDEX_OFFSET; break; default: return false; } } if (in.fail()) return false; if (groups.empty()) AddGroup(""); groups.back().faces.push_back(f); } else if (keyword == "mtllib") { in >> keyword; if (!material_lib.Load(keyword)) return false; } else if (keyword == "usemtl") { Group group; in >> group.material_name; if (in.fail()) return false; groups.push_back(group); } in.clear(); } return !vertices.empty(); } ObjModel::Group& ObjModel::AddGroup(const String& material_name) { groups.push_back(Group()); Group& group = groups.back(); group.material_name = material_name; if (!GetMaterial(material_name)) material_lib.materials.push_back(MaterialLib::Material(material_name)); return group; } ObjModel::MaterialLib::Material* ObjModel::GetMaterial(const String& name) { MaterialLib::Materials::iterator it(std::find_if(material_lib.materials.begin(), material_lib.materials.end(), [&name](const MaterialLib::Material& mat) { return mat.name == name; })); if (it == material_lib.materials.end()) return NULL; return &(*it); } /*----------------------------------------------------------------*/ <|endoftext|>
<commit_before>#include "SM_Polyline.h" #include <cavc/polylineoffset.hpp> namespace sm { std::vector<std::vector<vec2>> polyline_offset(const std::vector<vec2>& polyline, float distance, bool is_closed) { cavc::Polyline<float> input; input.isClosed() = is_closed; const size_t n = is_closed ? polyline.size() - 1 : polyline.size(); for (int i = 0; i < n; ++i) { input.addVertex(polyline[i].x, polyline[i].y, 0.0f); } auto results = cavc::parallelOffset(input, distance); std::vector<std::vector<vec2>> polylines; for (auto& src : results) { std::vector<vec2> dst; for (auto& pos : src.vertexes()) { dst.push_back(sm::vec2(pos.x(), pos.y())); } polylines.push_back(dst); } return polylines; } std::vector<std::vector<vec2>> polyline_expand(const std::vector<vec2>& polyline, float offste, bool is_closed) { std::vector<std::vector<sm::vec2>> ret; auto off0 = polyline_offset(polyline, offste, is_closed); auto off1 = polyline_offset(polyline, -offste, is_closed); if (off0.size() != off1.size() || off0.empty()) { return ret; } for (int i = 0, n = off0.size(); i < n; ++i) { auto off(off0[i]); std::copy(off1[i].rbegin(), off1[i].rend(), std::back_inserter(off)); ret.push_back(off); } return ret; } }<commit_msg>fix poly_offset<commit_after>#include "SM_Polyline.h" #include <cavc/polylineoffset.hpp> namespace sm { std::vector<std::vector<vec2>> polyline_offset(const std::vector<vec2>& polyline, float distance, bool is_closed) { cavc::Polyline<float> input; input.isClosed() = is_closed; const size_t n = (is_closed && polyline.front() == polyline.back()) ? polyline.size() - 1 : polyline.size(); for (int i = 0; i < n; ++i) { input.addVertex(polyline[i].x, polyline[i].y, 0.0f); } auto results = cavc::parallelOffset(input, distance); std::vector<std::vector<vec2>> polylines; for (auto& src : results) { std::vector<vec2> dst; for (auto& pos : src.vertexes()) { dst.push_back(sm::vec2(pos.x(), pos.y())); } polylines.push_back(dst); } return polylines; } std::vector<std::vector<vec2>> polyline_expand(const std::vector<vec2>& polyline, float offste, bool is_closed) { std::vector<std::vector<sm::vec2>> ret; auto off0 = polyline_offset(polyline, offste, is_closed); auto off1 = polyline_offset(polyline, -offste, is_closed); if (off0.size() != off1.size() || off0.empty()) { return ret; } for (int i = 0, n = off0.size(); i < n; ++i) { auto off(off0[i]); std::copy(off1[i].rbegin(), off1[i].rend(), std::back_inserter(off)); ret.push_back(off); } return ret; } }<|endoftext|>
<commit_before>// // ogrfielddefn.cc // // // Copyright (c) 2011, JF Gigand // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "php.h" #include "php_gdal.h" #include <ogr_feature.h> #include "ogrfielddefn.h" zend_class_entry *gdal_ogrfielddefn_ce; zend_object_handlers ogrfielddefn_object_handlers; // // PHP stuff // void ogrfielddefn_free_storage(void *object TSRMLS_DC) { php_ogrfielddefn_object *obj = (php_ogrfielddefn_object *)object; //delete obj->fielddefn; // TODO zend_hash_destroy(obj->std.properties); FREE_HASHTABLE(obj->std.properties); efree(obj); } zend_object_value ogrfielddefn_create_handler(zend_class_entry *type TSRMLS_DC) { zval *tmp; zend_object_value retval; php_ogrfielddefn_object *obj = (php_ogrfielddefn_object *)emalloc(sizeof(php_ogrfielddefn_object)); memset(obj, 0, sizeof(php_ogrfielddefn_object)); obj->std.ce = type; ALLOC_HASHTABLE(obj->std.properties); zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0); #if PHP_VERSION_ID < 50399 zend_hash_copy(obj->std.properties, &type->default_properties, (copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *)); #else object_properties_init(&obj->std, type); #endif retval.handle = zend_objects_store_put(obj, NULL, ogrfielddefn_free_storage, NULL TSRMLS_CC); retval.handlers = &ogrfielddefn_object_handlers; return retval; //pdo_stmt_construct(stmt, return_value, dbstmt_ce, ctor_args TSRMLS_CC); } // // CLASS METHODS // PHP_METHOD(OGRFieldDefn, SetName) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; char *name; int name_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"s", &name, &name_len) == FAILURE) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; fielddefn->SetName(name); } PHP_METHOD(OGRFieldDefn, GetNameRef) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; if (ZEND_NUM_ARGS() != 0) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; const char *name = fielddefn->GetNameRef(); if (name) { RETURN_STRING((char *)name, 1); } else { RETURN_NULL(); } } PHP_METHOD(OGRFieldDefn, GetType) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; if (ZEND_NUM_ARGS() != 0) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; RETURN_LONG((long)fielddefn->GetType()); } PHP_METHOD(OGRFieldDefn, SetType) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; long type; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l", &type) == FAILURE) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; fielddefn->SetType((OGRFieldType)type); } PHP_METHOD(OGRFieldDefn, GetJustify) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; if (ZEND_NUM_ARGS() != 0) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; RETURN_LONG((long)fielddefn->GetJustify()); } PHP_METHOD(OGRFieldDefn, SetJustify) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; long justification; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l", &justification) == FAILURE) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; fielddefn->SetJustify((OGRJustification)justification); } PHP_METHOD(OGRFieldDefn, GetWidth) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; if (ZEND_NUM_ARGS() != 0) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; RETURN_LONG(fielddefn->GetWidth()); } PHP_METHOD(OGRFieldDefn, SetWidth) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; long width; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l", &width) == FAILURE) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; fielddefn->SetWidth(width); } PHP_METHOD(OGRFieldDefn, GetPrecision) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; if (ZEND_NUM_ARGS() != 0) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; RETURN_LONG(fielddefn->GetPrecision()); } PHP_METHOD(OGRFieldDefn, SetPrecision) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; long precision; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l", &precision) == FAILURE) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; fielddefn->SetPrecision(precision); } // // PHP stuff // zend_function_entry ogrfielddefn_methods[] = { PHP_ME(OGRFieldDefn, SetName, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, GetNameRef, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, GetType, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, SetType, NULL, ZEND_ACC_PUBLIC) // PHP_ME(OGRFieldDefn, GetFieldTypeName, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, GetJustify, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, SetJustify, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, GetWidth, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, SetWidth, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, GetPrecision, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, SetPrecision, NULL, ZEND_ACC_PUBLIC) // PHP_ME(OGRFieldDefn, Set, NULL, ZEND_ACC_PUBLIC) // PHP_ME(OGRFieldDefn, SetDefault, NULL, ZEND_ACC_PUBLIC) // PHP_ME(OGRFieldDefn, GetDefaultRef, NULL, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; void php_gdal_ogrfielddefn_startup(INIT_FUNC_ARGS) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "OGRFieldDefn", ogrfielddefn_methods); gdal_ogrfielddefn_ce = zend_register_internal_class(&ce TSRMLS_CC); gdal_ogrfielddefn_ce->create_object = ogrfielddefn_create_handler; memcpy(&ogrfielddefn_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); ogrfielddefn_object_handlers.clone_obj = NULL; } <commit_msg>Constructor with name and field type for OGRFieldDefn<commit_after>// // ogrfielddefn.cc // // // Copyright (c) 2011, JF Gigand // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "php.h" #include "php_gdal.h" #include <ogr_feature.h> #include "ogrfielddefn.h" zend_class_entry *gdal_ogrfielddefn_ce; zend_object_handlers ogrfielddefn_object_handlers; // // PHP stuff // void ogrfielddefn_free_storage(void *object TSRMLS_DC) { php_ogrfielddefn_object *obj = (php_ogrfielddefn_object *)object; //delete obj->fielddefn; // TODO zend_hash_destroy(obj->std.properties); FREE_HASHTABLE(obj->std.properties); efree(obj); } zend_object_value ogrfielddefn_create_handler(zend_class_entry *type TSRMLS_DC) { zval *tmp; zend_object_value retval; php_ogrfielddefn_object *obj = (php_ogrfielddefn_object *)emalloc(sizeof(php_ogrfielddefn_object)); memset(obj, 0, sizeof(php_ogrfielddefn_object)); obj->std.ce = type; ALLOC_HASHTABLE(obj->std.properties); zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0); #if PHP_VERSION_ID < 50399 zend_hash_copy(obj->std.properties, &type->default_properties, (copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *)); #else object_properties_init(&obj->std, type); #endif retval.handle = zend_objects_store_put(obj, NULL, ogrfielddefn_free_storage, NULL TSRMLS_CC); retval.handlers = &ogrfielddefn_object_handlers; return retval; //pdo_stmt_construct(stmt, return_value, dbstmt_ce, ctor_args TSRMLS_CC); } // // CLASS METHODS // PHP_METHOD(OGRFieldDefn, __construct) { php_ogrfielddefn_object *obj; char *name; int name_len; long type; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"sl", &name, &name_len, &type) == FAILURE) { return; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); obj->fielddefn = new OGRFieldDefn(name, (OGRFieldType)type); } PHP_METHOD(OGRFieldDefn, SetName) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; char *name; int name_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"s", &name, &name_len) == FAILURE) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; fielddefn->SetName(name); } PHP_METHOD(OGRFieldDefn, GetNameRef) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; if (ZEND_NUM_ARGS() != 0) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; const char *name = fielddefn->GetNameRef(); if (name) { RETURN_STRING((char *)name, 1); } else { RETURN_NULL(); } } PHP_METHOD(OGRFieldDefn, GetType) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; if (ZEND_NUM_ARGS() != 0) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; RETURN_LONG((long)fielddefn->GetType()); } PHP_METHOD(OGRFieldDefn, SetType) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; long type; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l", &type) == FAILURE) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; fielddefn->SetType((OGRFieldType)type); } PHP_METHOD(OGRFieldDefn, GetJustify) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; if (ZEND_NUM_ARGS() != 0) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; RETURN_LONG((long)fielddefn->GetJustify()); } PHP_METHOD(OGRFieldDefn, SetJustify) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; long justification; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l", &justification) == FAILURE) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; fielddefn->SetJustify((OGRJustification)justification); } PHP_METHOD(OGRFieldDefn, GetWidth) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; if (ZEND_NUM_ARGS() != 0) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; RETURN_LONG(fielddefn->GetWidth()); } PHP_METHOD(OGRFieldDefn, SetWidth) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; long width; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l", &width) == FAILURE) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; fielddefn->SetWidth(width); } PHP_METHOD(OGRFieldDefn, GetPrecision) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; if (ZEND_NUM_ARGS() != 0) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; RETURN_LONG(fielddefn->GetPrecision()); } PHP_METHOD(OGRFieldDefn, SetPrecision) { OGRFieldDefn *fielddefn; php_ogrfielddefn_object *obj; long precision; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l", &precision) == FAILURE) { WRONG_PARAM_COUNT; } obj = (php_ogrfielddefn_object *) zend_object_store_get_object(getThis() TSRMLS_CC); fielddefn = obj->fielddefn; fielddefn->SetPrecision(precision); } // // PHP stuff // zend_function_entry ogrfielddefn_methods[] = { PHP_ME(OGRFieldDefn, __construct, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, SetName, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, GetNameRef, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, GetType, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, SetType, NULL, ZEND_ACC_PUBLIC) // PHP_ME(OGRFieldDefn, GetFieldTypeName, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, GetJustify, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, SetJustify, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, GetWidth, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, SetWidth, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, GetPrecision, NULL, ZEND_ACC_PUBLIC) PHP_ME(OGRFieldDefn, SetPrecision, NULL, ZEND_ACC_PUBLIC) // PHP_ME(OGRFieldDefn, Set, NULL, ZEND_ACC_PUBLIC) // PHP_ME(OGRFieldDefn, SetDefault, NULL, ZEND_ACC_PUBLIC) // PHP_ME(OGRFieldDefn, GetDefaultRef, NULL, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; void php_gdal_ogrfielddefn_startup(INIT_FUNC_ARGS) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "OGRFieldDefn", ogrfielddefn_methods); gdal_ogrfielddefn_ce = zend_register_internal_class(&ce TSRMLS_CC); gdal_ogrfielddefn_ce->create_object = ogrfielddefn_create_handler; memcpy(&ogrfielddefn_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); ogrfielddefn_object_handlers.clone_obj = NULL; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkAxesTransformRepresentation.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAxesTransformRepresentation.h" #include "vtkPointHandleRepresentation3D.h" #include "vtkPolyDataMapper.h" #include "vtkPoints.h" #include "vtkCellArray.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkVectorText.h" #include "vtkFollower.h" #include "vtkCamera.h" #include "vtkProperty.h" #include "vtkCoordinate.h" #include "vtkRenderer.h" #include "vtkObjectFactory.h" #include "vtkInteractorObserver.h" #include "vtkMath.h" #include "vtkWindow.h" #include "vtkSmartPointer.h" #include "vtkBox.h" #include "vtkGlyph3D.h" #include "vtkCylinderSource.h" #include "vtkDoubleArray.h" #include "vtkPointData.h" #include "vtkTransformPolyDataFilter.h" #include "vtkTransform.h" #include "vtkSmartPointer.h" vtkStandardNewMacro(vtkAxesTransformRepresentation); //---------------------------------------------------------------------- vtkAxesTransformRepresentation::vtkAxesTransformRepresentation() { // By default, use one of these handles this->OriginRepresentation = vtkPointHandleRepresentation3D::New(); this->SelectionRepresentation = vtkPointHandleRepresentation3D::New(); // The line this->LinePoints = vtkPoints::New(); this->LinePoints->SetDataTypeToDouble(); this->LinePoints->SetNumberOfPoints(2); this->LinePolyData = vtkPolyData::New(); this->LinePolyData->SetPoints(this->LinePoints); vtkSmartPointer<vtkCellArray> line = vtkSmartPointer<vtkCellArray>::New(); line->InsertNextCell(2); line->InsertCellPoint(0); line->InsertCellPoint(1); this->LinePolyData->SetLines(line); this->LineMapper = vtkPolyDataMapper::New(); this->LineMapper->SetInput(this->LinePolyData); this->LineActor = vtkActor::New(); this->LineActor->SetMapper(this->LineMapper); // The label this->LabelText = vtkVectorText::New(); this->LabelMapper = vtkPolyDataMapper::New(); this->LabelMapper->SetInputConnection(this->LabelText->GetOutputPort()); this->LabelActor = vtkFollower::New(); this->LabelActor->SetMapper(this->LabelMapper); // The tick marks this->GlyphPoints = vtkPoints::New(); this->GlyphPoints->SetDataTypeToDouble(); this->GlyphVectors = vtkDoubleArray::New(); this->GlyphVectors->SetNumberOfComponents(3); this->GlyphPolyData = vtkPolyData::New(); this->GlyphPolyData->SetPoints(this->GlyphPoints); this->GlyphPolyData->GetPointData()->SetVectors(this->GlyphVectors); this->GlyphCylinder = vtkCylinderSource::New(); this->GlyphCylinder->SetRadius(0.5); this->GlyphCylinder->SetHeight(0.1); this->GlyphCylinder->SetResolution(12); vtkSmartPointer<vtkTransform> xform = vtkSmartPointer<vtkTransform>::New(); this->GlyphXForm = vtkTransformPolyDataFilter::New(); this->GlyphXForm->SetInputConnection(this->GlyphCylinder->GetOutputPort()); this->GlyphXForm->SetTransform(xform); xform->RotateZ(90); this->Glyph3D = vtkGlyph3D::New(); this->Glyph3D->SetInput(this->GlyphPolyData); this->Glyph3D->SetSourceConnection(this->GlyphXForm->GetOutputPort()); this->Glyph3D->SetScaleModeToDataScalingOff(); this->GlyphMapper = vtkPolyDataMapper::New(); this->GlyphMapper->SetInputConnection(this->Glyph3D->GetOutputPort()); this->GlyphActor = vtkActor::New(); this->GlyphActor->SetMapper(this->GlyphMapper); // The bounding box this->BoundingBox = vtkBox::New(); } //---------------------------------------------------------------------- vtkAxesTransformRepresentation::~vtkAxesTransformRepresentation() { this->LinePoints->Delete(); this->LinePolyData->Delete(); this->LineMapper->Delete(); this->LineActor->Delete(); this->LabelText->Delete(); this->LabelMapper->Delete(); this->LabelActor->Delete(); this->GlyphPoints->Delete(); this->GlyphVectors->Delete(); this->GlyphPolyData->Delete(); this->GlyphCylinder->Delete(); this->GlyphXForm->Delete(); this->Glyph3D->Delete(); this->GlyphMapper->Delete(); this->GlyphActor->Delete(); this->BoundingBox->Delete(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::GetOriginWorldPosition(double pos[3]) { this->OriginRepresentation->GetWorldPosition(pos); } //---------------------------------------------------------------------- double* vtkAxesTransformRepresentation::GetOriginWorldPosition() { if (!this->OriginRepresentation) { static double temp[3]= {0, 0, 0}; return temp; } return this->OriginRepresentation->GetWorldPosition(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::SetOriginDisplayPosition(double x[3]) { this->OriginRepresentation->SetDisplayPosition(x); double p[3]; this->OriginRepresentation->GetWorldPosition(p); this->OriginRepresentation->SetWorldPosition(p); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::SetOriginWorldPosition(double x[3]) { if (this->OriginRepresentation) { this->OriginRepresentation->SetWorldPosition(x); } } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::GetOriginDisplayPosition(double pos[3]) { this->OriginRepresentation->GetDisplayPosition(pos); pos[2] = 0.0; } //---------------------------------------------------------------------- double *vtkAxesTransformRepresentation::GetBounds() { this->BuildRepresentation(); this->BoundingBox->SetBounds(this->OriginRepresentation->GetBounds()); this->BoundingBox->AddBounds(this->SelectionRepresentation->GetBounds()); this->BoundingBox->AddBounds(this->LineActor->GetBounds()); return this->BoundingBox->GetBounds(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::StartWidgetInteraction(double e[2]) { // Store the start position this->StartEventPosition[0] = e[0]; this->StartEventPosition[1] = e[1]; this->StartEventPosition[2] = 0.0; // Store the start position this->LastEventPosition[0] = e[0]; this->LastEventPosition[1] = e[1]; this->LastEventPosition[2] = 0.0; // Get the coordinates of the three handles // this->OriginRepresentation->GetWorldPosition(this->StartP1); // this->SelectionRepresentation->GetWorldPosition(this->StartP2); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::WidgetInteraction(double e[2]) { // Store the start position this->LastEventPosition[0] = e[0]; this->LastEventPosition[1] = e[1]; this->LastEventPosition[2] = 0.0; } //---------------------------------------------------------------------------- int vtkAxesTransformRepresentation::ComputeInteractionState(int X, int Y, int vtkNotUsed(modify)) { // Check if we are on the origin. Use the handle to determine this. int p1State = this->OriginRepresentation->ComputeInteractionState(X,Y,0); if ( p1State == vtkHandleRepresentation::Nearby ) { this->InteractionState = vtkAxesTransformRepresentation::OnOrigin; // this->SetRepresentationState(vtkAxesTransformRepresentation::OnOrigin); } else { this->InteractionState = vtkAxesTransformRepresentation::Outside; } // Okay if we're near a handle return, otherwise test the line if ( this->InteractionState != vtkAxesTransformRepresentation::Outside ) { return this->InteractionState; } return this->InteractionState; } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::BuildRepresentation() { if ( this->GetMTime() > this->BuildTime || this->OriginRepresentation->GetMTime() > this->BuildTime || this->SelectionRepresentation->GetMTime() > this->BuildTime || (this->Renderer && this->Renderer->GetVTKWindow() && this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime) ) { this->BuildTime.Modified(); } } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation:: ReleaseGraphicsResources(vtkWindow *w) { this->LineActor->ReleaseGraphicsResources(w); this->LabelActor->ReleaseGraphicsResources(w); this->GlyphActor->ReleaseGraphicsResources(w); } //---------------------------------------------------------------------- int vtkAxesTransformRepresentation:: RenderOpaqueGeometry(vtkViewport *v) { this->BuildRepresentation(); this->LineActor->RenderOpaqueGeometry(v); this->LabelActor->RenderOpaqueGeometry(v); this->GlyphActor->RenderOpaqueGeometry(v); return 3; } //---------------------------------------------------------------------- int vtkAxesTransformRepresentation:: RenderTranslucentPolygonalGeometry(vtkViewport *v) { this->BuildRepresentation(); this->LineActor->RenderTranslucentPolygonalGeometry(v); this->LabelActor->RenderTranslucentPolygonalGeometry(v); this->GlyphActor->RenderTranslucentPolygonalGeometry(v); return 3; } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::SetLabelScale( double scale[3] ) { this->LabelActor->SetScale( scale ); } //---------------------------------------------------------------------- double * vtkAxesTransformRepresentation::GetLabelScale() { return this->LabelActor->GetScale(); } //---------------------------------------------------------------------------- vtkProperty * vtkAxesTransformRepresentation::GetLabelProperty() { return this->LabelActor->GetProperty(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } <commit_msg>Fix Widgets printself test.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkAxesTransformRepresentation.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAxesTransformRepresentation.h" #include "vtkPointHandleRepresentation3D.h" #include "vtkPolyDataMapper.h" #include "vtkPoints.h" #include "vtkCellArray.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkVectorText.h" #include "vtkFollower.h" #include "vtkCamera.h" #include "vtkProperty.h" #include "vtkCoordinate.h" #include "vtkRenderer.h" #include "vtkObjectFactory.h" #include "vtkInteractorObserver.h" #include "vtkMath.h" #include "vtkWindow.h" #include "vtkSmartPointer.h" #include "vtkBox.h" #include "vtkGlyph3D.h" #include "vtkCylinderSource.h" #include "vtkDoubleArray.h" #include "vtkPointData.h" #include "vtkTransformPolyDataFilter.h" #include "vtkTransform.h" #include "vtkSmartPointer.h" vtkStandardNewMacro(vtkAxesTransformRepresentation); //---------------------------------------------------------------------- vtkAxesTransformRepresentation::vtkAxesTransformRepresentation() { // By default, use one of these handles this->OriginRepresentation = vtkPointHandleRepresentation3D::New(); this->SelectionRepresentation = vtkPointHandleRepresentation3D::New(); // The line this->LinePoints = vtkPoints::New(); this->LinePoints->SetDataTypeToDouble(); this->LinePoints->SetNumberOfPoints(2); this->LinePolyData = vtkPolyData::New(); this->LinePolyData->SetPoints(this->LinePoints); vtkSmartPointer<vtkCellArray> line = vtkSmartPointer<vtkCellArray>::New(); line->InsertNextCell(2); line->InsertCellPoint(0); line->InsertCellPoint(1); this->LinePolyData->SetLines(line); this->LineMapper = vtkPolyDataMapper::New(); this->LineMapper->SetInput(this->LinePolyData); this->LineActor = vtkActor::New(); this->LineActor->SetMapper(this->LineMapper); // The label this->LabelText = vtkVectorText::New(); this->LabelMapper = vtkPolyDataMapper::New(); this->LabelMapper->SetInputConnection(this->LabelText->GetOutputPort()); this->LabelActor = vtkFollower::New(); this->LabelActor->SetMapper(this->LabelMapper); // The tick marks this->GlyphPoints = vtkPoints::New(); this->GlyphPoints->SetDataTypeToDouble(); this->GlyphVectors = vtkDoubleArray::New(); this->GlyphVectors->SetNumberOfComponents(3); this->GlyphPolyData = vtkPolyData::New(); this->GlyphPolyData->SetPoints(this->GlyphPoints); this->GlyphPolyData->GetPointData()->SetVectors(this->GlyphVectors); this->GlyphCylinder = vtkCylinderSource::New(); this->GlyphCylinder->SetRadius(0.5); this->GlyphCylinder->SetHeight(0.1); this->GlyphCylinder->SetResolution(12); vtkSmartPointer<vtkTransform> xform = vtkSmartPointer<vtkTransform>::New(); this->GlyphXForm = vtkTransformPolyDataFilter::New(); this->GlyphXForm->SetInputConnection(this->GlyphCylinder->GetOutputPort()); this->GlyphXForm->SetTransform(xform); xform->RotateZ(90); this->Glyph3D = vtkGlyph3D::New(); this->Glyph3D->SetInput(this->GlyphPolyData); this->Glyph3D->SetSourceConnection(this->GlyphXForm->GetOutputPort()); this->Glyph3D->SetScaleModeToDataScalingOff(); this->GlyphMapper = vtkPolyDataMapper::New(); this->GlyphMapper->SetInputConnection(this->Glyph3D->GetOutputPort()); this->GlyphActor = vtkActor::New(); this->GlyphActor->SetMapper(this->GlyphMapper); // The bounding box this->BoundingBox = vtkBox::New(); } //---------------------------------------------------------------------- vtkAxesTransformRepresentation::~vtkAxesTransformRepresentation() { this->LinePoints->Delete(); this->LinePolyData->Delete(); this->LineMapper->Delete(); this->LineActor->Delete(); this->LabelText->Delete(); this->LabelMapper->Delete(); this->LabelActor->Delete(); this->GlyphPoints->Delete(); this->GlyphVectors->Delete(); this->GlyphPolyData->Delete(); this->GlyphCylinder->Delete(); this->GlyphXForm->Delete(); this->Glyph3D->Delete(); this->GlyphMapper->Delete(); this->GlyphActor->Delete(); this->BoundingBox->Delete(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::GetOriginWorldPosition(double pos[3]) { this->OriginRepresentation->GetWorldPosition(pos); } //---------------------------------------------------------------------- double* vtkAxesTransformRepresentation::GetOriginWorldPosition() { if (!this->OriginRepresentation) { static double temp[3]= {0, 0, 0}; return temp; } return this->OriginRepresentation->GetWorldPosition(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::SetOriginDisplayPosition(double x[3]) { this->OriginRepresentation->SetDisplayPosition(x); double p[3]; this->OriginRepresentation->GetWorldPosition(p); this->OriginRepresentation->SetWorldPosition(p); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::SetOriginWorldPosition(double x[3]) { if (this->OriginRepresentation) { this->OriginRepresentation->SetWorldPosition(x); } } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::GetOriginDisplayPosition(double pos[3]) { this->OriginRepresentation->GetDisplayPosition(pos); pos[2] = 0.0; } //---------------------------------------------------------------------- double *vtkAxesTransformRepresentation::GetBounds() { this->BuildRepresentation(); this->BoundingBox->SetBounds(this->OriginRepresentation->GetBounds()); this->BoundingBox->AddBounds(this->SelectionRepresentation->GetBounds()); this->BoundingBox->AddBounds(this->LineActor->GetBounds()); return this->BoundingBox->GetBounds(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::StartWidgetInteraction(double e[2]) { // Store the start position this->StartEventPosition[0] = e[0]; this->StartEventPosition[1] = e[1]; this->StartEventPosition[2] = 0.0; // Store the start position this->LastEventPosition[0] = e[0]; this->LastEventPosition[1] = e[1]; this->LastEventPosition[2] = 0.0; // Get the coordinates of the three handles // this->OriginRepresentation->GetWorldPosition(this->StartP1); // this->SelectionRepresentation->GetWorldPosition(this->StartP2); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::WidgetInteraction(double e[2]) { // Store the start position this->LastEventPosition[0] = e[0]; this->LastEventPosition[1] = e[1]; this->LastEventPosition[2] = 0.0; } //---------------------------------------------------------------------------- int vtkAxesTransformRepresentation::ComputeInteractionState(int X, int Y, int vtkNotUsed(modify)) { // Check if we are on the origin. Use the handle to determine this. int p1State = this->OriginRepresentation->ComputeInteractionState(X,Y,0); if ( p1State == vtkHandleRepresentation::Nearby ) { this->InteractionState = vtkAxesTransformRepresentation::OnOrigin; // this->SetRepresentationState(vtkAxesTransformRepresentation::OnOrigin); } else { this->InteractionState = vtkAxesTransformRepresentation::Outside; } // Okay if we're near a handle return, otherwise test the line if ( this->InteractionState != vtkAxesTransformRepresentation::Outside ) { return this->InteractionState; } return this->InteractionState; } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::BuildRepresentation() { if ( this->GetMTime() > this->BuildTime || this->OriginRepresentation->GetMTime() > this->BuildTime || this->SelectionRepresentation->GetMTime() > this->BuildTime || (this->Renderer && this->Renderer->GetVTKWindow() && this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime) ) { this->BuildTime.Modified(); } } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation:: ReleaseGraphicsResources(vtkWindow *w) { this->LineActor->ReleaseGraphicsResources(w); this->LabelActor->ReleaseGraphicsResources(w); this->GlyphActor->ReleaseGraphicsResources(w); } //---------------------------------------------------------------------- int vtkAxesTransformRepresentation:: RenderOpaqueGeometry(vtkViewport *v) { this->BuildRepresentation(); this->LineActor->RenderOpaqueGeometry(v); this->LabelActor->RenderOpaqueGeometry(v); this->GlyphActor->RenderOpaqueGeometry(v); return 3; } //---------------------------------------------------------------------- int vtkAxesTransformRepresentation:: RenderTranslucentPolygonalGeometry(vtkViewport *v) { this->BuildRepresentation(); this->LineActor->RenderTranslucentPolygonalGeometry(v); this->LabelActor->RenderTranslucentPolygonalGeometry(v); this->GlyphActor->RenderTranslucentPolygonalGeometry(v); return 3; } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::SetLabelScale( double scale[3] ) { this->LabelActor->SetScale( scale ); } //---------------------------------------------------------------------- double * vtkAxesTransformRepresentation::GetLabelScale() { return this->LabelActor->GetScale(); } //---------------------------------------------------------------------------- vtkProperty * vtkAxesTransformRepresentation::GetLabelProperty() { return this->LabelActor->GetProperty(); } //---------------------------------------------------------------------- void vtkAxesTransformRepresentation::PrintSelf(ostream& os, vtkIndent indent) { std::cout << "LabelFormat: " << this->LabelFormat << std::endl; std::cout << "Tolerance: " << this->Tolerance << std::endl; std::cout << "InteractionState: " << this->InteractionState << std::endl; std::cout << "OriginRepresentation: " << this->OriginRepresentation << endl; std::cout << "SelectionRepresentation: " << this->SelectionRepresentation << endl; this->Superclass::PrintSelf(os,indent); } <|endoftext|>
<commit_before> //#define __STRICT_ANSI__ #define ERROR_VALUE -1 #include "SerialClass.h" #include "stdio.h" #include <string> #include <errno.h> #include "error.h" Serial::Serial(char *portName) { // We're not yet connected this->connected = false; #ifdef _WIN32 // Try to connect to the given port throuh CreateFile this->hSerial = CreateFileA(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // Check if the connection was successfull if (this->hSerial == INVALID_HANDLE_VALUE) { // If not success full display an Error if (GetLastError() == ERROR_FILE_NOT_FOUND) { // Print Error if neccessary throw new Error(ConsoleColor(ConsoleColor::red),"Error: Handle was not attached. Reason: %s not available.\n", portName); } else { throw new Error(ConsoleColor(ConsoleColor::red),"Unknown error on com port!"); } } else { // If connected we try to set the comm parameters DCB dcbSerialParams = {0}; // Try to get the current if (!GetCommState(this->hSerial, &dcbSerialParams)) { // If impossible, show an error printf("failed to get current serial parameters!"); } else { // Define serial connection parameters for the arduino board dcbSerialParams.BaudRate = CBR_9600; dcbSerialParams.ByteSize = 8; dcbSerialParams.StopBits = ONESTOPBIT; dcbSerialParams.Parity = NOPARITY; dcbSerialParams.XonLim = 42; dcbSerialParams.XoffLim = 42; dcbSerialParams.fAbortOnError = TRUE; dcbSerialParams.fDtrControl = DTR_CONTROL_HANDSHAKE; dcbSerialParams.fRtsControl = RTS_CONTROL_HANDSHAKE; dcbSerialParams.fBinary = TRUE; dcbSerialParams.fParity = FALSE; dcbSerialParams.fInX = FALSE; dcbSerialParams.fOutX = FALSE; dcbSerialParams.XonChar = (unsigned char) 0x11; dcbSerialParams.XoffChar = (unsigned char) 0x13; dcbSerialParams.fErrorChar = FALSE; dcbSerialParams.fNull = FALSE; dcbSerialParams.fOutxCtsFlow = FALSE; dcbSerialParams.fOutxDsrFlow = FALSE; // Set the parameters and check for their proper application if (!SetCommState(hSerial, &dcbSerialParams)) { throw new Error(ConsoleColor(ConsoleColor::red),"Error: Could not set Serial Port parameters"); } else { // If everything went fine we're connected this->connected = true; // Flush any remaining characters in the buffers PurgeComm(this->hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR); // We wait 2s as the arduino board will be reseting Sleep(ARDUINO_WAIT_TIME); } } } #else com = open(portName, O_RDWR | O_NOCTTY); memset(&tty, 0, sizeof tty); /* Error Handling */ if (tcgetattr(com, &tty) != 0) { throw new Error(ConsoleColor(ConsoleColor::red),"Error handling %d from tcgetattr: %s\n", errno, strerror(errno)); } /* Save old tty parameters */ tty_old = tty; /* Set Baud Rate */ cfsetospeed(&tty, (speed_t)B9600); /* Setting other Port Stuff */ tty.c_cflag &= ~PARENB; // Make 8n1 tty.c_cflag &= ~CSTOPB; tty.c_cflag &= ~CSIZE; tty.c_cflag |= CS8; tty.c_cflag &= ~CRTSCTS; // no flow control tty.c_cc[VMIN] = 1; // read doesn't block tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines /* Make raw */ cfmakeraw(&tty); /* Flush Port, then applies attributes */ tcflush(com, TCIFLUSH); if (tcsetattr(com, TCSANOW, &tty) != 0) { throw new Error(ConsoleColor(ConsoleColor::red), "Error apply attributes %d from tcsetattr\n", errno); } this->connected = true; #endif } Serial::~Serial() { // Check if we are connected before trying to disconnect if (this->connected) { // We're no longer connected this->connected = false; #ifdef _WIN32 // Close the serial handler CloseHandle(this->hSerial); #else close(com); #endif } } bool Serial::WriteData(unsigned char *buffer, unsigned int nbChar) { #ifdef _WIN32 DWORD bytesSend; // Try to write the buffer on the Serial port if (!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0)) { // In case it don't work get comm error and return false ClearCommError(this->hSerial, &this->errors, &this->status); return false; } else ::Sleep(250); // Sleep 250ms to ensure a good break FlushFileBuffers(this->hSerial); PurgeComm(this->hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR); return true; #else if (write(com, buffer, nbChar) == ERROR_VALUE) { return false; }; return true; #endif } bool Serial::IsConnected() { // Simply return the connection status return this->connected; }<commit_msg>Поправлен баг при сборке под Linux<commit_after> //#define __STRICT_ANSI__ #define ERROR_VALUE -1 #include "SerialClass.h" #include "stdio.h" #include <string> #include "string.h" #include <errno.h> #include "error.h" Serial::Serial(char *portName) { // We're not yet connected this->connected = false; #ifdef _WIN32 // Try to connect to the given port throuh CreateFile this->hSerial = CreateFileA(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // Check if the connection was successfull if (this->hSerial == INVALID_HANDLE_VALUE) { // If not success full display an Error if (GetLastError() == ERROR_FILE_NOT_FOUND) { // Print Error if neccessary throw new Error(ConsoleColor(ConsoleColor::red),"Error: Handle was not attached. Reason: %s not available.\n", portName); } else { throw new Error(ConsoleColor(ConsoleColor::red),"Unknown error on com port!"); } } else { // If connected we try to set the comm parameters DCB dcbSerialParams = {0}; // Try to get the current if (!GetCommState(this->hSerial, &dcbSerialParams)) { // If impossible, show an error printf("failed to get current serial parameters!"); } else { // Define serial connection parameters for the arduino board dcbSerialParams.BaudRate = CBR_9600; dcbSerialParams.ByteSize = 8; dcbSerialParams.StopBits = ONESTOPBIT; dcbSerialParams.Parity = NOPARITY; dcbSerialParams.XonLim = 42; dcbSerialParams.XoffLim = 42; dcbSerialParams.fAbortOnError = TRUE; dcbSerialParams.fDtrControl = DTR_CONTROL_HANDSHAKE; dcbSerialParams.fRtsControl = RTS_CONTROL_HANDSHAKE; dcbSerialParams.fBinary = TRUE; dcbSerialParams.fParity = FALSE; dcbSerialParams.fInX = FALSE; dcbSerialParams.fOutX = FALSE; dcbSerialParams.XonChar = (unsigned char) 0x11; dcbSerialParams.XoffChar = (unsigned char) 0x13; dcbSerialParams.fErrorChar = FALSE; dcbSerialParams.fNull = FALSE; dcbSerialParams.fOutxCtsFlow = FALSE; dcbSerialParams.fOutxDsrFlow = FALSE; // Set the parameters and check for their proper application if (!SetCommState(hSerial, &dcbSerialParams)) { throw new Error(ConsoleColor(ConsoleColor::red),"Error: Could not set Serial Port parameters"); } else { // If everything went fine we're connected this->connected = true; // Flush any remaining characters in the buffers PurgeComm(this->hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR); // We wait 2s as the arduino board will be reseting Sleep(ARDUINO_WAIT_TIME); } } } #else com = open(portName, O_RDWR | O_NOCTTY); memset(&tty, 0, sizeof tty); /* Error Handling */ if (tcgetattr(com, &tty) != 0) { throw new Error(ConsoleColor(ConsoleColor::red),"Error handling %d from tcgetattr: %s\n", errno, strerror(errno)); } /* Save old tty parameters */ tty_old = tty; /* Set Baud Rate */ cfsetospeed(&tty, (speed_t)B9600); /* Setting other Port Stuff */ tty.c_cflag &= ~PARENB; // Make 8n1 tty.c_cflag &= ~CSTOPB; tty.c_cflag &= ~CSIZE; tty.c_cflag |= CS8; tty.c_cflag &= ~CRTSCTS; // no flow control tty.c_cc[VMIN] = 1; // read doesn't block tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines /* Make raw */ cfmakeraw(&tty); /* Flush Port, then applies attributes */ tcflush(com, TCIFLUSH); if (tcsetattr(com, TCSANOW, &tty) != 0) { throw new Error(ConsoleColor(ConsoleColor::red), "Error apply attributes %d from tcsetattr\n", errno); } this->connected = true; #endif } Serial::~Serial() { // Check if we are connected before trying to disconnect if (this->connected) { // We're no longer connected this->connected = false; #ifdef _WIN32 // Close the serial handler CloseHandle(this->hSerial); #else close(com); #endif } } bool Serial::WriteData(unsigned char *buffer, unsigned int nbChar) { #ifdef _WIN32 DWORD bytesSend; // Try to write the buffer on the Serial port if (!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0)) { // In case it don't work get comm error and return false ClearCommError(this->hSerial, &this->errors, &this->status); return false; } else ::Sleep(250); // Sleep 250ms to ensure a good break FlushFileBuffers(this->hSerial); PurgeComm(this->hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR); return true; #else if (write(com, buffer, nbChar) == ERROR_VALUE) { return false; }; return true; #endif } bool Serial::IsConnected() { // Simply return the connection status return this->connected; }<|endoftext|>
<commit_before>/* * Copyright 2010, Milos Pejovic. All rights reserved. * Distributed under the terms of the MIT License. */ #include <support/String.h> #include <stdio.h> #include "ScaleDialog.h" extern char* kOk; extern char* kCancel; const char* kScaleTitle = "Adjust the scale value"; ScaleDialog::ScaleDialog(char* title, float width, float height, char* text, int32 value, int32 minValue, int32 maxValue, int32 step, bool printPartial, bool hideValue) : Dialog(title, width, height) { if (title == NULL) SetTitle(kScaleTitle); fText = (text != NULL ? text : kScaleTitle); fMinValue = (minValue >= 0 ? minValue : 0); fMaxValue = (maxValue > 0 ? maxValue : 100); fStep = (fStep > 0 ? step : 1); fValue = (fValue >= fMinValue && fValue <= fMaxValue ? value : 0); fPrintPartial = printPartial; fHideValue = hideValue; if (width < 1.0) width = 200; if (height < 1.0) height = 110; CreateViews(); ResizeTo(width, height); InitControls(); } void ScaleDialog::CreateViews() { BButton* okayButton = new BButton( BRect(0, 1, 80, 1), "okayButton", kOk, new BMessage(MSG_OK_CLICKED), B_FOLLOW_RIGHT); okayButton->MakeDefault(true); BButton* cancelButton = new BButton( BRect(0, 1, 80, 1), "cancelButton", kCancel, new BMessage(MSG_CANCEL_CLICKED), B_FOLLOW_RIGHT); BStringView* textLabel = new BStringView( BRect(0, 0, 1, 1), NULL, fText); textLabel->SetAlignment(B_ALIGN_LEFT); textLabel->SetExplicitMaxSize( BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); fSlider = new BSlider( BRect(0, 0, 1, 1), "slider", NULL, new BMessage('SlDE'), fMinValue, fMaxValue); fSlider->SetExplicitMaxSize( BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); if (!fHideValue) { BString val; val << fValue; fValueLabel = new BStringView( BRect(0, 0, 1, 1), NULL, val.String()); } // Build the layout SetLayout(new BGroupLayout(B_HORIZONTAL)); BGroupLayoutBuilder builder = BGroupLayoutBuilder(B_VERTICAL, 10).Add(textLabel); if (!fHideValue) builder.Add(BGroupLayoutBuilder(B_HORIZONTAL, 5) .Add(fSlider) .Add(fValueLabel) ); else builder.Add(fSlider); AddChild( builder.AddGlue() .Add(BGroupLayoutBuilder(B_HORIZONTAL, 10) .AddGlue() .Add(cancelButton) .AddGlue() .Add(okayButton) .AddGlue() ) .SetInsets(5, 5, 5, 5) ); } void ScaleDialog::InitControls() { Lock(); fSlider->SetValue(fValue); fSlider->SetKeyIncrementValue(fStep); fSlider->MakeFocus(true); CenterOnScreen(); Unlock(); } void ScaleDialog::MessageReceived(BMessage* message) { switch (message->what) { case MSG_OK_CLICKED: { BString val; val << fSlider->Value(); fprintf(stdout, "%s\n", val.String()); Hide(); be_app->PostMessage(MSG_OK_CLICKED); break; } case MSG_CANCEL_CLICKED: Hide(); be_app->PostMessage(MSG_CANCEL_CLICKED); break; case 'SlDE': { fValue = fSlider->Value(); BString val; val << fValue; if (!fHideValue) fValueLabel->SetText(val.String()); if (fPrintPartial) fprintf(stdout, "%s\n", val.String()); break; } default: Dialog::MessageReceived(message); break; } } <commit_msg>now using ModificationMessage<commit_after>/* * Copyright 2010, Milos Pejovic. All rights reserved. * Distributed under the terms of the MIT License. */ #include <support/String.h> #include <stdio.h> #include "ScaleDialog.h" extern char* kOk; extern char* kCancel; const char* kScaleTitle = "Adjust the scale value"; ScaleDialog::ScaleDialog(char* title, float width, float height, char* text, int32 value, int32 minValue, int32 maxValue, int32 step, bool printPartial, bool hideValue) : Dialog(title, width, height) { if (title == NULL) SetTitle(kScaleTitle); fText = (text != NULL ? text : kScaleTitle); fMinValue = (minValue >= 0 ? minValue : 0); fMaxValue = (maxValue > 0 ? maxValue : 100); fStep = (fStep > 0 ? step : 1); fValue = (fValue >= fMinValue && fValue <= fMaxValue ? value : 0); fPrintPartial = printPartial; fHideValue = hideValue; if (width < 1.0) width = 200; if (height < 1.0) height = 110; CreateViews(); ResizeTo(width, height); InitControls(); } void ScaleDialog::CreateViews() { BButton* okayButton = new BButton( BRect(0, 1, 80, 1), "okayButton", kOk, new BMessage(MSG_OK_CLICKED), B_FOLLOW_RIGHT); okayButton->MakeDefault(true); BButton* cancelButton = new BButton( BRect(0, 1, 80, 1), "cancelButton", kCancel, new BMessage(MSG_CANCEL_CLICKED), B_FOLLOW_RIGHT); BStringView* textLabel = new BStringView( BRect(0, 0, 1, 1), NULL, fText); textLabel->SetAlignment(B_ALIGN_LEFT); textLabel->SetExplicitMaxSize( BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); fSlider = new BSlider( BRect(0, 0, 1, 1), "slider", NULL, NULL, fMinValue, fMaxValue); fSlider->SetModificationMessage(new BMessage('SlDE')); fSlider->SetExplicitMaxSize( BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); if (!fHideValue) { BString val; val << fValue; fValueLabel = new BStringView( BRect(0, 0, 1, 1), NULL, val.String()); } // Build the layout SetLayout(new BGroupLayout(B_HORIZONTAL)); BGroupLayoutBuilder builder = BGroupLayoutBuilder(B_VERTICAL, 10).Add(textLabel); if (!fHideValue) builder.Add(BGroupLayoutBuilder(B_HORIZONTAL, 5) .Add(fSlider) .Add(fValueLabel) ); else builder.Add(fSlider); AddChild( builder.AddGlue() .Add(BGroupLayoutBuilder(B_HORIZONTAL, 10) .AddGlue() .Add(cancelButton) .AddGlue() .Add(okayButton) .AddGlue() ) .SetInsets(5, 5, 5, 5) ); } void ScaleDialog::InitControls() { Lock(); fSlider->SetValue(fValue); fSlider->SetKeyIncrementValue(fStep); fSlider->MakeFocus(true); CenterOnScreen(); Unlock(); } void ScaleDialog::MessageReceived(BMessage* message) { switch (message->what) { case MSG_OK_CLICKED: { BString val; val << fSlider->Value(); fprintf(stdout, "%s\n", val.String()); Hide(); be_app->PostMessage(MSG_OK_CLICKED); break; } case MSG_CANCEL_CLICKED: Hide(); be_app->PostMessage(MSG_CANCEL_CLICKED); break; case 'SlDE': { int32 newValue = fSlider->Value(); // Avoid repeating same numbers if (fValue != newValue) { fValue = newValue; } else { return; } BString val; val << fValue; if (!fHideValue) fValueLabel->SetText(val.String()); if (fPrintPartial) fprintf(stdout, "%s\n", val.String()); break; } default: Dialog::MessageReceived(message); break; } } <|endoftext|>
<commit_before>#include "BigFix/ArchiveReader.h" #include "BigFix/ArchiveStream.h" #include "BigFix/DataRef.h" #include "BigFix/InflateStream.h" #include <iostream> using namespace BigFix; class ArchiveListStream : public ArchiveStream { public: virtual void Directory( const char* name, ArchiveEncoding nameEncoding, time_t mtime ) { std::cout << name << std::endl; } virtual void FileStart( const char* name, ArchiveEncoding nameEncoding, time_t mtime, uint64_t length ) { std::cout << name << std::endl; } virtual void FileWrite( const uint8_t* start, const uint8_t* end ) {} virtual void FileEnd() {} }; int main() { ArchiveListStream list; ArchiveReader reader( list ); InflateStream inflate( reader ); char buffer[4096]; while ( true ) { ssize_t nread = read( 0, buffer, sizeof( buffer ) ); if ( nread == 0 ) { inflate.End(); return 0; } if ( nread < 0 ) { std::cerr << "Error reading from stdin" << std::endl; return 1; } inflate.Write( DataRef( (uint8_t*)buffer, (uint8_t*)buffer + nread ) ); } } <commit_msg>Fix build<commit_after>#include "BigFix/ArchiveReader.h" #include "BigFix/ArchiveStream.h" #include "BigFix/DataRef.h" #include "BigFix/InflateStream.h" #include <iostream> using namespace BigFix; class ArchiveListStream : public ArchiveStream { public: virtual void Directory( const char* name, ArchiveEncoding nameEncoding, const DateTime& mtime ) { std::cout << name << std::endl; } virtual void FileStart( const char* name, ArchiveEncoding nameEncoding, const DateTime& mtime, uint64_t length ) { std::cout << name << std::endl; } virtual void FileWrite( const uint8_t* start, const uint8_t* end ) {} virtual void FileEnd() {} }; int main() { ArchiveListStream list; ArchiveReader reader( list ); InflateStream inflate( reader ); char buffer[4096]; while ( true ) { ssize_t nread = read( 0, buffer, sizeof( buffer ) ); if ( nread == 0 ) { inflate.End(); return 0; } if ( nread < 0 ) { std::cerr << "Error reading from stdin" << std::endl; return 1; } inflate.Write( DataRef( (uint8_t*)buffer, (uint8_t*)buffer + nread ) ); } } <|endoftext|>
<commit_before>/* Copyright 2018 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // libevent based server implementation #include "tensorflow_serving/util/net_http/server/internal/evhttp_server.h" #include <netinet/in.h> #include <sys/socket.h> #include <cstdint> #include <memory> #include <utility> #include "absl/base/call_once.h" #include "absl/base/internal/raw_logging.h" #include "absl/memory/memory.h" #include "libevent/include/event2/event.h" #include "libevent/include/event2/http.h" #include "libevent/include/event2/thread.h" #include "libevent/include/event2/util.h" namespace tensorflow { namespace serving { namespace net_http { namespace { absl::once_flag libevent_init_once; void InitLibEvent() { if (evthread_use_pthreads() != 0) { ABSL_RAW_LOG(FATAL, "Server requires pthread support."); } // TODO(wenboz): windows support needed? } void GlobalInitialize() { absl::call_once(libevent_init_once, &InitLibEvent); } } // namespace EvHTTPServer::EvHTTPServer(std::unique_ptr<ServerOptions> options) : server_options_(std::move(options)), accepting_requests_() {} // May crash the server if called before WaitForTermination() returns EvHTTPServer::~EvHTTPServer() { if (!is_terminating()) { ABSL_RAW_LOG(ERROR, "Serer has not been terminated. Force termination now."); Terminate(); } if (ev_http_ != nullptr) { // this frees the socket handlers too evhttp_free(ev_http_); } if (ev_base_ != nullptr) { event_base_free(ev_base_); } } // Checks options. // TODO(wenboz): support multiple ports bool EvHTTPServer::Initialize() { if (server_options_->executor() == nullptr) { ABSL_RAW_LOG(FATAL, "Default EventExecutor is not configured."); return false; } if (server_options_->ports().empty()) { ABSL_RAW_LOG(FATAL, "Server port is not specified."); return false; } GlobalInitialize(); // This ev_base_ created per-server v.s. global ev_base_ = event_base_new(); if (ev_base_ == nullptr) { ABSL_RAW_LOG(FATAL, "Failed to create an event_base."); return false; } timeval tv_zero = {0, 0}; immediate_ = event_base_init_common_timeout(ev_base_, &tv_zero); ev_http_ = evhttp_new(ev_base_); if (ev_http_ == nullptr) { ABSL_RAW_LOG(FATAL, "Failed to create evhttp."); return false; } evhttp_set_gencb(ev_http_, &DispatchEvRequestFn, this); return true; } // static function pointer void EvHTTPServer::DispatchEvRequestFn(evhttp_request* req, void* server) { EvHTTPServer* http_server = static_cast<EvHTTPServer*>(server); http_server->DispatchEvRequest(req); } void EvHTTPServer::DispatchEvRequest(evhttp_request* req) { auto parsed_request = absl::make_unique<ParsedEvRequest>(req); if (!parsed_request->decode()) { evhttp_send_error(req, HTTP_BADREQUEST, nullptr); return; } std::string path(parsed_request->path); bool dispatched = false; std::unique_ptr<EvHTTPRequest> ev_request( new EvHTTPRequest(std::move(parsed_request), this)); if (!ev_request->Initialize()) { evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr); return; } { absl::MutexLock l(&request_mu_); auto handler_map_it = uri_handlers_.find(path); if (handler_map_it != uri_handlers_.end()) { IncOps(); dispatched = true; ScheduleHandlerReference(handler_map_it->second.handler, ev_request.release()); } if (!dispatched) { for (const auto& dispatcher : dispatchers_) { auto handler = dispatcher.dispatcher(ev_request.get()); if (handler == nullptr) { continue; } IncOps(); dispatched = true; ScheduleHandler(std::move(handler), ev_request.release()); break; } } } if (!dispatched) { evhttp_send_error(req, HTTP_NOTFOUND, nullptr); return; } } void EvHTTPServer::ScheduleHandlerReference(const RequestHandler& handler, EvHTTPRequest* ev_request) { server_options_->executor()->Schedule( [&handler, ev_request]() { handler(ev_request); }); } // Exactly one copy of the handler argument // with the lambda passed by value to Schedule() void EvHTTPServer::ScheduleHandler(RequestHandler&& handler, EvHTTPRequest* ev_request) { server_options_->executor()->Schedule( [handler, ev_request]() { handler(ev_request); }); } namespace { void ResolveEphemeralPort(evhttp_bound_socket* listener, int* port) { sockaddr_storage ss = {}; ev_socklen_t socklen = sizeof(ss); evutil_socket_t fd = evhttp_bound_socket_get_fd(listener); if (getsockname(fd, reinterpret_cast<sockaddr*>(&ss), &socklen)) { ABSL_RAW_LOG(ERROR, "getsockname() failed"); return; } if (ss.ss_family == AF_INET) { *port = ntohs((reinterpret_cast<sockaddr_in*>(&ss))->sin_port); } else if (ss.ss_family == AF_INET6) { *port = ntohs((reinterpret_cast<sockaddr_in6*>(&ss))->sin6_port); } else { ABSL_RAW_LOG(ERROR, "Unknown address family %d", ss.ss_family); } } } // namespace bool EvHTTPServer::StartAcceptingRequests() { if (ev_http_ == nullptr) { ABSL_RAW_LOG(FATAL, "Server has not been successfully initialized"); return false; } const int port = server_options_->ports().front(); ev_listener_ = evhttp_bind_socket_with_handle(ev_http_, "::", // in6addr_any static_cast<ev_uint16_t>(port)); if (ev_listener_ == nullptr) { ABSL_RAW_LOG(FATAL, "Couldn't bind to port %d", port); return false; } IncOps(); port_ = port; if (port_ == 0) { ResolveEphemeralPort(ev_listener_, &port_); } IncOps(); server_options_->executor()->Schedule([this]() { ABSL_RAW_LOG(INFO, "Entering the event loop ..."); int result = event_base_dispatch(ev_base_); ABSL_RAW_LOG(INFO, "event_base_dispatch() exits with value %d", result); DecOps(); }); accepting_requests_.Notify(); return true; } int EvHTTPServer::listen_port() const { return port_; } bool EvHTTPServer::is_accepting_requests() const { return accepting_requests_.HasBeenNotified(); } void EvHTTPServer::Terminate() { if (!is_accepting_requests()) { ABSL_RAW_LOG(ERROR, "Server is not running ..."); return; } if (is_terminating()) { ABSL_RAW_LOG(ERROR, "Server is already being terminated ..."); return; } terminating_.Notify(); // call exit-loop from the event loop this->EventLoopSchedule([this]() { // Stop the listener first, which will delete ev_listener_ // This may cause the loop to exit, so need be scheduled from within evhttp_del_accept_socket(ev_http_, ev_listener_); DecOps(); }); // Current shut-down behavior: // - we don't proactively delete/close any HTTP connections as part of // Terminate(). This is not an issue as we don't support read-streaming yet. // - we don't wait for all dispatched requests to run to completion // before we stop the event loop. // - and otherwise, this is meant to be a clean shutdown } bool EvHTTPServer::is_terminating() const { return terminating_.HasBeenNotified(); } void EvHTTPServer::IncOps() { absl::MutexLock l(&ops_mu_); num_pending_ops_++; } void EvHTTPServer::DecOps() { absl::MutexLock l(&ops_mu_); num_pending_ops_--; } void EvHTTPServer::WaitForTermination() { { absl::MutexLock l(&ops_mu_); ops_mu_.Await(absl::Condition(+[](int64_t* count) { return *count <= 1; }, &num_pending_ops_)); } int result = event_base_loopexit(ev_base_, nullptr); ABSL_RAW_LOG(INFO, "event_base_loopexit() exits with value %d", result); { absl::MutexLock l(&ops_mu_); ops_mu_.Await(absl::Condition(+[](int64_t* count) { return *count == 0; }, &num_pending_ops_)); } } bool EvHTTPServer::WaitForTerminationWithTimeout(absl::Duration timeout) { bool wait_result = true; { absl::MutexLock l(&ops_mu_); wait_result = ops_mu_.AwaitWithTimeout( absl::Condition(+[](int64_t* count) { return *count <= 1; }, &num_pending_ops_), timeout); } if (wait_result) { int result = event_base_loopexit(ev_base_, nullptr); ABSL_RAW_LOG(INFO, "event_base_loopexit() exits with value %d", result); // This should pass immediately { absl::MutexLock l(&ops_mu_); wait_result = ops_mu_.AwaitWithTimeout( absl::Condition(+[](int64_t* count) { return *count == 0; }, &num_pending_ops_), timeout); } } return wait_result; } EvHTTPServer::UriHandlerInfo::UriHandlerInfo( absl::string_view uri_in, RequestHandler handler_in, const RequestHandlerOptions& options_in) : uri(uri_in.data(), uri_in.size()), handler(std::move(handler_in)), options(options_in) {} EvHTTPServer::DispatcherInfo::DispatcherInfo( RequestDispatcher dispatcher_in, const RequestHandlerOptions& options_in) : dispatcher(std::move(dispatcher_in)), options(options_in) {} void EvHTTPServer::RegisterRequestHandler( absl::string_view uri, RequestHandler handler, const RequestHandlerOptions& options) { absl::MutexLock l(&request_mu_); auto result = uri_handlers_.emplace( std::piecewise_construct, std::forward_as_tuple(uri), std::forward_as_tuple(uri, handler, options)); if (!result.second) { ABSL_RAW_LOG(INFO, "Overwrite the existing handler registered under " "the URI path %.*s", static_cast<int>(uri.size()), uri.data()); uri_handlers_.erase(result.first); if (!uri_handlers_ .emplace(std::piecewise_construct, std::forward_as_tuple(uri), std::forward_as_tuple(uri, handler, options)) .second) { ABSL_RAW_LOG(ERROR, "Failed to register an handler under the URI path %.*s", static_cast<int>(uri.size()), uri.data()); } } } void EvHTTPServer::RegisterRequestDispatcher( RequestDispatcher dispatcher, const RequestHandlerOptions& options) { absl::MutexLock l(&request_mu_); dispatchers_.emplace_back(dispatcher, options); } namespace { void EvImmediateCallback(evutil_socket_t socket, int16_t flags, void* arg) { auto fn = static_cast<std::function<void()>*>(arg); (*fn)(); delete fn; } } // namespace bool EvHTTPServer::EventLoopSchedule(std::function<void()> fn) { auto scheduled_fn = new std::function<void()>(std::move(fn)); int result = event_base_once(ev_base_, -1, EV_TIMEOUT, EvImmediateCallback, static_cast<void*>(scheduled_fn), immediate_); return result == 0; } } // namespace net_http } // namespace serving } // namespace tensorflow <commit_msg>Support ipv4-only hosts.<commit_after>/* Copyright 2018 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // libevent based server implementation #include "tensorflow_serving/util/net_http/server/internal/evhttp_server.h" #include <netinet/in.h> #include <sys/socket.h> #include <cstdint> #include <memory> #include <utility> #include "absl/base/call_once.h" #include "absl/base/internal/raw_logging.h" #include "absl/memory/memory.h" #include "libevent/include/event2/event.h" #include "libevent/include/event2/http.h" #include "libevent/include/event2/thread.h" #include "libevent/include/event2/util.h" namespace tensorflow { namespace serving { namespace net_http { namespace { absl::once_flag libevent_init_once; void InitLibEvent() { if (evthread_use_pthreads() != 0) { ABSL_RAW_LOG(FATAL, "Server requires pthread support."); } // TODO(wenboz): windows support needed? } void GlobalInitialize() { absl::call_once(libevent_init_once, &InitLibEvent); } } // namespace EvHTTPServer::EvHTTPServer(std::unique_ptr<ServerOptions> options) : server_options_(std::move(options)), accepting_requests_() {} // May crash the server if called before WaitForTermination() returns EvHTTPServer::~EvHTTPServer() { if (!is_terminating()) { ABSL_RAW_LOG(ERROR, "Serer has not been terminated. Force termination now."); Terminate(); } if (ev_http_ != nullptr) { // this frees the socket handlers too evhttp_free(ev_http_); } if (ev_base_ != nullptr) { event_base_free(ev_base_); } } // Checks options. // TODO(wenboz): support multiple ports bool EvHTTPServer::Initialize() { if (server_options_->executor() == nullptr) { ABSL_RAW_LOG(FATAL, "Default EventExecutor is not configured."); return false; } if (server_options_->ports().empty()) { ABSL_RAW_LOG(FATAL, "Server port is not specified."); return false; } GlobalInitialize(); // This ev_base_ created per-server v.s. global ev_base_ = event_base_new(); if (ev_base_ == nullptr) { ABSL_RAW_LOG(FATAL, "Failed to create an event_base."); return false; } timeval tv_zero = {0, 0}; immediate_ = event_base_init_common_timeout(ev_base_, &tv_zero); ev_http_ = evhttp_new(ev_base_); if (ev_http_ == nullptr) { ABSL_RAW_LOG(FATAL, "Failed to create evhttp."); return false; } evhttp_set_gencb(ev_http_, &DispatchEvRequestFn, this); return true; } // static function pointer void EvHTTPServer::DispatchEvRequestFn(evhttp_request* req, void* server) { EvHTTPServer* http_server = static_cast<EvHTTPServer*>(server); http_server->DispatchEvRequest(req); } void EvHTTPServer::DispatchEvRequest(evhttp_request* req) { auto parsed_request = absl::make_unique<ParsedEvRequest>(req); if (!parsed_request->decode()) { evhttp_send_error(req, HTTP_BADREQUEST, nullptr); return; } std::string path(parsed_request->path); bool dispatched = false; std::unique_ptr<EvHTTPRequest> ev_request( new EvHTTPRequest(std::move(parsed_request), this)); if (!ev_request->Initialize()) { evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr); return; } { absl::MutexLock l(&request_mu_); auto handler_map_it = uri_handlers_.find(path); if (handler_map_it != uri_handlers_.end()) { IncOps(); dispatched = true; ScheduleHandlerReference(handler_map_it->second.handler, ev_request.release()); } if (!dispatched) { for (const auto& dispatcher : dispatchers_) { auto handler = dispatcher.dispatcher(ev_request.get()); if (handler == nullptr) { continue; } IncOps(); dispatched = true; ScheduleHandler(std::move(handler), ev_request.release()); break; } } } if (!dispatched) { evhttp_send_error(req, HTTP_NOTFOUND, nullptr); return; } } void EvHTTPServer::ScheduleHandlerReference(const RequestHandler& handler, EvHTTPRequest* ev_request) { server_options_->executor()->Schedule( [&handler, ev_request]() { handler(ev_request); }); } // Exactly one copy of the handler argument // with the lambda passed by value to Schedule() void EvHTTPServer::ScheduleHandler(RequestHandler&& handler, EvHTTPRequest* ev_request) { server_options_->executor()->Schedule( [handler, ev_request]() { handler(ev_request); }); } namespace { void ResolveEphemeralPort(evhttp_bound_socket* listener, int* port) { sockaddr_storage ss = {}; ev_socklen_t socklen = sizeof(ss); evutil_socket_t fd = evhttp_bound_socket_get_fd(listener); if (getsockname(fd, reinterpret_cast<sockaddr*>(&ss), &socklen)) { ABSL_RAW_LOG(ERROR, "getsockname() failed"); return; } if (ss.ss_family == AF_INET) { *port = ntohs((reinterpret_cast<sockaddr_in*>(&ss))->sin_port); } else if (ss.ss_family == AF_INET6) { *port = ntohs((reinterpret_cast<sockaddr_in6*>(&ss))->sin6_port); } else { ABSL_RAW_LOG(ERROR, "Unknown address family %d", ss.ss_family); } } } // namespace bool EvHTTPServer::StartAcceptingRequests() { if (ev_http_ == nullptr) { ABSL_RAW_LOG(FATAL, "Server has not been successfully initialized"); return false; } const int port = server_options_->ports().front(); // "::" => in6addr_any ev_uint16_t ev_port = static_cast<ev_uint16_t>(port); ev_listener_ = evhttp_bind_socket_with_handle(ev_http_, "::", ev_port); if (ev_listener_ == nullptr) { // in case ipv6 is not supported, fallback to inaddr_any ev_listener_ = evhttp_bind_socket_with_handle(ev_http_, nullptr, ev_port); if (ev_listener_ == nullptr) { ABSL_RAW_LOG(FATAL, "Couldn't bind to port %d", port); return false; } } // Listener counts as an active operation IncOps(); port_ = port; if (port_ == 0) { ResolveEphemeralPort(ev_listener_, &port_); } IncOps(); server_options_->executor()->Schedule([this]() { ABSL_RAW_LOG(INFO, "Entering the event loop ..."); int result = event_base_dispatch(ev_base_); ABSL_RAW_LOG(INFO, "event_base_dispatch() exits with value %d", result); DecOps(); }); accepting_requests_.Notify(); return true; } int EvHTTPServer::listen_port() const { return port_; } bool EvHTTPServer::is_accepting_requests() const { return accepting_requests_.HasBeenNotified(); } void EvHTTPServer::Terminate() { if (!is_accepting_requests()) { ABSL_RAW_LOG(ERROR, "Server is not running ..."); return; } if (is_terminating()) { ABSL_RAW_LOG(ERROR, "Server is already being terminated ..."); return; } terminating_.Notify(); // call exit-loop from the event loop this->EventLoopSchedule([this]() { // Stop the listener first, which will delete ev_listener_ // This may cause the loop to exit, so need be scheduled from within evhttp_del_accept_socket(ev_http_, ev_listener_); DecOps(); }); // Current shut-down behavior: // - we don't proactively delete/close any HTTP connections as part of // Terminate(). This is not an issue as we don't support read-streaming yet. // - we don't wait for all dispatched requests to run to completion // before we stop the event loop. // - and otherwise, this is meant to be a clean shutdown } bool EvHTTPServer::is_terminating() const { return terminating_.HasBeenNotified(); } void EvHTTPServer::IncOps() { absl::MutexLock l(&ops_mu_); num_pending_ops_++; } void EvHTTPServer::DecOps() { absl::MutexLock l(&ops_mu_); num_pending_ops_--; } void EvHTTPServer::WaitForTermination() { { absl::MutexLock l(&ops_mu_); ops_mu_.Await(absl::Condition(+[](int64_t* count) { return *count <= 1; }, &num_pending_ops_)); } int result = event_base_loopexit(ev_base_, nullptr); ABSL_RAW_LOG(INFO, "event_base_loopexit() exits with value %d", result); { absl::MutexLock l(&ops_mu_); ops_mu_.Await(absl::Condition(+[](int64_t* count) { return *count == 0; }, &num_pending_ops_)); } } bool EvHTTPServer::WaitForTerminationWithTimeout(absl::Duration timeout) { bool wait_result = true; { absl::MutexLock l(&ops_mu_); wait_result = ops_mu_.AwaitWithTimeout( absl::Condition(+[](int64_t* count) { return *count <= 1; }, &num_pending_ops_), timeout); } if (wait_result) { int result = event_base_loopexit(ev_base_, nullptr); ABSL_RAW_LOG(INFO, "event_base_loopexit() exits with value %d", result); // This should pass immediately { absl::MutexLock l(&ops_mu_); wait_result = ops_mu_.AwaitWithTimeout( absl::Condition(+[](int64_t* count) { return *count == 0; }, &num_pending_ops_), timeout); } } return wait_result; } EvHTTPServer::UriHandlerInfo::UriHandlerInfo( absl::string_view uri_in, RequestHandler handler_in, const RequestHandlerOptions& options_in) : uri(uri_in.data(), uri_in.size()), handler(std::move(handler_in)), options(options_in) {} EvHTTPServer::DispatcherInfo::DispatcherInfo( RequestDispatcher dispatcher_in, const RequestHandlerOptions& options_in) : dispatcher(std::move(dispatcher_in)), options(options_in) {} void EvHTTPServer::RegisterRequestHandler( absl::string_view uri, RequestHandler handler, const RequestHandlerOptions& options) { absl::MutexLock l(&request_mu_); auto result = uri_handlers_.emplace( std::piecewise_construct, std::forward_as_tuple(uri), std::forward_as_tuple(uri, handler, options)); if (!result.second) { ABSL_RAW_LOG(INFO, "Overwrite the existing handler registered under " "the URI path %.*s", static_cast<int>(uri.size()), uri.data()); uri_handlers_.erase(result.first); if (!uri_handlers_ .emplace(std::piecewise_construct, std::forward_as_tuple(uri), std::forward_as_tuple(uri, handler, options)) .second) { ABSL_RAW_LOG(ERROR, "Failed to register an handler under the URI path %.*s", static_cast<int>(uri.size()), uri.data()); } } } void EvHTTPServer::RegisterRequestDispatcher( RequestDispatcher dispatcher, const RequestHandlerOptions& options) { absl::MutexLock l(&request_mu_); dispatchers_.emplace_back(dispatcher, options); } namespace { void EvImmediateCallback(evutil_socket_t socket, int16_t flags, void* arg) { auto fn = static_cast<std::function<void()>*>(arg); (*fn)(); delete fn; } } // namespace bool EvHTTPServer::EventLoopSchedule(std::function<void()> fn) { auto scheduled_fn = new std::function<void()>(std::move(fn)); int result = event_base_once(ev_base_, -1, EV_TIMEOUT, EvImmediateCallback, static_cast<void*>(scheduled_fn), immediate_); return result == 0; } } // namespace net_http } // namespace serving } // namespace tensorflow <|endoftext|>
<commit_before>//project #include "SuperRegion.h" SuperRegion::SuperRegion() : reward(0) { } SuperRegion::SuperRegion(const int& pReward) : reward(pReward) { } SuperRegion::~SuperRegion() { } void SuperRegion::addRegion(const int& region) { regions.push_back(region); } <commit_msg>added methods to SuperRegion<commit_after>//project #include "SuperRegion.h" SuperRegion::SuperRegion() : reward(0), Counterwastelands(0), neutrals(0), WASTESIZE(6) { } SuperRegion::SuperRegion(const int& pReward) : reward(pReward) { } SuperRegion::~SuperRegion() { } void SuperRegion::addRegion(const int& region) { regions.push_back(region); } void SuperRegion::calcWastelands(std::vector<int> Wastelands) { for(int j=0; j < Wastelands.size(); ++j) for (int i = 0; i < regions.size(); ++i) { if (regions[i] == Wastelands[j]) { Counterwastelands = Wastelands; break; } } calcNeutrals(); } void SuperRegion::calcNeutrals() { neutrals = regions.size()*2; neutrals += Counterwastelands* WASTESIZE; }<|endoftext|>
<commit_before>/* Copyright 2012 Tzvetan Mikov <tmikov@gmail.com> All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef SYMBOLTABLE_HPP #define SYMBOLTABLE_HPP #include <list> #include <boost/unordered_map.hpp> #include "base.hpp" #include "SourceCoords.hpp" #define _DEF_RESWORDS \ _MK_ENUM(NONE) \ _MK_ENUM(QUOTE) \ /* Handled by a macro \ _MK_ENUM(QUASIQUOTE) \ _MK_ENUM(UNQUOTE) \ _MK_ENUM(UNQUOTE_SPLICING) \ */ \ _MK_ENUM(SYNTAX) \ _MK_ENUM(QUASISYNTAX) \ _MK_ENUM(UNSYNTAX) \ _MK_ENUM(UNSYNTAX_SPLICING) \ \ _MK_ENUM(IF) \ _MK_ENUM(BEGIN) \ _MK_ENUM(LAMBDA) \ _MK_ENUM(DEFINE) \ _MK_ENUM(SETBANG) \ _MK_ENUM(LET) \ _MK_ENUM(LETREC) \ _MK_ENUM(LETREC_STAR) \ \ _MK_ENUM(BUILTIN) \ _MK_ENUM(DEFINE_MACRO) \ _MK_ENUM(DEFINE_IDENTIFIER_MACRO) \ _MK_ENUM(DEFINE_SET_MACRO) \ _MK_ENUM(MACRO_ENV) \ \ _MK_ENUM(UNSPECIFIED) struct ResWord { #define _MK_ENUM(x) x, enum Enum { _DEF_RESWORDS }; #undef _MK_ENUM static const char * name ( Enum x ) { return s_names[x]; } private: static const char * s_names[]; }; class Binding; class Symbol; class Scope; class SymbolTable; #define _DEF_BIND_TYPES \ _MK_ENUM(NONE) \ _MK_ENUM(RESWORD) \ _MK_ENUM(VAR) struct BindingType { #define _MK_ENUM(x) x, enum Enum { _DEF_BIND_TYPES }; #undef _MK_ENUM static const char * name ( Enum x ) { return s_names[x]; } private: static const char * s_names[]; }; class Scope : public gc { public: Scope ( SymbolTable * symbolTable, Scope * parent_ ) : m_symbolTable(symbolTable), parent( parent_ ), level(parent?parent->level+1:-1) { m_bindingList = NULL; m_active = false; } /** * * @param res * @param sym * @return true if a new symbol was defined, false if it was already present in the scope */ bool bind ( Binding * & res, Symbol * sym, BindingType::Enum btype, const SourceCoords & defCoords ); Binding * lookupOnlyHere ( Symbol * sym ); Binding * lookupHereAndUp ( Symbol * sym ); void addToBindingList ( Binding * bnd ); bool isActive () const { return m_active; } public: Scope * const parent; int const level; private: SymbolTable * const m_symbolTable; Binding * m_bindingList; //< linking Binding::prevInScope bool m_active; void popBindings (); friend class SymbolTable; }; class Binding : public gc { public: Binding ( Symbol * sym_, Scope * scope_, BindingType::Enum btype_, const SourceCoords & defCoords_ ) : sym(sym_), scope(scope_), btype(btype_), defCoords(defCoords_) { this->prev = NULL; } Symbol * const sym; Scope * const scope; SourceCoords defCoords; //< coordinates of the source definition const BindingType::Enum btype; union { ResWord::Enum resWord; class Variable * var; } u; private: Binding * prev; //< the same symbol in the previous scope Binding * prevInScope; //< link to the prev binding in our scope friend class Scope; friend class Symbol; }; std::ostream & operator << ( std::ostream & os, Binding & bnd ); inline void Scope::addToBindingList ( Binding * bnd ) { assert( bnd->prevInScope == NULL ); bnd->prevInScope = m_bindingList; m_bindingList = bnd; } struct Symbol : public gc, public boost::noncopyable { Symbol ( const gc_char * name_, uint32_t uid_ ) : name( name_ ), uid( uid_ ) { top = NULL; } void push ( Binding * bind ) { bind->prev = this->top; this->top = bind; } void pop ( Binding * bnd ) { assert( this->top == bnd ); this->top = this->top->prev; } const gc_char * const name; uint32_t const uid; //< different value for each symbol Binding * top; }; class SymbolTable : public gc { public: SymbolTable(); ~SymbolTable(); Symbol * newSymbol ( const gc_char * name ); Binding * lookup ( const Symbol * sym ) { return sym->top; } Scope * newScope (); void popThisScope ( Scope * scope ) { assert( m_topScope == scope ); popScope(); } void popScope (); Scope * topScope () const { return m_topScope; } private: struct gc_charstr_equal : public std::binary_function<const gc_char *,const gc_char *,bool> { bool operator () ( const gc_char * a, const gc_char * b ) const { return std::strcmp( a, b ) == 0; } }; struct gc_charstr_hash : std::unary_function<const gc_char *, std::size_t> { std::size_t operator () ( const gc_char * a ) const { std::size_t seed = 0; unsigned t; while ( (t = *((unsigned char *)a)) != 0) { boost::hash_combine( seed, t ); ++a; } return seed; } }; typedef boost::unordered_map<const gc_char *, Symbol *, gc_charstr_hash, gc_charstr_equal, gc_allocator<const gc_char *> > Map; Map m_map; uint32_t m_uid; Scope * m_topScope; }; class ScopePopper { public: ScopePopper ( SymbolTable & symbolTable, Scope * scope ) : m_symbolTable(symbolTable), m_scope(scope) {}; ~ScopePopper () { m_symbolTable.popThisScope(m_scope); } private: SymbolTable & m_symbolTable; Scope * m_scope; }; #endif /* SYMBOLTABLE_HPP */ <commit_msg>SymbolTable: add Macro<commit_after>/* Copyright 2012 Tzvetan Mikov <tmikov@gmail.com> All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef SYMBOLTABLE_HPP #define SYMBOLTABLE_HPP #include <list> #include <boost/unordered_map.hpp> #include "base.hpp" #include "SourceCoords.hpp" #define _DEF_RESWORDS \ _MK_ENUM(NONE) \ _MK_ENUM(QUOTE) \ /* Handled by a macro \ _MK_ENUM(QUASIQUOTE) \ _MK_ENUM(UNQUOTE) \ _MK_ENUM(UNQUOTE_SPLICING) \ */ \ _MK_ENUM(SYNTAX) \ _MK_ENUM(QUASISYNTAX) \ _MK_ENUM(UNSYNTAX) \ _MK_ENUM(UNSYNTAX_SPLICING) \ \ _MK_ENUM(IF) \ _MK_ENUM(BEGIN) \ _MK_ENUM(LAMBDA) \ _MK_ENUM(DEFINE) \ _MK_ENUM(SETBANG) \ _MK_ENUM(LET) \ _MK_ENUM(LETREC) \ _MK_ENUM(LETREC_STAR) \ \ _MK_ENUM(BUILTIN) \ _MK_ENUM(DEFINE_MACRO) \ _MK_ENUM(DEFINE_IDENTIFIER_MACRO) \ _MK_ENUM(DEFINE_SET_MACRO) \ _MK_ENUM(MACRO_ENV) \ \ _MK_ENUM(UNSPECIFIED) struct ResWord { #define _MK_ENUM(x) x, enum Enum { _DEF_RESWORDS }; #undef _MK_ENUM static const char * name ( Enum x ) { return s_names[x]; } private: static const char * s_names[]; }; class Binding; class Symbol; class Scope; class SymbolTable; #define _DEF_BIND_TYPES \ _MK_ENUM(NONE) \ _MK_ENUM(RESWORD) \ _MK_ENUM(VAR) \ _MK_ENUM(MACRO) struct BindingType { #define _MK_ENUM(x) x, enum Enum { _DEF_BIND_TYPES }; #undef _MK_ENUM static const char * name ( Enum x ) { return s_names[x]; } private: static const char * s_names[]; }; class Scope : public gc { public: Scope ( SymbolTable * symbolTable, Scope * parent_ ) : m_symbolTable(symbolTable), parent( parent_ ), level(parent?parent->level+1:-1) { m_bindingList = NULL; m_active = false; } /** * * @param res * @param sym * @return true if a new symbol was defined, false if it was already present in the scope */ bool bind ( Binding * & res, Symbol * sym, BindingType::Enum btype, const SourceCoords & defCoords ); Binding * lookupOnlyHere ( Symbol * sym ); Binding * lookupHereAndUp ( Symbol * sym ); void addToBindingList ( Binding * bnd ); bool isActive () const { return m_active; } public: Scope * const parent; int const level; private: SymbolTable * const m_symbolTable; Binding * m_bindingList; //< linking Binding::prevInScope bool m_active; void popBindings (); friend class SymbolTable; }; class Syntax; class Macro : public gc { public: Scope * const scope; Macro ( Scope * scope_ ) : scope(scope_) {} virtual Syntax * expand ( Syntax * datum ) = 0; }; class Binding : public gc { public: Binding ( Symbol * sym_, Scope * scope_, BindingType::Enum btype_, const SourceCoords & defCoords_ ) : sym(sym_), scope(scope_), btype(btype_), defCoords(defCoords_) { this->prev = NULL; } Symbol * const sym; Scope * const scope; SourceCoords defCoords; //< coordinates of the source definition const BindingType::Enum btype; union { ResWord::Enum resWord; class Variable * var; Macro * macro; } u; private: Binding * prev; //< the same symbol in the previous scope Binding * prevInScope; //< link to the prev binding in our scope friend class Scope; friend class Symbol; }; std::ostream & operator << ( std::ostream & os, Binding & bnd ); inline void Scope::addToBindingList ( Binding * bnd ) { assert( bnd->prevInScope == NULL ); bnd->prevInScope = m_bindingList; m_bindingList = bnd; } struct Symbol : public gc, public boost::noncopyable { Symbol ( const gc_char * name_, uint32_t uid_ ) : name( name_ ), uid( uid_ ) { top = NULL; } void push ( Binding * bind ) { bind->prev = this->top; this->top = bind; } void pop ( Binding * bnd ) { assert( this->top == bnd ); this->top = this->top->prev; } const gc_char * const name; uint32_t const uid; //< different value for each symbol Binding * top; }; class SymbolTable : public gc { public: SymbolTable(); ~SymbolTable(); Symbol * newSymbol ( const gc_char * name ); Binding * lookup ( const Symbol * sym ) { return sym->top; } Scope * newScope (); void popThisScope ( Scope * scope ) { assert( m_topScope == scope ); popScope(); } void popScope (); Scope * topScope () const { return m_topScope; } private: struct gc_charstr_equal : public std::binary_function<const gc_char *,const gc_char *,bool> { bool operator () ( const gc_char * a, const gc_char * b ) const { return std::strcmp( a, b ) == 0; } }; struct gc_charstr_hash : std::unary_function<const gc_char *, std::size_t> { std::size_t operator () ( const gc_char * a ) const { std::size_t seed = 0; unsigned t; while ( (t = *((unsigned char *)a)) != 0) { boost::hash_combine( seed, t ); ++a; } return seed; } }; typedef boost::unordered_map<const gc_char *, Symbol *, gc_charstr_hash, gc_charstr_equal, gc_allocator<const gc_char *> > Map; Map m_map; uint32_t m_uid; Scope * m_topScope; }; class ScopePopper { public: ScopePopper ( SymbolTable & symbolTable, Scope * scope ) : m_symbolTable(symbolTable), m_scope(scope) {}; ~ScopePopper () { m_symbolTable.popThisScope(m_scope); } private: SymbolTable & m_symbolTable; Scope * m_scope; }; #endif /* SYMBOLTABLE_HPP */ <|endoftext|>
<commit_before>#include "boid.h" /** * @brief Create a new boid * * Creates a new QQmlComponent using the main QQmlApplicationEngine of the program and * the Boid.qml file. * After the component is created and ready, the QObject is created and parented to the * canvas object. * Lastly we set the position randomly, but staying within the boundaries. */ Boid::Boid() { component = new QQmlComponent(getEngine(), QUrl(QStringLiteral("qrc:/Boid.qml"))); if(component->status() == component->Ready) { object = component->create(getEngine()->rootContext()); object->setProperty("parent", QVariant::fromValue(getCanvas())); QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); } else qDebug() << component->errorString(); setY(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasHeight() - 100)); setX(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasWidth() - 100)); lastVel = Vector2(); } Boid::~Boid() { delete component; delete object; } /** * @brief Boid logic */ void Boid::update(){ Vector2 v1 = Vector2(); Vector2 v2 = Vector2(); Vector2 v3 = Vector2(); Vector2 v4 = Vector2(); Vector2 center = Vector2(); // Rule1: move to local center of mass ( center becomes average of surrounding boids) for(int i = 0; i < 3; i++){ center = center + neighbours[i].position2; } center /= 3; v1 = center - position; // Rule2: Avoidance : if distance to next boid smaller than threshold T boid changes course. center = Vector2(); for(int i = 0; i < 3; i++){ if ((neighbours[i].position2 - position).getSqrMagnitude() < (getSize() + 10.0) * (getSize() + 10.0)){ center = center - (neighbours[i].position2 - position); } } v2 = center; // Rule3: Match velocity to surrounding Boids for(int i = 0; i < 3; i++){ v3 = v3 + neighbours[i].velocity2; } v3 = v3/3; // Rule 4: Follow mouse position Vector2 mp = getMousePosition(); if(!(mp == Vector2(0, 0))) { if((mp - position).getSqrMagnitude() > 7500) v4 = mp - position; } // Rule 5: Stray away from the boundaries Vector2 v5 = Vector2(); if(position.getX() < 80) v5.setX(1); else if(position.getX() >= getCanvasWidth() - 80) v5.setX(-1); if(position.getY() < 80) v5.setY(1); else if(position.getY() >= getCanvasHeight() - 80){ v5.setY(-1); } //Replace position with mouse position and look through the force-parameter with the mouse double power = 0.0; double power2 = 0.0; if(position.getX() < 80) power = 100 - position.getX(); else if(position.getX() >= getCanvasWidth() - 80) power = 100 + position.getX() - getCanvasWidth() ; else if(position.getY() < 80) power2 = 100 - position.getY(); else if(position.getY() >= getCanvasHeight() - 80) power2 = 100 + position.getY() - getCanvasHeight(); double force = 10*exp((power+ power2) *0.05); //qDebug << force; velocity = Vector2::lerp(lastVel, velocity + v1.normalize()*getFlockingFactor() + v2.normalize()*getAvoidanceFactor() + v3.normalize()*getVelocityMatchFactor() + v4.normalize()*getTargetFactor() + v5 * force, 0.016f); lastVel = velocity; } <commit_msg>Small Change: Fix due to Changing Values<commit_after>#include "boid.h" /** * @brief Create a new boid * * Creates a new QQmlComponent using the main QQmlApplicationEngine of the program and * the Boid.qml file. * After the component is created and ready, the QObject is created and parented to the * canvas object. * Lastly we set the position randomly, but staying within the boundaries. */ Boid::Boid() { component = new QQmlComponent(getEngine(), QUrl(QStringLiteral("qrc:/Boid.qml"))); if(component->status() == component->Ready) { object = component->create(getEngine()->rootContext()); object->setProperty("parent", QVariant::fromValue(getCanvas())); QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); } else qDebug() << component->errorString(); setY(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasHeight() - 100)); setX(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasWidth() - 100)); lastVel = Vector2(); } Boid::~Boid() { delete component; delete object; } /** * @brief Boid logic */ void Boid::update(){ Vector2 v1 = Vector2(); Vector2 v2 = Vector2(); Vector2 v3 = Vector2(); Vector2 v4 = Vector2(); Vector2 center = Vector2(); // Rule1: move to local center of mass ( center becomes average of surrounding boids) for(int i = 0; i < 3; i++){ center = center + neighbours[i].position2; } center /= 3; v1 = center - position; // Rule2: Avoidance : if distance to next boid smaller than threshold T boid changes course. center = Vector2(); for(int i = 0; i < 3; i++){ if ((neighbours[i].position2 - position).getSqrMagnitude() < (getSize() + 10.0) * (getSize() + 10.0)){ center = center - (neighbours[i].position2 - position); } } v2 = center; // Rule3: Match velocity to surrounding Boids for(int i = 0; i < 3; i++){ v3 = v3 + neighbours[i].velocity2; } v3 = v3/3; // Rule 4: Follow mouse position Vector2 mp = getMousePosition(); if(!(mp == Vector2(0, 0))) { if((mp - position).getSqrMagnitude() > 7500) v4 = mp - position; } // Rule 5: Stray away from the boundaries Vector2 v5 = Vector2(); if(position.getX() < 80) v5.setX(1); else if(position.getX() >= getCanvasWidth() - 80) v5.setX(-1); if(position.getY() < 80) v5.setY(1); else if(position.getY() >= getCanvasHeight() - 80){ v5.setY(-1); } //Replace position with mouse position and look through the force-parameter with the mouse double power = 0.0; double power2 = 0.0; if(position.getX() < 80) power = 80 - position.getX(); else if(position.getX() >= getCanvasWidth() - 80) power = 80 + position.getX() - getCanvasWidth() ; else if(position.getY() < 80) power2 = 80 - position.getY(); else if(position.getY() >= getCanvasHeight() - 80) power2 = 80 + position.getY() - getCanvasHeight(); double force = 10*exp((power+ power2) *0.05); //qDebug << force; velocity = Vector2::lerp(lastVel, velocity + v1.normalize()*getFlockingFactor() + v2.normalize()*getAvoidanceFactor() + v3.normalize()*getVelocityMatchFactor() + v4.normalize()*getTargetFactor() + v5 * force, 0.016f); lastVel = velocity; } <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2016-2017 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "PipelineStateViewer.h" #include "D3D11PipelineStateViewer.h" #include "D3D12PipelineStateViewer.h" #include "GLPipelineStateViewer.h" #include "VulkanPipelineStateViewer.h" #include "ui_PipelineStateViewer.h" PipelineStateViewer::PipelineStateViewer(CaptureContext *ctx, QWidget *parent) : QFrame(parent), ui(new Ui::PipelineStateViewer), m_Ctx(ctx) { ui->setupUi(this); m_D3D11 = NULL; m_D3D12 = NULL; m_GL = NULL; m_Vulkan = NULL; m_Current = NULL; m_Ctx->AddLogViewer(this); setToD3D11(); } PipelineStateViewer::~PipelineStateViewer() { reset(); m_Ctx->windowClosed(this); m_Ctx->RemoveLogViewer(this); delete ui; } void PipelineStateViewer::OnLogfileLoaded() { if(m_Ctx->APIProps().pipelineType == eGraphicsAPI_D3D11) setToD3D11(); else if(m_Ctx->APIProps().pipelineType == eGraphicsAPI_D3D12) setToD3D12(); else if(m_Ctx->APIProps().pipelineType == eGraphicsAPI_OpenGL) setToGL(); else if(m_Ctx->APIProps().pipelineType == eGraphicsAPI_Vulkan) setToVulkan(); if(m_Current) m_Current->OnLogfileLoaded(); } void PipelineStateViewer::OnLogfileClosed() { if(m_Current) m_Current->OnLogfileClosed(); } void PipelineStateViewer::OnEventChanged(uint32_t eventID) { if(m_Current) m_Current->OnEventChanged(eventID); } QVariant PipelineStateViewer::persistData() { QVariantMap state; if(m_Current == m_D3D11) state["type"] = "D3D11"; else if(m_Current == m_D3D12) state["type"] = "D3D12"; else if(m_Current == m_GL) state["type"] = "GL"; else if(m_Current == m_Vulkan) state["type"] = "Vulkan"; else state["type"] = ""; return state; } void PipelineStateViewer::setPersistData(const QVariant &persistData) { QString str = persistData.toMap()["type"].toString(); if(str == "D3D11") setToD3D11(); else if(str == "D3D12") setToD3D12(); else if(str == "GL") setToGL(); else if(str == "Vulkan") setToVulkan(); } void PipelineStateViewer::reset() { delete m_D3D11; delete m_D3D12; delete m_GL; delete m_Vulkan; m_D3D11 = NULL; m_D3D12 = NULL; m_GL = NULL; m_Vulkan = NULL; m_Current = NULL; } void PipelineStateViewer::setToD3D11() { if(m_D3D11) return; reset(); m_D3D11 = new D3D11PipelineStateViewer(m_Ctx, this); ui->layout->addWidget(m_D3D11); m_Current = m_D3D11; m_Ctx->CurPipelineState.DefaultType = eGraphicsAPI_D3D11; } void PipelineStateViewer::setToD3D12() { if(m_D3D12) return; reset(); m_D3D12 = new D3D12PipelineStateViewer(m_Ctx, this); ui->layout->addWidget(m_D3D12); m_Current = m_D3D12; m_Ctx->CurPipelineState.DefaultType = eGraphicsAPI_D3D12; } void PipelineStateViewer::setToGL() { if(m_GL) return; reset(); m_GL = new GLPipelineStateViewer(m_Ctx, this); ui->layout->addWidget(m_GL); m_Current = m_GL; m_Ctx->CurPipelineState.DefaultType = eGraphicsAPI_OpenGL; } void PipelineStateViewer::setToVulkan() { if(m_Vulkan) return; reset(); m_Vulkan = new VulkanPipelineStateViewer(m_Ctx, this); ui->layout->addWidget(m_Vulkan); m_Current = m_Vulkan; m_Ctx->CurPipelineState.DefaultType = eGraphicsAPI_Vulkan; } <commit_msg>If LogfileLoaded is called out of order, ensure pipeline state is ready<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2016-2017 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "PipelineStateViewer.h" #include "D3D11PipelineStateViewer.h" #include "D3D12PipelineStateViewer.h" #include "GLPipelineStateViewer.h" #include "VulkanPipelineStateViewer.h" #include "ui_PipelineStateViewer.h" PipelineStateViewer::PipelineStateViewer(CaptureContext *ctx, QWidget *parent) : QFrame(parent), ui(new Ui::PipelineStateViewer), m_Ctx(ctx) { ui->setupUi(this); m_D3D11 = NULL; m_D3D12 = NULL; m_GL = NULL; m_Vulkan = NULL; m_Current = NULL; m_Ctx->AddLogViewer(this); setToD3D11(); } PipelineStateViewer::~PipelineStateViewer() { reset(); m_Ctx->windowClosed(this); m_Ctx->RemoveLogViewer(this); delete ui; } void PipelineStateViewer::OnLogfileLoaded() { if(m_Ctx->APIProps().pipelineType == eGraphicsAPI_D3D11) setToD3D11(); else if(m_Ctx->APIProps().pipelineType == eGraphicsAPI_D3D12) setToD3D12(); else if(m_Ctx->APIProps().pipelineType == eGraphicsAPI_OpenGL) setToGL(); else if(m_Ctx->APIProps().pipelineType == eGraphicsAPI_Vulkan) setToVulkan(); if(m_Current) m_Current->OnLogfileLoaded(); } void PipelineStateViewer::OnLogfileClosed() { if(m_Current) m_Current->OnLogfileClosed(); } void PipelineStateViewer::OnEventChanged(uint32_t eventID) { if(m_Ctx->CurPipelineState.DefaultType != m_Ctx->APIProps().pipelineType) OnLogfileLoaded(); if(m_Current) m_Current->OnEventChanged(eventID); } QVariant PipelineStateViewer::persistData() { QVariantMap state; if(m_Current == m_D3D11) state["type"] = "D3D11"; else if(m_Current == m_D3D12) state["type"] = "D3D12"; else if(m_Current == m_GL) state["type"] = "GL"; else if(m_Current == m_Vulkan) state["type"] = "Vulkan"; else state["type"] = ""; return state; } void PipelineStateViewer::setPersistData(const QVariant &persistData) { QString str = persistData.toMap()["type"].toString(); if(str == "D3D11") setToD3D11(); else if(str == "D3D12") setToD3D12(); else if(str == "GL") setToGL(); else if(str == "Vulkan") setToVulkan(); } void PipelineStateViewer::reset() { delete m_D3D11; delete m_D3D12; delete m_GL; delete m_Vulkan; m_D3D11 = NULL; m_D3D12 = NULL; m_GL = NULL; m_Vulkan = NULL; m_Current = NULL; } void PipelineStateViewer::setToD3D11() { if(m_D3D11) return; reset(); m_D3D11 = new D3D11PipelineStateViewer(m_Ctx, this); ui->layout->addWidget(m_D3D11); m_Current = m_D3D11; m_Ctx->CurPipelineState.DefaultType = eGraphicsAPI_D3D11; } void PipelineStateViewer::setToD3D12() { if(m_D3D12) return; reset(); m_D3D12 = new D3D12PipelineStateViewer(m_Ctx, this); ui->layout->addWidget(m_D3D12); m_Current = m_D3D12; m_Ctx->CurPipelineState.DefaultType = eGraphicsAPI_D3D12; } void PipelineStateViewer::setToGL() { if(m_GL) return; reset(); m_GL = new GLPipelineStateViewer(m_Ctx, this); ui->layout->addWidget(m_GL); m_Current = m_GL; m_Ctx->CurPipelineState.DefaultType = eGraphicsAPI_OpenGL; } void PipelineStateViewer::setToVulkan() { if(m_Vulkan) return; reset(); m_Vulkan = new VulkanPipelineStateViewer(m_Ctx, this); ui->layout->addWidget(m_Vulkan); m_Current = m_Vulkan; m_Ctx->CurPipelineState.DefaultType = eGraphicsAPI_Vulkan; } <|endoftext|>
<commit_before>#ifndef MJOLNIR_CORE_EXCLUSION_LIST_HPP #define MJOLNIR_CORE_EXCLUSION_LIST_HPP #include <mjolnir/core/System.hpp> #include <mjolnir/util/range.hpp> #include <mjolnir/util/logger.hpp> #include <algorithm> #include <iterator> #include <utility> #include <vector> namespace mjolnir { // In some cases, like excluded volume interaction between particles that // are connected by a bond, some particular pairs of particles are excluded // from interacting pairs. // This class constructs a list that contains a list of pairs that are excluded // from interacting pairs using information in a topology and a potential class. class ExclusionList { public: using topology_type = Topology; using molecule_id_type = topology_type::molecule_id_type; using group_id_type = topology_type::group_id_type; using connection_kind_type = topology_type::connection_kind_type; public: ExclusionList() = default; ~ExclusionList() = default; ExclusionList(const ExclusionList&) = default; ExclusionList(ExclusionList&&) = default; ExclusionList& operator=(const ExclusionList&) = default; ExclusionList& operator=(ExclusionList&&) = default; // check an interaction exists between i-th and j-th particles. // // It searches a small list of indices and check j is found in a exclusion- // list of i-th particle. bool is_excluded(const std::size_t i, const std::size_t j) const { // assuming all the lists are enough small (< 20 or so) { const auto ign_grps = this->ignored_grp_of(this->grp_ids_[i]); const auto grp_of_j = this->grp_ids_[j]; if(std::binary_search(ign_grps.begin(), ign_grps.end(), grp_of_j)) { // if found, the pair is ignored. return true. return true; } } // check molecule ids... const auto mol_of_j = this->mol_ids_[j]; for(const auto& ignoring_mol : this->ignored_mol_of(this->mol_ids_[i])) { // already sorted like ignoring_mol = [4,5,6] if (mol_of_j < ignoring_mol) {break;} else if(mol_of_j == ignoring_mol) {return true;} } // check distance on topology... for(const auto& ignoring_idx : this->ignored_idx_of(i)) { if (ignoring_idx > j) {break;} else if(ignoring_idx == j) {return true;} } return false; } // construct exclusion lists from topology and potential. // // This function may take a bit long time. template<typename traitsT, typename PotentialT> void make(const System<traitsT>& sys, const PotentialT& pot) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); MJOLNIR_LOG_INFO("potential = ", pot.name()); const auto& topol = sys.topology(); const std::size_t N = sys.size(); // count groups and assign indices this->grp_list_.clear(); for(std::size_t i=0; i<N; ++i) { if(std::find(this->grp_list_.begin(), this->grp_list_.end(), topol.group_of(i)) == this->grp_list_.end()) { // if not found, push it to the list this->grp_list_.push_back(topol.group_of(i)); MJOLNIR_LOG_INFO("group ", topol.group_of(i), " found. ", this->grp_list_.size(), "-th group is ", topol.group_of(i)); } } MJOLNIR_LOG_INFO("all groups are found {", this->grp_list_, "}."); // Here, the list of all groups is constructed. // Next, construct grp_ids_. assign corresponding group-ids this->grp_ids_.resize(N); for(std::size_t i=0; i<N; ++i) { const auto found = std::find(grp_list_.begin(), grp_list_.end(), topol.group_of(i)); assert(found != grp_list_.end()); // should be found. this->grp_ids_.at(i) = std::distance(grp_list_.begin(), found); MJOLNIR_LOG_DEBUG("particle ", i, " belongs to ", *found, " and " "the corresponding group_idx is ", grp_ids_.at(i), " and the value is ", grp_list_.at(grp_ids_.at(i))); } // Next, construct exclusion list for group. { const std::size_t Ngrps = this->grp_list_.size(); std::size_t idx = 0; // the current index in the exclusion list for(std::size_t i=0; i<Ngrps; ++i) { const std::size_t first = idx; // first index of the sub-list const auto& grp_name_i = this->grp_list_.at(i); for(std::size_t j=0; j<Ngrps; ++j) { const auto& grp_name_j = this->grp_list_.at(j); if(pot.is_ignored_group(grp_name_i, grp_name_j)) { MJOLNIR_LOG_INFO("group ", grp_name_i, " and ", grp_name_j, " ignores each other on ", pot.name()); this->ignored_grps_.push_back(i); ++idx; } } const auto beg = ignored_grps_.begin(); // sort this sub-range [first, idx) std::sort(beg + first, beg + idx); this->grp_ranges_.emplace_back(first, idx); } } // copy molecule_ids from topol to this this->mol_ids_.resize(N); for(std::size_t i=0; i<N; ++i) { this->mol_ids_[i] = topol.molecule_of(i); MJOLNIR_LOG_DEBUG("particle ", i, " is belonging molecule ", topol.molecule_of(i)); } // make ignored_molecule_idxs { const std::size_t Nmols = topol.number_of_molecules(); std::size_t idx = 0; for(std::size_t i=0; i<Nmols; ++i) { const std::size_t first = idx; for(std::size_t j=0; j<Nmols; ++j) { if(pot.is_ignored_molecule(i, j)) { MJOLNIR_LOG_INFO("molecule ", i, " and molecule ", j, " will ignore each other on ", pot.name()); this->ignored_mols_.push_back(j); ++idx; } } const auto beg = ignored_mols_.begin(); std::sort(beg + first, beg + idx); this->mol_ranges_.emplace_back(first, idx); } } // make ignored_particle_idxs // excluded_connection := pair{connection kind, distance} { std::size_t idx = 0; for(std::size_t i=0; i<N; ++i) { const std::size_t first = idx; std::vector<std::size_t> ignored_particles{i}; for(const auto& connection : pot.ignore_within()) { const std::size_t dist = connection.second; for(const auto j : topol.list_adjacent_within(i, dist, connection.first)) { ignored_particles.push_back(j); } } std::sort(ignored_particles.begin(), ignored_particles.end()); const auto last = std::unique(ignored_particles.begin(), ignored_particles.end()); ignored_particles.erase(last, ignored_particles.end()); MJOLNIR_LOG_INFO("particle ", i, " ignores ", ignored_particles); for(const auto j : ignored_particles) { this->ignored_idxs_.push_back(j); ++idx; } this->idx_ranges_.emplace_back(first, idx); } } return; } private: range<typename std::vector<std::size_t>::const_iterator> ignored_idx_of(const std::size_t i) const noexcept { return range<typename std::vector<std::size_t>::const_iterator>{ this->ignored_idxs_.begin() + this->idx_ranges_[i].first, this->ignored_idxs_.begin() + this->idx_ranges_[i].second }; } range<typename std::vector<std::size_t>::const_iterator> ignored_mol_of(const std::size_t i) const noexcept { return range<typename std::vector<std::size_t>::const_iterator>{ this->ignored_mols_.begin() + this->mol_ranges_[i].first, this->ignored_mols_.begin() + this->mol_ranges_[i].second }; } range<typename std::vector<std::size_t>::const_iterator> ignored_grp_of(const std::size_t i) const noexcept { return range<typename std::vector<std::size_t>::const_iterator>{ this->ignored_grps_.begin() + this->grp_ranges_[i].first, this->ignored_grps_.begin() + this->grp_ranges_[i].second }; } private: // It contains the same infromation as {topol.nodes_.molecule_id}; std::vector<molecule_id_type> mol_ids_; // Here, ExclusionList counts a number of groups and assign a unique index // for each group. `grp_ids` contains the index, not std::string itself. // It would be changed by calling ExclusionList::make() because it counts // groups and and assigns IDs. std::vector<group_id_type> grp_list_; // list of the group names std::vector<std::size_t> grp_ids_; // the index of the above list // ignored mol_id... std::vector<std::size_t> ignored_mols_; std::vector<std::pair<std::size_t, std::size_t>> mol_ranges_; // grp_idx... std::vector<std::size_t> ignored_grps_; std::vector<std::pair<std::size_t, std::size_t>> grp_ranges_; // normal particle idx std::vector<std::size_t> ignored_idxs_; std::vector<std::pair<std::size_t, std::size_t>> idx_ranges_; }; } // mjolnir #endif// MJOLNIR_NEIGHBOR_LIST_HPP <commit_msg>fix: list corect group id<commit_after>#ifndef MJOLNIR_CORE_EXCLUSION_LIST_HPP #define MJOLNIR_CORE_EXCLUSION_LIST_HPP #include <mjolnir/core/System.hpp> #include <mjolnir/util/range.hpp> #include <mjolnir/util/logger.hpp> #include <algorithm> #include <iterator> #include <utility> #include <vector> namespace mjolnir { // In some cases, like excluded volume interaction between particles that // are connected by a bond, some particular pairs of particles are excluded // from interacting pairs. // This class constructs a list that contains a list of pairs that are excluded // from interacting pairs using information in a topology and a potential class. class ExclusionList { public: using topology_type = Topology; using molecule_id_type = topology_type::molecule_id_type; using group_id_type = topology_type::group_id_type; using connection_kind_type = topology_type::connection_kind_type; public: ExclusionList() = default; ~ExclusionList() = default; ExclusionList(const ExclusionList&) = default; ExclusionList(ExclusionList&&) = default; ExclusionList& operator=(const ExclusionList&) = default; ExclusionList& operator=(ExclusionList&&) = default; // check an interaction exists between i-th and j-th particles. // // It searches a small list of indices and check j is found in a exclusion- // list of i-th particle. bool is_excluded(const std::size_t i, const std::size_t j) const { // assuming all the lists are enough small (< 20 or so) { const auto ign_grps = this->ignored_grp_of(this->grp_ids_[i]); const auto grp_of_j = this->grp_ids_[j]; if(std::binary_search(ign_grps.begin(), ign_grps.end(), grp_of_j)) { // if found, the pair is ignored. return true. return true; } } // check molecule ids... const auto mol_of_j = this->mol_ids_[j]; for(const auto& ignoring_mol : this->ignored_mol_of(this->mol_ids_[i])) { // already sorted like ignoring_mol = [4,5,6] if (mol_of_j < ignoring_mol) {break;} else if(mol_of_j == ignoring_mol) {return true;} } // check distance on topology... for(const auto& ignoring_idx : this->ignored_idx_of(i)) { if (ignoring_idx > j) {break;} else if(ignoring_idx == j) {return true;} } return false; } // construct exclusion lists from topology and potential. // // This function may take a bit long time. template<typename traitsT, typename PotentialT> void make(const System<traitsT>& sys, const PotentialT& pot) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); MJOLNIR_LOG_INFO("potential = ", pot.name()); const auto& topol = sys.topology(); const std::size_t N = sys.size(); // count groups and assign indices this->grp_list_.clear(); for(std::size_t i=0; i<N; ++i) { if(std::find(this->grp_list_.begin(), this->grp_list_.end(), topol.group_of(i)) == this->grp_list_.end()) { // if not found, push it to the list this->grp_list_.push_back(topol.group_of(i)); MJOLNIR_LOG_INFO("group ", topol.group_of(i), " found. ", this->grp_list_.size(), "-th group is ", topol.group_of(i)); } } MJOLNIR_LOG_INFO("all groups are found {", this->grp_list_, "}."); // Here, the list of all groups is constructed. // Next, construct grp_ids_. assign corresponding group-ids this->grp_ids_.resize(N); for(std::size_t i=0; i<N; ++i) { const auto found = std::find(grp_list_.begin(), grp_list_.end(), topol.group_of(i)); assert(found != grp_list_.end()); // should be found. this->grp_ids_.at(i) = std::distance(grp_list_.begin(), found); MJOLNIR_LOG_DEBUG("particle ", i, " belongs to ", *found, " and " "the corresponding group_idx is ", grp_ids_.at(i), " and the value is ", grp_list_.at(grp_ids_.at(i))); } // Next, construct exclusion list for group. { const std::size_t Ngrps = this->grp_list_.size(); std::size_t idx = 0; // the current index in the exclusion list for(std::size_t i=0; i<Ngrps; ++i) { const std::size_t first = idx; // first index of the sub-list const auto& grp_name_i = this->grp_list_.at(i); for(std::size_t j=0; j<Ngrps; ++j) { const auto& grp_name_j = this->grp_list_.at(j); if(pot.is_ignored_group(grp_name_i, grp_name_j)) { MJOLNIR_LOG_INFO("group ", grp_name_i, " and ", grp_name_j, " ignores each other on ", pot.name()); this->ignored_grps_.push_back(j); ++idx; } } const auto beg = ignored_grps_.begin(); // sort this sub-range [first, idx) std::sort(beg + first, beg + idx); this->grp_ranges_.emplace_back(first, idx); } } // copy molecule_ids from topol to this this->mol_ids_.resize(N); for(std::size_t i=0; i<N; ++i) { this->mol_ids_[i] = topol.molecule_of(i); MJOLNIR_LOG_DEBUG("particle ", i, " is belonging molecule ", topol.molecule_of(i)); } // make ignored_molecule_idxs { const std::size_t Nmols = topol.number_of_molecules(); std::size_t idx = 0; for(std::size_t i=0; i<Nmols; ++i) { const std::size_t first = idx; for(std::size_t j=0; j<Nmols; ++j) { if(pot.is_ignored_molecule(i, j)) { MJOLNIR_LOG_INFO("molecule ", i, " and molecule ", j, " will ignore each other on ", pot.name()); this->ignored_mols_.push_back(j); ++idx; } } const auto beg = ignored_mols_.begin(); std::sort(beg + first, beg + idx); this->mol_ranges_.emplace_back(first, idx); } } // make ignored_particle_idxs // excluded_connection := pair{connection kind, distance} { std::size_t idx = 0; for(std::size_t i=0; i<N; ++i) { const std::size_t first = idx; std::vector<std::size_t> ignored_particles{i}; for(const auto& connection : pot.ignore_within()) { const std::size_t dist = connection.second; for(const auto j : topol.list_adjacent_within(i, dist, connection.first)) { ignored_particles.push_back(j); } } std::sort(ignored_particles.begin(), ignored_particles.end()); const auto last = std::unique(ignored_particles.begin(), ignored_particles.end()); ignored_particles.erase(last, ignored_particles.end()); MJOLNIR_LOG_INFO("particle ", i, " ignores ", ignored_particles); for(const auto j : ignored_particles) { this->ignored_idxs_.push_back(j); ++idx; } this->idx_ranges_.emplace_back(first, idx); } } return; } private: range<typename std::vector<std::size_t>::const_iterator> ignored_idx_of(const std::size_t i) const noexcept { return range<typename std::vector<std::size_t>::const_iterator>{ this->ignored_idxs_.begin() + this->idx_ranges_[i].first, this->ignored_idxs_.begin() + this->idx_ranges_[i].second }; } range<typename std::vector<std::size_t>::const_iterator> ignored_mol_of(const std::size_t i) const noexcept { return range<typename std::vector<std::size_t>::const_iterator>{ this->ignored_mols_.begin() + this->mol_ranges_[i].first, this->ignored_mols_.begin() + this->mol_ranges_[i].second }; } range<typename std::vector<std::size_t>::const_iterator> ignored_grp_of(const std::size_t i) const noexcept { return range<typename std::vector<std::size_t>::const_iterator>{ this->ignored_grps_.begin() + this->grp_ranges_[i].first, this->ignored_grps_.begin() + this->grp_ranges_[i].second }; } private: // It contains the same infromation as {topol.nodes_.molecule_id}; std::vector<molecule_id_type> mol_ids_; // Here, ExclusionList counts a number of groups and assign a unique index // for each group. `grp_ids` contains the index, not std::string itself. // It would be changed by calling ExclusionList::make() because it counts // groups and and assigns IDs. std::vector<group_id_type> grp_list_; // list of the group names std::vector<std::size_t> grp_ids_; // the index of the above list // ignored mol_id... std::vector<std::size_t> ignored_mols_; std::vector<std::pair<std::size_t, std::size_t>> mol_ranges_; // grp_idx... std::vector<std::size_t> ignored_grps_; std::vector<std::pair<std::size_t, std::size_t>> grp_ranges_; // normal particle idx std::vector<std::size_t> ignored_idxs_; std::vector<std::pair<std::size_t, std::size_t>> idx_ranges_; }; } // mjolnir #endif// MJOLNIR_NEIGHBOR_LIST_HPP <|endoftext|>
<commit_before><commit_msg>🛠 Avoid shadowing warning<commit_after><|endoftext|>
<commit_before>#include "cfilelistmodel.h" #include "shell/cshell.h" #include "ccontroller.h" #include "../../../cmainwindow.h" #include "../../columns.h" DISABLE_COMPILER_WARNINGS #include <QMimeData> #include <QUrl> RESTORE_COMPILER_WARNINGS #include <set> CFileListModel::CFileListModel(QTreeView * treeView, QObject *parent) : QStandardItemModel(0, NumberOfColumns, parent), _controller(CController::get()), _tree(treeView), _panel(UnknownPanel) { } // Sets the position (left or right) of a panel that this model represents void CFileListModel::setPanelPosition(Panel p) { assert_r(_panel == UnknownPanel); // Doesn't make sense to call this method more than once _panel = p; } Panel CFileListModel::panelPosition() const { return _panel; } QTreeView *CFileListModel::treeView() const { return _tree; } QVariant CFileListModel::data(const QModelIndex & index, int role /*= Qt::DisplayRole*/) const { if (role == Qt::ToolTipRole) { if (!index.isValid()) return QString(); const CFileSystemObject item = _controller.itemByHash(_panel, itemHash(index)); return QString(item.fullName() % "\n\n" % QString::fromStdWString(CShell::toolTip(item.fullAbsolutePath().toStdWString()))); } else if (role == Qt::EditRole) { return _controller.itemByHash(_panel, itemHash(index)).fullName(); } else if (role == FullNameRole) { return _controller.itemByHash(_panel, itemHash(index)).fullName(); } else return QStandardItemModel::data(index, role); } bool CFileListModel::setData(const QModelIndex & index, const QVariant & value, int role) { if (role == Qt::EditRole) { const qulonglong hash = itemHash(index); emit itemEdited(hash, value.toString()); return false; } else return QStandardItemModel::setData(index, value, role); } Qt::ItemFlags CFileListModel::flags(const QModelIndex & idx) const { const Qt::ItemFlags flags = QStandardItemModel::flags(idx); if (!idx.isValid()) return flags; const qulonglong hash = itemHash(idx); const CFileSystemObject item = _controller.itemByHash(_panel, hash); return item.exists() ? flags | Qt::ItemIsEditable : flags; } bool CFileListModel::canDropMimeData(const QMimeData * data, Qt::DropAction /*action*/, int /*row*/, int /*column*/, const QModelIndex & /*parent*/) const { return data->hasUrls(); } QStringList CFileListModel::mimeTypes() const { return QStringList("text/uri-list"); } bool CFileListModel::dropMimeData(const QMimeData * data, Qt::DropAction action, int /*row*/, int /*column*/, const QModelIndex & parent) { if (action == Qt::IgnoreAction) return true; else if (!data->hasUrls()) return false; CFileSystemObject dest = parent.isValid() ? _controller.itemByHash(_panel, itemHash(parent)) : CFileSystemObject(_controller.panel(_panel).currentDirPathNative()); if (dest.isFile()) dest = CFileSystemObject(dest.parentDirPath()); assert_and_return_r(dest.exists() && dest.isDir(), false); const QList<QUrl> urls = data->urls(); std::vector<CFileSystemObject> objects; for(const QUrl& url: urls) objects.emplace_back(url.toLocalFile()); if (objects.empty()) return false; if (action == Qt::CopyAction) return CMainWindow::get()->copyFiles(objects, dest.fullAbsolutePath()); else if (action == Qt::MoveAction) return CMainWindow::get()->moveFiles(objects, dest.fullAbsolutePath()); else return false; } QMimeData *CFileListModel::mimeData(const QModelIndexList & indexes) const { QMimeData * mime = new QMimeData(); QList<QUrl> urls; std::set<int> rows; for(const auto& idx: indexes) { if (idx.isValid() && rows.count(idx.row()) == 0) { const QString path = _controller.itemByHash(_panel, itemHash(index(idx.row(), 0))).fullAbsolutePath(); if (!path.isEmpty()) { rows.insert(idx.row()); urls.push_back(QUrl::fromLocalFile(path)); } } } mime->setUrls(urls); return mime; } qulonglong CFileListModel::itemHash(const QModelIndex & index) const { QStandardItem * itm = item(index.row(), 0); if (!itm) return 0; bool ok = false; const qulonglong hash = itm->data(Qt::UserRole).toULongLong(&ok); assert_and_return_r(ok, 0); return hash; } <commit_msg>Fixed #108<commit_after>#include "cfilelistmodel.h" #include "shell/cshell.h" #include "ccontroller.h" #include "../../../cmainwindow.h" #include "../../columns.h" DISABLE_COMPILER_WARNINGS #include <QMimeData> #include <QUrl> RESTORE_COMPILER_WARNINGS #include <set> CFileListModel::CFileListModel(QTreeView * treeView, QObject *parent) : QStandardItemModel(0, NumberOfColumns, parent), _controller(CController::get()), _tree(treeView), _panel(UnknownPanel) { } // Sets the position (left or right) of a panel that this model represents void CFileListModel::setPanelPosition(Panel p) { assert_r(_panel == UnknownPanel); // Doesn't make sense to call this method more than once _panel = p; } Panel CFileListModel::panelPosition() const { return _panel; } QTreeView *CFileListModel::treeView() const { return _tree; } QVariant CFileListModel::data(const QModelIndex & index, int role /*= Qt::DisplayRole*/) const { if (role == Qt::ToolTipRole) { if (!index.isValid()) return QString(); const CFileSystemObject item = _controller.itemByHash(_panel, itemHash(index)); return QString(item.fullName() % "\n\n" % QString::fromStdWString(CShell::toolTip(item.fullAbsolutePath().toStdWString()))); } else if (role == Qt::EditRole) { return _controller.itemByHash(_panel, itemHash(index)).fullName(); } else if (role == FullNameRole) { return _controller.itemByHash(_panel, itemHash(index)).fullName(); } else return QStandardItemModel::data(index, role); } bool CFileListModel::setData(const QModelIndex & index, const QVariant & value, int role) { if (role == Qt::EditRole) { const qulonglong hash = itemHash(index); emit itemEdited(hash, value.toString()); return false; } else return QStandardItemModel::setData(index, value, role); } Qt::ItemFlags CFileListModel::flags(const QModelIndex & idx) const { const Qt::ItemFlags flags = QStandardItemModel::flags(idx); if (!idx.isValid()) return flags; const qulonglong hash = itemHash(idx); const CFileSystemObject item = _controller.itemByHash(_panel, hash); return item.exists() && !item.isCdUp() ? flags | Qt::ItemIsEditable : flags; } bool CFileListModel::canDropMimeData(const QMimeData * data, Qt::DropAction /*action*/, int /*row*/, int /*column*/, const QModelIndex & /*parent*/) const { return data->hasUrls(); } QStringList CFileListModel::mimeTypes() const { return QStringList("text/uri-list"); } bool CFileListModel::dropMimeData(const QMimeData * data, Qt::DropAction action, int /*row*/, int /*column*/, const QModelIndex & parent) { if (action == Qt::IgnoreAction) return true; else if (!data->hasUrls()) return false; CFileSystemObject dest = parent.isValid() ? _controller.itemByHash(_panel, itemHash(parent)) : CFileSystemObject(_controller.panel(_panel).currentDirPathNative()); if (dest.isFile()) dest = CFileSystemObject(dest.parentDirPath()); assert_and_return_r(dest.exists() && dest.isDir(), false); const QList<QUrl> urls = data->urls(); std::vector<CFileSystemObject> objects; for(const QUrl& url: urls) objects.emplace_back(url.toLocalFile()); if (objects.empty()) return false; if (action == Qt::CopyAction) return CMainWindow::get()->copyFiles(objects, dest.fullAbsolutePath()); else if (action == Qt::MoveAction) return CMainWindow::get()->moveFiles(objects, dest.fullAbsolutePath()); else return false; } QMimeData *CFileListModel::mimeData(const QModelIndexList & indexes) const { QMimeData * mime = new QMimeData(); QList<QUrl> urls; std::set<int> rows; for(const auto& idx: indexes) { if (idx.isValid() && rows.count(idx.row()) == 0) { const QString path = _controller.itemByHash(_panel, itemHash(index(idx.row(), 0))).fullAbsolutePath(); if (!path.isEmpty()) { rows.insert(idx.row()); urls.push_back(QUrl::fromLocalFile(path)); } } } mime->setUrls(urls); return mime; } qulonglong CFileListModel::itemHash(const QModelIndex & index) const { QStandardItem * itm = item(index.row(), 0); if (!itm) return 0; bool ok = false; const qulonglong hash = itm->data(Qt::UserRole).toULongLong(&ok); assert_and_return_r(ok, 0); return hash; } <|endoftext|>
<commit_before>/* ------------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2019 Kim Kulling Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------------------------- */ #include <cppcore/Container/TArray.h> #include <cppcore/CPPCoreCommon.h> #include "gtest/gtest.h" #include <sstream> #include <iostream> using namespace CPPCore; static const size_t ArraySize = 4; static const float ArrayData[ ArraySize ] = { 0.0f, 1.0f, 2.0f, 3.0f }; //------------------------------------------------------------------------------------------------- /// @class TArrayTest /// @ingroup UnitTest /// /// @brief The array tests. //------------------------------------------------------------------------------------------------- class TArrayTest : public testing::Test { protected: void createArray( const float *pOrig, size_t numItems, TArray<float> &arrayInstance ) { for ( size_t i=0; i<numItems; ++i ) { arrayInstance.add( pOrig[ i ] ); } } }; TEST_F( TArrayTest, constructTest ) { TArray<float> arrayInstance; EXPECT_EQ( true, arrayInstance.isEmpty() ); EXPECT_EQ( 0U, arrayInstance.size() ); EXPECT_EQ( arrayInstance.begin(), arrayInstance.end() ); } TEST_F( TArrayTest, constructWithSizeTest) { TArray<float> arrayInstance( 4 ); EXPECT_EQ( 4u, arrayInstance.size() ); } TEST_F( TArrayTest, addTest) { TArray<float> arrayInstance; arrayInstance.add( 0.0f ); arrayInstance.add( 1.0f ); EXPECT_EQ( 2u, arrayInstance.size() ); EXPECT_EQ( 0.0f, arrayInstance[ 0 ] ); EXPECT_EQ( 1.0f, arrayInstance[ 1 ] ); } TEST_F( TArrayTest, addItemsTest ) { TArray<float> arrayInstance; arrayInstance.add( 0.0f ); float data[2] = { 0, 1 }; arrayInstance.add( data, 2 ); EXPECT_EQ( 3u, arrayInstance.size() ); EXPECT_EQ( 0.0f, arrayInstance[ 0 ] ); EXPECT_EQ( 0.0f, arrayInstance[ 1 ] ); EXPECT_EQ( 1.0f, arrayInstance[ 2 ] ); arrayInstance.add( nullptr, 0 ); EXPECT_EQ( 3u, arrayInstance.size() ); } TEST_F( TArrayTest, accessTest) { TArray<float> arrayInstance; arrayInstance.add( 0.0f ); arrayInstance.add( 1.0f ); EXPECT_EQ( 0.0f, arrayInstance[ 0 ] ); EXPECT_EQ( 1.0f, arrayInstance[ 1 ] ); } TEST_F( TArrayTest, backTest ) { float item( 0.0f ); TArray<float> arrayInstance; arrayInstance.add( 1.0f ); item = arrayInstance.back(); EXPECT_FLOAT_EQ( 1.0f, item ); arrayInstance.add( 2.0f ); item = arrayInstance.back(); EXPECT_FLOAT_EQ( 2.0f, item ); } struct foo { float m_item; foo() : m_item( 1.0f ) {} }; TEST_F( TArrayTest, constBackTest ) { TArray<foo> fooArrayInstance; foo foo1; foo1.m_item = 1.0f; fooArrayInstance.add( foo1 ); const foo &res1 = fooArrayInstance.back(); EXPECT_FLOAT_EQ( 1.0f, res1.m_item ); foo foo2; foo2.m_item = 2.0f; fooArrayInstance.add( foo2 ); const foo &res2 = fooArrayInstance.back(); EXPECT_FLOAT_EQ( 2.0f, res2.m_item ); } TEST_F( TArrayTest, removeTest) { TArray<float> arrayInstance; createArray( ArrayData, ArraySize, arrayInstance ); std::stringstream stream; static const size_t Size = 3; arrayInstance.remove( 1 ); EXPECT_EQ( Size, arrayInstance.size() ); float expectedResult[ Size ] = { 0.0f, 2.0f, 3.0f }; bool equal = true; for ( size_t i=0; i<Size; ++i ) { if ( arrayInstance[ i ] != expectedResult[ i ] ) { stream << "error in index " << i << std::endl; equal = false; break; } } EXPECT_TRUE( equal ) << stream.str(); } TEST_F( TArrayTest, removeItTest) { TArray<float> arrayInstance; arrayInstance.add( 1.0f ); EXPECT_EQ( 1u, arrayInstance.size() ); TArray<float>::Iterator it = arrayInstance.find( 1.0f ); EXPECT_NE( arrayInstance.end(), it ); arrayInstance.remove( it ); EXPECT_EQ( 0u, arrayInstance.size() ); } TEST_F( TArrayTest, removeBackTest) { TArray<float> arrayInstance; createArray( ArrayData, ArraySize, arrayInstance ); arrayInstance.removeBack(); EXPECT_EQ( 3u, arrayInstance.size() ); EXPECT_EQ( 2.0f, arrayInstance[ 2 ] ); } TEST_F( TArrayTest, resizeTest ) { TArray<float> arrayInstance; EXPECT_EQ( 0u, arrayInstance.size() ); arrayInstance.resize( 5 ); EXPECT_EQ( 5u, arrayInstance.size() ); } TEST_F( TArrayTest, moveTest ) { TArray<float> arrayInstance; arrayInstance.add( 1.0f ); arrayInstance.add( 2.0f ); arrayInstance.add( 3.0f ); arrayInstance.move( 1, 2 ); } TEST_F( TArrayTest, reserveTest ) { TArray<float> arrayInstance; EXPECT_EQ( 0u, arrayInstance.capacity() ); arrayInstance.reserve( 5 ); EXPECT_EQ( 5u, arrayInstance.capacity() ); static const size_t NewSize = 2000; arrayInstance.reserve(NewSize); EXPECT_EQ( NewSize, arrayInstance.capacity() ); } TEST_F( TArrayTest, resize_with_init_Test ) { TArray<float> arrayInstance; EXPECT_EQ( 0u, arrayInstance.capacity() ); arrayInstance.resize( 10, 1.0f ); EXPECT_EQ( 10u, arrayInstance.size() ); for ( size_t i = 0; i < 10; ++i ) { EXPECT_FLOAT_EQ( 1.0f, arrayInstance[ i ] ); } } TEST_F( TArrayTest, iterateTest ) { TArray<float> arrayInstance; createArray( ArrayData, ArraySize, arrayInstance ); size_t i( 0 ); for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ) { ++i; } EXPECT_EQ( i, arrayInstance.size() ); } TEST_F( TArrayTest, preIncIterateTest ) { TArray<float> arrayInstance; createArray( ArrayData, ArraySize, arrayInstance ); bool ok = true; try { size_t i( 0 ); for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ) { float tmp = *it; EXPECT_EQ( tmp, ArrayData[ i ] ); ++i; } } catch (...) { ok = false; } EXPECT_TRUE( ok ); } TEST_F( TArrayTest, postIncIterateTest ) { TArray<float> arrayInstance; createArray( ArrayData, ArraySize, arrayInstance ); bool ok = true; try { size_t i(0); for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); it++ ) { float tmp = *it; EXPECT_EQ( tmp, ArrayData[ i ] ); ++i; } } catch (...) { ok = false; } EXPECT_TRUE( ok ); } TEST_F( TArrayTest, findTest ) { TArray<float> arrayInstance; arrayInstance.add( 0.0f ); arrayInstance.add( 1.0f ); arrayInstance.add( 2.0f ); arrayInstance.add( 3.0f ); EXPECT_EQ( 4u, arrayInstance.size() ); TArray<float>::Iterator it = arrayInstance.find( 1.0f ); EXPECT_NE( it, arrayInstance.end() ); EXPECT_EQ( *it, 1.0f ); } TEST_F( TArrayTest, ContainerClearTest ) { TArray<float*> arrayInstance; ContainerClear( arrayInstance ); EXPECT_TRUE( arrayInstance.isEmpty() ); arrayInstance.add( new float( 0.0f ) ); arrayInstance.add( new float( 1.0f ) ); arrayInstance.add( new float( 2.0f ) ); EXPECT_EQ( arrayInstance.size(), 3U ); ContainerClear( arrayInstance ); EXPECT_EQ( arrayInstance.size(), 0U ); EXPECT_TRUE( arrayInstance.isEmpty() ); } //--------------------------------------------------------------------------------------------- // Crash when iterating an empty array. //--------------------------------------------------------------------------------------------- TEST_F( TArrayTest, bug_IterateEmptyListTest ) { TArray<float> arrayInstance; bool ok = true; try { for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ); } catch ( ... ) { ok = false; } EXPECT_TRUE( ok ); } //--------------------------------------------------------------------------------------------- // Heap corruption after grow. //--------------------------------------------------------------------------------------------- TEST_F( TArrayTest, bug_AddHeapCorruptTest ) { TArray<float> arrayInstance; for ( size_t i=0; i<50; ++i ) { arrayInstance.add( ( float ) i ); } } <commit_msg>Update TArrayTest.cpp<commit_after>/* ------------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2019 Kim Kulling Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------------------------- */ #include <cppcore/Container/TArray.h> #include <cppcore/CPPCoreCommon.h> #include "gtest/gtest.h" #include <sstream> #include <iostream> using namespace CPPCore; static const size_t ArraySize = 4; static const float ArrayData[ ArraySize ] = { 0.0f, 1.0f, 2.0f, 3.0f }; //------------------------------------------------------------------------------------------------- /// @class TArrayTest /// @ingroup UnitTest /// /// @brief The array tests, includes showcases how to add remove and access data. //------------------------------------------------------------------------------------------------- class TArrayTest : public testing::Test { protected: void createArray( const float *pOrig, size_t numItems, TArray<float> &arrayInstance ) { for ( size_t i=0; i<numItems; ++i ) { arrayInstance.add( pOrig[ i ] ); } } }; TEST_F( TArrayTest, constructTest ) { TArray<float> arrayInstance; EXPECT_EQ( true, arrayInstance.isEmpty() ); EXPECT_EQ( 0U, arrayInstance.size() ); EXPECT_EQ( arrayInstance.begin(), arrayInstance.end() ); } TEST_F( TArrayTest, constructWithSizeTest) { TArray<float> arrayInstance( 4 ); EXPECT_EQ( 4u, arrayInstance.size() ); for ( size_t i=0; i<4; ++i ) { const float f = arrayInstance[i]; EXPECT_EQ(0, f ); } } TEST_F( TArrayTest, addTest) { TArray<float> arrayInstance; arrayInstance.add( 0.0f ); arrayInstance.add( 1.0f ); EXPECT_EQ( 2u, arrayInstance.size() ); EXPECT_EQ( 0.0f, arrayInstance[ 0 ] ); EXPECT_EQ( 1.0f, arrayInstance[ 1 ] ); } TEST_F( TArrayTest, addItemsTest ) { TArray<float> arrayInstance; arrayInstance.add( 0.0f ); float data[2] = { 0, 1 }; arrayInstance.add( data, 2 ); EXPECT_EQ( 3u, arrayInstance.size() ); EXPECT_EQ( 0.0f, arrayInstance[ 0 ] ); EXPECT_EQ( 0.0f, arrayInstance[ 1 ] ); EXPECT_EQ( 1.0f, arrayInstance[ 2 ] ); arrayInstance.add( nullptr, 0 ); EXPECT_EQ( 3u, arrayInstance.size() ); } TEST_F( TArrayTest, accessTest) { TArray<float> arrayInstance; arrayInstance.add( 0.0f ); arrayInstance.add( 1.0f ); EXPECT_EQ( 0.0f, arrayInstance[ 0 ] ); EXPECT_EQ( 1.0f, arrayInstance[ 1 ] ); } TEST_F( TArrayTest, backTest ) { float item( 0.0f ); TArray<float> arrayInstance; arrayInstance.add( 1.0f ); item = arrayInstance.back(); EXPECT_FLOAT_EQ( 1.0f, item ); arrayInstance.add( 2.0f ); item = arrayInstance.back(); EXPECT_FLOAT_EQ( 2.0f, item ); } struct foo { float m_item; foo() : m_item( 1.0f ) {} }; TEST_F( TArrayTest, constBackTest ) { TArray<foo> fooArrayInstance; foo foo1; foo1.m_item = 1.0f; fooArrayInstance.add( foo1 ); const foo &res1 = fooArrayInstance.back(); EXPECT_FLOAT_EQ( 1.0f, res1.m_item ); foo foo2; foo2.m_item = 2.0f; fooArrayInstance.add( foo2 ); const foo &res2 = fooArrayInstance.back(); EXPECT_FLOAT_EQ( 2.0f, res2.m_item ); } TEST_F( TArrayTest, removeTest) { TArray<float> arrayInstance; createArray( ArrayData, ArraySize, arrayInstance ); std::stringstream stream; static const size_t Size = 3; arrayInstance.remove( 1 ); EXPECT_EQ( Size, arrayInstance.size() ); float expectedResult[ Size ] = { 0.0f, 2.0f, 3.0f }; bool equal = true; for ( size_t i=0; i<Size; ++i ) { if ( arrayInstance[ i ] != expectedResult[ i ] ) { stream << "error in index " << i << std::endl; equal = false; break; } } EXPECT_TRUE( equal ) << stream.str(); } TEST_F( TArrayTest, removeItTest) { TArray<float> arrayInstance; arrayInstance.add( 1.0f ); EXPECT_EQ( 1u, arrayInstance.size() ); TArray<float>::Iterator it = arrayInstance.find( 1.0f ); EXPECT_NE( arrayInstance.end(), it ); arrayInstance.remove( it ); EXPECT_EQ( 0u, arrayInstance.size() ); } TEST_F( TArrayTest, removeBackTest) { TArray<float> arrayInstance; createArray( ArrayData, ArraySize, arrayInstance ); arrayInstance.removeBack(); EXPECT_EQ( 3u, arrayInstance.size() ); EXPECT_EQ( 2.0f, arrayInstance[ 2 ] ); } TEST_F( TArrayTest, resizeTest ) { TArray<float> arrayInstance; EXPECT_EQ( 0u, arrayInstance.size() ); arrayInstance.resize( 5 ); EXPECT_EQ( 5u, arrayInstance.size() ); } TEST_F( TArrayTest, moveTest ) { TArray<float> arrayInstance; arrayInstance.add( 1.0f ); arrayInstance.add( 2.0f ); arrayInstance.add( 3.0f ); arrayInstance.move( 1, 2 ); } TEST_F( TArrayTest, reserveTest ) { TArray<float> arrayInstance; EXPECT_EQ( 0u, arrayInstance.capacity() ); arrayInstance.reserve( 5 ); EXPECT_EQ( 5u, arrayInstance.capacity() ); static const size_t NewSize = 2000; arrayInstance.reserve(NewSize); EXPECT_EQ( NewSize, arrayInstance.capacity() ); } TEST_F( TArrayTest, resize_with_init_Test ) { TArray<float> arrayInstance; EXPECT_EQ( 0u, arrayInstance.capacity() ); arrayInstance.resize( 10, 1.0f ); EXPECT_EQ( 10u, arrayInstance.size() ); for ( size_t i = 0; i < 10; ++i ) { EXPECT_FLOAT_EQ( 1.0f, arrayInstance[ i ] ); } } TEST_F( TArrayTest, iterateTest ) { TArray<float> arrayInstance; createArray( ArrayData, ArraySize, arrayInstance ); size_t i( 0 ); for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ) { ++i; } EXPECT_EQ( i, arrayInstance.size() ); } TEST_F( TArrayTest, preIncIterateTest ) { TArray<float> arrayInstance; createArray( ArrayData, ArraySize, arrayInstance ); bool ok = true; try { size_t i( 0 ); for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ) { float tmp = *it; EXPECT_EQ( tmp, ArrayData[ i ] ); ++i; } } catch (...) { ok = false; } EXPECT_TRUE( ok ); } TEST_F( TArrayTest, postIncIterateTest ) { TArray<float> arrayInstance; createArray( ArrayData, ArraySize, arrayInstance ); bool ok = true; try { size_t i(0); for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); it++ ) { float tmp = *it; EXPECT_EQ( tmp, ArrayData[ i ] ); ++i; } } catch (...) { ok = false; } EXPECT_TRUE( ok ); } TEST_F( TArrayTest, findTest ) { TArray<float> arrayInstance; arrayInstance.add( 0.0f ); arrayInstance.add( 1.0f ); arrayInstance.add( 2.0f ); arrayInstance.add( 3.0f ); EXPECT_EQ( 4u, arrayInstance.size() ); TArray<float>::Iterator it = arrayInstance.find( 1.0f ); EXPECT_NE( it, arrayInstance.end() ); EXPECT_EQ( *it, 1.0f ); } TEST_F( TArrayTest, ContainerClearTest ) { TArray<float*> arrayInstance; ContainerClear( arrayInstance ); EXPECT_TRUE( arrayInstance.isEmpty() ); arrayInstance.add( new float( 0.0f ) ); arrayInstance.add( new float( 1.0f ) ); arrayInstance.add( new float( 2.0f ) ); EXPECT_EQ( arrayInstance.size(), 3U ); ContainerClear( arrayInstance ); EXPECT_EQ( arrayInstance.size(), 0U ); EXPECT_TRUE( arrayInstance.isEmpty() ); } //--------------------------------------------------------------------------------------------- // Crash when iterating an empty array. //--------------------------------------------------------------------------------------------- TEST_F( TArrayTest, bug_IterateEmptyListTest ) { TArray<float> arrayInstance; bool ok = true; try { for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ); } catch ( ... ) { ok = false; } EXPECT_TRUE( ok ); } //--------------------------------------------------------------------------------------------- // Heap corruption after grow. //--------------------------------------------------------------------------------------------- TEST_F( TArrayTest, bug_AddHeapCorruptTest ) { TArray<float> arrayInstance; for ( size_t i=0; i<50; ++i ) { arrayInstance.add( ( float ) i ); } } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <entt/signal/delegate.hpp> int delegate_function(const int &i) { return i*i; } int curried_function(const int *i, int j) { return *i+j; } struct delegate_functor { int operator()(int i) { return i+i; } int identity(int i) const { return i; } static const int static_value = 3; const int data_member = 42; }; struct const_nonconst_noexcept { void f() { ++cnt; } void g() noexcept { ++cnt; } void h() const { ++cnt; } void i() const noexcept { ++cnt; } mutable int cnt{0}; }; TEST(Delegate, Functionalities) { entt::delegate<int(int)> ff_del; entt::delegate<int(int)> mf_del; delegate_functor functor; ASSERT_FALSE(ff_del); ASSERT_FALSE(mf_del); ASSERT_EQ(ff_del, mf_del); ff_del.connect<&delegate_function>(); mf_del.connect<&delegate_functor::operator()>(&functor); ASSERT_TRUE(ff_del); ASSERT_TRUE(mf_del); ASSERT_EQ(ff_del(3), 9); ASSERT_EQ(mf_del(3), 6); ff_del.reset(); ASSERT_FALSE(ff_del); ASSERT_TRUE(mf_del); ASSERT_EQ(ff_del, entt::delegate<int(int)>{}); ASSERT_NE(mf_del, entt::delegate<int(int)>{}); ASSERT_NE(ff_del, mf_del); mf_del.reset(); ASSERT_FALSE(ff_del); ASSERT_FALSE(mf_del); ASSERT_EQ(ff_del, entt::delegate<int(int)>{}); ASSERT_EQ(mf_del, entt::delegate<int(int)>{}); ASSERT_EQ(ff_del, mf_del); } TEST(Delegate, DataMembers) { entt::delegate<double()> delegate; delegate_functor functor; delegate.connect<&delegate_functor::data_member>(&functor); ASSERT_EQ(delegate(), 42); } TEST(Delegate, Comparison) { entt::delegate<int(int)> lhs; entt::delegate<int(int)> rhs; delegate_functor functor; delegate_functor other; const int value = 0; ASSERT_EQ(lhs, entt::delegate<int(int)>{}); ASSERT_FALSE(lhs != rhs); ASSERT_TRUE(lhs == rhs); ASSERT_EQ(lhs, rhs); lhs.connect<&delegate_function>(); ASSERT_EQ(lhs, entt::delegate<int(int)>{entt::connect_arg<&delegate_function>}); ASSERT_TRUE(lhs != rhs); ASSERT_FALSE(lhs == rhs); ASSERT_NE(lhs, rhs); rhs.connect<&delegate_function>(); ASSERT_EQ(rhs, entt::delegate<int(int)>{entt::connect_arg<&delegate_function>}); ASSERT_FALSE(lhs != rhs); ASSERT_TRUE(lhs == rhs); ASSERT_EQ(lhs, rhs); lhs.connect<&curried_function>(&value); ASSERT_EQ(lhs, (entt::delegate<int(int)>{entt::connect_arg<&curried_function>, &value})); ASSERT_TRUE(lhs != rhs); ASSERT_FALSE(lhs == rhs); ASSERT_NE(lhs, rhs); rhs.connect<&curried_function>(&value); ASSERT_EQ(rhs, (entt::delegate<int(int)>{entt::connect_arg<&curried_function>, &value})); ASSERT_FALSE(lhs != rhs); ASSERT_TRUE(lhs == rhs); ASSERT_EQ(lhs, rhs); lhs.connect<&delegate_functor::operator()>(&functor); ASSERT_EQ(lhs, (entt::delegate<int(int)>{entt::connect_arg<&delegate_functor::operator()>, &functor})); ASSERT_TRUE(lhs != rhs); ASSERT_FALSE(lhs == rhs); ASSERT_NE(lhs, rhs); rhs.connect<&delegate_functor::operator()>(&functor); ASSERT_EQ(rhs, (entt::delegate<int(int)>{entt::connect_arg<&delegate_functor::operator()>, &functor})); ASSERT_FALSE(lhs != rhs); ASSERT_TRUE(lhs == rhs); ASSERT_EQ(lhs, rhs); lhs.connect<&delegate_functor::operator()>(&other); ASSERT_EQ(lhs, (entt::delegate<int(int)>{entt::connect_arg<&delegate_functor::operator()>, &other})); ASSERT_NE(lhs.instance(), rhs.instance()); ASSERT_FALSE(lhs != rhs); ASSERT_TRUE(lhs == rhs); ASSERT_EQ(lhs, rhs); lhs.reset(); ASSERT_EQ(lhs, (entt::delegate<int(int)>{})); ASSERT_TRUE(lhs != rhs); ASSERT_FALSE(lhs == rhs); ASSERT_NE(lhs, rhs); rhs.reset(); ASSERT_EQ(rhs, (entt::delegate<int(int)>{})); ASSERT_FALSE(lhs != rhs); ASSERT_TRUE(lhs == rhs); ASSERT_EQ(lhs, rhs); } TEST(Delegate, ConstNonConstNoExcept) { entt::delegate<void()> delegate; const_nonconst_noexcept functor; delegate.connect<&const_nonconst_noexcept::f>(&functor); delegate(); delegate.connect<&const_nonconst_noexcept::g>(&functor); delegate(); delegate.connect<&const_nonconst_noexcept::h>(&functor); delegate(); delegate.connect<&const_nonconst_noexcept::i>(&functor); delegate(); ASSERT_EQ(functor.cnt, 4); } TEST(Delegate, DeducedGuidelines) { const_nonconst_noexcept functor; const int value = 0; entt::delegate func_deduced{entt::connect_arg<&delegate_function>}; entt::delegate curried_func_deduced{entt::connect_arg<&curried_function>, &value}; entt::delegate member_f_deduced{entt::connect_arg<&const_nonconst_noexcept::f>, &functor}; entt::delegate member_g_deduced{entt::connect_arg<&const_nonconst_noexcept::g>, &functor}; entt::delegate member_h_deduced{entt::connect_arg<&const_nonconst_noexcept::h>, &functor}; entt::delegate member_i_deduced{entt::connect_arg<&const_nonconst_noexcept::i>, &functor}; static_assert(std::is_same_v<typename decltype(func_deduced)::function_type, int(const int &)>); static_assert(std::is_same_v<typename decltype(curried_func_deduced)::function_type, int(int)>); static_assert(std::is_same_v<typename decltype(member_f_deduced)::function_type, void()>); static_assert(std::is_same_v<typename decltype(member_g_deduced)::function_type, void()>); static_assert(std::is_same_v<typename decltype(member_h_deduced)::function_type, void()>); static_assert(std::is_same_v<typename decltype(member_i_deduced)::function_type, void()>); ASSERT_TRUE(func_deduced); ASSERT_TRUE(curried_func_deduced); ASSERT_TRUE(member_f_deduced); ASSERT_TRUE(member_g_deduced); ASSERT_TRUE(member_h_deduced); ASSERT_TRUE(member_i_deduced); } TEST(Delegate, ConstInstance) { entt::delegate<int(int)> delegate; const delegate_functor functor; ASSERT_FALSE(delegate); delegate.connect<&delegate_functor::identity>(&functor); ASSERT_TRUE(delegate); ASSERT_EQ(delegate(3), 3); delegate.reset(); ASSERT_FALSE(delegate); ASSERT_EQ(delegate, entt::delegate<int(int)>{}); } TEST(Delegate, CurriedFunction) { entt::delegate<int(int)> delegate; const auto value = 3; delegate.connect<&curried_function>(&value); ASSERT_TRUE(delegate); ASSERT_EQ(delegate(1), 4); } TEST(Delegate, Constructors) { delegate_functor functor; const auto value = 2; entt::delegate<int(int)> empty{}; entt::delegate<int(int)> func{entt::connect_arg<&delegate_function>}; entt::delegate<int(int)> curr{entt::connect_arg<&curried_function>, &value}; entt::delegate<int(int)> member{entt::connect_arg<&delegate_functor::operator()>, &functor}; ASSERT_FALSE(empty); ASSERT_TRUE(func); ASSERT_EQ(9, func(3)); ASSERT_TRUE(curr); ASSERT_EQ(5, curr(3)); ASSERT_TRUE(member); ASSERT_EQ(6, member(3)); } TEST(Delegate, VoidVsNonVoidReturnType) { delegate_functor functor; entt::delegate<void(int)> func{entt::connect_arg<&delegate_function>}; entt::delegate<void(int)> member{entt::connect_arg<&delegate_functor::operator()>, &functor}; entt::delegate<void(int)> cmember{entt::connect_arg<&delegate_functor::identity>, &std::as_const(functor)}; ASSERT_TRUE(func); ASSERT_TRUE(member); ASSERT_TRUE(cmember); } <commit_msg>fixed typo<commit_after>#include <gtest/gtest.h> #include <entt/signal/delegate.hpp> int delegate_function(const int &i) { return i*i; } int curried_function(const int *i, int j) { return *i+j; } struct delegate_functor { int operator()(int i) { return i+i; } int identity(int i) const { return i; } static const int static_value = 3; const int data_member = 42; }; struct const_nonconst_noexcept { void f() { ++cnt; } void g() noexcept { ++cnt; } void h() const { ++cnt; } void i() const noexcept { ++cnt; } mutable int cnt{0}; }; TEST(Delegate, Functionalities) { entt::delegate<int(int)> ff_del; entt::delegate<int(int)> mf_del; delegate_functor functor; ASSERT_FALSE(ff_del); ASSERT_FALSE(mf_del); ASSERT_EQ(ff_del, mf_del); ff_del.connect<&delegate_function>(); mf_del.connect<&delegate_functor::operator()>(&functor); ASSERT_TRUE(ff_del); ASSERT_TRUE(mf_del); ASSERT_EQ(ff_del(3), 9); ASSERT_EQ(mf_del(3), 6); ff_del.reset(); ASSERT_FALSE(ff_del); ASSERT_TRUE(mf_del); ASSERT_EQ(ff_del, entt::delegate<int(int)>{}); ASSERT_NE(mf_del, entt::delegate<int(int)>{}); ASSERT_NE(ff_del, mf_del); mf_del.reset(); ASSERT_FALSE(ff_del); ASSERT_FALSE(mf_del); ASSERT_EQ(ff_del, entt::delegate<int(int)>{}); ASSERT_EQ(mf_del, entt::delegate<int(int)>{}); ASSERT_EQ(ff_del, mf_del); } TEST(Delegate, DataMembers) { entt::delegate<double()> delegate; delegate_functor functor; delegate.connect<&delegate_functor::data_member>(&functor); ASSERT_EQ(delegate(), 42); } TEST(Delegate, Comparison) { entt::delegate<int(int)> lhs; entt::delegate<int(int)> rhs; delegate_functor functor; delegate_functor other; const int value = 0; ASSERT_EQ(lhs, entt::delegate<int(int)>{}); ASSERT_FALSE(lhs != rhs); ASSERT_TRUE(lhs == rhs); ASSERT_EQ(lhs, rhs); lhs.connect<&delegate_function>(); ASSERT_EQ(lhs, entt::delegate<int(int)>{entt::connect_arg<&delegate_function>}); ASSERT_TRUE(lhs != rhs); ASSERT_FALSE(lhs == rhs); ASSERT_NE(lhs, rhs); rhs.connect<&delegate_function>(); ASSERT_EQ(rhs, entt::delegate<int(int)>{entt::connect_arg<&delegate_function>}); ASSERT_FALSE(lhs != rhs); ASSERT_TRUE(lhs == rhs); ASSERT_EQ(lhs, rhs); lhs.connect<&curried_function>(&value); ASSERT_EQ(lhs, (entt::delegate<int(int)>{entt::connect_arg<&curried_function>, &value})); ASSERT_TRUE(lhs != rhs); ASSERT_FALSE(lhs == rhs); ASSERT_NE(lhs, rhs); rhs.connect<&curried_function>(&value); ASSERT_EQ(rhs, (entt::delegate<int(int)>{entt::connect_arg<&curried_function>, &value})); ASSERT_FALSE(lhs != rhs); ASSERT_TRUE(lhs == rhs); ASSERT_EQ(lhs, rhs); lhs.connect<&delegate_functor::operator()>(&functor); ASSERT_EQ(lhs, (entt::delegate<int(int)>{entt::connect_arg<&delegate_functor::operator()>, &functor})); ASSERT_TRUE(lhs != rhs); ASSERT_FALSE(lhs == rhs); ASSERT_NE(lhs, rhs); rhs.connect<&delegate_functor::operator()>(&functor); ASSERT_EQ(rhs, (entt::delegate<int(int)>{entt::connect_arg<&delegate_functor::operator()>, &functor})); ASSERT_FALSE(lhs != rhs); ASSERT_TRUE(lhs == rhs); ASSERT_EQ(lhs, rhs); lhs.connect<&delegate_functor::operator()>(&other); ASSERT_EQ(lhs, (entt::delegate<int(int)>{entt::connect_arg<&delegate_functor::operator()>, &other})); ASSERT_NE(lhs.instance(), rhs.instance()); ASSERT_FALSE(lhs != rhs); ASSERT_TRUE(lhs == rhs); ASSERT_EQ(lhs, rhs); lhs.reset(); ASSERT_EQ(lhs, (entt::delegate<int(int)>{})); ASSERT_TRUE(lhs != rhs); ASSERT_FALSE(lhs == rhs); ASSERT_NE(lhs, rhs); rhs.reset(); ASSERT_EQ(rhs, (entt::delegate<int(int)>{})); ASSERT_FALSE(lhs != rhs); ASSERT_TRUE(lhs == rhs); ASSERT_EQ(lhs, rhs); } TEST(Delegate, ConstNonConstNoExcept) { entt::delegate<void()> delegate; const_nonconst_noexcept functor; delegate.connect<&const_nonconst_noexcept::f>(&functor); delegate(); delegate.connect<&const_nonconst_noexcept::g>(&functor); delegate(); delegate.connect<&const_nonconst_noexcept::h>(&functor); delegate(); delegate.connect<&const_nonconst_noexcept::i>(&functor); delegate(); ASSERT_EQ(functor.cnt, 4); } TEST(Delegate, DeducedGuide) { const_nonconst_noexcept functor; const int value = 0; entt::delegate func_deduced{entt::connect_arg<&delegate_function>}; entt::delegate curried_func_deduced{entt::connect_arg<&curried_function>, &value}; entt::delegate member_f_deduced{entt::connect_arg<&const_nonconst_noexcept::f>, &functor}; entt::delegate member_g_deduced{entt::connect_arg<&const_nonconst_noexcept::g>, &functor}; entt::delegate member_h_deduced{entt::connect_arg<&const_nonconst_noexcept::h>, &functor}; entt::delegate member_i_deduced{entt::connect_arg<&const_nonconst_noexcept::i>, &functor}; static_assert(std::is_same_v<typename decltype(func_deduced)::function_type, int(const int &)>); static_assert(std::is_same_v<typename decltype(curried_func_deduced)::function_type, int(int)>); static_assert(std::is_same_v<typename decltype(member_f_deduced)::function_type, void()>); static_assert(std::is_same_v<typename decltype(member_g_deduced)::function_type, void()>); static_assert(std::is_same_v<typename decltype(member_h_deduced)::function_type, void()>); static_assert(std::is_same_v<typename decltype(member_i_deduced)::function_type, void()>); ASSERT_TRUE(func_deduced); ASSERT_TRUE(curried_func_deduced); ASSERT_TRUE(member_f_deduced); ASSERT_TRUE(member_g_deduced); ASSERT_TRUE(member_h_deduced); ASSERT_TRUE(member_i_deduced); } TEST(Delegate, ConstInstance) { entt::delegate<int(int)> delegate; const delegate_functor functor; ASSERT_FALSE(delegate); delegate.connect<&delegate_functor::identity>(&functor); ASSERT_TRUE(delegate); ASSERT_EQ(delegate(3), 3); delegate.reset(); ASSERT_FALSE(delegate); ASSERT_EQ(delegate, entt::delegate<int(int)>{}); } TEST(Delegate, CurriedFunction) { entt::delegate<int(int)> delegate; const auto value = 3; delegate.connect<&curried_function>(&value); ASSERT_TRUE(delegate); ASSERT_EQ(delegate(1), 4); } TEST(Delegate, Constructors) { delegate_functor functor; const auto value = 2; entt::delegate<int(int)> empty{}; entt::delegate<int(int)> func{entt::connect_arg<&delegate_function>}; entt::delegate<int(int)> curr{entt::connect_arg<&curried_function>, &value}; entt::delegate<int(int)> member{entt::connect_arg<&delegate_functor::operator()>, &functor}; ASSERT_FALSE(empty); ASSERT_TRUE(func); ASSERT_EQ(9, func(3)); ASSERT_TRUE(curr); ASSERT_EQ(5, curr(3)); ASSERT_TRUE(member); ASSERT_EQ(6, member(3)); } TEST(Delegate, VoidVsNonVoidReturnType) { delegate_functor functor; entt::delegate<void(int)> func{entt::connect_arg<&delegate_function>}; entt::delegate<void(int)> member{entt::connect_arg<&delegate_functor::operator()>, &functor}; entt::delegate<void(int)> cmember{entt::connect_arg<&delegate_functor::identity>, &std::as_const(functor)}; ASSERT_TRUE(func); ASSERT_TRUE(member); ASSERT_TRUE(cmember); } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/i420_video_source.h" #include "test/util.h" namespace { const int kMaxErrorFrames = 8; const int kMaxDroppableFrames = 8; class ErrorResilienceTest : public ::libvpx_test::EncoderTest, public ::libvpx_test::CodecTestWithParam<libvpx_test::TestMode> { protected: ErrorResilienceTest() : EncoderTest(GET_PARAM(0)), psnr_(0.0), nframes_(0), mismatch_psnr_(0.0), mismatch_nframes_(0), encoding_mode_(GET_PARAM(1)) { Reset(); } virtual ~ErrorResilienceTest() {} void Reset() { error_nframes_ = 0; droppable_nframes_ = 0; } virtual void SetUp() { InitializeConfig(); SetMode(encoding_mode_); } virtual void BeginPassHook(unsigned int /*pass*/) { psnr_ = 0.0; nframes_ = 0; mismatch_psnr_ = 0.0; mismatch_nframes_ = 0; } virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) { psnr_ += pkt->data.psnr.psnr[0]; nframes_++; } virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video) { frame_flags_ &= ~(VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF); if (droppable_nframes_ > 0 && (cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) { for (unsigned int i = 0; i < droppable_nframes_; ++i) { if (droppable_frames_[i] == video->frame()) { std::cout << " Encoding droppable frame: " << droppable_frames_[i] << "\n"; frame_flags_ |= (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF); return; } } } } double GetAveragePsnr() const { if (nframes_) return psnr_ / nframes_; return 0.0; } double GetAverageMismatchPsnr() const { if (mismatch_nframes_) return mismatch_psnr_ / mismatch_nframes_; return 0.0; } virtual bool DoDecode() const { if (error_nframes_ > 0 && (cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) { for (unsigned int i = 0; i < error_nframes_; ++i) { if (error_frames_[i] == nframes_ - 1) { std::cout << " Skipping decoding frame: " << error_frames_[i] << "\n"; return 0; } } } return 1; } virtual void MismatchHook(const vpx_image_t *img1, const vpx_image_t *img2) { double mismatch_psnr = compute_psnr(img1, img2); mismatch_psnr_ += mismatch_psnr; ++mismatch_nframes_; // std::cout << "Mismatch frame psnr: " << mismatch_psnr << "\n"; } void SetErrorFrames(int num, unsigned int *list) { if (num > kMaxErrorFrames) num = kMaxErrorFrames; else if (num < 0) num = 0; error_nframes_ = num; for (unsigned int i = 0; i < error_nframes_; ++i) error_frames_[i] = list[i]; } void SetDroppableFrames(int num, unsigned int *list) { if (num > kMaxDroppableFrames) num = kMaxDroppableFrames; else if (num < 0) num = 0; droppable_nframes_ = num; for (unsigned int i = 0; i < droppable_nframes_; ++i) droppable_frames_[i] = list[i]; } unsigned int GetMismatchFrames() { return mismatch_nframes_; } private: double psnr_; unsigned int nframes_; unsigned int error_nframes_; unsigned int droppable_nframes_; double mismatch_psnr_; unsigned int mismatch_nframes_; unsigned int error_frames_[kMaxErrorFrames]; unsigned int droppable_frames_[kMaxDroppableFrames]; libvpx_test::TestMode encoding_mode_; }; TEST_P(ErrorResilienceTest, OnVersusOff) { const vpx_rational timebase = { 33333333, 1000000000 }; cfg_.g_timebase = timebase; cfg_.rc_target_bitrate = 2000; cfg_.g_lag_in_frames = 10; init_flags_ = VPX_CODEC_USE_PSNR; libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, timebase.den, timebase.num, 0, 30); // Error resilient mode OFF. cfg_.g_error_resilient = 0; ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); const double psnr_resilience_off = GetAveragePsnr(); EXPECT_GT(psnr_resilience_off, 25.0); // Error resilient mode ON. cfg_.g_error_resilient = 1; ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); const double psnr_resilience_on = GetAveragePsnr(); EXPECT_GT(psnr_resilience_on, 25.0); // Test that turning on error resilient mode hurts by 10% at most. if (psnr_resilience_off > 0.0) { const double psnr_ratio = psnr_resilience_on / psnr_resilience_off; EXPECT_GE(psnr_ratio, 0.9); EXPECT_LE(psnr_ratio, 1.1); } } TEST_P(ErrorResilienceTest, DropFramesWithoutRecovery) { const vpx_rational timebase = { 33333333, 1000000000 }; cfg_.g_timebase = timebase; cfg_.rc_target_bitrate = 500; // FIXME(debargha): Fix this to work for any lag. // Currently this test only works for lag = 0 cfg_.g_lag_in_frames = 0; init_flags_ = VPX_CODEC_USE_PSNR; libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, timebase.den, timebase.num, 0, 30); // Error resilient mode ON. cfg_.g_error_resilient = 1; // Set an arbitrary set of error frames same as droppable frames unsigned int num_droppable_frames = 2; unsigned int droppable_frame_list[] = {5, 16}; SetDroppableFrames(num_droppable_frames, droppable_frame_list); SetErrorFrames(num_droppable_frames, droppable_frame_list); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); // Test that no mismatches have been found std::cout << " Mismatch frames: " << GetMismatchFrames() << "\n"; EXPECT_EQ(GetMismatchFrames(), (unsigned int) 0); // reset previously set error/droppable frames Reset(); #if 0 // TODO(jkoleszar): This test is disabled for the time being as too // sensitive. It's not clear how to set a reasonable threshold for // this behavior. // Now set an arbitrary set of error frames that are non-droppable unsigned int num_error_frames = 3; unsigned int error_frame_list[] = {3, 10, 20}; SetErrorFrames(num_error_frames, error_frame_list); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); // Test that dropping an arbitrary set of inter frames does not hurt too much // Note the Average Mismatch PSNR is the average of the PSNR between // decoded frame and encoder's version of the same frame for all frames // with mismatch. const double psnr_resilience_mismatch = GetAverageMismatchPsnr(); std::cout << " Mismatch PSNR: " << psnr_resilience_mismatch << "\n"; EXPECT_GT(psnr_resilience_mismatch, 20.0); #endif } VP8_INSTANTIATE_TEST_CASE(ErrorResilienceTest, ONE_PASS_TEST_MODES); VP9_INSTANTIATE_TEST_CASE(ErrorResilienceTest, ONE_PASS_TEST_MODES); } // namespace <commit_msg>Add consective frame loss to error_resilience test.<commit_after>/* * Copyright (c) 2013 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/i420_video_source.h" #include "test/util.h" namespace { const int kMaxErrorFrames = 12; const int kMaxDroppableFrames = 12; class ErrorResilienceTest : public ::libvpx_test::EncoderTest, public ::libvpx_test::CodecTestWithParam<libvpx_test::TestMode> { protected: ErrorResilienceTest() : EncoderTest(GET_PARAM(0)), psnr_(0.0), nframes_(0), mismatch_psnr_(0.0), mismatch_nframes_(0), encoding_mode_(GET_PARAM(1)) { Reset(); } virtual ~ErrorResilienceTest() {} void Reset() { error_nframes_ = 0; droppable_nframes_ = 0; } virtual void SetUp() { InitializeConfig(); SetMode(encoding_mode_); } virtual void BeginPassHook(unsigned int /*pass*/) { psnr_ = 0.0; nframes_ = 0; mismatch_psnr_ = 0.0; mismatch_nframes_ = 0; } virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) { psnr_ += pkt->data.psnr.psnr[0]; nframes_++; } virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video) { frame_flags_ &= ~(VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF); if (droppable_nframes_ > 0 && (cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) { for (unsigned int i = 0; i < droppable_nframes_; ++i) { if (droppable_frames_[i] == video->frame()) { std::cout << " Encoding droppable frame: " << droppable_frames_[i] << "\n"; frame_flags_ |= (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF); return; } } } } double GetAveragePsnr() const { if (nframes_) return psnr_ / nframes_; return 0.0; } double GetAverageMismatchPsnr() const { if (mismatch_nframes_) return mismatch_psnr_ / mismatch_nframes_; return 0.0; } virtual bool DoDecode() const { if (error_nframes_ > 0 && (cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) { for (unsigned int i = 0; i < error_nframes_; ++i) { if (error_frames_[i] == nframes_ - 1) { std::cout << " Skipping decoding frame: " << error_frames_[i] << "\n"; return 0; } } } return 1; } virtual void MismatchHook(const vpx_image_t *img1, const vpx_image_t *img2) { double mismatch_psnr = compute_psnr(img1, img2); mismatch_psnr_ += mismatch_psnr; ++mismatch_nframes_; // std::cout << "Mismatch frame psnr: " << mismatch_psnr << "\n"; } void SetErrorFrames(int num, unsigned int *list) { if (num > kMaxErrorFrames) num = kMaxErrorFrames; else if (num < 0) num = 0; error_nframes_ = num; for (unsigned int i = 0; i < error_nframes_; ++i) error_frames_[i] = list[i]; } void SetDroppableFrames(int num, unsigned int *list) { if (num > kMaxDroppableFrames) num = kMaxDroppableFrames; else if (num < 0) num = 0; droppable_nframes_ = num; for (unsigned int i = 0; i < droppable_nframes_; ++i) droppable_frames_[i] = list[i]; } unsigned int GetMismatchFrames() { return mismatch_nframes_; } private: double psnr_; unsigned int nframes_; unsigned int error_nframes_; unsigned int droppable_nframes_; double mismatch_psnr_; unsigned int mismatch_nframes_; unsigned int error_frames_[kMaxErrorFrames]; unsigned int droppable_frames_[kMaxDroppableFrames]; libvpx_test::TestMode encoding_mode_; }; TEST_P(ErrorResilienceTest, OnVersusOff) { const vpx_rational timebase = { 33333333, 1000000000 }; cfg_.g_timebase = timebase; cfg_.rc_target_bitrate = 2000; cfg_.g_lag_in_frames = 10; init_flags_ = VPX_CODEC_USE_PSNR; libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, timebase.den, timebase.num, 0, 30); // Error resilient mode OFF. cfg_.g_error_resilient = 0; ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); const double psnr_resilience_off = GetAveragePsnr(); EXPECT_GT(psnr_resilience_off, 25.0); // Error resilient mode ON. cfg_.g_error_resilient = 1; ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); const double psnr_resilience_on = GetAveragePsnr(); EXPECT_GT(psnr_resilience_on, 25.0); // Test that turning on error resilient mode hurts by 10% at most. if (psnr_resilience_off > 0.0) { const double psnr_ratio = psnr_resilience_on / psnr_resilience_off; EXPECT_GE(psnr_ratio, 0.9); EXPECT_LE(psnr_ratio, 1.1); } } // Check for successful decoding and no encoder/decoder mismatch // if we lose (i.e., drop before decoding) a set of droppable // frames (i.e., frames that don't update any reference buffers). // Check both isolated and consecutive loss. TEST_P(ErrorResilienceTest, DropFramesWithoutRecovery) { const vpx_rational timebase = { 33333333, 1000000000 }; cfg_.g_timebase = timebase; cfg_.rc_target_bitrate = 500; // FIXME(debargha): Fix this to work for any lag. // Currently this test only works for lag = 0 cfg_.g_lag_in_frames = 0; init_flags_ = VPX_CODEC_USE_PSNR; libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, timebase.den, timebase.num, 0, 40); // Error resilient mode ON. cfg_.g_error_resilient = 1; cfg_.kf_mode = VPX_KF_DISABLED; // Set an arbitrary set of error frames same as droppable frames. // In addition to isolated loss/drop, add a long consecutive series // (of size 9) of dropped frames. unsigned int num_droppable_frames = 11; unsigned int droppable_frame_list[] = {5, 16, 22, 23, 24, 25, 26, 27, 28, 29, 30}; SetDroppableFrames(num_droppable_frames, droppable_frame_list); SetErrorFrames(num_droppable_frames, droppable_frame_list); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); // Test that no mismatches have been found std::cout << " Mismatch frames: " << GetMismatchFrames() << "\n"; EXPECT_EQ(GetMismatchFrames(), (unsigned int) 0); // Reset previously set of error/droppable frames. Reset(); #if 0 // TODO(jkoleszar): This test is disabled for the time being as too // sensitive. It's not clear how to set a reasonable threshold for // this behavior. // Now set an arbitrary set of error frames that are non-droppable unsigned int num_error_frames = 3; unsigned int error_frame_list[] = {3, 10, 20}; SetErrorFrames(num_error_frames, error_frame_list); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); // Test that dropping an arbitrary set of inter frames does not hurt too much // Note the Average Mismatch PSNR is the average of the PSNR between // decoded frame and encoder's version of the same frame for all frames // with mismatch. const double psnr_resilience_mismatch = GetAverageMismatchPsnr(); std::cout << " Mismatch PSNR: " << psnr_resilience_mismatch << "\n"; EXPECT_GT(psnr_resilience_mismatch, 20.0); #endif } VP8_INSTANTIATE_TEST_CASE(ErrorResilienceTest, ONE_PASS_TEST_MODES); VP9_INSTANTIATE_TEST_CASE(ErrorResilienceTest, ONE_PASS_TEST_MODES); } // namespace <|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> // // 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 "main.h" #include <Eigen/Geometry> #include <Eigen/LU> #include <Eigen/QR> template<typename LineType> void parametrizedline(const LineType& _line) { /* this test covers the following files: ParametrizedLine.h */ using std::abs; typedef typename LineType::Index Index; const Index dim = _line.dim(); typedef typename LineType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<Scalar, LineType::AmbientDimAtCompileTime, 1> VectorType; typedef Hyperplane<Scalar,LineType::AmbientDimAtCompileTime> HyperplaneType; VectorType p0 = VectorType::Random(dim); VectorType p1 = VectorType::Random(dim); VectorType d0 = VectorType::Random(dim).normalized(); LineType l0(p0, d0); Scalar s0 = internal::random<Scalar>(); Scalar s1 = abs(internal::random<Scalar>()); VERIFY_IS_MUCH_SMALLER_THAN( l0.distance(p0), RealScalar(1) ); VERIFY_IS_MUCH_SMALLER_THAN( l0.distance(p0+s0*d0), RealScalar(1) ); VERIFY_IS_APPROX( (l0.projection(p1)-p1).norm(), l0.distance(p1) ); VERIFY_IS_MUCH_SMALLER_THAN( l0.distance(l0.projection(p1)), RealScalar(1) ); VERIFY_IS_APPROX( Scalar(l0.distance((p0+s0*d0) + d0.unitOrthogonal() * s1)), s1 ); // casting const int Dim = LineType::AmbientDimAtCompileTime; typedef typename GetDifferentType<Scalar>::type OtherScalar; ParametrizedLine<OtherScalar,Dim> hp1f = l0.template cast<OtherScalar>(); VERIFY_IS_APPROX(hp1f.template cast<Scalar>(),l0); ParametrizedLine<Scalar,Dim> hp1d = l0.template cast<Scalar>(); VERIFY_IS_APPROX(hp1d.template cast<Scalar>(),l0); // intersections VectorType p2 = VectorType::Random(dim); VectorType n2 = VectorType::Random(dim).normalized(); HyperplaneType hp(p2,n2); Scalar t = l0.intersectionParameter(hp); VectorType pi = l0.pointAt(t); VERIFY_IS_MUCH_SMALLER_THAN(hp.signedDistance(pi), RealScalar(1)); VERIFY_IS_MUCH_SMALLER_THAN(l0.distance(pi), RealScalar(1)); VERIFY_IS_APPROX(l0.intersectionPoint(hp), pi); } template<typename Scalar> void parametrizedline_alignment() { typedef ParametrizedLine<Scalar,4,AutoAlign> Line4a; typedef ParametrizedLine<Scalar,4,DontAlign> Line4u; EIGEN_ALIGN_DEFAULT Scalar array1[8]; EIGEN_ALIGN_DEFAULT Scalar array2[8]; EIGEN_ALIGN_DEFAULT Scalar array3[8+1]; Scalar* array3u = array3+1; Line4a *p1 = ::new(reinterpret_cast<void*>(array1)) Line4a; Line4u *p2 = ::new(reinterpret_cast<void*>(array2)) Line4u; Line4u *p3 = ::new(reinterpret_cast<void*>(array3u)) Line4u; p1->origin().setRandom(); p1->direction().setRandom(); *p2 = *p1; *p3 = *p1; VERIFY_IS_APPROX(p1->origin(), p2->origin()); VERIFY_IS_APPROX(p1->origin(), p3->origin()); VERIFY_IS_APPROX(p1->direction(), p2->direction()); VERIFY_IS_APPROX(p1->direction(), p3->direction()); #if defined(EIGEN_VECTORIZE) && EIGEN_ALIGN_STATICALLY if(internal::packet_traits<Scalar>::Vectorizable && internal::packet_traits<Scalar>::size<=4) VERIFY_RAISES_ASSERT((::new(reinterpret_cast<void*>(array3u)) Line4a)); #endif } void test_geo_parametrizedline() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( parametrizedline(ParametrizedLine<float,2>()) ); CALL_SUBTEST_2( parametrizedline(ParametrizedLine<float,3>()) ); CALL_SUBTEST_2( parametrizedline_alignment<float>() ); CALL_SUBTEST_3( parametrizedline(ParametrizedLine<double,4>()) ); CALL_SUBTEST_3( parametrizedline_alignment<double>() ); CALL_SUBTEST_4( parametrizedline(ParametrizedLine<std::complex<double>,5>()) ); } } <commit_msg>Updated the geo_parametrizedline_2 test for AVX.<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> // // 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 "main.h" #include <Eigen/Geometry> #include <Eigen/LU> #include <Eigen/QR> template<typename LineType> void parametrizedline(const LineType& _line) { /* this test covers the following files: ParametrizedLine.h */ using std::abs; typedef typename LineType::Index Index; const Index dim = _line.dim(); typedef typename LineType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<Scalar, LineType::AmbientDimAtCompileTime, 1> VectorType; typedef Hyperplane<Scalar,LineType::AmbientDimAtCompileTime> HyperplaneType; VectorType p0 = VectorType::Random(dim); VectorType p1 = VectorType::Random(dim); VectorType d0 = VectorType::Random(dim).normalized(); LineType l0(p0, d0); Scalar s0 = internal::random<Scalar>(); Scalar s1 = abs(internal::random<Scalar>()); VERIFY_IS_MUCH_SMALLER_THAN( l0.distance(p0), RealScalar(1) ); VERIFY_IS_MUCH_SMALLER_THAN( l0.distance(p0+s0*d0), RealScalar(1) ); VERIFY_IS_APPROX( (l0.projection(p1)-p1).norm(), l0.distance(p1) ); VERIFY_IS_MUCH_SMALLER_THAN( l0.distance(l0.projection(p1)), RealScalar(1) ); VERIFY_IS_APPROX( Scalar(l0.distance((p0+s0*d0) + d0.unitOrthogonal() * s1)), s1 ); // casting const int Dim = LineType::AmbientDimAtCompileTime; typedef typename GetDifferentType<Scalar>::type OtherScalar; ParametrizedLine<OtherScalar,Dim> hp1f = l0.template cast<OtherScalar>(); VERIFY_IS_APPROX(hp1f.template cast<Scalar>(),l0); ParametrizedLine<Scalar,Dim> hp1d = l0.template cast<Scalar>(); VERIFY_IS_APPROX(hp1d.template cast<Scalar>(),l0); // intersections VectorType p2 = VectorType::Random(dim); VectorType n2 = VectorType::Random(dim).normalized(); HyperplaneType hp(p2,n2); Scalar t = l0.intersectionParameter(hp); VectorType pi = l0.pointAt(t); VERIFY_IS_MUCH_SMALLER_THAN(hp.signedDistance(pi), RealScalar(1)); VERIFY_IS_MUCH_SMALLER_THAN(l0.distance(pi), RealScalar(1)); VERIFY_IS_APPROX(l0.intersectionPoint(hp), pi); } template<typename Scalar> void parametrizedline_alignment() { typedef ParametrizedLine<Scalar,4,AutoAlign> Line4a; typedef ParametrizedLine<Scalar,4,DontAlign> Line4u; EIGEN_ALIGN_DEFAULT Scalar array1[16]; EIGEN_ALIGN_DEFAULT Scalar array2[16]; EIGEN_ALIGN_DEFAULT Scalar array3[16+1]; Scalar* array3u = array3+1; Line4a *p1 = ::new(reinterpret_cast<void*>(array1)) Line4a; Line4u *p2 = ::new(reinterpret_cast<void*>(array2)) Line4u; Line4u *p3 = ::new(reinterpret_cast<void*>(array3u)) Line4u; p1->origin().setRandom(); p1->direction().setRandom(); *p2 = *p1; *p3 = *p1; VERIFY_IS_APPROX(p1->origin(), p2->origin()); VERIFY_IS_APPROX(p1->origin(), p3->origin()); VERIFY_IS_APPROX(p1->direction(), p2->direction()); VERIFY_IS_APPROX(p1->direction(), p3->direction()); #if defined(EIGEN_VECTORIZE) && EIGEN_ALIGN_STATICALLY if(internal::packet_traits<Scalar>::Vectorizable && internal::packet_traits<Scalar>::size<=4) VERIFY_RAISES_ASSERT((::new(reinterpret_cast<void*>(array3u)) Line4a)); #endif } void test_geo_parametrizedline() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( parametrizedline(ParametrizedLine<float,2>()) ); CALL_SUBTEST_2( parametrizedline(ParametrizedLine<float,3>()) ); CALL_SUBTEST_2( parametrizedline_alignment<float>() ); CALL_SUBTEST_3( parametrizedline(ParametrizedLine<double,4>()) ); CALL_SUBTEST_3( parametrizedline_alignment<double>() ); CALL_SUBTEST_4( parametrizedline(ParametrizedLine<std::complex<double>,5>()) ); } } <|endoftext|>
<commit_before>#include "TableLogger.h" #include <boost/foreach.hpp> TableLogger::TableLogger() :header_space_(' ', 3) {} TableLogger::TableLogger(const std::vector<HeaderStyle> &header) :header_(header), header_space_(' ', 3) {} void TableLogger::LogTableHead() { using std::cout; cout << "Sphere Ellimination Records" << "\n"; cout << "==========================" << "\n"; cout << "Index Color Time (s) Event type" << "\n"; cout << "----- ----- -------- ----------" << "\n"; } void TableLogger::LogTableRow(std::vector<std::string> data) { static const unsigned int kIndexHeaderWidth = 5; using std::cout; BOOST_FOREACH(const std::string& s, data) { cout << center(s, kIndexHeaderWidth); cout << header_space_; cout << "\n"; } } std::string TableLogger::center(const std::string &s, std::string::size_type length) { if(s.length() > length) return s.substr(0, length); std::string result(length, ' '); int spaces = (length - s.length()) / 2; for(unsigned int i = 0; i < s.length(); ++i) result[i+spaces] = s[i]; return result; } <commit_msg>Implemented LogTableHeader<commit_after>#include "TableLogger.h" #include <boost/foreach.hpp> TableLogger::TableLogger( const std::string& title, const std::vector<HeaderStyle> &header) :title_(title), header_(header), header_space_(3, ' ') {} void TableLogger::LogTableHead() { using std::cout; cout << title_ << "\n"; BOOST_FOREACH(const HeaderStyle& h, header_) { cout << h.first << header_space_; } cout << "\n"; } void TableLogger::LogTableRow(std::vector<std::string> data) { static const unsigned int kIndexHeaderWidth = 5; using std::cout; BOOST_FOREACH(const std::string& s, data) { cout << center(s, 8); cout << header_space_; } cout << "\n"; } std::string TableLogger::center(const std::string &s, std::string::size_type length) { if(s.length() > length) return s.substr(0, length); std::string result(length, ' '); int spaces = (length - s.length()) / 2; for(unsigned int i = 0; i < s.length(); ++i) result[i+spaces] = s[i]; return result; } <|endoftext|>
<commit_before>// ============================================================================= // Authors: Radu Serban, Justin Madsen // ============================================================================= // // Base class for a vehicle wheel. // A wheel subsystem does not own a body. Instead, when attached to a suspension // subsystem, the wheel's mass properties are used to update those of the // spindle body owned by the suspension. // A concrete wheel subsystem can optionally carry its own visualization assets // and/or contact geometry (which are associated with the suspension's spindle // body). // ============================================================================= namespace chrono { } // end namespace chrono <commit_msg>Add missing comment block at top of file.<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Justin Madsen // ============================================================================= // // Base class for a vehicle wheel. // A wheel subsystem does not own a body. Instead, when attached to a suspension // subsystem, the wheel's mass properties are used to update those of the // spindle body owned by the suspension. // A concrete wheel subsystem can optionally carry its own visualization assets // and/or contact geometry (which are associated with the suspension's spindle // body). // ============================================================================= namespace chrono { } // end namespace chrono <|endoftext|>
<commit_before>#ifndef CPPUT_TESTHARNESS_HPP #define CPPUT_TESTHARNESS_HPP /////////////////////////////////////////////////////////////////////////////// /// /// \brief A light-weight and easy to use unit testing framework for C++ /// \details Header-only unit testing framework that makes unit testing easy /// and quick to set up. /// \version 0.2.0 /// \date December 2011 /// \author Tommy Back /// /// /// Simply include this header file to get started. /// /// \code /// #include <cpput/TestHarness.h> /// #include <Foo.h> /// /// TEST(Foo, some_descriptive_name) /// { /// // Arrange /// Foo foo; /// // Act /// bool result = foo.isBar(); /// // Assert /// ASSERT_TRUE(result); /// } /// \endcode /// /// In case you want to keep a single file with tests that compile to an /// executable you can also add the main function to the end of the file. /// This is simple to do with the provided macro: /// /// \code /// CPPUT_TEST_MAIN; /// \endcode /// /// For larger test suits, it's recommended to group the tests per class /// in separate files and let the compiler combine them into a single /// executable which has a main.cpp file that only has the main function /// declared. /// /// \example /// [Test_Foo.cpp] /// /// \code /// #include <cpput/TestHarness.h> /// #include <Foo.h> /// /// TEST(Foo, foo_bar_z) /// { /// ... /// \endcode /// /// [main.cpp] /// /// \code /// #include <cpput/TestHarness.h> /// /// CPPUT_TEST_MAIN; /// \endcode /// /// #include <iostream> #include <iomanip> #include <string> #include <vector> #include <sstream> #include <ctime> namespace cpput { struct Failure { Failure(const std::string& filename, std::size_t line, const std::string& message) : filename_(filename) , line_(line) , message_(message) { } friend std::ostream& operator<<(std::ostream& os, const Failure& f) { os << f.filename_ << ", line " << f.line_ << ": " << f.message_; return os; } std::string filename_; std::size_t line_; std::string message_; }; // ---------------------------------------------------------------------------- struct ResultWriter { virtual ~ResultWriter() {} virtual void startTest(const std::string& className, const std::string& name) = 0; virtual void endTest(bool success) = 0; virtual void failure(const Failure& failure) = 0; virtual int getNumberOfFailures() const = 0; }; // ---------------------------------------------------------------------------- class TextResultWriter : public ResultWriter { public: TextResultWriter() : testCount_(0) { } virtual ~TextResultWriter() { std::cout << "\n"; if (failures_.empty()) { std::cout << "All tests pass.\n"; return; } // print details of all failures std::cout << "\n"; for (std::size_t i=0; i<failures_.size(); ++i) { std::cout << failures_[i] << "\n"; } std::cout << "\n" << failures_.size() << " out of " << testCount_ << " tests failed.\n"; } virtual void startTest(const std::string&, const std::string&) { testCount_++; } virtual void endTest(bool success) { if (success) std::cout << '.'; else std::cout << 'F'; } virtual void failure(const Failure& failure) { failures_.push_back(failure); } virtual int getNumberOfFailures() const { return failures_.size(); } private: int testCount_; std::vector<Failure> failures_; }; // ---------------------------------------------------------------------------- class XmlResultWriter : public ResultWriter { public: XmlResultWriter() : startTime_(0) { std::cout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; std::cout << "<testsuite>\n"; } virtual ~XmlResultWriter() { std::cout << "</testsuite>\n"; } virtual void startTest(const std::string& className, const std::string& name) { startTime_ = std::clock(); std::cout << " <testcase classname=\"" << className << "\" name=\"" << name << "\" time=\""; } virtual void endTest(bool success) { if (success) { std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\""; std::cout << "/>\n"; } else std::cout << " </testcase>\n"; } virtual void failure(const Failure& failure) { std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\""; std::cout << ">\n" << " <failure>" << failure.message_ << " in " << failure.filename_ << ", line " << failure.line_ << "</failure>\n"; failureCount_++; } virtual int getNumberOfFailures() const { return failureCount_; } private: std::clock_t startTime_; int failureCount_; }; // ---------------------------------------------------------------------------- struct Result { Result(const std::string& testClassName, const std::string& testName, ResultWriter& out) : out_(out) , pass_(true) { out_.startTest(testClassName, testName); } ~Result() { out_.endTest(pass_); } template <typename T, typename U> void addFailure(const char* filename, std::size_t line, T expected, U actual) { pass_ = false; std::stringstream ss; ss << std::setprecision(20) << "failed comparison, expected " << expected << " got " << actual << "\n"; Failure f(filename, line, ss.str()); out_.failure(f); } void addFailure(const char* filename, std::size_t line, const char* message) { pass_ = false; Failure f(filename, line, message); out_.failure(f); } ResultWriter& out_; bool pass_; }; // ---------------------------------------------------------------------------- class Repository; class Case { friend class Repository; public: Case(const char* className, const char* name); virtual ~Case() {} void run(ResultWriter& out) { Result result(test_unit_class_name_, test_unit_name_, out); try { do_run(result); } catch (const std::exception& e) { result.addFailure(__FILE__, __LINE__, std::string("Unexpected exception: ").append(e.what()).c_str()); } catch (...) { result.addFailure(__FILE__, __LINE__, "Unspecified exception!"); } } Case* next() { return test_unit_next_; } private: virtual void do_run(Result& testResult_) = 0; private: std::string test_unit_class_name_; std::string test_unit_name_; Case* test_unit_next_; }; // ---------------------------------------------------------------------------- class Repository { public: static Repository& instance() { static Repository repo; return repo; } void add(Case* tc) { if (!cases_) { cases_ = tc; return; } // add as last Case* tmp = cases_; while (tmp->test_unit_next_) tmp = tmp->test_unit_next_; tmp->test_unit_next_ = tc; } Case* getCases() { return cases_; } private: Repository() : cases_(0) {} Repository(const Repository& other); Repository& operator=(const Repository& rhs) const; private: Case* cases_; }; inline Case::Case(const char* className, const char* name) : test_unit_class_name_(className) , test_unit_name_(name) , test_unit_next_(0) { Repository::instance().add(this); } // ---------------------------------------------------------------------------- struct Runner { static int run(ResultWriter& writer) { Case* c = Repository::instance().getCases(); while (c) { c->run(writer); c = c->next(); } return writer.getNumberOfFailures(); } private: Runner(); Runner(const Runner& other); Runner& operator=(const Runner& rhs) const; }; } // namespace cpput // Convenience macro to get main function. #define CPPUT_TEST_MAIN \ int main(int argc, char* argv[]) { \ if (argc == 2 && std::string(argv[1]) == "--xml") { \ cpput::XmlResultWriter writer; \ return ::cpput::Runner::run(writer); \ } \ cpput::TextResultWriter writer; \ return ::cpput::Runner::run(writer); \ } // ---------------------------------------------------------------------------- // Test Case Macros // ---------------------------------------------------------------------------- /// Stand-alone test case. /// #define TEST(group,name) \ class group##name##Test : public cpput::Case \ { \ public: \ group##name##Test() : cpput::Case(#group,#name) {} \ virtual ~group##name##Test() {} \ private: \ virtual void do_run(cpput::Result& testResult_); \ } group##name##TestInstance; \ inline void group##name##Test::do_run(cpput::Result& testResult_) /// Test case with fixture. /// #define TEST_F(group,name) \ class group##name##FixtureTest : public group { \ public: \ void do_run(cpput::Result& testResult_); \ }; \ class group##name##Test : public cpput::Case { \ public: \ group##name##Test() : Case(#group,#name) {} \ virtual void do_run(cpput::Result& testResult_); \ } group##name##TestInstance; \ inline void group##name##Test::do_run(cpput::Result& testResult_) { \ group##name##FixtureTest test; \ test.do_run(testResult_); \ } \ inline void group##name##FixtureTest::do_run(cpput::Result& testResult_) // ---------------------------------------------------------------------------- // Assertion Macros // ---------------------------------------------------------------------------- #define ASSERT_TRUE(expression) \ { \ if (expression) \ return; \ testResult_.addFailure(__FILE__, __LINE__, #expression); \ } #define ASSERT_FALSE(expression) ASSERT_TRUE(!(expression)) #define ASSERT_EQ(expected,actual) \ { \ if (!((expected) == (actual))) \ { \ testResult_.addFailure(__FILE__, __LINE__, expected, actual); \ return; \ } \ } #define ASSERT_NEQ(expected,actual) \ { \ if (((expected) == (actual))) \ { \ testResult_.addFailure(__FILE__, __LINE__, expected, actual); \ return; \ } \ } #define ASSERT_STREQ(expected,actual) { \ if (!(std::string(expected) == std::string(actual))) \ { \ testResult_.addFailure(__FILE__, __LINE__, expected, actual); \ return; \ } \ } #define ASSERT_NEAR(expected,actual,epsilon) \ { \ double actualTmp = actual; \ double expectedTmp = expected; \ double diff = expectedTmp - actualTmp; \ if ((diff > epsilon) || (-diff > epsilon)) \ { \ testResult_.addFailure(__FILE__, __LINE__, expectedTmp, actualTmp); \ return; \ } \ } #endif // CPPUT_TESTHARNESS_HPP <commit_msg>Replaced Runner class with non-member inline function.<commit_after>#ifndef CPPUT_TESTHARNESS_HPP #define CPPUT_TESTHARNESS_HPP /////////////////////////////////////////////////////////////////////////////// /// /// \brief A light-weight and easy to use unit testing framework for C++ /// \details Header-only unit testing framework that makes unit testing easy /// and quick to set up. /// \version 0.2.0 /// \date December 2011 /// \author Tommy Back /// /// /// Simply include this header file to get started. /// /// \code /// #include <cpput/TestHarness.h> /// #include <Foo.h> /// /// TEST(Foo, some_descriptive_name) /// { /// // Arrange /// Foo foo; /// // Act /// bool result = foo.isBar(); /// // Assert /// ASSERT_TRUE(result); /// } /// \endcode /// /// In case you want to keep a single file with tests that compile to an /// executable you can also add the main function to the end of the file. /// This is simple to do with the provided macro: /// /// \code /// CPPUT_TEST_MAIN; /// \endcode /// /// For larger test suits, it's recommended to group the tests per class /// in separate files and let the compiler combine them into a single /// executable which has a main.cpp file that only has the main function /// declared. /// /// \example /// [Test_Foo.cpp] /// /// \code /// #include <cpput/TestHarness.h> /// #include <Foo.h> /// /// TEST(Foo, foo_bar_z) /// { /// ... /// \endcode /// /// [main.cpp] /// /// \code /// #include <cpput/TestHarness.h> /// /// CPPUT_TEST_MAIN; /// \endcode /// /// #include <iostream> #include <iomanip> #include <string> #include <vector> #include <sstream> #include <ctime> namespace cpput { struct Failure { Failure(const std::string& filename, std::size_t line, const std::string& message) : filename_(filename) , line_(line) , message_(message) { } friend std::ostream& operator<<(std::ostream& os, const Failure& f) { os << f.filename_ << ", line " << f.line_ << ": " << f.message_; return os; } std::string filename_; std::size_t line_; std::string message_; }; // ---------------------------------------------------------------------------- struct ResultWriter { virtual ~ResultWriter() {} virtual void startTest(const std::string& className, const std::string& name) = 0; virtual void endTest(bool success) = 0; virtual void failure(const Failure& failure) = 0; virtual int getNumberOfFailures() const = 0; }; // ---------------------------------------------------------------------------- class TextResultWriter : public ResultWriter { public: TextResultWriter() : testCount_(0) { } virtual ~TextResultWriter() { std::cout << "\n"; if (failures_.empty()) { std::cout << "All tests pass.\n"; return; } // print details of all failures std::cout << "\n"; for (std::size_t i=0; i<failures_.size(); ++i) { std::cout << failures_[i] << "\n"; } std::cout << "\n" << failures_.size() << " out of " << testCount_ << " tests failed.\n"; } virtual void startTest(const std::string&, const std::string&) { testCount_++; } virtual void endTest(bool success) { if (success) std::cout << '.'; else std::cout << 'F'; } virtual void failure(const Failure& failure) { failures_.push_back(failure); } virtual int getNumberOfFailures() const { return failures_.size(); } private: int testCount_; std::vector<Failure> failures_; }; // ---------------------------------------------------------------------------- class XmlResultWriter : public ResultWriter { public: XmlResultWriter() : startTime_(0) { std::cout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; std::cout << "<testsuite>\n"; } virtual ~XmlResultWriter() { std::cout << "</testsuite>\n"; } virtual void startTest(const std::string& className, const std::string& name) { startTime_ = std::clock(); std::cout << " <testcase classname=\"" << className << "\" name=\"" << name << "\" time=\""; } virtual void endTest(bool success) { if (success) { std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\""; std::cout << "/>\n"; } else std::cout << " </testcase>\n"; } virtual void failure(const Failure& failure) { std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\""; std::cout << ">\n" << " <failure>" << failure.message_ << " in " << failure.filename_ << ", line " << failure.line_ << "</failure>\n"; failureCount_++; } virtual int getNumberOfFailures() const { return failureCount_; } private: std::clock_t startTime_; int failureCount_; }; // ---------------------------------------------------------------------------- struct Result { Result(const std::string& testClassName, const std::string& testName, ResultWriter& out) : out_(out) , pass_(true) { out_.startTest(testClassName, testName); } ~Result() { out_.endTest(pass_); } template <typename T, typename U> void addFailure(const char* filename, std::size_t line, T expected, U actual) { pass_ = false; std::stringstream ss; ss << std::setprecision(20) << "failed comparison, expected " << expected << " got " << actual << "\n"; Failure f(filename, line, ss.str()); out_.failure(f); } void addFailure(const char* filename, std::size_t line, const char* message) { pass_ = false; Failure f(filename, line, message); out_.failure(f); } ResultWriter& out_; bool pass_; }; // ---------------------------------------------------------------------------- class Repository; class Case { friend class Repository; public: Case(const char* className, const char* name); virtual ~Case() {} void run(ResultWriter& out) { Result result(test_unit_class_name_, test_unit_name_, out); try { do_run(result); } catch (const std::exception& e) { result.addFailure(__FILE__, __LINE__, std::string("Unexpected exception: ").append(e.what()).c_str()); } catch (...) { result.addFailure(__FILE__, __LINE__, "Unspecified exception!"); } } Case* next() { return test_unit_next_; } private: virtual void do_run(Result& testResult_) = 0; private: std::string test_unit_class_name_; std::string test_unit_name_; Case* test_unit_next_; }; // ---------------------------------------------------------------------------- class Repository { public: static Repository& instance() { static Repository repo; return repo; } void add(Case* tc) { if (!cases_) { cases_ = tc; return; } // add as last Case* tmp = cases_; while (tmp->test_unit_next_) tmp = tmp->test_unit_next_; tmp->test_unit_next_ = tc; } Case* getCases() { return cases_; } private: Repository() : cases_(0) {} Repository(const Repository& other); Repository& operator=(const Repository& rhs) const; private: Case* cases_; }; inline Case::Case(const char* className, const char* name) : test_unit_class_name_(className) , test_unit_name_(name) , test_unit_next_(0) { Repository::instance().add(this); } // ---------------------------------------------------------------------------- inline int runAllTests(ResultWriter& writer) { Case* c = Repository::instance().getCases(); while (c) { c->run(writer); c = c->next(); } return writer.getNumberOfFailures(); } } // namespace cpput // Convenience macro to get main function. #define CPPUT_TEST_MAIN \ int main(int argc, char* argv[]) { \ if (argc == 2 && std::string(argv[1]) == "--xml") { \ cpput::XmlResultWriter writer; \ return ::cpput::runAllTests(writer); \ } \ cpput::TextResultWriter writer; \ return ::cpput::runAllTests(writer); \ } // ---------------------------------------------------------------------------- // Test Case Macros // ---------------------------------------------------------------------------- /// Stand-alone test case. /// #define TEST(group,name) \ class group##name##Test : public cpput::Case \ { \ public: \ group##name##Test() : cpput::Case(#group,#name) {} \ virtual ~group##name##Test() {} \ private: \ virtual void do_run(cpput::Result& testResult_); \ } group##name##TestInstance; \ inline void group##name##Test::do_run(cpput::Result& testResult_) /// Test case with fixture. /// #define TEST_F(group,name) \ class group##name##FixtureTest : public group { \ public: \ void do_run(cpput::Result& testResult_); \ }; \ class group##name##Test : public cpput::Case { \ public: \ group##name##Test() : Case(#group,#name) {} \ virtual void do_run(cpput::Result& testResult_); \ } group##name##TestInstance; \ inline void group##name##Test::do_run(cpput::Result& testResult_) { \ group##name##FixtureTest test; \ test.do_run(testResult_); \ } \ inline void group##name##FixtureTest::do_run(cpput::Result& testResult_) // ---------------------------------------------------------------------------- // Assertion Macros // ---------------------------------------------------------------------------- #define ASSERT_TRUE(expression) \ { \ if (expression) \ return; \ testResult_.addFailure(__FILE__, __LINE__, #expression); \ } #define ASSERT_FALSE(expression) ASSERT_TRUE(!(expression)) #define ASSERT_EQ(expected,actual) \ { \ if (!((expected) == (actual))) \ { \ testResult_.addFailure(__FILE__, __LINE__, expected, actual); \ return; \ } \ } #define ASSERT_NEQ(expected,actual) \ { \ if (((expected) == (actual))) \ { \ testResult_.addFailure(__FILE__, __LINE__, expected, actual); \ return; \ } \ } #define ASSERT_STREQ(expected,actual) { \ if (!(std::string(expected) == std::string(actual))) \ { \ testResult_.addFailure(__FILE__, __LINE__, expected, actual); \ return; \ } \ } #define ASSERT_NEAR(expected,actual,epsilon) \ { \ double actualTmp = actual; \ double expectedTmp = expected; \ double diff = expectedTmp - actualTmp; \ if ((diff > epsilon) || (-diff > epsilon)) \ { \ testResult_.addFailure(__FILE__, __LINE__, expectedTmp, actualTmp); \ return; \ } \ } #endif // CPPUT_TESTHARNESS_HPP <|endoftext|>
<commit_before>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_TEST_LINEARELLIPTIC_SWIPDG_HH #define DUNE_HDD_TEST_LINEARELLIPTIC_SWIPDG_HH #include <algorithm> #if HAVE_ALUGRID # include <dune/grid/alugrid.hh> #endif #include <dune/stuff/common/exceptions.hh> #include <dune/gdt/products/l2.hh> #include <dune/gdt/products/h1.hh> #include <dune/gdt/playground/products/elliptic.hh> #include <dune/hdd/linearelliptic/discretizations/swipdg.hh> #include <dune/hdd/playground/linearelliptic/testcases/ESV2007.hh> #include <dune/hdd/playground/linearelliptic/testcases/OS2014.hh> #include "linearelliptic.hh" namespace Dune { namespace HDD { namespace LinearElliptic { namespace Tests { namespace internal { template< class TestCaseType, int polOrder, GDT::ChooseSpaceBackend space_backend, Stuff::LA::ChooseBackend la_backend > class DiscretizationSWIPDG { typedef typename TestCaseType::GridType GridType; typedef typename TestCaseType::RangeFieldType RangeFieldType; static const unsigned int dimRange = TestCaseType::dimRange; public: typedef Discretizations::SWIPDG < GridType, Stuff::Grid::ChooseLayer::level, RangeFieldType, dimRange, polOrder, space_backend, la_backend > Type; }; // class DiscretizationSWIPDG } // namespace internal template< class TestCaseType, int polOrder, GDT::ChooseSpaceBackend space_backend, Stuff::LA::ChooseBackend la_backend > class EocStudySWIPDG : public EocStudyBase< TestCaseType, typename internal::DiscretizationSWIPDG< TestCaseType, polOrder, space_backend, la_backend >::Type > { typedef EocStudyBase< TestCaseType, typename internal::DiscretizationSWIPDG< TestCaseType, polOrder, space_backend, la_backend >::Type > BaseType; typedef EocStudySWIPDG< TestCaseType, polOrder, space_backend, la_backend > ThisType; typedef typename BaseType::DiscretizationType DiscretizationType; typedef typename BaseType::GridViewType GridViewType; typedef typename BaseType::FunctionType FunctionType; typedef typename BaseType::VectorType VectorType; public: EocStudySWIPDG(const TestCaseType& test_case, const std::vector< std::string > only_these_norms = {}) : BaseType(test_case, only_these_norms) {} virtual ~EocStudySWIPDG() {} virtual std::string identifier() const DS_OVERRIDE DS_FINAL { return DiscretizationType::static_id() + " (polorder " + Stuff::Common::toString(polOrder) + ")"; } virtual size_t expected_rate(const std::string type) const DS_OVERRIDE DS_FINAL { if (type == "L2") return polOrder + 1; else if (type == "H1_semi") return polOrder; else if (type == "energy") return polOrder; else if (type == "eta_NC_ESV2007") return polOrder; else if (type == "eta_R_ESV2007") return polOrder + 1; else if (type == "eta_DF_ESV2007") return polOrder; else if (type == "eta_ESV2007") return polOrder; else if (type == "eff_ESV2007") return 0; else if (type == "eta_ESV2007_alt") return polOrder; else if (type == "eff_ESV2007_alt") return 0; else DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!"); } // ... expected_rate(...) virtual std::vector< double > expected_results(const std::string type) const DS_OVERRIDE DS_FINAL { #if HAVE_ALUGRID if (std::is_same< TestCaseType, TestCases::ESV2007< ALUConformGrid< 2, 2 > > >::value || std::is_same< TestCaseType, TestCases::ESV2007< ALUGrid< 2, 2, simplex, conforming > > >::value) { if (polOrder == 1) { if (type == "L2") return {1.84e-02, 4.54e-03, 1.13e-03, 2.79e-04}; else if (type == "H1_semi") return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02}; else if (type == "energy") return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02}; else if (type == "eta_NC_ESV2007") return {1.90e-1, 9.73e-2, 4.90e-2, 2.46e-2}; else if (type == "eta_R_ESV2007") return {7.24e-2, 1.83e-2, 4.55e-3, 1.15e-3}; else if (type == "eta_DF_ESV2007") { // these are the values reported in the ESV2007 preprint: // return {3.39e-1, 1.70e-1, 8.40e-2, 4.19e-2}; // but we do not want the test to fail each time, so we expect these: return {3.56e-1, 1.77e-1, 8.74e-2, 4.36e-2}; } else if (type == "eta_ESV2007") return {4.50e-01, 2.08e-01, 9.92e-02, 4.86e-02}; else if (type == "eff_ESV2007") { // these are the values reported in the ESV2007 preprint: // return {1.21, 1.21, 1.21, 1.21}; // but we do not want the test to fail each time, so we expect these: return {1.38, 1.29, 1.24, 1.22}; } else if (type == "eta_ESV2007_alt") return {5.94e-01, 2.74e-01, 1.32e-01, 6.43e-02}; else if (type == "eff_ESV2007_alt") return {1.82, 1.70, 1.64, 1.61}; else DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!"); } else DUNE_THROW(NotImplemented, "Please record the expected results for this polOrder!"); } else if (std::is_same< TestCaseType, TestCases::OS2014< ALUConformGrid< 2, 2 > > >::value || std::is_same< TestCaseType, TestCases::OS2014< ALUGrid< 2, 2, simplex, conforming > > >::value) { if (polOrder == 1) { if (type == "energy") return {4.75e-01, 2.63e-01, 1.28e-01, 5.62e-02}; else if (type == "eta_NC") return {2.39e-01, 1.43e-01, 6.83e-02, 3.14e-02}; else if (type == "eta_R") return {8.19e-02, 1.99e-02, 4.84e-03, 1.20e-03}; else if (type == "eta_DF") { return {6.35e-01, 3.62e-01, 1.88e-01, 9.18e-02}; } else if (type == "eta") return {7.51e-01, 4.06e-01, 2.01e-01, 9.80e-02}; else DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!"); } else DUNE_THROW(NotImplemented, "Please record the expected results for this polOrder!"); } else #endif // HAVE_ALUGRID DUNE_THROW(NotImplemented, "Please record the expected results for this TestCaseType/GridType combination!"); } // ... expected_results(...) private: virtual std::vector< std::string > available_norms_() const DS_OVERRIDE DS_FINAL { return { "L2" , "H1_semi" , "energy" }; } // ... available_norms_(...) virtual double compute_norm_(const GridViewType& grid_view, const FunctionType& function, const std::string type) const DS_OVERRIDE DS_FINAL { using namespace GDT; typedef typename TestCaseType::ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType; typedef typename TestCaseType::ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType; if (type == "L2") { return Products::L2< GridViewType >(grid_view).induced_norm(function); } else if (type == "H1_semi") { return Products::H1SemiGeneric< GridViewType >(grid_view).induced_norm(function); } else if (type == "energy") { const auto& diffusion_factor = *(this->test_case_.problem().diffusion_factor()); assert(!diffusion_factor.parametric()); assert(diffusion_factor.has_affine_part()); const auto& diffusion_tensor = *(this->test_case_.problem().diffusion_tensor()); assert(!diffusion_tensor.parametric()); assert(diffusion_tensor.has_affine_part()); Products::Elliptic< DiffusionFactorType, GridViewType, double, DiffusionTensorType > elliptic_product(*diffusion_factor.affine_part(), *diffusion_tensor.affine_part(), grid_view); return elliptic_product.induced_norm(function); } else DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!"); } // ... compute_norm_(...) virtual std::vector< std::string > available_estimators_() const DS_OVERRIDE DS_FINAL { auto ret = DiscretizationType::available_estimators(); if (std::find(ret.begin(), ret.end(), "eta_ESV2007") != ret.end()) ret.push_back("eff_ESV2007"); if (std::find(ret.begin(), ret.end(), "eta_ESV2007_alt") != ret.end()) ret.push_back("eff_ESV2007_alt"); return ret; } virtual double estimate_(const VectorType& vector, const std::string type) const DS_OVERRIDE DS_FINAL { if (type == "eff_ESV2007") return estimate_(vector, "eta_ESV2007") / const_cast< ThisType& >(*this).current_error_norm("energy"); else if (type == "eff_ESV2007_alt") return estimate_(vector, "eta_ESV2007_alt") / const_cast< ThisType& >(*this).current_error_norm("energy"); else { assert(this->current_discretization_); return this->current_discretization_->estimate(vector, type); } } // ... estimate_(...) }; // class EocStudySWIPDG } // namespace Tests } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_TEST_LINEARELLIPTIC_SWIPDG_HH <commit_msg>[test.linearelliptic-swipdg] whitespace<commit_after>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_TEST_LINEARELLIPTIC_SWIPDG_HH #define DUNE_HDD_TEST_LINEARELLIPTIC_SWIPDG_HH #include <algorithm> #if HAVE_ALUGRID # include <dune/grid/alugrid.hh> #endif #include <dune/stuff/common/exceptions.hh> #include <dune/gdt/products/l2.hh> #include <dune/gdt/products/h1.hh> #include <dune/gdt/playground/products/elliptic.hh> #include <dune/hdd/linearelliptic/discretizations/swipdg.hh> #include <dune/hdd/playground/linearelliptic/testcases/ESV2007.hh> #include <dune/hdd/playground/linearelliptic/testcases/OS2014.hh> #include "linearelliptic.hh" namespace Dune { namespace HDD { namespace LinearElliptic { namespace Tests { namespace internal { template< class TestCaseType, int polOrder, GDT::ChooseSpaceBackend space_backend, Stuff::LA::ChooseBackend la_backend > class DiscretizationSWIPDG { typedef typename TestCaseType::GridType GridType; typedef typename TestCaseType::RangeFieldType RangeFieldType; static const unsigned int dimRange = TestCaseType::dimRange; public: typedef Discretizations::SWIPDG < GridType, Stuff::Grid::ChooseLayer::level, RangeFieldType, dimRange, polOrder, space_backend, la_backend > Type; }; // class DiscretizationSWIPDG } // namespace internal template< class TestCaseType, int polOrder, GDT::ChooseSpaceBackend space_backend, Stuff::LA::ChooseBackend la_backend > class EocStudySWIPDG : public EocStudyBase< TestCaseType, typename internal::DiscretizationSWIPDG< TestCaseType, polOrder, space_backend, la_backend >::Type > { typedef EocStudyBase< TestCaseType, typename internal::DiscretizationSWIPDG< TestCaseType, polOrder, space_backend, la_backend >::Type > BaseType; typedef EocStudySWIPDG< TestCaseType, polOrder, space_backend, la_backend > ThisType; typedef typename BaseType::DiscretizationType DiscretizationType; typedef typename BaseType::GridViewType GridViewType; typedef typename BaseType::FunctionType FunctionType; typedef typename BaseType::VectorType VectorType; public: EocStudySWIPDG(const TestCaseType& test_case, const std::vector< std::string > only_these_norms = {}) : BaseType(test_case, only_these_norms) {} virtual ~EocStudySWIPDG() {} virtual std::string identifier() const DS_OVERRIDE DS_FINAL { return DiscretizationType::static_id() + " (polorder " + Stuff::Common::toString(polOrder) + ")"; } virtual size_t expected_rate(const std::string type) const DS_OVERRIDE DS_FINAL { if (type == "L2") return polOrder + 1; else if (type == "H1_semi") return polOrder; else if (type == "energy") return polOrder; else if (type == "eta_NC_ESV2007") return polOrder; else if (type == "eta_R_ESV2007") return polOrder + 1; else if (type == "eta_DF_ESV2007") return polOrder; else if (type == "eta_ESV2007") return polOrder; else if (type == "eff_ESV2007") return 0; else if (type == "eta_ESV2007_alt") return polOrder; else if (type == "eff_ESV2007_alt") return 0; else DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!"); } // ... expected_rate(...) virtual std::vector< double > expected_results(const std::string type) const DS_OVERRIDE DS_FINAL { #if HAVE_ALUGRID if (std::is_same< TestCaseType, TestCases::ESV2007< ALUConformGrid< 2, 2 > > >::value || std::is_same< TestCaseType, TestCases::ESV2007< ALUGrid< 2, 2, simplex, conforming > > >::value) { if (polOrder == 1) { if (type == "L2") return {1.84e-02, 4.54e-03, 1.13e-03, 2.79e-04}; else if (type == "H1_semi") return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02}; else if (type == "energy") return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02}; else if (type == "eta_NC_ESV2007") return {1.90e-1, 9.73e-2, 4.90e-2, 2.46e-2}; else if (type == "eta_R_ESV2007") return {7.24e-2, 1.83e-2, 4.55e-3, 1.15e-3}; else if (type == "eta_DF_ESV2007") { // these are the values reported in the ESV2007 preprint: // return {3.39e-1, 1.70e-1, 8.40e-2, 4.19e-2}; // but we do not want the test to fail each time, so we expect these: return {3.56e-1, 1.77e-1, 8.74e-2, 4.36e-2}; } else if (type == "eta_ESV2007") return {4.50e-01, 2.08e-01, 9.92e-02, 4.86e-02}; else if (type == "eff_ESV2007") { // these are the values reported in the ESV2007 preprint: // return {1.21, 1.21, 1.21, 1.21}; // but we do not want the test to fail each time, so we expect these: return {1.38, 1.29, 1.24, 1.22}; } else if (type == "eta_ESV2007_alt") return {5.94e-01, 2.74e-01, 1.32e-01, 6.43e-02}; else if (type == "eff_ESV2007_alt") return {1.82, 1.70, 1.64, 1.61}; else DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!"); } else DUNE_THROW(NotImplemented, "Please record the expected results for this polOrder!"); } else if (std::is_same< TestCaseType, TestCases::OS2014< ALUConformGrid< 2, 2 > > >::value || std::is_same< TestCaseType, TestCases::OS2014< ALUGrid< 2, 2, simplex, conforming > > >::value) { if (polOrder == 1) { if (type == "energy") return {4.75e-01, 2.63e-01, 1.28e-01, 5.62e-02}; else if (type == "eta_NC") return {2.39e-01, 1.43e-01, 6.83e-02, 3.14e-02}; else if (type == "eta_R") return {8.19e-02, 1.99e-02, 4.84e-03, 1.20e-03}; else if (type == "eta_DF") { return {6.35e-01, 3.62e-01, 1.88e-01, 9.18e-02}; } else if (type == "eta") return {7.51e-01, 4.06e-01, 2.01e-01, 9.80e-02}; else DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!"); } else DUNE_THROW(NotImplemented, "Please record the expected results for this polOrder!"); } else #endif // HAVE_ALUGRID DUNE_THROW(NotImplemented, "Please record the expected results for this TestCaseType/GridType combination!"); } // ... expected_results(...) private: virtual std::vector< std::string > available_norms_() const DS_OVERRIDE DS_FINAL { return {"L2", "H1_semi", "energy"}; } virtual double compute_norm_(const GridViewType& grid_view, const FunctionType& function, const std::string type) const DS_OVERRIDE DS_FINAL { using namespace GDT; typedef typename TestCaseType::ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType; typedef typename TestCaseType::ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType; if (type == "L2") { return Products::L2< GridViewType >(grid_view).induced_norm(function); } else if (type == "H1_semi") { return Products::H1SemiGeneric< GridViewType >(grid_view).induced_norm(function); } else if (type == "energy") { const auto& diffusion_factor = *(this->test_case_.problem().diffusion_factor()); assert(!diffusion_factor.parametric()); assert(diffusion_factor.has_affine_part()); const auto& diffusion_tensor = *(this->test_case_.problem().diffusion_tensor()); assert(!diffusion_tensor.parametric()); assert(diffusion_tensor.has_affine_part()); Products::Elliptic< DiffusionFactorType, GridViewType, double, DiffusionTensorType > elliptic_product(*diffusion_factor.affine_part(), *diffusion_tensor.affine_part(), grid_view); return elliptic_product.induced_norm(function); } else DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!"); } // ... compute_norm_(...) virtual std::vector< std::string > available_estimators_() const DS_OVERRIDE DS_FINAL { auto ret = DiscretizationType::available_estimators(); if (std::find(ret.begin(), ret.end(), "eta_ESV2007") != ret.end()) ret.push_back("eff_ESV2007"); if (std::find(ret.begin(), ret.end(), "eta_ESV2007_alt") != ret.end()) ret.push_back("eff_ESV2007_alt"); return ret; } virtual double estimate_(const VectorType& vector, const std::string type) const DS_OVERRIDE DS_FINAL { if (type == "eff_ESV2007") return estimate_(vector, "eta_ESV2007") / const_cast< ThisType& >(*this).current_error_norm("energy"); else if (type == "eff_ESV2007_alt") return estimate_(vector, "eta_ESV2007_alt") / const_cast< ThisType& >(*this).current_error_norm("energy"); else { assert(this->current_discretization_); return this->current_discretization_->estimate(vector, type); } } // ... estimate_(...) }; // class EocStudySWIPDG } // namespace Tests } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_TEST_LINEARELLIPTIC_SWIPDG_HH <|endoftext|>
<commit_before>#include "extensions/openpower-pels/data_interface.hpp" #include "extensions/openpower-pels/host_interface.hpp" #include <fcntl.h> #include <filesystem> #include <sdeventplus/source/io.hpp> #include <gmock/gmock.h> namespace openpower { namespace pels { class MockDataInterface : public DataInterfaceBase { public: MockDataInterface() { } MOCK_METHOD(std::string, getMachineTypeModel, (), (const override)); MOCK_METHOD(std::string, getMachineSerialNumber, (), (const override)); MOCK_METHOD(std::string, getServerFWVersion, (), (const override)); MOCK_METHOD(std::string, getBMCFWVersion, (), (const override)); MOCK_METHOD(std::string, getBMCFWVersionID, (), (const override)); void changeHostState(bool newState) { setHostState(newState); } void setHMCManaged(bool managed) { _hmcManaged = managed; } }; /** * @brief The mock HostInterface class * * This replaces the PLDM calls with a FIFO for the asynchronous * responses. */ class MockHostInterface : public HostInterface { public: /** * @brief Constructor * * @param[in] event - The sd_event object * @param[in] dataIface - The DataInterface class */ MockHostInterface(sd_event* event, DataInterfaceBase& dataIface) : HostInterface(event, dataIface) { char templ[] = "/tmp/cmdfifoXXXXXX"; std::filesystem::path dir = mkdtemp(templ); _fifo = dir / "fifo"; } /** * @brief Destructor */ virtual ~MockHostInterface() { std::filesystem::remove_all(_fifo.parent_path()); } MOCK_METHOD(CmdStatus, sendNewLogCmd, (uint32_t, uint32_t), (override)); /** * @brief Cancels waiting for a command response */ virtual void cancelCmd() override { _inProgress = false; _source = nullptr; } /** * @brief Returns the amount of time to wait before retrying after * a failed send command. * * @return milliseconds - The amount of time to wait */ virtual std::chrono::milliseconds getSendRetryDelay() const override { return std::chrono::milliseconds(2); } /** * @brief Returns the amount of time to wait before retrying after * a command receive. * * @return milliseconds - The amount of time to wait */ virtual std::chrono::milliseconds getReceiveRetryDelay() const override { return std::chrono::milliseconds(2); } /** * @brief Returns the amount of time to wait before retrying if the * host firmware's PEL storage was full and it can't store * any more logs until it is freed up somehow. * * @return milliseconds - The amount of time to wait */ virtual std::chrono::milliseconds getHostFullRetryDelay() const override { return std::chrono::milliseconds(20); } /** * @brief Returns the number of commands processed */ size_t numCmdsProcessed() const { return _cmdsProcessed; } /** * @brief Writes the data passed in to the FIFO * * @param[in] hostResponse - use a 0 to indicate success * * @return CmdStatus - success or failure */ CmdStatus send(uint8_t hostResponse) { // Create a FIFO once. if (!std::filesystem::exists(_fifo)) { if (mkfifo(_fifo.c_str(), 0622)) { ADD_FAILURE() << "Failed mkfifo " << _fifo << strerror(errno); exit(-1); } } // Open it and register the reponse callback to // be used on FD activity. int fd = open(_fifo.c_str(), O_NONBLOCK | O_RDWR); EXPECT_TRUE(fd >= 0) << "Unable to open FIFO"; auto callback = [this](sdeventplus::source::IO& source, int fd, uint32_t events) { this->receive(source, fd, events); }; try { _source = std::make_unique<sdeventplus::source::IO>( _event, fd, EPOLLIN, std::bind(callback, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } catch (std::exception& e) { ADD_FAILURE() << "Event exception: " << e.what(); close(fd); return CmdStatus::failure; } // Write the fake host reponse to the FIFO auto bytesWritten = write(fd, &hostResponse, sizeof(hostResponse)); EXPECT_EQ(bytesWritten, sizeof(hostResponse)); _inProgress = true; return CmdStatus::success; } protected: /** * @brief Reads the data written to the fifo and then calls * the subscriber's callback. * * Nonzero data indicates a command failure (for testing bad path). * * @param[in] source - The event source object * @param[in] fd - The file descriptor used * @param[in] events - The event bits */ void receive(sdeventplus::source::IO& source, int fd, uint32_t events) override { if (!(events & EPOLLIN)) { return; } _inProgress = false; int newFD = open(_fifo.c_str(), O_NONBLOCK | O_RDONLY); ASSERT_TRUE(newFD >= 0) << "Failed to open FIFO"; // Read the host success/failure response from the FIFO. uint8_t data; auto bytesRead = read(newFD, &data, sizeof(data)); EXPECT_EQ(bytesRead, sizeof(data)); close(newFD); ResponseStatus status = ResponseStatus::success; if (data != 0) { status = ResponseStatus::failure; } if (_responseFunc) { (*_responseFunc)(status); } // Keep account of the number of commands responses for testing. _cmdsProcessed++; } private: /** * @brief The event source for the fifo */ std::unique_ptr<sdeventplus::source::IO> _source; /** * @brief the path to the fifo */ std::filesystem::path _fifo; /** * @brief The number of commands processed */ size_t _cmdsProcessed = 0; }; } // namespace pels } // namespace openpower <commit_msg>PEL: Increase host full timeout val in test<commit_after>#include "extensions/openpower-pels/data_interface.hpp" #include "extensions/openpower-pels/host_interface.hpp" #include <fcntl.h> #include <filesystem> #include <sdeventplus/source/io.hpp> #include <gmock/gmock.h> namespace openpower { namespace pels { class MockDataInterface : public DataInterfaceBase { public: MockDataInterface() { } MOCK_METHOD(std::string, getMachineTypeModel, (), (const override)); MOCK_METHOD(std::string, getMachineSerialNumber, (), (const override)); MOCK_METHOD(std::string, getServerFWVersion, (), (const override)); MOCK_METHOD(std::string, getBMCFWVersion, (), (const override)); MOCK_METHOD(std::string, getBMCFWVersionID, (), (const override)); void changeHostState(bool newState) { setHostState(newState); } void setHMCManaged(bool managed) { _hmcManaged = managed; } }; /** * @brief The mock HostInterface class * * This replaces the PLDM calls with a FIFO for the asynchronous * responses. */ class MockHostInterface : public HostInterface { public: /** * @brief Constructor * * @param[in] event - The sd_event object * @param[in] dataIface - The DataInterface class */ MockHostInterface(sd_event* event, DataInterfaceBase& dataIface) : HostInterface(event, dataIface) { char templ[] = "/tmp/cmdfifoXXXXXX"; std::filesystem::path dir = mkdtemp(templ); _fifo = dir / "fifo"; } /** * @brief Destructor */ virtual ~MockHostInterface() { std::filesystem::remove_all(_fifo.parent_path()); } MOCK_METHOD(CmdStatus, sendNewLogCmd, (uint32_t, uint32_t), (override)); /** * @brief Cancels waiting for a command response */ virtual void cancelCmd() override { _inProgress = false; _source = nullptr; } /** * @brief Returns the amount of time to wait before retrying after * a failed send command. * * @return milliseconds - The amount of time to wait */ virtual std::chrono::milliseconds getSendRetryDelay() const override { return std::chrono::milliseconds(2); } /** * @brief Returns the amount of time to wait before retrying after * a command receive. * * @return milliseconds - The amount of time to wait */ virtual std::chrono::milliseconds getReceiveRetryDelay() const override { return std::chrono::milliseconds(2); } /** * @brief Returns the amount of time to wait before retrying if the * host firmware's PEL storage was full and it can't store * any more logs until it is freed up somehow. * * @return milliseconds - The amount of time to wait */ virtual std::chrono::milliseconds getHostFullRetryDelay() const override { return std::chrono::milliseconds(400); } /** * @brief Returns the number of commands processed */ size_t numCmdsProcessed() const { return _cmdsProcessed; } /** * @brief Writes the data passed in to the FIFO * * @param[in] hostResponse - use a 0 to indicate success * * @return CmdStatus - success or failure */ CmdStatus send(uint8_t hostResponse) { // Create a FIFO once. if (!std::filesystem::exists(_fifo)) { if (mkfifo(_fifo.c_str(), 0622)) { ADD_FAILURE() << "Failed mkfifo " << _fifo << strerror(errno); exit(-1); } } // Open it and register the reponse callback to // be used on FD activity. int fd = open(_fifo.c_str(), O_NONBLOCK | O_RDWR); EXPECT_TRUE(fd >= 0) << "Unable to open FIFO"; auto callback = [this](sdeventplus::source::IO& source, int fd, uint32_t events) { this->receive(source, fd, events); }; try { _source = std::make_unique<sdeventplus::source::IO>( _event, fd, EPOLLIN, std::bind(callback, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } catch (std::exception& e) { ADD_FAILURE() << "Event exception: " << e.what(); close(fd); return CmdStatus::failure; } // Write the fake host reponse to the FIFO auto bytesWritten = write(fd, &hostResponse, sizeof(hostResponse)); EXPECT_EQ(bytesWritten, sizeof(hostResponse)); _inProgress = true; return CmdStatus::success; } protected: /** * @brief Reads the data written to the fifo and then calls * the subscriber's callback. * * Nonzero data indicates a command failure (for testing bad path). * * @param[in] source - The event source object * @param[in] fd - The file descriptor used * @param[in] events - The event bits */ void receive(sdeventplus::source::IO& source, int fd, uint32_t events) override { if (!(events & EPOLLIN)) { return; } _inProgress = false; int newFD = open(_fifo.c_str(), O_NONBLOCK | O_RDONLY); ASSERT_TRUE(newFD >= 0) << "Failed to open FIFO"; // Read the host success/failure response from the FIFO. uint8_t data; auto bytesRead = read(newFD, &data, sizeof(data)); EXPECT_EQ(bytesRead, sizeof(data)); close(newFD); ResponseStatus status = ResponseStatus::success; if (data != 0) { status = ResponseStatus::failure; } if (_responseFunc) { (*_responseFunc)(status); } // Keep account of the number of commands responses for testing. _cmdsProcessed++; } private: /** * @brief The event source for the fifo */ std::unique_ptr<sdeventplus::source::IO> _source; /** * @brief the path to the fifo */ std::filesystem::path _fifo; /** * @brief The number of commands processed */ size_t _cmdsProcessed = 0; }; } // namespace pels } // namespace openpower <|endoftext|>
<commit_before>#include <functional> #include <future> #include <unordered_map> #include "kernel.h" #include "raster.h" #include "itemdomain.h" #include "thematicitem.h" #include "symboltable.h" #include "ilwisoperation.h" #include "classification/sampleset.h" #include "classifier.h" #include "rasterclassification.h" using namespace Ilwis; using namespace RasterOperations; RasterClassification::RasterClassification() { } RasterClassification::RasterClassification(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr) { } bool RasterClassification::execute(ExecutionContext *ctx, SymbolTable &symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx,symTable)) != sPREPARED) return false; PixelIterator iterIn(_sampleSet.sampleRasterSet()); iterIn.setFlow(PixelIterator::fZXY); PixelIterator iterOut(_outputRaster); _classifier->classify(iterIn, iterOut); return true; } Ilwis::OperationImplementation::State RasterClassification::prepare(ExecutionContext *, const SymbolTable &sym){ QString rasterSetName = _expression.parm(0).value(); IRasterCoverage rcSet; if (!rcSet.prepare(rasterSetName)) { ERROR2(ERR_COULD_NOT_LOAD_2,rasterSetName,""); return sPREPAREFAILED; } QString domain = _expression.parm(1).value(); IThematicDomain themes; if ( !themes.prepare(domain)){ ERROR2(ERR_COULD_NOT_LOAD_2,domain,""); return sPREPAREFAILED; } QString trainingsRaster = _expression.parm(2).value(); IRasterCoverage rcTraining; if (!rcTraining.prepare(trainingsRaster, itRASTER)) { ERROR2(ERR_COULD_NOT_LOAD_2,trainingsRaster,""); return sPREPAREFAILED; } _sampleSet = SampleSet(rcSet, themes, rcTraining); _sampleSet.prepare(); QString outputName = _expression.parm(0,false).value(); _outputRaster = OperationHelperRaster::initialize(_sampleSet.sampleRasterSet(),itRASTER, itCOORDSYSTEM | itGEODETICDATUM | itGEOREF); if ( !_outputRaster.isValid()) { ERROR1(ERR_NO_INITIALIZED_1, "output rastercoverage"); return sPREPAREFAILED; } _outputRaster->datadef().domain(_sampleSet.thematicDomain()); _outputRaster->size(_sampleSet.sampleRasterSet()->size().twod()); if ( outputName!= sUNDEF) _outputRaster->name(outputName); return sPREPARED; } int RasterClassification::fillOperationMetadata(OperationResource &operation) { operation.addInParameter(0,itRASTER , TR("Multiband raster"),TR("Multi band raster to be classified")); operation.addInParameter(1,itITEMDOMAIN , TR("Thematic domain"),TR("Domain of the classified map")); operation.addInParameter(2,itRASTER , TR("Training set"),TR("Raster containing trainingset(s) of pixels")); return 3; } //------------------------------------------------------- REGISTER_OPERATION(BoxClassification) BoxClassification::BoxClassification(quint64 metaid, const Ilwis::OperationExpression &expr) : RasterClassification(metaid, expr) { } Ilwis::OperationImplementation *BoxClassification::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new BoxClassification(metaid, expr); } Ilwis::OperationImplementation::State BoxClassification::prepare(ExecutionContext *ctx, const SymbolTable &sym) { OperationImplementation::State prepareState = sNOTPREPARED; if ( (prepareState = RasterClassification::prepare(ctx,sym)) != sPREPARED){ return prepareState; } bool ok; _widenFactor = _expression.parm(3).value().toDouble(&ok); if (!ok || _widenFactor <= 0){ ERROR2(ERR_ILLEGAL_VALUE_2, "widen factor", _expression.parm(1).value()); } _classifier.reset( new BoxClassifier(_widenFactor,_sampleSet)); return sPREPARED; } quint64 BoxClassification::createMetadata() { OperationResource operation({"ilwis://operations/boxclassification"}); operation.setSyntax("boxclassifcation(samplesetname,widen-factor)"); operation.setDescription(TR("performs a multi-spectral image classification according to training pixels in a sample set")); unsigned int n = RasterClassification::fillOperationMetadata(operation); operation.setInParameterCount({1 + n}); operation.addInParameter(n,itNUMBER , TR("widen-factor"),TR("allows you to widen (factor > 1) the boxes that are 'drawn' around class means")); operation.setOutParameterCount({1}); operation.addOutParameter(1,itRASTER, TR("output rastercoverage with the domain of the sampleset")); operation.setKeywords("classification,raster"); mastercatalog()->addItems({operation}); return operation.id(); } <commit_msg>added setting of output for classifier<commit_after>#include <functional> #include <future> #include <unordered_map> #include "kernel.h" #include "raster.h" #include "itemdomain.h" #include "thematicitem.h" #include "symboltable.h" #include "ilwisoperation.h" #include "classification/sampleset.h" #include "classifier.h" #include "rasterclassification.h" using namespace Ilwis; using namespace RasterOperations; RasterClassification::RasterClassification() { } RasterClassification::RasterClassification(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr) { } bool RasterClassification::execute(ExecutionContext *ctx, SymbolTable &symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx,symTable)) != sPREPARED) return false; PixelIterator iterIn(_sampleSet.sampleRasterSet()); iterIn.setFlow(PixelIterator::fZXY); PixelIterator iterOut(_outputRaster); bool res = _classifier->classify(iterIn, iterOut); _outputRaster->statistics() if ( res && ctx != 0) { QVariant value; value.setValue<IRasterCoverage>(_outputRaster); ctx->setOutput(symTable,value,_outputRaster->name(), itRASTER, _outputRaster->source(IlwisObject::cmEXTENDED) ); } return res; } Ilwis::OperationImplementation::State RasterClassification::prepare(ExecutionContext *, const SymbolTable &sym){ QString rasterSetName = _expression.parm(0).value(); IRasterCoverage rcSet; if (!rcSet.prepare(rasterSetName)) { ERROR2(ERR_COULD_NOT_LOAD_2,rasterSetName,""); return sPREPAREFAILED; } QString domain = _expression.parm(1).value(); IThematicDomain themes; if ( !themes.prepare(domain)){ ERROR2(ERR_COULD_NOT_LOAD_2,domain,""); return sPREPAREFAILED; } QString trainingsRaster = _expression.parm(2).value(); IRasterCoverage rcTraining; if (!rcTraining.prepare(trainingsRaster, itRASTER)) { ERROR2(ERR_COULD_NOT_LOAD_2,trainingsRaster,""); return sPREPAREFAILED; } _sampleSet = SampleSet(rcSet, themes, rcTraining); _sampleSet.prepare(); QString outputName = _expression.parm(0,false).value(); OperationHelperRaster::initialize(_sampleSet.sampleRasterSet(), _outputRaster, itCOORDSYSTEM | itGEODETICDATUM | itGEOREF | itRASTERSIZE); if ( !_outputRaster.isValid()) { ERROR1(ERR_NO_INITIALIZED_1, "output rastercoverage"); return sPREPAREFAILED; } _outputRaster->datadef().domain(_sampleSet.thematicDomain()); _outputRaster->size(_sampleSet.sampleRasterSet()->size().twod()); if ( outputName!= sUNDEF) _outputRaster->name(outputName); return sPREPARED; } int RasterClassification::fillOperationMetadata(OperationResource &operation) { operation.addInParameter(0,itRASTER , TR("Multiband raster"),TR("Multi band raster to be classified")); operation.addInParameter(1,itITEMDOMAIN , TR("Thematic domain"),TR("Domain of the classified map")); operation.addInParameter(2,itRASTER , TR("Training set"),TR("Raster containing trainingset(s) of pixels")); return 3; } //------------------------------------------------------- REGISTER_OPERATION(BoxClassification) BoxClassification::BoxClassification(quint64 metaid, const Ilwis::OperationExpression &expr) : RasterClassification(metaid, expr) { } Ilwis::OperationImplementation *BoxClassification::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new BoxClassification(metaid, expr); } Ilwis::OperationImplementation::State BoxClassification::prepare(ExecutionContext *ctx, const SymbolTable &sym) { OperationImplementation::State prepareState = sNOTPREPARED; if ( (prepareState = RasterClassification::prepare(ctx,sym)) != sPREPARED){ return prepareState; } bool ok; _widenFactor = _expression.parm(3).value().toDouble(&ok); if (!ok || _widenFactor <= 0){ ERROR2(ERR_ILLEGAL_VALUE_2, "widen factor", _expression.parm(1).value()); } _classifier.reset( new BoxClassifier(_widenFactor,_sampleSet)); if(!_classifier->prepare()) return sPREPAREFAILED; return sPREPARED; } quint64 BoxClassification::createMetadata() { OperationResource operation({"ilwis://operations/boxclassification"}); operation.setSyntax("boxclassifcation(samplesetname,widen-factor)"); operation.setDescription(TR("performs a multi-spectral image classification according to training pixels in a sample set")); unsigned int n = RasterClassification::fillOperationMetadata(operation); operation.setInParameterCount({1 + n}); operation.addInParameter(n,itNUMBER , TR("widen-factor"),TR("allows you to widen (factor > 1) the boxes that are 'drawn' around class means")); operation.setOutParameterCount({1}); operation.addOutParameter(1,itRASTER, TR("output rastercoverage with the domain of the sampleset")); operation.setKeywords("classification,raster"); mastercatalog()->addItems({operation}); return operation.id(); } <|endoftext|>
<commit_before>//===--- swift-serialize-diagnostics.cpp ----------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Convert localization YAML files to a srialized format. // //===----------------------------------------------------------------------===// #include "swift/AST/LocalizationFormat.h" #include "swift/Basic/LLVMInitialize.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Bitstream/BitstreamReader.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/EndianStream.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/OnDiskHashTable.h" #include "llvm/Support/Path.h" #include "llvm/Support/YAMLParser.h" #include "llvm/Support/YAMLTraits.h" #include "llvm/Support/raw_ostream.h" #include <cstdlib> using namespace swift; using namespace swift::diag; namespace options { static llvm::cl::OptionCategory Category("swift-serialize-diagnostics Options"); static llvm::cl::opt<std::string> InputFilePath("input-file-path", llvm::cl::desc("Path to the YAML input file"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> OutputDirectory("output-directory", llvm::cl::desc("Directory for the output file"), llvm::cl::cat(Category)); } // namespace options int main(int argc, char *argv[]) { PROGRAM_START(argc, argv); INITIALIZE_LLVM(); llvm::cl::HideUnrelatedOptions(options::Category); llvm::cl::ParseCommandLineOptions(argc, argv, "Swift Serialize Diagnostics Tool\n"); if (!llvm::sys::fs::exists(options::InputFilePath)) { llvm::errs() << "YAML file not found\n"; return 1; } YAMLLocalizationProducer yaml(options::InputFilePath); auto localeCode = llvm::sys::path::filename(options::InputFilePath); llvm::SmallString<128> SerializedFilePath(options::OutputDirectory); llvm::sys::path::append(SerializedFilePath, localeCode); llvm::sys::path::replace_extension(SerializedFilePath, ".db"); SerializedLocalizationWriter Serializer; yaml.forEachAvailable( [&Serializer](swift::DiagID id, llvm::StringRef translation) { Serializer.insert(id, translation); }); if (Serializer.emit(SerializedFilePath.str())) { llvm::errs() << "Cannot serialize diagnostic file " << options::InputFilePath << '\n'; return 1; } return 0; } <commit_msg>[Localization] Make return type of the serialization main cross platform<commit_after>//===--- swift-serialize-diagnostics.cpp ----------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Convert localization YAML files to a srialized format. // //===----------------------------------------------------------------------===// #include "swift/AST/LocalizationFormat.h" #include "swift/Basic/LLVMInitialize.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Bitstream/BitstreamReader.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/EndianStream.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/OnDiskHashTable.h" #include "llvm/Support/Path.h" #include "llvm/Support/YAMLParser.h" #include "llvm/Support/YAMLTraits.h" #include "llvm/Support/raw_ostream.h" #include <cstdlib> using namespace swift; using namespace swift::diag; namespace options { static llvm::cl::OptionCategory Category("swift-serialize-diagnostics Options"); static llvm::cl::opt<std::string> InputFilePath("input-file-path", llvm::cl::desc("Path to the YAML input file"), llvm::cl::cat(Category)); static llvm::cl::opt<std::string> OutputDirectory("output-directory", llvm::cl::desc("Directory for the output file"), llvm::cl::cat(Category)); } // namespace options int main(int argc, char *argv[]) { PROGRAM_START(argc, argv); llvm::cl::HideUnrelatedOptions(options::Category); llvm::cl::ParseCommandLineOptions(argc, argv, "Swift Serialize Diagnostics Tool\n"); if (!llvm::sys::fs::exists(options::InputFilePath)) { llvm::errs() << "YAML file not found\n"; return EXIT_FAILURE; } YAMLLocalizationProducer yaml(options::InputFilePath); auto localeCode = llvm::sys::path::filename(options::InputFilePath); llvm::SmallString<128> SerializedFilePath(options::OutputDirectory); llvm::sys::path::append(SerializedFilePath, localeCode); llvm::sys::path::replace_extension(SerializedFilePath, ".db"); SerializedLocalizationWriter Serializer; yaml.forEachAvailable( [&Serializer](swift::DiagID id, llvm::StringRef translation) { Serializer.insert(id, translation); }); if (Serializer.emit(SerializedFilePath.str())) { llvm::errs() << "Cannot serialize diagnostic file " << options::InputFilePath << '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>Use IOMessageLoop in a SyncFileSystem test<commit_after><|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/dll_workarounds.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ // *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com> // *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #ifndef _MSS_WORKAROUNDS_DLL_H_ #define _MSS_WORKAROUNDS_DLL_H_ #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <map> namespace mss { /// /// @brief class to keep trace of DLL info for workaround /// struct dll_map { // Same values for DP16 and ADR enumerations // Used DP16 enumerations...just because static constexpr uint64_t REGS_RXDLL_DAC_COARSE = MCA_DDRPHY_DP16_DLL_VREG_COARSE0_P0_1_01_REGS_RXDLL_DAC_COARSE; static constexpr uint64_t REGS_RXDLL_DAC_COARSE_LEN = MCA_DDRPHY_DP16_DLL_VREG_COARSE0_P0_1_01_REGS_RXDLL_DAC_COARSE_LEN; static constexpr uint64_t DLL_CNTL_CAL_ERROR = MCA_DDRPHY_DP16_DLL_CNTL0_P0_1_01_CAL_ERROR; static constexpr uint64_t DLL_CNTL_CAL_ERROR_FINE = MCA_DDRPHY_DP16_DLL_CNTL0_P0_1_01_CAL_ERROR_FINE; static constexpr uint64_t DLL_CAL_GOOD = MCA_DDRPHY_DP16_DLL_CNTL0_P0_1_01_CAL_GOOD; // Value for UPPER and LOWER DAC are the same // Used LOWER DAC enumeration...just because static constexpr uint64_t REGS_RXDLL_VREG = MCA_DDRPHY_DP16_DLL_DAC_LOWER0_P0_0_01_REGS_RXDLL_VREG_LOWER; static constexpr uint64_t REGS_RXDLL_VREG_LEN = MCA_DDRPHY_DP16_DLL_DAC_LOWER0_P0_0_01_REGS_RXDLL_VREG_LOWER_LEN; /// /// @brief Checks for DLL error status /// @param[in] i_cntrl_reg /// @param[in] i_vreg_coarse_same_dll /// @param[in] i_vreg_coarse_neighbor_dll /// @param[in] i_dll_dac_upper /// @param[in] i_dll_dac_lower /// constexpr dll_map(const uint64_t i_cntrl_reg, const uint64_t i_vreg_coarse_same_dll, const uint64_t i_vreg_coarse_neighbor_dll, const uint64_t i_dll_dac_lower, const uint64_t i_dll_dac_upper) : iv_cntrl(i_cntrl_reg), iv_vreg_coarse_same_dll(i_vreg_coarse_same_dll), iv_vreg_coarse_neighbor_dll(i_vreg_coarse_neighbor_dll), iv_dll_dac_lower(i_dll_dac_lower), iv_dll_dac_upper(i_dll_dac_upper) {} const uint64_t iv_cntrl; // DP16 or ADR CNTRL register const uint64_t iv_vreg_coarse_same_dll; // VREG_COARSE register for same DLL as iv_cntrl_reg const uint64_t iv_vreg_coarse_neighbor_dll; // VREG_COARSE register for DLL neighbor for this workaround const uint64_t iv_dll_dac_lower; // DLL DAC Upper register const uint64_t iv_dll_dac_upper; // DLL DAC Lower register }; namespace workarounds { namespace dll { /// /// @brief Clears the DLL firs /// @param[in] i_target the MCA target /// @return returns true unless if scom errors /// fapi2::ReturnCode clear_dll_fir( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target ); /// /// @brief Checks if CAL_ERROR and CAL_ERROR_FINE bits are set /// @param[in] i_dll_cntrl_data DLL CNTRL data /// @return bool /// bool did_cal_fail( const fapi2::buffer<uint64_t>& i_dll_cntrl_data ); /// /// @brief Logs DLL error mappings from failed DLLs /// @param[in] i_target the fapi2 target /// @param[in] i_map dll map of DLLs to log errors from /// @param[in,out] io_failed_dll_cntrl failed list of DLL CNTRL regs /// @param[in,out] io_failed_dll_vreg_coarse map of VREG COARSE from failed DLLs /// @param[in,out] io_failed_dll_dac map of DLL DAC from failed DLLs /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode log_fails(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const mss::dll_map& i_map, std::vector< uint64_t >& io_failed_dll_cntrl, std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& io_failed_dll_vreg_coarse, std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& io_failed_dll_dac); /// /// @brief Checks for DLL error status /// @param[in] i_target the fapi2 target /// @param[in] i_failed_dll_cntrl vector of failed DLLs /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode check_status(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const std::vector< uint64_t >& i_failed_dll_cntrl); /// /// @brief Change VREG_COARSE for failed DLLs /// @param[in] i_target the fapi2 target /// @param[in] i_failed_dll_map failed DLL VREG COARSE map /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode change_vreg_coarse(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& i_failed_dll_map); /// /// @brief Change DLL DAC for failled DLLs map /// @param[in] i_target the fapi2 target /// @param[in] i_failed_dll_dac_map failed DLL DAC map /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode change_dac(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& i_failed_dll_dac_map); /// /// @brief DLL Workaround algorithm to fax bad voltage settings /// @tparam T fapi2 Target Type - derived /// @param[in] i_target the fapi2 target /// @return FAPI2_RC_SUCCESS iff ok /// template< fapi2::TargetType T > fapi2::ReturnCode fix_bad_voltage_settings(const fapi2::Target<T>& i_target); } // close namespace dll } // close namespace workarounds } // close namespace mss #endif <commit_msg>Update HPW Level for MSS API library<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/dll_workarounds.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ // *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com> // *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #ifndef _MSS_WORKAROUNDS_DLL_H_ #define _MSS_WORKAROUNDS_DLL_H_ #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <map> namespace mss { /// /// @brief class to keep trace of DLL info for workaround /// struct dll_map { // Same values for DP16 and ADR enumerations // Used DP16 enumerations...just because static constexpr uint64_t REGS_RXDLL_DAC_COARSE = MCA_DDRPHY_DP16_DLL_VREG_COARSE0_P0_1_01_REGS_RXDLL_DAC_COARSE; static constexpr uint64_t REGS_RXDLL_DAC_COARSE_LEN = MCA_DDRPHY_DP16_DLL_VREG_COARSE0_P0_1_01_REGS_RXDLL_DAC_COARSE_LEN; static constexpr uint64_t DLL_CNTL_CAL_ERROR = MCA_DDRPHY_DP16_DLL_CNTL0_P0_1_01_CAL_ERROR; static constexpr uint64_t DLL_CNTL_CAL_ERROR_FINE = MCA_DDRPHY_DP16_DLL_CNTL0_P0_1_01_CAL_ERROR_FINE; static constexpr uint64_t DLL_CAL_GOOD = MCA_DDRPHY_DP16_DLL_CNTL0_P0_1_01_CAL_GOOD; // Value for UPPER and LOWER DAC are the same // Used LOWER DAC enumeration...just because static constexpr uint64_t REGS_RXDLL_VREG = MCA_DDRPHY_DP16_DLL_DAC_LOWER0_P0_0_01_REGS_RXDLL_VREG_LOWER; static constexpr uint64_t REGS_RXDLL_VREG_LEN = MCA_DDRPHY_DP16_DLL_DAC_LOWER0_P0_0_01_REGS_RXDLL_VREG_LOWER_LEN; /// /// @brief Checks for DLL error status /// @param[in] i_cntrl_reg /// @param[in] i_vreg_coarse_same_dll /// @param[in] i_vreg_coarse_neighbor_dll /// @param[in] i_dll_dac_upper /// @param[in] i_dll_dac_lower /// constexpr dll_map(const uint64_t i_cntrl_reg, const uint64_t i_vreg_coarse_same_dll, const uint64_t i_vreg_coarse_neighbor_dll, const uint64_t i_dll_dac_lower, const uint64_t i_dll_dac_upper) : iv_cntrl(i_cntrl_reg), iv_vreg_coarse_same_dll(i_vreg_coarse_same_dll), iv_vreg_coarse_neighbor_dll(i_vreg_coarse_neighbor_dll), iv_dll_dac_lower(i_dll_dac_lower), iv_dll_dac_upper(i_dll_dac_upper) {} const uint64_t iv_cntrl; // DP16 or ADR CNTRL register const uint64_t iv_vreg_coarse_same_dll; // VREG_COARSE register for same DLL as iv_cntrl_reg const uint64_t iv_vreg_coarse_neighbor_dll; // VREG_COARSE register for DLL neighbor for this workaround const uint64_t iv_dll_dac_lower; // DLL DAC Upper register const uint64_t iv_dll_dac_upper; // DLL DAC Lower register }; namespace workarounds { namespace dll { /// /// @brief Clears the DLL firs /// @param[in] i_target the MCA target /// @return returns true unless if scom errors /// fapi2::ReturnCode clear_dll_fir( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target ); /// /// @brief Checks if CAL_ERROR and CAL_ERROR_FINE bits are set /// @param[in] i_dll_cntrl_data DLL CNTRL data /// @return bool /// bool did_cal_fail( const fapi2::buffer<uint64_t>& i_dll_cntrl_data ); /// /// @brief Logs DLL error mappings from failed DLLs /// @param[in] i_target the fapi2 target /// @param[in] i_map dll map of DLLs to log errors from /// @param[in,out] io_failed_dll_cntrl failed list of DLL CNTRL regs /// @param[in,out] io_failed_dll_vreg_coarse map of VREG COARSE from failed DLLs /// @param[in,out] io_failed_dll_dac map of DLL DAC from failed DLLs /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode log_fails(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const mss::dll_map& i_map, std::vector< uint64_t >& io_failed_dll_cntrl, std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& io_failed_dll_vreg_coarse, std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& io_failed_dll_dac); /// /// @brief Checks for DLL error status /// @param[in] i_target the fapi2 target /// @param[in] i_failed_dll_cntrl vector of failed DLLs /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode check_status(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const std::vector< uint64_t >& i_failed_dll_cntrl); /// /// @brief Change VREG_COARSE for failed DLLs /// @param[in] i_target the fapi2 target /// @param[in] i_failed_dll_map failed DLL VREG COARSE map /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode change_vreg_coarse(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& i_failed_dll_map); /// /// @brief Change DLL DAC for failled DLLs map /// @param[in] i_target the fapi2 target /// @param[in] i_failed_dll_dac_map failed DLL DAC map /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode change_dac(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const std::map< fapi2::buffer<uint64_t>, fapi2::buffer<uint64_t> >& i_failed_dll_dac_map); /// /// @brief DLL Workaround algorithm to fax bad voltage settings /// @tparam T fapi2 Target Type - derived /// @param[in] i_target the fapi2 target /// @return FAPI2_RC_SUCCESS iff ok /// template< fapi2::TargetType T > fapi2::ReturnCode fix_bad_voltage_settings(const fapi2::Target<T>& i_target); } // close namespace dll } // close namespace workarounds } // close namespace mss #endif <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2011 Francois Beaune // // 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. // // Interface header. #include "physicalsurfaceshader.h" // appleseed.renderer headers. #include "renderer/kernel/lighting/ilightingengine.h" #include "renderer/kernel/shading/shadingcontext.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/shading/shadingray.h" #include "renderer/kernel/shading/shadingresult.h" #include "renderer/modeling/environment/environment.h" #include "renderer/modeling/environmentshader/environmentshader.h" #include "renderer/modeling/input/inputarray.h" #include "renderer/modeling/input/inputevaluator.h" #include "renderer/modeling/input/source.h" #include "renderer/modeling/scene/scene.h" #include "renderer/modeling/surfaceshader/surfaceshader.h" // appleseed.foundation headers. #include "foundation/image/colorspace.h" #include "foundation/math/vector.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/containers/specializedarrays.h" // Standard headers. #include <algorithm> #include <cmath> // Forward declarations. namespace renderer { class Assembly; } namespace renderer { class Project; } namespace renderer { class TextureCache; } using namespace foundation; using namespace std; namespace renderer { namespace { // // Physical surface shader. // const char* Model = "physical_surface_shader"; class PhysicalSurfaceShader : public SurfaceShader { public: PhysicalSurfaceShader( const char* name, const ParamArray& params) : SurfaceShader(name, params) , m_lighting_conditions(IlluminantCIED65, XYZCMFCIE196410Deg) , m_has_alpha_mask(false) { m_inputs.declare("alpha_mask", InputFormatSpectrum, true); m_inputs.declare("aerial_persp_sky_color", InputFormatSpectrum, true); const string aerial_persp_mode = m_params.get_required<string>("aerial_persp_mode", "none"); if (aerial_persp_mode == "none") m_aerial_persp_mode = AerialPerspNone; else if (aerial_persp_mode == "environment_shader") m_aerial_persp_mode = AerialPerspEnvironmentShader; else if (aerial_persp_mode == "sky_color") m_aerial_persp_mode = AerialPerspSkyColor; else { RENDERER_LOG_ERROR( "invalid value \"%s\" for parameter \"aerial_persp_mode\", ", "using default value \"none\"", aerial_persp_mode.c_str()); m_aerial_persp_mode = AerialPerspNone; } m_aerial_persp_rcp_distance = 1.0 / m_params.get_optional<double>("aerial_persp_distance", 1000.0); m_aerial_persp_intensity = m_params.get_optional<double>("aerial_persp_intensity", 0.01); } virtual void release() override { delete this; } virtual const char* get_model() const override { return Model; } virtual void on_frame_begin( const Project& project, const Assembly& assembly) override { SurfaceShader::on_frame_begin(project, assembly); m_has_alpha_mask = m_inputs.source("alpha_mask") != 0; } virtual void evaluate( SamplingContext& sampling_context, const ShadingContext& shading_context, const ShadingPoint& shading_point, ShadingResult& shading_result) const override { // Set color space to spectral. shading_result.m_color_space = ColorSpaceSpectral; // Retrieve the lighting engine. ILightingEngine* lighting_engine = shading_context.get_lighting_engine(); assert(lighting_engine); // Compute the lighting. lighting_engine->compute_lighting( sampling_context, shading_context, shading_point, shading_result.m_color); // Evaluate alpha mask. evaluate_alpha_mask( sampling_context, shading_context.get_texture_cache(), shading_point, shading_result.m_alpha); if (m_aerial_persp_mode != AerialPerspNone) { Spectrum sky_color; if (m_aerial_persp_mode == AerialPerspSkyColor) { // Evaluate the inputs to obtain the sky color. InputValues values; m_inputs.evaluate( shading_context.get_texture_cache(), shading_point.get_input_params(), &values); sky_color = values.m_aerial_persp_sky_color; } else { // Retrieve the environment shader of the scene. const Scene& scene = shading_point.get_scene(); const EnvironmentShader* environment_shader = scene.get_environment()->get_environment_shader(); if (environment_shader) { // Execute the environment shader to obtain the sky color in the direction of the ray. InputEvaluator input_evaluator(shading_context.get_texture_cache()); const ShadingRay& ray = shading_point.get_ray(); const Vector3d direction = normalize(ray.m_dir); ShadingResult sky; environment_shader->evaluate(input_evaluator, direction, sky); sky.transform_to_spectrum(m_lighting_conditions); sky_color = sky.m_color; } else sky_color.set(0.0f); } // Compute the blend factor. const double d = shading_point.get_distance() * m_aerial_persp_rcp_distance; const double k = m_aerial_persp_intensity * exp(d); const double blend = min(k, 1.0); // Blend the shading result and the sky color. sky_color *= static_cast<float>(blend); shading_result.m_color *= static_cast<float>(1.0 - blend); shading_result.m_color += sky_color; } } virtual void evaluate_alpha_mask( SamplingContext& sampling_context, TextureCache& texture_cache, const ShadingPoint& shading_point, Alpha& alpha) const override { if (!m_has_alpha_mask) { // Set alpha channel to full opacity. alpha = Alpha(1.0); } else { // Evaluate the inputs. InputValues values; m_inputs.evaluate( texture_cache, shading_point.get_input_params(), &values); // Set alpha channel. alpha = values.m_alpha_mask_alpha; } } private: struct InputValues { Spectrum m_alpha_mask_color; // unused Alpha m_alpha_mask_alpha; Spectrum m_aerial_persp_sky_color; Alpha m_aerial_persp_sky_alpha; // unused }; enum AerialPerspMode { AerialPerspNone, AerialPerspEnvironmentShader, AerialPerspSkyColor }; const LightingConditions m_lighting_conditions; bool m_has_alpha_mask; AerialPerspMode m_aerial_persp_mode; double m_aerial_persp_rcp_distance; double m_aerial_persp_intensity; }; } // // PhysicalSurfaceShaderFactory class implementation. // const char* PhysicalSurfaceShaderFactory::get_model() const { return Model; } const char* PhysicalSurfaceShaderFactory::get_human_readable_model() const { return "Physical"; } DictionaryArray PhysicalSurfaceShaderFactory::get_widget_definitions() const { DictionaryArray definitions; definitions.push_back( Dictionary() .insert("name", "alpha_mask") .insert("label", "Alpha Mask") .insert("widget", "entity_picker") .insert("entity_types", Dictionary() .insert("color", "Colors") .insert("texture_instance", "Textures")) .insert("use", "optional") .insert("default", "")); definitions.push_back( Dictionary() .insert("name", "aerial_persp_mode") .insert("label", "Aerial Perspective Mode") .insert("widget", "dropdown_list") .insert("dropdown_items", Dictionary() .insert("None", "none") .insert("Use Environment Shader", "environment_shader") .insert("Use Sky Color", "sky_color")) .insert("use", "optional") .insert("default", "none")); definitions.push_back( Dictionary() .insert("name", "aerial_persp_sky_color") .insert("label", "Aerial Perspective Sky Color") .insert("widget", "entity_picker") .insert("entity_types", Dictionary().insert("color", "Colors")) .insert("use", "optional") .insert("default", "")); definitions.push_back( Dictionary() .insert("name", "aerial_persp_distance") .insert("label", "Aerial Perspective Distance") .insert("widget", "text_box") .insert("default", "1000.0") .insert("use", "optional")); definitions.push_back( Dictionary() .insert("name", "aerial_persp_intensity") .insert("label", "Aerial Perspective Intensity") .insert("widget", "text_box") .insert("default", "0.01") .insert("use", "optional")); return definitions; } auto_release_ptr<SurfaceShader> PhysicalSurfaceShaderFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<SurfaceShader>( new PhysicalSurfaceShader(name, params)); } } // namespace renderer <commit_msg>the "aerial_persp_mode" parameter of the Physical surface shader is optional, not required.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2011 Francois Beaune // // 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. // // Interface header. #include "physicalsurfaceshader.h" // appleseed.renderer headers. #include "renderer/kernel/lighting/ilightingengine.h" #include "renderer/kernel/shading/shadingcontext.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/shading/shadingray.h" #include "renderer/kernel/shading/shadingresult.h" #include "renderer/modeling/environment/environment.h" #include "renderer/modeling/environmentshader/environmentshader.h" #include "renderer/modeling/input/inputarray.h" #include "renderer/modeling/input/inputevaluator.h" #include "renderer/modeling/input/source.h" #include "renderer/modeling/scene/scene.h" #include "renderer/modeling/surfaceshader/surfaceshader.h" // appleseed.foundation headers. #include "foundation/image/colorspace.h" #include "foundation/math/vector.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/containers/specializedarrays.h" // Standard headers. #include <algorithm> #include <cmath> // Forward declarations. namespace renderer { class Assembly; } namespace renderer { class Project; } namespace renderer { class TextureCache; } using namespace foundation; using namespace std; namespace renderer { namespace { // // Physical surface shader. // const char* Model = "physical_surface_shader"; class PhysicalSurfaceShader : public SurfaceShader { public: PhysicalSurfaceShader( const char* name, const ParamArray& params) : SurfaceShader(name, params) , m_lighting_conditions(IlluminantCIED65, XYZCMFCIE196410Deg) , m_has_alpha_mask(false) { m_inputs.declare("alpha_mask", InputFormatSpectrum, true); m_inputs.declare("aerial_persp_sky_color", InputFormatSpectrum, true); const string aerial_persp_mode = m_params.get_optional<string>("aerial_persp_mode", "none"); if (aerial_persp_mode == "none") m_aerial_persp_mode = AerialPerspNone; else if (aerial_persp_mode == "environment_shader") m_aerial_persp_mode = AerialPerspEnvironmentShader; else if (aerial_persp_mode == "sky_color") m_aerial_persp_mode = AerialPerspSkyColor; else { RENDERER_LOG_ERROR( "invalid value \"%s\" for parameter \"aerial_persp_mode\", ", "using default value \"none\"", aerial_persp_mode.c_str()); m_aerial_persp_mode = AerialPerspNone; } m_aerial_persp_rcp_distance = 1.0 / m_params.get_optional<double>("aerial_persp_distance", 1000.0); m_aerial_persp_intensity = m_params.get_optional<double>("aerial_persp_intensity", 0.01); } virtual void release() override { delete this; } virtual const char* get_model() const override { return Model; } virtual void on_frame_begin( const Project& project, const Assembly& assembly) override { SurfaceShader::on_frame_begin(project, assembly); m_has_alpha_mask = m_inputs.source("alpha_mask") != 0; } virtual void evaluate( SamplingContext& sampling_context, const ShadingContext& shading_context, const ShadingPoint& shading_point, ShadingResult& shading_result) const override { // Set color space to spectral. shading_result.m_color_space = ColorSpaceSpectral; // Retrieve the lighting engine. ILightingEngine* lighting_engine = shading_context.get_lighting_engine(); assert(lighting_engine); // Compute the lighting. lighting_engine->compute_lighting( sampling_context, shading_context, shading_point, shading_result.m_color); // Evaluate alpha mask. evaluate_alpha_mask( sampling_context, shading_context.get_texture_cache(), shading_point, shading_result.m_alpha); if (m_aerial_persp_mode != AerialPerspNone) { Spectrum sky_color; if (m_aerial_persp_mode == AerialPerspSkyColor) { // Evaluate the inputs to obtain the sky color. InputValues values; m_inputs.evaluate( shading_context.get_texture_cache(), shading_point.get_input_params(), &values); sky_color = values.m_aerial_persp_sky_color; } else { // Retrieve the environment shader of the scene. const Scene& scene = shading_point.get_scene(); const EnvironmentShader* environment_shader = scene.get_environment()->get_environment_shader(); if (environment_shader) { // Execute the environment shader to obtain the sky color in the direction of the ray. InputEvaluator input_evaluator(shading_context.get_texture_cache()); const ShadingRay& ray = shading_point.get_ray(); const Vector3d direction = normalize(ray.m_dir); ShadingResult sky; environment_shader->evaluate(input_evaluator, direction, sky); sky.transform_to_spectrum(m_lighting_conditions); sky_color = sky.m_color; } else sky_color.set(0.0f); } // Compute the blend factor. const double d = shading_point.get_distance() * m_aerial_persp_rcp_distance; const double k = m_aerial_persp_intensity * exp(d); const double blend = min(k, 1.0); // Blend the shading result and the sky color. sky_color *= static_cast<float>(blend); shading_result.m_color *= static_cast<float>(1.0 - blend); shading_result.m_color += sky_color; } } virtual void evaluate_alpha_mask( SamplingContext& sampling_context, TextureCache& texture_cache, const ShadingPoint& shading_point, Alpha& alpha) const override { if (!m_has_alpha_mask) { // Set alpha channel to full opacity. alpha = Alpha(1.0); } else { // Evaluate the inputs. InputValues values; m_inputs.evaluate( texture_cache, shading_point.get_input_params(), &values); // Set alpha channel. alpha = values.m_alpha_mask_alpha; } } private: struct InputValues { Spectrum m_alpha_mask_color; // unused Alpha m_alpha_mask_alpha; Spectrum m_aerial_persp_sky_color; Alpha m_aerial_persp_sky_alpha; // unused }; enum AerialPerspMode { AerialPerspNone, AerialPerspEnvironmentShader, AerialPerspSkyColor }; const LightingConditions m_lighting_conditions; bool m_has_alpha_mask; AerialPerspMode m_aerial_persp_mode; double m_aerial_persp_rcp_distance; double m_aerial_persp_intensity; }; } // // PhysicalSurfaceShaderFactory class implementation. // const char* PhysicalSurfaceShaderFactory::get_model() const { return Model; } const char* PhysicalSurfaceShaderFactory::get_human_readable_model() const { return "Physical"; } DictionaryArray PhysicalSurfaceShaderFactory::get_widget_definitions() const { DictionaryArray definitions; definitions.push_back( Dictionary() .insert("name", "alpha_mask") .insert("label", "Alpha Mask") .insert("widget", "entity_picker") .insert("entity_types", Dictionary() .insert("color", "Colors") .insert("texture_instance", "Textures")) .insert("use", "optional") .insert("default", "")); definitions.push_back( Dictionary() .insert("name", "aerial_persp_mode") .insert("label", "Aerial Perspective Mode") .insert("widget", "dropdown_list") .insert("dropdown_items", Dictionary() .insert("None", "none") .insert("Use Environment Shader", "environment_shader") .insert("Use Sky Color", "sky_color")) .insert("use", "optional") .insert("default", "none")); definitions.push_back( Dictionary() .insert("name", "aerial_persp_sky_color") .insert("label", "Aerial Perspective Sky Color") .insert("widget", "entity_picker") .insert("entity_types", Dictionary().insert("color", "Colors")) .insert("use", "optional") .insert("default", "")); definitions.push_back( Dictionary() .insert("name", "aerial_persp_distance") .insert("label", "Aerial Perspective Distance") .insert("widget", "text_box") .insert("default", "1000.0") .insert("use", "optional")); definitions.push_back( Dictionary() .insert("name", "aerial_persp_intensity") .insert("label", "Aerial Perspective Intensity") .insert("widget", "text_box") .insert("default", "0.01") .insert("use", "optional")); return definitions; } auto_release_ptr<SurfaceShader> PhysicalSurfaceShaderFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<SurfaceShader>( new PhysicalSurfaceShader(name, params)); } } // namespace renderer <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // size_type find_first_not_of(charT c, size_type pos = 0) const; #include <string> #include <cassert> template <class S> void test(const S& s, typename S::value_type c, typename S::size_type pos, typename S::size_type x) { assert(s.find_first_not_of(c, pos) == x); if (x != S::npos) assert(pos <= x && x < s.size()); } template <class S> void test(const S& s, typename S::value_type c, typename S::size_type x) { assert(s.find_first_not_of(c) == x); if (x != S::npos) assert(x < s.size()); } typedef std::string S; int main() { test(S(""), 'q', 0, S::npos); test(S(""), 'q', 1, S::npos); test(S("kitcj"), 'q', 0, 0); test(S("qkamf"), 'q', 1, 1); test(S("nhmko"), 'q', 2, 2); test(S("tpsaf"), 'q', 4, 4); test(S("lahfb"), 'q', 5, S::npos); test(S("irkhs"), 'q', 6, S::npos); test(S("gmfhdaipsr"), 'q', 0, 0); test(S("kantesmpgj"), 'q', 1, 1); test(S("odaftiegpm"), 'q', 5, 5); test(S("oknlrstdpi"), 'q', 9, 9); test(S("eolhfgpjqk"), 'q', 10, S::npos); test(S("pcdrofikas"), 'q', 11, S::npos); test(S("nbatdlmekrgcfqsophij"), 'q', 0, 0); test(S("bnrpehidofmqtcksjgla"), 'q', 1, 1); test(S("jdmciepkaqgotsrfnhlb"), 'q', 10, 10); test(S("jtdaefblsokrmhpgcnqi"), 'q', 19, 19); test(S("hkbgspofltajcnedqmri"), 'q', 20, S::npos); test(S("oselktgbcapndfjihrmq"), 'q', 21, S::npos); test(S(""), 'q', S::npos); test(S("csope"), 'q', 0); test(S("gfsmthlkon"), 'q', 0); test(S("laenfsbridchgotmkqpj"), 'q', 0); } <commit_msg>Klaas de Vries: Fix bug in libc++'s std::string::find_first_not_of.<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // size_type find_first_not_of(charT c, size_type pos = 0) const; #include <string> #include <cassert> template <class S> void test(const S& s, typename S::value_type c, typename S::size_type pos, typename S::size_type x) { assert(s.find_first_not_of(c, pos) == x); if (x != S::npos) assert(pos <= x && x < s.size()); } template <class S> void test(const S& s, typename S::value_type c, typename S::size_type x) { assert(s.find_first_not_of(c) == x); if (x != S::npos) assert(x < s.size()); } typedef std::string S; int main() { test(S(""), 'q', 0, S::npos); test(S(""), 'q', 1, S::npos); test(S("kitcj"), 'q', 0, 0); test(S("qkamf"), 'q', 1, 1); test(S("nhmko"), 'q', 2, 2); test(S("tpsaf"), 'q', 4, 4); test(S("lahfb"), 'q', 5, S::npos); test(S("irkhs"), 'q', 6, S::npos); test(S("gmfhdaipsr"), 'q', 0, 0); test(S("kantesmpgj"), 'q', 1, 1); test(S("odaftiegpm"), 'q', 5, 5); test(S("oknlrstdpi"), 'q', 9, 9); test(S("eolhfgpjqk"), 'q', 10, S::npos); test(S("pcdrofikas"), 'q', 11, S::npos); test(S("nbatdlmekrgcfqsophij"), 'q', 0, 0); test(S("bnrpehidofmqtcksjgla"), 'q', 1, 1); test(S("jdmciepkaqgotsrfnhlb"), 'q', 10, 10); test(S("jtdaefblsokrmhpgcnqi"), 'q', 19, 19); test(S("hkbgspofltajcnedqmri"), 'q', 20, S::npos); test(S("oselktgbcapndfjihrmq"), 'q', 21, S::npos); test(S(""), 'q', S::npos); test(S("q"), 'q', S::npos); test(S("qqq"), 'q', S::npos); test(S("csope"), 'q', 0); test(S("gfsmthlkon"), 'q', 0); test(S("laenfsbridchgotmkqpj"), 'q', 0); } <|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 <QDebug> #include <QDBusInterface> #include <QDBusConnection> #include <QDBusReply> #include <QSystemNetworkInfo> QTM_USE_NAMESPACE const static QString NORMAL_MODE = "normal"; const static QString OFFLINE_MODE = "offline"; static QDBusInterface mceConnectionInterface("com.nokia.mce", "/com/nokia/mce/request", "com.nokia.mce.request", QDBusConnection::systemBus()); /** * Starts an event loop that runs until the given signal is received. * Optionally the event loop can return earlier on a timeout. * * \return \p true if the requested signal was received * \p false on timeout */ static bool waitForSignal(QObject *obj, const char *signal, int timeout = 0) { QEventLoop loop; QObject::connect(obj, signal, &loop, SLOT(quit())); QTimer timer; QSignalSpy timeoutSpy(&timer, SIGNAL(timeout())); if (timeout > 0) { QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); timer.setSingleShot(true); timer.start(timeout); } loop.exec(); return timeoutSpy.isEmpty(); } static void log(QString message) { qDebug() << QDateTime::currentDateTime().toTime_t() << " " << message; } static void setDeviceMode(QString deviceMode) { mceConnectionInterface.call("req_device_mode_change", deviceMode); } class DropNetworkThread : public QThread { public: void run() { log("DropNetworkThread: Waiting 2s before dropping the cellular network"); sleep(2); setDeviceMode(OFFLINE_MODE); log("DropNetworkThread: Cellular network dropped"); } }; class tst_QSystemNetworkInfo : public QObject { Q_OBJECT public: tst_QSystemNetworkInfo(); virtual ~tst_QSystemNetworkInfo(); public slots: void init(); void cleanup(); private slots: void networkSignalStrengthChanged(); void networkStatusChanged(); void mobileCountryCodeChanged(); void mobileNetworkCodeChanged(); void networkNameChanged(); void networkModeChanged(); private: QSystemNetworkInfo *m_systemNetworkInfo; DropNetworkThread *m_dropNetworkThread; }; tst_QSystemNetworkInfo::tst_QSystemNetworkInfo() { m_dropNetworkThread = new DropNetworkThread(); m_systemNetworkInfo = new QSystemNetworkInfo(); } tst_QSystemNetworkInfo::~tst_QSystemNetworkInfo() { delete m_dropNetworkThread, m_dropNetworkThread = 0; delete m_systemNetworkInfo, m_systemNetworkInfo = 0; } /* * Called before each test case */ void tst_QSystemNetworkInfo::init() { log("init: setDeviceMode: normal"); setDeviceMode(NORMAL_MODE); QTest::qWait(2000); log("init done"); } /* * Called after each test case */ void tst_QSystemNetworkInfo::cleanup() { QTest::qWait(2000); log("cleanup: setDeviceMode: normal"); setDeviceMode(NORMAL_MODE); QTest::qWait(2000); log("cleanup done"); } /* * The test cases */ void tst_QSystemNetworkInfo::networkSignalStrengthChanged() { m_dropNetworkThread->start(); log("Waiting 60s for network signal strength to change"); QVERIFY(::waitForSignal(m_systemNetworkInfo, SIGNAL(networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode, int)), 60 * 1000)); log("networkSignalStrengthChanged"); } void tst_QSystemNetworkInfo::networkStatusChanged() { m_dropNetworkThread->start(); log("Waiting 60s for network status to change"); QVERIFY(::waitForSignal(m_systemNetworkInfo, SIGNAL(networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus)), 60 * 1000)); log("networkStatusChanged"); } void tst_QSystemNetworkInfo::mobileCountryCodeChanged() { m_dropNetworkThread->start(); log("Waiting 60s for mobile country code to change"); QVERIFY(::waitForSignal(m_systemNetworkInfo, SIGNAL(currentMobileCountryCodeChanged(QString)), 60 * 1000)); log("currentMobileCountryCodeChanged"); } void tst_QSystemNetworkInfo::mobileNetworkCodeChanged() { m_dropNetworkThread->start(); log("Waiting 60s for mobile network code to change"); QVERIFY(::waitForSignal(m_systemNetworkInfo, SIGNAL(currentMobileNetworkCodeChanged(QString)), 60 * 1000)); log("currentMobileNetworkCodeChanged"); } void tst_QSystemNetworkInfo::networkNameChanged() { m_dropNetworkThread->start(); log("Waiting 60s for network name to change"); QVERIFY(::waitForSignal(m_systemNetworkInfo, SIGNAL(networkNameChanged(QSystemNetworkInfo::NetworkMode,QString)), 60 * 1000)); log("networkNameChanged"); } void tst_QSystemNetworkInfo::networkModeChanged() { m_dropNetworkThread->start(); log("Waiting 60s for network mode to change"); QVERIFY(::waitForSignal(m_systemNetworkInfo, SIGNAL(networkModeChanged(QSystemNetworkInfo::NetworkMode)), 60 * 1000)); log("networkModeChanged"); } QTEST_MAIN(tst_QSystemNetworkInfo) #include "tst_qsystemnetworkinfo_maemo.moc" <commit_msg>fix spelling error<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 <QDebug> #include <QDBusInterface> #include <QDBusConnection> #include <QDBusReply> #include <QSystemInfo/QSystemNetworkInfo> QTM_USE_NAMESPACE const static QString NORMAL_MODE = "normal"; const static QString OFFLINE_MODE = "offline"; static QDBusInterface mceConnectionInterface("com.nokia.mce", "/com/nokia/mce/request", "com.nokia.mce.request", QDBusConnection::systemBus()); /** * Starts an event loop that runs until the given signal is received. * Optionally the event loop can return earlier on a timeout. * * \return \p true if the requested signal was received * \p false on timeout */ static bool waitForSignal(QObject *obj, const char *signal, int timeout = 0) { QEventLoop loop; QObject::connect(obj, signal, &loop, SLOT(quit())); QTimer timer; QSignalSpy timeoutSpy(&timer, SIGNAL(timeout())); if (timeout > 0) { QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); timer.setSingleShot(true); timer.start(timeout); } loop.exec(); return timeoutSpy.isEmpty(); } static void log(QString message) { qDebug() << QDateTime::currentDateTime().toTime_t() << " " << message; } static void setDeviceMode(QString deviceMode) { mceConnectionInterface.call("req_device_mode_change", deviceMode); } class DropNetworkThread : public QThread { public: void run() { log("DropNetworkThread: Waiting 2s before dropping the cellular network"); sleep(2); setDeviceMode(OFFLINE_MODE); log("DropNetworkThread: Cellular network dropped"); } }; class tst_QSystemNetworkInfo : public QObject { Q_OBJECT public: tst_QSystemNetworkInfo(); virtual ~tst_QSystemNetworkInfo(); public slots: void init(); void cleanup(); private slots: void networkSignalStrengthChanged(); void networkStatusChanged(); void mobileCountryCodeChanged(); void mobileNetworkCodeChanged(); void networkNameChanged(); void networkModeChanged(); private: QSystemNetworkInfo *m_systemNetworkInfo; DropNetworkThread *m_dropNetworkThread; }; tst_QSystemNetworkInfo::tst_QSystemNetworkInfo() { m_dropNetworkThread = new DropNetworkThread(); m_systemNetworkInfo = new QSystemNetworkInfo(); } tst_QSystemNetworkInfo::~tst_QSystemNetworkInfo() { delete m_dropNetworkThread, m_dropNetworkThread = 0; delete m_systemNetworkInfo, m_systemNetworkInfo = 0; } /* * Called before each test case */ void tst_QSystemNetworkInfo::init() { log("init: setDeviceMode: normal"); setDeviceMode(NORMAL_MODE); QTest::qWait(2000); log("init done"); } /* * Called after each test case */ void tst_QSystemNetworkInfo::cleanup() { QTest::qWait(2000); log("cleanup: setDeviceMode: normal"); setDeviceMode(NORMAL_MODE); QTest::qWait(2000); log("cleanup done"); } /* * The test cases */ void tst_QSystemNetworkInfo::networkSignalStrengthChanged() { m_dropNetworkThread->start(); log("Waiting 60s for network signal strength to change"); QVERIFY(::waitForSignal(m_systemNetworkInfo, SIGNAL(networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode, int)), 60 * 1000)); log("networkSignalStrengthChanged"); } void tst_QSystemNetworkInfo::networkStatusChanged() { m_dropNetworkThread->start(); log("Waiting 60s for network status to change"); QVERIFY(::waitForSignal(m_systemNetworkInfo, SIGNAL(networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus)), 60 * 1000)); log("networkStatusChanged"); } void tst_QSystemNetworkInfo::mobileCountryCodeChanged() { m_dropNetworkThread->start(); log("Waiting 60s for mobile country code to change"); QVERIFY(::waitForSignal(m_systemNetworkInfo, SIGNAL(currentMobileCountryCodeChanged(QString)), 60 * 1000)); log("currentMobileCountryCodeChanged"); } void tst_QSystemNetworkInfo::mobileNetworkCodeChanged() { m_dropNetworkThread->start(); log("Waiting 60s for mobile network code to change"); QVERIFY(::waitForSignal(m_systemNetworkInfo, SIGNAL(currentMobileNetworkCodeChanged(QString)), 60 * 1000)); log("currentMobileNetworkCodeChanged"); } void tst_QSystemNetworkInfo::networkNameChanged() { m_dropNetworkThread->start(); log("Waiting 60s for network name to change"); QVERIFY(::waitForSignal(m_systemNetworkInfo, SIGNAL(networkNameChanged(QSystemNetworkInfo::NetworkMode,QString)), 60 * 1000)); log("networkNameChanged"); } void tst_QSystemNetworkInfo::networkModeChanged() { m_dropNetworkThread->start(); log("Waiting 60s for network mode to change"); QVERIFY(::waitForSignal(m_systemNetworkInfo, SIGNAL(networkModeChanged(QSystemNetworkInfo::NetworkMode)), 60 * 1000)); log("networkModeChanged"); } QTEST_MAIN(tst_QSystemNetworkInfo) #include "tst_qsystemnetworkinfo_maemo.moc" <|endoftext|>
<commit_before>/* * Copyright 2014-2021 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> extern "C" { #include "media/aeron_udp_channel_transport.h" #include "media/aeron_udp_channel_transport_loss.h" #include "protocol/aeron_udp_protocol.h" #include "util/aeron_netutil.h" #if !defined(HAVE_STRUCT_MMSGHDR) struct mmsghdr { struct msghdr msg_hdr; unsigned int msg_len; }; #endif } #define TEMP_URL_LEN (128) class UdpChannelTransporTest : public testing::Test { public: UdpChannelTransporTest() = default; protected: void SetUp() override { aeron_driver_context_init(&m_driverContext); } void TearDown() override { aeron_driver_context_close(m_driverContext); } aeron_driver_context_t *m_driverContext = nullptr; }; void test_revc_func( aeron_udp_channel_data_paths_t *data_paths, aeron_udp_channel_transport_t *transport, void *receiver_clientd, void *endpoint_clientd, void *destination_clientd, uint8_t *buffer, size_t length, struct sockaddr_storage *addr, struct timespec *media_timestamp) { } TEST_F(UdpChannelTransporTest, shouldErrorWithInvalidSendAddress) { aeron_udp_channel_transport_bindings_t *transport_bindings = aeron_udp_channel_transport_bindings_load_media( "default"); aeron_udp_channel_data_paths_t data_paths = {}; ASSERT_NE( -1, aeron_udp_channel_data_paths_init( &data_paths, nullptr, nullptr, transport_bindings, test_revc_func, m_driverContext, AERON_UDP_CHANNEL_TRANSPORT_AFFINITY_SENDER)); ASSERT_NE(nullptr, transport_bindings) << aeron_errmsg(); struct sockaddr_in bind_addr = {}; struct sockaddr_in send_addr = {}; ASSERT_NE( -1, aeron_ip_addr_resolver("127.0.0.1", (struct sockaddr_storage*)&bind_addr, AF_INET, IPPROTO_UDP)); bind_addr.sin_port = 0; ASSERT_NE( -1, aeron_ip_addr_resolver("0.0.0.0", (struct sockaddr_storage*)&send_addr, AF_INET, IPPROTO_UDP)); send_addr.sin_port = 6666; aeron_udp_channel_transport_t transport = {}; ASSERT_NE(-1, transport_bindings->init_func( &transport, (struct sockaddr_storage*)&bind_addr, (struct sockaddr_storage*)nullptr, 0, 16, 65536, 65536, false, m_driverContext, AERON_UDP_CHANNEL_TRANSPORT_AFFINITY_SENDER)) << aeron_errmsg(); const char *data = "Hello World"; struct iovec message = {}; message.iov_base = static_cast<void *>(const_cast<char *>(data)); message.iov_len = static_cast<unsigned int>(strlen(data)); struct msghdr header = {}; header.msg_name = static_cast<void *>(&send_addr); header.msg_namelen = sizeof(send_addr); header.msg_iov = &message; header.msg_iovlen = 1; header.msg_control = nullptr; header.msg_controllen = 1; header.msg_flags = 389475; ASSERT_EQ(-1, transport_bindings->sendmsg_func(&data_paths, &transport, &header)) << aeron_errmsg(); } <commit_msg>[C] Spelling.<commit_after>/* * Copyright 2014-2021 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> extern "C" { #include "media/aeron_udp_channel_transport.h" #include "media/aeron_udp_channel_transport_loss.h" #include "protocol/aeron_udp_protocol.h" #include "util/aeron_netutil.h" #if !defined(HAVE_STRUCT_MMSGHDR) struct mmsghdr { struct msghdr msg_hdr; unsigned int msg_len; }; #endif } #define TEMP_URL_LEN (128) class UdpChannelTransportTest : public testing::Test { public: UdpChannelTransportTest() = default; protected: void SetUp() override { aeron_driver_context_init(&m_driverContext); } void TearDown() override { aeron_driver_context_close(m_driverContext); } aeron_driver_context_t *m_driverContext = nullptr; }; void test_revc_func( aeron_udp_channel_data_paths_t *data_paths, aeron_udp_channel_transport_t *transport, void *receiver_clientd, void *endpoint_clientd, void *destination_clientd, uint8_t *buffer, size_t length, struct sockaddr_storage *addr, struct timespec *media_timestamp) { } TEST_F(UdpChannelTransportTest, shouldErrorWithInvalidSendAddress) { aeron_udp_channel_transport_bindings_t *transport_bindings = aeron_udp_channel_transport_bindings_load_media( "default"); aeron_udp_channel_data_paths_t data_paths = {}; ASSERT_NE( -1, aeron_udp_channel_data_paths_init( &data_paths, nullptr, nullptr, transport_bindings, test_revc_func, m_driverContext, AERON_UDP_CHANNEL_TRANSPORT_AFFINITY_SENDER)); ASSERT_NE(nullptr, transport_bindings) << aeron_errmsg(); struct sockaddr_in bind_addr = {}; struct sockaddr_in send_addr = {}; ASSERT_NE( -1, aeron_ip_addr_resolver("127.0.0.1", (struct sockaddr_storage*)&bind_addr, AF_INET, IPPROTO_UDP)); bind_addr.sin_port = 0; ASSERT_NE( -1, aeron_ip_addr_resolver("0.0.0.0", (struct sockaddr_storage*)&send_addr, AF_INET, IPPROTO_UDP)); send_addr.sin_port = 6666; aeron_udp_channel_transport_t transport = {}; ASSERT_NE(-1, transport_bindings->init_func( &transport, (struct sockaddr_storage*)&bind_addr, (struct sockaddr_storage*)nullptr, 0, 16, 65536, 65536, false, m_driverContext, AERON_UDP_CHANNEL_TRANSPORT_AFFINITY_SENDER)) << aeron_errmsg(); const char *data = "Hello World"; struct iovec message = {}; message.iov_base = static_cast<void *>(const_cast<char *>(data)); message.iov_len = static_cast<unsigned int>(strlen(data)); struct msghdr header = {}; header.msg_name = static_cast<void *>(&send_addr); header.msg_namelen = sizeof(send_addr); header.msg_iov = &message; header.msg_iovlen = 1; header.msg_control = nullptr; header.msg_controllen = 1; header.msg_flags = 389475; ASSERT_EQ(-1, transport_bindings->sendmsg_func(&data_paths, &transport, &header)) << aeron_errmsg(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Nagoya University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <ros/ros.h> #include <geometry_msgs/Vector3Stamped.h> #include <geometry_msgs/PoseStamped.h> #include "vehicle_socket/CanInfo.h" namespace { ros::Publisher g_vel_publisher; ros::Publisher g_pose_publisher; void callbackFromCanInfo(const vehicle_socket::CanInfoConstPtr &msg) { geometry_msgs::Vector3Stamped vel; vel.header = msg->header; vel.vector.x = (msg->speed * 1000) / (60 * 60); // km/h -> m/s g_vel_publisher.publish(vel); } void callbackFromPoseStamped(const geometry_msgs::PoseStampedConstPtr &msg) { g_pose_publisher.publish(*msg); } void callbackFromVector3Stamped(const geometry_msgs::Vector3StampedConstPtr &msg) { g_vel_publisher.publish(*msg); } } // namespace int main(int argc, char **argv) { // set up ros ros::init(argc, argv, "vel_pose_mux"); ros::NodeHandle nh; ros::NodeHandle private_nh("~"); int32_t pose_mux_select, vel_mux_select; bool sim_mode; // setting params private_nh.param<int32_t>("pose_mux_select", pose_mux_select, int32_t(0)); //ROS_INFO_STREAM("pose_mux_select : " << pose_mux_select); private_nh.param<int32_t>("vel_mux_select", vel_mux_select, int32_t(1)); //ROS_INFO_STREAM("vel_mux_select : " << vel_mux_select); private_nh.param<bool>("sim_mode", sim_mode, false); //ROS_INFO_STREAM("sim_mode : " << sim_mode); // publish topic g_vel_publisher = nh.advertise<geometry_msgs::Vector3Stamped>("current_velocity", 10); g_pose_publisher = nh.advertise<geometry_msgs::PoseStamped>("current_pose", 10); // subscribe topic ros::Subscriber pose_subcscriber; ros::Subscriber vel_subcscriber; if (sim_mode) { vel_subcscriber = nh.subscribe("sim_velocity", 10, callbackFromVector3Stamped); pose_subcscriber = nh.subscribe("sim_pose", 10, callbackFromPoseStamped); } else { // pose switch (pose_mux_select) { case 0: // ndt_localizer { pose_subcscriber = nh.subscribe("ndt_pose", 10, callbackFromPoseStamped); break; } case 1: // gnss { pose_subcscriber = nh.subscribe("gnss_pose", 10, callbackFromPoseStamped); break; } default: break; } // velocity switch (vel_mux_select) { case 0: // ndt_localizer { vel_subcscriber = nh.subscribe("estimated_vel", 10, callbackFromVector3Stamped); break; } case 1: // CAN { vel_subcscriber = nh.subscribe("can_info", 10, callbackFromCanInfo); break; } default: break; } } ros::spin(); return 0; } <commit_msg>Add specific namespace<commit_after>/* * Copyright (c) 2015, Nagoya University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <ros/ros.h> #include <geometry_msgs/Vector3Stamped.h> #include <geometry_msgs/PoseStamped.h> #include "vehicle_socket/CanInfo.h" namespace vel_pose_mux { ros::Publisher g_vel_publisher; ros::Publisher g_pose_publisher; void callbackFromCanInfo(const vehicle_socket::CanInfoConstPtr &msg) { geometry_msgs::Vector3Stamped vel; vel.header = msg->header; vel.vector.x = (msg->speed * 1000) / (60 * 60); // km/h -> m/s g_vel_publisher.publish(vel); } void callbackFromPoseStamped(const geometry_msgs::PoseStampedConstPtr &msg) { g_pose_publisher.publish(*msg); } void callbackFromVector3Stamped(const geometry_msgs::Vector3StampedConstPtr &msg) { g_vel_publisher.publish(*msg); } } // namespace int main(int argc, char **argv) { // set up ros ros::init(argc, argv, "vel_pose_mux"); ros::NodeHandle nh; ros::NodeHandle private_nh("~"); int32_t pose_mux_select, vel_mux_select; bool sim_mode; // setting params private_nh.param<int32_t>("pose_mux_select", pose_mux_select, int32_t(0)); //ROS_INFO_STREAM("pose_mux_select : " << pose_mux_select); private_nh.param<int32_t>("vel_mux_select", vel_mux_select, int32_t(1)); //ROS_INFO_STREAM("vel_mux_select : " << vel_mux_select); private_nh.param<bool>("sim_mode", sim_mode, false); //ROS_INFO_STREAM("sim_mode : " << sim_mode); // publish topic g_vel_publisher = nh.advertise<geometry_msgs::Vector3Stamped>("current_velocity", 10); g_pose_publisher = nh.advertise<geometry_msgs::PoseStamped>("current_pose", 10); // subscribe topic ros::Subscriber pose_subcscriber; ros::Subscriber vel_subcscriber; if (sim_mode) { vel_subcscriber = nh.subscribe("sim_velocity", 10, callbackFromVector3Stamped); pose_subcscriber = nh.subscribe("sim_pose", 10, callbackFromPoseStamped); } else { // pose switch (pose_mux_select) { case 0: // ndt_localizer { pose_subcscriber = nh.subscribe("ndt_pose", 10, callbackFromPoseStamped); break; } case 1: // gnss { pose_subcscriber = nh.subscribe("gnss_pose", 10, callbackFromPoseStamped); break; } default: break; } // velocity switch (vel_mux_select) { case 0: // ndt_localizer { vel_subcscriber = nh.subscribe("estimated_vel", 10, callbackFromVector3Stamped); break; } case 1: // CAN { vel_subcscriber = nh.subscribe("can_info", 10, callbackFromCanInfo); break; } default: break; } } ros::spin(); return 0; } <|endoftext|>
<commit_before>#include "telnetpp/detail/routing_visitor.hpp" #include "telnetpp/options/naws/client.hpp" #include "telnetpp/options/naws.hpp" #include "telnetpp/protocol.hpp" #include "telnetpp/detail/registration.hpp" #include "expect_elements.hpp" #include <gtest/gtest.h> TEST(routing_visitor_test, text_routes_to_text_function) { telnetpp::detail::command_router cmd_router; telnetpp::detail::negotiation_router neg_router; telnetpp::detail::subnegotiation_router sub_router; std::string text; std::string expected_text = "expected text"; telnetpp::detail::routing_visitor visitor( [&text](auto &&new_text) -> std::vector<telnetpp::token> { text = new_text; return {}; }, cmd_router, neg_router, sub_router); telnetpp::element text_token(expected_text); boost::apply_visitor(visitor, text_token); ASSERT_EQ(expected_text, text); } TEST(routing_visitor_test, text_does_not_route_to_null_function) { telnetpp::detail::command_router cmd_router; telnetpp::detail::negotiation_router neg_router; telnetpp::detail::subnegotiation_router sub_router; telnetpp::detail::routing_visitor visitor( nullptr, cmd_router, neg_router, sub_router); telnetpp::element text_token(telnetpp::element("text token")); boost::apply_visitor(visitor, text_token); } TEST(routing_visitor_test, command_routes_to_command_router) { telnetpp::detail::command_router cmd_router; telnetpp::detail::negotiation_router neg_router; telnetpp::detail::subnegotiation_router sub_router; telnetpp::command cmd(0x00); telnetpp::command expected_command(telnetpp::ayt); cmd_router.register_route(expected_command, [&cmd](auto &&new_cmd) -> std::vector<telnetpp::token> { cmd = new_cmd; return {}; }); telnetpp::detail::routing_visitor visitor( [](auto &&) -> std::vector<telnetpp::token> { return {}; }, cmd_router, neg_router, sub_router); telnetpp::element cmd_token(expected_command); boost::apply_visitor(visitor, cmd_token); ASSERT_EQ(expected_command, cmd); } TEST(routing_visitor_test, negotiation_routes_to_negotiation_router) { telnetpp::detail::command_router cmd_router; telnetpp::detail::negotiation_router neg_router; telnetpp::detail::subnegotiation_router sub_router; telnetpp::options::naws::client client; client.activate(); bool state_changed = false; client.on_state_changed.connect( [&state_changed]() -> std::vector<telnetpp::token> { state_changed = true; return {}; }); telnetpp::detail::register_client_option(client, neg_router, sub_router); telnetpp::detail::routing_visitor visitor( [](auto &&) -> std::vector<telnetpp::token> { return {}; }, cmd_router, neg_router, sub_router); telnetpp::element neg_token( telnetpp::negotiation( telnetpp::will, telnetpp::options::naws::option)); boost::apply_visitor(visitor, neg_token); ASSERT_EQ(true, state_changed); ASSERT_EQ(true, client.is_active()); } TEST(routing_visitor_test, subnegotiation_routes_to_subnegotiation_router) { telnetpp::detail::command_router cmd_router; telnetpp::detail::negotiation_router neg_router; telnetpp::detail::subnegotiation_router sub_router; telnetpp::options::naws::client client; client.activate(); client.negotiate(telnetpp::will); telnetpp::u16 width = 0; telnetpp::u16 height = 0; client.on_window_size_changed.connect( [&width, &height](auto &&new_width, auto &&new_height) -> std::vector<telnetpp::token> { width = new_width; height = new_height; return {}; }); telnetpp::detail::register_route_from_subnegotiation_to_option( sub_router, client); telnetpp::detail::routing_visitor visitor( [](auto &&) -> std::vector<telnetpp::token> { return {}; }, cmd_router, neg_router, sub_router); telnetpp::element sub_token( telnetpp::subnegotiation( telnetpp::options::naws::option, {0, 80, 0, 24})); boost::apply_visitor(visitor, sub_token); telnetpp::u16 expected_width = 80; telnetpp::u16 expected_height = 24; ASSERT_EQ(expected_width, width); ASSERT_EQ(expected_height, height); } TEST(routing_visitor_test, subnegotiation_accumulates_responses) { telnetpp::detail::command_router cmd_router; telnetpp::detail::negotiation_router neg_router; telnetpp::detail::subnegotiation_router sub_router; telnetpp::options::naws::client client; telnetpp::detail::register_client_option(client, neg_router, sub_router); client.on_window_size_changed.connect( [&client](auto &&, auto &&) { return client.deactivate(); }); telnetpp::detail::routing_visitor visitor( [](auto &&) -> std::vector<telnetpp::token> { return {}; }, cmd_router, neg_router, sub_router); client.activate(); telnetpp::element do_negotiation_token( telnetpp::negotiation(telnetpp::will, telnetpp::options::naws::option)); expect_elements( {}, boost::apply_visitor(visitor, do_negotiation_token)); telnetpp::element sub_token( telnetpp::subnegotiation( telnetpp::options::naws::option, {0, 80, 0, 24})); expect_elements({ telnetpp::negotiation( telnetpp::dont, telnetpp::options::naws::option) }, boost::apply_visitor(visitor, sub_token)); } <commit_msg>Fix broken compile of routing test.<commit_after>#include "telnetpp/detail/routing_visitor.hpp" #include "telnetpp/options/naws/client.hpp" #include "telnetpp/protocol.hpp" #include "telnetpp/detail/registration.hpp" #include "expect_elements.hpp" #include <gtest/gtest.h> TEST(routing_visitor_test, text_routes_to_text_function) { telnetpp::detail::command_router cmd_router; telnetpp::detail::negotiation_router neg_router; telnetpp::detail::subnegotiation_router sub_router; std::string text; std::string expected_text = "expected text"; telnetpp::detail::routing_visitor visitor( [&text](auto &&new_text) -> std::vector<telnetpp::token> { text = new_text; return {}; }, cmd_router, neg_router, sub_router); telnetpp::element text_token(expected_text); boost::apply_visitor(visitor, text_token); ASSERT_EQ(expected_text, text); } TEST(routing_visitor_test, text_does_not_route_to_null_function) { telnetpp::detail::command_router cmd_router; telnetpp::detail::negotiation_router neg_router; telnetpp::detail::subnegotiation_router sub_router; telnetpp::detail::routing_visitor visitor( nullptr, cmd_router, neg_router, sub_router); telnetpp::element text_token(telnetpp::element("text token")); boost::apply_visitor(visitor, text_token); } TEST(routing_visitor_test, command_routes_to_command_router) { telnetpp::detail::command_router cmd_router; telnetpp::detail::negotiation_router neg_router; telnetpp::detail::subnegotiation_router sub_router; telnetpp::command cmd(0x00); telnetpp::command expected_command(telnetpp::ayt); cmd_router.register_route(expected_command, [&cmd](auto &&new_cmd) -> std::vector<telnetpp::token> { cmd = new_cmd; return {}; }); telnetpp::detail::routing_visitor visitor( [](auto &&) -> std::vector<telnetpp::token> { return {}; }, cmd_router, neg_router, sub_router); telnetpp::element cmd_token(expected_command); boost::apply_visitor(visitor, cmd_token); ASSERT_EQ(expected_command, cmd); } TEST(routing_visitor_test, negotiation_routes_to_negotiation_router) { telnetpp::detail::command_router cmd_router; telnetpp::detail::negotiation_router neg_router; telnetpp::detail::subnegotiation_router sub_router; telnetpp::options::naws::client client; client.activate(); bool state_changed = false; client.on_state_changed.connect( [&state_changed]() -> std::vector<telnetpp::token> { state_changed = true; return {}; }); telnetpp::detail::register_client_option(client, neg_router, sub_router); telnetpp::detail::routing_visitor visitor( [](auto &&) -> std::vector<telnetpp::token> { return {}; }, cmd_router, neg_router, sub_router); telnetpp::element neg_token( telnetpp::negotiation(telnetpp::will, client.option())); boost::apply_visitor(visitor, neg_token); ASSERT_EQ(true, state_changed); ASSERT_EQ(true, client.is_active()); } TEST(routing_visitor_test, subnegotiation_routes_to_subnegotiation_router) { telnetpp::detail::command_router cmd_router; telnetpp::detail::negotiation_router neg_router; telnetpp::detail::subnegotiation_router sub_router; telnetpp::options::naws::client client; client.activate(); client.negotiate(telnetpp::will); telnetpp::u16 width = 0; telnetpp::u16 height = 0; client.on_window_size_changed.connect( [&width, &height](auto &&new_width, auto &&new_height) -> std::vector<telnetpp::token> { width = new_width; height = new_height; return {}; }); telnetpp::detail::register_route_from_subnegotiation_to_option( sub_router, client); telnetpp::detail::routing_visitor visitor( [](auto &&) -> std::vector<telnetpp::token> { return {}; }, cmd_router, neg_router, sub_router); telnetpp::element sub_token( telnetpp::subnegotiation(client.option(), {0, 80, 0, 24})); boost::apply_visitor(visitor, sub_token); telnetpp::u16 expected_width = 80; telnetpp::u16 expected_height = 24; ASSERT_EQ(expected_width, width); ASSERT_EQ(expected_height, height); } TEST(routing_visitor_test, subnegotiation_accumulates_responses) { telnetpp::detail::command_router cmd_router; telnetpp::detail::negotiation_router neg_router; telnetpp::detail::subnegotiation_router sub_router; telnetpp::options::naws::client client; telnetpp::detail::register_client_option(client, neg_router, sub_router); client.on_window_size_changed.connect( [&client](auto &&, auto &&) { return client.deactivate(); }); telnetpp::detail::routing_visitor visitor( [](auto &&) -> std::vector<telnetpp::token> { return {}; }, cmd_router, neg_router, sub_router); client.activate(); telnetpp::element do_negotiation_token( telnetpp::negotiation(telnetpp::will, client.option())); expect_elements( {}, boost::apply_visitor(visitor, do_negotiation_token)); telnetpp::element sub_token( telnetpp::subnegotiation(client.option(), {0, 80, 0, 24})); expect_elements({ telnetpp::negotiation( telnetpp::dont, client.option()) }, boost::apply_visitor(visitor, sub_token)); } <|endoftext|>
<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__MULTI_STUDENT_T_HPP__ #define __STAN__PROB__DISTRIBUTIONS__MULTI_STUDENT_T_HPP__ #include <cstdlib> #include <boost/math/special_functions/gamma.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <stan/math/error_handling.hpp> #include <stan/math/matrix_error_handling.hpp> #include <stan/prob/constants.hpp> #include <stan/prob/traits.hpp> #include <stan/prob/distributions/multivariate/continuous/multi_normal.hpp> #include <stan/prob/distributions/univariate/continuous/inv_gamma.hpp> #include <boost/random/variate_generator.hpp> namespace stan { namespace prob { /** * Return the log of the multivariate Student t distribution * at the specified arguments. * * @tparam propto Carry out calculations up to a proportion */ template <bool propto, typename T_y, typename T_dof, typename T_loc, typename T_scale> typename boost::math::tools::promote_args<T_y,T_dof,T_loc,T_scale>::type multi_student_t_log(const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y, const T_dof& nu, const Eigen::Matrix<T_loc,Eigen::Dynamic,1>& mu, const Eigen::Matrix<T_scale, Eigen::Dynamic,Eigen::Dynamic>& Sigma) { static const char* function = "stan::prob::multi_student_t(%1%)"; using stan::math::check_size_match; using stan::math::check_finite; using stan::math::check_not_nan; using stan::math::check_symmetric; using stan::math::check_positive; using boost::math::tools::promote_args; using boost::math::lgamma; using stan::math::log_determinant_ldlt; using stan::math::mdivide_left_ldlt; using stan::math::LDLT_factor; typename promote_args<T_y,T_dof,T_loc,T_scale>::type lp(0.0); if (!check_size_match(function, y.size(), "Size of random variable", mu.size(), "size of location parameter", &lp)) return lp; if (!check_size_match(function, y.size(), "Size of random variable", Sigma.rows(), "rows of scale parameter", &lp)) return lp; if (!check_size_match(function, y.size(), "Size of random variable", Sigma.cols(), "columns of scale parameter", &lp)) return lp; if (!check_finite(function, mu, "Location parameter", &lp)) return lp; if (!check_not_nan(function, y, "Random variable", &lp)) return lp; if (!check_symmetric(function, Sigma, "Scale parameter", &lp)) return lp; LDLT_factor<T_scale,Eigen::Dynamic,Eigen::Dynamic> ldlt_Sigma(Sigma); if (!ldlt_Sigma.success()) { std::ostringstream message; message << "Scale matrix is not positive definite. " << "Sigma(0,0) is %1%."; std::string str(message.str()); stan::math::dom_err(function,Sigma(0,0),"Scale matrix",str.c_str(),"",&lp); return lp; } // allows infinities if (!check_not_nan(function, nu, "Degrees of freedom parameter", &lp)) return lp; if (!check_positive(function, nu, "Degrees of freedom parameter", &lp)) return lp; using boost::math::isinf; if (isinf(nu)) // already checked nu > 0 return multi_normal_log(y,mu,Sigma); double d = y.size(); if (include_summand<propto,T_dof>::value) { lp += lgamma(0.5 * (nu + d)); lp -= lgamma(0.5 * nu); lp -= (0.5 * d) * log(nu); } if (include_summand<propto>::value) lp -= (0.5 * d) * LOG_PI; using stan::math::multiply; using stan::math::dot_product; using stan::math::subtract; using Eigen::Array; if (include_summand<propto,T_scale>::value) { lp -= 0.5*log_determinant_ldlt(ldlt_Sigma); } if (include_summand<propto,T_y,T_dof,T_loc,T_scale>::value) { Eigen::Matrix<typename promote_args<T_y,T_loc>::type, Eigen::Dynamic, 1> y_minus_mu = subtract(y,mu); Eigen::Matrix<typename promote_args<T_scale,T_y,T_loc>::type, Eigen::Dynamic, 1> invSigma_dy = mdivide_left_ldlt(ldlt_Sigma, y_minus_mu); lp -= 0.5 * (nu + d) * log(1.0 + dot_product(y_minus_mu,invSigma_dy) / nu); } return lp; } template <typename T_y, typename T_dof, typename T_loc, typename T_scale> inline typename boost::math::tools::promote_args<T_y,T_dof,T_loc,T_scale>::type multi_student_t_log(const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y, const T_dof& nu, const Eigen::Matrix<T_loc,Eigen::Dynamic,1>& mu, const Eigen::Matrix<T_scale, Eigen::Dynamic,Eigen::Dynamic>& Sigma) { return multi_student_t_log<false>(y,nu,mu,Sigma); } template <class RNG> inline Eigen::VectorXd multi_student_t_rng(const double nu, const Eigen::Matrix<double,Eigen::Dynamic,1>& mu, const Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic>& s, RNG& rng) { static const char* function = "stan::prob::multi_student_t_rng(%1%)"; using stan::math::check_finite; using stan::math::check_not_nan; using stan::math::check_symmetric; using stan::math::check_positive; check_finite(function, mu, "Location parameter"); check_symmetric(function, s, "Scale parameter"); check_not_nan(function, nu, "Degrees of freedom parameter"); check_positive(function, nu, "Degrees of freedom parameter"); Eigen::VectorXd z(s.cols()); z.setZero(); double w = stan::prob::inv_gamma_rng(nu / 2, nu / 2, rng); return mu + std::sqrt(w) * stan::prob::multi_normal_rng(z, s, rng); } } } #endif <commit_msg>Use trace_inv_quad_form_ldlt() in multi_student_t.<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__MULTI_STUDENT_T_HPP__ #define __STAN__PROB__DISTRIBUTIONS__MULTI_STUDENT_T_HPP__ #include <cstdlib> #include <boost/math/special_functions/gamma.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <stan/math/error_handling.hpp> #include <stan/math/matrix_error_handling.hpp> #include <stan/prob/constants.hpp> #include <stan/prob/traits.hpp> #include <stan/prob/distributions/multivariate/continuous/multi_normal.hpp> #include <stan/prob/distributions/univariate/continuous/inv_gamma.hpp> #include <boost/random/variate_generator.hpp> namespace stan { namespace prob { /** * Return the log of the multivariate Student t distribution * at the specified arguments. * * @tparam propto Carry out calculations up to a proportion */ template <bool propto, typename T_y, typename T_dof, typename T_loc, typename T_scale> typename boost::math::tools::promote_args<T_y,T_dof,T_loc,T_scale>::type multi_student_t_log(const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y, const T_dof& nu, const Eigen::Matrix<T_loc,Eigen::Dynamic,1>& mu, const Eigen::Matrix<T_scale, Eigen::Dynamic,Eigen::Dynamic>& Sigma) { static const char* function = "stan::prob::multi_student_t(%1%)"; using stan::math::check_size_match; using stan::math::check_finite; using stan::math::check_not_nan; using stan::math::check_symmetric; using stan::math::check_positive; using boost::math::tools::promote_args; using boost::math::lgamma; using stan::math::log_determinant_ldlt; using stan::math::LDLT_factor; typename promote_args<T_y,T_dof,T_loc,T_scale>::type lp(0.0); if (!check_size_match(function, y.size(), "Size of random variable", mu.size(), "size of location parameter", &lp)) return lp; if (!check_size_match(function, y.size(), "Size of random variable", Sigma.rows(), "rows of scale parameter", &lp)) return lp; if (!check_size_match(function, y.size(), "Size of random variable", Sigma.cols(), "columns of scale parameter", &lp)) return lp; if (!check_finite(function, mu, "Location parameter", &lp)) return lp; if (!check_not_nan(function, y, "Random variable", &lp)) return lp; if (!check_symmetric(function, Sigma, "Scale parameter", &lp)) return lp; LDLT_factor<T_scale,Eigen::Dynamic,Eigen::Dynamic> ldlt_Sigma(Sigma); if (!ldlt_Sigma.success()) { std::ostringstream message; message << "Scale matrix is not positive definite. " << "Sigma(0,0) is %1%."; std::string str(message.str()); stan::math::dom_err(function,Sigma(0,0),"Scale matrix",str.c_str(),"",&lp); return lp; } // allows infinities if (!check_not_nan(function, nu, "Degrees of freedom parameter", &lp)) return lp; if (!check_positive(function, nu, "Degrees of freedom parameter", &lp)) return lp; using boost::math::isinf; if (isinf(nu)) // already checked nu > 0 return multi_normal_log(y,mu,Sigma); double d = y.size(); if (include_summand<propto,T_dof>::value) { lp += lgamma(0.5 * (nu + d)); lp -= lgamma(0.5 * nu); lp -= (0.5 * d) * log(nu); } if (include_summand<propto>::value) lp -= (0.5 * d) * LOG_PI; using stan::math::multiply; using stan::math::dot_product; using stan::math::subtract; using Eigen::Array; if (include_summand<propto,T_scale>::value) { lp -= 0.5*log_determinant_ldlt(ldlt_Sigma); } if (include_summand<propto,T_y,T_dof,T_loc,T_scale>::value) { Eigen::Matrix<typename promote_args<T_y,T_loc>::type, Eigen::Dynamic, 1> y_minus_mu = subtract(y,mu); lp -= 0.5 * (nu + d) * log(1.0 + trace_inv_quad_form_ldlt(ldlt_Sigma,y_minus_mu) / nu); } return lp; } template <typename T_y, typename T_dof, typename T_loc, typename T_scale> inline typename boost::math::tools::promote_args<T_y,T_dof,T_loc,T_scale>::type multi_student_t_log(const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y, const T_dof& nu, const Eigen::Matrix<T_loc,Eigen::Dynamic,1>& mu, const Eigen::Matrix<T_scale, Eigen::Dynamic,Eigen::Dynamic>& Sigma) { return multi_student_t_log<false>(y,nu,mu,Sigma); } template <class RNG> inline Eigen::VectorXd multi_student_t_rng(const double nu, const Eigen::Matrix<double,Eigen::Dynamic,1>& mu, const Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic>& s, RNG& rng) { static const char* function = "stan::prob::multi_student_t_rng(%1%)"; using stan::math::check_finite; using stan::math::check_not_nan; using stan::math::check_symmetric; using stan::math::check_positive; check_finite(function, mu, "Location parameter"); check_symmetric(function, s, "Scale parameter"); check_not_nan(function, nu, "Degrees of freedom parameter"); check_positive(function, nu, "Degrees of freedom parameter"); Eigen::VectorXd z(s.cols()); z.setZero(); double w = stan::prob::inv_gamma_rng(nu / 2, nu / 2, rng); return mu + std::sqrt(w) * stan::prob::multi_normal_rng(z, s, rng); } } } #endif <|endoftext|>
<commit_before>#include "catch.hpp" #include <iostream> #include <exception> // std::bad_function_call, std::runtime_error #include <thread> // std::thread, std::this_thread::yield #include <mutex> // std::mutex, std::unique_lock #include <condition_variable> // std::condition_variable #include <functional> // std::function class EventThreader { public: std::condition_variable event_waiter; std::condition_variable calling_waiter; std::unique_lock<std::mutex>* event_lock = nullptr; std::unique_lock<std::mutex>* calling_lock = nullptr; std::mutex mtx; std::mutex allocation_mtx; std::thread event_thread; void switchToCallingThread(); bool require_switch_from_event = false; std::function<void(void)> event_cleanup; std::runtime_error* exception_from_the_event_thread; void deallocate(); public: EventThreader(std::function<void (std::function<void (void)>)> func); ~EventThreader(); void switchToEventThread(); void join(); void setEventCleanup(std::function<void(void)>); }; EventThreader::EventThreader(std::function<void (std::function<void (void)>)> func) { } EventThreader::~EventThreader() { } void EventThreader::deallocate() { } void EventThreader::switchToCallingThread() { } void EventThreader::switchToEventThread() { } void EventThreader::join() { } void EventThreader::setEventCleanup(std::function<void(void)> cleanup) { event_cleanup = cleanup; } TEST_CASE( "EventThreader", "[EventThreader]" ) { std::stringstream ss; SECTION("Finding the error") { EventThreader et([](std::function<void(void)> f){}); // class variables std::mutex mtx; bool require_switch_from_event = false; std::function<void(void)> event_cleanup; std::runtime_error* exception_from_the_event_thread; // class functions auto deallocate = [&]() { et.allocation_mtx.lock(); if (exception_from_the_event_thread != nullptr) { delete exception_from_the_event_thread; exception_from_the_event_thread = nullptr; } if (et.calling_lock != nullptr) { delete et.calling_lock; et.calling_lock = nullptr; } if (et.event_lock != nullptr) { delete et.event_lock; et.event_lock = nullptr; } et.allocation_mtx.unlock(); }; auto join = [&]() { et.allocation_mtx.lock(); delete et.calling_lock; // remove lock on this thread, allow event to run et.calling_lock = nullptr; et.allocation_mtx.unlock(); if (et.event_lock != nullptr) { et.event_waiter.notify_one(); std::this_thread::yield(); } et.event_thread.join(); if (exception_from_the_event_thread != nullptr) { /* an exception occured */ std::runtime_error e_copy(exception_from_the_event_thread->what()); et.allocation_mtx.lock(); delete exception_from_the_event_thread; exception_from_the_event_thread = nullptr; et.allocation_mtx.unlock(); throw e_copy; } deallocate(); }; auto switchToCallingThread = [&]() { if (!require_switch_from_event) { throw std::runtime_error("switch to calling not matched with a switch to event"); } require_switch_from_event = false; /* switch to calling */ et.calling_waiter.notify_one(); std::this_thread::yield(); et.event_waiter.wait(*(et.event_lock)); std::this_thread::yield(); /* back from calling */ }; auto switchToEventThread= [&]() { if (require_switch_from_event) { throw std::runtime_error("switch to event not matched with a switch to calling"); } require_switch_from_event = true; /* switch to event */ et.event_waiter.notify_one(); std::this_thread::yield(); et.calling_waiter.wait(*et.calling_lock); std::this_thread::yield(); /* back from event */ if (require_switch_from_event) { /* this exception is thrown if switchToCallingThread() was not used, which means the thread ended */ join(); } }; /* Example of most basic use */ auto f = [&ss](std::function<void(void)> switchToMainThread){ for(int i = 0; i < 100; i++) { ss << "*"; } switchToMainThread(); for(int i = 0; i < 50; i++) { ss << "*"; } switchToMainThread(); }; std::function<void (std::function<void (void)>)> func = f; // Start construction et.allocation_mtx.lock(); exception_from_the_event_thread = nullptr; et.event_lock = nullptr; et.calling_lock = nullptr; et.calling_lock = new std::unique_lock<std::mutex>(mtx); et.allocation_mtx.unlock(); exception_from_the_event_thread = nullptr; event_cleanup = [](){}; // empty function auto event = [&](){ /* mtx force switch to calling - blocked by the mutex */ et.allocation_mtx.lock(); et.event_lock = new std::unique_lock<std::mutex>(mtx); et.allocation_mtx.unlock(); et.calling_waiter.notify_one(); et.event_waiter.wait(*(et.event_lock)); std::this_thread::yield(); try { func([&](){switchToCallingThread();}); if (require_switch_from_event) { // the event has ended, but not ready to join // rejoin the calling thread after dealing with this exception throw std::runtime_error("switch to event not matched with a switch to calling"); } } catch (const std::runtime_error &e) { /* report the exception to the calling thread */ et.allocation_mtx.lock(); exception_from_the_event_thread = new std::runtime_error(e); et.allocation_mtx.unlock(); et.calling_waiter.notify_one(); std::this_thread::yield(); } et.allocation_mtx.lock(); delete et.event_lock; et.event_lock = nullptr; et.allocation_mtx.unlock(); event_cleanup(); }; et.event_thread = std::thread(event); std::this_thread::yield(); et.calling_waiter.wait(*(et.calling_lock)); std::this_thread::yield(); // End constuction //EventThreader et(f); switchToEventThread(); for(int i = 0; i < 75; i++) { ss << "$"; } switchToEventThread(); for(int i = 0; i < 25; i++) { ss << "$"; } join(); /* Generate what the result should look like */ std::string requirement; for(int i = 0; i < 100; i++) { requirement += "*"; } for(int i = 0; i < 75; i++) { requirement += "$"; } for(int i = 0; i < 50; i++) { requirement += "*"; } for(int i = 0; i < 25; i++) { requirement += "$"; } REQUIRE( requirement == ss.str()); deallocate(); } /* SECTION("Abitrary use") { // Example of most basic use auto f = [&ss](std::function<void(void)> switchToMainThread){ for(int i = 0; i < 100; i++) { ss << "*"; } switchToMainThread(); for(int i = 0; i < 50; i++) { ss << "*"; } switchToMainThread(); }; EventThreader et(f); switchToEventThread(); for(int i = 0; i < 75; i++) { ss << "$"; } switchToEventThread(); for(int i = 0; i < 25; i++) { ss << "$"; } join(); // Generate what the result should look like std::string requirement; for(int i = 0; i < 100; i++) { requirement += "*"; } for(int i = 0; i < 75; i++) { requirement += "$"; } for(int i = 0; i < 50; i++) { requirement += "*"; } for(int i = 0; i < 25; i++) { requirement += "$"; } REQUIRE( requirement == ss.str()); } */ } <commit_msg>moving lock ptrs<commit_after>#include "catch.hpp" #include <iostream> #include <exception> // std::bad_function_call, std::runtime_error #include <thread> // std::thread, std::this_thread::yield #include <mutex> // std::mutex, std::unique_lock #include <condition_variable> // std::condition_variable #include <functional> // std::function class EventThreader { public: std::condition_variable event_waiter; std::condition_variable calling_waiter; std::unique_lock<std::mutex>* event_lock = nullptr; std::unique_lock<std::mutex>* calling_lock = nullptr; std::mutex mtx; std::mutex allocation_mtx; std::thread event_thread; void switchToCallingThread(); bool require_switch_from_event = false; std::function<void(void)> event_cleanup; std::runtime_error* exception_from_the_event_thread; void deallocate(); public: EventThreader(std::function<void (std::function<void (void)>)> func); ~EventThreader(); void switchToEventThread(); void join(); void setEventCleanup(std::function<void(void)>); }; EventThreader::EventThreader(std::function<void (std::function<void (void)>)> func) { } EventThreader::~EventThreader() { } void EventThreader::deallocate() { } void EventThreader::switchToCallingThread() { } void EventThreader::switchToEventThread() { } void EventThreader::join() { } void EventThreader::setEventCleanup(std::function<void(void)> cleanup) { event_cleanup = cleanup; } TEST_CASE( "EventThreader", "[EventThreader]" ) { std::stringstream ss; SECTION("Finding the error") { EventThreader et([](std::function<void(void)> f){}); // class variables std::mutex mtx; std::function<void(void)> event_cleanup; std::runtime_error* exception_from_the_event_thread; // class functions auto deallocate = [&]() { et.allocation_mtx.lock(); if (exception_from_the_event_thread != nullptr) { delete exception_from_the_event_thread; exception_from_the_event_thread = nullptr; } if (et.calling_lock != nullptr) { delete et.calling_lock; et.calling_lock = nullptr; } if (et.event_lock != nullptr) { delete et.event_lock; et.event_lock = nullptr; } et.allocation_mtx.unlock(); }; auto join = [&]() { et.allocation_mtx.lock(); delete et.calling_lock; // remove lock on this thread, allow event to run et.calling_lock = nullptr; et.allocation_mtx.unlock(); if (et.event_lock != nullptr) { et.event_waiter.notify_one(); std::this_thread::yield(); } et.event_thread.join(); if (exception_from_the_event_thread != nullptr) { /* an exception occured */ std::runtime_error e_copy(exception_from_the_event_thread->what()); et.allocation_mtx.lock(); delete exception_from_the_event_thread; exception_from_the_event_thread = nullptr; et.allocation_mtx.unlock(); throw e_copy; } deallocate(); }; auto switchToCallingThread = [&]() { if (!et.require_switch_from_event) { throw std::runtime_error("switch to calling not matched with a switch to event"); } et.require_switch_from_event = false; /* switch to calling */ et.calling_waiter.notify_one(); std::this_thread::yield(); et.event_waiter.wait(*(et.event_lock)); std::this_thread::yield(); /* back from calling */ }; auto switchToEventThread= [&]() { if (et.require_switch_from_event) { throw std::runtime_error("switch to event not matched with a switch to calling"); } et.require_switch_from_event = true; /* switch to event */ et.event_waiter.notify_one(); std::this_thread::yield(); et.calling_waiter.wait(*et.calling_lock); std::this_thread::yield(); /* back from event */ if (et.require_switch_from_event) { /* this exception is thrown if switchToCallingThread() was not used, which means the thread ended */ join(); } }; /* Example of most basic use */ auto f = [&ss](std::function<void(void)> switchToMainThread){ for(int i = 0; i < 100; i++) { ss << "*"; } switchToMainThread(); for(int i = 0; i < 50; i++) { ss << "*"; } switchToMainThread(); }; std::function<void (std::function<void (void)>)> func = f; // Start construction et.allocation_mtx.lock(); exception_from_the_event_thread = nullptr; et.event_lock = nullptr; et.calling_lock = nullptr; et.calling_lock = new std::unique_lock<std::mutex>(mtx); et.allocation_mtx.unlock(); exception_from_the_event_thread = nullptr; event_cleanup = [](){}; // empty function auto event = [&](){ /* mtx force switch to calling - blocked by the mutex */ et.allocation_mtx.lock(); et.event_lock = new std::unique_lock<std::mutex>(mtx); et.allocation_mtx.unlock(); et.calling_waiter.notify_one(); et.event_waiter.wait(*(et.event_lock)); std::this_thread::yield(); try { func([&](){switchToCallingThread();}); if (et.require_switch_from_event) { // the event has ended, but not ready to join // rejoin the calling thread after dealing with this exception throw std::runtime_error("switch to event not matched with a switch to calling"); } } catch (const std::runtime_error &e) { /* report the exception to the calling thread */ et.allocation_mtx.lock(); exception_from_the_event_thread = new std::runtime_error(e); et.allocation_mtx.unlock(); et.calling_waiter.notify_one(); std::this_thread::yield(); } et.allocation_mtx.lock(); delete et.event_lock; et.event_lock = nullptr; et.allocation_mtx.unlock(); event_cleanup(); }; et.event_thread = std::thread(event); std::this_thread::yield(); et.calling_waiter.wait(*(et.calling_lock)); std::this_thread::yield(); // End constuction //EventThreader et(f); switchToEventThread(); for(int i = 0; i < 75; i++) { ss << "$"; } switchToEventThread(); for(int i = 0; i < 25; i++) { ss << "$"; } join(); /* Generate what the result should look like */ std::string requirement; for(int i = 0; i < 100; i++) { requirement += "*"; } for(int i = 0; i < 75; i++) { requirement += "$"; } for(int i = 0; i < 50; i++) { requirement += "*"; } for(int i = 0; i < 25; i++) { requirement += "$"; } REQUIRE( requirement == ss.str()); deallocate(); } /* SECTION("Abitrary use") { // Example of most basic use auto f = [&ss](std::function<void(void)> switchToMainThread){ for(int i = 0; i < 100; i++) { ss << "*"; } switchToMainThread(); for(int i = 0; i < 50; i++) { ss << "*"; } switchToMainThread(); }; EventThreader et(f); switchToEventThread(); for(int i = 0; i < 75; i++) { ss << "$"; } switchToEventThread(); for(int i = 0; i < 25; i++) { ss << "$"; } join(); // Generate what the result should look like std::string requirement; for(int i = 0; i < 100; i++) { requirement += "*"; } for(int i = 0; i < 75; i++) { requirement += "$"; } for(int i = 0; i < 50; i++) { requirement += "*"; } for(int i = 0; i < 25; i++) { requirement += "$"; } REQUIRE( requirement == ss.str()); } */ } <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/connection_queue.hpp" #include "libtorrent/http_connection.hpp" #include "setup_transfer.hpp" #include <fstream> #include <boost/optional.hpp> using namespace libtorrent; io_service ios; connection_queue cq(ios); int connect_handler_called = 0; int handler_called = 0; int data_size = 0; int http_status = 0; error_code g_error_code; char data_buffer[4000]; void print_http_header(http_parser const& p) { std::cerr << " < " << p.status_code() << " " << p.message() << std::endl; for (std::map<std::string, std::string>::const_iterator i = p.headers().begin(), end(p.headers().end()); i != end; ++i) { std::cerr << " < " << i->first << ": " << i->second << std::endl; } } void http_connect_handler(http_connection& c) { ++connect_handler_called; TEST_CHECK(c.socket().is_open()); std::cerr << "connected to: " << c.socket().remote_endpoint() << std::endl; TEST_CHECK(c.socket().remote_endpoint().address() == address::from_string("127.0.0.1")); } void http_handler(error_code const& ec, http_parser const& parser , char const* data, int size, http_connection& c) { ++handler_called; data_size = size; g_error_code = ec; if (parser.header_finished()) { http_status = parser.status_code(); if (http_status == 200) { TEST_CHECK(memcmp(data, data_buffer, size) == 0); } } print_http_header(parser); cq.close(); } void reset_globals() { connect_handler_called = 0; handler_called = 0; data_size = 0; http_status = 0; g_error_code = error_code(); } void run_test(std::string const& url, int size, int status, int connected , boost::optional<error_code> ec, proxy_settings const& ps) { reset_globals(); std::cerr << " ===== TESTING: " << url << " =====" << std::endl; boost::shared_ptr<http_connection> h(new http_connection(ios, cq , &::http_handler, true, &::http_connect_handler)); h->get(url, seconds(5), 0, &ps); ios.reset(); ios.run(); std::cerr << "connect_handler_called: " << connect_handler_called << std::endl; std::cerr << "handler_called: " << handler_called << std::endl; std::cerr << "status: " << http_status << std::endl; std::cerr << "size: " << data_size << std::endl; std::cerr << "error_code: " << g_error_code.message() << std::endl; TEST_CHECK(connect_handler_called == connected); TEST_CHECK(handler_called == 1); TEST_CHECK(data_size == size || size == -1); TEST_CHECK(!ec || g_error_code == *ec); TEST_CHECK(http_status == status || status == -1); } void run_suite(std::string const& protocol, proxy_settings const& ps) { if (ps.type != proxy_settings::none) { start_proxy(ps.port, ps.type); } char const* test_name[] = {"no", "SOCKS4", "SOCKS5" , "SOCKS5 password protected", "HTTP", "HTTP password protected"}; std::cout << "\n\n********************** using " << test_name[ps.type] << " proxy **********************\n" << std::endl; typedef boost::optional<error_code> err; // this requires the hosts file to be modified // run_test(protocol + "://test.dns.ts:8001/test_file", 3216, 200, 1, error_code(), ps); run_test(protocol + "://127.0.0.1:8001/relative/redirect", 3216, 200, 2, error_code(), ps); run_test(protocol + "://127.0.0.1:8001/redirect", 3216, 200, 2, error_code(), ps); run_test(protocol + "://127.0.0.1:8001/infinite_redirect", 0, 301, 6, error_code(), ps); run_test(protocol + "://127.0.0.1:8001/test_file", 3216, 200, 1, error_code(), ps); run_test(protocol + "://127.0.0.1:8001/test_file.gz", 3216, 200, 1, error_code(), ps); run_test(protocol + "://127.0.0.1:8001/non-existing-file", -1, 404, 1, err(), ps); // if we're going through an http proxy, we won't get the same error as if the hostname // resolution failed if ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != "https") run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, 502, 1, err(), ps); else run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, -1, 0, err(libtorrent::asio::error::host_not_found), ps); if (ps.type != proxy_settings::none) stop_proxy(ps.port); } int test_main() { std::srand(std::time(0)); std::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand); std::ofstream("test_file").write(data_buffer, 3216); std::system("gzip -9 -c test_file > test_file.gz"); proxy_settings ps; ps.hostname = "127.0.0.1"; ps.port = 8034; ps.username = "testuser"; ps.password = "testpass"; start_web_server(8001); for (int i = 0; i < 5; ++i) { ps.type = (proxy_settings::proxy_type)i; run_suite("http", ps); } stop_web_server(8001); #ifdef TORRENT_USE_OPENSSL start_web_server(8001, true); for (int i = 0; i < 5; ++i) { ps.type = (proxy_settings::proxy_type)i; run_suite("https", ps); } stop_web_server(8001); #endif std::remove("test_file"); return 0; } <commit_msg>fixed http_connection test<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/connection_queue.hpp" #include "libtorrent/http_connection.hpp" #include "setup_transfer.hpp" #include <fstream> #include <boost/optional.hpp> using namespace libtorrent; io_service ios; connection_queue cq(ios); int connect_handler_called = 0; int handler_called = 0; int data_size = 0; int http_status = 0; error_code g_error_code; char data_buffer[4000]; void print_http_header(http_parser const& p) { std::cerr << " < " << p.status_code() << " " << p.message() << std::endl; for (std::map<std::string, std::string>::const_iterator i = p.headers().begin(), end(p.headers().end()); i != end; ++i) { std::cerr << " < " << i->first << ": " << i->second << std::endl; } } void http_connect_handler(http_connection& c) { ++connect_handler_called; TEST_CHECK(c.socket().is_open()); std::cerr << "connected to: " << c.socket().remote_endpoint() << std::endl; TEST_CHECK(c.socket().remote_endpoint().address() == address::from_string("127.0.0.1")); } void http_handler(error_code const& ec, http_parser const& parser , char const* data, int size, http_connection& c) { ++handler_called; data_size = size; g_error_code = ec; if (parser.header_finished()) { http_status = parser.status_code(); if (http_status == 200) { TEST_CHECK(memcmp(data, data_buffer, size) == 0); } } print_http_header(parser); cq.close(); } void reset_globals() { connect_handler_called = 0; handler_called = 0; data_size = 0; http_status = 0; g_error_code = error_code(); } void run_test(std::string const& url, int size, int status, int connected , boost::optional<error_code> ec, proxy_settings const& ps) { reset_globals(); std::cerr << " ===== TESTING: " << url << " =====" << std::endl; boost::shared_ptr<http_connection> h(new http_connection(ios, cq , &::http_handler, true, &::http_connect_handler)); h->get(url, seconds(5), 0, &ps); ios.reset(); ios.run(); std::cerr << "connect_handler_called: " << connect_handler_called << std::endl; std::cerr << "handler_called: " << handler_called << std::endl; std::cerr << "status: " << http_status << std::endl; std::cerr << "size: " << data_size << std::endl; std::cerr << "error_code: " << g_error_code.message() << std::endl; TEST_CHECK(connect_handler_called == connected); TEST_CHECK(handler_called == 1); TEST_CHECK(data_size == size || size == -1); TEST_CHECK(!ec || g_error_code == *ec); TEST_CHECK(http_status == status || status == -1); } void run_suite(std::string const& protocol, proxy_settings const& ps) { if (ps.type != proxy_settings::none) { start_proxy(ps.port, ps.type); } char const* test_name[] = {"no", "SOCKS4", "SOCKS5" , "SOCKS5 password protected", "HTTP", "HTTP password protected"}; std::cout << "\n\n********************** using " << test_name[ps.type] << " proxy **********************\n" << std::endl; typedef boost::optional<error_code> err; // this requires the hosts file to be modified // run_test(protocol + "://test.dns.ts:8001/test_file", 3216, 200, 1, error_code(), ps); run_test(protocol + "://127.0.0.1:8001/relative/redirect", 3216, 200, 2, error_code(), ps); run_test(protocol + "://127.0.0.1:8001/redirect", 3216, 200, 2, error_code(), ps); run_test(protocol + "://127.0.0.1:8001/infinite_redirect", 0, 301, 6, error_code(), ps); run_test(protocol + "://127.0.0.1:8001/test_file", 3216, 200, 1, error_code(), ps); run_test(protocol + "://127.0.0.1:8001/test_file.gz", 3216, 200, 1, error_code(), ps); run_test(protocol + "://127.0.0.1:8001/non-existing-file", -1, 404, 1, err(), ps); // if we're going through an http proxy, we won't get the same error as if the hostname // resolution failed if ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != "https") run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, 502, 1, err(), ps); else run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, -1, 0, err(), ps); if (ps.type != proxy_settings::none) stop_proxy(ps.port); } int test_main() { std::srand(std::time(0)); std::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand); std::ofstream("test_file").write(data_buffer, 3216); std::system("gzip -9 -c test_file > test_file.gz"); proxy_settings ps; ps.hostname = "127.0.0.1"; ps.port = 8034; ps.username = "testuser"; ps.password = "testpass"; start_web_server(8001); for (int i = 0; i < 5; ++i) { ps.type = (proxy_settings::proxy_type)i; run_suite("http", ps); } stop_web_server(8001); #ifdef TORRENT_USE_OPENSSL start_web_server(8001, true); for (int i = 0; i < 5; ++i) { ps.type = (proxy_settings::proxy_type)i; run_suite("https", ps); } stop_web_server(8001); #endif std::remove("test_file"); return 0; } <|endoftext|>
<commit_before>/* Totem Cone plugin * * Copyright © 2004 Bastien Nocera <hadess@hadess.net> * Copyright © 2002 David A. Schleef <ds@schleef.org> * Copyright © 2006, 2008 Christian Persch * * 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., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. */ #include <config.h> #include <string.h> #include <glib.h> #include "totemPlugin.h" #include "totemConePlaylist.h" static const char *propertyNames[] = { "isPlaying", "items" }; static const char *methodNames[] = { "add", "next", "play", "playItem", "prev", "removeItem", "stop", "togglePause" }; TOTEM_IMPLEMENT_NPCLASS (totemConePlaylist, propertyNames, G_N_ELEMENTS (propertyNames), methodNames, G_N_ELEMENTS (methodNames), NULL); totemConePlaylist::totemConePlaylist (NPP aNPP) : totemNPObject (aNPP) { TOTEM_LOG_CTOR (); } totemConePlaylist::~totemConePlaylist () { TOTEM_LOG_DTOR (); } bool totemConePlaylist::InvokeByIndex (int aIndex, const NPVariant *argv, uint32_t argc, NPVariant *_result) { TOTEM_LOG_INVOKE (aIndex, totemConePlaylist); switch (Methods (aIndex)) { case eAdd: { /* long add (in AUTF8String MRL, [in AUTF8String name, in AUTF8String options]); */ if (!CheckArgc (argc, 1, 3)) return false; NPString mrl; if (!GetNPStringFromArguments (argv, argc, 0, mrl)) return false; NPString title; if (argc != 3 || !GetNPStringFromArguments (argv, argc, 1, title)) title.UTF8Characters = NULL; NPString options; if (argc != 3 || !GetNPStringFromArguments (argv, argc, 2, options)) options.UTF8Characters = NULL; //FIXME handle options as array //http://wiki.videolan.org/Documentation:WebPlugin#Playlist_object char *subtitle = NULL; if (options.UTF8Characters && options.UTF8Length) { char *str, **items; guint i; str = g_strndup (options.UTF8Characters, options.UTF8Length); items = g_strsplit (str, " ", -1); g_free (str); for (i = 0; items[i] != NULL; i++) { if (g_str_has_prefix (items[i], ":sub-file=")) { subtitle = g_strdup (items[i] + strlen (":sub-file=")); break; } } g_strfreev (items); } Plugin()->AddItem (mrl, title, subtitle); g_free (subtitle); //FIXME we're supposed to return a unique number here return Int32Variant (_result, 1); } case ePlay: Plugin()->Command (TOTEM_COMMAND_PLAY); return VoidVariant (_result); case eStop: Plugin()->Command (TOTEM_COMMAND_STOP); return VoidVariant (_result); case eNext: case ePlayItem: case ePrev: case eRemoveItem: case eTogglePause: TOTEM_WARN_INVOKE_UNIMPLEMENTED (aIndex, totemConePlaylist); return VoidVariant (_result); } return false; } bool totemConePlaylist::GetPropertyByIndex (int aIndex, NPVariant *_result) { TOTEM_LOG_GETTER (aIndex, totemConePlaylist); switch (Properties (aIndex)) { case eItems: return ObjectVariant (_result, Plugin()->GetNPObject (totemPlugin::eConePlaylistItems)); case eIsPlaying: return BoolVariant (_result, Plugin()->State() == TOTEM_STATE_PLAYING); } return false; } bool totemConePlaylist::SetPropertyByIndex (int aIndex, const NPVariant *aValue) { TOTEM_LOG_SETTER (aIndex, totemConePlaylist); return ThrowPropertyNotWritable (); } <commit_msg>Support for the togglePause() function from VLC JavaScript API.<commit_after>/* Totem Cone plugin * * Copyright © 2004 Bastien Nocera <hadess@hadess.net> * Copyright © 2002 David A. Schleef <ds@schleef.org> * Copyright © 2006, 2008 Christian Persch * * 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., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. */ #include <config.h> #include <string.h> #include <glib.h> #include "totemPlugin.h" #include "totemConePlaylist.h" static const char *propertyNames[] = { "isPlaying", "items" }; static const char *methodNames[] = { "add", "next", "play", "playItem", "prev", "removeItem", "stop", "togglePause" }; TOTEM_IMPLEMENT_NPCLASS (totemConePlaylist, propertyNames, G_N_ELEMENTS (propertyNames), methodNames, G_N_ELEMENTS (methodNames), NULL); totemConePlaylist::totemConePlaylist (NPP aNPP) : totemNPObject (aNPP) { TOTEM_LOG_CTOR (); } totemConePlaylist::~totemConePlaylist () { TOTEM_LOG_DTOR (); } bool totemConePlaylist::InvokeByIndex (int aIndex, const NPVariant *argv, uint32_t argc, NPVariant *_result) { TOTEM_LOG_INVOKE (aIndex, totemConePlaylist); switch (Methods (aIndex)) { case eAdd: { /* long add (in AUTF8String MRL, [in AUTF8String name, in AUTF8String options]); */ if (!CheckArgc (argc, 1, 3)) return false; NPString mrl; if (!GetNPStringFromArguments (argv, argc, 0, mrl)) return false; NPString title; if (argc != 3 || !GetNPStringFromArguments (argv, argc, 1, title)) title.UTF8Characters = NULL; NPString options; if (argc != 3 || !GetNPStringFromArguments (argv, argc, 2, options)) options.UTF8Characters = NULL; //FIXME handle options as array //http://wiki.videolan.org/Documentation:WebPlugin#Playlist_object char *subtitle = NULL; if (options.UTF8Characters && options.UTF8Length) { char *str, **items; guint i; str = g_strndup (options.UTF8Characters, options.UTF8Length); items = g_strsplit (str, " ", -1); g_free (str); for (i = 0; items[i] != NULL; i++) { if (g_str_has_prefix (items[i], ":sub-file=")) { subtitle = g_strdup (items[i] + strlen (":sub-file=")); break; } } g_strfreev (items); } Plugin()->AddItem (mrl, title, subtitle); g_free (subtitle); //FIXME we're supposed to return a unique number here return Int32Variant (_result, 1); } case ePlay: Plugin()->Command (TOTEM_COMMAND_PLAY); return VoidVariant (_result); case eStop: Plugin()->Command (TOTEM_COMMAND_STOP); return VoidVariant (_result); case eTogglePause: if (Plugin()->State() == TOTEM_STATE_PLAYING) { Plugin()->Command (TOTEM_COMMAND_PAUSE); } else if (Plugin()->State() == TOTEM_STATE_PAUSED) { Plugin()->Command (TOTEM_COMMAND_PLAY); } return VoidVariant (_result); case eNext: case ePlayItem: case ePrev: case eRemoveItem: TOTEM_WARN_INVOKE_UNIMPLEMENTED (aIndex, totemConePlaylist); return VoidVariant (_result); } return false; } bool totemConePlaylist::GetPropertyByIndex (int aIndex, NPVariant *_result) { TOTEM_LOG_GETTER (aIndex, totemConePlaylist); switch (Properties (aIndex)) { case eItems: return ObjectVariant (_result, Plugin()->GetNPObject (totemPlugin::eConePlaylistItems)); case eIsPlaying: return BoolVariant (_result, Plugin()->State() == TOTEM_STATE_PLAYING); } return false; } bool totemConePlaylist::SetPropertyByIndex (int aIndex, const NPVariant *aValue) { TOTEM_LOG_SETTER (aIndex, totemConePlaylist); return ThrowPropertyNotWritable (); } <|endoftext|>
<commit_before>/* * Copyright (c) 2020 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/util.h" #include "test/yuv_video_source.h" #include "third_party/googletest/src/include/gtest/gtest.h" #include "vpx/vpx_ext_ratectrl.h" namespace { constexpr int kModelMagicNumber = 51396; constexpr unsigned int PrivMagicNumber = 5566UL; constexpr int kFrameNum = 5; constexpr int kLosslessCodingIndex = 2; struct ToyRateCtrl { int magic_number; int coding_index; }; vpx_rc_status_t rc_create_model(void *priv, const vpx_rc_config_t *ratectrl_config, vpx_rc_model_t *rate_ctrl_model_pt) { ToyRateCtrl *toy_rate_ctrl = new (std::nothrow) ToyRateCtrl; EXPECT_NE(toy_rate_ctrl, nullptr); toy_rate_ctrl->magic_number = kModelMagicNumber; toy_rate_ctrl->coding_index = -1; *rate_ctrl_model_pt = (vpx_rc_model_t)toy_rate_ctrl; EXPECT_EQ(priv, reinterpret_cast<void *>(PrivMagicNumber)); EXPECT_EQ(ratectrl_config->frame_width, 352); EXPECT_EQ(ratectrl_config->frame_height, 288); EXPECT_EQ(ratectrl_config->show_frame_count, kFrameNum); EXPECT_EQ(ratectrl_config->target_bitrate_kbps, 24000); EXPECT_EQ(ratectrl_config->frame_rate_num, 30); EXPECT_EQ(ratectrl_config->frame_rate_den, 1); return vpx_rc_ok; } vpx_rc_status_t rc_send_firstpass_stats( vpx_rc_model_t rate_ctrl_model, const vpx_rc_firstpass_stats_t *first_pass_stats) { const ToyRateCtrl *toy_rate_ctrl = static_cast<ToyRateCtrl *>(rate_ctrl_model); EXPECT_EQ(toy_rate_ctrl->magic_number, kModelMagicNumber); EXPECT_EQ(first_pass_stats->num_frames, kFrameNum); for (int i = 0; i < first_pass_stats->num_frames; ++i) { EXPECT_DOUBLE_EQ(first_pass_stats->frame_stats[i].frame, i); } return vpx_rc_ok; } vpx_rc_status_t rc_get_encodeframe_decision( vpx_rc_model_t rate_ctrl_model, const vpx_rc_encodeframe_info_t *encode_frame_info, vpx_rc_encodeframe_decision_t *frame_decision) { ToyRateCtrl *toy_rate_ctrl = static_cast<ToyRateCtrl *>(rate_ctrl_model); toy_rate_ctrl->coding_index += 1; EXPECT_EQ(toy_rate_ctrl->magic_number, kModelMagicNumber); EXPECT_LT(encode_frame_info->show_index, kFrameNum); EXPECT_EQ(encode_frame_info->coding_index, toy_rate_ctrl->coding_index); if (encode_frame_info->coding_index == 0) { EXPECT_EQ(encode_frame_info->frame_type, 0 /*kFrameTypeKey*/); EXPECT_EQ(encode_frame_info->ref_frame_valid_list[0], 0); // kRefFrameTypeLast EXPECT_EQ(encode_frame_info->ref_frame_valid_list[1], 0); // kRefFrameTypePast EXPECT_EQ(encode_frame_info->ref_frame_valid_list[2], 0); // kRefFrameTypeFuture } if (encode_frame_info->coding_index == 1) { EXPECT_EQ(encode_frame_info->frame_type, 2 /*kFrameTypeAltRef*/); EXPECT_EQ(encode_frame_info->ref_frame_valid_list[0], 1); // kRefFrameTypeLast EXPECT_EQ(encode_frame_info->ref_frame_valid_list[1], 0); // kRefFrameTypePast EXPECT_EQ(encode_frame_info->ref_frame_valid_list[2], 0); // kRefFrameTypeFuture EXPECT_EQ(encode_frame_info->ref_frame_coding_indexes[0], 0); // kRefFrameTypeLast } if (encode_frame_info->coding_index >= 2 && encode_frame_info->coding_index < 5) { EXPECT_EQ(encode_frame_info->frame_type, 1 /*kFrameTypeInter*/); } if (encode_frame_info->coding_index == 5) { EXPECT_EQ(encode_frame_info->frame_type, 3 /*kFrameTypeOverlay*/); EXPECT_EQ(encode_frame_info->ref_frame_valid_list[0], 1); // kRefFrameTypeLast EXPECT_EQ(encode_frame_info->ref_frame_valid_list[1], 1); // kRefFrameTypePast EXPECT_EQ(encode_frame_info->ref_frame_valid_list[2], 1); // kRefFrameTypeFuture EXPECT_EQ(encode_frame_info->ref_frame_coding_indexes[0], 4); // kRefFrameTypeLast EXPECT_EQ(encode_frame_info->ref_frame_coding_indexes[1], 0); // kRefFrameTypePast EXPECT_EQ(encode_frame_info->ref_frame_coding_indexes[2], 1); // kRefFrameTypeFuture } if (encode_frame_info->coding_index == kLosslessCodingIndex) { // We should get sse == 0 at rc_update_encodeframe_result() frame_decision->q_index = 0; } else { frame_decision->q_index = 100; } return vpx_rc_ok; } vpx_rc_status_t rc_update_encodeframe_result( vpx_rc_model_t rate_ctrl_model, const vpx_rc_encodeframe_result_t *encode_frame_result) { const ToyRateCtrl *toy_rate_ctrl = static_cast<ToyRateCtrl *>(rate_ctrl_model); EXPECT_EQ(toy_rate_ctrl->magic_number, kModelMagicNumber); int64_t ref_pixel_count = 352 * 288 * 3 / 2; EXPECT_EQ(encode_frame_result->pixel_count, ref_pixel_count); if (toy_rate_ctrl->coding_index == kLosslessCodingIndex) { EXPECT_EQ(encode_frame_result->sse, 0); } return vpx_rc_ok; } vpx_rc_status_t rc_delete_model(vpx_rc_model_t rate_ctrl_model) { ToyRateCtrl *toy_rate_ctrl = static_cast<ToyRateCtrl *>(rate_ctrl_model); EXPECT_EQ(toy_rate_ctrl->magic_number, kModelMagicNumber); delete toy_rate_ctrl; return vpx_rc_ok; } class ExtRateCtrlTest : public ::libvpx_test::EncoderTest, public ::testing::Test { protected: ExtRateCtrlTest() : EncoderTest(&::libvpx_test::kVP9) {} ~ExtRateCtrlTest() = default; void SetUp() override { InitializeConfig(); SetMode(::libvpx_test::kTwoPassGood); } void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) override { if (video->frame() == 0) { vpx_rc_funcs_t rc_funcs; rc_funcs.create_model = rc_create_model; rc_funcs.send_firstpass_stats = rc_send_firstpass_stats; rc_funcs.get_encodeframe_decision = rc_get_encodeframe_decision; rc_funcs.update_encodeframe_result = rc_update_encodeframe_result; rc_funcs.delete_model = rc_delete_model; rc_funcs.priv = reinterpret_cast<void *>(PrivMagicNumber); encoder->Control(VP9E_SET_EXTERNAL_RATE_CONTROL, &rc_funcs); } } }; TEST_F(ExtRateCtrlTest, EncodeTest) { cfg_.rc_target_bitrate = 24000; std::unique_ptr<libvpx_test::VideoSource> video; video.reset(new libvpx_test::YUVVideoSource("bus_352x288_420_f20_b8.yuv", VPX_IMG_FMT_I420, 352, 288, 30, 1, 0, kFrameNum)); ASSERT_NE(video.get(), nullptr); ASSERT_NO_FATAL_FAILURE(RunLoop(video.get())); } } // namespace <commit_msg>Small changes of vp9_ext_ratectrl_test.cc<commit_after>/* * Copyright (c) 2020 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <new> #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/util.h" #include "test/yuv_video_source.h" #include "third_party/googletest/src/include/gtest/gtest.h" #include "vpx/vpx_ext_ratectrl.h" namespace { constexpr int kModelMagicNumber = 51396; constexpr unsigned int PrivMagicNumber = 5566; constexpr int kFrameNum = 5; constexpr int kLosslessCodingIndex = 2; struct ToyRateCtrl { int magic_number; int coding_index; }; vpx_rc_status_t rc_create_model(void *priv, const vpx_rc_config_t *ratectrl_config, vpx_rc_model_t *rate_ctrl_model_pt) { ToyRateCtrl *toy_rate_ctrl = new (std::nothrow) ToyRateCtrl; EXPECT_NE(toy_rate_ctrl, nullptr); toy_rate_ctrl->magic_number = kModelMagicNumber; toy_rate_ctrl->coding_index = -1; *rate_ctrl_model_pt = toy_rate_ctrl; EXPECT_EQ(priv, reinterpret_cast<void *>(PrivMagicNumber)); EXPECT_EQ(ratectrl_config->frame_width, 352); EXPECT_EQ(ratectrl_config->frame_height, 288); EXPECT_EQ(ratectrl_config->show_frame_count, kFrameNum); EXPECT_EQ(ratectrl_config->target_bitrate_kbps, 24000); EXPECT_EQ(ratectrl_config->frame_rate_num, 30); EXPECT_EQ(ratectrl_config->frame_rate_den, 1); return vpx_rc_ok; } vpx_rc_status_t rc_send_firstpass_stats( vpx_rc_model_t rate_ctrl_model, const vpx_rc_firstpass_stats_t *first_pass_stats) { const ToyRateCtrl *toy_rate_ctrl = static_cast<ToyRateCtrl *>(rate_ctrl_model); EXPECT_EQ(toy_rate_ctrl->magic_number, kModelMagicNumber); EXPECT_EQ(first_pass_stats->num_frames, kFrameNum); for (int i = 0; i < first_pass_stats->num_frames; ++i) { EXPECT_DOUBLE_EQ(first_pass_stats->frame_stats[i].frame, i); } return vpx_rc_ok; } vpx_rc_status_t rc_get_encodeframe_decision( vpx_rc_model_t rate_ctrl_model, const vpx_rc_encodeframe_info_t *encode_frame_info, vpx_rc_encodeframe_decision_t *frame_decision) { ToyRateCtrl *toy_rate_ctrl = static_cast<ToyRateCtrl *>(rate_ctrl_model); toy_rate_ctrl->coding_index += 1; EXPECT_EQ(toy_rate_ctrl->magic_number, kModelMagicNumber); EXPECT_LT(encode_frame_info->show_index, kFrameNum); EXPECT_EQ(encode_frame_info->coding_index, toy_rate_ctrl->coding_index); if (encode_frame_info->coding_index == 0) { EXPECT_EQ(encode_frame_info->frame_type, 0 /*kFrameTypeKey*/); EXPECT_EQ(encode_frame_info->ref_frame_valid_list[0], 0); // kRefFrameTypeLast EXPECT_EQ(encode_frame_info->ref_frame_valid_list[1], 0); // kRefFrameTypePast EXPECT_EQ(encode_frame_info->ref_frame_valid_list[2], 0); // kRefFrameTypeFuture } if (encode_frame_info->coding_index == 1) { EXPECT_EQ(encode_frame_info->frame_type, 2 /*kFrameTypeAltRef*/); EXPECT_EQ(encode_frame_info->ref_frame_valid_list[0], 1); // kRefFrameTypeLast EXPECT_EQ(encode_frame_info->ref_frame_valid_list[1], 0); // kRefFrameTypePast EXPECT_EQ(encode_frame_info->ref_frame_valid_list[2], 0); // kRefFrameTypeFuture EXPECT_EQ(encode_frame_info->ref_frame_coding_indexes[0], 0); // kRefFrameTypeLast } if (encode_frame_info->coding_index >= 2 && encode_frame_info->coding_index < 5) { EXPECT_EQ(encode_frame_info->frame_type, 1 /*kFrameTypeInter*/); } if (encode_frame_info->coding_index == 5) { EXPECT_EQ(encode_frame_info->frame_type, 3 /*kFrameTypeOverlay*/); EXPECT_EQ(encode_frame_info->ref_frame_valid_list[0], 1); // kRefFrameTypeLast EXPECT_EQ(encode_frame_info->ref_frame_valid_list[1], 1); // kRefFrameTypePast EXPECT_EQ(encode_frame_info->ref_frame_valid_list[2], 1); // kRefFrameTypeFuture EXPECT_EQ(encode_frame_info->ref_frame_coding_indexes[0], 4); // kRefFrameTypeLast EXPECT_EQ(encode_frame_info->ref_frame_coding_indexes[1], 0); // kRefFrameTypePast EXPECT_EQ(encode_frame_info->ref_frame_coding_indexes[2], 1); // kRefFrameTypeFuture } if (encode_frame_info->coding_index == kLosslessCodingIndex) { // We should get sse == 0 at rc_update_encodeframe_result() frame_decision->q_index = 0; } else { frame_decision->q_index = 100; } return vpx_rc_ok; } vpx_rc_status_t rc_update_encodeframe_result( vpx_rc_model_t rate_ctrl_model, const vpx_rc_encodeframe_result_t *encode_frame_result) { const ToyRateCtrl *toy_rate_ctrl = static_cast<ToyRateCtrl *>(rate_ctrl_model); EXPECT_EQ(toy_rate_ctrl->magic_number, kModelMagicNumber); const int64_t ref_pixel_count = 352 * 288 * 3 / 2; EXPECT_EQ(encode_frame_result->pixel_count, ref_pixel_count); if (toy_rate_ctrl->coding_index == kLosslessCodingIndex) { EXPECT_EQ(encode_frame_result->sse, 0); } return vpx_rc_ok; } vpx_rc_status_t rc_delete_model(vpx_rc_model_t rate_ctrl_model) { ToyRateCtrl *toy_rate_ctrl = static_cast<ToyRateCtrl *>(rate_ctrl_model); EXPECT_EQ(toy_rate_ctrl->magic_number, kModelMagicNumber); delete toy_rate_ctrl; return vpx_rc_ok; } class ExtRateCtrlTest : public ::libvpx_test::EncoderTest, public ::testing::Test { protected: ExtRateCtrlTest() : EncoderTest(&::libvpx_test::kVP9) {} ~ExtRateCtrlTest() = default; void SetUp() override { InitializeConfig(); SetMode(::libvpx_test::kTwoPassGood); } void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) override { if (video->frame() == 0) { vpx_rc_funcs_t rc_funcs; rc_funcs.create_model = rc_create_model; rc_funcs.send_firstpass_stats = rc_send_firstpass_stats; rc_funcs.get_encodeframe_decision = rc_get_encodeframe_decision; rc_funcs.update_encodeframe_result = rc_update_encodeframe_result; rc_funcs.delete_model = rc_delete_model; rc_funcs.priv = reinterpret_cast<void *>(PrivMagicNumber); encoder->Control(VP9E_SET_EXTERNAL_RATE_CONTROL, &rc_funcs); } } }; TEST_F(ExtRateCtrlTest, EncodeTest) { cfg_.rc_target_bitrate = 24000; std::unique_ptr<libvpx_test::VideoSource> video; video.reset(new (std::nothrow) libvpx_test::YUVVideoSource( "bus_352x288_420_f20_b8.yuv", VPX_IMG_FMT_I420, 352, 288, 30, 1, 0, kFrameNum)); ASSERT_NE(video.get(), nullptr); ASSERT_NO_FATAL_FAILURE(RunLoop(video.get())); } } // namespace <|endoftext|>
<commit_before>#include "TestScene.h" #include "base/stringUtil.h" using namespace fei; void TestScene::init() { setCamera(&mainCam); mainCam.setCameraSize(Vec2(800, 600)); _renderTarget.setSize(Vec2(800, 600)); _renderTarget.getTexture()->setHasAlpha(true); _renderTarget.getTexture()->setMagFilter(GL_NEAREST); testMath(); testPhysics(); testRender(); testAudio(); testFont(); testUtil(); } void TestScene::destroy() { } void TestScene::update() { auto window = Interface::getInstance()->getCurrentWindow(); static Vec2 oldPos = window->getRHCursorPos(); Vec2 deltaV = (window->getRHCursorPos() - oldPos) / -mainCam.getCameraScale(); oldPos = window->getRHCursorPos(); if (window->getMouseButton(GLFW_MOUSE_BUTTON_MIDDLE)) { mainCam.move(deltaV); } } void TestScene::beforeDraw() { _renderTarget.bind(); Render::getInstance()->clearBuffer(); } void TestScene::afterDraw() { _renderTarget.unbind(); auto image = _renderTarget.getTexture()->getImage(); auto camera = Render::getInstance()->getCurrentCamera(); auto rct = camera->getCameraRect(); Color::White.use(); image.drawRect(rct); } void TestScene::testMath() { Vec2 a; if (a == Vec2::ZERO) { std::printf("Vec2: 1ok!\n"); } a.set(1.5f, 1.5f); auto b = a; a.mul(10.0f); a/=10.0f; if (a == b) { std::printf("Vec2: 2ok!\n"); } a.add(a); if (a == Vec2(3.0f)) { std::printf("Vec2: 3ok!\n"); } a = Vec2(10.0f); a += a + a * 3.0f / 100.0f; if (a == Vec2(20.3f)) { std::printf("Vec2: 4ok!\n"); } a.normalize(); Segment x(Vec2::ZERO, Vec2(10.0f)); Vec2 tmp; if (x.collideRay(tmp, Vec2(10.0f, 0.0f), Vec2(-10.0f, 10.0f))) { if (tmp == Vec2(5.0f)) { std::printf("Segment: 1ok!\n"); } } Polygon y; y.pushVertex(Vec2(98.999977f, 76.000000f)); y.pushVertex(Vec2(209.999985f, 6.999993f)); y.pushVertex(Vec2(141.421356f, 141.421356f)); y.pushVertex(Vec2(-141.421356f, 141.421356f)); y.pushVertex(Vec2(141.421326f, -141.421371f)); y.pushVertex(Vec2(-141.421326f, -141.421371f)); auto tl = y.getVisibleVerticesIndex(1); std::printf("%lu\n", tl.size()); for (int vertex : tl) { std::printf("%d\n", vertex); } std::printf("%d\n", y.getBestCutVertexIndex(1)); auto p = fei::collideLine(Vec2(0.0, 1.0), Vec2(0.0, 2.0), Vec2(1.0, 0.0), Vec2(2.0, 0.0)); std::printf("(0.0, 0.0) == (%f, %f)\n", p.x, p.y); if (p == Vec2::ZERO) { std::printf("Yes\n"); } else { std::printf("No\n"); } p = fei::collideLine(Vec2(0.0, 1.0), Vec2(0.0, 2.0), Vec2(2.0, 0.0), Vec2(1.0, 0.0)); std::printf("(0.0, 0.0) == (%f, %f)\n", p.x, p.y); if (p == Vec2::ZERO) { std::printf("Yes\n"); } else { std::printf("No\n"); } } void TestScene::keyCallback(int key, int scancode, int action, int mods) { if (key == GLFW_KEY_F11 && action == GLFW_PRESS) { auto window = fei::Interface::getInstance()->getCurrentWindow(); window->setFullscreen(!window->isFullscreen()); auto winSize = window->getFrameSize(); std::printf("%f %f\n", winSize.x, winSize.y); mainCam.setCameraSize(winSize); _renderTarget.setSize(winSize, Texture::Format::RGBAF); testTex.setPosition(Vec2(2048) - winSize / 2.0f); } if (key == GLFW_KEY_ENTER && action == GLFW_PRESS) { comLabel.executeCommand(); } if (key == GLFW_KEY_BACKSPACE && (action == GLFW_PRESS || action == GLFW_REPEAT)) { comLabel.deleteChar(); } } void TestScene::scrollCallback(double xoffset, double yoffset) { if (yoffset > 0.0) { mainCam.zoomCameraScale(1.1f); } if (yoffset < 0.0) { mainCam.zoomCameraScale(0.90909f); } } void TestScene::charactorCallback(unsigned int codepoint) { comLabel.inputChar(codepoint); } void TestScene::testPhysics() { } void TestScene::testRender() { int s = Render::getInstance()->getMaxTextureSize(); std::printf("%d\n", s); } void TestScene::testFont() { fc.loadFont("res/font/wqy.ttc", 24); std::vector<unsigned long> str; for (int i = 1; i < 255; i++) { str.push_back(i); } fc.updateCache(str); str.clear(); for (int i = 0x4e00; i <= 0x9fa5; i++) { str.push_back(i); } fc.updateCache(str); auto window = fei::Interface::getInstance()->getCurrentWindow(); auto winSize = window->getWindowSize(); testTex = fc.getCacheTexture(); testTex.setPosition(Vec2(2048) - winSize / 2.0f); testTex.setColor(Color("#3f0")); testTex.setMagFilter(GL_LINEAR); add(&testTex); label.setString(fc, "Hello World! 我能吞下玻璃而不伤身体!"); add(&label); button.setRectSize(Vec2(100.0f, 20.0f)); button.setLabelString(fc, "Test!"); add(&button); } void TestScene::testAudio() { src.loadWAV("res/sound/test.wav"); src.play(); } void TestScene::testUtil() { auto result = fei::strSplit("This is a split test! "); for (auto str : result) { std::printf(">>%s<<\n", str.c_str()); } comLabel.setPosition(fei::Vec2(0.0f, 100.0f)); comLabel.setFontCache(&fc); comLabel.getInterpreter()->registerCommand({":print"}, [](std::vector<std::string> params){if (params.size() >= 1) {std::printf("%s\n", params[0].c_str());} return fut::CommandResult::Ok;}); add(&comLabel); } <commit_msg>update bug-tests<commit_after>#include "TestScene.h" #include "base/stringUtil.h" using namespace fei; void TestScene::init() { setCamera(&mainCam); mainCam.setCameraSize(Vec2(800, 600)); _renderTarget.setSize(Vec2(800, 600)); _renderTarget.getTexture()->setHasAlpha(true); _renderTarget.getTexture()->setMagFilter(GL_NEAREST); testMath(); testPhysics(); testRender(); testAudio(); testFont(); testUtil(); } void TestScene::destroy() { } void TestScene::update() { auto window = Interface::getInstance()->getCurrentWindow(); static Vec2 oldPos = window->getRHCursorPos(); Vec2 deltaV = (window->getRHCursorPos() - oldPos) / -mainCam.getCameraScale(); oldPos = window->getRHCursorPos(); if (window->getMouseButton(GLFW_MOUSE_BUTTON_MIDDLE)) { mainCam.move(deltaV); } } void TestScene::beforeDraw() { _renderTarget.bind(); Render::getInstance()->clearBuffer(); } void TestScene::afterDraw() { _renderTarget.unbind(); auto image = _renderTarget.getTexture()->getImage(); auto camera = Render::getInstance()->getCurrentCamera(); auto rct = camera->getCameraRect(); Color::White.use(); image.drawRect(rct); } void TestScene::testMath() { Vec2 a(0.0f); if (a == Vec2::ZERO) { std::printf("Vec2: 1ok!\n"); } a.set(1.5f, 1.5f); auto b = a; a.mul(10.0f); a/=10.0f; if (a == b) { std::printf("Vec2: 2ok!\n"); } a.add(a); if (a == Vec2(3.0f)) { std::printf("Vec2: 3ok!\n"); } a = Vec2(10.0f); a += a + a * 3.0f / 100.0f; if (a == Vec2(20.3f)) { std::printf("Vec2: 4ok!\n"); } a.normalize(); Segment x(Vec2::ZERO, Vec2(10.0f)); Vec2 tmp; if (x.collideRay(tmp, Vec2(10.0f, 0.0f), Vec2(-10.0f, 10.0f))) { if (tmp == Vec2(5.0f)) { std::printf("Segment: 1ok!\n"); } } Polygon y; y.pushVertex(Vec2(98.999977f, 76.000000f)); y.pushVertex(Vec2(209.999985f, 6.999993f)); y.pushVertex(Vec2(141.421356f, 141.421356f)); y.pushVertex(Vec2(-141.421356f, 141.421356f)); y.pushVertex(Vec2(141.421326f, -141.421371f)); y.pushVertex(Vec2(-141.421326f, -141.421371f)); auto tl = y.getVisibleVerticesIndex(1); std::printf("%lu\n", tl.size()); for (int vertex : tl) { std::printf("%d\n", vertex); } std::printf("%d\n", y.getBestCutVertexIndex(1)); auto p = fei::collideLine(Vec2(0.0, 1.0), Vec2(0.0, 2.0), Vec2(1.0, 0.0), Vec2(2.0, 0.0)); std::printf("(0.0, 0.0) == (%f, %f)\n", p.x, p.y); if (p == Vec2::ZERO) { std::printf("Yes\n"); } else { std::printf("No\n"); } p = fei::collideLine(Vec2(0.0, 1.0), Vec2(0.0, 2.0), Vec2(2.0, 0.0), Vec2(1.0, 0.0)); std::printf("(0.0, 0.0) == (%f, %f)\n", p.x, p.y); if (p == Vec2::ZERO) { std::printf("Yes\n"); } else { std::printf("No\n"); } } void TestScene::keyCallback(int key, int scancode, int action, int mods) { if (key == GLFW_KEY_F11 && action == GLFW_PRESS) { auto window = fei::Interface::getInstance()->getCurrentWindow(); window->setFullscreen(!window->isFullscreen()); auto winSize = window->getFrameSize(); std::printf("%f %f\n", winSize.x, winSize.y); mainCam.setCameraSize(winSize); _renderTarget.setSize(winSize, Texture::Format::RGBAF); testTex.setPosition(Vec2(2048) - winSize / 2.0f); } if (key == GLFW_KEY_ENTER && action == GLFW_PRESS) { comLabel.executeCommand(); } if (key == GLFW_KEY_BACKSPACE && (action == GLFW_PRESS || action == GLFW_REPEAT)) { comLabel.deleteChar(); } } void TestScene::scrollCallback(double xoffset, double yoffset) { if (yoffset > 0.0) { mainCam.zoomCameraScale(1.1f); } if (yoffset < 0.0) { mainCam.zoomCameraScale(0.90909f); } } void TestScene::charactorCallback(unsigned int codepoint) { comLabel.inputChar(codepoint); } void TestScene::testPhysics() { } void TestScene::testRender() { int s = Render::getInstance()->getMaxTextureSize(); std::printf("%d\n", s); } void TestScene::testFont() { fc.loadFont("res/font/wqy.ttc", 24); std::vector<unsigned long> str; for (int i = 1; i < 255; i++) { str.push_back(i); } fc.updateCache(str); str.clear(); for (int i = 0x4e00; i <= 0x9fa5; i++) { str.push_back(i); } fc.updateCache(str); auto window = fei::Interface::getInstance()->getCurrentWindow(); auto winSize = window->getWindowSize(); testTex = fc.getCacheTexture(); testTex.setPosition(Vec2(2048) - winSize / 2.0f); testTex.setColor(Color("#3f0")); testTex.setMagFilter(GL_LINEAR); add(&testTex); label.setString(fc, "Hello World! 我能吞下玻璃而不伤身体!"); add(&label); button.setRectSize(Vec2(100.0f, 20.0f)); button.setLabelString(fc, "Test!"); add(&button); } void TestScene::testAudio() { src.loadWAV("res/sound/test.wav"); src.play(); } void TestScene::testUtil() { auto result = fei::strSplit("This is a split test! "); for (auto str : result) { std::printf(">>%s<<\n", str.c_str()); } comLabel.setPosition(fei::Vec2(0.0f, 100.0f)); comLabel.setFontCache(&fc); comLabel.getInterpreter()->registerCommand({":print"}, [](std::vector<std::string> params){if (params.size() >= 1) {std::printf("%s\n", params[0].c_str());} return fut::CommandResult::Ok;}); add(&comLabel); } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <errors.h> #include <instruction.h> #define TEST_CLASS InstructionSetTest class TEST_CLASS : public testing::Test { protected: TEST_CLASS(); InstructionSet set; Instruction low, high; }; TEST_CLASS::TEST_CLASS() : low({'a', 'b'}, 0, NULL), high({'a', 'b', 'c'}, 0, NULL) { } TEST_F(TEST_CLASS, TestAddPreOverlap) { int iret; iret = set.add(low); ASSERT_EQ(iret, ERR_SUCCESS) << "Failed to add instruction"; iret = set.add(high); ASSERT_EQ(iret, ERR_CONFLICT) << "Added overlapping instruction"; iret = set.count(); ASSERT_EQ(iret, 1) << "Incorrect instruction count"; } TEST_F(TEST_CLASS, TestAddPostOverlap) { int iret; iret = set.add(high); ASSERT_EQ(iret, ERR_SUCCESS) << "Failed to add instruction"; iret = set.add(low); ASSERT_EQ(iret, ERR_CONFLICT) << "Added overlapping instruction"; iret = set.count(); ASSERT_EQ(iret, 1) << "Incorrect instruction count"; } TEST_F(TEST_CLASS, TestAddExactOverlap) { int iret; iret = set.add(low); ASSERT_EQ(iret, ERR_SUCCESS) << "Failed to add instruction"; iret = set.add(low); ASSERT_EQ(iret, ERR_CONFLICT) << "Added duplicate instruction"; iret = set.count(); ASSERT_EQ(iret, 1) << "Incorrect instruction count"; } TEST_F(TEST_CLASS, TestAddSuccess) { int iret; iret = set.add(low); ASSERT_EQ(iret, ERR_SUCCESS) << "Failed to add instruction"; iret = set.count(); ASSERT_EQ(iret, 1) << "Incorrect instruction count"; } TEST_F(TEST_CLASS, TestAddDiffernt) { Instruction other({'x'}, 0, NULL); int iret; iret = set.add(low); ASSERT_EQ(iret, ERR_SUCCESS) << "Failed to add instruction"; iret = set.add(other); ASSERT_EQ(iret, ERR_SUCCESS) << "Failed to add instruction"; iret = set.count(); ASSERT_EQ(iret, 2) << "Incorrect instruction count"; }<commit_msg>Write instruction decode tests<commit_after>#include <gtest/gtest.h> #include <errors.h> #include <instruction.h> #define TEST_CLASS InstructionSetTest class TEST_CLASS : public testing::Test { protected: TEST_CLASS(); InstructionSet set; Instruction low, high; }; TEST_CLASS::TEST_CLASS() : low({'a', 'b'}, 0, nullptr), high({'a', 'b', 'c'}, 0, nullptr) { Instruction seed1({'z', '1'}, 0, nullptr); Instruction seed2({'z', '2', 'a'}, 0, nullptr); set.add(seed1); set.add(seed2); int iret = set.count(); EXPECT_EQ(iret, 2) << "Incorrect instruction count during setup"; } TEST_F(TEST_CLASS, TestAddPreOverlap) { int iret; iret = set.add(low); ASSERT_EQ(iret, ERR_SUCCESS) << "Failed to add instruction"; iret = set.add(high); ASSERT_EQ(iret, ERR_CONFLICT) << "Added overlapping instruction"; iret = set.count(); ASSERT_EQ(iret, 3) << "Incorrect instruction count"; } TEST_F(TEST_CLASS, TestAddPostOverlap) { int iret; iret = set.add(high); ASSERT_EQ(iret, ERR_SUCCESS) << "Failed to add instruction"; iret = set.add(low); ASSERT_EQ(iret, ERR_CONFLICT) << "Added overlapping instruction"; iret = set.count(); ASSERT_EQ(iret, 3) << "Incorrect instruction count"; } TEST_F(TEST_CLASS, TestAddExactOverlap) { int iret; iret = set.add(low); ASSERT_EQ(iret, ERR_SUCCESS) << "Failed to add instruction"; iret = set.add(low); ASSERT_EQ(iret, ERR_CONFLICT) << "Added duplicate instruction"; iret = set.count(); ASSERT_EQ(iret, 3) << "Incorrect instruction count"; } TEST_F(TEST_CLASS, TestAddSuccess) { int iret; iret = set.add(low); ASSERT_EQ(iret, ERR_SUCCESS) << "Failed to add instruction"; iret = set.count(); ASSERT_EQ(iret, 3) << "Incorrect instruction count"; } TEST_F(TEST_CLASS, TestAddDiffernt) { int iret; Instruction other({'v'}, 0, nullptr); iret = set.add(low); ASSERT_EQ(iret, ERR_SUCCESS) << "Failed to add instruction"; iret = set.add(other); ASSERT_EQ(iret, ERR_SUCCESS) << "Failed to add instruction"; iret = set.count(); ASSERT_EQ(iret, 4) << "Incorrect instruction count"; } TEST_F(TEST_CLASS, TestDecodeMultipleMatches) { int iret; const Instruction *out; out = nullptr; iret = set.decode({'z'}, &out); ASSERT_EQ(iret, ERR_CONFLICT) << "Failed to match all instructions"; ASSERT_EQ(out, nullptr) << "Incorrectly Returned instruction data"; } TEST_F(TEST_CLASS, TestDecodeNoMatches) { int iret; const Instruction *out; out = nullptr; iret = set.decode({'y'}, &out); ASSERT_EQ(iret, ERR_BADRANGE) << "Incorrectly matched instructions"; ASSERT_EQ(out, nullptr) << "Incorrectly Returned instruction data"; } TEST_F(TEST_CLASS, TestDecodeSingleMatch) { int iret; const Instruction *out; out = nullptr; iret = set.decode({'z', '2'}, &out); ASSERT_EQ(iret, ERR_INCOMPLETE) << "Incorrectly matched instructions"; ASSERT_EQ(out, nullptr) << "Incorrectly Returned instruction data"; } TEST_F(TEST_CLASS, TestDecodeExactMatch) { int iret; const Instruction *out; out = nullptr; iret = set.decode({'z', '2', 'a'}, &out); ASSERT_EQ(iret, ERR_SUCCESS) << "Incorrectly matched instructions"; ASSERT_NE(out, nullptr) << "Incorrectly Returned null instruction data"; }<|endoftext|>
<commit_before>/* * Copyright 2019 Couchbase, 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 "node.h" #include <folly/portability/Unistd.h> #include <nlohmann/json.hpp> #include <platform/dirutils.h> #include <platform/strerror.h> #include <protocol/connection/client_connection_map.h> #ifndef WIN32 #include <signal.h> #include <sys/wait.h> #endif #include <chrono> #include <fstream> #include <iostream> #include <thread> namespace cb { namespace test { Node::~Node() = default; Node::Node(std::string directory) : directory(std::move(directory)) { } class NodeImpl : public Node { public: NodeImpl(std::string directory, std::string id); ~NodeImpl() override; void startMemcachedServer(); bool isRunning() const override; std::unique_ptr<MemcachedConnection> getConnection() override; protected: void parsePortnumberFile(); std::string configfile; #ifdef WIN32 mutable HANDLE child = INVALID_HANDLE_VALUE; #else mutable pid_t child = 0; #endif nlohmann::json config; ConnectionMap connectionMap; const std::string id; }; NodeImpl::NodeImpl(std::string directory, std::string id) : Node(std::move(directory)), id(std::move(id)) { std::string errmaps(SOURCE_ROOT); errmaps.append("/etc/couchbase/kv/error_maps"); cb::io::sanitizePath(errmaps); std::string rbac(SOURCE_ROOT); rbac.append("/tests/testapp_cluster/rbac.json"); cb::io::sanitizePath(rbac); std::string log_filename = NodeImpl::directory + "/memcached_log"; cb::io::sanitizePath(log_filename); std::string portnumber_file = NodeImpl::directory + "/memcached.ports.json"; cb::io::sanitizePath(portnumber_file); std::string minidump_dir = NodeImpl::directory + "/crash"; cb::io::sanitizePath(minidump_dir); cb::io::mkdirp(minidump_dir); config = { {"max_connections", 1000}, {"system_connections", 250}, {"stdin_listener", false}, {"datatype_json", true}, {"datatype_snappy", true}, {"xattr_enabled", true}, {"dedupe_nmvb_maps", false}, {"active_external_users_push_interval", "30 m"}, {"error_maps_dir", errmaps}, {"rbac_file", rbac}, {"ssl_cipher_list", "HIGH"}, {"ssl_minimum_protocol", "tlsv1"}, {"opcode_attributes_override", {{"version", 1}, {"EWB_CTL", {{"slow", 50}}}}}, {"logger", {{"unit_test", true}, {"console", false}, {"filename", log_filename}}}, {"breakpad", {{"enabled", true}, {"minidump_dir", minidump_dir}, {"content", "default"}}}, {"portnumber_file", portnumber_file}, {"parent_identifier", (int)getpid()} }; config["interfaces"][0] = {{"tag", "plain"}, {"system", true}, {"port", 0}, {"ipv4", "required"}, {"host", "*"}}; configfile = NodeImpl::directory + "/memcached.json"; cb::io::sanitizePath(configfile); std::ofstream out(configfile); out << config.dump(2); out.close(); } void NodeImpl::startMemcachedServer() { #ifdef WIN32 STARTUPINFO sinfo{}; PROCESS_INFORMATION pinfo{}; sinfo.cb = sizeof(sinfo); char commandline[1024]; sprintf(commandline, "memcached.exe -C %s", configfile.c_str()); if (!CreateProcess("memcached.exe", // lpApplicationName commandline, // lpCommandLine nullptr, // lpProcessAttributes nullptr, // lpThreadAttributes false, // bInheritHandles 0, // dwCreationFlags nullptr, // lpEnvironment nullptr, // lpCurrentDirectory &sinfo, // lpStartupInfo &pinfo)) { // lpProcessInfoqrmation throw std::system_error(GetLastError(), std::system_category(), "Failed to execute memcached"); } child = pinfo.hProcess; #else child = fork(); if (child == -1) { throw std::system_error( errno, std::system_category(), "Failed to start client"); } if (child == 0) { std::string binary(OBJECT_ROOT); binary.append("/memcached"); const char* argv[20]; int arg = 0; argv[arg++] = binary.c_str(); argv[arg++] = "-C"; argv[arg++] = configfile.c_str(); argv[arg++] = nullptr; execvp(argv[0], const_cast<char**>(argv)); throw std::system_error( errno, std::system_category(), "Failed to execute memcached"); } #endif // wait and read the portnumber file parsePortnumberFile(); } NodeImpl::~NodeImpl() { if (isRunning()) { #ifdef WIN32 // @todo This should be made a bit more robust TerminateProcess(child, 0); WaitForSingleObject(child, 60000); DWORD status; GetExitCodeProcess(child, &status); #else // Start by giving it a slow and easy start... const auto timeout = std::chrono::steady_clock::now() + std::chrono::seconds(15); kill(child, SIGTERM); do { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } while (isRunning() && std::chrono::steady_clock::now() < timeout); if (isRunning()) { // no mercy! kill(child, SIGKILL); int status; pid_t ret; while (true) { ret = waitpid(child, &status, 0); if (ret == reinterpret_cast<pid_t>(-1) && errno == EINTR) { // Just loop again continue; } break; } } #endif } if (!configfile.empty()) { cb::io::rmrf(configfile); } } void NodeImpl::parsePortnumberFile() { using std::chrono::steady_clock; const auto timeout = steady_clock::now() + std::chrono::minutes(5); do { std::this_thread::sleep_for(std::chrono::milliseconds(10)); if (cb::io::isFile(config["portnumber_file"])) { break; } if (!isRunning()) { throw std::runtime_error("parsePortnumberFile: node " + id + " is no longer running"); } } while (steady_clock::now() < timeout); if (!cb::io::isFile(config["portnumber_file"])) { throw std::runtime_error( "parsePortnumberFile: Timed out after 5 minutes waiting for " "memcached port file for node " + id); } connectionMap.initialize( nlohmann::json::parse(cb::io::loadFile(config["portnumber_file"]))); cb::io::rmrf(config["portnumber_file"]); } #ifdef WIN32 bool NodeImpl::isRunning() const { if (child != INVALID_HANDLE_VALUE) { DWORD status; if (!GetExitCodeProcess(child, &status)) { throw std::system_error( GetLastError(), std::system_category(), "NodeImpl::isRunning: GetExitCodeProcess failed"); std::cerr << "GetExitCodeProcess: failed: " << cb_strerror() << std::endl; exit(EXIT_FAILURE); } if (status == STILL_ACTIVE) { return true; } CloseHandle(child); child = INVALID_HANDLE_VALUE; } return false; } #else bool NodeImpl::isRunning() const { if (child != 0) { int status; auto next = waitpid(child, &status, WNOHANG); if (next == static_cast<pid_t>(-1)) { throw std::system_error(errno, std::system_category(), "NodeImpl::isRunning: waitpid failed"); } if (next == child) { child = 0; return false; } return true; } return false; } #endif std::unique_ptr<MemcachedConnection> NodeImpl::getConnection() { auto ret = connectionMap.getConnection().clone(); ret->setAutoRetryTmpfail(true); ret->setFeature(cb::mcbp::Feature::XERROR, true); ret->setFeature(cb::mcbp::Feature::JSON, true); ret->setFeature(cb::mcbp::Feature::MUTATION_SEQNO, true); return ret; } std::unique_ptr<Node> Node::create(const std::string& directory, const std::string& id) { auto ret = std::make_unique<NodeImpl>(directory, id); ret->startMemcachedServer(); return ret; } } // namespace test } // namespace cb <commit_msg>[cluster_testapp] set all features at once<commit_after>/* * Copyright 2019 Couchbase, 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 "node.h" #include <folly/portability/Unistd.h> #include <nlohmann/json.hpp> #include <platform/dirutils.h> #include <platform/strerror.h> #include <protocol/connection/client_connection_map.h> #ifndef WIN32 #include <signal.h> #include <sys/wait.h> #endif #include <chrono> #include <fstream> #include <iostream> #include <thread> namespace cb { namespace test { Node::~Node() = default; Node::Node(std::string directory) : directory(std::move(directory)) { } class NodeImpl : public Node { public: NodeImpl(std::string directory, std::string id); ~NodeImpl() override; void startMemcachedServer(); bool isRunning() const override; std::unique_ptr<MemcachedConnection> getConnection() override; protected: void parsePortnumberFile(); std::string configfile; #ifdef WIN32 mutable HANDLE child = INVALID_HANDLE_VALUE; #else mutable pid_t child = 0; #endif nlohmann::json config; ConnectionMap connectionMap; const std::string id; }; NodeImpl::NodeImpl(std::string directory, std::string id) : Node(std::move(directory)), id(std::move(id)) { std::string errmaps(SOURCE_ROOT); errmaps.append("/etc/couchbase/kv/error_maps"); cb::io::sanitizePath(errmaps); std::string rbac(SOURCE_ROOT); rbac.append("/tests/testapp_cluster/rbac.json"); cb::io::sanitizePath(rbac); std::string log_filename = NodeImpl::directory + "/memcached_log"; cb::io::sanitizePath(log_filename); std::string portnumber_file = NodeImpl::directory + "/memcached.ports.json"; cb::io::sanitizePath(portnumber_file); std::string minidump_dir = NodeImpl::directory + "/crash"; cb::io::sanitizePath(minidump_dir); cb::io::mkdirp(minidump_dir); config = { {"max_connections", 1000}, {"system_connections", 250}, {"stdin_listener", false}, {"datatype_json", true}, {"datatype_snappy", true}, {"xattr_enabled", true}, {"dedupe_nmvb_maps", false}, {"active_external_users_push_interval", "30 m"}, {"error_maps_dir", errmaps}, {"rbac_file", rbac}, {"ssl_cipher_list", "HIGH"}, {"ssl_minimum_protocol", "tlsv1"}, {"opcode_attributes_override", {{"version", 1}, {"EWB_CTL", {{"slow", 50}}}}}, {"logger", {{"unit_test", true}, {"console", false}, {"filename", log_filename}}}, {"breakpad", {{"enabled", true}, {"minidump_dir", minidump_dir}, {"content", "default"}}}, {"portnumber_file", portnumber_file}, {"parent_identifier", (int)getpid()} }; config["interfaces"][0] = {{"tag", "plain"}, {"system", true}, {"port", 0}, {"ipv4", "required"}, {"host", "*"}}; configfile = NodeImpl::directory + "/memcached.json"; cb::io::sanitizePath(configfile); std::ofstream out(configfile); out << config.dump(2); out.close(); } void NodeImpl::startMemcachedServer() { #ifdef WIN32 STARTUPINFO sinfo{}; PROCESS_INFORMATION pinfo{}; sinfo.cb = sizeof(sinfo); char commandline[1024]; sprintf(commandline, "memcached.exe -C %s", configfile.c_str()); if (!CreateProcess("memcached.exe", // lpApplicationName commandline, // lpCommandLine nullptr, // lpProcessAttributes nullptr, // lpThreadAttributes false, // bInheritHandles 0, // dwCreationFlags nullptr, // lpEnvironment nullptr, // lpCurrentDirectory &sinfo, // lpStartupInfo &pinfo)) { // lpProcessInfoqrmation throw std::system_error(GetLastError(), std::system_category(), "Failed to execute memcached"); } child = pinfo.hProcess; #else child = fork(); if (child == -1) { throw std::system_error( errno, std::system_category(), "Failed to start client"); } if (child == 0) { std::string binary(OBJECT_ROOT); binary.append("/memcached"); const char* argv[20]; int arg = 0; argv[arg++] = binary.c_str(); argv[arg++] = "-C"; argv[arg++] = configfile.c_str(); argv[arg++] = nullptr; execvp(argv[0], const_cast<char**>(argv)); throw std::system_error( errno, std::system_category(), "Failed to execute memcached"); } #endif // wait and read the portnumber file parsePortnumberFile(); } NodeImpl::~NodeImpl() { if (isRunning()) { #ifdef WIN32 // @todo This should be made a bit more robust TerminateProcess(child, 0); WaitForSingleObject(child, 60000); DWORD status; GetExitCodeProcess(child, &status); #else // Start by giving it a slow and easy start... const auto timeout = std::chrono::steady_clock::now() + std::chrono::seconds(15); kill(child, SIGTERM); do { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } while (isRunning() && std::chrono::steady_clock::now() < timeout); if (isRunning()) { // no mercy! kill(child, SIGKILL); int status; pid_t ret; while (true) { ret = waitpid(child, &status, 0); if (ret == reinterpret_cast<pid_t>(-1) && errno == EINTR) { // Just loop again continue; } break; } } #endif } if (!configfile.empty()) { cb::io::rmrf(configfile); } } void NodeImpl::parsePortnumberFile() { using std::chrono::steady_clock; const auto timeout = steady_clock::now() + std::chrono::minutes(5); do { std::this_thread::sleep_for(std::chrono::milliseconds(10)); if (cb::io::isFile(config["portnumber_file"])) { break; } if (!isRunning()) { throw std::runtime_error("parsePortnumberFile: node " + id + " is no longer running"); } } while (steady_clock::now() < timeout); if (!cb::io::isFile(config["portnumber_file"])) { throw std::runtime_error( "parsePortnumberFile: Timed out after 5 minutes waiting for " "memcached port file for node " + id); } connectionMap.initialize( nlohmann::json::parse(cb::io::loadFile(config["portnumber_file"]))); cb::io::rmrf(config["portnumber_file"]); } #ifdef WIN32 bool NodeImpl::isRunning() const { if (child != INVALID_HANDLE_VALUE) { DWORD status; if (!GetExitCodeProcess(child, &status)) { throw std::system_error( GetLastError(), std::system_category(), "NodeImpl::isRunning: GetExitCodeProcess failed"); std::cerr << "GetExitCodeProcess: failed: " << cb_strerror() << std::endl; exit(EXIT_FAILURE); } if (status == STILL_ACTIVE) { return true; } CloseHandle(child); child = INVALID_HANDLE_VALUE; } return false; } #else bool NodeImpl::isRunning() const { if (child != 0) { int status; auto next = waitpid(child, &status, WNOHANG); if (next == static_cast<pid_t>(-1)) { throw std::system_error(errno, std::system_category(), "NodeImpl::isRunning: waitpid failed"); } if (next == child) { child = 0; return false; } return true; } return false; } #endif std::unique_ptr<MemcachedConnection> NodeImpl::getConnection() { auto ret = connectionMap.getConnection().clone(); ret->setAutoRetryTmpfail(true); std::vector<cb::mcbp::Feature> features = { {cb::mcbp::Feature::MUTATION_SEQNO, cb::mcbp::Feature::XATTR, cb::mcbp::Feature::XERROR, cb::mcbp::Feature::JSON}}; ret->setFeatures("cluster_testapp", features); return ret; } std::unique_ptr<Node> Node::create(const std::string& directory, const std::string& id) { auto ret = std::make_unique<NodeImpl>(directory, id); ret->startMemcachedServer(); return ret; } } // namespace test } // namespace cb <|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "BenchTimer.h" #include "SamplePipeControllers.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkGPipe.h" #include "SkOSFile.h" #include "SkPicture.h" #include "SkStream.h" #include "SkTArray.h" #include "picture_utils.h" const int DEFAULT_REPEATS = 100; const int DEFAULT_TILE_WIDTH = 256; const int DEFAULT_TILE_HEIGHT = 256; struct Options; static void run_simple_benchmark(SkPicture* picture, const SkBitmap&, const Options&); struct Options { int fRepeats; void (*fBenchmark) (SkPicture*, const SkBitmap& bitmap, const Options& options); int fTileWidth; int fTileHeight; Options() : fRepeats(DEFAULT_REPEATS), fBenchmark(run_simple_benchmark), fTileWidth(DEFAULT_TILE_WIDTH), fTileHeight(DEFAULT_TILE_HEIGHT){} }; static void usage(const char* argv0) { SkDebugf("SkPicture benchmarking tool\n"); SkDebugf("\n" "Usage: \n" " %s <inputDir>...\n" " [--repeat] [--tile width height]" , argv0); SkDebugf("\n\n"); SkDebugf( " inputDir: A list of directories and files to use as input.\n" " Files are expected to have the .skp extension.\n\n"); SkDebugf( " --pipe : " "Set to use piping." " Default is to not use piping.\n"); SkDebugf( " --repeat : " "Set the number of times to repeat each test." " Default is %i.\n", DEFAULT_REPEATS); SkDebugf( " --tile width height: " "Set to use the tiling size and specify the dimensions of each tile." " Default is to not use tiling\n"); } static void run_simple_benchmark(SkPicture* picture, const SkBitmap& bitmap, const Options& options) { SkCanvas canvas(bitmap); // We throw this away to remove first time effects (such as paging in this // program) canvas.drawPicture(*picture); BenchTimer timer = BenchTimer(NULL); timer.start(); for (int i = 0; i < options.fRepeats; ++i) { canvas.drawPicture(*picture); } timer.end(); printf("simple: cmsecs = %6.2f\n", timer.fWall / options.fRepeats); } struct TileInfo { SkBitmap* fBitmap; SkCanvas* fCanvas; }; static void clip_tile(SkPicture* picture, const TileInfo& tile) { SkRect clip = SkRect::MakeWH(SkIntToScalar(picture->width()), SkIntToScalar(picture->height())); tile.fCanvas->clipRect(clip); } static void setup_single_tile(SkPicture* picture, const SkBitmap& bitmap, const Options& options, SkTArray<TileInfo>* tiles, int tile_x_start, int tile_y_start) { TileInfo& tile = tiles->push_back(); tile.fBitmap = new SkBitmap(); SkIRect rect = SkIRect::MakeXYWH(tile_x_start, tile_y_start, options.fTileWidth, options.fTileHeight); bitmap.extractSubset(tile.fBitmap, rect); tile.fCanvas = new SkCanvas(*(tile.fBitmap)); tile.fCanvas->translate(SkIntToScalar(-tile_x_start), SkIntToScalar(-tile_y_start)); clip_tile(picture, tile); } static void setup_tiles(SkPicture* picture, const SkBitmap& bitmap, const Options& options, SkTArray<TileInfo>* tiles) { for (int tile_y_start = 0; tile_y_start < picture->height(); tile_y_start += options.fTileHeight) { for (int tile_x_start = 0; tile_x_start < picture->width(); tile_x_start += options.fTileWidth) { setup_single_tile(picture, bitmap, options, tiles, tile_x_start, tile_y_start); } } } static void run_tile_benchmark(SkPicture* picture, const SkBitmap& bitmap, const Options& options) { SkTArray<TileInfo> tiles; setup_tiles(picture, bitmap, options, &tiles); // We throw this away to remove first time effects (such as paging in this // program) for (int j = 0; j < tiles.count(); ++j) { tiles[j].fCanvas->drawPicture(*picture); } BenchTimer timer = BenchTimer(NULL); timer.start(); for (int i = 0; i < options.fRepeats; ++i) { for (int j = 0; j < tiles.count(); ++j) { tiles[j].fCanvas->drawPicture(*picture); } } timer.end(); for (int i = 0; i < tiles.count(); ++i) { delete tiles[i].fCanvas; delete tiles[i].fBitmap; } printf("%i_tiles_%ix%i: cmsecs = %6.2f\n", tiles.count(), options.fTileWidth, options.fTileHeight, timer.fWall / options.fRepeats); } static void pipe_run(SkPicture* picture, SkCanvas* canvas) { PipeController pipeController(canvas); SkGPipeWriter writer; SkCanvas* pipeCanvas = writer.startRecording(&pipeController); pipeCanvas->drawPicture(*picture); writer.endRecording(); } static void run_pipe_benchmark(SkPicture* picture, const SkBitmap& bitmap, const Options& options) { SkCanvas canvas(bitmap); // We throw this away to remove first time effects (such as paging in this // program) pipe_run(picture, &canvas); BenchTimer timer = BenchTimer(NULL); timer.start(); for (int i = 0; i < options.fRepeats; ++i) { pipe_run(picture, &canvas); } timer.end(); printf("pipe: cmsecs = %6.2f\n", timer.fWall / options.fRepeats); } static void run_single_benchmark(const SkString& inputPath, const Options& options) { SkFILEStream inputStream; inputStream.setPath(inputPath.c_str()); if (!inputStream.isValid()) { SkDebugf("Could not open file %s\n", inputPath.c_str()); return; } SkPicture picture(&inputStream); SkBitmap bitmap; sk_tools::setup_bitmap(&bitmap, picture.width(), picture.height()); SkString filename; sk_tools::get_basename(&filename, inputPath); printf("running bench [%i %i] %s ", picture.width(), picture.height(), filename.c_str()); options.fBenchmark(&picture, bitmap, options); } static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs, Options* options) { const char* argv0 = argv[0]; char* const* stop = argv + argc; for (++argv; argv < stop; ++argv) { if (0 == strcmp(*argv, "--repeat")) { ++argv; if (argv < stop) { options->fRepeats = atoi(*argv); if (options->fRepeats < 1) { SkDebugf("--repeat must be given a value > 0\n"); exit(-1); } } else { SkDebugf("Missing arg for --repeat\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--tile")) { options->fBenchmark = run_tile_benchmark; ++argv; if (argv < stop) { options->fTileWidth = atoi(*argv); if (options->fTileWidth < 1) { SkDebugf("--tile must be given a width with a value > 0\n"); exit(-1); } } else { SkDebugf("Missing width for --tile\n"); usage(argv0); exit(-1); } ++argv; if (argv < stop) { options->fTileHeight = atoi(*argv); if (options->fTileHeight < 1) { SkDebugf("--tile must be given a height with a value > 0" "\n"); exit(-1); } } else { SkDebugf("Missing height for --tile\n"); usage(argv0);\ exit(-1); } } else if (0 == strcmp(*argv, "--pipe")) { options->fBenchmark = run_pipe_benchmark; } else if (0 == strcmp(*argv, "--help") || 0 == strcmp(*argv, "-h")) { usage(argv0); exit(0); } else { inputs->push_back(SkString(*argv)); } } if (inputs->count() < 1) { usage(argv0); exit(-1); } } static void process_input(const SkString& input, const Options& options) { SkOSFile::Iter iter(input.c_str(), "skp"); SkString inputFilename; if (iter.next(&inputFilename)) { do { SkString inputPath; sk_tools::make_filepath(&inputPath, input.c_str(), inputFilename); run_single_benchmark(inputPath, options); } while(iter.next(&inputFilename)); } else { run_single_benchmark(input, options); } } int main(int argc, char* const argv[]) { SkTArray<SkString> inputs; Options options; parse_commandline(argc, argv, &inputs, &options); for (int i = 0; i < inputs.count(); ++i) { process_input(inputs[i], options); } } <commit_msg>bench_pictures can now take percentages for tiling width and height.Review URL: https://codereview.appspot.com/6354074<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "BenchTimer.h" #include "SamplePipeControllers.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkGPipe.h" #include "SkOSFile.h" #include "SkPicture.h" #include "SkStream.h" #include "SkTArray.h" #include "picture_utils.h" const int DEFAULT_REPEATS = 100; const int DEFAULT_TILE_WIDTH = 256; const int DEFAULT_TILE_HEIGHT = 256; struct Options; static void run_simple_benchmark(SkPicture* picture, const SkBitmap&, const Options&); struct Options { int fRepeats; void (*fBenchmark) (SkPicture*, const SkBitmap& bitmap, const Options& options); int fTileWidth; int fTileHeight; double fTileWidthPercentage; double fTileHeightPercentage; Options() : fRepeats(DEFAULT_REPEATS), fBenchmark(run_simple_benchmark), fTileWidth(DEFAULT_TILE_WIDTH), fTileHeight(DEFAULT_TILE_HEIGHT), fTileWidthPercentage(0), fTileHeightPercentage(0){} }; static void usage(const char* argv0) { SkDebugf("SkPicture benchmarking tool\n"); SkDebugf("\n" "Usage: \n" " %s <inputDir>...\n" " [--repeat] [--tile width height]" , argv0); SkDebugf("\n\n"); SkDebugf( " inputDir: A list of directories and files to use as input.\n" " Files are expected to have the .skp extension.\n\n"); SkDebugf( " --pipe : " "Set to use piping." " Default is to not use piping.\n"); SkDebugf( " --repeat : " "Set the number of times to repeat each test." " Default is %i.\n", DEFAULT_REPEATS); SkDebugf( " --tile width[%] height[%]: " "Set to use the tiling size and specify the dimensions of each tile.\n" " Default is to not use tiling\n"); } static void run_simple_benchmark(SkPicture* picture, const SkBitmap& bitmap, const Options& options) { SkCanvas canvas(bitmap); // We throw this away to remove first time effects (such as paging in this // program) canvas.drawPicture(*picture); BenchTimer timer = BenchTimer(NULL); timer.start(); for (int i = 0; i < options.fRepeats; ++i) { canvas.drawPicture(*picture); } timer.end(); printf("simple: cmsecs = %6.2f\n", timer.fWall / options.fRepeats); } struct TileInfo { SkBitmap* fBitmap; SkCanvas* fCanvas; }; static void clip_tile(SkPicture* picture, const TileInfo& tile) { SkRect clip = SkRect::MakeWH(SkIntToScalar(picture->width()), SkIntToScalar(picture->height())); tile.fCanvas->clipRect(clip); } static void setup_single_tile(SkPicture* picture, const SkBitmap& bitmap, const Options& options, SkTArray<TileInfo>* tiles, int tile_x_start, int tile_y_start) { TileInfo& tile = tiles->push_back(); tile.fBitmap = new SkBitmap(); SkIRect rect = SkIRect::MakeXYWH(tile_x_start, tile_y_start, options.fTileWidth, options.fTileHeight); bitmap.extractSubset(tile.fBitmap, rect); tile.fCanvas = new SkCanvas(*(tile.fBitmap)); tile.fCanvas->translate(SkIntToScalar(-tile_x_start), SkIntToScalar(-tile_y_start)); clip_tile(picture, tile); } static void setup_tiles(SkPicture* picture, const SkBitmap& bitmap, const Options& options, SkTArray<TileInfo>* tiles) { for (int tile_y_start = 0; tile_y_start < picture->height(); tile_y_start += options.fTileHeight) { for (int tile_x_start = 0; tile_x_start < picture->width(); tile_x_start += options.fTileWidth) { setup_single_tile(picture, bitmap, options, tiles, tile_x_start, tile_y_start); } } } static void run_tile_benchmark(SkPicture* picture, const SkBitmap& bitmap, const Options& options) { SkTArray<TileInfo> tiles; setup_tiles(picture, bitmap, options, &tiles); // We throw this away to remove first time effects (such as paging in this // program) for (int j = 0; j < tiles.count(); ++j) { tiles[j].fCanvas->drawPicture(*picture); } BenchTimer timer = BenchTimer(NULL); timer.start(); for (int i = 0; i < options.fRepeats; ++i) { for (int j = 0; j < tiles.count(); ++j) { tiles[j].fCanvas->drawPicture(*picture); } } timer.end(); for (int i = 0; i < tiles.count(); ++i) { delete tiles[i].fCanvas; delete tiles[i].fBitmap; } printf("%i_tiles_%ix%i: cmsecs = %6.2f\n", tiles.count(), options.fTileWidth, options.fTileHeight, timer.fWall / options.fRepeats); } static void pipe_run(SkPicture* picture, SkCanvas* canvas) { PipeController pipeController(canvas); SkGPipeWriter writer; SkCanvas* pipeCanvas = writer.startRecording(&pipeController); pipeCanvas->drawPicture(*picture); writer.endRecording(); } static void run_pipe_benchmark(SkPicture* picture, const SkBitmap& bitmap, const Options& options) { SkCanvas canvas(bitmap); // We throw this away to remove first time effects (such as paging in this // program) pipe_run(picture, &canvas); BenchTimer timer = BenchTimer(NULL); timer.start(); for (int i = 0; i < options.fRepeats; ++i) { pipe_run(picture, &canvas); } timer.end(); printf("pipe: cmsecs = %6.2f\n", timer.fWall / options.fRepeats); } static void run_single_benchmark(const SkString& inputPath, Options* options) { SkFILEStream inputStream; inputStream.setPath(inputPath.c_str()); if (!inputStream.isValid()) { SkDebugf("Could not open file %s\n", inputPath.c_str()); return; } SkPicture picture(&inputStream); SkBitmap bitmap; sk_tools::setup_bitmap(&bitmap, picture.width(), picture.height()); SkString filename; sk_tools::get_basename(&filename, inputPath); printf("running bench [%i %i] %s ", picture.width(), picture.height(), filename.c_str()); if (options->fTileWidthPercentage > 0) { options->fTileWidth = sk_float_ceil2int(options->fTileWidthPercentage * picture.width() / 100); } if (options->fTileHeightPercentage > 0) { options->fTileHeight = sk_float_ceil2int(options->fTileHeightPercentage * picture.height() / 100); } options->fBenchmark(&picture, bitmap, *options); } static bool is_percentage(char* const string) { SkString skString(string); return skString.endsWith("%"); } static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs, Options* options) { const char* argv0 = argv[0]; char* const* stop = argv + argc; for (++argv; argv < stop; ++argv) { if (0 == strcmp(*argv, "--repeat")) { ++argv; if (argv < stop) { options->fRepeats = atoi(*argv); if (options->fRepeats < 1) { SkDebugf("--repeat must be given a value > 0\n"); exit(-1); } } else { SkDebugf("Missing arg for --repeat\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--tile")) { options->fBenchmark = run_tile_benchmark; ++argv; if (argv < stop) { if (is_percentage(*argv)) { options->fTileWidthPercentage = atof(*argv); if (!(options->fTileWidthPercentage > 0)) { SkDebugf("--tile must be given a width percentage > 0\n"); exit(-1); } } else { options->fTileWidth = atoi(*argv); if (!(options->fTileWidth > 0)) { SkDebugf("--tile must be given a width > 0\n"); exit(-1); } } } else { SkDebugf("Missing width for --tile\n"); usage(argv0); exit(-1); } ++argv; if (argv < stop) { if (is_percentage(*argv)) { options->fTileHeightPercentage = atof(*argv); if (!(options->fTileHeightPercentage > 0)) { SkDebugf( "--tile must be given a height percentage > 0\n"); exit(-1); } } else { options->fTileHeight = atoi(*argv); if (!(options->fTileHeight > 0)) { SkDebugf("--tile must be given a height > 0\n"); exit(-1); } } } else { SkDebugf("Missing height for --tile\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--pipe")) { options->fBenchmark = run_pipe_benchmark; } else if (0 == strcmp(*argv, "--help") || 0 == strcmp(*argv, "-h")) { usage(argv0); exit(0); } else { inputs->push_back(SkString(*argv)); } } if (inputs->count() < 1) { usage(argv0); exit(-1); } } static void process_input(const SkString& input, Options* options) { SkOSFile::Iter iter(input.c_str(), "skp"); SkString inputFilename; if (iter.next(&inputFilename)) { do { SkString inputPath; sk_tools::make_filepath(&inputPath, input.c_str(), inputFilename); run_single_benchmark(inputPath, options); } while(iter.next(&inputFilename)); } else { run_single_benchmark(input, options); } } int main(int argc, char* const argv[]) { SkTArray<SkString> inputs; Options options; parse_commandline(argc, argv, &inputs, &options); for (int i = 0; i < inputs.count(); ++i) { process_input(inputs[i], &options); } } <|endoftext|>
<commit_before> /* * Copyright (c) 2012 Karl N. Redgate * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** \file Neighbor.cc * \brief * */ #include <stdint.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/wait.h> #include <arpa/inet.h> #include <stdlib.h> #include <signal.h> #include <fcntl.h> #include <time.h> #include <string.h> #include <glob.h> #include <errno.h> #include <tcl.h> #include "tcl_util.h" #include "logger.h" #include "util.h" #include "Neighbor.h" #include "Interface.h" /* * I do not like this - try to eliminate OS defines */ #if defined(__APPLE__) || defined(__darwin__) /* OSX seems not to define these. */ #ifndef s6_addr16 #define s6_addr16 __u6_addr.__u6_addr16 #endif #ifndef s6_addr32 #define s6_addr32 __u6_addr.__u6_addr32 #endif #endif namespace { int debug = 0; } /** */ void Network::Node::uuid( UUID& that ) { _uuid = that; _ordinal = 255; valid = true; // log_notice( "new node allocated with uuid %s", _uuid.to_s() ); } /** */ void Network::Node::ordinal( uint8_t value ) { _ordinal = value; // log_notice( "node%d %s", _ordinal, _uuid.to_s() ); } /** */ bool Network::Node::operator == ( UUID& that ) { return _uuid == that; } /** */ bool Network::Node::operator != ( UUID& that ) { return _uuid != that; } /** * Used to iterate through the node list and clear the partner * bit in all entries. */ class ClearNodePartner : public Network::NodeIterator { public: ClearNodePartner() {} virtual ~ClearNodePartner() {} virtual int operator() ( Network::Node& node ) { if ( node.not_partner() ) return 0; log_notice( "clear partner [%s]", node.uuid().to_s() ); node.clear_partner(); return 1; } }; /** */ Network::Peer::~Peer() { if ( _name != NULL ) free( _name ); _name = NULL; } /** * This one should be deprecated */ Network::Peer::Peer( Network::Node *__node, struct in6_addr *address ) : _node(__node), _ordinal(0), _name(NULL) { memcpy( &lladdr, address, sizeof lladdr ); memset( &neighbor_updated, 0, sizeof neighbor_updated ); } /** */ void Network::Peer::node( Node *that ) { _node = that; /* * Here we have just discovered a new partner. If this was the * cached partner, then the _node would already be a partner. * Since it was not and the neighbor is a partner - it must * have been discovered on priv0, which either overrides the * cached partner (node replace or the like) or this is the * first time we have discovered the partner. Either way * we need to cache the newly discovered partner. */ if ( is_partner() and _node->not_partner() ) { _node->make_partner(); log_notice( "node %s is partner", _node->uuid().to_s() ); } /* * Cases that are ignored: * peer->not_partner() and _node->not_partner() * -- who cares about this neighbor * * peer->is_partner() and _node->is_partner() * -- we already have all necessary state * */ if ( debug < 2 ) return; char buffer[80]; const char *address_string = inet_ntop(AF_INET6, &lladdr, buffer, sizeof buffer); log_notice( "%s at %s is node %s", (_node->is_partner() ? "partner" : "neighbor"), address_string, _node->uuid().to_s() ); } /** */ Network::Node * Network::Peer::node() const { return _node; } /** * Since this is a sort of allocation method, maybe this should check if * already valid and either disallow usage -- or at least report that the * address is changing. */ void Network::Peer::address( struct in6_addr *addr ) { memcpy( &lladdr, addr, sizeof lladdr ); valid = true; if ( debug < 2 ) return; char buffer[80]; const char *address_string = inet_ntop(AF_INET6, addr, buffer, sizeof buffer); log_notice( "new neighbor %s", address_string ); } /** */ void Network::Peer::set_interface( bool set_private, uint8_t set_ordinal ) { _is_private = set_private; _ordinal = set_ordinal; } /** */ void Network::Peer::set_interface_name( char *name ) { if ( name == NULL ) { // If the new name is NULL... if ( _name != NULL ) { // ...and the Peer had a name... free( _name ); // ...free the old name... _name = NULL; // ...and invalidate the name. } return; } if ( _name != NULL ) { // If the Peer already has a name... if ( strcmp( name, _name ) ) { // ...and it is *not* the same name... free( _name ); // ...free the old name... _name = strdup( name ); // ...and copy the new name. } // If it *is* the same name, don't do free()/strdup() } else { // If the Peer does not have a name... _name = strdup( name ); // ...copy the new name. } } /** */ void Network::Peer::copy_address( struct in6_addr *address ) const { memcpy( address, &lladdr, sizeof lladdr ); } /** */ void Network::Peer::touch_advertised() { gettimeofday( &neighbor_advertised, 0 ); } /** */ void Network::Peer::touch() { gettimeofday( &neighbor_updated, 0 ); } /** */ int Network::Peer::seconds_since_last_update() const { struct timeval now; gettimeofday( &now, 0 ); return now.tv_sec - neighbor_updated.tv_sec; } /** */ bool Network::Peer::operator == ( struct in6_addr& that ) { if ( that.s6_addr32[0] != lladdr.s6_addr32[0] ) return false; if ( that.s6_addr32[1] != lladdr.s6_addr32[1] ) return false; if ( that.s6_addr32[2] != lladdr.s6_addr32[2] ) return false; if ( that.s6_addr32[3] != lladdr.s6_addr32[3] ) return false; return true; } /** */ bool Network::Peer::operator != ( struct in6_addr& that ) { if ( that.s6_addr32[0] != lladdr.s6_addr32[0] ) return true; if ( that.s6_addr32[1] != lladdr.s6_addr32[1] ) return true; if ( that.s6_addr32[2] != lladdr.s6_addr32[2] ) return true; if ( that.s6_addr32[3] != lladdr.s6_addr32[3] ) return true; return false; } /** */ bool Network::Peer::has_address( struct in6_addr *address ) { if ( address->s6_addr32[0] != lladdr.s6_addr32[0] ) return false; if ( address->s6_addr32[1] != lladdr.s6_addr32[1] ) return false; if ( address->s6_addr32[2] != lladdr.s6_addr32[2] ) return false; if ( address->s6_addr32[3] != lladdr.s6_addr32[3] ) return false; return true; } /** */ static void construct_remote_interface_name( Network::Peer *neighbor, char *name, int size ) { if ( neighbor->name() != NULL ) { strncpy( name, neighbor->name(), size ); } else { int ordinal = neighbor->ordinal(); if ( neighbor->is_private() ) { if ( ordinal & 0x40 ) { int slot = ( ordinal & 0x3c ) >> 2; int port = ( ordinal & 0x03); snprintf( name, size, "sync_pci%dp%d", slot, port ); } else { snprintf( name, size, "priv%d", ordinal ); } } else { snprintf( name, size, "ibiz%d", ordinal ); } } } /** */ void Network::Peer::topology_changed( Network::Monitor *monitor, Network::Interface *interface ) { char node_ordinal = (node() == NULL) ? '?' : ('0' + node()->ordinal()); char remote_interface_name[32]; construct_remote_interface_name( this, remote_interface_name, sizeof(remote_interface_name) ); log_notice( "Topology change: node%c:%s seen on %s", node_ordinal, remote_interface_name, interface->name() ); _spine_notified = true; monitor->topology_changed(); } /* vim: set autoindent expandtab sw=4 : */ <commit_msg>fix compile errors<commit_after> /* * Copyright (c) 2012 Karl N. Redgate * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** \file Neighbor.cc * \brief * */ #include <stdint.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/wait.h> #include <arpa/inet.h> #include <stdlib.h> #include <signal.h> #include <fcntl.h> #include <time.h> #include <string.h> #include <glob.h> #include <errno.h> #include <tcl.h> #include "tcl_util.h" #include "logger.h" #include "util.h" #include "Neighbor.h" #include "NodeIterator.h" #include "Interface.h" /* * I do not like this - try to eliminate OS defines */ #if defined(__APPLE__) || defined(__darwin__) /* OSX seems not to define these. */ #ifndef s6_addr16 #define s6_addr16 __u6_addr.__u6_addr16 #endif #ifndef s6_addr32 #define s6_addr32 __u6_addr.__u6_addr32 #endif #endif namespace { int debug = 0; } /** */ void Network::Node::uuid( UUID& that ) { _uuid = that; _ordinal = 255; valid = true; // log_notice( "new node allocated with uuid %s", _uuid.to_s() ); } /** */ void Network::Node::ordinal( uint8_t value ) { _ordinal = value; // log_notice( "node%d %s", _ordinal, _uuid.to_s() ); } /** */ bool Network::Node::operator == ( UUID& that ) { return _uuid == that; } /** */ bool Network::Node::operator != ( UUID& that ) { return _uuid != that; } /** * Used to iterate through the node list and clear the partner * bit in all entries. */ class ClearNodePartner : public Network::NodeIterator { public: ClearNodePartner() {} virtual ~ClearNodePartner() {} virtual int operator() ( Network::Node& node ) { if ( node.not_partner() ) return 0; log_notice( "clear partner [%s]", node.uuid().to_s() ); node.clear_partner(); return 1; } }; /** */ Network::Peer::~Peer() { if ( _name != NULL ) free( _name ); _name = NULL; } /** * This one should be deprecated */ Network::Peer::Peer( Network::Node *__node, struct in6_addr *address ) : _node(__node), _ordinal(0), _name(NULL) { memcpy( &lladdr, address, sizeof lladdr ); memset( &neighbor_updated, 0, sizeof neighbor_updated ); } /** */ void Network::Peer::node( Node *that ) { _node = that; /* * Here we have just discovered a new partner. If this was the * cached partner, then the _node would already be a partner. * Since it was not and the neighbor is a partner - it must * have been discovered on priv0, which either overrides the * cached partner (node replace or the like) or this is the * first time we have discovered the partner. Either way * we need to cache the newly discovered partner. */ if ( is_partner() and _node->not_partner() ) { _node->make_partner(); log_notice( "node %s is partner", _node->uuid().to_s() ); } /* * Cases that are ignored: * peer->not_partner() and _node->not_partner() * -- who cares about this neighbor * * peer->is_partner() and _node->is_partner() * -- we already have all necessary state * */ if ( debug < 2 ) return; char buffer[80]; const char *address_string = inet_ntop(AF_INET6, &lladdr, buffer, sizeof buffer); log_notice( "%s at %s is node %s", (_node->is_partner() ? "partner" : "neighbor"), address_string, _node->uuid().to_s() ); } /** */ Network::Node * Network::Peer::node() const { return _node; } /** * Since this is a sort of allocation method, maybe this should check if * already valid and either disallow usage -- or at least report that the * address is changing. */ void Network::Peer::address( struct in6_addr *addr ) { memcpy( &lladdr, addr, sizeof lladdr ); valid = true; if ( debug < 2 ) return; char buffer[80]; const char *address_string = inet_ntop(AF_INET6, addr, buffer, sizeof buffer); log_notice( "new neighbor %s", address_string ); } /** */ void Network::Peer::set_interface( bool set_private, uint8_t set_ordinal ) { _is_private = set_private; _ordinal = set_ordinal; } /** */ void Network::Peer::set_interface_name( char *name ) { if ( name == NULL ) { // If the new name is NULL... if ( _name != NULL ) { // ...and the Peer had a name... free( _name ); // ...free the old name... _name = NULL; // ...and invalidate the name. } return; } if ( _name != NULL ) { // If the Peer already has a name... if ( strcmp( name, _name ) ) { // ...and it is *not* the same name... free( _name ); // ...free the old name... _name = strdup( name ); // ...and copy the new name. } // If it *is* the same name, don't do free()/strdup() } else { // If the Peer does not have a name... _name = strdup( name ); // ...copy the new name. } } /** */ void Network::Peer::copy_address( struct in6_addr *address ) const { memcpy( address, &lladdr, sizeof lladdr ); } /** */ void Network::Peer::touch_advertised() { gettimeofday( &neighbor_advertised, 0 ); } /** */ void Network::Peer::touch() { gettimeofday( &neighbor_updated, 0 ); } /** */ int Network::Peer::seconds_since_last_update() const { struct timeval now; gettimeofday( &now, 0 ); return now.tv_sec - neighbor_updated.tv_sec; } /** */ bool Network::Peer::operator == ( struct in6_addr& that ) { if ( that.s6_addr32[0] != lladdr.s6_addr32[0] ) return false; if ( that.s6_addr32[1] != lladdr.s6_addr32[1] ) return false; if ( that.s6_addr32[2] != lladdr.s6_addr32[2] ) return false; if ( that.s6_addr32[3] != lladdr.s6_addr32[3] ) return false; return true; } /** */ bool Network::Peer::operator != ( struct in6_addr& that ) { if ( that.s6_addr32[0] != lladdr.s6_addr32[0] ) return true; if ( that.s6_addr32[1] != lladdr.s6_addr32[1] ) return true; if ( that.s6_addr32[2] != lladdr.s6_addr32[2] ) return true; if ( that.s6_addr32[3] != lladdr.s6_addr32[3] ) return true; return false; } /** */ bool Network::Peer::has_address( struct in6_addr *address ) { if ( address->s6_addr32[0] != lladdr.s6_addr32[0] ) return false; if ( address->s6_addr32[1] != lladdr.s6_addr32[1] ) return false; if ( address->s6_addr32[2] != lladdr.s6_addr32[2] ) return false; if ( address->s6_addr32[3] != lladdr.s6_addr32[3] ) return false; return true; } /** */ static void construct_remote_interface_name( Network::Peer *neighbor, char *name, int size ) { if ( neighbor->name() != NULL ) { strncpy( name, neighbor->name(), size ); } else { int ordinal = neighbor->ordinal(); if ( neighbor->is_private() ) { if ( ordinal & 0x40 ) { int slot = ( ordinal & 0x3c ) >> 2; int port = ( ordinal & 0x03); snprintf( name, size, "sync_pci%dp%d", slot, port ); } else { snprintf( name, size, "priv%d", ordinal ); } } else { snprintf( name, size, "ibiz%d", ordinal ); } } } /** */ void Network::Peer::topology_changed( Network::Monitor *monitor, Network::Interface *interface ) { char node_ordinal = (node() == NULL) ? '?' : ('0' + node()->ordinal()); char remote_interface_name[32]; construct_remote_interface_name( this, remote_interface_name, sizeof(remote_interface_name) ); log_notice( "Topology change: node%c:%s seen on %s", node_ordinal, remote_interface_name, interface->name() ); _spine_notified = true; } /* vim: set autoindent expandtab sw=4 : */ <|endoftext|>
<commit_before>#include "main.h" void mainLoop() { handleInput(); glfwGetFramebufferSize(window, &width, &height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // bottom-left: Euler Camera (float) drawQuarter(0, 0, width/2, height/2, rcamf); // bottom-right: Euler Camera (double) drawQuarter(width/2, 0, width/2, height/2, rcamd); // top-left: Quaternion Camera (float) drawQuarter(0, height/2, width/2, height/2, qcamf); // top-right: Quaternion Camera (double) drawQuarter(width/2, height/2, width/2, height/2, qcamd); double rdiff = getDifference(rcamf, rcamd); double qdiff = getDifference(qcamf, qcamd); cout.precision(15); cout << std::fixed << rdiff << ", " << qdiff << endl; /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } void handleInput() { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } double x, y; int key; if (is_reading) { if (!(input_file >> mouse_ready)) { glfwSetWindowShouldClose(window, GL_TRUE); return; } input_file >> x >> y; input_file >> key; while (key != -1) { doKeyToCameras(key); input_file >> key; } } else { glfwGetCursorPos(window, &x, &y); if (is_writing) output_file << mouse_ready << " " << x << " " << y << " "; for (unsigned i = 0; i < sizeof(KEYS)/sizeof(int); i++) { if (glfwGetKey(window, KEYS[i]) == GLFW_PRESS) { doKeyToCameras(KEYS[i]); if (is_writing) output_file << KEYS[i] << " "; } } if (is_writing) output_file << "-1" << endl; } mouseMoved(x, y); } void doKeyToCameras(int key) { rcamf->doKey(key); rcamd->doKey(key); qcamf->doKey(key); qcamd->doKey(key); } void mouseCheck(GLFWwindow*,double x,double y) { if (!mouse_ready) { mouse_ready = true; mx = x; my = y; if (is_writing) output_file << "0 " << mx << " " << my << " -1 "; } } void mouseMoved(double x, double y) { if (mouse_ready) { double dx = x - mx; double dy = y - my; rcamf->mouseLook((float)dx,(float)dy); qcamf->mouseLook((float)dx,(float)dy); rcamd->mouseLook(dx,dy); qcamd->mouseLook(dx,dy); } mx = x; my = y; } void initGlfw() { if (!glfwInit()) exit(-1); // Because Apple refuses to keep up with standards! #ifdef __APPLE__ glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif } void init() { initGlfw(); initWindow(); initGlew(); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); if (!is_reading) glfwSetCursorPosCallback(window, mouseCheck); glEnable(GL_VERTEX_ARRAY); glEnable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glClearColor(1,1,1,1); } void initWindow() { window = glfwCreateWindow(640, 480, "Euler vs Hamilton", NULL, NULL); if (!window) { glfwTerminate(); exit(-1); } /* Make the window's context current */ glfwMakeContextCurrent(window); } void initGlew() { glewExperimental = GL_TRUE; glewInit(); } void loadShaders() { shader_program = glCreateProgram(); GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_glsl, NULL); glCompileShader(vertex_shader); shaderLog(vertex_shader); GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_glsl, NULL); glCompileShader(fragment_shader); shaderLog(fragment_shader); glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); glLinkProgram(shader_program); programLog(shader_program); glUseProgram(shader_program); view_location = glGetUniformLocation(shader_program, "view"); projection_location = glGetUniformLocation(shader_program, "projection"); world_location = glGetUniformLocation(shader_program, "world"); } void loadGeometry() { int i = 0; verts[i++] = -1.0f; verts[i++] = 0.0f; verts[i++] = -1.0f; verts[i++] = 1.0f; verts[i++] = 0.0f; verts[i++] = -1.0f; verts[i++] = 1.0f; verts[i++] = 0.0f; verts[i++] = 1.0f; verts[i++] = -1.0f; verts[i++] = 0.0f; verts[i++] = 1.0f; i = 0; faces[i++] = 0; faces[i++] = 2; faces[i++] = 1; faces[i++] = 0; faces[i++] = 3; faces[i++] = 2; GLuint vptr, iptr; glGenVertexArrays(1, &quad); glBindVertexArray(quad); glGenBuffers(1, &vptr); glBindBuffer(GL_ARRAY_BUFFER, vptr); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)(VERTEX_ARRAY_SIZE * sizeof(GLfloat)), verts, GL_STATIC_DRAW); glGenBuffers(1, &iptr); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iptr); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)(INDEX_ARRAY_SIZE * sizeof(GLuint)), faces, GL_STATIC_DRAW); glEnableVertexAttribArray(POSITION_LOC); glVertexAttribPointer(POSITION_LOC, VERTEX_SIZE, GL_FLOAT, GL_FALSE, (GLsizei)(VERTEX_SIZE * sizeof(GLfloat)), 0); world = scale(world, vec3(10,10,10)); glUniformMatrix4fv(world_location, 1, GL_FALSE, value_ptr(world)); } double getDifference(CamF* camf, CamD* camd) { CamD::mat4_type matf = (CamD::mat4_type) camf->getMat(); CamD::mat4_type matd = camd->getMat(); double diff = 0; for (int i = 0; i < 4; i++) { tvec4<double,highp> v = column(matf, i) - column(matd, i); diff += (v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w); } return diff/16.0; } void handleArguments(int argc, char ** argv) { for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-i") == 0) { i++; input_file.open(argv[i]); is_reading = true; } else if (strcmp(argv[i], "-o") == 0) { i++; output_file.open(argv[i]); is_writing = true; } } } int main(int argc, char ** argv) { handleArguments(argc, argv); init(); loadShaders(); loadGeometry(); cout << ("Euler, Quaternion") << endl; /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { mainLoop(); } glfwTerminate(); input_file.close(); output_file.close(); return 0; } <commit_msg>Don't disable cursor if we are reading from file<commit_after>#include "main.h" void mainLoop() { handleInput(); glfwGetFramebufferSize(window, &width, &height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // bottom-left: Euler Camera (float) drawQuarter(0, 0, width/2, height/2, rcamf); // bottom-right: Euler Camera (double) drawQuarter(width/2, 0, width/2, height/2, rcamd); // top-left: Quaternion Camera (float) drawQuarter(0, height/2, width/2, height/2, qcamf); // top-right: Quaternion Camera (double) drawQuarter(width/2, height/2, width/2, height/2, qcamd); double rdiff = getDifference(rcamf, rcamd); double qdiff = getDifference(qcamf, qcamd); cout.precision(15); cout << std::fixed << rdiff << ", " << qdiff << endl; /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } void handleInput() { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } double x, y; int key; if (is_reading) { if (!(input_file >> mouse_ready)) { glfwSetWindowShouldClose(window, GL_TRUE); return; } input_file >> x >> y; input_file >> key; while (key != -1) { doKeyToCameras(key); input_file >> key; } } else { glfwGetCursorPos(window, &x, &y); if (is_writing) output_file << mouse_ready << " " << x << " " << y << " "; for (unsigned i = 0; i < sizeof(KEYS)/sizeof(int); i++) { if (glfwGetKey(window, KEYS[i]) == GLFW_PRESS) { doKeyToCameras(KEYS[i]); if (is_writing) output_file << KEYS[i] << " "; } } if (is_writing) output_file << "-1" << endl; } mouseMoved(x, y); } void doKeyToCameras(int key) { rcamf->doKey(key); rcamd->doKey(key); qcamf->doKey(key); qcamd->doKey(key); } void mouseCheck(GLFWwindow*,double x,double y) { if (!mouse_ready) { mouse_ready = true; mx = x; my = y; if (is_writing) output_file << "0 " << mx << " " << my << " -1 "; } } void mouseMoved(double x, double y) { if (mouse_ready) { double dx = x - mx; double dy = y - my; rcamf->mouseLook((float)dx,(float)dy); qcamf->mouseLook((float)dx,(float)dy); rcamd->mouseLook(dx,dy); qcamd->mouseLook(dx,dy); } mx = x; my = y; } void initGlfw() { if (!glfwInit()) exit(-1); // Because Apple refuses to keep up with standards! #ifdef __APPLE__ glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif } void init() { initGlfw(); initWindow(); initGlew(); if (!is_reading) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPosCallback(window, mouseCheck); } glEnable(GL_VERTEX_ARRAY); glEnable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glClearColor(1,1,1,1); } void initWindow() { window = glfwCreateWindow(640, 480, "Euler vs Hamilton", NULL, NULL); if (!window) { glfwTerminate(); exit(-1); } /* Make the window's context current */ glfwMakeContextCurrent(window); } void initGlew() { glewExperimental = GL_TRUE; glewInit(); } void loadShaders() { shader_program = glCreateProgram(); GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_glsl, NULL); glCompileShader(vertex_shader); shaderLog(vertex_shader); GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_glsl, NULL); glCompileShader(fragment_shader); shaderLog(fragment_shader); glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); glLinkProgram(shader_program); programLog(shader_program); glUseProgram(shader_program); view_location = glGetUniformLocation(shader_program, "view"); projection_location = glGetUniformLocation(shader_program, "projection"); world_location = glGetUniformLocation(shader_program, "world"); } void loadGeometry() { int i = 0; verts[i++] = -1.0f; verts[i++] = 0.0f; verts[i++] = -1.0f; verts[i++] = 1.0f; verts[i++] = 0.0f; verts[i++] = -1.0f; verts[i++] = 1.0f; verts[i++] = 0.0f; verts[i++] = 1.0f; verts[i++] = -1.0f; verts[i++] = 0.0f; verts[i++] = 1.0f; i = 0; faces[i++] = 0; faces[i++] = 2; faces[i++] = 1; faces[i++] = 0; faces[i++] = 3; faces[i++] = 2; GLuint vptr, iptr; glGenVertexArrays(1, &quad); glBindVertexArray(quad); glGenBuffers(1, &vptr); glBindBuffer(GL_ARRAY_BUFFER, vptr); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)(VERTEX_ARRAY_SIZE * sizeof(GLfloat)), verts, GL_STATIC_DRAW); glGenBuffers(1, &iptr); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iptr); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)(INDEX_ARRAY_SIZE * sizeof(GLuint)), faces, GL_STATIC_DRAW); glEnableVertexAttribArray(POSITION_LOC); glVertexAttribPointer(POSITION_LOC, VERTEX_SIZE, GL_FLOAT, GL_FALSE, (GLsizei)(VERTEX_SIZE * sizeof(GLfloat)), 0); world = scale(world, vec3(10,10,10)); glUniformMatrix4fv(world_location, 1, GL_FALSE, value_ptr(world)); } double getDifference(CamF* camf, CamD* camd) { CamD::mat4_type matf = (CamD::mat4_type) camf->getMat(); CamD::mat4_type matd = camd->getMat(); double diff = 0; for (int i = 0; i < 4; i++) { tvec4<double,highp> v = column(matf, i) - column(matd, i); diff += (v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w); } return diff/16.0; } void handleArguments(int argc, char ** argv) { for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-i") == 0) { i++; input_file.open(argv[i]); is_reading = true; } else if (strcmp(argv[i], "-o") == 0) { i++; output_file.open(argv[i]); is_writing = true; } } } int main(int argc, char ** argv) { handleArguments(argc, argv); init(); loadShaders(); loadGeometry(); cout << ("Euler, Quaternion") << endl; /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { mainLoop(); } glfwTerminate(); input_file.close(); output_file.close(); return 0; } <|endoftext|>
<commit_before>/** * Copyright (C) 2013 Regents of the University of California. * @author: Zhenkai Zhu <zhenkai@cs.ucla.edu> * @author: Alexander Afanasyev <alexander.afanasyev@ucla.edu> * @author: Jeff Thompson <jefft0@remap.ucla.edu> * See COPYING for copyright and distribution information. */ #ifndef NDN_SIGNED_BLOB_HPP #define NDN_SIGNED_BLOB_HPP #include "blob.hpp" namespace ndn { /** * A SignedBlob extends Blob to keep the offsets of a signed portion (e.g., the bytes of Data packet). */ class SignedBlob : public Blob { public: /** * Create a new SignedBlob with an immutable copy of the given array. * @param value A pointer to the byte array which is copied. * @param valueLength The length of value. * @param signedPortionBeginOffset The offset in the encoding of the beginning of the signed portion. * @param signedPortionEndOffset The offset in the encoding of the end of the signed portion. */ SignedBlob (const unsigned char* value, unsigned int valueLength, unsigned int signedPortionBeginOffset, unsigned int signedPortionEndOffset) : Blob(value, valueLength), signedPortionBeginOffset_(signedPortionBeginOffset), signedPortionEndOffset_(signedPortionEndOffset) { } /** * Create a new SignedBlob with an immutable copy of the array in the given vector. * If you want to transfer the array without copying, the the vector has to start as a * ptr_lib::shared_ptr<std::vector<unsigned char> > and you can use the SignedBlob constructor with this type. * @param value A reference to a vector which is copied. * @param signedPortionBeginOffset The offset in the encoding of the beginning of the signed portion. * @param signedPortionEndOffset The offset in the encoding of the end of the signed portion. */ SignedBlob (const std::vector<unsigned char> &value, unsigned int signedPortionBeginOffset, unsigned int signedPortionEndOffset) : Blob(value), signedPortionBeginOffset_(signedPortionBeginOffset), signedPortionEndOffset_(signedPortionEndOffset) { } /** * Create a new SignedBlob to point to an existing byte array. IMPORTANT: After calling this constructor, * if you keep a pointer to the array then you must treat the array as immutable and promise not to change it. * @param value A pointer to a vector with the byte array. This takes another reference and does not copy the bytes. * @param signedPortionBeginOffset The offset in the array of the beginning of the signed portion. * @param signedPortionEndOffset The offset in the array of the end of the signed portion. */ SignedBlob (const ptr_lib::shared_ptr<std::vector<unsigned char> > &value, unsigned int signedPortionBeginOffset, unsigned int signedPortionEndOffset) : Blob(value), signedPortionBeginOffset_(signedPortionBeginOffset), signedPortionEndOffset_(signedPortionEndOffset) { } SignedBlob (const ptr_lib::shared_ptr<const std::vector<unsigned char> > &value, unsigned int signedPortionBeginOffset, unsigned int signedPortionEndOffset) : Blob(value), signedPortionBeginOffset_(signedPortionBeginOffset), signedPortionEndOffset_(signedPortionEndOffset) { } /** * Return the length of the signed portion of the immutable byte array, or 0 of the pointer to the array is null. */ unsigned int signedSize() const { if (*this) return signedPortionEndOffset_ - signedPortionBeginOffset_; else return 0; } /** * Return a const pointer to the first byte of the signed portion of the immutable byte array, or 0 if the * pointer to the array is null. */ const unsigned char* signedBuf() const { if (*this) return &(*this)->front() + signedPortionBeginOffset_; else return 0; } /** * Return the offset in the array of the beginning of the signed portion. */ unsigned int getSignedPortionBeginOffset() { return signedPortionBeginOffset_; } /** * Return the offset in the array of the end of the signed portion. */ unsigned int getSignedPortionEndOffset() { return signedPortionEndOffset_; } private: unsigned int signedPortionBeginOffset_; unsigned int signedPortionEndOffset_; }; } #endif <commit_msg>Added a default constructor.<commit_after>/** * Copyright (C) 2013 Regents of the University of California. * @author: Zhenkai Zhu <zhenkai@cs.ucla.edu> * @author: Alexander Afanasyev <alexander.afanasyev@ucla.edu> * @author: Jeff Thompson <jefft0@remap.ucla.edu> * See COPYING for copyright and distribution information. */ #ifndef NDN_SIGNED_BLOB_HPP #define NDN_SIGNED_BLOB_HPP #include "blob.hpp" namespace ndn { /** * A SignedBlob extends Blob to keep the offsets of a signed portion (e.g., the bytes of Data packet). */ class SignedBlob : public Blob { public: /** * Create a new SignedBlob with a null pointer. */ SignedBlob() : signedPortionBeginOffset_(0), signedPortionEndOffset_(0) { } /** * Create a new SignedBlob with an immutable copy of the given array. * @param value A pointer to the byte array which is copied. * @param valueLength The length of value. * @param signedPortionBeginOffset The offset in the encoding of the beginning of the signed portion. * @param signedPortionEndOffset The offset in the encoding of the end of the signed portion. */ SignedBlob (const unsigned char* value, unsigned int valueLength, unsigned int signedPortionBeginOffset, unsigned int signedPortionEndOffset) : Blob(value, valueLength), signedPortionBeginOffset_(signedPortionBeginOffset), signedPortionEndOffset_(signedPortionEndOffset) { } /** * Create a new SignedBlob with an immutable copy of the array in the given vector. * If you want to transfer the array without copying, the the vector has to start as a * ptr_lib::shared_ptr<std::vector<unsigned char> > and you can use the SignedBlob constructor with this type. * @param value A reference to a vector which is copied. * @param signedPortionBeginOffset The offset in the encoding of the beginning of the signed portion. * @param signedPortionEndOffset The offset in the encoding of the end of the signed portion. */ SignedBlob (const std::vector<unsigned char> &value, unsigned int signedPortionBeginOffset, unsigned int signedPortionEndOffset) : Blob(value), signedPortionBeginOffset_(signedPortionBeginOffset), signedPortionEndOffset_(signedPortionEndOffset) { } /** * Create a new SignedBlob to point to an existing byte array. IMPORTANT: After calling this constructor, * if you keep a pointer to the array then you must treat the array as immutable and promise not to change it. * @param value A pointer to a vector with the byte array. This takes another reference and does not copy the bytes. * @param signedPortionBeginOffset The offset in the array of the beginning of the signed portion. * @param signedPortionEndOffset The offset in the array of the end of the signed portion. */ SignedBlob (const ptr_lib::shared_ptr<std::vector<unsigned char> > &value, unsigned int signedPortionBeginOffset, unsigned int signedPortionEndOffset) : Blob(value), signedPortionBeginOffset_(signedPortionBeginOffset), signedPortionEndOffset_(signedPortionEndOffset) { } SignedBlob (const ptr_lib::shared_ptr<const std::vector<unsigned char> > &value, unsigned int signedPortionBeginOffset, unsigned int signedPortionEndOffset) : Blob(value), signedPortionBeginOffset_(signedPortionBeginOffset), signedPortionEndOffset_(signedPortionEndOffset) { } /** * Return the length of the signed portion of the immutable byte array, or 0 of the pointer to the array is null. */ unsigned int signedSize() const { if (*this) return signedPortionEndOffset_ - signedPortionBeginOffset_; else return 0; } /** * Return a const pointer to the first byte of the signed portion of the immutable byte array, or 0 if the * pointer to the array is null. */ const unsigned char* signedBuf() const { if (*this) return &(*this)->front() + signedPortionBeginOffset_; else return 0; } /** * Return the offset in the array of the beginning of the signed portion. */ unsigned int getSignedPortionBeginOffset() { return signedPortionBeginOffset_; } /** * Return the offset in the array of the end of the signed portion. */ unsigned int getSignedPortionEndOffset() { return signedPortionEndOffset_; } private: unsigned int signedPortionBeginOffset_; unsigned int signedPortionEndOffset_; }; } #endif <|endoftext|>
<commit_before><commit_msg>Disk Cache: Make sure that file descriptors are valid before calling close().<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2019 pengjian.uestc @ gmail.com */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "redis/server.hh" #include "service/storage_service.hh" #include "db/consistency_level_type.hh" #include "db/config.hh" #include "db/write_type.hh" #include <seastar/core/future-util.hh> #include <seastar/core/seastar.hh> #include <seastar/net/byteorder.hh> #include <seastar/core/execution_stage.hh> #include "service/query_state.hh" #include "exceptions/exceptions.hh" #include "auth/authenticator.hh" #include <cassert> #include <string> #include "redis/request.hh" #include "redis/reply.hh" #include <unordered_map> namespace redis_transport { static logging::logger logging("redis_server"); redis_server::redis_server(distributed<service::storage_proxy>& proxy, distributed<redis::query_processor>& qp, auth::service& auth_service, redis_server_config config) : _proxy(proxy) , _query_processor(qp) , _config(config) , _max_request_size(config._max_request_size) , _memory_available(_max_request_size) , _auth_service(auth_service) , _total_redis_db_count(config._total_redis_db_count) { } future<> redis_server::stop() { _stopping = true; size_t nr = 0; size_t nr_total = _listeners.size(); logging.debug("redis_server: abort accept nr_total={}", nr_total); for (auto&& l : _listeners) { l.abort_accept(); logging.debug("redis_server: abort accept {} out of {} done", ++nr, nr_total); } auto nr_conn = make_lw_shared<size_t>(0); auto nr_conn_total = _connections_list.size(); logging.debug("redis_server: shutdown connection nr_total={}", nr_conn_total); return parallel_for_each(_connections_list.begin(), _connections_list.end(), [nr_conn, nr_conn_total] (auto&& c) { return c.shutdown().then([nr_conn, nr_conn_total] { logging.debug("redis_server: shutdown connection {} out of {} done", ++(*nr_conn), nr_conn_total); }); }).then([this] { return std::move(_stopped); }); } future<> redis_server::listen(socket_address addr, std::shared_ptr<seastar::tls::credentials_builder> creds, bool keepalive) { listen_options lo; lo.reuse_address = true; server_socket ss; try { ss = creds ? seastar::tls::listen(creds->build_server_credentials(), addr, lo) : seastar::listen(addr, lo); } catch (...) { throw std::runtime_error(sprint("Redis server error while listening on %s -> %s", addr, std::current_exception())); } _listeners.emplace_back(std::move(ss)); _stopped = when_all(std::move(_stopped), do_accepts(_listeners.size() - 1, keepalive, addr)).discard_result(); return make_ready_future<>(); } future<> redis_server::do_accepts(int which, bool keepalive, socket_address server_addr) { return repeat([this, which, keepalive, server_addr] { ++_stats._connections_being_accepted; return _listeners[which].accept().then_wrapped([this, which, keepalive, server_addr] (future<accept_result> f_cs_sa) mutable { --_stats._connections_being_accepted; if (_stopping) { f_cs_sa.ignore_ready_future(); maybe_idle(); return stop_iteration::yes; } auto cs_sa = f_cs_sa.get0(); auto fd = std::move(cs_sa.connection); auto addr = std::move(cs_sa.remote_address); fd.set_nodelay(true); fd.set_keepalive(keepalive); auto conn = make_shared<connection>(*this, server_addr, std::move(fd), std::move(addr)); ++_stats._connects; ++_stats._connections; (void)conn->process().then_wrapped([this, conn] (future<> f) { --_stats._connections; try { f.get(); } catch (...) { logging.debug("connection error: {}", std::current_exception()); } }); return stop_iteration::no; }).handle_exception([] (auto ep) { logging.debug("accept failed: {}", ep); return stop_iteration::no; }); }); } future<redis_server::result> redis_server::connection::process_request_one(redis::request&& request, redis::redis_options& opts, service_permit permit) { return futurize_invoke([this, request = std::move(request), &opts, permit] () mutable { return _server._query_processor.local().process(std::move(request), seastar::ref(opts), permit).then([] (auto&& message) { return make_ready_future<redis_server::result> (std::move(message)); }); }); } redis_server::connection::connection(redis_server& server, socket_address server_addr, connected_socket&& fd, socket_address addr) : _server(server) , _server_addr(server_addr) , _fd(std::move(fd)) , _read_buf(_fd.input()) , _write_buf(_fd.output()) , _options(server._config._read_consistency_level, server._config._write_consistency_level, server._config._timeout_config, server._auth_service, addr, server._total_redis_db_count) { ++_server._stats._total_connections; ++_server._stats._current_connections; _server._connections_list.push_back(*this); } redis_server::connection::~connection() { --_server._stats._current_connections; _server._connections_list.erase(_server._connections_list.iterator_to(*this)); _server.maybe_idle(); } future<> redis_server::connection::process() { return do_until([this] { return _read_buf.eof(); }, [this] { return with_gate(_pending_requests_gate, [this] { return process_request().then_wrapped([this] (auto f) { try { f.get(); } catch (redis_exception& e) { write_reply(e); } catch (std::exception& e) { write_reply(redis_exception { e.what() }); } catch (...) { write_reply(redis_exception { "Unknown exception" }); } }); }); }).finally([this] { return _pending_requests_gate.close().then([this] { return _ready_to_respond.finally([this] { return _write_buf.close(); }); }); }); } future<> redis_server::connection::shutdown() { try { _fd.shutdown_input(); _fd.shutdown_output(); } catch (...) { } return make_ready_future<>(); } thread_local redis_server::connection::execution_stage_type redis_server::connection::_process_request_stage {"redis_transport", &connection::process_request_one}; future<redis_server::result> redis_server::connection::process_request_internal() { return _process_request_stage(this, std::move(_parser.get_request()), seastar::ref(_options), empty_service_permit()); } void redis_server::connection::write_reply(const redis_exception& e) { _ready_to_respond = _ready_to_respond.then([this, exception_message = e.what_message()] () mutable { return redis_message::exception(exception_message).then([this] (auto&& result) { auto m = result.message(); return _write_buf.write(std::move(*m)).then([this] { return _write_buf.flush(); }); }); }); } void redis_server::connection::write_reply(redis_server::result result) { _ready_to_respond = _ready_to_respond.then([this, result = std::move(result)] () mutable { auto m = result.make_message(); return _write_buf.write(std::move(*m)).then([this] { return _write_buf.flush(); }); }); } future<> redis_server::connection::process_request() { _parser.init(); return _read_buf.consume(_parser).then([this] { if (_parser.eof()) { return make_ready_future<>(); } ++_server._stats._requests_serving; _pending_requests_gate.enter(); utils::latency_counter lc; lc.start(); auto leave = defer([this] { _pending_requests_gate.leave(); }); return process_request_internal().then([this, leave = std::move(leave), lc = std::move(lc)] (auto&& result) mutable { --_server._stats._requests_serving; try { write_reply(std::move(result)); ++_server._stats._requests_served; _server._stats._requests.mark(lc.stop().latency()); if (lc.is_start()) { _server._stats._estimated_requests_latency.add(lc.latency(), _server._stats._requests.hist.count); } } catch (...) { logging.error("request processing failed: {}", std::current_exception()); } }); }); } static inline bytes_view to_bytes_view(temporary_buffer<char>& b) { using byte = bytes_view::value_type; return bytes_view(reinterpret_cast<const byte*>(b.get()), b.size()); } } db::consistency_level make_consistency_level(const sstring& level) { std::unordered_map<sstring, db::consistency_level> consistency_levels { {"ONE", db::consistency_level::ONE}, {"QUORUM", db::consistency_level::QUORUM}, {"LOCAL_QUORUM", db::consistency_level::LOCAL_QUORUM}, {"EACH_QUORUM", db::consistency_level::EACH_QUORUM}, {"ALL", db::consistency_level::ALL}, {"ANY", db::consistency_level::ANY}, {"TWO", db::consistency_level::TWO}, {"THREE", db::consistency_level::THREE}, {"SERIAL", db::consistency_level::SERIAL}, {"LOCAL_SERIAL", db::consistency_level::LOCAL_SERIAL}, {"LOCAL_ONE", db::consistency_level::LOCAL_ONE}, }; auto iter_cl = consistency_levels.find(level); if (iter_cl == consistency_levels.end()) { return db::consistency_level::ONE; } return iter_cl->second; } <commit_msg>redis: Use reloadable tls certificates<commit_after>/* * Copyright (C) 2019 pengjian.uestc @ gmail.com */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "redis/server.hh" #include "service/storage_service.hh" #include "db/consistency_level_type.hh" #include "db/config.hh" #include "db/write_type.hh" #include <seastar/core/future-util.hh> #include <seastar/core/seastar.hh> #include <seastar/net/byteorder.hh> #include <seastar/core/execution_stage.hh> #include "service/query_state.hh" #include "exceptions/exceptions.hh" #include "auth/authenticator.hh" #include <cassert> #include <string> #include "redis/request.hh" #include "redis/reply.hh" #include <unordered_map> namespace redis_transport { static logging::logger logging("redis_server"); redis_server::redis_server(distributed<service::storage_proxy>& proxy, distributed<redis::query_processor>& qp, auth::service& auth_service, redis_server_config config) : _proxy(proxy) , _query_processor(qp) , _config(config) , _max_request_size(config._max_request_size) , _memory_available(_max_request_size) , _auth_service(auth_service) , _total_redis_db_count(config._total_redis_db_count) { } future<> redis_server::stop() { _stopping = true; size_t nr = 0; size_t nr_total = _listeners.size(); logging.debug("redis_server: abort accept nr_total={}", nr_total); for (auto&& l : _listeners) { l.abort_accept(); logging.debug("redis_server: abort accept {} out of {} done", ++nr, nr_total); } auto nr_conn = make_lw_shared<size_t>(0); auto nr_conn_total = _connections_list.size(); logging.debug("redis_server: shutdown connection nr_total={}", nr_conn_total); return parallel_for_each(_connections_list.begin(), _connections_list.end(), [nr_conn, nr_conn_total] (auto&& c) { return c.shutdown().then([nr_conn, nr_conn_total] { logging.debug("redis_server: shutdown connection {} out of {} done", ++(*nr_conn), nr_conn_total); }); }).then([this] { return std::move(_stopped); }); } future<> redis_server::listen(socket_address addr, std::shared_ptr<seastar::tls::credentials_builder> creds, bool keepalive) { auto f = make_ready_future<shared_ptr<seastar::tls::server_credentials>>(nullptr); if (creds) { f = creds->build_reloadable_server_credentials([](const std::unordered_set<sstring>& files, std::exception_ptr ep) { if (ep) { logging.warn("Exception loading {}: {}", files, ep); } else { logging.info("Reloaded {}", files); } }); } return f.then([this, addr, keepalive](shared_ptr<seastar::tls::server_credentials> creds) { listen_options lo; lo.reuse_address = true; server_socket ss; try { ss = creds ? seastar::tls::listen(std::move(creds), addr, lo) : seastar::listen(addr, lo); } catch (...) { throw std::runtime_error(sprint("Redis server error while listening on %s -> %s", addr, std::current_exception())); } _listeners.emplace_back(std::move(ss)); _stopped = when_all(std::move(_stopped), do_accepts(_listeners.size() - 1, keepalive, addr)).discard_result(); }); } future<> redis_server::do_accepts(int which, bool keepalive, socket_address server_addr) { return repeat([this, which, keepalive, server_addr] { ++_stats._connections_being_accepted; return _listeners[which].accept().then_wrapped([this, which, keepalive, server_addr] (future<accept_result> f_cs_sa) mutable { --_stats._connections_being_accepted; if (_stopping) { f_cs_sa.ignore_ready_future(); maybe_idle(); return stop_iteration::yes; } auto cs_sa = f_cs_sa.get0(); auto fd = std::move(cs_sa.connection); auto addr = std::move(cs_sa.remote_address); fd.set_nodelay(true); fd.set_keepalive(keepalive); auto conn = make_shared<connection>(*this, server_addr, std::move(fd), std::move(addr)); ++_stats._connects; ++_stats._connections; (void)conn->process().then_wrapped([this, conn] (future<> f) { --_stats._connections; try { f.get(); } catch (...) { logging.debug("connection error: {}", std::current_exception()); } }); return stop_iteration::no; }).handle_exception([] (auto ep) { logging.debug("accept failed: {}", ep); return stop_iteration::no; }); }); } future<redis_server::result> redis_server::connection::process_request_one(redis::request&& request, redis::redis_options& opts, service_permit permit) { return futurize_invoke([this, request = std::move(request), &opts, permit] () mutable { return _server._query_processor.local().process(std::move(request), seastar::ref(opts), permit).then([] (auto&& message) { return make_ready_future<redis_server::result> (std::move(message)); }); }); } redis_server::connection::connection(redis_server& server, socket_address server_addr, connected_socket&& fd, socket_address addr) : _server(server) , _server_addr(server_addr) , _fd(std::move(fd)) , _read_buf(_fd.input()) , _write_buf(_fd.output()) , _options(server._config._read_consistency_level, server._config._write_consistency_level, server._config._timeout_config, server._auth_service, addr, server._total_redis_db_count) { ++_server._stats._total_connections; ++_server._stats._current_connections; _server._connections_list.push_back(*this); } redis_server::connection::~connection() { --_server._stats._current_connections; _server._connections_list.erase(_server._connections_list.iterator_to(*this)); _server.maybe_idle(); } future<> redis_server::connection::process() { return do_until([this] { return _read_buf.eof(); }, [this] { return with_gate(_pending_requests_gate, [this] { return process_request().then_wrapped([this] (auto f) { try { f.get(); } catch (redis_exception& e) { write_reply(e); } catch (std::exception& e) { write_reply(redis_exception { e.what() }); } catch (...) { write_reply(redis_exception { "Unknown exception" }); } }); }); }).finally([this] { return _pending_requests_gate.close().then([this] { return _ready_to_respond.finally([this] { return _write_buf.close(); }); }); }); } future<> redis_server::connection::shutdown() { try { _fd.shutdown_input(); _fd.shutdown_output(); } catch (...) { } return make_ready_future<>(); } thread_local redis_server::connection::execution_stage_type redis_server::connection::_process_request_stage {"redis_transport", &connection::process_request_one}; future<redis_server::result> redis_server::connection::process_request_internal() { return _process_request_stage(this, std::move(_parser.get_request()), seastar::ref(_options), empty_service_permit()); } void redis_server::connection::write_reply(const redis_exception& e) { _ready_to_respond = _ready_to_respond.then([this, exception_message = e.what_message()] () mutable { return redis_message::exception(exception_message).then([this] (auto&& result) { auto m = result.message(); return _write_buf.write(std::move(*m)).then([this] { return _write_buf.flush(); }); }); }); } void redis_server::connection::write_reply(redis_server::result result) { _ready_to_respond = _ready_to_respond.then([this, result = std::move(result)] () mutable { auto m = result.make_message(); return _write_buf.write(std::move(*m)).then([this] { return _write_buf.flush(); }); }); } future<> redis_server::connection::process_request() { _parser.init(); return _read_buf.consume(_parser).then([this] { if (_parser.eof()) { return make_ready_future<>(); } ++_server._stats._requests_serving; _pending_requests_gate.enter(); utils::latency_counter lc; lc.start(); auto leave = defer([this] { _pending_requests_gate.leave(); }); return process_request_internal().then([this, leave = std::move(leave), lc = std::move(lc)] (auto&& result) mutable { --_server._stats._requests_serving; try { write_reply(std::move(result)); ++_server._stats._requests_served; _server._stats._requests.mark(lc.stop().latency()); if (lc.is_start()) { _server._stats._estimated_requests_latency.add(lc.latency(), _server._stats._requests.hist.count); } } catch (...) { logging.error("request processing failed: {}", std::current_exception()); } }); }); } static inline bytes_view to_bytes_view(temporary_buffer<char>& b) { using byte = bytes_view::value_type; return bytes_view(reinterpret_cast<const byte*>(b.get()), b.size()); } } db::consistency_level make_consistency_level(const sstring& level) { std::unordered_map<sstring, db::consistency_level> consistency_levels { {"ONE", db::consistency_level::ONE}, {"QUORUM", db::consistency_level::QUORUM}, {"LOCAL_QUORUM", db::consistency_level::LOCAL_QUORUM}, {"EACH_QUORUM", db::consistency_level::EACH_QUORUM}, {"ALL", db::consistency_level::ALL}, {"ANY", db::consistency_level::ANY}, {"TWO", db::consistency_level::TWO}, {"THREE", db::consistency_level::THREE}, {"SERIAL", db::consistency_level::SERIAL}, {"LOCAL_SERIAL", db::consistency_level::LOCAL_SERIAL}, {"LOCAL_ONE", db::consistency_level::LOCAL_ONE}, }; auto iter_cl = consistency_levels.find(level); if (iter_cl == consistency_levels.end()) { return db::consistency_level::ONE; } return iter_cl->second; } <|endoftext|>
<commit_before>/* * Copyright 2011, Blender Foundation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "tile.h" #include "util_algorithm.h" #include "util_types.h" CCL_NAMESPACE_BEGIN TileManager::TileManager(bool progressive_, int num_samples_, int2 tile_size_, int start_resolution_, bool preserve_tile_device_, bool background_, int num_devices_) { progressive = progressive_; tile_size = tile_size_; start_resolution = start_resolution_; num_devices = num_devices_; preserve_tile_device = preserve_tile_device_; background = background_; BufferParams buffer_params; reset(buffer_params, 0); } TileManager::~TileManager() { } void TileManager::reset(BufferParams& params_, int num_samples_) { params = params_; int divider = 1; int w = params.width, h = params.height; if(start_resolution != INT_MAX) { while(w*h > start_resolution*start_resolution) { w = max(1, w/2); h = max(1, h/2); divider *= 2; } } num_samples = num_samples_; state.buffer = BufferParams(); state.sample = -1; state.num_tiles = 0; state.num_rendered_tiles = 0; state.num_samples = 0; state.resolution_divider = divider; state.tiles.clear(); } void TileManager::set_samples(int num_samples_) { num_samples = num_samples_; } /* splits image into tiles and assigns equal amount of tiles to every render device */ void TileManager::gen_tiles_global() { int resolution = state.resolution_divider; int image_w = max(1, params.width/resolution); int image_h = max(1, params.height/resolution); state.tiles.clear(); int tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)/tile_size.x; int tile_h = (tile_size.y >= image_h)? 1: (image_h + tile_size.y - 1)/tile_size.y; int num_logical_devices = preserve_tile_device? num_devices: 1; int num = min(image_h, num_logical_devices); int tile_index = 0; int tiles_per_device = (tile_w * tile_h + num - 1) / num; int cur_device = 0, cur_tiles = 0; for(int tile_y = 0; tile_y < tile_h; tile_y++) { for(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) { int x = tile_x * tile_size.x; int y = tile_y * tile_size.y; int w = (tile_x == tile_w-1)? image_w - x: tile_size.x; int h = (tile_y == tile_h-1)? image_h - y: tile_size.y; state.tiles.push_back(Tile(tile_index, x, y, w, h, cur_device)); cur_tiles++; if(cur_tiles == tiles_per_device) { cur_tiles = 0; cur_device++; } } } } /* slices image into as much pieces as how many devices are rendering this image */ void TileManager::gen_tiles_sliced() { int resolution = state.resolution_divider; int image_w = max(1, params.width/resolution); int image_h = max(1, params.height/resolution); state.tiles.clear(); int num_logical_devices = preserve_tile_device? num_devices: 1; int num = min(image_h, num_logical_devices); int tile_index = 0; for(int device = 0; device < num; device++) { int device_y = (image_h/num)*device; int device_h = (device == num-1)? image_h - device*(image_h/num): image_h/num; int tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)/tile_size.x; int tile_h = (tile_size.y >= device_h)? 1: (device_h + tile_size.y - 1)/tile_size.y; for(int tile_y = 0; tile_y < tile_h; tile_y++) { for(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) { int x = tile_x * tile_size.x; int y = tile_y * tile_size.y; int w = (tile_x == tile_w-1)? image_w - x: tile_size.x; int h = (tile_y == tile_h-1)? device_h - y: tile_size.x; state.tiles.push_back(Tile(tile_index, x, y + device_y, w, h, device)); } } } } void TileManager::set_tiles() { int resolution = state.resolution_divider; int image_w = max(1, params.width/resolution); int image_h = max(1, params.height/resolution); if(background) gen_tiles_global(); else gen_tiles_sliced(); state.num_tiles = state.tiles.size(); state.buffer.width = image_w; state.buffer.height = image_h; state.buffer.full_x = params.full_x/resolution; state.buffer.full_y = params.full_y/resolution; state.buffer.full_width = max(1, params.full_width/resolution); state.buffer.full_height = max(1, params.full_height/resolution); } list<Tile>::iterator TileManager::next_center_tile(int device) { list<Tile>::iterator iter, best = state.tiles.end(); int resolution = state.resolution_divider; int image_w = max(1, params.width/resolution); int image_h = max(1, params.height/resolution); int logical_device = preserve_tile_device? device: 0; int64_t centx = image_w / 2, centy = image_h / 2, tot = 1; int64_t mindist = (int64_t) image_w * (int64_t) image_h; /* find center of rendering tiles, image center counts for 1 too */ for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) { if(iter->rendering) { Tile &cur_tile = *iter; centx += cur_tile.x + cur_tile.w / 2; centy += cur_tile.y + cur_tile.h / 2; tot++; } } centx /= tot; centy /= tot; /* closest of the non-rendering tiles */ for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) { if(iter->device == logical_device && iter->rendering == false) { Tile &cur_tile = *iter; int64_t distx = centx - (cur_tile.x + cur_tile.w / 2); int64_t disty = centy - (cur_tile.y + cur_tile.h / 2); distx = (int64_t) sqrt((double)distx * distx + disty * disty); if(distx < mindist) { best = iter; mindist = distx; } } } return best; } list<Tile>::iterator TileManager::next_simple_tile(int device) { list<Tile>::iterator iter; int logical_device = preserve_tile_device? device: 0; for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) { if(iter->device == logical_device && iter->rendering == false) return iter; } return state.tiles.end(); } bool TileManager::next_tile(Tile& tile, int device) { list<Tile>::iterator tile_it; if(background) tile_it = next_center_tile(device); else tile_it = next_simple_tile(device); if(tile_it != state.tiles.end()) { tile_it->rendering = true; tile = *tile_it; state.num_rendered_tiles++; return true; } return false; } bool TileManager::done() { return (state.sample+state.num_samples >= num_samples && state.resolution_divider == 1); } bool TileManager::next() { if(done()) return false; if(progressive && state.resolution_divider > 1) { state.sample = 0; state.resolution_divider /= 2; state.num_samples = 1; set_tiles(); } else { state.sample++; if(progressive) state.num_samples = 1; else state.num_samples = num_samples; state.resolution_divider = 1; set_tiles(); } return true; } CCL_NAMESPACE_END <commit_msg>Stupid copy-paste typo in tiles commit.<commit_after>/* * Copyright 2011, Blender Foundation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "tile.h" #include "util_algorithm.h" #include "util_types.h" CCL_NAMESPACE_BEGIN TileManager::TileManager(bool progressive_, int num_samples_, int2 tile_size_, int start_resolution_, bool preserve_tile_device_, bool background_, int num_devices_) { progressive = progressive_; tile_size = tile_size_; start_resolution = start_resolution_; num_devices = num_devices_; preserve_tile_device = preserve_tile_device_; background = background_; BufferParams buffer_params; reset(buffer_params, 0); } TileManager::~TileManager() { } void TileManager::reset(BufferParams& params_, int num_samples_) { params = params_; int divider = 1; int w = params.width, h = params.height; if(start_resolution != INT_MAX) { while(w*h > start_resolution*start_resolution) { w = max(1, w/2); h = max(1, h/2); divider *= 2; } } num_samples = num_samples_; state.buffer = BufferParams(); state.sample = -1; state.num_tiles = 0; state.num_rendered_tiles = 0; state.num_samples = 0; state.resolution_divider = divider; state.tiles.clear(); } void TileManager::set_samples(int num_samples_) { num_samples = num_samples_; } /* splits image into tiles and assigns equal amount of tiles to every render device */ void TileManager::gen_tiles_global() { int resolution = state.resolution_divider; int image_w = max(1, params.width/resolution); int image_h = max(1, params.height/resolution); state.tiles.clear(); int tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)/tile_size.x; int tile_h = (tile_size.y >= image_h)? 1: (image_h + tile_size.y - 1)/tile_size.y; int num_logical_devices = preserve_tile_device? num_devices: 1; int num = min(image_h, num_logical_devices); int tile_index = 0; int tiles_per_device = (tile_w * tile_h + num - 1) / num; int cur_device = 0, cur_tiles = 0; for(int tile_y = 0; tile_y < tile_h; tile_y++) { for(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) { int x = tile_x * tile_size.x; int y = tile_y * tile_size.y; int w = (tile_x == tile_w-1)? image_w - x: tile_size.x; int h = (tile_y == tile_h-1)? image_h - y: tile_size.y; state.tiles.push_back(Tile(tile_index, x, y, w, h, cur_device)); cur_tiles++; if(cur_tiles == tiles_per_device) { cur_tiles = 0; cur_device++; } } } } /* slices image into as much pieces as how many devices are rendering this image */ void TileManager::gen_tiles_sliced() { int resolution = state.resolution_divider; int image_w = max(1, params.width/resolution); int image_h = max(1, params.height/resolution); state.tiles.clear(); int num_logical_devices = preserve_tile_device? num_devices: 1; int num = min(image_h, num_logical_devices); int tile_index = 0; for(int device = 0; device < num; device++) { int device_y = (image_h/num)*device; int device_h = (device == num-1)? image_h - device*(image_h/num): image_h/num; int tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)/tile_size.x; int tile_h = (tile_size.y >= device_h)? 1: (device_h + tile_size.y - 1)/tile_size.y; for(int tile_y = 0; tile_y < tile_h; tile_y++) { for(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) { int x = tile_x * tile_size.x; int y = tile_y * tile_size.y; int w = (tile_x == tile_w-1)? image_w - x: tile_size.x; int h = (tile_y == tile_h-1)? device_h - y: tile_size.y; state.tiles.push_back(Tile(tile_index, x, y + device_y, w, h, device)); } } } } void TileManager::set_tiles() { int resolution = state.resolution_divider; int image_w = max(1, params.width/resolution); int image_h = max(1, params.height/resolution); if(background) gen_tiles_global(); else gen_tiles_sliced(); state.num_tiles = state.tiles.size(); state.buffer.width = image_w; state.buffer.height = image_h; state.buffer.full_x = params.full_x/resolution; state.buffer.full_y = params.full_y/resolution; state.buffer.full_width = max(1, params.full_width/resolution); state.buffer.full_height = max(1, params.full_height/resolution); } list<Tile>::iterator TileManager::next_center_tile(int device) { list<Tile>::iterator iter, best = state.tiles.end(); int resolution = state.resolution_divider; int image_w = max(1, params.width/resolution); int image_h = max(1, params.height/resolution); int logical_device = preserve_tile_device? device: 0; int64_t centx = image_w / 2, centy = image_h / 2, tot = 1; int64_t mindist = (int64_t) image_w * (int64_t) image_h; /* find center of rendering tiles, image center counts for 1 too */ for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) { if(iter->rendering) { Tile &cur_tile = *iter; centx += cur_tile.x + cur_tile.w / 2; centy += cur_tile.y + cur_tile.h / 2; tot++; } } centx /= tot; centy /= tot; /* closest of the non-rendering tiles */ for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) { if(iter->device == logical_device && iter->rendering == false) { Tile &cur_tile = *iter; int64_t distx = centx - (cur_tile.x + cur_tile.w / 2); int64_t disty = centy - (cur_tile.y + cur_tile.h / 2); distx = (int64_t) sqrt((double)distx * distx + disty * disty); if(distx < mindist) { best = iter; mindist = distx; } } } return best; } list<Tile>::iterator TileManager::next_simple_tile(int device) { list<Tile>::iterator iter; int logical_device = preserve_tile_device? device: 0; for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) { if(iter->device == logical_device && iter->rendering == false) return iter; } return state.tiles.end(); } bool TileManager::next_tile(Tile& tile, int device) { list<Tile>::iterator tile_it; if(background) tile_it = next_center_tile(device); else tile_it = next_simple_tile(device); if(tile_it != state.tiles.end()) { tile_it->rendering = true; tile = *tile_it; state.num_rendered_tiles++; return true; } return false; } bool TileManager::done() { return (state.sample+state.num_samples >= num_samples && state.resolution_divider == 1); } bool TileManager::next() { if(done()) return false; if(progressive && state.resolution_divider > 1) { state.sample = 0; state.resolution_divider /= 2; state.num_samples = 1; set_tiles(); } else { state.sample++; if(progressive) state.num_samples = 1; else state.num_samples = num_samples; state.resolution_divider = 1; set_tiles(); } return true; } CCL_NAMESPACE_END <|endoftext|>
<commit_before>#pragma once #include "constants.hpp" #include "libkrbn/libkrbn.h" #include "logger.hpp" #include <pqrs/spdlog.hpp> class libkrbn_log_lines_class final { public: libkrbn_log_lines_class(std::shared_ptr<std::deque<std::string>> lines) : lines_(lines) { } std::shared_ptr<std::deque<std::string>> get_lines(void) const { return lines_; } private: std::shared_ptr<std::deque<std::string>> lines_; }; class libkrbn_log_monitor final { public: libkrbn_log_monitor(const libkrbn_log_monitor&) = delete; libkrbn_log_monitor(libkrbn_log_monitor_callback callback, void* refcon) { krbn::logger::get_logger()->info(__func__); std::vector<std::string> targets = { "/var/log/karabiner/observer.log", "/var/log/karabiner/grabber.log", fmt::format("/var/log/karabiner/session_monitor.{0}.log", geteuid()), }; auto log_directory = krbn::constants::get_user_log_directory(); if (!log_directory.empty()) { targets.push_back(log_directory + "/console_user_server.log"); } monitor_ = std::make_unique<pqrs::spdlog::monitor>(pqrs::dispatcher::extra::get_shared_dispatcher(), targets, 250); monitor_->log_file_updated.connect([callback, refcon](auto&& lines) { if (callback) { auto log_lines = new libkrbn_log_lines_class(lines); callback(reinterpret_cast<libkrbn_log_lines*>(log_lines), refcon); delete log_lines; } }); monitor_->async_start(std::chrono::milliseconds(1000)); } ~libkrbn_log_monitor(void) { krbn::logger::get_logger()->info(__func__); } private: std::unique_ptr<pqrs::spdlog::monitor> monitor_; }; <commit_msg>add kextd.log to libkrbn_log_monitor<commit_after>#pragma once #include "constants.hpp" #include "libkrbn/libkrbn.h" #include "logger.hpp" #include <pqrs/spdlog.hpp> class libkrbn_log_lines_class final { public: libkrbn_log_lines_class(std::shared_ptr<std::deque<std::string>> lines) : lines_(lines) { } std::shared_ptr<std::deque<std::string>> get_lines(void) const { return lines_; } private: std::shared_ptr<std::deque<std::string>> lines_; }; class libkrbn_log_monitor final { public: libkrbn_log_monitor(const libkrbn_log_monitor&) = delete; libkrbn_log_monitor(libkrbn_log_monitor_callback callback, void* refcon) { krbn::logger::get_logger()->info(__func__); std::vector<std::string> targets = { "/var/log/karabiner/kextd.log", "/var/log/karabiner/grabber.log", "/var/log/karabiner/observer.log", fmt::format("/var/log/karabiner/session_monitor.{0}.log", geteuid()), }; auto log_directory = krbn::constants::get_user_log_directory(); if (!log_directory.empty()) { targets.push_back(log_directory + "/console_user_server.log"); } monitor_ = std::make_unique<pqrs::spdlog::monitor>(pqrs::dispatcher::extra::get_shared_dispatcher(), targets, 250); monitor_->log_file_updated.connect([callback, refcon](auto&& lines) { if (callback) { auto log_lines = new libkrbn_log_lines_class(lines); callback(reinterpret_cast<libkrbn_log_lines*>(log_lines), refcon); delete log_lines; } }); monitor_->async_start(std::chrono::milliseconds(1000)); } ~libkrbn_log_monitor(void) { krbn::logger::get_logger()->info(__func__); } private: std::unique_ptr<pqrs::spdlog::monitor> monitor_; }; <|endoftext|>
<commit_before>/** * \file Poisson.cpp * \brief * * Poisson disk points generator * * \version 1.0 * \date 06/05/2014 * \author Sergey Kosarevsky, 2014 * \author support@linderdaum.com http://www.linderdaum.com */ /* To compile: gcc Poisson.cpp -std=c++11 -lstdc++ */ // Fast Poisson Disk Sampling in Arbitrary Dimensions // http://people.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf // Implementation based on http://devmag.org.za/2009/05/03/poisson-disk-sampling/ #include <iostream> #include <vector> #include <random> #include <stdint.h> #include <fstream> #include <memory.h> ///////////////// User selectable parameters /////////////////////////////// const int NumPoints = 20000; // minimal number of points to generate const bool Circle = true; // 'true' to fill a circle, 'false' to fill a rectangle const int ImageSize = 1024; // generate RGB image [ImageSize x ImageSize] const int k = 30; // refer to bridson-siggraph07-poissondisk.pdf for details //////////////////////////////////////////////////////////////////////////// const char* Version = "1.0 (06/05/2014)"; const float MinDistance = sqrt( float(NumPoints) ) / float(NumPoints); std::random_device rd; std::mt19937 gen( rd() ); std::uniform_real_distribution<> dis( 0.0, 1.0 ); struct sPoint { sPoint(): Valid( false ) {} sPoint( float X, float Y ) : x( X ) , y( Y ) , Valid( true ) {} float x; float y; bool Valid; // bool IsInRectangle() const { return x >= 0 && y >= 0 && x <= 1 && y <= 1; } // bool IsInCircle() const { float fx = x - 0.5f; float fy = y - 0.5f; return ( fx*fx + fy*fy ) <= 0.25f; } }; struct sGridPoint { sGridPoint( int X, int Y ) : x( X ) , y( Y ) {} int x; int y; }; float RandomFloat() { return static_cast<float>( dis( gen ) ); } float GetDistance( const sPoint& P1, const sPoint& P2 ) { return sqrt( ( P1.x - P2.x ) * ( P1.x - P2.x ) + ( P1.y - P2.y ) * ( P1.y - P2.y ) ); } sGridPoint ImageToGrid( const sPoint& P, float CellSize ) { return sGridPoint( ( int )( P.x / CellSize ), ( int )( P.y / CellSize ) ); } struct sGrid { sGrid( int W, int H, float CellSize ) : m_W( W ) , m_H( H ) , m_CellSize( CellSize ) { m_Grid.resize( m_H ); for ( auto i = m_Grid.begin(); i != m_Grid.end(); i++ ) { i->resize( m_W ); } } void Insert( const sPoint& P ) { sGridPoint G = ImageToGrid( P, m_CellSize ); m_Grid[G.x][G.y] = P; } bool IsInNeighbourhood( sPoint Point, float MinDist, float CellSize ) { sGridPoint G = ImageToGrid( Point, CellSize ); // number of adjucent cells to look for neighbour points int D = 5; // scan the neighbourhood of the point in the grid for ( int i = G.x - D; i < G.x + D; i++ ) { for ( int j = G.y - D; j < G.y + D; j++ ) { if ( i >= 0 && i < m_W && j >= 0 && j < m_H ) { sPoint P = m_Grid[i][j]; if ( P.Valid && GetDistance( P, Point ) < MinDist ) { return true; } } } } return false; } private: int m_W; int m_H; float m_CellSize; std::vector< std::vector<sPoint> > m_Grid; }; sPoint PopRandom( std::vector<sPoint>& Points ) { std::uniform_int_distribution<> dis( 0, Points.size() - 1 ); int Idx = dis( gen ); sPoint P = Points[ Idx ]; Points.erase( Points.begin() + Idx ); return P; } sPoint GenerateRandomPointAround( const sPoint& P, float MinDist ) { // start with non-uniform distribution float R1 = RandomFloat(); float R2 = RandomFloat(); // radius should be between MinDist and 2 * MinDist float Radius = MinDist * ( R1 + 1.0f ); // random angle float Angle = 2 * 3.141592653589f * R2; // the new point is generated around the point (x, y) float X = P.x + Radius * cos( Angle ); float Y = P.y + Radius * sin( Angle ); return sPoint( X, Y ); } std::vector<sPoint> GeneratePoissonPoints( float MinDist, int NewPointsCount, size_t NumPoints ) { std::vector<sPoint> SamplePoints; std::vector<sPoint> ProcessList; // create the grid float CellSize = MinDist / sqrt( 2.0f ); int GridW = ( int )ceil( 1.0f / CellSize ); int GridH = ( int )ceil( 1.0f / CellSize ); sGrid Grid( GridW, GridH, CellSize ); sPoint FirstPoint = sPoint( RandomFloat(), RandomFloat() ); // update containers ProcessList.push_back( FirstPoint ); SamplePoints.push_back( FirstPoint ); Grid.Insert( FirstPoint ); // generate new points for each point in the queue while ( !ProcessList.empty() && SamplePoints.size() < NumPoints ) { // a progress indicator, kind of if ( SamplePoints.size() % 100 == 0 ) std::cout << "."; sPoint Point = PopRandom( ProcessList ); for ( int i = 0; i < NewPointsCount; i++ ) { sPoint NewPoint = GenerateRandomPointAround( Point, MinDist ); bool Fits = Circle ? NewPoint.IsInCircle() : NewPoint.IsInRectangle(); if ( Fits && !Grid.IsInNeighbourhood( NewPoint, MinDist, CellSize ) ) { ProcessList.push_back( NewPoint ); SamplePoints.push_back( NewPoint ); Grid.Insert( NewPoint ); continue; } } } std::cout << std::endl << std::endl; return SamplePoints; } #if defined( __GNUC__ ) # define GCC_PACK(n) __attribute__((packed,aligned(n))) #else # define GCC_PACK(n) __declspec(align(n)) #endif // __GNUC__ #pragma pack(push, 1) struct GCC_PACK( 1 ) sBMPHeader { // BITMAPFILEHEADER unsigned short bfType; uint32_t bfSize; unsigned short bfReserved1; unsigned short bfReserved2; uint32_t bfOffBits; // BITMAPINFOHEADER uint32_t biSize; uint32_t biWidth; uint32_t biHeight; unsigned short biPlanes; unsigned short biBitCount; uint32_t biCompression; uint32_t biSizeImage; uint32_t biXPelsPerMeter; uint32_t biYPelsPerMeter; uint32_t biClrUsed; uint32_t biClrImportant; }; #pragma pack(pop) void SaveBMP( const char* FileName, const void* RawBGRImage, int Width, int Height ) { sBMPHeader Header; int ImageSize = Width * Height * 3; Header.bfType = 0x4D * 256 + 0x42; Header.bfSize = ImageSize + sizeof( sBMPHeader ); Header.bfReserved1 = 0; Header.bfReserved2 = 0; Header.bfOffBits = 0x36; Header.biSize = 40; Header.biWidth = Width; Header.biHeight = Height; Header.biPlanes = 1; Header.biBitCount = 24; Header.biCompression = 0; Header.biSizeImage = ImageSize; Header.biXPelsPerMeter = 6000; Header.biYPelsPerMeter = 6000; Header.biClrUsed = 0; Header.biClrImportant = 0; std::ofstream File( FileName, std::ios::out | std::ios::binary ); File.write( (const char*)&Header, sizeof( Header ) ); File.write( (const char*)RawBGRImage, ImageSize ); std::cout << "Saved " << FileName << std::endl; } void PrintBanner() { std::cout << "Poisson disk points generator" << std::endl; std::cout << "Version " << Version << std::endl; std::cout << "Sergey Kosarevsky, 2014" << std::endl; std::cout << "support@linderdaum.com http://www.linderdaum.com" << std::endl; std::cout << std::endl; } int main() { PrintBanner(); std::vector<sPoint> Points = GeneratePoissonPoints( MinDistance, k, NumPoints ); // prepare BGR image size_t DataSize = 3*ImageSize*ImageSize; unsigned char* Img = new unsigned char[ DataSize ]; memset( Img, 0, DataSize ); for ( auto i = Points.begin(); i != Points.end(); i++ ) { int x = int( i->x * ImageSize ); int y = int( i->y * ImageSize ); int Base = 3 * (x + y * ImageSize); Img[ Base+0 ] = Img[ Base+1 ] = Img[ Base+2 ] = 255; } SaveBMP( "Poisson.bmp", Img, ImageSize, ImageSize ); delete[] Img; return 0; } <commit_msg>Density map loading (uncompressed bitmap)<commit_after>/** * \file Poisson.cpp * \brief * * Poisson Disk Points Generator * * \version 1.1.0 * \date 07/05/2014 * \author Sergey Kosarevsky, 2014 * \author support@linderdaum.com http://www.linderdaum.com */ /* To compile: gcc Poisson.cpp -std=c++11 -lstdc++ */ // Fast Poisson Disk Sampling in Arbitrary Dimensions // http://people.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf // Implementation based on http://devmag.org.za/2009/05/03/poisson-disk-sampling/ #include <iostream> #include <vector> #include <random> #include <stdint.h> #include <fstream> #include <memory.h> ///////////////// User selectable parameters /////////////////////////////// const int NumPoints = 20000; // minimal number of points to generate const bool Circle = true; // 'true' to fill a circle, 'false' to fill a rectangle const int ImageSize = 1024; // generate RGB image [ImageSize x ImageSize] const int k = 30; // refer to bridson-siggraph07-poissondisk.pdf for details //////////////////////////////////////////////////////////////////////////// const char* Version = "1.1.0 (07/05/2014)"; const float MinDistance = sqrt( float(NumPoints) ) / float(NumPoints); std::random_device rd; std::mt19937 gen( rd() ); std::uniform_real_distribution<> dis( 0.0, 1.0 ); float* g_DensityMap = NULL; struct sPoint { sPoint(): Valid( false ) {} sPoint( float X, float Y ) : x( X ) , y( Y ) , Valid( true ) {} float x; float y; bool Valid; // bool IsInRectangle() const { return x >= 0 && y >= 0 && x <= 1 && y <= 1; } // bool IsInCircle() const { float fx = x - 0.5f; float fy = y - 0.5f; return ( fx*fx + fy*fy ) <= 0.25f; } }; struct sGridPoint { sGridPoint( int X, int Y ) : x( X ) , y( Y ) {} int x; int y; }; float RandomFloat() { return static_cast<float>( dis( gen ) ); } float GetDistance( const sPoint& P1, const sPoint& P2 ) { return sqrt( ( P1.x - P2.x ) * ( P1.x - P2.x ) + ( P1.y - P2.y ) * ( P1.y - P2.y ) ); } sGridPoint ImageToGrid( const sPoint& P, float CellSize ) { return sGridPoint( ( int )( P.x / CellSize ), ( int )( P.y / CellSize ) ); } struct sGrid { sGrid( int W, int H, float CellSize ) : m_W( W ) , m_H( H ) , m_CellSize( CellSize ) { m_Grid.resize( m_H ); for ( auto i = m_Grid.begin(); i != m_Grid.end(); i++ ) { i->resize( m_W ); } } void Insert( const sPoint& P ) { sGridPoint G = ImageToGrid( P, m_CellSize ); m_Grid[G.x][G.y] = P; } bool IsInNeighbourhood( sPoint Point, float MinDist, float CellSize ) { sGridPoint G = ImageToGrid( Point, CellSize ); // number of adjucent cells to look for neighbour points int D = 5; // scan the neighbourhood of the point in the grid for ( int i = G.x - D; i < G.x + D; i++ ) { for ( int j = G.y - D; j < G.y + D; j++ ) { if ( i >= 0 && i < m_W && j >= 0 && j < m_H ) { sPoint P = m_Grid[i][j]; if ( P.Valid && GetDistance( P, Point ) < MinDist ) { return true; } } } } return false; } private: int m_W; int m_H; float m_CellSize; std::vector< std::vector<sPoint> > m_Grid; }; sPoint PopRandom( std::vector<sPoint>& Points ) { std::uniform_int_distribution<> dis( 0, Points.size() - 1 ); int Idx = dis( gen ); sPoint P = Points[ Idx ]; Points.erase( Points.begin() + Idx ); return P; } sPoint GenerateRandomPointAround( const sPoint& P, float MinDist ) { // start with non-uniform distribution float R1 = RandomFloat(); float R2 = RandomFloat(); // radius should be between MinDist and 2 * MinDist float Radius = MinDist * ( R1 + 1.0f ); // random angle float Angle = 2 * 3.141592653589f * R2; // the new point is generated around the point (x, y) float X = P.x + Radius * cos( Angle ); float Y = P.y + Radius * sin( Angle ); return sPoint( X, Y ); } std::vector<sPoint> GeneratePoissonPoints( float MinDist, int NewPointsCount, size_t NumPoints ) { std::vector<sPoint> SamplePoints; std::vector<sPoint> ProcessList; // create the grid float CellSize = MinDist / sqrt( 2.0f ); int GridW = ( int )ceil( 1.0f / CellSize ); int GridH = ( int )ceil( 1.0f / CellSize ); sGrid Grid( GridW, GridH, CellSize ); sPoint FirstPoint = sPoint( RandomFloat(), RandomFloat() ); // update containers ProcessList.push_back( FirstPoint ); SamplePoints.push_back( FirstPoint ); Grid.Insert( FirstPoint ); // generate new points for each point in the queue while ( !ProcessList.empty() && SamplePoints.size() < NumPoints ) { // a progress indicator, kind of if ( SamplePoints.size() % 100 == 0 ) std::cout << "."; sPoint Point = PopRandom( ProcessList ); for ( int i = 0; i < NewPointsCount; i++ ) { sPoint NewPoint = GenerateRandomPointAround( Point, MinDist ); bool Fits = Circle ? NewPoint.IsInCircle() : NewPoint.IsInRectangle(); if ( Fits && !Grid.IsInNeighbourhood( NewPoint, MinDist, CellSize ) ) { ProcessList.push_back( NewPoint ); SamplePoints.push_back( NewPoint ); Grid.Insert( NewPoint ); continue; } } } std::cout << std::endl << std::endl; return SamplePoints; } #if defined( __GNUC__ ) # define GCC_PACK(n) __attribute__((packed,aligned(n))) #else # define GCC_PACK(n) __declspec(align(n)) #endif // __GNUC__ #pragma pack(push, 1) struct GCC_PACK( 1 ) sBMPHeader { // BITMAPFILEHEADER unsigned short bfType; uint32_t bfSize; unsigned short bfReserved1; unsigned short bfReserved2; uint32_t bfOffBits; // BITMAPINFOHEADER uint32_t biSize; uint32_t biWidth; uint32_t biHeight; unsigned short biPlanes; unsigned short biBitCount; uint32_t biCompression; uint32_t biSizeImage; uint32_t biXPelsPerMeter; uint32_t biYPelsPerMeter; uint32_t biClrUsed; uint32_t biClrImportant; }; #pragma pack(pop) void SaveBMP( const char* FileName, const void* RawBGRImage, int Width, int Height ) { sBMPHeader Header; int ImageSize = Width * Height * 3; Header.bfType = 0x4D * 256 + 0x42; Header.bfSize = ImageSize + sizeof( sBMPHeader ); Header.bfReserved1 = 0; Header.bfReserved2 = 0; Header.bfOffBits = 0x36; Header.biSize = 40; Header.biWidth = Width; Header.biHeight = Height; Header.biPlanes = 1; Header.biBitCount = 24; Header.biCompression = 0; Header.biSizeImage = ImageSize; Header.biXPelsPerMeter = 6000; Header.biYPelsPerMeter = 6000; Header.biClrUsed = 0; Header.biClrImportant = 0; std::ofstream File( FileName, std::ios::out | std::ios::binary ); File.write( (const char*)&Header, sizeof( Header ) ); File.write( (const char*)RawBGRImage, ImageSize ); std::cout << "Saved " << FileName << std::endl; } unsigned char* LoadBMP( const char* FileName, int* OutWidth, int* OutHeight ) { sBMPHeader Header; std::ifstream File( FileName, std::ifstream::binary ); File.read( (char*)&Header, sizeof( Header ) ); *OutWidth = Header.biWidth; *OutHeight = Header.biHeight; size_t DataSize = 3 * Header.biWidth * Header.biHeight; unsigned char* Img = new unsigned char[ DataSize ]; File.read( (char*)Img, DataSize ); return Img; } void LoadDensityMap( const char* FileName ) { std::cout << "Loading density map " << FileName << std::endl; int W, H; unsigned char* Data = LoadBMP( FileName, &W, &H ); std::cout << "Loaded ( " << W << " x " << H << " ) " << std::endl; if ( W != ImageSize || H != ImageSize ) { std::cout << "ERROR: density map should be " << ImageSize << " x " << ImageSize << std::endl; exit( 255 ); } g_DensityMap = new float[ W * H ]; for ( int y = 0; y != H; y++ ) { for ( int x = 0; x != W; x++ ) { g_DensityMap[ x + y * W ] = float( Data[ 3 * (x + y * W) ] ) / 255.0f; } } delete[]( Data ); } void PrintBanner() { std::cout << "Poisson disk points generator" << std::endl; std::cout << "Version " << Version << std::endl; std::cout << "Sergey Kosarevsky, 2014" << std::endl; std::cout << "support@linderdaum.com http://www.linderdaum.com" << std::endl; std::cout << std::endl; std::cout << "Usage: Poisson [density-map-rgb24.bmp]" << std::endl; std::cout << std::endl; } int main( int argc, char** argv ) { PrintBanner(); if ( argc > 1 ) { LoadDensityMap( argv[1] ); } std::vector<sPoint> Points = GeneratePoissonPoints( MinDistance, k, NumPoints ); // prepare BGR image size_t DataSize = 3 * ImageSize * ImageSize; unsigned char* Img = new unsigned char[ DataSize ]; memset( Img, 0, DataSize ); for ( auto i = Points.begin(); i != Points.end(); i++ ) { int x = int( i->x * ImageSize ); int y = int( i->y * ImageSize ); if ( g_DensityMap ) { // dice float R = RandomFloat(); float P = g_DensityMap[ x + y * ImageSize ]; if ( R > P ) continue; } int Base = 3 * (x + y * ImageSize); Img[ Base+0 ] = Img[ Base+1 ] = Img[ Base+2 ] = 255; } SaveBMP( "Poisson.bmp", Img, ImageSize, ImageSize ); delete[]( Img ); return 0; } <|endoftext|>
<commit_before>// http://algospot.com/judge/problem/read/CLOCKSYNC #include <iostream> #include <cstdio> using namespace std; int sw [] = { // switch 7, // {0, 1, 2}, 2696, // {3, 7, 9, 11}, 50192, // {4, 10, 14, 15}, 241, // {0, 4, 5, 6, 7}, 5568, // {6, 7, 8, 10, 12}, 49157, // {0, 2, 14, 15}, 49160, // {3, 14, 15}, 49328, // {4, 5, 7, 14, 15}, 62, // {1, 2, 3, 4, 5}, 8760 // {3, 4, 5, 9, 13} }; unsigned int state; int n; void getInput() { int in; state = 0; for (int i = 0; i < 16; i++) { cin >> in; in = (in / 3) % 4; state |= (in & 0x3) << (i * 2); } } unsigned int move(int index, unsigned int st) { int r = sw[index]; while (r) { int i = __builtin_ctz(r) * 2; r &= r - 1; int current = st & (0x3 << i); current += st &= ~(0x3 << i); st |= ; } } void solve() { for (int i = 0; i < 10; i++) { } } int main() { int num; cin >> num; for (int i = 0; i < num; i++) {getInput(); solve();} return 0; } <commit_msg>not completed<commit_after>// http://algospot.com/judge/problem/read/CLOCKSYNC #include <iostream> using namespace std; int sw [] = { // switch 7, // {0, 1, 2}, 2696, // {3, 7, 9, 11}, 50192, // {4, 10, 14, 15}, 241, // {0, 4, 5, 6, 7}, 5568, // {6, 7, 8, 10, 12}, 49157, // {0, 2, 14, 15}, 49160, // {3, 14, 15}, 49328, // {4, 5, 7, 14, 15}, 62, // {1, 2, 3, 4, 5}, 8760 // {3, 4, 5, 9, 13} }; unsigned int state; int n; int count; void getInput() { int in; state = 0; for (int i = 0; i < 16; i++) { cin >> in; in = (in / 3) % 4; state |= (in & 0x3) << (i * 2); } } unsigned int move(int index, unsigned int st) { int r = sw[index]; while (r) { int i = __builtin_ctz(r) * 2; r &= r - 1; int current = st + (0x1 << i); st &= ~(0x3 << i); st |= current & (0x3 << i); } return st; } void test(int c, int index, int st) { if (c >= count) return; if (index == 10) return; if (st == 0) { count = c; return; } for (int i = 0; i < 4; i++) { test(c + i, index + 1, st); st = move(index, st); } } void solve() { count = 500; unsigned int st = state; for (int i = 0; i < 4; i++) { test(i, 0, st); st = move(0, st); } if (count == 500) count = -1; cout << count << endl; } int main() { int num; cin >> num; for (int i = 0; i < num; i++) {getInput(); solve();} return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the Free * * Software Foundation; either version 2 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * * more details. * * * * You should have received a copy of the GNU General Public License along * * with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "stdafx.h" #include <sofa/helper/Quater.h> // Including component #include <SofaBoundaryCondition/AffineMovementConstraint.h> #include "../deformationMapping/LinearMapping.h" #include <SofaTest/Mapping_test.h> namespace sofa { using namespace defaulttype; using namespace component; using namespace component::mapping; /// Linear Deformation mappings test /** * Test the deformation mappings by applying a rigid transformation (translation and rotation) * to all rigid nodes and checks if the resulting deformation gradient is equal to rotation. * This screenshot explains how this test works: * \image html RigidDeformationMapping.png */ template <typename _Mapping> struct RigidLinearDeformationMappings_test : public Mapping_test<_Mapping> { typedef Mapping_test<_Mapping> Inherited; typedef typename Inherited::In In; typedef typename In::CPos CPos; typedef typename In::Coord Coord; typedef typename Inherited::Out Out; typedef typename Inherited::Real Real; typedef typename Inherited::OutVecCoord OutVecCoord; typedef typename Inherited::InVecCoord InVecCoord; typedef typename Out::Frame OutFrame; typedef component::container::MechanicalObject<In> InDOFs; typedef component::container::MechanicalObject<Out> OutDOFs; typedef defaulttype::Quat Quat; typedef defaulttype::Vector3 Vec3; /// Tested Rotation: random rotation matrix defaulttype::Mat<3,3,Real> testedRotation; Quat testedQuaternion; /// Tested Translation: random translation Vec3 testedTranslation; // Constructor: call the constructor of the base class which loads the scene to test RigidLinearDeformationMappings_test() : Mapping_test<_Mapping>(std::string(FLEXIBLE_TEST_SCENES_DIR) + "/" + "RigidLineDeformationMapping.scn") { // rotation and translation this->SetRandomTestedRotationAndTranslation(); typedef projectiveconstraintset::AffineMovementConstraint<In> AffineMovementConstraint; typename AffineMovementConstraint::SPtr affineConstraint = this->root->template get<AffineMovementConstraint>(this->root->SearchDown); affineConstraint->m_quaternion.setValue(testedQuaternion); affineConstraint->m_translation.setValue(testedTranslation); testedQuaternion.toMatrix(testedRotation); static_cast<_Mapping*>(this->mapping)->d_geometricStiffness.setValue( 1 ); } void SetRandomTestedRotationAndTranslation() { // Random Rotation SReal x,y,z,w=0; // Random axis x = SReal(helper::drand(1)); y = SReal(helper::drand(1)); z = SReal(helper::drand(1)); // If the rotation axis is null Vec3 rotationAxis(x,y,z); rotationAxis.normalize( Vec3(0,0,1), 1e-7 ); // with failsafe // Random angle between 0 and M_PI while( !w ) w = helper::drand()* M_PI; // Quat = (rotationAxis*sin(angle/2) , cos(angle/2)) angle = 2*w testedQuaternion = Quat(sin(w)*rotationAxis[0],rotationAxis[1]*sin(w),rotationAxis[2]*sin(w),cos(w)); // to be sure if( !testedQuaternion.normalize() ) { msg_warning("RigidLinearDeformationMappings_test")<<"testedQuaternion is too small - random values: "<<x<<" "<<y<<" "<<z<<" "<<w<<" testedQuaternion="<<testedQuaternion; testedQuaternion.set( 0, 0, 0, 1 ); } // Translation for(size_t i=0;i<testedTranslation.size();++i) { testedTranslation[i]=helper::drand(2); } msg_info("RigidLinearDeformationMappings_test")<<"random values: "<<x<<" "<<y<<" "<<z<<" "<<w<<" testedQuaternion="<<testedQuaternion<<" - testedTranslation="<<testedTranslation; } using Inherited::runTest; /// After simulation compare the positions of deformation gradients to the theoretical positions. bool runTest(double convergenceAccuracy) { // Init simulation sofa::simulation::getSimulation()->init(this->root.get()); // Get dofs positions typename InDOFs::ReadVecCoord x = this->inDofs->readPositions(); // xin InVecCoord xin(x.size()); copyFromData(xin,x); // xout typename OutDOFs::ReadVecCoord xelasticityDofs = this->outDofs->readPositions(); OutVecCoord xout(xelasticityDofs.size()); copyFromData(xout,xelasticityDofs); // Initialize parameters to test convergence size_t numNodes = xin.size(); InVecCoord xPrev(numNodes); InVecCoord dx(numNodes); bool hasConverged = true; for (size_t i=0; i<numNodes; i++) { xPrev[i] = CPos(0,0,0); } // Animate do { hasConverged = true; sofa::simulation::getSimulation()->animate(this->root.get(),0.05); typename InDOFs::ReadVecCoord xCurrent = this->inDofs->readPositions(); // Compute dx for (size_t i=0; i<xCurrent.size(); i++) { // Translation dx[i].getCenter() = xCurrent[i].getCenter()-xPrev[i].getCenter(); //Rotation dx[i].getOrientation() = xCurrent[i].getOrientation().inverse()*xPrev[i].getOrientation(); // Test convergence if(dx[i].norm()>convergenceAccuracy) hasConverged = false; } // xprev = xCurrent for (size_t i=0; i<numNodes; i++) { xPrev[i]=xCurrent[i]; } } while(!hasConverged); // not converged // Parent new : Get simulated positions typename InDOFs::WriteVecCoord xinNew = this->inDofs->writePositions(); // New position of parents InVecCoord parentNew(xinNew.size()); for(size_t i=0; i<xinNew.size();++i) { parentNew[i] = xinNew[i]; } // Expected children positions: rotation from affine constraint typename OutDOFs::WriteVecCoord xoutNew = this->outDofs->writePositions(); OutVecCoord expectedChildCoords(xoutNew.size()); for(size_t i=0;i<xoutNew.size();++i) { OutFrame &f = expectedChildCoords[i].getF(); f = testedRotation; } // run the mapping test return Inherited::runTest(xin,xout,parentNew,expectedChildCoords); } }; // Define the list of DataTypes to instantiate using testing::Types; typedef Types< LinearMapping<Rigid3Types, F331Types>, LinearMapping<Rigid3Types, F332Types> > DataTypes; // the types to instantiate. // Test suite for all the instantiations TYPED_TEST_CASE(RigidLinearDeformationMappings_test, DataTypes); // test case: polarcorotationalStrainMapping TYPED_TEST( RigidLinearDeformationMappings_test , RigidStrainDeformationPatchTest) { ASSERT_TRUE( this->runTest(1e-15)); } } // namespace sofa <commit_msg>[Flexible] trying to fix RigidDeformationMapping_test<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the Free * * Software Foundation; either version 2 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * * more details. * * * * You should have received a copy of the GNU General Public License along * * with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "stdafx.h" #include <sofa/helper/Quater.h> // Including component #include <SofaBoundaryCondition/AffineMovementConstraint.h> #include "../deformationMapping/LinearMapping.h" #include <SofaTest/Mapping_test.h> namespace sofa { using namespace defaulttype; using namespace component; using namespace component::mapping; /// Linear Deformation mappings test /** * Test the deformation mappings by applying a rigid transformation (translation and rotation) * to all rigid nodes and checks if the resulting deformation gradient is equal to rotation. * This screenshot explains how this test works: * \image html RigidDeformationMapping.png */ template <typename _Mapping> struct RigidLinearDeformationMappings_test : public Mapping_test<_Mapping> { typedef Mapping_test<_Mapping> Inherited; typedef typename Inherited::In In; typedef typename In::CPos CPos; typedef typename In::Coord Coord; typedef typename Inherited::Out Out; typedef typename Inherited::Real Real; typedef typename Inherited::OutVecCoord OutVecCoord; typedef typename Inherited::InVecCoord InVecCoord; typedef typename Out::Frame OutFrame; typedef component::container::MechanicalObject<In> InDOFs; typedef component::container::MechanicalObject<Out> OutDOFs; typedef defaulttype::Quat Quat; typedef defaulttype::Vector3 Vec3; /// Tested Rotation: random rotation matrix defaulttype::Mat<3,3,Real> testedRotation; // Constructor: call the constructor of the base class which loads the scene to test RigidLinearDeformationMappings_test() : Mapping_test<_Mapping>(std::string(FLEXIBLE_TEST_SCENES_DIR) + "/" + "RigidLineDeformationMapping.scn") { // random rotation and translation Coord randomRigid = Coord::rand(180); msg_info("RigidLinearDeformationMappings_test")<<"randomRigid="<<randomRigid; // to debug typedef projectiveconstraintset::AffineMovementConstraint<In> AffineMovementConstraint; typename AffineMovementConstraint::SPtr affineConstraint = this->root->template get<AffineMovementConstraint>(this->root->SearchDown); affineConstraint->m_quaternion.setValue(randomRigid.getOrientation()); affineConstraint->m_translation.setValue(randomRigid.getCenter()); randomRigid.getOrientation().toMatrix(testedRotation); static_cast<_Mapping*>(this->mapping)->d_geometricStiffness.setValue( 1 ); } using Inherited::runTest; /// After simulation compare the positions of deformation gradients to the theoretical positions. bool runTest(double convergenceAccuracy) { // Init simulation sofa::simulation::getSimulation()->init(this->root.get()); // Get dofs positions typename InDOFs::ReadVecCoord x = this->inDofs->readPositions(); // xin InVecCoord xin(x.size()); copyFromData(xin,x); // xout typename OutDOFs::ReadVecCoord xelasticityDofs = this->outDofs->readPositions(); OutVecCoord xout(xelasticityDofs.size()); copyFromData(xout,xelasticityDofs); // Initialize parameters to test convergence size_t numNodes = xin.size(); InVecCoord xPrev(numNodes); InVecCoord dx(numNodes); bool hasConverged = true; for (size_t i=0; i<numNodes; i++) { xPrev[i] = CPos(0,0,0); } // Animate do { hasConverged = true; sofa::simulation::getSimulation()->animate(this->root.get(),0.05); typename InDOFs::ReadVecCoord xCurrent = this->inDofs->readPositions(); // Compute dx for (size_t i=0; i<xCurrent.size(); i++) { // Translation dx[i].getCenter() = xCurrent[i].getCenter()-xPrev[i].getCenter(); //Rotation dx[i].getOrientation() = xCurrent[i].getOrientation().inverse()*xPrev[i].getOrientation(); // Test convergence if(dx[i].norm()>convergenceAccuracy) hasConverged = false; } // xprev = xCurrent for (size_t i=0; i<numNodes; i++) { xPrev[i]=xCurrent[i]; } } while(!hasConverged); // not converged // Parent new : Get simulated positions typename InDOFs::WriteVecCoord xinNew = this->inDofs->writePositions(); // New position of parents InVecCoord parentNew(xinNew.size()); for(size_t i=0; i<xinNew.size();++i) { parentNew[i] = xinNew[i]; } // Expected children positions: rotation from affine constraint typename OutDOFs::WriteVecCoord xoutNew = this->outDofs->writePositions(); OutVecCoord expectedChildCoords(xoutNew.size()); for(size_t i=0;i<xoutNew.size();++i) { OutFrame &f = expectedChildCoords[i].getF(); f = testedRotation; } // run the mapping test return Inherited::runTest(xin,xout,parentNew,expectedChildCoords); } }; // Define the list of DataTypes to instantiate using testing::Types; typedef Types< LinearMapping<Rigid3Types, F331Types>, LinearMapping<Rigid3Types, F332Types> > DataTypes; // the types to instantiate. // Test suite for all the instantiations TYPED_TEST_CASE(RigidLinearDeformationMappings_test, DataTypes); // test case: polarcorotationalStrainMapping TYPED_TEST( RigidLinearDeformationMappings_test , RigidStrainDeformationPatchTest) { ASSERT_TRUE( this->runTest(1e-15)); } } // namespace sofa <|endoftext|>
<commit_before> #include <Flexible/config.h> #include "ComponentSpecializationsDefines.h" #include <sofa/core/ObjectFactory.h> #include <SofaBaseMechanics/IdentityMapping.inl> #include <SofaMiscMapping/SubsetMultiMapping.inl> namespace sofa { namespace component { namespace mapping { SOFA_DECL_CLASS(EVALUATOR(TYPEABSTRACTNAME,IdentityMapping)) // Register in the Factory int EVALUATOR(TYPEABSTRACTNAME,IdentityMappingClass) = core::RegisterObject("Special case of mapping where the child points are the same as the parent points") #ifndef SOFA_FLOAT .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3dTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3dTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3dTypes > >() #endif #ifndef SOFA_DOUBLE .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3fTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3fTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3fTypes > >() #endif #ifndef SOFA_FLOAT #ifndef SOFA_DOUBLE .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3dTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3dTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3fTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3fTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3dTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3fTypes > >() #endif #endif ; #ifndef SOFA_FLOAT template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3dTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3dTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3dTypes >; #endif #ifndef SOFA_DOUBLE template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3fTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3fTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3fTypes >; #endif #ifndef SOFA_FLOAT #ifndef SOFA_DOUBLE template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3dTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3dTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3fTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3fTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3dTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3fTypes >; #endif #endif /////////////////////////////// using namespace sofa::defaulttype; SOFA_DECL_CLASS(EVALUATOR(TYPEABSTRACTNAME,SubsetMultiMapping)) int EVALUATOR(TYPEABSTRACTNAME,SubsetMultiMappingClass) = core::RegisterObject("Compute a subset of the input MechanicalObjects according to a dof index list") #ifndef SOFA_FLOAT .add< SubsetMultiMapping< TYPEABSTRACTNAME3dTypes, TYPEABSTRACTNAME3dTypes > >() #endif #ifndef SOFA_DOUBLE .add< SubsetMultiMapping< TYPEABSTRACTNAME3fTypes, TYPEABSTRACTNAME3fTypes > >() #endif ; #ifndef SOFA_FLOAT template class SOFA_Flexible_API SubsetMultiMapping< TYPEABSTRACTNAME3dTypes, TYPEABSTRACTNAME3dTypes >; #endif #ifndef SOFA_DOUBLE template class SOFA_Flexible_API SubsetMultiMapping< TYPEABSTRACTNAME3fTypes, TYPEABSTRACTNAME3fTypes >; #endif } // namespace mapping } // namespace component } // namespace sofa #include "ComponentSpecializationsUndef.h" <commit_msg>[Flexible] fixed debug build<commit_after> #include <Flexible/config.h> #include "ComponentSpecializationsDefines.h" #include <sofa/core/ObjectFactory.h> #include <sofa/core/Mapping.inl> #include <SofaBaseMechanics/IdentityMapping.inl> #include <SofaMiscMapping/SubsetMultiMapping.inl> namespace sofa { namespace component { namespace mapping { SOFA_DECL_CLASS(EVALUATOR(TYPEABSTRACTNAME,IdentityMapping)) // Register in the Factory int EVALUATOR(TYPEABSTRACTNAME,IdentityMappingClass) = core::RegisterObject("Special case of mapping where the child points are the same as the parent points") #ifndef SOFA_FLOAT .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3dTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3dTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3dTypes > >() #endif #ifndef SOFA_DOUBLE .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3fTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3fTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3fTypes > >() #endif #ifndef SOFA_FLOAT #ifndef SOFA_DOUBLE .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3dTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3dTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3fTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3fTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3dTypes > >() .add< IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3fTypes > >() #endif #endif ; #ifndef SOFA_FLOAT template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3dTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3dTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3dTypes >; #endif #ifndef SOFA_DOUBLE template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3fTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3fTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3fTypes >; #endif #ifndef SOFA_FLOAT #ifndef SOFA_DOUBLE template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::Vec3dTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::ExtVec3dTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::Vec3fTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::ExtVec3fTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3fTypes, defaulttype::TYPEABSTRACTNAME3dTypes >; template class SOFA_Flexible_API IdentityMapping< defaulttype::TYPEABSTRACTNAME3dTypes, defaulttype::TYPEABSTRACTNAME3fTypes >; #endif #endif /////////////////////////////// using namespace sofa::defaulttype; SOFA_DECL_CLASS(EVALUATOR(TYPEABSTRACTNAME,SubsetMultiMapping)) int EVALUATOR(TYPEABSTRACTNAME,SubsetMultiMappingClass) = core::RegisterObject("Compute a subset of the input MechanicalObjects according to a dof index list") #ifndef SOFA_FLOAT .add< SubsetMultiMapping< TYPEABSTRACTNAME3dTypes, TYPEABSTRACTNAME3dTypes > >() #endif #ifndef SOFA_DOUBLE .add< SubsetMultiMapping< TYPEABSTRACTNAME3fTypes, TYPEABSTRACTNAME3fTypes > >() #endif ; #ifndef SOFA_FLOAT template class SOFA_Flexible_API SubsetMultiMapping< TYPEABSTRACTNAME3dTypes, TYPEABSTRACTNAME3dTypes >; #endif #ifndef SOFA_DOUBLE template class SOFA_Flexible_API SubsetMultiMapping< TYPEABSTRACTNAME3fTypes, TYPEABSTRACTNAME3fTypes >; #endif } // namespace mapping } // namespace component } // namespace sofa #include "ComponentSpecializationsUndef.h" <|endoftext|>
<commit_before>/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "rtksubselect_ggo.h" #include "rtkGgoFunctions.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkProjectionsReader.h" #include <itkImageFileWriter.h> #include <itkRegularExpressionSeriesFileNames.h> int main(int argc, char * argv[]) { GGO(rtksubselect, args_info); // Generate file names itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New(); names->SetDirectory(args_info.path_arg); names->SetNumericSort(args_info.nsort_flag); names->SetRegularExpression(args_info.regexp_arg); names->SetSubMatch(args_info.submatch_arg); if(args_info.verbose_flag) std::cout << "Regular expression matches " << names->GetFileNames().size() << " file(s)..." << std::endl; // Geometry if(args_info.verbose_flag) std::cout << "Reading geometry information from " << args_info.geometry_arg << "..." << std::endl; rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader; geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geometryReader->SetFilename(args_info.geometry_arg); TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() ) // Output RTK geometry object typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer outputGeometry = GeometryType::New(); // Output filenames std::vector< std::string > outputProjectionsNames; // Subsection int n = geometryReader->GetOutputObject()->GetGantryAngles().size(); if(args_info.list_given) { for(unsigned int i=0; i<args_info.list_given; i++) { int noProj = args_info.list_arg[i]; outputGeometry->AddProjection(geometryReader->GetOutputObject()->GetSourceToIsocenterDistances()[noProj], geometryReader->GetOutputObject()->GetSourceToDetectorDistances()[noProj], geometryReader->GetOutputObject()->GetGantryAngles()[noProj], geometryReader->GetOutputObject()->GetProjectionOffsetsX()[noProj], geometryReader->GetOutputObject()->GetProjectionOffsetsY()[noProj], geometryReader->GetOutputObject()->GetOutOfPlaneAngles()[noProj], geometryReader->GetOutputObject()->GetInPlaneAngles()[noProj], geometryReader->GetOutputObject()->GetSourceOffsetsX()[noProj], geometryReader->GetOutputObject()->GetSourceOffsetsY()[noProj]); outputProjectionsNames.push_back(names->GetFileNames()[noProj]); } } else for(int noProj=args_info.first_arg; noProj<n; noProj+=args_info.step_arg) { outputGeometry->AddProjection(geometryReader->GetOutputObject()->GetSourceToIsocenterDistances()[noProj], geometryReader->GetOutputObject()->GetSourceToDetectorDistances()[noProj], geometryReader->GetOutputObject()->GetGantryAngles()[noProj], geometryReader->GetOutputObject()->GetProjectionOffsetsX()[noProj], geometryReader->GetOutputObject()->GetProjectionOffsetsY()[noProj], geometryReader->GetOutputObject()->GetOutOfPlaneAngles()[noProj], geometryReader->GetOutputObject()->GetInPlaneAngles()[noProj], geometryReader->GetOutputObject()->GetSourceOffsetsX()[noProj], geometryReader->GetOutputObject()->GetSourceOffsetsY()[noProj]); outputProjectionsNames.push_back(names->GetFileNames()[noProj]); } // Geometry writer if(args_info.verbose_flag) std::cout << "Writing geometry information in " << args_info.out_geometry_arg << "..." << std::endl; rtk::ThreeDCircularProjectionGeometryXMLFileWriter::Pointer xmlWriter = rtk::ThreeDCircularProjectionGeometryXMLFileWriter::New(); xmlWriter->SetFilename(args_info.out_geometry_arg); xmlWriter->SetObject( &(*outputGeometry) ); TRY_AND_EXIT_ON_ITK_EXCEPTION( xmlWriter->WriteFile() ) typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // Projections reader if(args_info.verbose_flag) std::cout << "Reading and writing projections in " << args_info.out_proj_arg << "..." << std::endl; typedef rtk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileNames( outputProjectionsNames ); // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.out_proj_arg ); writer->SetInput( reader->GetOutput() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->UpdateOutputInformation() ) writer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) ); TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ) return EXIT_SUCCESS; } <commit_msg>Modified rtksubselect : It can now take in input a single file containing several projections. It now writes its output projections in a single file too.<commit_after>/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "rtksubselect_ggo.h" #include "rtkGgoFunctions.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkProjectionsReader.h" #include "rtkConstantImageSource.h" #include <itkImageFileWriter.h> #include <itkRegularExpressionSeriesFileNames.h> #include <itkPasteImageFilter.h> int main(int argc, char * argv[]) { GGO(rtksubselect, args_info); typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // Projections reader typedef rtk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); rtk::SetProjectionsReaderFromGgo<ReaderType, args_info_rtksubselect>(reader, args_info); reader->Update(); // Geometry if(args_info.verbose_flag) std::cout << "Reading geometry information from " << args_info.geometry_arg << "..." << std::endl; rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader; geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geometryReader->SetFilename(args_info.geometry_arg); TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() ) // Compute the indices of the selected projections std::vector<int> indices; int n = geometryReader->GetOutputObject()->GetGantryAngles().size(); if(args_info.list_given) for(unsigned int i=0; i<args_info.list_given; i++) { indices.push_back(args_info.list_arg[i]); } else for(int noProj=args_info.first_arg; noProj<n; noProj+=args_info.step_arg) { indices.push_back(noProj); } // Output RTK geometry object typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer outputGeometry = GeometryType::New(); // Output projections object typedef rtk::ConstantImageSource< OutputImageType > SourceType; SourceType::Pointer source = SourceType::New(); source->SetInformationFromImage(reader->GetOutput()); OutputImageType::SizeType outputSize = reader->GetOutput()->GetLargestPossibleRegion().GetSize(); outputSize[Dimension - 1] = indices.size(); source->SetSize(outputSize); source->SetConstant(0); source->Update(); // Fill in the outputGeometry and the output projections typedef itk::PasteImageFilter<OutputImageType> PasteType; PasteType::Pointer paste = PasteType::New(); paste->SetSourceImage(reader->GetOutput()); paste->SetDestinationImage(source->GetOutput()); OutputImageType::RegionType sourceRegion; OutputImageType::IndexType destinationIndex; for (unsigned int i=0; i<indices.size(); i++) { // If it is not the first projection, we need to use the output of // the paste filter as input if(i) { OutputImageType::Pointer pimg = paste->GetOutput(); pimg->DisconnectPipeline(); paste->SetDestinationImage(pimg); } sourceRegion = reader->GetOutput()->GetLargestPossibleRegion().GetSize(); sourceRegion.SetIndex(Dimension - 1, indices[i]); sourceRegion.SetSize(Dimension - 1, 1); paste->SetSourceRegion(sourceRegion); destinationIndex.Fill(0); destinationIndex[Dimension -1] = i; paste->SetDestinationIndex(destinationIndex); paste->Update(); // Fill in the output geometry object outputGeometry->AddProjection(geometryReader->GetOutputObject()->GetSourceToIsocenterDistances()[indices[i]], geometryReader->GetOutputObject()->GetSourceToDetectorDistances()[indices[i]], geometryReader->GetOutputObject()->GetGantryAngles()[indices[i]], geometryReader->GetOutputObject()->GetProjectionOffsetsX()[indices[i]], geometryReader->GetOutputObject()->GetProjectionOffsetsY()[indices[i]], geometryReader->GetOutputObject()->GetOutOfPlaneAngles()[indices[i]], geometryReader->GetOutputObject()->GetInPlaneAngles()[indices[i]], geometryReader->GetOutputObject()->GetSourceOffsetsX()[indices[i]], geometryReader->GetOutputObject()->GetSourceOffsetsY()[indices[i]]); } // Geometry writer if(args_info.verbose_flag) std::cout << "Writing geometry information in " << args_info.out_geometry_arg << "..." << std::endl; rtk::ThreeDCircularProjectionGeometryXMLFileWriter::Pointer xmlWriter = rtk::ThreeDCircularProjectionGeometryXMLFileWriter::New(); xmlWriter->SetFilename(args_info.out_geometry_arg); xmlWriter->SetObject( &(*outputGeometry) ); TRY_AND_EXIT_ON_ITK_EXCEPTION( xmlWriter->WriteFile() ) // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.out_proj_arg ); writer->SetInput( paste->GetOutput() ); //TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->UpdateOutputInformation() ) // writer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) ); TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ) return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * File: main.cpp * Author: chenone2316 * * Created on June 1, 2015, 1:46 PM */ #include <broker/broker.hh> #include <broker/endpoint.hh> #include <broker/message_queue.hh> #include <osquery/sdk.h> #include <poll.h> #include <iostream> #include <unistd.h> #include <iostream> #include <sstream> #include <osquery/filesystem.h> #include <osquery/events.h> #include <osquery/filesystem.h> #include <osquery/logger.h> #include <osquery/registry.h> #include <osquery/sql.h> //#include <pthread.h> using namespace osquery; broker::endpoint PC("VM"); /* * */ class BrokerQueryPlugin: public ConfigPlugin { private: typedef std::map<std::string, std::string>::const_iterator pt; QueryData bQresult; public: //////////////////////////////////////////////////////////////////////////// //////////////////broker connection///////////////////////////////////////// Status brokerConnection() { std::cout<<"In the broker Connection\n"; auto status = Status(0,"OK"); broker::init(); PC.peer("192.168.1.187",9999); auto conn_status = PC.outgoing_connection_status().need_pop(); for(auto cs: conn_status) { if(cs.status == broker::outgoing_connection_status::tag::established) { std::cout<<"Connection Established"<<std::endl; break; } else { std::cout<<"Error: Connection Failed"<<std::endl; status = Status(-1,"Not Connected"); } } return status; } //////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// std::string brokerMessageExtractor(const broker::message &msg) { std::string broQuery = broker::to_string(broker::message(msg)); broQuery = broQuery.substr(1,broQuery.size()-2); return broQuery; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// Status brokerMessageQuery() { std::cout<<"In the Message Query Function\n"; broker::message_queue mq("Testing", PC); pollfd pfd{mq.fd(), POLLIN, 0}; int rv; std::string temp_query; std::string out; auto status = Status(0,"OK"); QueryData test; while(true) { rv = poll(&pfd,1,10000); if(!(rv== -1) && !(rv==0)) { for(auto& msg : mq.need_pop()) { temp_query = brokerMessageExtractor(msg); std::cout<<"Query = "<<temp_query<<std::endl; test = brokerQuery(temp_query); for (auto& r : test) { for(pt iter = r.begin(); iter != r.end(); iter++) { std::cout << iter->first << ": "; out += iter->first + ": "; std::cout << iter->second <<std::endl ; out += iter->second + "\n" ; } std::cout << out; usleep(500000); PC.send("Testing", broker::message{out}); usleep(500000); } } } } } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// QueryData brokerQuery(const std::string& queryString) { QueryData qd; osquery::queryExternal(queryString, qd); return qd; } ////////////////////////////////////////////////////////////////////////// //************************************************************************* Status genConfig(std::map<std::string,std::string>& config) { return Status(0,"OK"); } ////////////////////////////////////////////////////////////////////// /* Status broker_osquery_init() { std::cout<<"In the broker_init() function"<<std::endl; //BrokerQueryPlugin b; auto status = Status(0,"OK"); status = brokerConnection(); if(status.ok()) { brokerMessageQuery(); } else { std::cout<<"Could not Connect"; } return Status(0,"OK"); }*/ }; void *broker_osquery_init(void *threadid) { std::cout<<"In the broker_init() function"<<std::endl; BrokerQueryPlugin b; auto status = Status(0,"OK"); status = b.brokerConnection(); while(!status.ok()) { b.brokerConnection(); } b.brokerMessageQuery(); pthread_exit(NULL); } ////////////////////////////////////////////////// // Note 3: Use REGISTER_EXTERNAL to define your plugin REGISTER_EXTERNAL(BrokerQueryPlugin, "config", "brokerQuery") int main(int argc, char* argv[]) { pthread_t broker_thread; int rc; long t=0; std::cout<<"Starting the program"<<std::endl; BrokerQueryPlugin b; //b.broker_osquery_init(); rc = pthread_create(&broker_thread, NULL, broker_osquery_init, (void*)t); if(rc) { std::cout<< "Error in pthread_create(): " <<rc <<std::endl; exit(-1); } // Note 4: Start logging, threads, etc. osquery::Initializer runner(argc, argv, OSQUERY_EXTENSION); std::cout<<"Initialized OSquery"<<std::endl; // Note 5: Connect to osqueryi or osqueryd. auto status = startExtension("brokerQuery", "0.0.1"); if (!status.ok()) { LOG(ERROR) << status.getMessage(); } /*BrokerQueryPlugin b; b.genConfig();*/ std::cout<<"Shutting downn extension"<<std::endl; // Finally shutdown. runner.shutdown(); return 0; } <commit_msg>Update bro_osquery.cpp<commit_after>/* * File: main.cpp * Author: chenone2316 * * Created on June 1, 2015, 1:46 PM */ #include <broker/broker.hh> #include <broker/endpoint.hh> #include <broker/message_queue.hh> #include <osquery/sdk.h> #include <poll.h> #include <iostream> #include <unistd.h> #include <iostream> #include <sstream> #include <osquery/filesystem.h> #include <osquery/events.h> #include <osquery/filesystem.h> #include <osquery/logger.h> #include <osquery/registry.h> #include <osquery/sql.h> //#include <pthread.h> using namespace osquery; broker::endpoint PC("VM"); /* * */ class BrokerQueryPlugin: public ConfigPlugin { private: typedef std::map<std::string, std::string>::const_iterator pt; QueryData bQresult; public: //////////////////////////////////////////////////////////////////////////// //////////////////broker connection///////////////////////////////////////// Status brokerConnection() { std::cout<<"In the broker Connection\n"; auto status = Status(0,"OK"); broker::init(); PC.peer("192.168.1.187",9999); auto conn_status = PC.outgoing_connection_status().need_pop(); for(auto cs: conn_status) { if(cs.status == broker::outgoing_connection_status::tag::established) { std::cout<<"Connection Established"<<std::endl; break; } else { std::cout<<"Error: Connection Failed"<<std::endl; status = Status(-1,"Not Connected"); } } return status; } //////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// std::string brokerMessageExtractor(const broker::message &msg) { std::string broQuery = broker::to_string(broker::message(msg)); broQuery = broQuery.substr(1,broQuery.size()-2); if(broQuery.substr(0,6)!= "SELECT") { return ""; } else return broQuery; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// Status brokerMessageQuery() { std::cout<<"In the Message Query Function\n"; broker::message_queue mq("Testing", PC); pollfd pfd{mq.fd(), POLLIN, 0}; int rv; std::string temp_query; std::string out1; std::string out2; std::string out; auto status = Status(0,"OK"); QueryData test; while(true) { rv = poll(&pfd,1,10000); if(!(rv== -1) && !(rv==0)) { for(auto& msg : mq.need_pop()) { temp_query = brokerMessageExtractor(msg); if(!temp_query.empty()) { std::cout<<"Query = "<<temp_query<<std::endl; test = brokerQuery(temp_query); for (auto& r : test) { for(pt iter = r.begin(); iter != r.end(); iter++) { // std::cout << iter->first << ": "; out1 += iter->first + " | "; // std::cout << iter->second <<std::endl ; out2 += iter->second + " | " ; } out1 += "\n"; out2 +="\n"; out = out1 + out2 ; std::cout << out ; usleep(500000); PC.send("Testing", broker::message{out}); usleep(500000); out1=out2=out="\0"; break; } } } } } } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// QueryData brokerQuery(const std::string& queryString) { QueryData qd; osquery::queryExternal(queryString, qd); return qd; } ////////////////////////////////////////////////////////////////////////// //************************************************************************* Status genConfig(std::map<std::string,std::string>& config) { return Status(0,"OK"); } ////////////////////////////////////////////////////////////////////// /* Status broker_osquery_init() { std::cout<<"In the broker_init() function"<<std::endl; //BrokerQueryPlugin b; auto status = Status(0,"OK"); status = brokerConnection(); if(status.ok()) { brokerMessageQuery(); } else { std::cout<<"Could not Connect"; } return Status(0,"OK"); }*/ }; void *broker_osquery_init(void *threadid) { std::cout<<"In the broker_init() function"<<std::endl; BrokerQueryPlugin b; auto status = Status(0,"OK"); status = b.brokerConnection(); while(!status.ok()) { b.brokerConnection(); } b.brokerMessageQuery(); pthread_exit(NULL); } ////////////////////////////////////////////////// // Note 3: Use REGISTER_EXTERNAL to define your plugin REGISTER_EXTERNAL(BrokerQueryPlugin, "config", "brokerQuery") int main(int argc, char* argv[]) { pthread_t broker_thread; int rc; long t=0; std::cout<<"Starting the program"<<std::endl; BrokerQueryPlugin b; //b.broker_osquery_init(); rc = pthread_create(&broker_thread, NULL, broker_osquery_init, (void*)t); if(rc) { std::cout<< "Error in pthread_create(): " <<rc <<std::endl; exit(-1); } // Note 4: Start logging, threads, etc. osquery::Initializer runner(argc, argv, OSQUERY_EXTENSION); std::cout<<"Initialized OSquery"<<std::endl; // Note 5: Connect to osqueryi or osqueryd. auto status = startExtension("brokerQuery", "0.0.1"); if (!status.ok()) { LOG(ERROR) << status.getMessage(); } /*BrokerQueryPlugin b; b.genConfig();*/ std::cout<<"Shutting downn extension"<<std::endl; // Finally shutdown. runner.shutdown(); return 0; } <|endoftext|>
<commit_before>// Filename: main.cpp // Author: Christopher Goes // Course: CS 404 Machine Learning and Data Mining // Semester: Spring 2016 // Description: Assignment 3 main program logic #include <iostream> #include <iomanip> #include <cstdlib> #include <vector> #include <cmath> #include "matrix.h" #define DEBUG 0 #define DEBUGINPUT 0 #define DEBUG_RESULTS 0 using namespace std; double activate( double input ); // Activation Function double sigmoid( double input ); // Sigmoid function int main() { // Initialization int numInputs = 0; int numOutputs = 0; int rows = 0; int cols = 0; int testRows = 0; int testCols = 0; double temp = -99; double bias = -1; // -1 is what the book uses. double eta = 0.025; // 0.25 is what the book uses. open to tweaking. int attempts = 5; // if debugging, SET THIS TO A SMALL NUMBER! int num_hidden_layers = 1; // is this a thing int num_hidden_nodes = 0; double max = 1; double min = 1; // Training Data Input // cin >> numInputs; cin >> num_hidden_nodes; cin >> rows; cin >> cols; numOutputs = cols - numInputs; Matrix* tinput = new Matrix(rows, numInputs + 1); Matrix* toutput = new Matrix(rows, numOutputs); if(DEBUGINPUT) { cout << "Inputs: " << numInputs << "\nHidden Nodes: " << num_hidden_nodes << "\nRows: " << rows << "\nCols: " << cols << endl; } // Fill the matrix for(int r = 0; r < rows; r++) { for(int c = 0; c < numInputs; c++) { cin >> temp; if( temp > max ) max = temp; else if( temp < min ) min = temp; tinput->setValue( r, c, temp); } for(int c = 0; c < numOutputs; c++ ) { cin >> temp; if( temp > max ) max = temp; else if( temp < min ) min = temp; toutput->setValue( r, c, temp); } } // Append the bias for( int r = 0; r < rows; r++ ) { tinput->setValue(r, numInputs, bias); } numInputs++; if(DEBUGINPUT) { cout << "\nTraining Inputs..." << endl; tinput->printAll(); cout << "\nTraining Outputs..." << endl; toutput->printAll(); } // Test Data Input // cin >> testRows; cin >> testCols; Matrix * testInput = new Matrix(testRows, testCols + 1); // Fill the matrix for(int r = 0; r < testRows; r++) { for(int c = 0; c < testCols; c++) { cin >> temp; if( temp > max ) max = temp; else if( temp < min ) min = temp; testInput->setValue(r, c, temp); } } // Append the bias for( int r = 0; r < testRows; r++ ) { testInput->setValue(r, testCols, bias); } testCols++; if(DEBUGINPUT) { cout << "\nTest Inputs matrix" << endl; testInput->printAll(); } // // // * Training * // Matrix * hw = new Matrix(numInputs, numOutputs, 2); Matrix * ow = new Matrix(numInputs + 1, numOutputs, 2); // +1 for the extra bias between hidden and output layers Matrix * tempmat; double tResult = -66.6; //init values are paranoia for error catching double aResult = -55.0; double fResult = -42.0; temp = -99; if(DEBUG) { cout << "\nInitialized Hidden Weight matrix..." << endl; hw->printAll(); } // Normalize our input (THIS COULD BE IMPROVED) TODO tinput->normalize(min, max); Matrix * deltah; // error in hidden layer Matrix * deltao; // error in output layer Matrix * a; // hidden layer output Matrix * y; // output layer output Matrix * hVec; Matrix * inVec; Matrix * v; Matrix * t; Matrix * sumh; Matrix * sumo; // re-implementation for( int attempt = 0; attempt < attempts; attempt++ ) { for( int r = 0; r < rows; r++ ) { inVec = tinput->getRow(r); t = toutput->getRow(r); // hidden layer a = inVec->dot(hw); a->sigmoid(); hVec = new Matrix(a); hVec->data[0].push_back(bias); hVec->numCols++; // output layer y = hVec->dot(hw); y->sigmoid(); // output error t = t->sub(y); t = t->dot(y); y->scalarPreSub(1.0); deltao = t->dot(y); // hidden error deltah = hVec; hVec->scalarPreSub(1.0); deltah->dot(hVec); hVec->scalarPreSub(1.0); tempmat = deltao->dot(ow); tempmat = tempmat->transpose(); deltah = deltah->dot(tempmat); // update matricies tempmat = hVec->transpose(); tempmat = tempmat->dot(deltao); tempmat = tempmat->dot(eta); ow = ow->add(tempmat); deltah->data[0].pop_back(); deltah->numCols--; tempmat = inVec->transpose(); tempmat = inVec->dot(deltah); tempmat = tempmat->dot(eta); hw = hw->add(tempmat); } // rows } // attempts // // // Testing // tResult = -66.6; fResult = -42.0; double * tempResults = new double[numOutputs]; double * finalResults = new double[numOutputs]; cout << "BEGIN TESTING" << endl; for( int r = 0; r < rows; r++ ) { // Each row in testing set for (int i = 0; i < (numInputs - 1); i++) { cout << fixed << setprecision(2) << testInput->getValue(r, i) << " "; } for( int out = 0; out < numOutputs; out++ ) { // Each output tResult = 0.0; // clear tempResults before we add for( int i = 0; i < numInputs; i++ ) { // Each input //tResult += test->getValue(r, i) * w->getValue(i, out); } tResult = sigmoid(tResult); fResult = activate(tResult); tempResults[out] = tResult; finalResults[out] = fResult; } // per-output loop for( int i = 0; i < numOutputs; i++ ) { cout << fixed << setprecision(0) << finalResults[i] << " "; } cout << endl; // end the row's output } // row in set loop // Cleanup // delete tempResults; delete finalResults; delete hw; delete ow; delete tinput; delete toutput; delete testInput; return(0); } double activate( double input ) { if( input > 0.0 ) return 1.0; else return 0.0; } double sigmoid( double input ) { return (2 / (1 + exp(-25 * input)) - 1); } <commit_msg>added test output and memory management<commit_after>// Filename: main.cpp // Author: Christopher Goes // Course: CS 404 Machine Learning and Data Mining // Semester: Spring 2016 // Description: Assignment 3 main program logic #include <iostream> #include <iomanip> #include <cstdlib> #include <vector> #include <cmath> #include "matrix.h" #define DEBUG 0 #define DEBUGINPUT 0 #define DEBUG_RESULTS 0 using namespace std; double activate( double input ); // Activation Function double sigmoid( double input ); // Sigmoid function int main() { // Initialization int numInputs = 0; int numOutputs = 0; int rows = 0; int cols = 0; int testRows = 0; int testCols = 0; double temp = -99; double bias = -1; // -1 is what the book uses. double eta = 0.025; // 0.25 is what the book uses. open to tweaking. int attempts = 5; // if debugging, SET THIS TO A SMALL NUMBER! int num_hidden_layers = 1; // is this a thing int num_hidden_nodes = 0; double max = 1; double min = 1; // Training Data Input // cin >> numInputs; cin >> num_hidden_nodes; cin >> rows; cin >> cols; numOutputs = cols - numInputs; Matrix* tinput = new Matrix(rows, numInputs + 1); Matrix* toutput = new Matrix(rows, numOutputs); if(DEBUGINPUT) { cout << "Inputs: " << numInputs << "\nHidden Nodes: " << num_hidden_nodes << "\nRows: " << rows << "\nCols: " << cols << endl; } // Fill the matrix for(int r = 0; r < rows; r++) { for(int c = 0; c < numInputs; c++) { cin >> temp; if( temp > max ) max = temp; else if( temp < min ) min = temp; tinput->setValue( r, c, temp); } for(int c = 0; c < numOutputs; c++ ) { cin >> temp; if( temp > max ) max = temp; else if( temp < min ) min = temp; toutput->setValue( r, c, temp); } } // Append the bias for( int r = 0; r < rows; r++ ) { tinput->setValue(r, numInputs, bias); } numInputs++; if(DEBUGINPUT) { cout << "\nTraining Inputs..." << endl; tinput->printAll(); cout << "\nTraining Outputs..." << endl; toutput->printAll(); } // Test Data Input // cin >> testRows; cin >> testCols; Matrix * testInput = new Matrix(testRows, testCols + 1); // Fill the matrix for(int r = 0; r < testRows; r++) { for(int c = 0; c < testCols; c++) { cin >> temp; if( temp > max ) max = temp; else if( temp < min ) min = temp; testInput->setValue(r, c, temp); } } // Append the bias for( int r = 0; r < testRows; r++ ) { testInput->setValue(r, testCols, bias); } testCols++; if(DEBUGINPUT) { cout << "\nTest Inputs matrix" << endl; testInput->printAll(); } // // // * Training * // Matrix * hw = new Matrix(numInputs, numOutputs, 2); Matrix * ow = new Matrix(numInputs + 1, numOutputs, 2); // +1 for the extra bias between hidden and output layers Matrix * tempmat; double tResult = -66.6; //init values are paranoia for error catching double aResult = -55.0; double fResult = -42.0; temp = -99; if(DEBUG) { cout << "\nInitialized Hidden Weight matrix..." << endl; hw->printAll(); } // Normalize our input (THIS COULD BE IMPROVED) TODO tinput->normalize(min, max); Matrix * deltah; // error in hidden layer Matrix * deltao; // error in output layer Matrix * a; // hidden layer output Matrix * y; // output layer output Matrix * hVec; Matrix * inVec; Matrix * t; // re-implementation for( int attempt = 0; attempt < attempts; attempt++ ) { for( int r = 0; r < rows; r++ ) { inVec = tinput->getRow(r); t = toutput->getRow(r); // hidden layer a = inVec->dot(hw); a->sigmoid(); hVec = new Matrix(a); hVec->data[0].push_back(bias); hVec->numCols++; // output layer y = hVec->dot(hw); y->sigmoid(); // output error t = t->sub(y); t = t->dot(y); y->scalarPreSub(1.0); deltao = t->dot(y); // hidden error deltah = hVec; hVec->scalarPreSub(1.0); deltah->dot(hVec); hVec->scalarPreSub(1.0); tempmat = deltao->dot(ow); tempmat = tempmat->transpose(); deltah = deltah->dot(tempmat); // update matricies tempmat = hVec->transpose(); tempmat = tempmat->dot(deltao); tempmat = tempmat->dot(eta); ow = ow->add(tempmat); deltah->data[0].pop_back(); deltah->numCols--; tempmat = inVec->transpose(); tempmat = inVec->dot(deltah); tempmat = tempmat->dot(eta); hw = hw->add(tempmat); delete deltao; delete deltah; delete a; delete y; delete hVec; delete inVec; delete t; } // rows } // attempts // // // Testing // tResult = -66.6; fResult = -42.0; //double * tempResults = new double[numOutputs]; //double * finalResults = new double[numOutputs]; cout << "BEGIN TESTING" << endl; for( int r = 0; r < rows; r++ ) { // Each row in testing set inVec = testInput->getRow(r); for (int i = 0; i < (numInputs - 1); i++) { cout << fixed << setprecision(2) << testInput->getValue(r, i) << " "; } // hidden layer a = inVec->dot(hw); a->sigmoid(); hVec = new Matrix(a); hVec->data[0].push_back(bias); hVec->numCols++; // output layer y = hVec->dot(hw); y->sigmoid(); for( int i = 0; i < numOutputs; i++ ) { cout << fixed << setprecision(0) << y->getValue(r, i) << " "; } cout << endl; // end the row's output } // row in set loop // Final Cleanup // delete hw; delete ow; delete tinput; delete toutput; delete testInput; return(0); } double activate( double input ) { if( input > 0.0 ) return 1.0; else return 0.0; } double sigmoid( double input ) { return (2 / (1 + exp(-25 * input)) - 1); } <|endoftext|>
<commit_before>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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 RESEMBLA_RESEMBLA_ENSEMBLE_HPP #define RESEMBLA_RESEMBLA_ENSEMBLE_HPP #include <math.h> #include <string> #include <vector> #include <memory> #include <unordered_map> #include <algorithm> #include <simstring/simstring.h> #include "resembla_interface.hpp" #include "eliminator.hpp" namespace resembla { template<typename Indexer, typename ScoreFunction> class ResemblaEnsemble: public ResemblaInterface { public: ResemblaEnsemble(const std::string& db_path, const std::string& index_path, std::shared_ptr<Indexer> indexer, std::shared_ptr<ScoreFunction> score, const std::string& measure_name, const size_t max_candidate = 0): indexer(indexer), score(score), measure_name(measure_name), max_candidate(max_candidate), total_weight(0.0) { load(db_path, index_path); } void append(const std::shared_ptr<ResemblaInterface> resembla, double weight = 1.0) { children.push_back(std::make_pair(resembla, weight)); total_weight += weight; } std::vector<output_type> find(const string_type& query, double threshold = 0.0, size_t max_response = 0) const { string_type search_query = indexer->index(query); // search from N-gram index std::vector<string_type> simstring_result; { std::lock_guard<std::mutex> lock(mutex_simstring); db.retrieve(search_query, simstring_measure, simstring_threshold, std::back_inserter(simstring_result)); } if(simstring_result.empty()){ return {}; } else if(simstring_result.size() > max_candidate){ Eliminator<string_type> eliminate(search_query); eliminate(simstring_result, max_candidate, true); } return eval(query, simstring_result, threshold, max_response); } std::vector<output_type> eval(const string_type& query, const std::vector<string_type>& candidates, double threshold = 0.0, size_t max_response = 0) const { std::unordered_map<string_type, std::vector<double>> work; for(const auto& child: children){ for(const auto& r: child->eval(query, candidates, 0.0, 0)){ auto p = work.insert(std::make_pair(r.text, r.score)); if(!p.second){ p.first += r.score; } } } std::vector<output_type> results; for(const auto& p: work){ double score = score_func(weights, p.second); if(score >= threshold){ results.push_back({p.first, measure_name, score}); } } if(max_response != 0 && response.size() > max_response){ std::partial_sort(results.begin(), results.begin() + max_response, results.end()); results.erase(results.begin() + max_response, results.end()); } else{ std::sort(results.begin(), results.end()); } return response; } protected: struct Child { std::string name; std::shared_ptr<ResemblaInterface> resembla; double weight; }; // name to be used in response const std::string measure_name; const size_t max_candidate; double total_weight; std::vector<Child> children; }; } #endif <commit_msg>simplify code<commit_after>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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 RESEMBLA_RESEMBLA_ENSEMBLE_HPP #define RESEMBLA_RESEMBLA_ENSEMBLE_HPP #include <math.h> #include <string> #include <vector> #include <memory> #include <unordered_map> #include <algorithm> #include <simstring/simstring.h> #include "resembla_interface.hpp" #include "eliminator.hpp" namespace resembla { template<typename Indexer, typename ScoreFunction> class ResemblaEnsemble: public ResemblaInterface { public: ResemblaEnsemble(const std::string& db_path, const std::string& index_path, std::shared_ptr<Indexer> indexer, std::shared_ptr<ScoreFunction> score, const std::string& measure_name, const size_t max_candidate = 0): indexer(indexer), score(score), measure_name(measure_name), max_candidate(max_candidate), total_weight(0.0) { load(db_path, index_path); } void append(const std::shared_ptr<ResemblaInterface> resembla, double weight = 1.0) { children.push_back(std::make_pair(resembla, weight)); weights.push_back(weight); total_weight += weight; } std::vector<output_type> find(const string_type& query, double threshold = 0.0, size_t max_response = 0) const { string_type search_query = indexer->index(query); // search from N-gram index std::vector<string_type> simstring_result; { std::lock_guard<std::mutex> lock(mutex_simstring); db.retrieve(search_query, simstring_measure, simstring_threshold, std::back_inserter(simstring_result)); } if(simstring_result.empty()){ return {}; } else if(simstring_result.size() > max_candidate){ Eliminator<string_type> eliminate(search_query); eliminate(simstring_result, max_candidate, true); } return eval(query, simstring_result, threshold, max_response); } std::vector<output_type> eval(const string_type& query, const std::vector<string_type>& candidates, double threshold = 0.0, size_t max_response = 0) const { std::unordered_map<string_type, std::vector<double>> work; for(const auto& resembla: children){ for(const auto& r: resembla->eval(query, candidates, 0.0, 0)){ auto p = work.insert(std::make_pair(r.text, {r.score})); if(!p.second){ p.first.push_back(r.score); } } } std::vector<output_type> results; for(const auto& p: work){ double score = score_func(weights, p.second); if(score >= threshold){ results.push_back({p.first, measure_name, score}); } } if(max_response != 0 && response.size() > max_response){ std::partial_sort(results.begin(), results.begin() + max_response, results.end()); results.erase(results.begin() + max_response, results.end()); } else{ std::sort(results.begin(), results.end()); } return response; } protected: // name to be used in response const std::string measure_name; const size_t max_candidate; std::vector<std::shared_ptr<ResemblaInterface>> children; std::vector<double> weights; double total_weight; }; } #endif <|endoftext|>
<commit_before>#include "map/place_page_info.hpp" #include "map/reachable_by_taxi_checker.hpp" #include "partners_api/ads_engine.hpp" #include "partners_api/banner.hpp" #include "indexer/feature_utils.hpp" #include "indexer/osm_editor.hpp" #include "platform/measurement_utils.hpp" #include "platform/preferred_languages.hpp" #include "platform/settings.hpp" namespace place_page { char const * const Info::kSubtitleSeparator = " • "; char const * const Info::kStarSymbol = "★"; char const * const Info::kMountainSymbol = "▲"; char const * const Info::kEmptyRatingSymbol = "-"; char const * const Info::kPricingSymbol = "$"; bool Info::IsFeature() const { return m_featureID.IsValid(); } bool Info::IsBookmark() const { return m_bac.IsValid(); } bool Info::IsMyPosition() const { return m_isMyPosition; } bool Info::IsRoutePoint() const { return m_isRoutePoint; } bool Info::IsSponsored() const { return m_sponsoredType != SponsoredType::None; } bool Info::IsNotEditableSponsored() const { return m_sponsoredType != SponsoredType::None && m_sponsoredType != SponsoredType::Opentable; } bool Info::ShouldShowAddPlace() const { auto const isPointOrBuilding = IsPointType() || IsBuilding(); return m_canEditOrAdd && !(IsFeature() && isPointOrBuilding); } bool Info::ShouldShowAddBusiness() const { return m_canEditOrAdd && IsBuilding(); } bool Info::ShouldShowEditPlace() const { return m_canEditOrAdd && // TODO(mgsergio): Does IsFeature() imply !IsMyPosition()? !IsMyPosition() && IsFeature(); } bool Info::HasApiUrl() const { return !m_apiUrl.empty(); } bool Info::HasWifi() const { return GetInternet() == osm::Internet::Wlan; } string Info::FormatNewBookmarkName() const { string const title = GetTitle(); if (title.empty()) return GetLocalizedType(); return title; } string Info::GetTitle() const { if (!m_customName.empty()) return m_customName; auto const mwmInfo = GetID().m_mwmId.GetInfo(); string primaryName; if (mwmInfo) { auto const deviceLang = StringUtf8Multilang::GetLangIndex(languages::GetCurrentNorm()); string secondaryName; feature::GetPreferredNames(mwmInfo->GetRegionData(), m_name, deviceLang, true /* allowTranslit */, primaryName, secondaryName); } return primaryName; } string Info::GetSecondaryTitle() const { auto const mwmInfo = GetID().m_mwmId.GetInfo(); string secondaryName; if (mwmInfo) { auto const deviceLang = StringUtf8Multilang::GetLangIndex(languages::GetCurrentNorm()); string primaryName; feature::GetPreferredNames(mwmInfo->GetRegionData(), m_name, deviceLang, true /* allowTranslit */, primaryName, secondaryName); } return secondaryName; } string Info::GetSubtitle() const { if (!IsFeature()) { if (IsBookmark()) return m_bookmarkCategoryName; return {}; } vector<string> values; // Bookmark category. if (IsBookmark()) values.push_back(m_bookmarkCategoryName); // Type. values.push_back(GetLocalizedType()); // Flats. string const flats = GetFlats(); if (!flats.empty()) values.push_back(flats); // Cuisines. for (string const & cuisine : GetLocalizedCuisines()) values.push_back(cuisine); // Stars. string const stars = FormatStars(); if (!stars.empty()) values.push_back(stars); // Operator. string const op = GetOperator(); if (!op.empty()) values.push_back(op); // Elevation. string const eleStr = GetElevationFormatted(); if (!eleStr.empty()) values.push_back(kMountainSymbol + eleStr); if (HasWifi()) values.push_back(m_localizedWifiString); return strings::JoinStrings(values, kSubtitleSeparator); } string Info::FormatStars() const { string stars; for (int i = 0; i < GetStars(); ++i) stars.append(kStarSymbol); return stars; } string Info::GetFormattedCoordinate(bool isDMS) const { auto const & ll = GetLatLon(); return isDMS ? measurement_utils::FormatLatLon(ll.lat, ll.lon, true) : measurement_utils::FormatLatLonAsDMS(ll.lat, ll.lon, 2); } string Info::GetCustomName() const { return m_customName; } BookmarkAndCategory Info::GetBookmarkAndCategory() const { return m_bac; } string Info::GetBookmarkCategoryName() const { return m_bookmarkCategoryName; } string const & Info::GetApiUrl() const { return m_apiUrl; } string const & Info::GetSponsoredUrl() const { return m_sponsoredUrl; } string const & Info::GetSponsoredDescriptionUrl() const { return m_sponsoredDescriptionUrl; } string const & Info::GetSponsoredReviewUrl() const { return m_sponsoredReviewUrl; } string Info::GetRatingFormatted() const { if (!IsSponsored()) return string(); auto const r = GetMetadata().Get(feature::Metadata::FMD_RATING); char const * rating = r.empty() ? kEmptyRatingSymbol : r.c_str(); int const size = snprintf(nullptr, 0, m_localizedRatingString.c_str(), rating); if (size < 0) { LOG(LERROR, ("Incorrect size for string:", m_localizedRatingString, ", rating:", rating)); return string(); } vector<char> buf(size + 1); snprintf(buf.data(), buf.size(), m_localizedRatingString.c_str(), rating); return string(buf.begin(), buf.end()); } string Info::GetApproximatePricing() const { if (!IsSponsored()) return string(); int pricing; if (!strings::to_int(GetMetadata().Get(feature::Metadata::FMD_PRICE_RATE), pricing)) return string(); string result; for (auto i = 0; i < pricing; i++) result.append(kPricingSymbol); return result; } bool Info::HasBanner() const { if (!m_adsEngine) return false; if (IsMyPosition()) return false; return m_adsEngine->HasBanner(m_types, m_topmostCountryIds, languages::GetCurrentNorm()); } vector<ads::Banner> Info::GetBanners() const { if (!m_adsEngine) return {}; return m_adsEngine->GetBanners(m_types, m_topmostCountryIds, languages::GetCurrentNorm()); } bool Info::IsReachableByTaxi() const { return IsReachableByTaxiChecker::Instance()(m_types); } void Info::SetMercator(m2::PointD const & mercator) { m_mercator = mercator; } vector<string> Info::GetRawTypes() const { return m_types.ToObjectNames(); } string const & Info::GetBookingSearchUrl() const { return m_bookingSearchUrl; } LocalAdsStatus Info::GetLocalAdsStatus() const { return m_localAdsStatus; } string const & Info::GetLocalAdsUrl() const { return m_localAdsUrl; } } // namespace place_page <commit_msg>Added wheelchair sybmol into place page subtitle.<commit_after>#include "map/place_page_info.hpp" #include "map/reachable_by_taxi_checker.hpp" #include "partners_api/ads_engine.hpp" #include "partners_api/banner.hpp" #include "indexer/feature_utils.hpp" #include "indexer/osm_editor.hpp" #include "platform/measurement_utils.hpp" #include "platform/preferred_languages.hpp" #include "platform/settings.hpp" namespace place_page { char const * const Info::kSubtitleSeparator = " • "; char const * const Info::kStarSymbol = "★"; char const * const Info::kMountainSymbol = "▲"; char const * const Info::kEmptyRatingSymbol = "-"; char const * const Info::kPricingSymbol = "$"; char const * const kWheelchairSymbol = u8"\u267F"; bool Info::IsFeature() const { return m_featureID.IsValid(); } bool Info::IsBookmark() const { return m_bac.IsValid(); } bool Info::IsMyPosition() const { return m_isMyPosition; } bool Info::IsRoutePoint() const { return m_isRoutePoint; } bool Info::IsSponsored() const { return m_sponsoredType != SponsoredType::None; } bool Info::IsNotEditableSponsored() const { return m_sponsoredType != SponsoredType::None && m_sponsoredType != SponsoredType::Opentable; } bool Info::ShouldShowAddPlace() const { auto const isPointOrBuilding = IsPointType() || IsBuilding(); return m_canEditOrAdd && !(IsFeature() && isPointOrBuilding); } bool Info::ShouldShowAddBusiness() const { return m_canEditOrAdd && IsBuilding(); } bool Info::ShouldShowEditPlace() const { return m_canEditOrAdd && // TODO(mgsergio): Does IsFeature() imply !IsMyPosition()? !IsMyPosition() && IsFeature(); } bool Info::HasApiUrl() const { return !m_apiUrl.empty(); } bool Info::HasWifi() const { return GetInternet() == osm::Internet::Wlan; } string Info::FormatNewBookmarkName() const { string const title = GetTitle(); if (title.empty()) return GetLocalizedType(); return title; } string Info::GetTitle() const { if (!m_customName.empty()) return m_customName; auto const mwmInfo = GetID().m_mwmId.GetInfo(); string primaryName; if (mwmInfo) { auto const deviceLang = StringUtf8Multilang::GetLangIndex(languages::GetCurrentNorm()); string secondaryName; feature::GetPreferredNames(mwmInfo->GetRegionData(), m_name, deviceLang, true /* allowTranslit */, primaryName, secondaryName); } return primaryName; } string Info::GetSecondaryTitle() const { auto const mwmInfo = GetID().m_mwmId.GetInfo(); string secondaryName; if (mwmInfo) { auto const deviceLang = StringUtf8Multilang::GetLangIndex(languages::GetCurrentNorm()); string primaryName; feature::GetPreferredNames(mwmInfo->GetRegionData(), m_name, deviceLang, true /* allowTranslit */, primaryName, secondaryName); } return secondaryName; } string Info::GetSubtitle() const { if (!IsFeature()) { if (IsBookmark()) return m_bookmarkCategoryName; return {}; } vector<string> values; // Bookmark category. if (IsBookmark()) values.push_back(m_bookmarkCategoryName); // Type. values.push_back(GetLocalizedType()); // Flats. string const flats = GetFlats(); if (!flats.empty()) values.push_back(flats); // Cuisines. for (string const & cuisine : GetLocalizedCuisines()) values.push_back(cuisine); // Stars. string const stars = FormatStars(); if (!stars.empty()) values.push_back(stars); // Operator. string const op = GetOperator(); if (!op.empty()) values.push_back(op); // Elevation. string const eleStr = GetElevationFormatted(); if (!eleStr.empty()) values.push_back(kMountainSymbol + eleStr); if (HasWifi()) values.push_back(m_localizedWifiString); // Wheelchair if (GetWheelchairType() == wheelchair::Type::Yes) values.push_back(kWheelchairSymbol); return strings::JoinStrings(values, kSubtitleSeparator); } string Info::FormatStars() const { string stars; for (int i = 0; i < GetStars(); ++i) stars.append(kStarSymbol); return stars; } string Info::GetFormattedCoordinate(bool isDMS) const { auto const & ll = GetLatLon(); return isDMS ? measurement_utils::FormatLatLon(ll.lat, ll.lon, true) : measurement_utils::FormatLatLonAsDMS(ll.lat, ll.lon, 2); } string Info::GetCustomName() const { return m_customName; } BookmarkAndCategory Info::GetBookmarkAndCategory() const { return m_bac; } string Info::GetBookmarkCategoryName() const { return m_bookmarkCategoryName; } string const & Info::GetApiUrl() const { return m_apiUrl; } string const & Info::GetSponsoredUrl() const { return m_sponsoredUrl; } string const & Info::GetSponsoredDescriptionUrl() const { return m_sponsoredDescriptionUrl; } string const & Info::GetSponsoredReviewUrl() const { return m_sponsoredReviewUrl; } string Info::GetRatingFormatted() const { if (!IsSponsored()) return string(); auto const r = GetMetadata().Get(feature::Metadata::FMD_RATING); char const * rating = r.empty() ? kEmptyRatingSymbol : r.c_str(); int const size = snprintf(nullptr, 0, m_localizedRatingString.c_str(), rating); if (size < 0) { LOG(LERROR, ("Incorrect size for string:", m_localizedRatingString, ", rating:", rating)); return string(); } vector<char> buf(size + 1); snprintf(buf.data(), buf.size(), m_localizedRatingString.c_str(), rating); return string(buf.begin(), buf.end()); } string Info::GetApproximatePricing() const { if (!IsSponsored()) return string(); int pricing; if (!strings::to_int(GetMetadata().Get(feature::Metadata::FMD_PRICE_RATE), pricing)) return string(); string result; for (auto i = 0; i < pricing; i++) result.append(kPricingSymbol); return result; } bool Info::HasBanner() const { if (!m_adsEngine) return false; if (IsMyPosition()) return false; return m_adsEngine->HasBanner(m_types, m_topmostCountryIds, languages::GetCurrentNorm()); } vector<ads::Banner> Info::GetBanners() const { if (!m_adsEngine) return {}; return m_adsEngine->GetBanners(m_types, m_topmostCountryIds, languages::GetCurrentNorm()); } bool Info::IsReachableByTaxi() const { return IsReachableByTaxiChecker::Instance()(m_types); } void Info::SetMercator(m2::PointD const & mercator) { m_mercator = mercator; } vector<string> Info::GetRawTypes() const { return m_types.ToObjectNames(); } string const & Info::GetBookingSearchUrl() const { return m_bookingSearchUrl; } LocalAdsStatus Info::GetLocalAdsStatus() const { return m_localAdsStatus; } string const & Info::GetLocalAdsUrl() const { return m_localAdsUrl; } } // namespace place_page <|endoftext|>
<commit_before>#include "utAllocore.h" int utFile() { #define DELIM AL_FILE_DELIMITER_STR // static functions assert(File::exists(".")); //assert(File::exists("." DELIM)); // fails under win32 assert(File::isDirectory(".")); assert(File::isDirectory(".." )); assert(!File::isDirectory(".." DELIM ".." DELIM "Makefile")); assert( File::conformDirectory("test") == "test" DELIM ); assert( File::conformDirectory("test" DELIM) == "test" DELIM ); assert( File::conformPathToOS("..\\../Makefile") == ".." DELIM ".." DELIM "Makefile" ); assert( File::conformPathToOS("..\\../") == ".." DELIM ".." DELIM ); assert( File::conformPathToOS("..\\..") == ".." DELIM ".." DELIM ); // simple file/directory searching { std::string dir; // Search for file (that exists and probably will not be moved...) std::string find = "Makefile"; bool r = File::searchBack(dir, find); assert(r); assert(File::exists(dir + find)); find = ".." DELIM + find; // check for a file with path r = File::searchBack(dir, find); assert(r); assert(File::exists(dir + find)); assert(!File::searchBack(dir, "thisdirectorydoesnotexist" DELIM "thisfiledoesnotexist.ext")); } { const char * path = "utFile.txt"; const char * text = "This is a test of AlloCore file i/o functionality. You can safely delete this file."; // write data File f(path, "w"); assert(!f.opened()); assert(f.open()); assert(f.opened()); assert(File::exists(path)); assert( f.write(text, strlen(text)) ); assert(f.size() == (int)strlen(text)); f.close(); assert(!f.opened()); assert(File::exists(path)); // read data f.mode("r").open(); assert(f.opened()); const char * read = f.readAll(); assert(f.size() == (int)strlen(text)); for(int i=0; i<f.size(); ++i){ assert(read[i] == text[i]); // printf("%c", read[i]); } f.close(); f.path( "thisdirectroydoesnotexist" DELIM "neitherdoesthisone" DELIM "notafile.txt" ); assert(!f.open()); } { assert(Dir::make("utFileTestDir")); assert(Dir::remove("utFileTestDir")); // For now, just make sure this compiles and doesn't crash. :) Dir dir; if(dir.open("/")){ for(int i=0; i<1; ++i){ dir.rewind(); while(dir.read()){ //printf("%c %s\n", dir.entry().type() == FileInfo::DIR ? 'd':' ', dir.entry().name().c_str()); } } } } { // TODO: SearchPaths sp; //printf("%s\n", sp.appPath().c_str()); } { // TODO: FilePath fp("file.txt", "path"); //printf("%s\n", fp.filepath().c_str()); } #undef DELIM return 0; } <commit_msg>Fix for failing test on allocoreTests<commit_after>#include "utAllocore.h" int utFile() { #define DELIM AL_FILE_DELIMITER_STR // static functions assert(File::exists(".")); //assert(File::exists("." DELIM)); // fails under win32 assert(File::isDirectory(".")); assert(File::isDirectory(".." )); assert(!File::isDirectory(".." DELIM ".." DELIM "Makefile")); assert( File::conformDirectory("test") == "test" DELIM ); assert( File::conformDirectory("test" DELIM) == "test" DELIM ); assert( File::conformPathToOS("..\\../Makefile") == ".." DELIM ".." DELIM "Makefile" ); assert( File::conformPathToOS("..\\../") == ".." DELIM ".." DELIM ); assert( File::conformPathToOS("..\\..") == ".." DELIM ".." DELIM ); // simple file/directory searching { std::string dir; // Search for file (that exists and probably will not be moved...) std::string find = "Makefile"; bool r = File::searchBack(dir, find); assert(r); assert(File::exists(dir + find)); find = "allocore" DELIM + find; // check for a file with path r = File::searchBack(dir, find); assert(r); assert(File::exists(dir + find)); assert(!File::searchBack(dir, "thisdirectorydoesnotexist" DELIM "thisfiledoesnotexist.ext")); } { const char * path = "utFile.txt"; const char * text = "This is a test of AlloCore file i/o functionality. You can safely delete this file."; // write data File f(path, "w"); assert(!f.opened()); assert(f.open()); assert(f.opened()); assert(File::exists(path)); assert( f.write(text, strlen(text)) ); assert(f.size() == (int)strlen(text)); f.close(); assert(!f.opened()); assert(File::exists(path)); // read data f.mode("r").open(); assert(f.opened()); const char * read = f.readAll(); assert(f.size() == (int)strlen(text)); for(int i=0; i<f.size(); ++i){ assert(read[i] == text[i]); // printf("%c", read[i]); } f.close(); f.path( "thisdirectroydoesnotexist" DELIM "neitherdoesthisone" DELIM "notafile.txt" ); assert(!f.open()); } { assert(Dir::make("utFileTestDir")); assert(Dir::remove("utFileTestDir")); // For now, just make sure this compiles and doesn't crash. :) Dir dir; if(dir.open("/")){ for(int i=0; i<1; ++i){ dir.rewind(); while(dir.read()){ //printf("%c %s\n", dir.entry().type() == FileInfo::DIR ? 'd':' ', dir.entry().name().c_str()); } } } } { // TODO: SearchPaths sp; //printf("%s\n", sp.appPath().c_str()); } { // TODO: FilePath fp("file.txt", "path"); //printf("%s\n", fp.filepath().c_str()); } #undef DELIM return 0; } <|endoftext|>
<commit_before>/** * \file drawSliceInPhi.cc * \example segmented/drawSliceInPhi.cc */ // Draw weighting potential of a segment of Siegfried (6 segments in phi) void CalculateWeightingPotential() { GeFiCa::SegmentedInPhi *siegfried = new GeFiCa::SegmentedInPhi; siegfried->V0=0*GeFiCa::volt; siegfried->V1=1*GeFiCa::volt; siegfried->SegmentNum=6; siegfried->SegmentID=1; siegfried->CalculatePotential(GeFiCa::kSOR2); siegfried->SaveField("siegfried.root"); } //______________________________________________________________________________ // void DrawWeightingPotential() { // pick up a good default drawing style to modify gROOT->SetStyle("Plain"); gStyle->SetTitleFont(132,"XYZ"); gStyle->SetTitleSize(0.05,"XYZ"); gStyle->SetLabelFont(132,"XYZ"); gStyle->SetLabelSize(0.05,"XYZ"); gStyle->SetPadRightMargin(0.12); gStyle->SetPadLeftMargin(0.08); gStyle->SetPadTopMargin(0.02); // create a smoother palette than the default one const int nRGBs = 5; const int nCont = 255; double stops[nRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 }; double red[nRGBs] = { 0.00, 0.00, 0.87, 1.00, 0.51 }; double green[nRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 }; double blue[nRGBs] = { 0.51, 1.00, 0.12, 0.00, 0.00 }; TColor::CreateGradientColorTable(nRGBs, stops, red, green, blue, nCont); gStyle->SetNumberContours(nCont); // make a square canvas TCanvas *c = new TCanvas("c", "c", 450, 450); c->SetLogz(); // load data and draw TChain *t = new TChain("t"); t->Add("siegfried.root"); t->Draw("c1*sin(c2):c1*cos(c2):v","","colz"); // fine tune plot TH2F *h = (TH2F*) gPad->GetPrimitive("htemp"); h->SetTitle(";x [cm];y [cm];weighting potential [V]"); h->GetYaxis()->SetTitleOffset(0.7); h->GetZaxis()->SetTitleOffset(-0.4); h->GetXaxis()->CenterTitle(); h->GetYaxis()->CenterTitle(); h->GetZaxis()->CenterTitle(); // widen the color palette gPad->Update(); // create the palette by forcely drawing the plot TPaletteAxis *palette = (TPaletteAxis*) h->GetListOfFunctions()->FindObject("palette"); palette->SetX2NDC(0.94); h->Draw("colz"); // let the new setup take effect // draw segmentation scheme GeFiCa::SegmentedInPhi *siegfried = new GeFiCa::SegmentedInPhi(); double r=siegfried->RUpperBound, x=r*cos(3.14/3), y=r*sin(3.14/3); TLine *l1 = new TLine(-r,0,r,0); l1->SetLineColor(kWhite); l1->SetLineStyle(kDashed); l1->Draw(); TLine *l2 = new TLine(-x,-y,x,y); l2->SetLineColor(kWhite); l2->SetLineStyle(kDashed); l2->Draw(); TLine *l3 = new TLine(-x,y,x,-y); l3->SetLineColor(kWhite); l3->SetLineStyle(kDashed); l3->Draw(); } //______________________________________________________________________________ // void drawSliceInPhi() { if (1||gSystem->Which(".","siegfried.root")==0) CalculateWeightingPotential(); DrawWeightingPotential(); } <commit_msg>minor change<commit_after>// Draw weighting potential of a segment of Siegfried (6 segments in phi) void CalculateWeightingPotential() { GeFiCa::SegmentedInPhi *siegfried = new GeFiCa::SegmentedInPhi; siegfried->V0=0*GeFiCa::volt; siegfried->V1=1*GeFiCa::volt; siegfried->SegmentNum=6; siegfried->SegmentID=1; siegfried->CalculatePotential(GeFiCa::kSOR2); siegfried->SaveField("siegfried.root"); } //______________________________________________________________________________ // void DrawWeightingPotential() { // pick up a good default drawing style to modify gROOT->SetStyle("Plain"); gStyle->SetTitleFont(132,"XYZ"); gStyle->SetTitleSize(0.05,"XYZ"); gStyle->SetLabelFont(132,"XYZ"); gStyle->SetLabelSize(0.05,"XYZ"); gStyle->SetPadRightMargin(0.12); gStyle->SetPadLeftMargin(0.08); gStyle->SetPadTopMargin(0.02); // create a smoother palette than the default one const int nRGBs = 5; const int nCont = 255; double stops[nRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 }; double red[nRGBs] = { 0.00, 0.00, 0.87, 1.00, 0.51 }; double green[nRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 }; double blue[nRGBs] = { 0.51, 1.00, 0.12, 0.00, 0.00 }; TColor::CreateGradientColorTable(nRGBs, stops, red, green, blue, nCont); gStyle->SetNumberContours(nCont); // make a square canvas TCanvas *c = new TCanvas("c", "c", 450, 450); c->SetLogz(); // load data and draw TChain *t = new TChain("t"); t->Add("siegfried.root"); t->Draw("c1*sin(c2):c1*cos(c2):v","","colz"); // fine tune plot TH2F *h = (TH2F*) gPad->GetPrimitive("htemp"); h->SetTitle(";x [cm];y [cm];weighting potential [V]"); h->GetYaxis()->SetTitleOffset(0.7); h->GetZaxis()->SetTitleOffset(-0.4); h->GetXaxis()->CenterTitle(); h->GetYaxis()->CenterTitle(); h->GetZaxis()->CenterTitle(); // widen the color palette gPad->Update(); // create the palette by forcedly drawing the plot TPaletteAxis *palette = (TPaletteAxis*) h->GetListOfFunctions()->FindObject("palette"); palette->SetX2NDC(0.94); h->Draw("colz"); // let the new setup take effect // draw segmentation scheme GeFiCa::SegmentedInPhi *siegfried = new GeFiCa::SegmentedInPhi(); double r=siegfried->RUpperBound, x=r*cos(3.14/3), y=r*sin(3.14/3); TLine *l1 = new TLine(-r,0,r,0); l1->SetLineColor(kWhite); l1->SetLineStyle(kDashed); l1->Draw(); TLine *l2 = new TLine(-x,-y,x,y); l2->SetLineColor(kWhite); l2->SetLineStyle(kDashed); l2->Draw(); TLine *l3 = new TLine(-x,y,x,-y); l3->SetLineColor(kWhite); l3->SetLineStyle(kDashed); l3->Draw(); } //______________________________________________________________________________ // void drawSliceInPhi() { if (1||gSystem->Which(".","siegfried.root")==0) CalculateWeightingPotential(); DrawWeightingPotential(); } <|endoftext|>
<commit_before>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <globals.h> #include <prototypes.h> #include <pthread.h> #include <iostream.h> #include <stdio.h> #include <unistd.h> #include <sys/time.h> // DT: 3/97 needed for time function #include "../rtstuff/heap/heap.h" #include "../rtstuff/rtdefs.h" #include "../H/dbug.h" //#define TBUG //#define ALLBUG double baseTime; long elapsed; IBusClass checkClass(BusSlot *slot) { if (slot == NULL) return UNKNOWN; if ((slot->auxin_count > 0) && (slot->auxout_count > 0)) return AUX_TO_AUX; if ((slot->auxout_count > 0) && (slot->out_count > 0)) return TO_AUX_AND_OUT; if (slot->auxout_count > 0) return TO_AUX; if (slot->out_count > 0) return TO_OUT; return UNKNOWN; } extern "C" { void *inTraverse(void *arg) { short rtInst; short playEm; int i,j,chunksamps; int heapSize,rtQSize,allQSize; int offset,endsamp; int keepGoing; int dummy; short bus_q_offset; Instrument *Iptr; unsigned long bufEndSamp; unsigned long chunkStart; unsigned long heapChunkStart; struct timeval tv; struct timezone tz; double sec,usec; Bool aux_pb_done,frame_done; short bus,bus_count,play_bus,busq,endbus,t_bus,t_count; IBusClass bus_class,qStatus,t_class; BusType bus_type; // cout << "ENTERING inTraverse() FUNCTION *****\n"; // Wait for the ok to go ahead if (!audio_config) { cout << "inTraverse(): waiting for audio_config . . . "; } while (!audio_config) { // Do nothing } if (audio_config && rtInteractive) { cout << "audio set.\n\n"; } gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; usec = (double)tv.tv_usec; baseTime = (sec * 1e6) + usec; // Initialize everything bufStartSamp = 0; // current end sample for buffer bufEndSamp = RTBUFSAMPS; chunkStart = 0; heapSize = 0; chunkStart = 0; elapsed = 0; rtInst = 0; playEm = 0; // printf("ENTERING inTraverse() FUNCTION\n"); // NOTE: audioin, aux and output buffers are zero'd during allocation // read in an input buffer (if audio input is active) if (audio_on) { rtgetsamps(); rtsendzeros(0); // send a buffer of zeros to audio device } if (rtsetparams_called) // otherwise, disk-based only playEm = 1; while(playEm) { // the big loop ========================================== pthread_mutex_lock(&heapLock); heapSize = rtHeap.getSize(); if (heapSize > 0) { heapChunkStart = rtHeap.getTop(); } pthread_mutex_unlock(&heapLock); // Pop elements off rtHeap and insert into rtQueue ---------------------- while ((heapChunkStart < bufEndSamp) && (heapSize > 0)) { rtInst = 1; pthread_mutex_lock(&heapLock); Iptr = rtHeap.deleteMin(); // get next instrument off heap pthread_mutex_unlock(&heapLock); if (!Iptr) break; #ifdef TBUG if ((Bus_Configed == NO) && (print_is_on)) { printf("WARNING: no bus_configs defined, using default\n"); } #endif // DJT Now we push things onto different queues bus_class = checkClass(Iptr->bus_config); switch (bus_class) { case TO_AUX: bus_count = Iptr->bus_config->auxout_count; bus_q_offset = 0; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->auxout[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_AUX[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; case AUX_TO_AUX: bus_count = Iptr->bus_config->auxout_count; bus_q_offset = MAXBUS; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->auxout[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on AUX_TO_AUX[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; case TO_OUT: bus_count = Iptr->bus_config->out_count; bus_q_offset = MAXBUS*2; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->out[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_OUT[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; case TO_AUX_AND_OUT: bus_count = Iptr->bus_config->out_count; bus_q_offset = MAXBUS; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->out[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_OUT2[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } bus_count = Iptr->bus_config->auxout_count; bus_q_offset = 2*MAXBUS; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->auxout[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_AUX2[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } pthread_mutex_lock(&heapLock); heapSize = rtHeap.getSize(); if (heapSize > 0) heapChunkStart = rtHeap.getTop(); pthread_mutex_unlock(&heapLock); } qStatus = TO_AUX; play_bus = 0; aux_pb_done = NO; allQSize = 0; // rtQueue[] playback shuffling ---------------------------------------- while (!aux_pb_done) { switch (qStatus) { case TO_AUX: bus_q_offset = 0; bus_type = BUS_AUX_OUT; bus = ToAuxPlayList[play_bus++]; break; case AUX_TO_AUX: bus_q_offset = MAXBUS; bus = AuxToAuxPlayList[play_bus++]; bus_type = BUS_AUX_OUT; break; case TO_OUT: bus_q_offset = MAXBUS*2; bus = ToOutPlayList[play_bus++]; bus_type = BUS_OUT; break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } if (bus != -1) busq = bus+bus_q_offset; else busq = bus; if (bus == -1) { switch (qStatus) { case TO_AUX: qStatus = AUX_TO_AUX; play_bus = 0; break; case AUX_TO_AUX: qStatus = TO_OUT; play_bus = 0; break; case TO_OUT: #ifdef TBUG cout << "aux_pb_done\n"; #endif aux_pb_done = YES; break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } } #ifdef TBUG cout << "bus: " << bus << endl; cout << "busq: " << busq << endl; #endif if (busq != -1) { rtQSize = rtQueue[busq].getSize(); if (rtQSize > 0) { chunkStart = rtQueue[busq].nextChunk(); } } // Play elements on queue (insert back in if needed) - - - - - - - - while ((rtQSize > 0) && (chunkStart < bufEndSamp) && (bus != -1)) { #ifdef ALLBUG cout << "Begin iteration==========\n"; cout << "Q-chunkStart: " << chunkStart << endl; cout << "bufEndSamp: " << bufEndSamp << endl; cout << "RTBUFSAMPS: " << RTBUFSAMPS << endl; #endif Iptr = rtQueue[busq].pop(); // get next instrument off queue endsamp = Iptr->getendsamp(); // difference in sample start (countdown) offset = chunkStart - bufStartSamp; if (offset < 0) { // BGG: added this trap for robustness cout << "WARNING: the scheduler is behind the queue!" << endl; offset = 0; } Iptr->set_output_offset(offset); if (endsamp < bufEndSamp) { // compute # of samples to write chunksamps = endsamp-chunkStart; } else { chunksamps = bufEndSamp-chunkStart; } Iptr->setchunk(chunksamps); // set "chunksamps" #ifdef TBUG cout << "Iptr->exec(" << bus_type << "," << bus << ")\n"; #endif Iptr->exec(bus_type, bus); // write the samples * * * * * * * * * #ifdef TBUG cout << "endbus " << endbus << endl; #endif // ReQueue or delete - - - - - - - - - - - - - - - - - - - if (endsamp > bufEndSamp) { #ifdef ALLBUG cout << "inTraverse(): re queueing instrument\n"; #endif rtQueue[busq].push(Iptr,chunkStart+chunksamps); // put back onto queue } else { t_class = checkClass(Iptr->bus_config); switch (t_class) { case TO_AUX: t_count = Iptr->bus_config->auxout_count; endbus = Iptr->bus_config->auxout[t_count]; break; case AUX_TO_AUX: t_count = Iptr->bus_config->auxout_count; endbus = Iptr->bus_config->auxout[t_count]; break; case TO_AUX_AND_OUT: if (qStatus == TO_OUT) { t_count = Iptr->bus_config->out_count; endbus = Iptr->bus_config->out[t_count]; } else endbus = 1000; /* can never equal this */ break; case TO_OUT: t_count = Iptr->bus_config->out_count; endbus = Iptr->bus_config->out[t_count]; break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } if ((qStatus == t_class) && (bus == endbus) && (endsamp >= bufEndSamp)) delete Iptr; } // DJT: not sure this check before new chunkStart is necessary rtQSize = rtQueue[busq].getSize(); if (rtQSize) { chunkStart = rtQueue[busq].nextChunk(); allQSize += rtQSize; } #ifdef TBUG cout << "rtQSize: " << rtQSize << endl; cout << "chunkStart: " << chunkStart << endl; cout << "chunksamps: " << chunksamps << endl; cout << "Iteration done==========\n"; #endif } } // Write buf to audio device ------------------------------------------- #ifdef ALLBUG cout << "Writing samples----------\n"; cout << "Q-chunkStart: " << chunkStart << endl; cout << "bufEndSamp: " << bufEndSamp << endl; #endif rtsendsamps(); // zero the buffers clear_aux_buffers(); clear_output_buffers(); // read in an input buffer (if audio input is active) if (audio_on) { // cout << "Reading data from audio port\n"; rtgetsamps(); } gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; usec = (double)tv.tv_usec; baseTime = (sec * 1e6) + usec; elapsed += RTBUFSAMPS; bufStartSamp += RTBUFSAMPS; bufEndSamp += RTBUFSAMPS; if (!rtInteractive) { // Ending condition if ((heapSize == 0) && (allQSize == 0)) { #ifdef TBUG cout << "heapSize: " << heapSize << endl; cout << "rtQSize: " << rtQSize << endl; cout << "PLAYEM = 0\n"; cout << "The end\n\n"; #endif playEm = 0; } } } // end playEm ========================================================= if (rtsetparams_called) { if (play_audio) { // Play zero'd buffers to avoid clicks int count = NCHANS * 4; // DJT: clicks on my box with 2 for (j = 0; j < count; j++) rtsendzeros(0); } close_audio_ports(); rtreportstats(); rtcloseout(); } cout << "\n"; // cout << "EXITING inTraverse() FUNCTION *****\n"; // exit(1); } } /* extern "C" */ <commit_msg>More fixes to Iptr deletion.<commit_after>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <globals.h> #include <prototypes.h> #include <pthread.h> #include <iostream.h> #include <stdio.h> #include <unistd.h> #include <sys/time.h> // DT: 3/97 needed for time function #include "../rtstuff/heap/heap.h" #include "../rtstuff/rtdefs.h" #include "../H/dbug.h" //#define TBUG //#define ALLBUG double baseTime; long elapsed; IBusClass checkClass(BusSlot *slot) { if (slot == NULL) return UNKNOWN; if ((slot->auxin_count > 0) && (slot->auxout_count > 0)) return AUX_TO_AUX; if ((slot->auxout_count > 0) && (slot->out_count > 0)) return TO_AUX_AND_OUT; if (slot->auxout_count > 0) return TO_AUX; if (slot->out_count > 0) return TO_OUT; return UNKNOWN; } extern "C" { void *inTraverse(void *arg) { short rtInst; short playEm; int i,j,chunksamps; int heapSize,rtQSize,allQSize; int offset,endsamp; int keepGoing; int dummy; short bus_q_offset; Instrument *Iptr; unsigned long bufEndSamp; unsigned long chunkStart; unsigned long heapChunkStart; struct timeval tv; struct timezone tz; double sec,usec; Bool aux_pb_done,frame_done; short bus,bus_count,play_bus,busq,endbus,t_bus,t_count; IBusClass bus_class,qStatus,t_class; BusType bus_type; // cout << "ENTERING inTraverse() FUNCTION *****\n"; // Wait for the ok to go ahead if (!audio_config) { cout << "inTraverse(): waiting for audio_config . . . "; } while (!audio_config) { // Do nothing } if (audio_config && rtInteractive) { cout << "audio set.\n\n"; } gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; usec = (double)tv.tv_usec; baseTime = (sec * 1e6) + usec; // Initialize everything bufStartSamp = 0; // current end sample for buffer bufEndSamp = RTBUFSAMPS; chunkStart = 0; heapSize = 0; chunkStart = 0; elapsed = 0; rtInst = 0; playEm = 0; // printf("ENTERING inTraverse() FUNCTION\n"); // NOTE: audioin, aux and output buffers are zero'd during allocation // read in an input buffer (if audio input is active) if (audio_on) { rtgetsamps(); rtsendzeros(0); // send a buffer of zeros to audio device } if (rtsetparams_called) // otherwise, disk-based only playEm = 1; while(playEm) { // the big loop ========================================== pthread_mutex_lock(&heapLock); heapSize = rtHeap.getSize(); if (heapSize > 0) { heapChunkStart = rtHeap.getTop(); } pthread_mutex_unlock(&heapLock); // Pop elements off rtHeap and insert into rtQueue ---------------------- while ((heapChunkStart < bufEndSamp) && (heapSize > 0)) { rtInst = 1; pthread_mutex_lock(&heapLock); Iptr = rtHeap.deleteMin(); // get next instrument off heap pthread_mutex_unlock(&heapLock); if (!Iptr) break; #ifdef TBUG if ((Bus_Configed == NO) && (print_is_on)) { printf("WARNING: no bus_configs defined, using default\n"); } #endif // DJT Now we push things onto different queues bus_class = checkClass(Iptr->bus_config); switch (bus_class) { case TO_AUX: bus_count = Iptr->bus_config->auxout_count; bus_q_offset = 0; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->auxout[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_AUX[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; case AUX_TO_AUX: bus_count = Iptr->bus_config->auxout_count; bus_q_offset = MAXBUS; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->auxout[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on AUX_TO_AUX[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; case TO_OUT: bus_count = Iptr->bus_config->out_count; bus_q_offset = MAXBUS*2; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->out[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_OUT[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; case TO_AUX_AND_OUT: bus_count = Iptr->bus_config->out_count; bus_q_offset = MAXBUS; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->out[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_OUT2[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } bus_count = Iptr->bus_config->auxout_count; bus_q_offset = 2*MAXBUS; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->auxout[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_AUX2[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } pthread_mutex_lock(&heapLock); heapSize = rtHeap.getSize(); if (heapSize > 0) heapChunkStart = rtHeap.getTop(); pthread_mutex_unlock(&heapLock); } qStatus = TO_AUX; play_bus = 0; aux_pb_done = NO; allQSize = 0; // rtQueue[] playback shuffling ---------------------------------------- while (!aux_pb_done) { switch (qStatus) { case TO_AUX: bus_q_offset = 0; bus_type = BUS_AUX_OUT; bus = ToAuxPlayList[play_bus++]; break; case AUX_TO_AUX: bus_q_offset = MAXBUS; bus = AuxToAuxPlayList[play_bus++]; bus_type = BUS_AUX_OUT; break; case TO_OUT: bus_q_offset = MAXBUS*2; bus = ToOutPlayList[play_bus++]; bus_type = BUS_OUT; break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } if (bus != -1) busq = bus+bus_q_offset; else busq = bus; if (bus == -1) { switch (qStatus) { case TO_AUX: qStatus = AUX_TO_AUX; play_bus = 0; break; case AUX_TO_AUX: qStatus = TO_OUT; play_bus = 0; break; case TO_OUT: #ifdef TBUG cout << "aux_pb_done\n"; #endif aux_pb_done = YES; break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } } #ifdef TBUG cout << "bus: " << bus << endl; cout << "busq: " << busq << endl; #endif if (busq != -1) { rtQSize = rtQueue[busq].getSize(); if (rtQSize > 0) { chunkStart = rtQueue[busq].nextChunk(); } } // Play elements on queue (insert back in if needed) - - - - - - - - while ((rtQSize > 0) && (chunkStart < bufEndSamp) && (bus != -1)) { #ifdef ALLBUG cout << "Begin iteration==========\n"; cout << "Q-chunkStart: " << chunkStart << endl; cout << "bufEndSamp: " << bufEndSamp << endl; cout << "RTBUFSAMPS: " << RTBUFSAMPS << endl; #endif Iptr = rtQueue[busq].pop(); // get next instrument off queue endsamp = Iptr->getendsamp(); // difference in sample start (countdown) offset = chunkStart - bufStartSamp; if (offset < 0) { // BGG: added this trap for robustness cout << "WARNING: the scheduler is behind the queue!" << endl; offset = 0; } Iptr->set_output_offset(offset); if (endsamp < bufEndSamp) { // compute # of samples to write chunksamps = endsamp-chunkStart; } else { chunksamps = bufEndSamp-chunkStart; } Iptr->setchunk(chunksamps); // set "chunksamps" #ifdef TBUG cout << "Iptr->exec(" << bus_type << "," << bus << ")\n"; #endif Iptr->exec(bus_type, bus); // write the samples * * * * * * * * * #ifdef TBUG cout << "endbus " << endbus << endl; #endif // ReQueue or delete - - - - - - - - - - - - - - - - - - - if (endsamp > bufEndSamp) { #ifdef ALLBUG cout << "inTraverse(): re queueing instrument\n"; #endif rtQueue[busq].push(Iptr,chunkStart+chunksamps); // put back onto queue } else { t_class = checkClass(Iptr->bus_config); switch (t_class) { case TO_AUX: t_count = Iptr->bus_config->auxout_count; endbus = Iptr->bus_config->auxout[t_count-1]; break; case AUX_TO_AUX: t_count = Iptr->bus_config->auxout_count; endbus = Iptr->bus_config->auxout[t_count-1]; break; case TO_AUX_AND_OUT: if (qStatus == TO_OUT) { t_count = Iptr->bus_config->out_count; endbus = Iptr->bus_config->out[t_count-1]; } else endbus = 1000; /* can never equal this */ break; case TO_OUT: t_count = Iptr->bus_config->out_count; endbus = Iptr->bus_config->out[t_count-1]; break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } if ((qStatus == t_class) && (bus == endbus)) { delete Iptr; } } // DJT: not sure this check before new chunkStart is necessary rtQSize = rtQueue[busq].getSize(); if (rtQSize) { chunkStart = rtQueue[busq].nextChunk(); allQSize += rtQSize; } #ifdef TBUG cout << "rtQSize: " << rtQSize << endl; cout << "chunkStart: " << chunkStart << endl; cout << "chunksamps: " << chunksamps << endl; cout << "Iteration done==========\n"; #endif } } // end aux_pb_done ======================================== // Write buf to audio device ------------------------------------------- #ifdef ALLBUG cout << "Writing samples----------\n"; cout << "Q-chunkStart: " << chunkStart << endl; cout << "bufEndSamp: " << bufEndSamp << endl; #endif rtsendsamps(); // zero the buffers clear_aux_buffers(); clear_output_buffers(); // read in an input buffer (if audio input is active) if (audio_on) { // cout << "Reading data from audio port\n"; rtgetsamps(); } gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; usec = (double)tv.tv_usec; baseTime = (sec * 1e6) + usec; elapsed += RTBUFSAMPS; bufStartSamp += RTBUFSAMPS; bufEndSamp += RTBUFSAMPS; if (!rtInteractive) { // Ending condition if ((heapSize == 0) && (allQSize == 0)) { #ifdef TBUG cout << "heapSize: " << heapSize << endl; cout << "rtQSize: " << rtQSize << endl; cout << "PLAYEM = 0\n"; cout << "The end\n\n"; #endif playEm = 0; } } } // end playEm ========================================================= if (rtsetparams_called) { if (play_audio) { // Play zero'd buffers to avoid clicks int count = NCHANS * 4; // DJT: clicks on my box with 2 for (j = 0; j < count; j++) rtsendzeros(0); } close_audio_ports(); rtreportstats(); rtcloseout(); } cout << "\n"; // cout << "EXITING inTraverse() FUNCTION *****\n"; // exit(1); } } /* extern "C" */ <|endoftext|>
<commit_before> #include "../JSUtil.hpp" #include "../EmersonScript.hpp" #include "JSTimerStruct.hpp" #include "../JSObjects/JSFields.hpp" #include <v8.h> #include "../JSLogging.hpp" #include <sirikata/core/network/IOTimer.hpp> #include <sirikata/core/network/Asio.hpp> #include <sirikata/core/service/Context.hpp> #include "JSSuspendable.hpp" #include "Util.hpp" namespace Sirikata { namespace JS { JSTimerStruct::JSTimerStruct(EmersonScript* eobj, Duration dur, v8::Persistent<v8::Function>& callback, JSContextStruct* jscont, uint32 contID, double timeRemaining, bool isSuspended,bool isCleared, JSCtx* jsctx) :JSSuspendable(), emerScript(eobj), cb(callback), jsContStruct(jscont), mCtx(jsctx), mDeadlineTimer(Sirikata::Network::IOTimer::create(*jsctx->getIOService())), timeUntil(dur), mTimeRemaining(timeRemaining), amExecuting(false), killAfterFire(false), noTimerWaiting(true) { if (isCleared) { clear(); return; } if (isSuspended) suspend(); if (contID != jscont->getContextID()) { eobj->registerFixupSuspendable(this,contID); } else { noTimerWaiting=false; if (timeRemaining == 0) { mDeadlineTimer->wait( timeUntil,std::tr1::bind( &JSTimerStruct::evaluateCallback,this,livenessToken())); } else { mDeadlineTimer->wait( Duration::microseconds(timeRemaining*1000000), std::tr1::bind(&JSTimerStruct::evaluateCallback,this,livenessToken())); } if (jscont != NULL) jscont->struct_registerSuspendable(this); } } void JSTimerStruct::setPersistentObject(v8::Persistent<v8::Object>pers) { mPersistentHandle = pers; } void JSTimerStruct::timerWeakReferenceCleanup( v8::Persistent<v8::Value> containsTimer, void* otherArg) { JSTimerLivenessHolder* jstlh = (JSTimerLivenessHolder*) otherArg; if (!jstlh->lt) { delete jstlh; return; } Liveness::Lock locked(jstlh->lt); delete jstlh; if (!locked) return; if (!containsTimer->IsObject()) { JSLOG(error, "Error when cleaning up jstimer. Received a timer to clean up that wasn't an object."); return; } v8::Handle<v8::Object> timer = containsTimer->ToObject(); //check to make sure object has adequate number of fields. CHECK_INTERNAL_FIELD_COUNT(timer,jstimer,TIMER_JSTIMER_TEMPLATE_FIELD_COUNT, ); //should return if have already cleared the timer. String err = "Potential error when cleaning up jstimer. Could not decode timer struct. Likely the timer struct was already cleared, but could be more serious."; JSTimerStruct* jstimer = JSTimerStruct::decodeTimerStruct(timer,err); if (jstimer == NULL) { JSLOG(insane,err); return; } //asks the particular timer to free itself if it's never going to fire //again, or schedule itself to be freed after will never fire again. jstimer->mCtx->objStrand->post( std::tr1::bind(&JSTimerStruct::noReference, jstimer, jstimer->livenessToken()), "JSTimerStruct::noReference" ); } /** Called by timerWeakReferenceCleanup and after firing timer when killAfterFire is true. Means that no Emerson objects hold references to this timer any longer and that this object should either: 1) Free itself if there's no way that its timer will re-fire. 2) Schedule itself to be freed after its timer fires. For case 1: the timer has already fired, and (the timer isn't suspended and its context isn't suspended). For case 2: just sets killAfterFire to be true. Will re-evaluate these conditions after timer actually fires. */ void JSTimerStruct::noReference(const Liveness::Token& alive) { v8::Locker locker (mCtx->mIsolate); v8::Isolate::Scope iscope(mCtx->mIsolate); if (alive) { killAfterFire = true; if (noTimerWaiting) { //check if it's suspended and its context is suspended if (!(getIsSuspended() && jsContStruct->getIsSuspended())) { //can kill clear(); } } } } void JSTimerStruct::fixSuspendableToContext(JSContextStruct* toAttachTo) { jsContStruct = toAttachTo; noTimerWaiting=false; if (mTimeRemaining == 0) { mDeadlineTimer->wait( timeUntil,std::tr1::bind( &JSTimerStruct::evaluateCallback,this,livenessToken())); } else { mDeadlineTimer->wait( Duration::microseconds(mTimeRemaining*1000000), std::tr1::bind(&JSTimerStruct::evaluateCallback,this,livenessToken())); } jsContStruct->struct_registerSuspendable(this); } JSTimerStruct* JSTimerStruct::decodeTimerStruct(v8::Handle<v8::Value> toDecode,String& errorMessage) { v8::HandleScope handle_scope; //for garbage collection. if (! toDecode->IsObject()) { errorMessage += "Error in decode of timer object in JSTimerStruct.cpp. Should have received an object to decode."; return NULL; } v8::Handle<v8::Object> toDecodeObject = toDecode->ToObject(); //now check internal field count if (toDecodeObject->InternalFieldCount() != TIMER_JSTIMER_TEMPLATE_FIELD_COUNT) { errorMessage += "Error in decode of timer object in JSTimerStruct. Object given does not have adequate number of internal fields for decode."; return NULL; } //now actually try to decode each. //decode the jsTimerStruct field v8::Local<v8::External> wrapJSTimerStruct; wrapJSTimerStruct = v8::Local<v8::External>::Cast(toDecodeObject->GetInternalField(TIMER_JSTIMERSTRUCT_FIELD)); void* ptr = wrapJSTimerStruct->Value(); JSTimerStruct* returner; returner = static_cast<JSTimerStruct*>(ptr); if (returner == NULL) errorMessage += "Error in decode of timer object in JSTimerStruct.cpp. Internal field of object given cannot be casted to a JSTimerStruct."; return returner; } JSTimerStruct::~JSTimerStruct() { letDie(); clear(); } //returning all data necessary to re-generate timer // uint32 contextId // double period // double timeUntil timer expires // bool isSuspended // bool isCleared // func cb v8::Handle<v8::Value> JSTimerStruct::struct_getAllData() { v8::HandleScope handle_scope; uint32 contId = jsContStruct->getContextID(); bool issusp = getIsSuspended(); bool isclear = getIsCleared(); double period = -1; double tUntil = -1; v8::Handle<v8::Function> cbFunc; if (! isclear) { cbFunc = cb; period = timeUntil.toSeconds(); if (issusp) tUntil = timeUntil.toSeconds(); else { Duration pt = mDeadlineTimer->expiresFromNow(); tUntil = pt.seconds(); } } v8::Handle<v8::Object> returner = v8::Object::New(); if (isclear) { returner->Set(v8::String::New("isCleared"),v8::Boolean::New(isclear)); returner->Set(v8::String::New("contextId"), v8::Integer::NewFromUnsigned(contId)); return handle_scope.Close(returner); } returner->Set(v8::String::New("period"), v8::Number::New(period)); returner->Set(v8::String::New("callback"),cbFunc); returner->Set(v8::String::New("timeRemaining"),v8::Number::New(tUntil)); returner->Set(v8::String::New("isSuspended"),v8::Boolean::New(issusp)); return handle_scope.Close(returner); } void JSTimerStruct::evaluateCallback(Liveness::Token isAlive) { if (!isAlive) return; Liveness::Lock locked(isAlive); if (!locked) return; if (mCtx->stopped()) return; mCtx->objStrand->post( std::tr1::bind(&JSTimerStruct::iEvaluateCallback,this, isAlive), "JSTimerStruct::iEvaluateCallback" ); } void JSTimerStruct::iEvaluateCallback(Liveness::Token token) { //lkjs; FIXME: Can weak reference clean up a timer //while it's in this function? (If we try to use lock, we run //into a problem when the timer tries to clear itself.) if (!token) return; if (mCtx->stopped()) { JSLOG(warn, "Timer evaluateCallback invoked after stop request, ignoring..."); noTimerWaiting=true; // Allow cleanup, see notes below return; } while(!mCtx->initialized()) {} amExecuting = true; emerScript->invokeCallbackInContext(emerScript->livenessToken(), cb, jsContStruct); //if we were told to kill the timer after firing, then check kill conditions //again in noReference. if (killAfterFire) { mCtx->objStrand->post( std::tr1::bind(&JSTimerStruct::noReference,this, livenessToken()), "JSTimerStruct::noReference" ); } //means that we have no pending timer operation. // Note that since this allows the JS GC thread to destroy this object // in response to all references to it being lost, // we need to make sure it is absolutely the *last* operation we do on // member variables. noTimerWaiting=true; amExecuting = false; } v8::Handle<v8::Value> JSTimerStruct::suspend() { if (getIsCleared()) { JSLOG(info, "Error in suspend of JSTimerStruct.cpp. Called suspend even though the timer had previously been cleared."); return v8::ThrowException( v8::Exception::Error(v8::String::New("Error. Called suspend on a timer that had already been cleared."))); } JSLOG(insane,"suspending timer"); //note, it is important that call to JSSuspendable::supsend occurs before //actually cancelling the deadline timer so that we're performing correct //checks for timer cleanup. v8::HandleScope handle_scope; v8::Handle<v8::Value>returner = JSSuspendable::suspend(); mDeadlineTimer->cancel(); // Note that since this allows the JS GC thread to destroy this object // in response to all references to it being lost, // we need to make sure it is absolutely the *last* operation we do on // member variables. noTimerWaiting = true; return handle_scope.Close(returner); } //has more of a reset-type functionality than resume //if the time has not been cleared, then, cancel the current timer, //and start a new countdown to execute the callback. v8::Handle<v8::Value> JSTimerStruct::resume() { if (getIsCleared()) { JSLOG(info,"Error in JSTimerStruct. Trying to resume a timer object that has already been cleared. Taking no action"); return JSSuspendable::getIsSuspendedV8(); } mDeadlineTimer->cancel(); noTimerWaiting=false; mDeadlineTimer->wait( timeUntil,std::tr1::bind( &JSTimerStruct::evaluateCallback,this,livenessToken())); return JSSuspendable::resume(); } v8::Handle<v8::Value> JSTimerStruct::clear() { if (getIsCleared()) { JSLOG(insane,"In JSTimerStruct, calling clear on a timer that has already been cleared."); return JSSuspendable::clear(); } v8::HandleScope handle_scope; JSSuspendable::clear(); mDeadlineTimer->cancel(); if (! cb.IsEmpty()) cb.Dispose(); if (! mPersistentHandle.IsEmpty()) { //check to make sure object has adequate number of fields. CHECK_INTERNAL_FIELD_COUNT(mPersistentHandle,jstimer,TIMER_JSTIMER_TEMPLATE_FIELD_COUNT, v8::Boolean::New(true)); //delete typeId, and return if have incorrect params for type id DEL_TYPEID_AND_CHECK(mPersistentHandle,jstimer,TIMER_TYPEID_STRING,v8::Boolean::New(true)); mPersistentHandle->SetInternalField(TIMER_JSTIMERSTRUCT_FIELD, External::New(NULL)); } // Be careful after this! JSContextStruct::struct_deregisterSuspendable will // delete this object so you shouldn't use any member variables after // invoking it. if (jsContStruct != NULL) { //cannot clear if amExecuting. if (amExecuting) { mCtx->objStrand->post( std::tr1::bind(&JSContextStruct::struct_asyncDeregisterSuspendable,jsContStruct,this, jsContStruct->livenessToken(),livenessToken()), "JSContextStruct::struct_asyncDeregisterSuspendable" ); } else jsContStruct->struct_deregisterSuspendable(this); } // Note that since this allows the JS GC thread to destroy this object // in response to all references to it being lost, // we need to make sure it is absolutely the *last* operation we do on // member variables. // In this case, the above call will have deleted this JSTimerStruct, so we // don't even set it at all. It would have been unsafe to set it earlier // because we could have ended up with two threads trying to do the deletion. //noTimerWaiting = true; return v8::Boolean::New(true); } v8::Handle<v8::Value> JSTimerStruct::struct_resetTimer(double timeInSecondsToRefire) { if (getIsCleared()) { JSLOG(info,"Error in JSTimerStruct. Calling reset on a timer that has already been cleared."); return JSSuspendable::clear(); } mDeadlineTimer->cancel(); noTimerWaiting=false; mDeadlineTimer->wait( Duration::seconds(timeInSecondsToRefire), std::tr1::bind(&JSTimerStruct::evaluateCallback,this, livenessToken())); return JSSuspendable::resume(); } } //end namespace js } //end namespace sirikata <commit_msg>Fix liveness check in JSTimerStruct.<commit_after> #include "../JSUtil.hpp" #include "../EmersonScript.hpp" #include "JSTimerStruct.hpp" #include "../JSObjects/JSFields.hpp" #include <v8.h> #include "../JSLogging.hpp" #include <sirikata/core/network/IOTimer.hpp> #include <sirikata/core/network/Asio.hpp> #include <sirikata/core/service/Context.hpp> #include "JSSuspendable.hpp" #include "Util.hpp" namespace Sirikata { namespace JS { JSTimerStruct::JSTimerStruct(EmersonScript* eobj, Duration dur, v8::Persistent<v8::Function>& callback, JSContextStruct* jscont, uint32 contID, double timeRemaining, bool isSuspended,bool isCleared, JSCtx* jsctx) :JSSuspendable(), emerScript(eobj), cb(callback), jsContStruct(jscont), mCtx(jsctx), mDeadlineTimer(Sirikata::Network::IOTimer::create(*jsctx->getIOService())), timeUntil(dur), mTimeRemaining(timeRemaining), amExecuting(false), killAfterFire(false), noTimerWaiting(true) { if (isCleared) { clear(); return; } if (isSuspended) suspend(); if (contID != jscont->getContextID()) { eobj->registerFixupSuspendable(this,contID); } else { noTimerWaiting=false; if (timeRemaining == 0) { mDeadlineTimer->wait( timeUntil,std::tr1::bind( &JSTimerStruct::evaluateCallback,this,livenessToken())); } else { mDeadlineTimer->wait( Duration::microseconds(timeRemaining*1000000), std::tr1::bind(&JSTimerStruct::evaluateCallback,this,livenessToken())); } if (jscont != NULL) jscont->struct_registerSuspendable(this); } } void JSTimerStruct::setPersistentObject(v8::Persistent<v8::Object>pers) { mPersistentHandle = pers; } void JSTimerStruct::timerWeakReferenceCleanup( v8::Persistent<v8::Value> containsTimer, void* otherArg) { JSTimerLivenessHolder* jstlh = (JSTimerLivenessHolder*) otherArg; if (!jstlh->lt) { delete jstlh; return; } Liveness::Lock locked(jstlh->lt); delete jstlh; if (!locked) return; if (!containsTimer->IsObject()) { JSLOG(error, "Error when cleaning up jstimer. Received a timer to clean up that wasn't an object."); return; } v8::Handle<v8::Object> timer = containsTimer->ToObject(); //check to make sure object has adequate number of fields. CHECK_INTERNAL_FIELD_COUNT(timer,jstimer,TIMER_JSTIMER_TEMPLATE_FIELD_COUNT, ); //should return if have already cleared the timer. String err = "Potential error when cleaning up jstimer. Could not decode timer struct. Likely the timer struct was already cleared, but could be more serious."; JSTimerStruct* jstimer = JSTimerStruct::decodeTimerStruct(timer,err); if (jstimer == NULL) { JSLOG(insane,err); return; } //asks the particular timer to free itself if it's never going to fire //again, or schedule itself to be freed after will never fire again. jstimer->mCtx->objStrand->post( std::tr1::bind(&JSTimerStruct::noReference, jstimer, jstimer->livenessToken()), "JSTimerStruct::noReference" ); } /** Called by timerWeakReferenceCleanup and after firing timer when killAfterFire is true. Means that no Emerson objects hold references to this timer any longer and that this object should either: 1) Free itself if there's no way that its timer will re-fire. 2) Schedule itself to be freed after its timer fires. For case 1: the timer has already fired, and (the timer isn't suspended and its context isn't suspended). For case 2: just sets killAfterFire to be true. Will re-evaluate these conditions after timer actually fires. */ void JSTimerStruct::noReference(const Liveness::Token& alive) { if (!alive) return; Liveness::Lock locked(alive); if (!locked) return; v8::Locker locker (mCtx->mIsolate); v8::Isolate::Scope iscope(mCtx->mIsolate); killAfterFire = true; if (noTimerWaiting) { //check if it's suspended and its context is suspended if (!(getIsSuspended() && jsContStruct->getIsSuspended())) { //can kill clear(); } } } void JSTimerStruct::fixSuspendableToContext(JSContextStruct* toAttachTo) { jsContStruct = toAttachTo; noTimerWaiting=false; if (mTimeRemaining == 0) { mDeadlineTimer->wait( timeUntil,std::tr1::bind( &JSTimerStruct::evaluateCallback,this,livenessToken())); } else { mDeadlineTimer->wait( Duration::microseconds(mTimeRemaining*1000000), std::tr1::bind(&JSTimerStruct::evaluateCallback,this,livenessToken())); } jsContStruct->struct_registerSuspendable(this); } JSTimerStruct* JSTimerStruct::decodeTimerStruct(v8::Handle<v8::Value> toDecode,String& errorMessage) { v8::HandleScope handle_scope; //for garbage collection. if (! toDecode->IsObject()) { errorMessage += "Error in decode of timer object in JSTimerStruct.cpp. Should have received an object to decode."; return NULL; } v8::Handle<v8::Object> toDecodeObject = toDecode->ToObject(); //now check internal field count if (toDecodeObject->InternalFieldCount() != TIMER_JSTIMER_TEMPLATE_FIELD_COUNT) { errorMessage += "Error in decode of timer object in JSTimerStruct. Object given does not have adequate number of internal fields for decode."; return NULL; } //now actually try to decode each. //decode the jsTimerStruct field v8::Local<v8::External> wrapJSTimerStruct; wrapJSTimerStruct = v8::Local<v8::External>::Cast(toDecodeObject->GetInternalField(TIMER_JSTIMERSTRUCT_FIELD)); void* ptr = wrapJSTimerStruct->Value(); JSTimerStruct* returner; returner = static_cast<JSTimerStruct*>(ptr); if (returner == NULL) errorMessage += "Error in decode of timer object in JSTimerStruct.cpp. Internal field of object given cannot be casted to a JSTimerStruct."; return returner; } JSTimerStruct::~JSTimerStruct() { letDie(); clear(); } //returning all data necessary to re-generate timer // uint32 contextId // double period // double timeUntil timer expires // bool isSuspended // bool isCleared // func cb v8::Handle<v8::Value> JSTimerStruct::struct_getAllData() { v8::HandleScope handle_scope; uint32 contId = jsContStruct->getContextID(); bool issusp = getIsSuspended(); bool isclear = getIsCleared(); double period = -1; double tUntil = -1; v8::Handle<v8::Function> cbFunc; if (! isclear) { cbFunc = cb; period = timeUntil.toSeconds(); if (issusp) tUntil = timeUntil.toSeconds(); else { Duration pt = mDeadlineTimer->expiresFromNow(); tUntil = pt.seconds(); } } v8::Handle<v8::Object> returner = v8::Object::New(); if (isclear) { returner->Set(v8::String::New("isCleared"),v8::Boolean::New(isclear)); returner->Set(v8::String::New("contextId"), v8::Integer::NewFromUnsigned(contId)); return handle_scope.Close(returner); } returner->Set(v8::String::New("period"), v8::Number::New(period)); returner->Set(v8::String::New("callback"),cbFunc); returner->Set(v8::String::New("timeRemaining"),v8::Number::New(tUntil)); returner->Set(v8::String::New("isSuspended"),v8::Boolean::New(issusp)); return handle_scope.Close(returner); } void JSTimerStruct::evaluateCallback(Liveness::Token isAlive) { if (!isAlive) return; Liveness::Lock locked(isAlive); if (!locked) return; if (mCtx->stopped()) return; mCtx->objStrand->post( std::tr1::bind(&JSTimerStruct::iEvaluateCallback,this, isAlive), "JSTimerStruct::iEvaluateCallback" ); } void JSTimerStruct::iEvaluateCallback(Liveness::Token token) { //lkjs; FIXME: Can weak reference clean up a timer //while it's in this function? (If we try to use lock, we run //into a problem when the timer tries to clear itself.) if (!token) return; if (mCtx->stopped()) { JSLOG(warn, "Timer evaluateCallback invoked after stop request, ignoring..."); noTimerWaiting=true; // Allow cleanup, see notes below return; } while(!mCtx->initialized()) {} amExecuting = true; emerScript->invokeCallbackInContext(emerScript->livenessToken(), cb, jsContStruct); //if we were told to kill the timer after firing, then check kill conditions //again in noReference. if (killAfterFire) { mCtx->objStrand->post( std::tr1::bind(&JSTimerStruct::noReference,this, livenessToken()), "JSTimerStruct::noReference" ); } //means that we have no pending timer operation. // Note that since this allows the JS GC thread to destroy this object // in response to all references to it being lost, // we need to make sure it is absolutely the *last* operation we do on // member variables. noTimerWaiting=true; amExecuting = false; } v8::Handle<v8::Value> JSTimerStruct::suspend() { if (getIsCleared()) { JSLOG(info, "Error in suspend of JSTimerStruct.cpp. Called suspend even though the timer had previously been cleared."); return v8::ThrowException( v8::Exception::Error(v8::String::New("Error. Called suspend on a timer that had already been cleared."))); } JSLOG(insane,"suspending timer"); //note, it is important that call to JSSuspendable::supsend occurs before //actually cancelling the deadline timer so that we're performing correct //checks for timer cleanup. v8::HandleScope handle_scope; v8::Handle<v8::Value>returner = JSSuspendable::suspend(); mDeadlineTimer->cancel(); // Note that since this allows the JS GC thread to destroy this object // in response to all references to it being lost, // we need to make sure it is absolutely the *last* operation we do on // member variables. noTimerWaiting = true; return handle_scope.Close(returner); } //has more of a reset-type functionality than resume //if the time has not been cleared, then, cancel the current timer, //and start a new countdown to execute the callback. v8::Handle<v8::Value> JSTimerStruct::resume() { if (getIsCleared()) { JSLOG(info,"Error in JSTimerStruct. Trying to resume a timer object that has already been cleared. Taking no action"); return JSSuspendable::getIsSuspendedV8(); } mDeadlineTimer->cancel(); noTimerWaiting=false; mDeadlineTimer->wait( timeUntil,std::tr1::bind( &JSTimerStruct::evaluateCallback,this,livenessToken())); return JSSuspendable::resume(); } v8::Handle<v8::Value> JSTimerStruct::clear() { if (getIsCleared()) { JSLOG(insane,"In JSTimerStruct, calling clear on a timer that has already been cleared."); return JSSuspendable::clear(); } v8::HandleScope handle_scope; JSSuspendable::clear(); mDeadlineTimer->cancel(); if (! cb.IsEmpty()) cb.Dispose(); if (! mPersistentHandle.IsEmpty()) { //check to make sure object has adequate number of fields. CHECK_INTERNAL_FIELD_COUNT(mPersistentHandle,jstimer,TIMER_JSTIMER_TEMPLATE_FIELD_COUNT, v8::Boolean::New(true)); //delete typeId, and return if have incorrect params for type id DEL_TYPEID_AND_CHECK(mPersistentHandle,jstimer,TIMER_TYPEID_STRING,v8::Boolean::New(true)); mPersistentHandle->SetInternalField(TIMER_JSTIMERSTRUCT_FIELD, External::New(NULL)); } // Be careful after this! JSContextStruct::struct_deregisterSuspendable will // delete this object so you shouldn't use any member variables after // invoking it. if (jsContStruct != NULL) { //cannot clear if amExecuting. if (amExecuting) { mCtx->objStrand->post( std::tr1::bind(&JSContextStruct::struct_asyncDeregisterSuspendable,jsContStruct,this, jsContStruct->livenessToken(),livenessToken()), "JSContextStruct::struct_asyncDeregisterSuspendable" ); } else jsContStruct->struct_deregisterSuspendable(this); } // Note that since this allows the JS GC thread to destroy this object // in response to all references to it being lost, // we need to make sure it is absolutely the *last* operation we do on // member variables. // In this case, the above call will have deleted this JSTimerStruct, so we // don't even set it at all. It would have been unsafe to set it earlier // because we could have ended up with two threads trying to do the deletion. //noTimerWaiting = true; return v8::Boolean::New(true); } v8::Handle<v8::Value> JSTimerStruct::struct_resetTimer(double timeInSecondsToRefire) { if (getIsCleared()) { JSLOG(info,"Error in JSTimerStruct. Calling reset on a timer that has already been cleared."); return JSSuspendable::clear(); } mDeadlineTimer->cancel(); noTimerWaiting=false; mDeadlineTimer->wait( Duration::seconds(timeInSecondsToRefire), std::tr1::bind(&JSTimerStruct::evaluateCallback,this, livenessToken())); return JSSuspendable::resume(); } } //end namespace js } //end namespace sirikata <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Stanford University * * Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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 <stdint.h> #include <stdio.h> #include <unistd.h> #include <sys/param.h> #include <sys/types.h> #include <sys/stat.h> #include <getopt.h> #include <string> #include <iostream> #include <oriutil/debug.h> #include <oriutil/orifile.h> #include <ori/repostore.h> using namespace std; void usage_list() { cout << "ori list" << endl; cout << endl; cout << "List all local file systems." << endl; } /* * List local file systems. */ int cmd_list(int argc, char * const argv[]) { set<string> repos = RepoStore_GetRepos(); set<string>::iterator it; for (it = repos.begin(); it != repos.end(); it++) { cout << *it << endl; } return 0; } <commit_msg>Show FSID on list operation.<commit_after>/* * Copyright (c) 2013 Stanford University * * Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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 <stdint.h> #include <stdio.h> #include <unistd.h> #include <sys/param.h> #include <sys/types.h> #include <sys/stat.h> #include <getopt.h> #include <string> #include <iostream> #include <iomanip> #include <oriutil/debug.h> #include <oriutil/orifile.h> #include <ori/repostore.h> #include <ori/localrepo.h> using namespace std; void usage_list() { cout << "ori list" << endl; cout << endl; cout << "List all local file systems." << endl; } /* * List local file systems. */ int cmd_list(int argc, char * const argv[]) { set<string> repos = RepoStore_GetRepos(); set<string>::iterator it; cout << left << setw(32) << "Name" << "File System ID" << endl; for (it = repos.begin(); it != repos.end(); it++) { string path, id; path = RepoStore_GetRepoPath(*it) + ORI_PATH_UUID; id = OriFile_ReadFile(path); cout << left << setw(32) << *it << id << endl; } return 0; } <|endoftext|>
<commit_before>/** * \file Encryption.cc * \author Rik Honcoop * \copyright Copyright (c) 2017, The R2D2 Team * \license See LICENSE */ #include "Encryption.hh" Encryption::Encryption(){ encryptKey = 1; } Encryption::Encryption(int encryptionKey){ encryptKey = encryptionKey; } string Encryption::Decrypt(string input, int keyCode){ string restr = input; for(unsigned int i =0; i <= input.length() -1; i ++){ restr[i] = restr[i]-keyCode ; } return restr; } string Encryption::Decrypt(string input){ string restr = input; for(unsigned int i =0; i <= input.length() -1; i ++){ restr[i] = restr[i]-encryptKey ; } return restr; } string Encryption::Encrypt(string input, int keyCode){ string restr = input; for(unsigned int i =0; i <= input.length() -1; i ++){ restr[i] = restr[i]+keyCode ; } return restr; } string Encryption::Encrypt(string input){ string restr = input; for(unsigned int i =0; i <= input.length() -1; i ++){ restr[i] = restr[i]+encryptKey ; } return restr; } void Encryption::setEncryptionKey(int encryptionKey){ encryptKey = encryptionKey; } <commit_msg>[RFID-01] Merge branch 'feat-rfid' of https://github.com/R2D2-2017/R2D2-2017 into feat-rfid<commit_after>/** * \file Encryption.cc * \author Rik Honcoop * \copyright Copyright (c) 2017, The R2D2 Team * \license See LICENSE */ #include "encryption.hh" Encryption::Encryption(){ encryptKey = 1; } Encryption::Encryption(int encryptionKey){ encryptKey = encryptionKey; } string Encryption::Decrypt(string input, int keyCode){ string restr = input; for(unsigned int i =0; i <= input.length() -1; i ++){ restr[i] = restr[i]-keyCode ; } return restr; } string Encryption::Decrypt(string input){ string restr = input; for(unsigned int i =0; i <= input.length() -1; i ++){ restr[i] = restr[i]-encryptKey ; } return restr; } string Encryption::Encrypt(string input, int keyCode){ string restr = input; for(unsigned int i =0; i <= input.length() -1; i ++){ restr[i] = restr[i]+keyCode ; } return restr; } string Encryption::Encrypt(string input){ string restr = input; for(unsigned int i =0; i <= input.length() -1; i ++){ restr[i] = restr[i]+encryptKey ; } return restr; } void Encryption::setEncryptionKey(int encryptionKey){ encryptKey = encryptionKey; } <|endoftext|>
<commit_before>#include <ctime> #include <iostream> #include <opencv2/highgui/highgui.hpp> #include "camera.hpp" #include <vector> //static const int WIDTH = 640; //static const int HEIGHT = 480; static const int FPS = 6; static const int DEVICE = 0; static const std::string DIRECTORY_PATH = "/home/pi/Pictures/";//pathの先頭 static const std::string FILE_EXTENTION = ".jpg";//拡張子 static const int AOV = 62.2;//ANGLE OF VIEW //明度について static const int MAX_VALUE = 255;//明るさ最大 static const int NO_VALUE = 0;//明るさ最小 static const double MIN_AREA = 10;//抽出する面積の最小値 Camera::Camera() { if(!capture.open(DEVICE)) { std::cout<<"capture is not opened 1"<<std::endl; } if (!capture.isOpened()) { std::cout<<"capture is not opened 2"<<std::endl; } //capture.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH); //capture.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT); capture.set(CV_CAP_PROP_FPS,FPS); //以下 対応してない //capture.set(CV_CAP_PROP_BUFFERSIZE, 1); } Camera::~Camera() { capture.release(); } int Camera::takePhoto() { makeTimePath(); cv::Mat frame; for (int i = 0; i < 5; i++) { capture.grab(); } do { capture>>frame; } while(frame.empty()); input = frame; imwrite(timePath+FILE_EXTENTION,input); return 0; } //時間を元にtimePathを作る int Camera::makeTimePath(void) { time_t timer;//時刻を受け取る変数 struct tm *timeptr;//日時を集めた構造体ポインタ char buffer[80]; time(&timer);//現在時刻の取得 timeptr = localtime(&timer);//ポインタ strftime(buffer, sizeof(buffer), "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してsに代入 std::string str(buffer); timePath = DIRECTORY_PATH+str; return 0; } //ノイズ除去,引数aは抽出する輪郭の面積の最小値 cv::Mat Camera::rmNoise(cv::Mat src) { std::vector<std::vector<cv::Point> > contours;//輪郭座標の二次元配列 cv::findContours(src,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);//CV_RETR_EXTERNAL:最も外側の輪郭を検出、CV_CHAIN_APPROX_NONE:近似手法 std::vector<std::vector<cv::Point> > contours_subset; for (int i = 0;i<contours.size();i++) { double area = cv::contourArea(contours.at(i));//各輪郭の面積 if (area>MIN_AREA) { contours_subset.push_back(contours.at(i));//contours_subsetに一定面積以上の輪郭を追加 } } cv::Mat mask = cv::Mat::zeros(src.rows, src.cols, CV_8UC1); cv::drawContours(mask, contours_subset, -1, cv::Scalar(255), -1);//maskに一定面積以上の輪郭をdraw return mask; } int Camera::binarize() { cv::Mat hsv; cv::Mat hsv_filtered15;//画像の初期化 cv::Mat hsv_filtered180;//画像の初期化 cv::cvtColor(input,hsv,CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換 //inRange(入力画像,下界画像,上界画像,出力画像) //「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value) cv::inRange(hsv,cv::Scalar(0,100,160),cv::Scalar(3,255,MAX_VALUE),hsv_filtered15); cv::inRange(hsv,cv::Scalar(175,100,160),cv::Scalar(180,255,MAX_VALUE),hsv_filtered180); cv::add(hsv_filtered15,hsv_filtered180,hsv); output = rmNoise(hsv); imwrite(timePath+"BINARY"+FILE_EXTENTION,output); return 0; } //二値化した画像から1の面積を抽出 double Camera::countArea() { double Area = output.rows*output.cols;//全ピクセル数 double redCount = 0; //赤色を認識したピクセルの数 redCount = cv::countNonZero(output);//赤色部分の面積を計算 double percentage = 0; //割合 percentage = (redCount / Area)*100;//割合を計算 std::cout<<"面積のPercentageは"<<percentage<<std::endl; return percentage; } //二値化画像のcenterを角度で返す double Camera::getCenter() { cv::Moments mu = cv::moments(output, false);//重心の計算結果をmuに代入 double mc = mu.m10 / mu.m00;//重心のx座標 double center = (mc - output.cols / 2) * AOV / output.cols;//正規化 std::cout<<"重心の位置は"<<center<<std::endl; return center; } <commit_msg>debug<commit_after>#include <ctime> #include <iostream> #include <opencv2/highgui/highgui.hpp> #include "camera.hpp" #include <vector> //static const int WIDTH = 640; //static const int HEIGHT = 480; static const int FPS = 6; static const int DEVICE = 0; static const std::string DIRECTORY_PATH = "/home/pi/Pictures/";//pathの先頭 static const std::string FILE_EXTENTION = ".jpg";//拡張子 static const int AOV = 62.2;//ANGLE OF VIEW //明度について static const int MAX_VALUE = 255;//明るさ最大 static const int NO_VALUE = 0;//明るさ最小 static const double MIN_AREA = 10;//抽出する面積の最小値 Camera::Camera() { if(!capture.open(DEVICE)) { std::cout<<"capture is not opened 1"<<std::endl; } if (!capture.isOpened()) { std::cout<<"capture is not opened 2"<<std::endl; } //capture.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH); //capture.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT); capture.set(CV_CAP_PROP_FPS,FPS); //以下 対応してない //capture.set(CV_CAP_PROP_BUFFERSIZE, 1); } Camera::~Camera() { capture.release(); } int Camera::takePhoto() { makeTimePath(); cv::Mat frame; for (int i = 0; i < 5; i++) { capture.grab(); } do { capture>>frame; } while(frame.empty()); input = frame; imwrite(timePath+FILE_EXTENTION,input); return 0; } //時間を元にtimePathを作る int Camera::makeTimePath(void) { time_t timer;//時刻を受け取る変数 struct tm *timeptr;//日時を集めた構造体ポインタ char buffer[80]; time(&timer);//現在時刻の取得 timeptr = localtime(&timer);//ポインタ strftime(buffer, sizeof(buffer), "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してsに代入 std::string str(buffer); timePath = DIRECTORY_PATH+str; return 0; } //ノイズ除去,引数aは抽出する輪郭の面積の最小値 cv::Mat Camera::rmNoise(cv::Mat src) { std::vector<std::vector<cv::Point> > contours;//輪郭座標の二次元配列 cv::findContours(src,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);//CV_RETR_EXTERNAL:最も外側の輪郭を検出、CV_CHAIN_APPROX_NONE:近似手法 std::vector<std::vector<cv::Point> > contours_subset; for (int i = 0;i<contours.size();i++) { double area = cv::contourArea(contours.at(i));//各輪郭の面積 if (area>MIN_AREA) { contours_subset.push_back(contours.at(i));//contours_subsetに一定面積以上の輪郭を追加 } } cv::Mat mask = cv::Mat::zeros(src.rows, src.cols, CV_8UC1); cv::drawContours(mask, contours_subset, -1, cv::Scalar(255), -1);//maskに一定面積以上の輪郭をdraw return mask; } int Camera::binarize() { cv::Mat hsv; cv::Mat hsv_filtered15;//画像の初期化 cv::Mat hsv_filtered180;//画像の初期化 cv::cvtColor(input,hsv,CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換 //inRange(入力画像,下界画像,上界画像,出力画像) //「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value) cv::inRange(hsv,cv::Scalar(0,160,60),cv::Scalar(3,255,MAX_VALUE),hsv_filtered15); cv::inRange(hsv,cv::Scalar(175,160,60),cv::Scalar(180,255,MAX_VALUE),hsv_filtered180); cv::add(hsv_filtered15,hsv_filtered180,hsv); output = rmNoise(hsv); imwrite(timePath+"BINARY"+FILE_EXTENTION,output); return 0; } //二値化した画像から1の面積を抽出 double Camera::countArea() { double Area = output.rows*output.cols;//全ピクセル数 double redCount = 0; //赤色を認識したピクセルの数 redCount = cv::countNonZero(output);//赤色部分の面積を計算 double percentage = 0; //割合 percentage = (redCount / Area)*100;//割合を計算 std::cout<<"面積のPercentageは"<<percentage<<std::endl; return percentage; } //二値化画像のcenterを角度で返す double Camera::getCenter() { cv::Moments mu = cv::moments(output, false);//重心の計算結果をmuに代入 double mc = mu.m10 / mu.m00;//重心のx座標 double center = (mc - output.cols / 2) * AOV / output.cols;//正規化 std::cout<<"重心の位置は"<<center<<std::endl; return center; } <|endoftext|>
<commit_before>#include "General_Utilities.hpp" #include <cmath> #include <iostream> #include <fstream> #include <chrono> #include <cstdlib> #include <libconfig.h++> #include "Physical_Parameters.hpp" using namespace libconfig; //Config file string FormFactor="None"; string SimID="default"; string experiment="default"; string version="v1.0"; double mChi=0,sigma=0; double rhoDM=0.0; int SampleSize=0; int SimDate [3] = {0,0,0}; int SimTime [3] = {0,0,0}; double nJ2000 = 0.0; Eigen::Vector3d vEarth(0,0,0); double vcut=0.0; void Read_Config_File(char *inputfile) { Config cfg; std::string id(inputfile); std::string path = "../data/"+id+".cfg"; const char *cstr = path.c_str(); // Read the file. If there is an error, report it and exit. try { cfg.readFile(cstr); } catch(const FileIOException &fioex) { std::cerr << "I/O error while reading configuration file." << std::endl; exit(EXIT_FAILURE); } catch(const ParseException &pex) { std::cerr << "Configurate file parse error at " << pex.getFile() << ":" << pex.getLine() << " - " << pex.getError() << std::endl; exit(EXIT_FAILURE); } //Simulation ID try { SimID = cfg.lookup("simID").c_str(); } catch(const SettingNotFoundException &nfex) { cerr << "No 'simID' setting in configuration file." << endl; exit(EXIT_FAILURE); } //Experiment try { experiment = cfg.lookup("experiment").c_str(); } catch(const SettingNotFoundException &nfex) { cerr << "No 'simID' setting in configuration file." << endl; exit(EXIT_FAILURE); } //sample size try { SampleSize = cfg.lookup("samplesize"); } catch(const SettingNotFoundException &nfex) { cerr << "No 'samplesize' setting in configuration file." << endl; exit(EXIT_FAILURE); } //Mass try { mChi = cfg.lookup("mass"); mChi*=MeV; } catch(const SettingNotFoundException &nfex) { cerr << "No 'mass' setting in configuration file." << endl; exit(EXIT_FAILURE); } //Cross section try { sigma = cfg.lookup("sigma"); sigma*=pb; } catch(const SettingNotFoundException &nfex) { cerr << "Error: While reading 'sigma' setting in configuration file. Computation cancelled." << endl; exit(EXIT_FAILURE); } //DM energy density try { rhoDM = cfg.lookup("rho"); rhoDM*=GeV/cm/cm/cm; } catch(const SettingNotFoundException &nfex) { cerr << "Error: While reading 'rho' setting in configuration file. Computation cancelled." << endl; exit(EXIT_FAILURE); } //Date try { SimDate[0] = cfg.lookup("date")[0]; SimDate[1] = cfg.lookup("date")[1]; SimDate[2] = cfg.lookup("date")[2]; } catch(const SettingNotFoundException &nfex) { cerr << "Error: While reading 'date' setting in configuration file. Computation cancelled." << endl; exit(EXIT_FAILURE); } //Time try { SimTime[0] = cfg.lookup("time")[0]; SimTime[1] = cfg.lookup("time")[1]; SimTime[2] = cfg.lookup("time")[2]; } catch(const SettingNotFoundException &nfex) { cerr << "Error: While reading 'time' setting in configuration file. Computation cancelled." << endl; exit(EXIT_FAILURE); } //Time and Detector nJ2000= FractionalDays(SimDate,SimTime); //Earth Velocity vEarth=EarthVelocity(nJ2000); } void LogAnalysis(double duration,int worldsize) { ofstream f; f.open("../results/"+SimID+".log",std::ofstream::app); std::chrono::time_point<std::chrono::system_clock> end; end = std::chrono::system_clock::now(); std::time_t end_time = std::chrono::system_clock::to_time_t(end); f <<"\n////////////////////////////////////////////////////\n\n" <<"//Data analysis performed:\t" <<std::ctime(&end_time)<<endl <<"\tMPI processes:\t\t" <<worldsize<<endl <<"\tExperiment:\t\t" <<experiment<<endl <<"\tComputation time:\t" <<duration <<"\t("<<floor(duration/3600.0)<<":"<<floor(fmod(duration/60.0,60.0))<<":"<<floor(fmod(duration,60.0))<<":"<<floor(fmod(1000*duration,1000.0)) <<")"<<endl; } std::vector<int> WorkDivision(int WorldSize) { std::vector<int> output; int overlap = WorldSize*ceil(180.0/WorldSize)-180; for(int i =0 ; i<=WorldSize; i++) { if(i==0) output.push_back(0); else if(i<=overlap) output.push_back(i*floor(180.0/WorldSize)); else output.push_back(output[i-1]+ceil(180.0/WorldSize)); } return output; }<commit_msg>Updating the working division between the MPI processes during the analysis. Now the processes handeling the high theta rings are relieved.<commit_after>#include "General_Utilities.hpp" #include <cmath> #include <iostream> #include <fstream> #include <chrono> #include <cstdlib> #include <libconfig.h++> #include "Physical_Parameters.hpp" using namespace libconfig; //Config file string FormFactor="None"; string SimID="default"; string experiment="default"; string version="v1.0"; double mChi=0,sigma=0; double rhoDM=0.0; int SampleSize=0; int SimDate [3] = {0,0,0}; int SimTime [3] = {0,0,0}; double nJ2000 = 0.0; Eigen::Vector3d vEarth(0,0,0); double vcut=0.0; void Read_Config_File(char *inputfile) { Config cfg; std::string id(inputfile); std::string path = "../data/"+id+".cfg"; const char *cstr = path.c_str(); // Read the file. If there is an error, report it and exit. try { cfg.readFile(cstr); } catch(const FileIOException &fioex) { std::cerr << "I/O error while reading configuration file." << std::endl; exit(EXIT_FAILURE); } catch(const ParseException &pex) { std::cerr << "Configurate file parse error at " << pex.getFile() << ":" << pex.getLine() << " - " << pex.getError() << std::endl; exit(EXIT_FAILURE); } //Simulation ID try { SimID = cfg.lookup("simID").c_str(); } catch(const SettingNotFoundException &nfex) { cerr << "No 'simID' setting in configuration file." << endl; exit(EXIT_FAILURE); } //Experiment try { experiment = cfg.lookup("experiment").c_str(); } catch(const SettingNotFoundException &nfex) { cerr << "No 'simID' setting in configuration file." << endl; exit(EXIT_FAILURE); } //sample size try { SampleSize = cfg.lookup("samplesize"); } catch(const SettingNotFoundException &nfex) { cerr << "No 'samplesize' setting in configuration file." << endl; exit(EXIT_FAILURE); } //Mass try { mChi = cfg.lookup("mass"); mChi*=MeV; } catch(const SettingNotFoundException &nfex) { cerr << "No 'mass' setting in configuration file." << endl; exit(EXIT_FAILURE); } //Cross section try { sigma = cfg.lookup("sigma"); sigma*=pb; } catch(const SettingNotFoundException &nfex) { cerr << "Error: While reading 'sigma' setting in configuration file. Computation cancelled." << endl; exit(EXIT_FAILURE); } //DM energy density try { rhoDM = cfg.lookup("rho"); rhoDM*=GeV/cm/cm/cm; } catch(const SettingNotFoundException &nfex) { cerr << "Error: While reading 'rho' setting in configuration file. Computation cancelled." << endl; exit(EXIT_FAILURE); } //Date try { SimDate[0] = cfg.lookup("date")[0]; SimDate[1] = cfg.lookup("date")[1]; SimDate[2] = cfg.lookup("date")[2]; } catch(const SettingNotFoundException &nfex) { cerr << "Error: While reading 'date' setting in configuration file. Computation cancelled." << endl; exit(EXIT_FAILURE); } //Time try { SimTime[0] = cfg.lookup("time")[0]; SimTime[1] = cfg.lookup("time")[1]; SimTime[2] = cfg.lookup("time")[2]; } catch(const SettingNotFoundException &nfex) { cerr << "Error: While reading 'time' setting in configuration file. Computation cancelled." << endl; exit(EXIT_FAILURE); } //Time and Detector nJ2000= FractionalDays(SimDate,SimTime); //Earth Velocity vEarth=EarthVelocity(nJ2000); } void LogAnalysis(double duration,int worldsize) { ofstream f; f.open("../results/"+SimID+".log",std::ofstream::app); std::chrono::time_point<std::chrono::system_clock> end; end = std::chrono::system_clock::now(); std::time_t end_time = std::chrono::system_clock::to_time_t(end); f <<"\n////////////////////////////////////////////////////\n\n" <<"//Data analysis performed:\t" <<std::ctime(&end_time)<<endl <<"\tMPI processes:\t\t" <<worldsize<<endl <<"\tExperiment:\t\t" <<experiment<<endl <<"\tComputation time:\t" <<duration <<"\t("<<floor(duration/3600.0)<<":"<<floor(fmod(duration/60.0,60.0))<<":"<<floor(fmod(duration,60.0))<<":"<<floor(fmod(1000*duration,1000.0)) <<")"<<endl; } std::vector<int> WorkDivision(int WorldSize) { std::vector<int> output; int overlap = WorldSize*ceil(180.0/WorldSize)-180; for(int i =0 ; i<=WorldSize; i++) { if(i==0) output.push_back(0); else if(i<=(WorldSize-overlap)) output.push_back(i*ceil(180.0/WorldSize)); else output.push_back(output[i-1]+floor(180.0/WorldSize)); } return output; }<|endoftext|>
<commit_before><commit_msg>Take reference instead of copying whole.<commit_after><|endoftext|>
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include <core/session/onnxruntime_cxx_api.h> #include <iostream> #include <fstream> #ifdef _WIN32 #include "getopt.h" #else #include <getopt.h> #include <thread> #endif #include "TestResultStat.h" #include "testenv.h" #include "runner.h" #include "path_lib.h" #include "sync_api.h" #include "providers.h" #include "core/session/onnxruntime_cxx_api.h" using namespace onnxruntime; namespace { void usage() { printf( "onnx_test_runner [options...] <data_root>\n" "Options:\n" "\t-j [models]: Specifies the number of models to run simultaneously.\n" "\t-A : Disable memory arena\n" "\t-c [runs]: Specifies the number of Session::Run() to invoke simultaneously for each model.\n" "\t-r [repeat]: Specifies the number of times to repeat\n" "\t-v: verbose\n" "\t-n [test_case_name]: Specifies a single test case to run.\n" "\t-e [EXECUTION_PROVIDER]: EXECUTION_PROVIDER could be 'cpu', 'cuda' or 'mkldnn'. Default: 'cpu'.\n" "\t-x: Use parallel executor, default (without -x): sequential executor.\n" "\t-h: help\n"); } #ifdef _WIN32 int GetNumCpuCores() { SYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer[256]; DWORD returnLength = sizeof(buffer); if (GetLogicalProcessorInformation(buffer, &returnLength) == FALSE) { // try GetSystemInfo SYSTEM_INFO sysInfo; GetSystemInfo(&sysInfo); if (sysInfo.dwNumberOfProcessors <= 0) { ORT_THROW("Fatal error: 0 count processors from GetSystemInfo"); } // This is the number of logical processors in the current group return sysInfo.dwNumberOfProcessors; } int processorCoreCount = 0; int count = (int)(returnLength / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION)); for (int i = 0; i != count; ++i) { if (buffer[i].Relationship == RelationProcessorCore) { ++processorCoreCount; } } if (!processorCoreCount) ORT_THROW("Fatal error: 0 count processors from GetLogicalProcessorInformation"); return processorCoreCount; } #else int GetNumCpuCores() { return std::thread::hardware_concurrency(); } #endif } // namespace #ifdef _WIN32 int real_main(int argc, wchar_t* argv[]) { #else int real_main(int argc, char* argv[]) { #endif //if this var is not empty, only run the tests with name in this list std::vector<std::basic_string<PATH_CHAR_TYPE> > whitelisted_test_cases; int concurrent_session_runs = GetNumCpuCores(); bool enable_cpu_mem_arena = true; bool enable_sequential_execution = true; int repeat_count = 1; int p_models = GetNumCpuCores(); bool enable_cuda = false; bool enable_mkl = false; bool enable_nuphar = false; OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_kWARNING; { int ch; while ((ch = getopt(argc, argv, ORT_TSTR("Ac:hj:m:n:r:e:xv"))) != -1) { switch (ch) { case 'A': enable_cpu_mem_arena = false; break; case 'v': logging_level = ORT_LOGGING_LEVEL_kINFO; break; case 'c': concurrent_session_runs = static_cast<int>(MyStrtol<PATH_CHAR_TYPE>(optarg, nullptr, 10)); if (concurrent_session_runs <= 0) { usage(); return -1; } break; case 'j': p_models = static_cast<int>(MyStrtol<PATH_CHAR_TYPE>(optarg, nullptr, 10)); if (p_models <= 0) { usage(); return -1; } break; case 'r': repeat_count = static_cast<int>(MyStrtol<PATH_CHAR_TYPE>(optarg, nullptr, 10)); if (repeat_count <= 0) { usage(); return -1; } break; case 'm': //ignore. break; case 'n': //run only some whitelisted tests //TODO: parse name str to an array whitelisted_test_cases.emplace_back(optarg); break; case 'e': if (!MyStrCmp(optarg, ORT_TSTR("cpu"))) { //do nothing } else if (!MyStrCmp(optarg, ORT_TSTR("cuda"))) { enable_cuda = true; } else if (!MyStrCmp(optarg, ORT_TSTR("mkldnn"))) { enable_mkl = true; } else if (!MyStrCmp(optarg, ORT_TSTR("nuphar"))) { enable_nuphar = true; } else { usage(); return -1; } break; case 'x': enable_sequential_execution = false; break; case '?': case 'h': default: usage(); return -1; } } } if (concurrent_session_runs > 1 && repeat_count > 1) { fprintf(stderr, "when you use '-r [repeat]', please set '-c' to 1\n"); usage(); return -1; } argc -= optind; argv += optind; if (argc < 1) { fprintf(stderr, "please specify a test data dir\n"); usage(); return -1; } std::unique_ptr<OrtEnv> env; { OrtEnv* t; ONNXStatus* ost = OrtInitialize(logging_level, "Default", &t); if (ost != nullptr) { fprintf(stderr, "Error creating environment: %s \n", OrtGetErrorMessage(ost)); ReleaseONNXStatus(ost); return -1; } env.reset(t); } std::vector<std::basic_string<PATH_CHAR_TYPE> > data_dirs; TestResultStat stat; std::unique_ptr<OrtAllocator> default_allocator; { OrtAllocator* p; ONNXStatus* ost = OrtCreateDefaultAllocator(&p); if (ost != nullptr) { fprintf(stderr, "Error creating environment: %s \n", OrtGetErrorMessage(ost)); ReleaseONNXStatus(ost); return -1; } default_allocator.reset(p); } for (int i = 0; i != argc; ++i) { data_dirs.emplace_back(argv[i]); } { std::vector<ITestCase*> tests = LoadTests(data_dirs, whitelisted_test_cases, default_allocator.get()); SessionOptionsWrapper sf(env.get()); if (enable_cpu_mem_arena) sf.EnableCpuMemArena(); else sf.DisableCpuMemArena(); if (enable_sequential_execution) sf.EnableSequentialExecution(); else sf.DisableSequentialExecution(); if (enable_cuda) { #ifdef USE_CUDA OrtProviderFactoryInterface** f; ORT_THROW_ON_ERROR(OrtCreateCUDAExecutionProviderFactory(0, &f)); sf.AppendExecutionProvider(f); OrtReleaseObject(f); #else fprintf(stderr, "CUDA is supported in this build"); return -1; #endif } if (enable_nuphar) { #ifdef USE_NUPHAR OrtProviderFactoryInterface** f; ORT_THROW_ON_ERROR(OrtCreateNupharExecutionProviderFactory(0, "", &f)); sf.AppendExecutionProvider(f); OrtReleaseObject(f); #else fprintf(stderr, "Nuphar is supported in this build"); return -1; #endif } if (enable_mkl) { #ifdef USE_MKLDNN OrtProviderFactoryInterface** f; ORT_THROW_ON_ERROR(OrtCreateMkldnnExecutionProviderFactory(enable_cpu_mem_arena ? 1 : 0, &f)); sf.AppendExecutionProvider(f); OrtReleaseObject(f); #else fprintf(stderr, "MKL-DNN is supported in this build"); return -1; #endif } TestEnv args(tests, stat, sf); Status st = RunTests(args, p_models, concurrent_session_runs, static_cast<size_t>(repeat_count), GetDefaultThreadPool(Env::Default())); if (!st.IsOK()) { fprintf(stderr, "%s\n", st.ErrorMessage().c_str()); return -1; } std::string res = stat.ToString(); fwrite(res.c_str(), 1, res.size(), stdout); for (ITestCase* l : tests) { delete l; } } std::map<std::string, std::string> broken_tests{ {"AvgPool1d", "disable reason"}, {"AvgPool1d_stride", "disable reason"}, {"AvgPool2d", "disable reason"}, {"AvgPool2d_stride", "disable reason"}, {"AvgPool3d", "disable reason"}, {"AvgPool3d_stride", "disable reason"}, {"AvgPool3d_stride1_pad0_gpu_input", "disable reason"}, {"BatchNorm1d_3d_input_eval", "disable reason"}, {"BatchNorm2d_eval", "disable reason"}, {"BatchNorm2d_momentum_eval", "disable reason"}, {"BatchNorm3d_eval", "disable reason"}, {"BatchNorm3d_momentum_eval", "disable reason"}, {"GLU", "disable reason"}, {"GLU_dim", "disable reason"}, {"Linear", "disable reason"}, {"PReLU_1d", "disable reason"}, {"PReLU_1d_multiparam", "disable reason"}, {"PReLU_2d", "disable reason"}, {"PReLU_2d_multiparam", "disable reason"}, {"PReLU_3d", "disable reason"}, {"PReLU_3d_multiparam", "disable reason"}, {"PoissonNLLLLoss_no_reduce", "disable reason"}, {"Softsign", "disable reason"}, {"convtranspose_1d", "disable reason"}, {"convtranspose_3d", "disable reason"}, {"dynamic_slice", "disable reason"}, {"dynamic_slice_default_axes", "disable reason"}, {"dynamic_slice_end_out_of_bounds", "disable reason"}, {"dynamic_slice_neg", "disable reason"}, {"dynamic_slice_start_out_of_bounds", "disable reason"}, {"eyelike_populate_off_main_diagonal", "disable reason"}, {"eyelike_with_dtype", "disable reason"}, {"eyelike_without_dtype", "disable reason"}, {"flatten_axis0", "disable reason"}, {"flatten_axis1", "disable reason"}, {"flatten_axis2", "disable reason"}, {"flatten_axis3", "disable reason"}, {"flatten_default_axis", "disable reason"}, {"gemm_broadcast", "disable reason"}, {"gemm_nobroadcast", "disable reason"}, {"greater", "disable reason"}, {"greater_bcast", "disable reason"}, {"less", "disable reason"}, {"less_bcast", "disable reason"}, {"matmul_2d", "disable reason"}, {"matmul_3d", "disable reason"}, {"matmul_4d", "disable reason"}, {"mvn", "disable reason"}, {"operator_add_broadcast", "disable reason"}, {"operator_add_size1_broadcast", "disable reason"}, {"operator_add_size1_right_broadcast", "disable reason"}, {"operator_add_size1_singleton_broadcast", "disable reason"}, {"operator_addconstant", "disable reason"}, {"operator_addmm", "disable reason"}, {"operator_basic", "disable reason"}, {"operator_lstm", "disable reason"}, {"operator_mm", "disable reason"}, {"operator_non_float_params", "disable reason"}, {"operator_params", "disable reason"}, {"operator_pow", "disable reason"}, {"operator_rnn", "disable reason"}, {"operator_rnn_single_layer", "disable reason"}, {"prelu_broadcast", "disable reason"}, {"prelu_example", "disable reason"}, {"maxunpool_export_with_output_shape", "opset 9 not supported yet"}, {"maxunpool_export_without_output_shape", "opset 9 not supported yet"}, {"upsample_nearest", "opset 9 not supported yet"}, {"onehot_with_axis", "opset 9 not supported yet"}, {"onehot_without_axis", "opset 9 not supported yet"}, // also has bug in current test re: output type. Spandan to fix. {"sinh", "opset 9 not supported yet"}, {"cosh", "opset 9 not supported yet"}, {"asinh", "opset 9 not supported yet"}, {"acosh", "opset 9 not supported yet"}, {"atanh", "opset 9 not supported yet"}, {"sinh_example", "opset 9 not supported yet"}, {"cosh_example", "opset 9 not supported yet"}, {"asinh_example", "opset 9 not supported yet"}, {"acosh_example", "opset 9 not supported yet"}, {"atanh_example", "opset 9 not supported yet"}, {"sign_model", "opset 9 not supported yet"}, {"sign", "opset 9 not supported yet"}, {"scatter_with_axis", "opset 9 not supported yet"}, {"scatter_without_axis", "opset 9 not supported yet"}, {"scan_sum", "opset 9 not supported yet"}}; #ifdef USE_CUDA broken_tests["maxpool_2d_default"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_pads"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_precomputed_strides"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_precomputed_pads"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_strides"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_precomputed_same_upper"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_same_upper"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_same_lower"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_3d_default"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_1d_default"] = "cudnn pooling only support input dimension >= 3"; #endif int result = 0; for (const std::string& s : stat.GetFailedTest()) { if (broken_tests.find(s) == broken_tests.end()) { fprintf(stderr, "test %s failed, please fix it\n", s.c_str()); result = -1; } } return result; } #ifdef _WIN32 int wmain(int argc, wchar_t* argv[]) { #else int main(int argc, char* argv[]) { #endif try { return real_main(argc, argv); } catch (std::exception& ex) { fprintf(stderr, "%s\n", ex.what()); return -1; } } <commit_msg>fix typo<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include <core/session/onnxruntime_cxx_api.h> #include <iostream> #include <fstream> #ifdef _WIN32 #include "getopt.h" #else #include <getopt.h> #include <thread> #endif #include "TestResultStat.h" #include "testenv.h" #include "runner.h" #include "path_lib.h" #include "sync_api.h" #include "providers.h" #include "core/session/onnxruntime_cxx_api.h" using namespace onnxruntime; namespace { void usage() { printf( "onnx_test_runner [options...] <data_root>\n" "Options:\n" "\t-j [models]: Specifies the number of models to run simultaneously.\n" "\t-A : Disable memory arena\n" "\t-c [runs]: Specifies the number of Session::Run() to invoke simultaneously for each model.\n" "\t-r [repeat]: Specifies the number of times to repeat\n" "\t-v: verbose\n" "\t-n [test_case_name]: Specifies a single test case to run.\n" "\t-e [EXECUTION_PROVIDER]: EXECUTION_PROVIDER could be 'cpu', 'cuda' or 'mkldnn'. Default: 'cpu'.\n" "\t-x: Use parallel executor, default (without -x): sequential executor.\n" "\t-h: help\n"); } #ifdef _WIN32 int GetNumCpuCores() { SYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer[256]; DWORD returnLength = sizeof(buffer); if (GetLogicalProcessorInformation(buffer, &returnLength) == FALSE) { // try GetSystemInfo SYSTEM_INFO sysInfo; GetSystemInfo(&sysInfo); if (sysInfo.dwNumberOfProcessors <= 0) { ORT_THROW("Fatal error: 0 count processors from GetSystemInfo"); } // This is the number of logical processors in the current group return sysInfo.dwNumberOfProcessors; } int processorCoreCount = 0; int count = (int)(returnLength / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION)); for (int i = 0; i != count; ++i) { if (buffer[i].Relationship == RelationProcessorCore) { ++processorCoreCount; } } if (!processorCoreCount) ORT_THROW("Fatal error: 0 count processors from GetLogicalProcessorInformation"); return processorCoreCount; } #else int GetNumCpuCores() { return std::thread::hardware_concurrency(); } #endif } // namespace #ifdef _WIN32 int real_main(int argc, wchar_t* argv[]) { #else int real_main(int argc, char* argv[]) { #endif //if this var is not empty, only run the tests with name in this list std::vector<std::basic_string<PATH_CHAR_TYPE> > whitelisted_test_cases; int concurrent_session_runs = GetNumCpuCores(); bool enable_cpu_mem_arena = true; bool enable_sequential_execution = true; int repeat_count = 1; int p_models = GetNumCpuCores(); bool enable_cuda = false; bool enable_mkl = false; bool enable_nuphar = false; OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_kWARNING; { int ch; while ((ch = getopt(argc, argv, ORT_TSTR("Ac:hj:m:n:r:e:xv"))) != -1) { switch (ch) { case 'A': enable_cpu_mem_arena = false; break; case 'v': logging_level = ORT_LOGGING_LEVEL_kINFO; break; case 'c': concurrent_session_runs = static_cast<int>(MyStrtol<PATH_CHAR_TYPE>(optarg, nullptr, 10)); if (concurrent_session_runs <= 0) { usage(); return -1; } break; case 'j': p_models = static_cast<int>(MyStrtol<PATH_CHAR_TYPE>(optarg, nullptr, 10)); if (p_models <= 0) { usage(); return -1; } break; case 'r': repeat_count = static_cast<int>(MyStrtol<PATH_CHAR_TYPE>(optarg, nullptr, 10)); if (repeat_count <= 0) { usage(); return -1; } break; case 'm': //ignore. break; case 'n': //run only some whitelisted tests //TODO: parse name str to an array whitelisted_test_cases.emplace_back(optarg); break; case 'e': if (!MyStrCmp(optarg, ORT_TSTR("cpu"))) { //do nothing } else if (!MyStrCmp(optarg, ORT_TSTR("cuda"))) { enable_cuda = true; } else if (!MyStrCmp(optarg, ORT_TSTR("mkldnn"))) { enable_mkl = true; } else if (!MyStrCmp(optarg, ORT_TSTR("nuphar"))) { enable_nuphar = true; } else { usage(); return -1; } break; case 'x': enable_sequential_execution = false; break; case '?': case 'h': default: usage(); return -1; } } } if (concurrent_session_runs > 1 && repeat_count > 1) { fprintf(stderr, "when you use '-r [repeat]', please set '-c' to 1\n"); usage(); return -1; } argc -= optind; argv += optind; if (argc < 1) { fprintf(stderr, "please specify a test data dir\n"); usage(); return -1; } std::unique_ptr<OrtEnv> env; { OrtEnv* t; ONNXStatus* ost = OrtInitialize(logging_level, "Default", &t); if (ost != nullptr) { fprintf(stderr, "Error creating environment: %s \n", OrtGetErrorMessage(ost)); ReleaseONNXStatus(ost); return -1; } env.reset(t); } std::vector<std::basic_string<PATH_CHAR_TYPE> > data_dirs; TestResultStat stat; std::unique_ptr<OrtAllocator> default_allocator; { OrtAllocator* p; ONNXStatus* ost = OrtCreateDefaultAllocator(&p); if (ost != nullptr) { fprintf(stderr, "Error creating environment: %s \n", OrtGetErrorMessage(ost)); ReleaseONNXStatus(ost); return -1; } default_allocator.reset(p); } for (int i = 0; i != argc; ++i) { data_dirs.emplace_back(argv[i]); } { std::vector<ITestCase*> tests = LoadTests(data_dirs, whitelisted_test_cases, default_allocator.get()); SessionOptionsWrapper sf(env.get()); if (enable_cpu_mem_arena) sf.EnableCpuMemArena(); else sf.DisableCpuMemArena(); if (enable_sequential_execution) sf.EnableSequentialExecution(); else sf.DisableSequentialExecution(); if (enable_cuda) { #ifdef USE_CUDA OrtProviderFactoryInterface** f; ORT_THROW_ON_ERROR(OrtCreateCUDAExecutionProviderFactory(0, &f)); sf.AppendExecutionProvider(f); OrtReleaseObject(f); #else fprintf(stderr, "CUDA is not supported in this build"); return -1; #endif } if (enable_nuphar) { #ifdef USE_NUPHAR OrtProviderFactoryInterface** f; ORT_THROW_ON_ERROR(OrtCreateNupharExecutionProviderFactory(0, "", &f)); sf.AppendExecutionProvider(f); OrtReleaseObject(f); #else fprintf(stderr, "Nuphar is not supported in this build"); return -1; #endif } if (enable_mkl) { #ifdef USE_MKLDNN OrtProviderFactoryInterface** f; ORT_THROW_ON_ERROR(OrtCreateMkldnnExecutionProviderFactory(enable_cpu_mem_arena ? 1 : 0, &f)); sf.AppendExecutionProvider(f); OrtReleaseObject(f); #else fprintf(stderr, "MKL-DNN is not supported in this build"); return -1; #endif } TestEnv args(tests, stat, sf); Status st = RunTests(args, p_models, concurrent_session_runs, static_cast<size_t>(repeat_count), GetDefaultThreadPool(Env::Default())); if (!st.IsOK()) { fprintf(stderr, "%s\n", st.ErrorMessage().c_str()); return -1; } std::string res = stat.ToString(); fwrite(res.c_str(), 1, res.size(), stdout); for (ITestCase* l : tests) { delete l; } } std::map<std::string, std::string> broken_tests{ {"AvgPool1d", "disable reason"}, {"AvgPool1d_stride", "disable reason"}, {"AvgPool2d", "disable reason"}, {"AvgPool2d_stride", "disable reason"}, {"AvgPool3d", "disable reason"}, {"AvgPool3d_stride", "disable reason"}, {"AvgPool3d_stride1_pad0_gpu_input", "disable reason"}, {"BatchNorm1d_3d_input_eval", "disable reason"}, {"BatchNorm2d_eval", "disable reason"}, {"BatchNorm2d_momentum_eval", "disable reason"}, {"BatchNorm3d_eval", "disable reason"}, {"BatchNorm3d_momentum_eval", "disable reason"}, {"GLU", "disable reason"}, {"GLU_dim", "disable reason"}, {"Linear", "disable reason"}, {"PReLU_1d", "disable reason"}, {"PReLU_1d_multiparam", "disable reason"}, {"PReLU_2d", "disable reason"}, {"PReLU_2d_multiparam", "disable reason"}, {"PReLU_3d", "disable reason"}, {"PReLU_3d_multiparam", "disable reason"}, {"PoissonNLLLLoss_no_reduce", "disable reason"}, {"Softsign", "disable reason"}, {"convtranspose_1d", "disable reason"}, {"convtranspose_3d", "disable reason"}, {"dynamic_slice", "disable reason"}, {"dynamic_slice_default_axes", "disable reason"}, {"dynamic_slice_end_out_of_bounds", "disable reason"}, {"dynamic_slice_neg", "disable reason"}, {"dynamic_slice_start_out_of_bounds", "disable reason"}, {"eyelike_populate_off_main_diagonal", "disable reason"}, {"eyelike_with_dtype", "disable reason"}, {"eyelike_without_dtype", "disable reason"}, {"flatten_axis0", "disable reason"}, {"flatten_axis1", "disable reason"}, {"flatten_axis2", "disable reason"}, {"flatten_axis3", "disable reason"}, {"flatten_default_axis", "disable reason"}, {"gemm_broadcast", "disable reason"}, {"gemm_nobroadcast", "disable reason"}, {"greater", "disable reason"}, {"greater_bcast", "disable reason"}, {"less", "disable reason"}, {"less_bcast", "disable reason"}, {"matmul_2d", "disable reason"}, {"matmul_3d", "disable reason"}, {"matmul_4d", "disable reason"}, {"mvn", "disable reason"}, {"operator_add_broadcast", "disable reason"}, {"operator_add_size1_broadcast", "disable reason"}, {"operator_add_size1_right_broadcast", "disable reason"}, {"operator_add_size1_singleton_broadcast", "disable reason"}, {"operator_addconstant", "disable reason"}, {"operator_addmm", "disable reason"}, {"operator_basic", "disable reason"}, {"operator_lstm", "disable reason"}, {"operator_mm", "disable reason"}, {"operator_non_float_params", "disable reason"}, {"operator_params", "disable reason"}, {"operator_pow", "disable reason"}, {"operator_rnn", "disable reason"}, {"operator_rnn_single_layer", "disable reason"}, {"prelu_broadcast", "disable reason"}, {"prelu_example", "disable reason"}, {"maxunpool_export_with_output_shape", "opset 9 not supported yet"}, {"maxunpool_export_without_output_shape", "opset 9 not supported yet"}, {"upsample_nearest", "opset 9 not supported yet"}, {"onehot_with_axis", "opset 9 not supported yet"}, {"onehot_without_axis", "opset 9 not supported yet"}, // also has bug in current test re: output type. Spandan to fix. {"sinh", "opset 9 not supported yet"}, {"cosh", "opset 9 not supported yet"}, {"asinh", "opset 9 not supported yet"}, {"acosh", "opset 9 not supported yet"}, {"atanh", "opset 9 not supported yet"}, {"sinh_example", "opset 9 not supported yet"}, {"cosh_example", "opset 9 not supported yet"}, {"asinh_example", "opset 9 not supported yet"}, {"acosh_example", "opset 9 not supported yet"}, {"atanh_example", "opset 9 not supported yet"}, {"sign_model", "opset 9 not supported yet"}, {"sign", "opset 9 not supported yet"}, {"scatter_with_axis", "opset 9 not supported yet"}, {"scatter_without_axis", "opset 9 not supported yet"}, {"scan_sum", "opset 9 not supported yet"}}; #ifdef USE_CUDA broken_tests["maxpool_2d_default"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_pads"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_precomputed_strides"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_precomputed_pads"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_strides"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_precomputed_same_upper"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_same_upper"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_2d_same_lower"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_3d_default"] = "cudnn pooling only support input dimension >= 3"; broken_tests["maxpool_1d_default"] = "cudnn pooling only support input dimension >= 3"; #endif int result = 0; for (const std::string& s : stat.GetFailedTest()) { if (broken_tests.find(s) == broken_tests.end()) { fprintf(stderr, "test %s failed, please fix it\n", s.c_str()); result = -1; } } return result; } #ifdef _WIN32 int wmain(int argc, wchar_t* argv[]) { #else int main(int argc, char* argv[]) { #endif try { return real_main(argc, argv); } catch (std::exception& ex) { fprintf(stderr, "%s\n", ex.what()); return -1; } } <|endoftext|>